Add hook to generate ios/build/util/CANARY_VERSION on iOS.
[chromium-blink-merge.git] / pdf / pdfium / pdfium_engine.cc
blob89fa7eb0a8ad75f17d288a63e4a526eb98dd328a
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "pdf/pdfium/pdfium_engine.h"
7 #include <math.h>
9 #include "base/i18n/icu_encoding_detection.h"
10 #include "base/i18n/icu_string_conversions.h"
11 #include "base/json/json_writer.h"
12 #include "base/logging.h"
13 #include "base/memory/scoped_ptr.h"
14 #include "base/numerics/safe_conversions.h"
15 #include "base/stl_util.h"
16 #include "base/strings/string_number_conversions.h"
17 #include "base/strings/string_piece.h"
18 #include "base/strings/string_util.h"
19 #include "base/strings/utf_string_conversions.h"
20 #include "base/values.h"
21 #include "gin/public/gin_embedders.h"
22 #include "pdf/draw_utils.h"
23 #include "pdf/pdfium/pdfium_api_string_buffer_adapter.h"
24 #include "pdf/pdfium/pdfium_mem_buffer_file_read.h"
25 #include "pdf/pdfium/pdfium_mem_buffer_file_write.h"
26 #include "ppapi/c/pp_errors.h"
27 #include "ppapi/c/pp_input_event.h"
28 #include "ppapi/c/ppb_core.h"
29 #include "ppapi/c/private/ppb_pdf.h"
30 #include "ppapi/cpp/dev/memory_dev.h"
31 #include "ppapi/cpp/input_event.h"
32 #include "ppapi/cpp/instance.h"
33 #include "ppapi/cpp/module.h"
34 #include "ppapi/cpp/private/pdf.h"
35 #include "ppapi/cpp/trusted/browser_font_trusted.h"
36 #include "ppapi/cpp/url_response_info.h"
37 #include "ppapi/cpp/var.h"
38 #include "ppapi/cpp/var_dictionary.h"
39 #include "printing/units.h"
40 #include "third_party/pdfium/public/fpdf_edit.h"
41 #include "third_party/pdfium/public/fpdf_ext.h"
42 #include "third_party/pdfium/public/fpdf_flatten.h"
43 #include "third_party/pdfium/public/fpdf_ppo.h"
44 #include "third_party/pdfium/public/fpdf_save.h"
45 #include "third_party/pdfium/public/fpdf_searchex.h"
46 #include "third_party/pdfium/public/fpdf_sysfontinfo.h"
47 #include "third_party/pdfium/public/fpdf_transformpage.h"
48 #include "ui/events/keycodes/keyboard_codes.h"
49 #include "v8/include/v8.h"
51 using printing::ConvertUnit;
52 using printing::ConvertUnitDouble;
53 using printing::kPointsPerInch;
54 using printing::kPixelsPerInch;
56 namespace chrome_pdf {
58 namespace {
60 #define kPageShadowTop 3
61 #define kPageShadowBottom 7
62 #define kPageShadowLeft 5
63 #define kPageShadowRight 5
65 #define kPageSeparatorThickness 4
66 #define kHighlightColorR 153
67 #define kHighlightColorG 193
68 #define kHighlightColorB 218
70 const uint32 kPendingPageColor = 0xFFEEEEEE;
72 #define kFormHighlightColor 0xFFE4DD
73 #define kFormHighlightAlpha 100
75 #define kMaxPasswordTries 3
77 // See Table 3.20 in
78 // http://www.adobe.com/devnet/acrobat/pdfs/pdf_reference_1-7.pdf
79 #define kPDFPermissionPrintLowQualityMask 1 << 2
80 #define kPDFPermissionPrintHighQualityMask 1 << 11
81 #define kPDFPermissionCopyMask 1 << 4
82 #define kPDFPermissionCopyAccessibleMask 1 << 9
84 #define kLoadingTextVerticalOffset 50
86 // The maximum amount of time we'll spend doing a paint before we give back
87 // control of the thread.
88 #define kMaxProgressivePaintTimeMs 50
90 // The maximum amount of time we'll spend doing the first paint. This is less
91 // than the above to keep things smooth if the user is scrolling quickly. We
92 // try painting a little because with accelerated compositing, we get flushes
93 // only every 16 ms. If we were to wait until the next flush to paint the rest
94 // of the pdf, we would never get to draw the pdf and would only draw the
95 // scrollbars. This value is picked to give enough time for gpu related code to
96 // do its thing and still fit within the timelimit for 60Hz. For the
97 // non-composited case, this doesn't make things worse since we're still
98 // painting the scrollbars > 60 Hz.
99 #define kMaxInitialProgressivePaintTimeMs 10
101 struct ClipBox {
102 float left;
103 float right;
104 float top;
105 float bottom;
108 std::vector<uint32_t> GetPageNumbersFromPrintPageNumberRange(
109 const PP_PrintPageNumberRange_Dev* page_ranges,
110 uint32_t page_range_count) {
111 std::vector<uint32_t> page_numbers;
112 for (uint32_t index = 0; index < page_range_count; ++index) {
113 for (uint32_t page_number = page_ranges[index].first_page_number;
114 page_number <= page_ranges[index].last_page_number; ++page_number) {
115 page_numbers.push_back(page_number);
118 return page_numbers;
121 #if defined(OS_LINUX)
123 PP_Instance g_last_instance_id;
125 struct PDFFontSubstitution {
126 const char* pdf_name;
127 const char* face;
128 bool bold;
129 bool italic;
132 PP_BrowserFont_Trusted_Weight WeightToBrowserFontTrustedWeight(int weight) {
133 static_assert(PP_BROWSERFONT_TRUSTED_WEIGHT_100 == 0,
134 "PP_BrowserFont_Trusted_Weight min");
135 static_assert(PP_BROWSERFONT_TRUSTED_WEIGHT_900 == 8,
136 "PP_BrowserFont_Trusted_Weight max");
137 const int kMinimumWeight = 100;
138 const int kMaximumWeight = 900;
139 int normalized_weight =
140 std::min(std::max(weight, kMinimumWeight), kMaximumWeight);
141 normalized_weight = (normalized_weight / 100) - 1;
142 return static_cast<PP_BrowserFont_Trusted_Weight>(normalized_weight);
145 // This list is for CPWL_FontMap::GetDefaultFontByCharset().
146 // We pretend to have these font natively and let the browser (or underlying
147 // fontconfig) to pick the proper font on the system.
148 void EnumFonts(struct _FPDF_SYSFONTINFO* sysfontinfo, void* mapper) {
149 FPDF_AddInstalledFont(mapper, "Arial", FXFONT_DEFAULT_CHARSET);
151 const FPDF_CharsetFontMap* font_map = FPDF_GetDefaultTTFMap();
152 for (; font_map->charset != -1; ++font_map) {
153 FPDF_AddInstalledFont(mapper, font_map->fontname, font_map->charset);
157 const PDFFontSubstitution PDFFontSubstitutions[] = {
158 {"Courier", "Courier New", false, false},
159 {"Courier-Bold", "Courier New", true, false},
160 {"Courier-BoldOblique", "Courier New", true, true},
161 {"Courier-Oblique", "Courier New", false, true},
162 {"Helvetica", "Arial", false, false},
163 {"Helvetica-Bold", "Arial", true, false},
164 {"Helvetica-BoldOblique", "Arial", true, true},
165 {"Helvetica-Oblique", "Arial", false, true},
166 {"Times-Roman", "Times New Roman", false, false},
167 {"Times-Bold", "Times New Roman", true, false},
168 {"Times-BoldItalic", "Times New Roman", true, true},
169 {"Times-Italic", "Times New Roman", false, true},
171 // MS P?(Mincho|Gothic) are the most notable fonts in Japanese PDF files
172 // without embedding the glyphs. Sometimes the font names are encoded
173 // in Japanese Windows's locale (CP932/Shift_JIS) without space.
174 // Most Linux systems don't have the exact font, but for outsourcing
175 // fontconfig to find substitutable font in the system, we pass ASCII
176 // font names to it.
177 {"MS-PGothic", "MS PGothic", false, false},
178 {"MS-Gothic", "MS Gothic", false, false},
179 {"MS-PMincho", "MS PMincho", false, false},
180 {"MS-Mincho", "MS Mincho", false, false},
181 // MS PGothic in Shift_JIS encoding.
182 {"\x82\x6C\x82\x72\x82\x6F\x83\x53\x83\x56\x83\x62\x83\x4E",
183 "MS PGothic", false, false},
184 // MS Gothic in Shift_JIS encoding.
185 {"\x82\x6C\x82\x72\x83\x53\x83\x56\x83\x62\x83\x4E",
186 "MS Gothic", false, false},
187 // MS PMincho in Shift_JIS encoding.
188 {"\x82\x6C\x82\x72\x82\x6F\x96\xBE\x92\xA9",
189 "MS PMincho", false, false},
190 // MS Mincho in Shift_JIS encoding.
191 {"\x82\x6C\x82\x72\x96\xBE\x92\xA9",
192 "MS Mincho", false, false},
195 void* MapFont(struct _FPDF_SYSFONTINFO*, int weight, int italic,
196 int charset, int pitch_family, const char* face, int* exact) {
197 // Do not attempt to map fonts if pepper is not initialized (for privet local
198 // printing).
199 // TODO(noamsml): Real font substitution (http://crbug.com/391978)
200 if (!pp::Module::Get())
201 return NULL;
203 pp::BrowserFontDescription description;
205 // Pretend the system does not have the Symbol font to force a fallback to
206 // the built in Symbol font in CFX_FontMapper::FindSubstFont().
207 if (strcmp(face, "Symbol") == 0)
208 return NULL;
210 if (pitch_family & FXFONT_FF_FIXEDPITCH) {
211 description.set_family(PP_BROWSERFONT_TRUSTED_FAMILY_MONOSPACE);
212 } else if (pitch_family & FXFONT_FF_ROMAN) {
213 description.set_family(PP_BROWSERFONT_TRUSTED_FAMILY_SERIF);
216 // Map from the standard PDF fonts to TrueType font names.
217 size_t i;
218 for (i = 0; i < arraysize(PDFFontSubstitutions); ++i) {
219 if (strcmp(face, PDFFontSubstitutions[i].pdf_name) == 0) {
220 description.set_face(PDFFontSubstitutions[i].face);
221 if (PDFFontSubstitutions[i].bold)
222 description.set_weight(PP_BROWSERFONT_TRUSTED_WEIGHT_BOLD);
223 if (PDFFontSubstitutions[i].italic)
224 description.set_italic(true);
225 break;
229 if (i == arraysize(PDFFontSubstitutions)) {
230 // Convert to UTF-8 before calling set_face().
231 std::string face_utf8;
232 if (base::IsStringUTF8(face)) {
233 face_utf8 = face;
234 } else {
235 std::string encoding;
236 if (base::DetectEncoding(face, &encoding)) {
237 // ConvertToUtf8AndNormalize() clears |face_utf8| on failure.
238 base::ConvertToUtf8AndNormalize(face, encoding, &face_utf8);
242 if (face_utf8.empty())
243 return nullptr;
245 description.set_face(face_utf8);
246 description.set_weight(WeightToBrowserFontTrustedWeight(weight));
247 description.set_italic(italic > 0);
250 if (!pp::PDF::IsAvailable()) {
251 NOTREACHED();
252 return NULL;
255 PP_Resource font_resource = pp::PDF::GetFontFileWithFallback(
256 pp::InstanceHandle(g_last_instance_id),
257 &description.pp_font_description(),
258 static_cast<PP_PrivateFontCharset>(charset));
259 long res_id = font_resource;
260 return reinterpret_cast<void*>(res_id);
263 unsigned long GetFontData(struct _FPDF_SYSFONTINFO*, void* font_id,
264 unsigned int table, unsigned char* buffer,
265 unsigned long buf_size) {
266 if (!pp::PDF::IsAvailable()) {
267 NOTREACHED();
268 return 0;
271 uint32_t size = buf_size;
272 long res_id = reinterpret_cast<long>(font_id);
273 if (!pp::PDF::GetFontTableForPrivateFontFile(res_id, table, buffer, &size))
274 return 0;
275 return size;
278 void DeleteFont(struct _FPDF_SYSFONTINFO*, void* font_id) {
279 long res_id = reinterpret_cast<long>(font_id);
280 pp::Module::Get()->core()->ReleaseResource(res_id);
283 FPDF_SYSFONTINFO g_font_info = {
286 EnumFonts,
287 MapFont,
289 GetFontData,
292 DeleteFont
294 #endif // defined(OS_LINUX)
296 PDFiumEngine* g_engine_for_unsupported;
298 void Unsupported_Handler(UNSUPPORT_INFO*, int type) {
299 if (!g_engine_for_unsupported) {
300 NOTREACHED();
301 return;
304 g_engine_for_unsupported->UnsupportedFeature(type);
307 UNSUPPORT_INFO g_unsuppored_info = {
309 Unsupported_Handler
312 // Set the destination page size and content area in points based on source
313 // page rotation and orientation.
315 // |rotated| True if source page is rotated 90 degree or 270 degree.
316 // |is_src_page_landscape| is true if the source page orientation is landscape.
317 // |page_size| has the actual destination page size in points.
318 // |content_rect| has the actual destination page printable area values in
319 // points.
320 void SetPageSizeAndContentRect(bool rotated,
321 bool is_src_page_landscape,
322 pp::Size* page_size,
323 pp::Rect* content_rect) {
324 bool is_dst_page_landscape = page_size->width() > page_size->height();
325 bool page_orientation_mismatched = is_src_page_landscape !=
326 is_dst_page_landscape;
327 bool rotate_dst_page = rotated ^ page_orientation_mismatched;
328 if (rotate_dst_page) {
329 page_size->SetSize(page_size->height(), page_size->width());
330 content_rect->SetRect(content_rect->y(), content_rect->x(),
331 content_rect->height(), content_rect->width());
335 // Calculate the scale factor between |content_rect| and a page of size
336 // |src_width| x |src_height|.
338 // |scale_to_fit| is true, if we need to calculate the scale factor.
339 // |content_rect| specifies the printable area of the destination page, with
340 // origin at left-bottom. Values are in points.
341 // |src_width| specifies the source page width in points.
342 // |src_height| specifies the source page height in points.
343 // |rotated| True if source page is rotated 90 degree or 270 degree.
344 double CalculateScaleFactor(bool scale_to_fit,
345 const pp::Rect& content_rect,
346 double src_width, double src_height, bool rotated) {
347 if (!scale_to_fit || src_width == 0 || src_height == 0)
348 return 1.0;
350 double actual_source_page_width = rotated ? src_height : src_width;
351 double actual_source_page_height = rotated ? src_width : src_height;
352 double ratio_x = static_cast<double>(content_rect.width()) /
353 actual_source_page_width;
354 double ratio_y = static_cast<double>(content_rect.height()) /
355 actual_source_page_height;
356 return std::min(ratio_x, ratio_y);
359 // Compute source clip box boundaries based on the crop box / media box of
360 // source page and scale factor.
362 // |page| Handle to the source page. Returned by FPDF_LoadPage function.
363 // |scale_factor| specifies the scale factor that should be applied to source
364 // clip box boundaries.
365 // |rotated| True if source page is rotated 90 degree or 270 degree.
366 // |clip_box| out param to hold the computed source clip box values.
367 void CalculateClipBoxBoundary(FPDF_PAGE page, double scale_factor, bool rotated,
368 ClipBox* clip_box) {
369 if (!FPDFPage_GetCropBox(page, &clip_box->left, &clip_box->bottom,
370 &clip_box->right, &clip_box->top)) {
371 if (!FPDFPage_GetMediaBox(page, &clip_box->left, &clip_box->bottom,
372 &clip_box->right, &clip_box->top)) {
373 // Make the default size to be letter size (8.5" X 11"). We are just
374 // following the PDFium way of handling these corner cases. PDFium always
375 // consider US-Letter as the default page size.
376 float paper_width = 612;
377 float paper_height = 792;
378 clip_box->left = 0;
379 clip_box->bottom = 0;
380 clip_box->right = rotated ? paper_height : paper_width;
381 clip_box->top = rotated ? paper_width : paper_height;
384 clip_box->left *= scale_factor;
385 clip_box->right *= scale_factor;
386 clip_box->bottom *= scale_factor;
387 clip_box->top *= scale_factor;
390 // Calculate the clip box translation offset for a page that does need to be
391 // scaled. All parameters are in points.
393 // |content_rect| specifies the printable area of the destination page, with
394 // origin at left-bottom.
395 // |source_clip_box| specifies the source clip box positions, relative to
396 // origin at left-bottom.
397 // |offset_x| and |offset_y| will contain the final translation offsets for the
398 // source clip box, relative to origin at left-bottom.
399 void CalculateScaledClipBoxOffset(const pp::Rect& content_rect,
400 const ClipBox& source_clip_box,
401 double* offset_x, double* offset_y) {
402 const float clip_box_width = source_clip_box.right - source_clip_box.left;
403 const float clip_box_height = source_clip_box.top - source_clip_box.bottom;
405 // Center the intended clip region to real clip region.
406 *offset_x = (content_rect.width() - clip_box_width) / 2 + content_rect.x() -
407 source_clip_box.left;
408 *offset_y = (content_rect.height() - clip_box_height) / 2 + content_rect.y() -
409 source_clip_box.bottom;
412 // Calculate the clip box offset for a page that does not need to be scaled.
413 // All parameters are in points.
415 // |content_rect| specifies the printable area of the destination page, with
416 // origin at left-bottom.
417 // |rotation| specifies the source page rotation values which are N / 90
418 // degrees.
419 // |page_width| specifies the screen destination page width.
420 // |page_height| specifies the screen destination page height.
421 // |source_clip_box| specifies the source clip box positions, relative to origin
422 // at left-bottom.
423 // |offset_x| and |offset_y| will contain the final translation offsets for the
424 // source clip box, relative to origin at left-bottom.
425 void CalculateNonScaledClipBoxOffset(const pp::Rect& content_rect, int rotation,
426 int page_width, int page_height,
427 const ClipBox& source_clip_box,
428 double* offset_x, double* offset_y) {
429 // Align the intended clip region to left-top corner of real clip region.
430 switch (rotation) {
431 case 0:
432 *offset_x = -1 * source_clip_box.left;
433 *offset_y = page_height - source_clip_box.top;
434 break;
435 case 1:
436 *offset_x = 0;
437 *offset_y = -1 * source_clip_box.bottom;
438 break;
439 case 2:
440 *offset_x = page_width - source_clip_box.right;
441 *offset_y = 0;
442 break;
443 case 3:
444 *offset_x = page_height - source_clip_box.right;
445 *offset_y = page_width - source_clip_box.top;
446 break;
447 default:
448 NOTREACHED();
449 break;
453 // This formats a string with special 0xfffe end-of-line hyphens the same way
454 // as Adobe Reader. When a hyphen is encountered, the next non-CR/LF whitespace
455 // becomes CR+LF and the hyphen is erased. If there is no whitespace between
456 // two hyphens, the latter hyphen is erased and ignored.
457 void FormatStringWithHyphens(base::string16* text) {
458 // First pass marks all the hyphen positions.
459 struct HyphenPosition {
460 HyphenPosition() : position(0), next_whitespace_position(0) {}
461 size_t position;
462 size_t next_whitespace_position; // 0 for none
464 std::vector<HyphenPosition> hyphen_positions;
465 HyphenPosition current_hyphen_position;
466 bool current_hyphen_position_is_valid = false;
467 const base::char16 kPdfiumHyphenEOL = 0xfffe;
469 for (size_t i = 0; i < text->size(); ++i) {
470 const base::char16& current_char = (*text)[i];
471 if (current_char == kPdfiumHyphenEOL) {
472 if (current_hyphen_position_is_valid)
473 hyphen_positions.push_back(current_hyphen_position);
474 current_hyphen_position = HyphenPosition();
475 current_hyphen_position.position = i;
476 current_hyphen_position_is_valid = true;
477 } else if (base::IsUnicodeWhitespace(current_char)) {
478 if (current_hyphen_position_is_valid) {
479 if (current_char != L'\r' && current_char != L'\n')
480 current_hyphen_position.next_whitespace_position = i;
481 hyphen_positions.push_back(current_hyphen_position);
482 current_hyphen_position_is_valid = false;
486 if (current_hyphen_position_is_valid)
487 hyphen_positions.push_back(current_hyphen_position);
489 // With all the hyphen positions, do the search and replace.
490 while (!hyphen_positions.empty()) {
491 static const base::char16 kCr[] = {L'\r', L'\0'};
492 const HyphenPosition& position = hyphen_positions.back();
493 if (position.next_whitespace_position != 0) {
494 (*text)[position.next_whitespace_position] = L'\n';
495 text->insert(position.next_whitespace_position, kCr);
497 text->erase(position.position, 1);
498 hyphen_positions.pop_back();
501 // Adobe Reader also get rid of trailing spaces right before a CRLF.
502 static const base::char16 kSpaceCrCn[] = {L' ', L'\r', L'\n', L'\0'};
503 static const base::char16 kCrCn[] = {L'\r', L'\n', L'\0'};
504 base::ReplaceSubstringsAfterOffset(text, 0, kSpaceCrCn, kCrCn);
507 // Replace CR/LF with just LF on POSIX.
508 void FormatStringForOS(base::string16* text) {
509 #if defined(OS_POSIX)
510 static const base::char16 kCr[] = {L'\r', L'\0'};
511 static const base::char16 kBlank[] = {L'\0'};
512 base::ReplaceChars(*text, kCr, kBlank, text);
513 #elif defined(OS_WIN)
514 // Do nothing
515 #else
516 NOTIMPLEMENTED();
517 #endif
520 // Returns a VarDictionary (representing a bookmark), which in turn contains
521 // child VarDictionaries (representing the child bookmarks).
522 // If NULL is passed in as the bookmark then we traverse from the "root".
523 // Note that the "root" bookmark contains no useful information.
524 pp::VarDictionary TraverseBookmarks(FPDF_DOCUMENT doc, FPDF_BOOKMARK bookmark) {
525 pp::VarDictionary dict;
526 base::string16 title;
527 unsigned long buffer_size = FPDFBookmark_GetTitle(bookmark, NULL, 0);
528 size_t title_length = base::checked_cast<size_t>(buffer_size) /
529 sizeof(base::string16::value_type);
530 if (title_length > 0) {
531 PDFiumAPIStringBufferAdapter<base::string16> api_string_adapter(
532 &title, title_length, true);
533 void* data = api_string_adapter.GetData();
534 FPDFBookmark_GetTitle(bookmark, data, buffer_size);
535 api_string_adapter.Close(title_length);
537 dict.Set(pp::Var("title"), pp::Var(base::UTF16ToUTF8(title)));
539 FPDF_DEST dest = FPDFBookmark_GetDest(doc, bookmark);
540 // Some bookmarks don't have a page to select.
541 if (dest) {
542 int page_index = FPDFDest_GetPageIndex(doc, dest);
543 dict.Set(pp::Var("page"), pp::Var(page_index));
546 pp::VarArray children;
547 int child_index = 0;
548 for (FPDF_BOOKMARK child_bookmark = FPDFBookmark_GetFirstChild(doc, bookmark);
549 child_bookmark != NULL;
550 child_bookmark = FPDFBookmark_GetNextSibling(doc, child_bookmark)) {
551 children.Set(child_index, TraverseBookmarks(doc, child_bookmark));
552 child_index++;
554 dict.Set(pp::Var("children"), children);
555 return dict;
558 } // namespace
560 bool InitializeSDK() {
561 FPDF_InitLibrary();
563 #if defined(OS_LINUX)
564 // Font loading doesn't work in the renderer sandbox in Linux.
565 FPDF_SetSystemFontInfo(&g_font_info);
566 #endif
568 FSDK_SetUnSpObjProcessHandler(&g_unsuppored_info);
570 return true;
573 void ShutdownSDK() {
574 FPDF_DestroyLibrary();
577 PDFEngine* PDFEngine::Create(PDFEngine::Client* client) {
578 return new PDFiumEngine(client);
581 PDFiumEngine::PDFiumEngine(PDFEngine::Client* client)
582 : client_(client),
583 current_zoom_(1.0),
584 current_rotation_(0),
585 doc_loader_(this),
586 password_tries_remaining_(0),
587 doc_(NULL),
588 form_(NULL),
589 defer_page_unload_(false),
590 selecting_(false),
591 mouse_down_state_(PDFiumPage::NONSELECTABLE_AREA,
592 PDFiumPage::LinkTarget()),
593 next_page_to_search_(-1),
594 last_page_to_search_(-1),
595 last_character_index_to_search_(-1),
596 permissions_(0),
597 permissions_handler_revision_(-1),
598 fpdf_availability_(NULL),
599 next_timer_id_(0),
600 last_page_mouse_down_(-1),
601 first_visible_page_(-1),
602 most_visible_page_(-1),
603 called_do_document_action_(false),
604 render_grayscale_(false),
605 progressive_paint_timeout_(0),
606 getting_password_(false) {
607 find_factory_.Initialize(this);
608 password_factory_.Initialize(this);
610 file_access_.m_FileLen = 0;
611 file_access_.m_GetBlock = &GetBlock;
612 file_access_.m_Param = &doc_loader_;
614 file_availability_.version = 1;
615 file_availability_.IsDataAvail = &IsDataAvail;
616 file_availability_.loader = &doc_loader_;
618 download_hints_.version = 1;
619 download_hints_.AddSegment = &AddSegment;
620 download_hints_.loader = &doc_loader_;
622 // Initialize FPDF_FORMFILLINFO member variables. Deriving from this struct
623 // allows the static callbacks to be able to cast the FPDF_FORMFILLINFO in
624 // callbacks to ourself instead of maintaining a map of them to
625 // PDFiumEngine.
626 FPDF_FORMFILLINFO::version = 1;
627 FPDF_FORMFILLINFO::m_pJsPlatform = this;
628 FPDF_FORMFILLINFO::Release = NULL;
629 FPDF_FORMFILLINFO::FFI_Invalidate = Form_Invalidate;
630 FPDF_FORMFILLINFO::FFI_OutputSelectedRect = Form_OutputSelectedRect;
631 FPDF_FORMFILLINFO::FFI_SetCursor = Form_SetCursor;
632 FPDF_FORMFILLINFO::FFI_SetTimer = Form_SetTimer;
633 FPDF_FORMFILLINFO::FFI_KillTimer = Form_KillTimer;
634 FPDF_FORMFILLINFO::FFI_GetLocalTime = Form_GetLocalTime;
635 FPDF_FORMFILLINFO::FFI_OnChange = Form_OnChange;
636 FPDF_FORMFILLINFO::FFI_GetPage = Form_GetPage;
637 FPDF_FORMFILLINFO::FFI_GetCurrentPage = Form_GetCurrentPage;
638 FPDF_FORMFILLINFO::FFI_GetRotation = Form_GetRotation;
639 FPDF_FORMFILLINFO::FFI_ExecuteNamedAction = Form_ExecuteNamedAction;
640 FPDF_FORMFILLINFO::FFI_SetTextFieldFocus = Form_SetTextFieldFocus;
641 FPDF_FORMFILLINFO::FFI_DoURIAction = Form_DoURIAction;
642 FPDF_FORMFILLINFO::FFI_DoGoToAction = Form_DoGoToAction;
643 #ifdef PDF_USE_XFA
644 FPDF_FORMFILLINFO::version = 2;
645 FPDF_FORMFILLINFO::FFI_EmailTo = Form_EmailTo;
646 FPDF_FORMFILLINFO::FFI_DisplayCaret = Form_DisplayCaret;
647 FPDF_FORMFILLINFO::FFI_SetCurrentPage = Form_SetCurrentPage;
648 FPDF_FORMFILLINFO::FFI_GetCurrentPageIndex = Form_GetCurrentPageIndex;
649 FPDF_FORMFILLINFO::FFI_GetPageViewRect = Form_GetPageViewRect;
650 FPDF_FORMFILLINFO::FFI_GetPlatform = Form_GetPlatform;
651 FPDF_FORMFILLINFO::FFI_PopupMenu = Form_PopupMenu;
652 FPDF_FORMFILLINFO::FFI_PostRequestURL = Form_PostRequestURL;
653 FPDF_FORMFILLINFO::FFI_PutRequestURL = Form_PutRequestURL;
654 FPDF_FORMFILLINFO::FFI_UploadTo = Form_UploadTo;
655 FPDF_FORMFILLINFO::FFI_DownloadFromURL = Form_DownloadFromURL;
656 FPDF_FORMFILLINFO::FFI_OpenFile = Form_OpenFile;
657 FPDF_FORMFILLINFO::FFI_GotoURL = Form_GotoURL;
658 FPDF_FORMFILLINFO::FFI_GetLanguage = Form_GetLanguage;
659 #endif // PDF_USE_XFA
660 IPDF_JSPLATFORM::version = 2;
661 IPDF_JSPLATFORM::app_alert = Form_Alert;
662 IPDF_JSPLATFORM::app_beep = Form_Beep;
663 IPDF_JSPLATFORM::app_response = Form_Response;
664 IPDF_JSPLATFORM::Doc_getFilePath = Form_GetFilePath;
665 IPDF_JSPLATFORM::Doc_mail = Form_Mail;
666 IPDF_JSPLATFORM::Doc_print = Form_Print;
667 IPDF_JSPLATFORM::Doc_submitForm = Form_SubmitForm;
668 IPDF_JSPLATFORM::Doc_gotoPage = Form_GotoPage;
669 IPDF_JSPLATFORM::Field_browse = Form_Browse;
670 IPDF_JSPLATFORM::m_isolate = v8::Isolate::GetCurrent();
671 IPDF_JSPLATFORM::m_v8EmbedderSlot = gin::kEmbedderPDFium;
673 IFSDK_PAUSE::version = 1;
674 IFSDK_PAUSE::user = NULL;
675 IFSDK_PAUSE::NeedToPauseNow = Pause_NeedToPauseNow;
678 PDFiumEngine::~PDFiumEngine() {
679 for (size_t i = 0; i < pages_.size(); ++i)
680 pages_[i]->Unload();
682 if (doc_) {
683 FORM_DoDocumentAAction(form_, FPDFDOC_AACTION_WC);
685 #ifdef PDF_USE_XFA
686 // XFA may require |form_| to outlive |doc_|, so shut down in that order.
687 FPDF_CloseDocument(doc_);
688 FPDFDOC_ExitFormFillEnvironment(form_);
689 #else
690 // Normally |doc_| should outlive |form_|.
691 FPDFDOC_ExitFormFillEnvironment(form_);
692 FPDF_CloseDocument(doc_);
693 #endif
695 FPDFAvail_Destroy(fpdf_availability_);
697 STLDeleteElements(&pages_);
700 #ifdef PDF_USE_XFA
702 // This is just for testing, needs to be removed later
703 #if defined(WIN32)
704 #define XFA_TESTFILE(filename) "E:/"#filename
705 #else
706 #define XFA_TESTFILE(filename) "/home/"#filename
707 #endif
709 struct FPDF_FILE {
710 FPDF_FILEHANDLER file_handler;
711 FILE* file;
714 void Sample_Release(FPDF_LPVOID client_data) {
715 if (!client_data)
716 return;
717 FPDF_FILE* file_wrapper = (FPDF_FILE*)client_data;
718 fclose(file_wrapper->file);
719 delete file_wrapper;
722 FPDF_DWORD Sample_GetSize(FPDF_LPVOID client_data) {
723 if (!client_data)
724 return 0;
725 FPDF_FILE* file_wrapper = (FPDF_FILE*)client_data;
726 long cur_pos = ftell(file_wrapper->file);
727 if (cur_pos == -1)
728 return 0;
729 if (fseek(file_wrapper->file, 0, SEEK_END))
730 return 0;
731 long size = ftell(file_wrapper->file);
732 fseek(file_wrapper->file, cur_pos, SEEK_SET);
733 return (FPDF_DWORD)size;
736 FPDF_RESULT Sample_ReadBlock(FPDF_LPVOID client_data,
737 FPDF_DWORD offset,
738 FPDF_LPVOID buffer,
739 FPDF_DWORD size) {
740 if (!client_data)
741 return -1;
742 FPDF_FILE* file_wrapper = (FPDF_FILE*)client_data;
743 if (fseek(file_wrapper->file, (long)offset, SEEK_SET))
744 return -1;
745 size_t read_size = fread(buffer, 1, size, file_wrapper->file);
746 return read_size == size ? 0 : -1;
749 FPDF_RESULT Sample_WriteBlock(FPDF_LPVOID client_data,
750 FPDF_DWORD offset,
751 FPDF_LPCVOID buffer,
752 FPDF_DWORD size) {
753 if (!client_data)
754 return -1;
755 FPDF_FILE* file_wrapper = (FPDF_FILE*)client_data;
756 if (fseek(file_wrapper->file, (long)offset, SEEK_SET))
757 return -1;
758 // Write data
759 size_t write_size = fwrite(buffer, 1, size, file_wrapper->file);
760 return write_size == size ? 0 : -1;
763 FPDF_RESULT Sample_Flush(FPDF_LPVOID client_data) {
764 if (!client_data)
765 return -1;
766 // Flush file
767 fflush(((FPDF_FILE*)client_data)->file);
768 return 0;
771 FPDF_RESULT Sample_Truncate(FPDF_LPVOID client_data, FPDF_DWORD size) {
772 return 0;
775 void PDFiumEngine::Form_EmailTo(FPDF_FORMFILLINFO* param,
776 FPDF_FILEHANDLER* file_handler,
777 FPDF_WIDESTRING to,
778 FPDF_WIDESTRING subject,
779 FPDF_WIDESTRING cc,
780 FPDF_WIDESTRING bcc,
781 FPDF_WIDESTRING message) {
782 std::string to_str =
783 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(to));
784 std::string subject_str =
785 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(subject));
786 std::string cc_str =
787 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(cc));
788 std::string bcc_str =
789 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(bcc));
790 std::string message_str =
791 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(message));
793 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
794 engine->client_->Email(to_str, cc_str, bcc_str, subject_str, message_str);
797 void PDFiumEngine::Form_DisplayCaret(FPDF_FORMFILLINFO* param,
798 FPDF_PAGE page,
799 FPDF_BOOL visible,
800 double left,
801 double top,
802 double right,
803 double bottom) {
804 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
805 engine->client_->UpdateCursor(PP_CURSORTYPE_IBEAM);
806 std::vector<pp::Rect> tickmarks;
807 pp::Rect rect(left, top, right, bottom);
808 tickmarks.push_back(rect);
809 engine->client_->UpdateTickMarks(tickmarks);
812 void PDFiumEngine::Form_SetCurrentPage(FPDF_FORMFILLINFO* param,
813 FPDF_DOCUMENT document,
814 int page) {
815 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
816 pp::Rect page_view_rect = engine->GetPageContentsRect(page);
817 engine->ScrolledToYPosition(page_view_rect.height());
818 pp::Point pos(1, page_view_rect.height());
819 engine->SetScrollPosition(pos);
822 int PDFiumEngine::Form_GetCurrentPageIndex(FPDF_FORMFILLINFO* param,
823 FPDF_DOCUMENT document) {
824 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
825 return engine->GetMostVisiblePage();
828 void PDFiumEngine::Form_GetPageViewRect(FPDF_FORMFILLINFO* param,
829 FPDF_PAGE page,
830 double* left,
831 double* top,
832 double* right,
833 double* bottom) {
834 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
835 int page_index = engine->GetMostVisiblePage();
836 pp::Rect page_view_rect = engine->GetPageContentsRect(page_index);
838 *left = page_view_rect.x();
839 *right = page_view_rect.right();
840 *top = page_view_rect.y();
841 *bottom = page_view_rect.bottom();
844 int PDFiumEngine::Form_GetPlatform(FPDF_FORMFILLINFO* param,
845 void* platform,
846 int length) {
847 int platform_flag = -1;
849 #if defined(WIN32)
850 platform_flag = 0;
851 #elif defined(__linux__)
852 platform_flag = 1;
853 #else
854 platform_flag = 2;
855 #endif
857 std::string javascript = "alert(\"Platform:"
858 + base::DoubleToString(platform_flag)
859 + "\")";
861 return platform_flag;
864 FPDF_BOOL PDFiumEngine::Form_PopupMenu(FPDF_FORMFILLINFO* param,
865 FPDF_PAGE page,
866 FPDF_WIDGET widget,
867 int menu_flag,
868 float x,
869 float y) {
870 return false;
873 FPDF_BOOL PDFiumEngine::Form_PostRequestURL(FPDF_FORMFILLINFO* param,
874 FPDF_WIDESTRING url,
875 FPDF_WIDESTRING data,
876 FPDF_WIDESTRING content_type,
877 FPDF_WIDESTRING encode,
878 FPDF_WIDESTRING header,
879 FPDF_BSTR* response) {
880 std::string url_str =
881 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(url));
882 std::string data_str =
883 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(data));
884 std::string content_type_str =
885 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(content_type));
886 std::string encode_str =
887 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(encode));
888 std::string header_str =
889 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(header));
891 std::string javascript = "alert(\"Post:"
892 + url_str + "," + data_str + "," + content_type_str + ","
893 + encode_str + "," + header_str
894 + "\")";
895 return true;
898 FPDF_BOOL PDFiumEngine::Form_PutRequestURL(FPDF_FORMFILLINFO* param,
899 FPDF_WIDESTRING url,
900 FPDF_WIDESTRING data,
901 FPDF_WIDESTRING encode) {
902 std::string url_str =
903 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(url));
904 std::string data_str =
905 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(data));
906 std::string encode_str =
907 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(encode));
909 std::string javascript = "alert(\"Put:"
910 + url_str + "," + data_str + "," + encode_str
911 + "\")";
913 return true;
916 void PDFiumEngine::Form_UploadTo(FPDF_FORMFILLINFO* param,
917 FPDF_FILEHANDLER* file_handle,
918 int file_flag,
919 FPDF_WIDESTRING to) {
920 std::string to_str =
921 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(to));
922 // TODO: needs the full implementation of form uploading
925 FPDF_LPFILEHANDLER PDFiumEngine::Form_DownloadFromURL(FPDF_FORMFILLINFO* param,
926 FPDF_WIDESTRING url) {
927 std::string url_str =
928 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(url));
930 // Now should get data from url.
931 // For testing purpose, use data read from file
932 // TODO: needs the full implementation here
933 FILE* file = fopen(XFA_TESTFILE("downloadtest.tem"), "w");
935 FPDF_FILE* file_wrapper = new FPDF_FILE;
936 file_wrapper->file = file;
937 file_wrapper->file_handler.clientData = file_wrapper;
938 file_wrapper->file_handler.Flush = Sample_Flush;
939 file_wrapper->file_handler.GetSize = Sample_GetSize;
940 file_wrapper->file_handler.ReadBlock = Sample_ReadBlock;
941 file_wrapper->file_handler.Release = Sample_Release;
942 file_wrapper->file_handler.Truncate = Sample_Truncate;
943 file_wrapper->file_handler.WriteBlock = Sample_WriteBlock;
945 return &file_wrapper->file_handler;
948 FPDF_FILEHANDLER* PDFiumEngine::Form_OpenFile(FPDF_FORMFILLINFO* param,
949 int file_flag,
950 FPDF_WIDESTRING url,
951 const char* mode) {
952 std::string url_str = "NULL";
953 if (url != NULL) {
954 url_str =
955 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(url));
957 // TODO: need to implement open file from the url
958 // Use a file path for the ease of testing
959 FILE* file = fopen(XFA_TESTFILE("tem.txt"), mode);
960 FPDF_FILE* file_wrapper = new FPDF_FILE;
961 file_wrapper->file = file;
962 file_wrapper->file_handler.clientData = file_wrapper;
963 file_wrapper->file_handler.Flush = Sample_Flush;
964 file_wrapper->file_handler.GetSize = Sample_GetSize;
965 file_wrapper->file_handler.ReadBlock = Sample_ReadBlock;
966 file_wrapper->file_handler.Release = Sample_Release;
967 file_wrapper->file_handler.Truncate = Sample_Truncate;
968 file_wrapper->file_handler.WriteBlock = Sample_WriteBlock;
969 return &file_wrapper->file_handler;
972 void PDFiumEngine::Form_GotoURL(FPDF_FORMFILLINFO* param,
973 FPDF_DOCUMENT document,
974 FPDF_WIDESTRING url) {
975 std::string url_str =
976 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(url));
977 // TODO: needs to implement GOTO URL action
980 int PDFiumEngine::Form_GetLanguage(FPDF_FORMFILLINFO* param,
981 void* language,
982 int length) {
983 return 0;
986 #endif // PDF_USE_XFA
988 int PDFiumEngine::GetBlock(void* param, unsigned long position,
989 unsigned char* buffer, unsigned long size) {
990 DocumentLoader* loader = static_cast<DocumentLoader*>(param);
991 return loader->GetBlock(position, size, buffer);
994 FPDF_BOOL PDFiumEngine::IsDataAvail(FX_FILEAVAIL* param,
995 size_t offset, size_t size) {
996 PDFiumEngine::FileAvail* file_avail =
997 static_cast<PDFiumEngine::FileAvail*>(param);
998 return file_avail->loader->IsDataAvailable(offset, size);
1001 void PDFiumEngine::AddSegment(FX_DOWNLOADHINTS* param,
1002 size_t offset, size_t size) {
1003 PDFiumEngine::DownloadHints* download_hints =
1004 static_cast<PDFiumEngine::DownloadHints*>(param);
1005 return download_hints->loader->RequestData(offset, size);
1008 bool PDFiumEngine::New(const char* url,
1009 const char* headers) {
1010 url_ = url;
1011 if (!headers)
1012 headers_.clear();
1013 else
1014 headers_ = headers;
1015 return true;
1018 void PDFiumEngine::PageOffsetUpdated(const pp::Point& page_offset) {
1019 page_offset_ = page_offset;
1022 void PDFiumEngine::PluginSizeUpdated(const pp::Size& size) {
1023 CancelPaints();
1025 plugin_size_ = size;
1026 CalculateVisiblePages();
1029 void PDFiumEngine::ScrolledToXPosition(int position) {
1030 CancelPaints();
1032 int old_x = position_.x();
1033 position_.set_x(position);
1034 CalculateVisiblePages();
1035 client_->Scroll(pp::Point(old_x - position, 0));
1038 void PDFiumEngine::ScrolledToYPosition(int position) {
1039 CancelPaints();
1041 int old_y = position_.y();
1042 position_.set_y(position);
1043 CalculateVisiblePages();
1044 client_->Scroll(pp::Point(0, old_y - position));
1047 void PDFiumEngine::PrePaint() {
1048 for (size_t i = 0; i < progressive_paints_.size(); ++i)
1049 progressive_paints_[i].painted_ = false;
1052 void PDFiumEngine::Paint(const pp::Rect& rect,
1053 pp::ImageData* image_data,
1054 std::vector<pp::Rect>* ready,
1055 std::vector<pp::Rect>* pending) {
1056 DCHECK(image_data);
1057 DCHECK(ready);
1058 DCHECK(pending);
1060 pp::Rect leftover = rect;
1061 for (size_t i = 0; i < visible_pages_.size(); ++i) {
1062 int index = visible_pages_[i];
1063 pp::Rect page_rect = pages_[index]->rect();
1064 // Convert the current page's rectangle to screen rectangle. We do this
1065 // instead of the reverse (converting the dirty rectangle from screen to
1066 // page coordinates) because then we'd have to convert back to screen
1067 // coordinates, and the rounding errors sometime leave pixels dirty or even
1068 // move the text up or down a pixel when zoomed.
1069 pp::Rect page_rect_in_screen = GetPageScreenRect(index);
1070 pp::Rect dirty_in_screen = page_rect_in_screen.Intersect(leftover);
1071 if (dirty_in_screen.IsEmpty())
1072 continue;
1074 leftover = leftover.Subtract(dirty_in_screen);
1076 if (pages_[index]->available()) {
1077 int progressive = GetProgressiveIndex(index);
1078 if (progressive != -1) {
1079 DCHECK_GE(progressive, 0);
1080 DCHECK_LT(static_cast<size_t>(progressive), progressive_paints_.size());
1081 if (progressive_paints_[progressive].rect != dirty_in_screen) {
1082 // The PDFium code can only handle one progressive paint at a time, so
1083 // queue this up. Previously we used to merge the rects when this
1084 // happened, but it made scrolling up on complex PDFs very slow since
1085 // there would be a damaged rect at the top (from scroll) and at the
1086 // bottom (from toolbar).
1087 pending->push_back(dirty_in_screen);
1088 continue;
1092 if (progressive == -1) {
1093 progressive = StartPaint(index, dirty_in_screen);
1094 progressive_paint_timeout_ = kMaxInitialProgressivePaintTimeMs;
1095 } else {
1096 progressive_paint_timeout_ = kMaxProgressivePaintTimeMs;
1099 progressive_paints_[progressive].painted_ = true;
1100 if (ContinuePaint(progressive, image_data)) {
1101 FinishPaint(progressive, image_data);
1102 ready->push_back(dirty_in_screen);
1103 } else {
1104 pending->push_back(dirty_in_screen);
1106 } else {
1107 PaintUnavailablePage(index, dirty_in_screen, image_data);
1108 ready->push_back(dirty_in_screen);
1113 void PDFiumEngine::PostPaint() {
1114 for (size_t i = 0; i < progressive_paints_.size(); ++i) {
1115 if (progressive_paints_[i].painted_)
1116 continue;
1118 // This rectangle must have been merged with another one, that's why we
1119 // weren't asked to paint it. Remove it or otherwise we'll never finish
1120 // painting.
1121 FPDF_RenderPage_Close(
1122 pages_[progressive_paints_[i].page_index]->GetPage());
1123 FPDFBitmap_Destroy(progressive_paints_[i].bitmap);
1124 progressive_paints_.erase(progressive_paints_.begin() + i);
1125 --i;
1129 bool PDFiumEngine::HandleDocumentLoad(const pp::URLLoader& loader) {
1130 password_tries_remaining_ = kMaxPasswordTries;
1131 return doc_loader_.Init(loader, url_, headers_);
1134 pp::Instance* PDFiumEngine::GetPluginInstance() {
1135 return client_->GetPluginInstance();
1138 pp::URLLoader PDFiumEngine::CreateURLLoader() {
1139 return client_->CreateURLLoader();
1142 void PDFiumEngine::AppendPage(PDFEngine* engine, int index) {
1143 // Unload and delete the blank page before appending.
1144 pages_[index]->Unload();
1145 pages_[index]->set_calculated_links(false);
1146 pp::Size curr_page_size = GetPageSize(index);
1147 FPDFPage_Delete(doc_, index);
1148 FPDF_ImportPages(doc_,
1149 static_cast<PDFiumEngine*>(engine)->doc(),
1150 "1",
1151 index);
1152 pp::Size new_page_size = GetPageSize(index);
1153 if (curr_page_size != new_page_size)
1154 LoadPageInfo(true);
1155 client_->Invalidate(GetPageScreenRect(index));
1158 pp::Point PDFiumEngine::GetScrollPosition() {
1159 return position_;
1162 void PDFiumEngine::SetScrollPosition(const pp::Point& position) {
1163 position_ = position;
1166 bool PDFiumEngine::IsProgressiveLoad() {
1167 return doc_loader_.is_partial_document();
1170 void PDFiumEngine::OnPartialDocumentLoaded() {
1171 file_access_.m_FileLen = doc_loader_.document_size();
1172 fpdf_availability_ = FPDFAvail_Create(&file_availability_, &file_access_);
1173 DCHECK(fpdf_availability_);
1175 // Currently engine does not deal efficiently with some non-linearized files.
1176 // See http://code.google.com/p/chromium/issues/detail?id=59400
1177 // To improve user experience we download entire file for non-linearized PDF.
1178 if (!FPDFAvail_IsLinearized(fpdf_availability_)) {
1179 doc_loader_.RequestData(0, doc_loader_.document_size());
1180 return;
1183 LoadDocument();
1186 void PDFiumEngine::OnPendingRequestComplete() {
1187 if (!doc_ || !form_) {
1188 LoadDocument();
1189 return;
1192 // LoadDocument() will result in |pending_pages_| being reset so there's no
1193 // need to run the code below in that case.
1194 bool update_pages = false;
1195 std::vector<int> still_pending;
1196 for (size_t i = 0; i < pending_pages_.size(); ++i) {
1197 if (CheckPageAvailable(pending_pages_[i], &still_pending)) {
1198 update_pages = true;
1199 if (IsPageVisible(pending_pages_[i]))
1200 client_->Invalidate(GetPageScreenRect(pending_pages_[i]));
1203 pending_pages_.swap(still_pending);
1204 if (update_pages)
1205 LoadPageInfo(true);
1208 void PDFiumEngine::OnNewDataAvailable() {
1209 client_->DocumentLoadProgress(doc_loader_.GetAvailableData(),
1210 doc_loader_.document_size());
1213 void PDFiumEngine::OnDocumentComplete() {
1214 if (!doc_ || !form_) {
1215 file_access_.m_FileLen = doc_loader_.document_size();
1216 LoadDocument();
1217 return;
1220 bool need_update = false;
1221 for (size_t i = 0; i < pages_.size(); ++i) {
1222 if (pages_[i]->available())
1223 continue;
1225 pages_[i]->set_available(true);
1226 // We still need to call IsPageAvail() even if the whole document is
1227 // already downloaded.
1228 FPDFAvail_IsPageAvail(fpdf_availability_, i, &download_hints_);
1229 need_update = true;
1230 if (IsPageVisible(i))
1231 client_->Invalidate(GetPageScreenRect(i));
1233 if (need_update)
1234 LoadPageInfo(true);
1236 FinishLoadingDocument();
1239 void PDFiumEngine::FinishLoadingDocument() {
1240 DCHECK(doc_loader_.IsDocumentComplete() && doc_);
1241 if (called_do_document_action_)
1242 return;
1243 called_do_document_action_ = true;
1245 // These can only be called now, as the JS might end up needing a page.
1246 FORM_DoDocumentJSAction(form_);
1247 FORM_DoDocumentOpenAction(form_);
1248 if (most_visible_page_ != -1) {
1249 FPDF_PAGE new_page = pages_[most_visible_page_]->GetPage();
1250 FORM_DoPageAAction(new_page, form_, FPDFPAGE_AACTION_OPEN);
1253 if (doc_) // This can only happen if loading |doc_| fails.
1254 client_->DocumentLoadComplete(pages_.size());
1257 void PDFiumEngine::UnsupportedFeature(int type) {
1258 std::string feature;
1259 switch (type) {
1260 #ifndef PDF_USE_XFA
1261 case FPDF_UNSP_DOC_XFAFORM:
1262 feature = "XFA";
1263 break;
1264 #endif
1265 case FPDF_UNSP_DOC_PORTABLECOLLECTION:
1266 feature = "Portfolios_Packages";
1267 break;
1268 case FPDF_UNSP_DOC_ATTACHMENT:
1269 case FPDF_UNSP_ANNOT_ATTACHMENT:
1270 feature = "Attachment";
1271 break;
1272 case FPDF_UNSP_DOC_SECURITY:
1273 feature = "Rights_Management";
1274 break;
1275 case FPDF_UNSP_DOC_SHAREDREVIEW:
1276 feature = "Shared_Review";
1277 break;
1278 case FPDF_UNSP_DOC_SHAREDFORM_ACROBAT:
1279 case FPDF_UNSP_DOC_SHAREDFORM_FILESYSTEM:
1280 case FPDF_UNSP_DOC_SHAREDFORM_EMAIL:
1281 feature = "Shared_Form";
1282 break;
1283 case FPDF_UNSP_ANNOT_3DANNOT:
1284 feature = "3D";
1285 break;
1286 case FPDF_UNSP_ANNOT_MOVIE:
1287 feature = "Movie";
1288 break;
1289 case FPDF_UNSP_ANNOT_SOUND:
1290 feature = "Sound";
1291 break;
1292 case FPDF_UNSP_ANNOT_SCREEN_MEDIA:
1293 case FPDF_UNSP_ANNOT_SCREEN_RICHMEDIA:
1294 feature = "Screen";
1295 break;
1296 case FPDF_UNSP_ANNOT_SIG:
1297 feature = "Digital_Signature";
1298 break;
1300 client_->DocumentHasUnsupportedFeature(feature);
1303 void PDFiumEngine::ContinueFind(int32_t result) {
1304 StartFind(current_find_text_.c_str(), !!result);
1307 bool PDFiumEngine::HandleEvent(const pp::InputEvent& event) {
1308 DCHECK(!defer_page_unload_);
1309 defer_page_unload_ = true;
1310 bool rv = false;
1311 switch (event.GetType()) {
1312 case PP_INPUTEVENT_TYPE_MOUSEDOWN:
1313 rv = OnMouseDown(pp::MouseInputEvent(event));
1314 break;
1315 case PP_INPUTEVENT_TYPE_MOUSEUP:
1316 rv = OnMouseUp(pp::MouseInputEvent(event));
1317 break;
1318 case PP_INPUTEVENT_TYPE_MOUSEMOVE:
1319 rv = OnMouseMove(pp::MouseInputEvent(event));
1320 break;
1321 case PP_INPUTEVENT_TYPE_KEYDOWN:
1322 rv = OnKeyDown(pp::KeyboardInputEvent(event));
1323 break;
1324 case PP_INPUTEVENT_TYPE_KEYUP:
1325 rv = OnKeyUp(pp::KeyboardInputEvent(event));
1326 break;
1327 case PP_INPUTEVENT_TYPE_CHAR:
1328 rv = OnChar(pp::KeyboardInputEvent(event));
1329 break;
1330 default:
1331 break;
1334 DCHECK(defer_page_unload_);
1335 defer_page_unload_ = false;
1336 for (size_t i = 0; i < deferred_page_unloads_.size(); ++i)
1337 pages_[deferred_page_unloads_[i]]->Unload();
1338 deferred_page_unloads_.clear();
1339 return rv;
1342 uint32_t PDFiumEngine::QuerySupportedPrintOutputFormats() {
1343 if (!HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY))
1344 return 0;
1345 return PP_PRINTOUTPUTFORMAT_PDF;
1348 void PDFiumEngine::PrintBegin() {
1349 FORM_DoDocumentAAction(form_, FPDFDOC_AACTION_WP);
1352 pp::Resource PDFiumEngine::PrintPages(
1353 const PP_PrintPageNumberRange_Dev* page_ranges, uint32_t page_range_count,
1354 const PP_PrintSettings_Dev& print_settings) {
1355 if (HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY))
1356 return PrintPagesAsPDF(page_ranges, page_range_count, print_settings);
1357 else if (HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY))
1358 return PrintPagesAsRasterPDF(page_ranges, page_range_count, print_settings);
1359 return pp::Resource();
1362 FPDF_DOCUMENT PDFiumEngine::CreateSinglePageRasterPdf(
1363 double source_page_width,
1364 double source_page_height,
1365 const PP_PrintSettings_Dev& print_settings,
1366 PDFiumPage* page_to_print) {
1367 FPDF_DOCUMENT temp_doc = FPDF_CreateNewDocument();
1368 if (!temp_doc)
1369 return temp_doc;
1371 const pp::Size& bitmap_size(page_to_print->rect().size());
1373 FPDF_PAGE temp_page =
1374 FPDFPage_New(temp_doc, 0, source_page_width, source_page_height);
1376 pp::ImageData image = pp::ImageData(client_->GetPluginInstance(),
1377 PP_IMAGEDATAFORMAT_BGRA_PREMUL,
1378 bitmap_size,
1379 false);
1381 FPDF_BITMAP bitmap = FPDFBitmap_CreateEx(bitmap_size.width(),
1382 bitmap_size.height(),
1383 FPDFBitmap_BGRx,
1384 image.data(),
1385 image.stride());
1387 // Clear the bitmap
1388 FPDFBitmap_FillRect(
1389 bitmap, 0, 0, bitmap_size.width(), bitmap_size.height(), 0xFFFFFFFF);
1391 pp::Rect page_rect = page_to_print->rect();
1392 FPDF_RenderPageBitmap(bitmap,
1393 page_to_print->GetPrintPage(),
1394 page_rect.x(),
1395 page_rect.y(),
1396 page_rect.width(),
1397 page_rect.height(),
1398 print_settings.orientation,
1399 FPDF_ANNOT | FPDF_PRINTING | FPDF_NO_CATCH);
1401 double ratio_x = ConvertUnitDouble(bitmap_size.width(),
1402 print_settings.dpi,
1403 kPointsPerInch);
1404 double ratio_y = ConvertUnitDouble(bitmap_size.height(),
1405 print_settings.dpi,
1406 kPointsPerInch);
1408 // Add the bitmap to an image object and add the image object to the output
1409 // page.
1410 FPDF_PAGEOBJECT temp_img = FPDFPageObj_NewImgeObj(temp_doc);
1411 FPDFImageObj_SetBitmap(&temp_page, 1, temp_img, bitmap);
1412 FPDFImageObj_SetMatrix(temp_img, ratio_x, 0, 0, ratio_y, 0, 0);
1413 FPDFPage_InsertObject(temp_page, temp_img);
1414 FPDFPage_GenerateContent(temp_page);
1415 FPDF_ClosePage(temp_page);
1417 page_to_print->ClosePrintPage();
1418 FPDFBitmap_Destroy(bitmap);
1420 return temp_doc;
1423 pp::Buffer_Dev PDFiumEngine::PrintPagesAsRasterPDF(
1424 const PP_PrintPageNumberRange_Dev* page_ranges, uint32_t page_range_count,
1425 const PP_PrintSettings_Dev& print_settings) {
1426 if (!page_range_count)
1427 return pp::Buffer_Dev();
1429 // If document is not downloaded yet, disable printing.
1430 if (doc_ && !doc_loader_.IsDocumentComplete())
1431 return pp::Buffer_Dev();
1433 FPDF_DOCUMENT output_doc = FPDF_CreateNewDocument();
1434 if (!output_doc)
1435 return pp::Buffer_Dev();
1437 SaveSelectedFormForPrint();
1439 std::vector<PDFiumPage> pages_to_print;
1440 // width and height of source PDF pages.
1441 std::vector<std::pair<double, double> > source_page_sizes;
1442 // Collect pages to print and sizes of source pages.
1443 std::vector<uint32_t> page_numbers =
1444 GetPageNumbersFromPrintPageNumberRange(page_ranges, page_range_count);
1445 for (size_t i = 0; i < page_numbers.size(); ++i) {
1446 uint32_t page_number = page_numbers[i];
1447 FPDF_PAGE pdf_page = FPDF_LoadPage(doc_, page_number);
1448 double source_page_width = FPDF_GetPageWidth(pdf_page);
1449 double source_page_height = FPDF_GetPageHeight(pdf_page);
1450 source_page_sizes.push_back(std::make_pair(source_page_width,
1451 source_page_height));
1453 int width_in_pixels = ConvertUnit(source_page_width,
1454 kPointsPerInch,
1455 print_settings.dpi);
1456 int height_in_pixels = ConvertUnit(source_page_height,
1457 kPointsPerInch,
1458 print_settings.dpi);
1460 pp::Rect rect(width_in_pixels, height_in_pixels);
1461 pages_to_print.push_back(PDFiumPage(this, page_number, rect, true));
1462 FPDF_ClosePage(pdf_page);
1465 #if defined(OS_LINUX)
1466 g_last_instance_id = client_->GetPluginInstance()->pp_instance();
1467 #endif
1469 size_t i = 0;
1470 for (; i < pages_to_print.size(); ++i) {
1471 double source_page_width = source_page_sizes[i].first;
1472 double source_page_height = source_page_sizes[i].second;
1474 // Use temp_doc to compress image by saving PDF to buffer.
1475 FPDF_DOCUMENT temp_doc = CreateSinglePageRasterPdf(source_page_width,
1476 source_page_height,
1477 print_settings,
1478 &pages_to_print[i]);
1480 if (!temp_doc)
1481 break;
1483 pp::Buffer_Dev buffer = GetFlattenedPrintData(temp_doc);
1484 FPDF_CloseDocument(temp_doc);
1486 PDFiumMemBufferFileRead file_read(buffer.data(), buffer.size());
1487 temp_doc = FPDF_LoadCustomDocument(&file_read, NULL);
1489 FPDF_BOOL imported = FPDF_ImportPages(output_doc, temp_doc, "1", i);
1490 FPDF_CloseDocument(temp_doc);
1491 if (!imported)
1492 break;
1495 pp::Buffer_Dev buffer;
1496 if (i == pages_to_print.size()) {
1497 FPDF_CopyViewerPreferences(output_doc, doc_);
1498 FitContentsToPrintableAreaIfRequired(output_doc, print_settings);
1499 // Now flatten all the output pages.
1500 buffer = GetFlattenedPrintData(output_doc);
1502 FPDF_CloseDocument(output_doc);
1503 return buffer;
1506 pp::Buffer_Dev PDFiumEngine::GetFlattenedPrintData(const FPDF_DOCUMENT& doc) {
1507 int page_count = FPDF_GetPageCount(doc);
1508 bool flatten_succeeded = true;
1509 for (int i = 0; i < page_count; ++i) {
1510 FPDF_PAGE page = FPDF_LoadPage(doc, i);
1511 DCHECK(page);
1512 if (page) {
1513 int flatten_ret = FPDFPage_Flatten(page, FLAT_PRINT);
1514 FPDF_ClosePage(page);
1515 if (flatten_ret == FLATTEN_FAIL) {
1516 flatten_succeeded = false;
1517 break;
1519 } else {
1520 flatten_succeeded = false;
1521 break;
1524 if (!flatten_succeeded) {
1525 FPDF_CloseDocument(doc);
1526 return pp::Buffer_Dev();
1529 pp::Buffer_Dev buffer;
1530 PDFiumMemBufferFileWrite output_file_write;
1531 if (FPDF_SaveAsCopy(doc, &output_file_write, 0)) {
1532 buffer = pp::Buffer_Dev(
1533 client_->GetPluginInstance(), output_file_write.size());
1534 if (!buffer.is_null()) {
1535 memcpy(buffer.data(), output_file_write.buffer().c_str(),
1536 output_file_write.size());
1539 return buffer;
1542 pp::Buffer_Dev PDFiumEngine::PrintPagesAsPDF(
1543 const PP_PrintPageNumberRange_Dev* page_ranges, uint32_t page_range_count,
1544 const PP_PrintSettings_Dev& print_settings) {
1545 if (!page_range_count)
1546 return pp::Buffer_Dev();
1548 DCHECK(doc_);
1549 FPDF_DOCUMENT output_doc = FPDF_CreateNewDocument();
1550 if (!output_doc)
1551 return pp::Buffer_Dev();
1553 SaveSelectedFormForPrint();
1555 std::string page_number_str;
1556 for (uint32_t index = 0; index < page_range_count; ++index) {
1557 if (!page_number_str.empty())
1558 page_number_str.append(",");
1559 page_number_str.append(
1560 base::IntToString(page_ranges[index].first_page_number + 1));
1561 if (page_ranges[index].first_page_number !=
1562 page_ranges[index].last_page_number) {
1563 page_number_str.append("-");
1564 page_number_str.append(
1565 base::IntToString(page_ranges[index].last_page_number + 1));
1569 std::vector<uint32_t> page_numbers =
1570 GetPageNumbersFromPrintPageNumberRange(page_ranges, page_range_count);
1571 for (size_t i = 0; i < page_numbers.size(); ++i) {
1572 uint32_t page_number = page_numbers[i];
1573 pages_[page_number]->GetPage();
1574 if (!IsPageVisible(page_numbers[i]))
1575 pages_[page_number]->Unload();
1578 FPDF_CopyViewerPreferences(output_doc, doc_);
1579 if (!FPDF_ImportPages(output_doc, doc_, page_number_str.c_str(), 0)) {
1580 FPDF_CloseDocument(output_doc);
1581 return pp::Buffer_Dev();
1584 FitContentsToPrintableAreaIfRequired(output_doc, print_settings);
1586 // Now flatten all the output pages.
1587 pp::Buffer_Dev buffer = GetFlattenedPrintData(output_doc);
1588 FPDF_CloseDocument(output_doc);
1589 return buffer;
1592 void PDFiumEngine::FitContentsToPrintableAreaIfRequired(
1593 const FPDF_DOCUMENT& doc, const PP_PrintSettings_Dev& print_settings) {
1594 // Check to see if we need to fit pdf contents to printer paper size.
1595 if (print_settings.print_scaling_option !=
1596 PP_PRINTSCALINGOPTION_SOURCE_SIZE) {
1597 int num_pages = FPDF_GetPageCount(doc);
1598 // In-place transformation is more efficient than creating a new
1599 // transformed document from the source document. Therefore, transform
1600 // every page to fit the contents in the selected printer paper.
1601 for (int i = 0; i < num_pages; ++i) {
1602 FPDF_PAGE page = FPDF_LoadPage(doc, i);
1603 TransformPDFPageForPrinting(page, print_settings);
1604 FPDF_ClosePage(page);
1609 void PDFiumEngine::SaveSelectedFormForPrint() {
1610 FORM_ForceToKillFocus(form_);
1611 client_->FormTextFieldFocusChange(false);
1614 void PDFiumEngine::PrintEnd() {
1615 FORM_DoDocumentAAction(form_, FPDFDOC_AACTION_DP);
1618 PDFiumPage::Area PDFiumEngine::GetCharIndex(const pp::MouseInputEvent& event,
1619 int* page_index,
1620 int* char_index,
1621 int* form_type,
1622 PDFiumPage::LinkTarget* target) {
1623 // First figure out which page this is in.
1624 pp::Point mouse_point = event.GetPosition();
1625 return GetCharIndex(mouse_point, page_index, char_index, form_type, target);
1628 PDFiumPage::Area PDFiumEngine::GetCharIndex(const pp::Point& point,
1629 int* page_index,
1630 int* char_index,
1631 int* form_type,
1632 PDFiumPage::LinkTarget* target) {
1633 int page = -1;
1634 pp::Point point_in_page(
1635 static_cast<int>((point.x() + position_.x()) / current_zoom_),
1636 static_cast<int>((point.y() + position_.y()) / current_zoom_));
1637 for (size_t i = 0; i < visible_pages_.size(); ++i) {
1638 if (pages_[visible_pages_[i]]->rect().Contains(point_in_page)) {
1639 page = visible_pages_[i];
1640 break;
1643 if (page == -1)
1644 return PDFiumPage::NONSELECTABLE_AREA;
1646 // If the page hasn't finished rendering, calling into the page sometimes
1647 // leads to hangs.
1648 for (size_t i = 0; i < progressive_paints_.size(); ++i) {
1649 if (progressive_paints_[i].page_index == page)
1650 return PDFiumPage::NONSELECTABLE_AREA;
1653 *page_index = page;
1654 return pages_[page]->GetCharIndex(
1655 point_in_page, current_rotation_, char_index, form_type, target);
1658 bool PDFiumEngine::OnMouseDown(const pp::MouseInputEvent& event) {
1659 if (event.GetButton() == PP_INPUTEVENT_MOUSEBUTTON_RIGHT) {
1660 if (!selection_.size())
1661 return false;
1662 std::vector<pp::Rect> selection_rect_vector;
1663 GetAllScreenRectsUnion(&selection_, GetVisibleRect().point(),
1664 &selection_rect_vector);
1665 pp::Point point = event.GetPosition();
1666 for (size_t i = 0; i < selection_rect_vector.size(); ++i) {
1667 if (selection_rect_vector[i].Contains(point.x(), point.y()))
1668 return false;
1670 SelectionChangeInvalidator selection_invalidator(this);
1671 selection_.clear();
1672 return true;
1674 if (event.GetButton() != PP_INPUTEVENT_MOUSEBUTTON_LEFT)
1675 return false;
1677 SelectionChangeInvalidator selection_invalidator(this);
1678 selection_.clear();
1680 int page_index = -1;
1681 int char_index = -1;
1682 int form_type = FPDF_FORMFIELD_UNKNOWN;
1683 PDFiumPage::LinkTarget target;
1684 PDFiumPage::Area area =
1685 GetCharIndex(event, &page_index, &char_index, &form_type, &target);
1686 mouse_down_state_.Set(area, target);
1688 // Decide whether to open link or not based on user action in mouse up and
1689 // mouse move events.
1690 if (area == PDFiumPage::WEBLINK_AREA)
1691 return true;
1693 if (area == PDFiumPage::DOCLINK_AREA) {
1694 client_->ScrollToPage(target.page);
1695 client_->FormTextFieldFocusChange(false);
1696 return true;
1699 if (page_index != -1) {
1700 last_page_mouse_down_ = page_index;
1701 double page_x, page_y;
1702 pp::Point point = event.GetPosition();
1703 DeviceToPage(page_index, point.x(), point.y(), &page_x, &page_y);
1705 FORM_OnLButtonDown(form_, pages_[page_index]->GetPage(), 0, page_x, page_y);
1706 if (form_type > FPDF_FORMFIELD_UNKNOWN) { // returns -1 sometimes...
1707 mouse_down_state_.Set(PDFiumPage::NONSELECTABLE_AREA, target);
1708 bool is_valid_control = (form_type == FPDF_FORMFIELD_TEXTFIELD ||
1709 form_type == FPDF_FORMFIELD_COMBOBOX);
1710 #ifdef PDF_USE_XFA
1711 is_valid_control |= (form_type == FPDF_FORMFIELD_XFA);
1712 #endif
1713 client_->FormTextFieldFocusChange(is_valid_control);
1714 return true; // Return now before we get into the selection code.
1718 client_->FormTextFieldFocusChange(false);
1720 if (area != PDFiumPage::TEXT_AREA)
1721 return true; // Return true so WebKit doesn't do its own highlighting.
1723 if (event.GetClickCount() == 1) {
1724 OnSingleClick(page_index, char_index);
1725 } else if (event.GetClickCount() == 2 ||
1726 event.GetClickCount() == 3) {
1727 OnMultipleClick(event.GetClickCount(), page_index, char_index);
1730 return true;
1733 void PDFiumEngine::OnSingleClick(int page_index, int char_index) {
1734 SetSelecting(true);
1735 selection_.push_back(PDFiumRange(pages_[page_index], char_index, 0));
1738 void PDFiumEngine::OnMultipleClick(int click_count,
1739 int page_index,
1740 int char_index) {
1741 // It would be more efficient if the SDK could support finding a space, but
1742 // now it doesn't.
1743 int start_index = char_index;
1744 do {
1745 base::char16 cur = pages_[page_index]->GetCharAtIndex(start_index);
1746 // For double click, we want to select one word so we look for whitespace
1747 // boundaries. For triple click, we want the whole line.
1748 if (cur == '\n' || (click_count == 2 && (cur == ' ' || cur == '\t')))
1749 break;
1750 } while (--start_index >= 0);
1751 if (start_index)
1752 start_index++;
1754 int end_index = char_index;
1755 int total = pages_[page_index]->GetCharCount();
1756 while (end_index++ <= total) {
1757 base::char16 cur = pages_[page_index]->GetCharAtIndex(end_index);
1758 if (cur == '\n' || (click_count == 2 && (cur == ' ' || cur == '\t')))
1759 break;
1762 selection_.push_back(PDFiumRange(
1763 pages_[page_index], start_index, end_index - start_index));
1766 bool PDFiumEngine::OnMouseUp(const pp::MouseInputEvent& event) {
1767 if (event.GetButton() != PP_INPUTEVENT_MOUSEBUTTON_LEFT)
1768 return false;
1770 int page_index = -1;
1771 int char_index = -1;
1772 int form_type = FPDF_FORMFIELD_UNKNOWN;
1773 PDFiumPage::LinkTarget target;
1774 PDFiumPage::Area area =
1775 GetCharIndex(event, &page_index, &char_index, &form_type, &target);
1777 // Open link on mouse up for same link for which mouse down happened earlier.
1778 if (mouse_down_state_.Matches(area, target)) {
1779 if (area == PDFiumPage::WEBLINK_AREA) {
1780 bool open_in_new_tab = !!(event.GetModifiers() & kDefaultKeyModifier);
1781 client_->NavigateTo(target.url, open_in_new_tab);
1782 client_->FormTextFieldFocusChange(false);
1783 return true;
1787 if (page_index != -1) {
1788 double page_x, page_y;
1789 pp::Point point = event.GetPosition();
1790 DeviceToPage(page_index, point.x(), point.y(), &page_x, &page_y);
1791 FORM_OnLButtonUp(
1792 form_, pages_[page_index]->GetPage(), 0, page_x, page_y);
1795 if (!selecting_)
1796 return false;
1798 SetSelecting(false);
1799 return true;
1802 bool PDFiumEngine::OnMouseMove(const pp::MouseInputEvent& event) {
1803 int page_index = -1;
1804 int char_index = -1;
1805 int form_type = FPDF_FORMFIELD_UNKNOWN;
1806 PDFiumPage::LinkTarget target;
1807 PDFiumPage::Area area =
1808 GetCharIndex(event, &page_index, &char_index, &form_type, &target);
1810 // Clear |mouse_down_state_| if mouse moves away from where the mouse down
1811 // happened.
1812 if (!mouse_down_state_.Matches(area, target))
1813 mouse_down_state_.Reset();
1815 if (!selecting_) {
1816 PP_CursorType_Dev cursor;
1817 switch (area) {
1818 case PDFiumPage::TEXT_AREA:
1819 cursor = PP_CURSORTYPE_IBEAM;
1820 break;
1821 case PDFiumPage::WEBLINK_AREA:
1822 case PDFiumPage::DOCLINK_AREA:
1823 cursor = PP_CURSORTYPE_HAND;
1824 break;
1825 case PDFiumPage::NONSELECTABLE_AREA:
1826 default:
1827 switch (form_type) {
1828 case FPDF_FORMFIELD_PUSHBUTTON:
1829 case FPDF_FORMFIELD_CHECKBOX:
1830 case FPDF_FORMFIELD_RADIOBUTTON:
1831 case FPDF_FORMFIELD_COMBOBOX:
1832 case FPDF_FORMFIELD_LISTBOX:
1833 cursor = PP_CURSORTYPE_HAND;
1834 break;
1835 case FPDF_FORMFIELD_TEXTFIELD:
1836 cursor = PP_CURSORTYPE_IBEAM;
1837 break;
1838 default:
1839 cursor = PP_CURSORTYPE_POINTER;
1840 break;
1842 break;
1845 if (page_index != -1) {
1846 double page_x, page_y;
1847 pp::Point point = event.GetPosition();
1848 DeviceToPage(page_index, point.x(), point.y(), &page_x, &page_y);
1849 FORM_OnMouseMove(form_, pages_[page_index]->GetPage(), 0, page_x, page_y);
1852 client_->UpdateCursor(cursor);
1853 pp::Point point = event.GetPosition();
1854 std::string url = GetLinkAtPosition(event.GetPosition());
1855 if (url != link_under_cursor_) {
1856 link_under_cursor_ = url;
1857 pp::PDF::SetLinkUnderCursor(GetPluginInstance(), url.c_str());
1859 // No need to swallow the event, since this might interfere with the
1860 // scrollbars if the user is dragging them.
1861 return false;
1864 // We're selecting but right now we're not over text, so don't change the
1865 // current selection.
1866 if (area != PDFiumPage::TEXT_AREA && area != PDFiumPage::WEBLINK_AREA &&
1867 area != PDFiumPage::DOCLINK_AREA) {
1868 return false;
1871 SelectionChangeInvalidator selection_invalidator(this);
1873 // Check if the user has descreased their selection area and we need to remove
1874 // pages from selection_.
1875 for (size_t i = 0; i < selection_.size(); ++i) {
1876 if (selection_[i].page_index() == page_index) {
1877 // There should be no other pages after this.
1878 selection_.erase(selection_.begin() + i + 1, selection_.end());
1879 break;
1883 if (selection_.size() == 0)
1884 return false;
1886 int last = selection_.size() - 1;
1887 if (selection_[last].page_index() == page_index) {
1888 // Selecting within a page.
1889 int count;
1890 if (char_index >= selection_[last].char_index()) {
1891 // Selecting forward.
1892 count = char_index - selection_[last].char_index() + 1;
1893 } else {
1894 count = char_index - selection_[last].char_index() - 1;
1896 selection_[last].SetCharCount(count);
1897 } else if (selection_[last].page_index() < page_index) {
1898 // Selecting into the next page.
1900 // First make sure that there are no gaps in selection, i.e. if mousedown on
1901 // page one but we only get mousemove over page three, we want page two.
1902 for (int i = selection_[last].page_index() + 1; i < page_index; ++i) {
1903 selection_.push_back(PDFiumRange(pages_[i], 0,
1904 pages_[i]->GetCharCount()));
1907 int count = pages_[selection_[last].page_index()]->GetCharCount();
1908 selection_[last].SetCharCount(count - selection_[last].char_index());
1909 selection_.push_back(PDFiumRange(pages_[page_index], 0, char_index));
1910 } else {
1911 // Selecting into the previous page.
1912 // The selection's char_index is 0-based, so the character count is one
1913 // more than the index. The character count needs to be negative to
1914 // indicate a backwards selection.
1915 selection_[last].SetCharCount(-(selection_[last].char_index() + 1));
1917 // First make sure that there are no gaps in selection, i.e. if mousedown on
1918 // page three but we only get mousemove over page one, we want page two.
1919 for (int i = selection_[last].page_index() - 1; i > page_index; --i) {
1920 selection_.push_back(PDFiumRange(pages_[i], 0,
1921 pages_[i]->GetCharCount()));
1924 int count = pages_[page_index]->GetCharCount();
1925 selection_.push_back(
1926 PDFiumRange(pages_[page_index], count, count - char_index));
1929 return true;
1932 bool PDFiumEngine::OnKeyDown(const pp::KeyboardInputEvent& event) {
1933 if (last_page_mouse_down_ == -1)
1934 return false;
1936 bool rv = !!FORM_OnKeyDown(
1937 form_, pages_[last_page_mouse_down_]->GetPage(),
1938 event.GetKeyCode(), event.GetModifiers());
1940 if (event.GetKeyCode() == ui::VKEY_BACK ||
1941 event.GetKeyCode() == ui::VKEY_ESCAPE) {
1942 // Chrome doesn't send char events for backspace or escape keys, see
1943 // PlatformKeyboardEventBuilder::isCharacterKey() and
1944 // http://chrome-corpsvn.mtv.corp.google.com/viewvc?view=rev&root=chrome&revision=31805
1945 // for more information. So just fake one since PDFium uses it.
1946 std::string str;
1947 str.push_back(event.GetKeyCode());
1948 pp::KeyboardInputEvent synthesized(pp::KeyboardInputEvent(
1949 client_->GetPluginInstance(),
1950 PP_INPUTEVENT_TYPE_CHAR,
1951 event.GetTimeStamp(),
1952 event.GetModifiers(),
1953 event.GetKeyCode(),
1954 str));
1955 OnChar(synthesized);
1958 return rv;
1961 bool PDFiumEngine::OnKeyUp(const pp::KeyboardInputEvent& event) {
1962 if (last_page_mouse_down_ == -1)
1963 return false;
1965 return !!FORM_OnKeyUp(
1966 form_, pages_[last_page_mouse_down_]->GetPage(),
1967 event.GetKeyCode(), event.GetModifiers());
1970 bool PDFiumEngine::OnChar(const pp::KeyboardInputEvent& event) {
1971 if (last_page_mouse_down_ == -1)
1972 return false;
1974 base::string16 str = base::UTF8ToUTF16(event.GetCharacterText().AsString());
1975 return !!FORM_OnChar(
1976 form_, pages_[last_page_mouse_down_]->GetPage(),
1977 str[0],
1978 event.GetModifiers());
1981 void PDFiumEngine::StartFind(const char* text, bool case_sensitive) {
1982 // We can get a call to StartFind before we have any page information (i.e.
1983 // before the first call to LoadDocument has happened). Handle this case.
1984 if (pages_.empty())
1985 return;
1987 bool first_search = false;
1988 int character_to_start_searching_from = 0;
1989 if (current_find_text_ != text) { // First time we search for this text.
1990 first_search = true;
1991 std::vector<PDFiumRange> old_selection = selection_;
1992 StopFind();
1993 current_find_text_ = text;
1995 if (old_selection.empty()) {
1996 // Start searching from the beginning of the document.
1997 next_page_to_search_ = 0;
1998 last_page_to_search_ = pages_.size() - 1;
1999 last_character_index_to_search_ = -1;
2000 } else {
2001 // There's a current selection, so start from it.
2002 next_page_to_search_ = old_selection[0].page_index();
2003 last_character_index_to_search_ = old_selection[0].char_index();
2004 character_to_start_searching_from = old_selection[0].char_index();
2005 last_page_to_search_ = next_page_to_search_;
2009 int current_page = next_page_to_search_;
2011 if (pages_[current_page]->available()) {
2012 base::string16 str = base::UTF8ToUTF16(text);
2013 // Don't use PDFium to search for now, since it doesn't support unicode
2014 // text. Leave the code for now to avoid bit-rot, in case it's fixed later.
2015 if (0) {
2016 SearchUsingPDFium(
2017 str, case_sensitive, first_search, character_to_start_searching_from,
2018 current_page);
2019 } else {
2020 SearchUsingICU(
2021 str, case_sensitive, first_search, character_to_start_searching_from,
2022 current_page);
2025 if (!IsPageVisible(current_page))
2026 pages_[current_page]->Unload();
2029 if (next_page_to_search_ != last_page_to_search_ ||
2030 (first_search && last_character_index_to_search_ != -1)) {
2031 ++next_page_to_search_;
2034 if (next_page_to_search_ == static_cast<int>(pages_.size()))
2035 next_page_to_search_ = 0;
2036 // If there's only one page in the document and we start searching midway,
2037 // then we'll want to search the page one more time.
2038 bool end_of_search =
2039 next_page_to_search_ == last_page_to_search_ &&
2040 // Only one page but didn't start midway.
2041 ((pages_.size() == 1 && last_character_index_to_search_ == -1) ||
2042 // Started midway, but only 1 page and we already looped around.
2043 (pages_.size() == 1 && !first_search) ||
2044 // Started midway, and we've just looped around.
2045 (pages_.size() > 1 && current_page == next_page_to_search_));
2047 if (end_of_search) {
2048 // Send the final notification.
2049 client_->NotifyNumberOfFindResultsChanged(find_results_.size(), true);
2051 // When searching is complete, resume finding at a particular index.
2052 // Assuming the user has not clicked the find button in the meanwhile.
2053 if (resume_find_index_.valid() && !current_find_index_.valid()) {
2054 size_t resume_index = resume_find_index_.GetIndex();
2055 if (resume_index >= find_results_.size()) {
2056 // This might happen if the PDF has some dynamically generated text?
2057 resume_index = 0;
2059 current_find_index_.SetIndex(resume_index);
2060 client_->NotifySelectedFindResultChanged(resume_index);
2062 resume_find_index_.Invalidate();
2063 } else {
2064 pp::CompletionCallback callback =
2065 find_factory_.NewCallback(&PDFiumEngine::ContinueFind);
2066 pp::Module::Get()->core()->CallOnMainThread(
2067 0, callback, case_sensitive ? 1 : 0);
2071 void PDFiumEngine::SearchUsingPDFium(const base::string16& term,
2072 bool case_sensitive,
2073 bool first_search,
2074 int character_to_start_searching_from,
2075 int current_page) {
2076 // Find all the matches in the current page.
2077 unsigned long flags = case_sensitive ? FPDF_MATCHCASE : 0;
2078 FPDF_SCHHANDLE find = FPDFText_FindStart(
2079 pages_[current_page]->GetTextPage(),
2080 reinterpret_cast<const unsigned short*>(term.c_str()),
2081 flags, character_to_start_searching_from);
2083 // Note: since we search one page at a time, we don't find matches across
2084 // page boundaries. We could do this manually ourself, but it seems low
2085 // priority since Reader itself doesn't do it.
2086 while (FPDFText_FindNext(find)) {
2087 PDFiumRange result(pages_[current_page],
2088 FPDFText_GetSchResultIndex(find),
2089 FPDFText_GetSchCount(find));
2091 if (!first_search &&
2092 last_character_index_to_search_ != -1 &&
2093 result.page_index() == last_page_to_search_ &&
2094 result.char_index() >= last_character_index_to_search_) {
2095 break;
2098 AddFindResult(result);
2101 FPDFText_FindClose(find);
2104 void PDFiumEngine::SearchUsingICU(const base::string16& term,
2105 bool case_sensitive,
2106 bool first_search,
2107 int character_to_start_searching_from,
2108 int current_page) {
2109 base::string16 page_text;
2110 int text_length = pages_[current_page]->GetCharCount();
2111 if (character_to_start_searching_from) {
2112 text_length -= character_to_start_searching_from;
2113 } else if (!first_search &&
2114 last_character_index_to_search_ != -1 &&
2115 current_page == last_page_to_search_) {
2116 text_length = last_character_index_to_search_;
2118 if (text_length <= 0)
2119 return;
2121 PDFiumAPIStringBufferAdapter<base::string16> api_string_adapter(&page_text,
2122 text_length,
2123 false);
2124 unsigned short* data =
2125 reinterpret_cast<unsigned short*>(api_string_adapter.GetData());
2126 int written = FPDFText_GetText(pages_[current_page]->GetTextPage(),
2127 character_to_start_searching_from,
2128 text_length,
2129 data);
2130 api_string_adapter.Close(written);
2132 std::vector<PDFEngine::Client::SearchStringResult> results;
2133 client_->SearchString(
2134 page_text.c_str(), term.c_str(), case_sensitive, &results);
2135 for (size_t i = 0; i < results.size(); ++i) {
2136 // Need to map the indexes from the page text, which may have generated
2137 // characters like space etc, to character indices from the page.
2138 int temp_start = results[i].start_index + character_to_start_searching_from;
2139 int start = FPDFText_GetCharIndexFromTextIndex(
2140 pages_[current_page]->GetTextPage(), temp_start);
2141 int end = FPDFText_GetCharIndexFromTextIndex(
2142 pages_[current_page]->GetTextPage(),
2143 temp_start + results[i].length);
2144 AddFindResult(PDFiumRange(pages_[current_page], start, end - start));
2148 void PDFiumEngine::AddFindResult(const PDFiumRange& result) {
2149 // Figure out where to insert the new location, since we could have
2150 // started searching midway and now we wrapped.
2151 size_t result_index;
2152 int page_index = result.page_index();
2153 int char_index = result.char_index();
2154 for (result_index = 0; result_index < find_results_.size(); ++result_index) {
2155 if (find_results_[result_index].page_index() > page_index ||
2156 (find_results_[result_index].page_index() == page_index &&
2157 find_results_[result_index].char_index() > char_index)) {
2158 break;
2161 find_results_.insert(find_results_.begin() + result_index, result);
2162 UpdateTickMarks();
2164 if (current_find_index_.valid()) {
2165 if (result_index <= current_find_index_.GetIndex()) {
2166 // Update the current match index
2167 size_t find_index = current_find_index_.IncrementIndex();
2168 DCHECK_LT(find_index, find_results_.size());
2169 client_->NotifySelectedFindResultChanged(current_find_index_.GetIndex());
2171 } else if (!resume_find_index_.valid()) {
2172 // Both indices are invalid. Select the first match.
2173 SelectFindResult(true);
2175 client_->NotifyNumberOfFindResultsChanged(find_results_.size(), false);
2178 bool PDFiumEngine::SelectFindResult(bool forward) {
2179 if (find_results_.empty()) {
2180 NOTREACHED();
2181 return false;
2184 SelectionChangeInvalidator selection_invalidator(this);
2186 // Move back/forward through the search locations we previously found.
2187 size_t new_index;
2188 const size_t last_index = find_results_.size() - 1;
2189 if (current_find_index_.valid()) {
2190 size_t current_index = current_find_index_.GetIndex();
2191 if (forward) {
2192 new_index = (current_index >= last_index) ? 0 : current_index + 1;
2193 } else {
2194 new_index = (current_find_index_.GetIndex() == 0) ?
2195 last_index : current_index - 1;
2197 } else {
2198 new_index = forward ? 0 : last_index;
2200 current_find_index_.SetIndex(new_index);
2202 // Update the selection before telling the client to scroll, since it could
2203 // paint then.
2204 selection_.clear();
2205 selection_.push_back(find_results_[current_find_index_.GetIndex()]);
2207 // If the result is not in view, scroll to it.
2208 pp::Rect bounding_rect;
2209 pp::Rect visible_rect = GetVisibleRect();
2210 // Use zoom of 1.0 since visible_rect is without zoom.
2211 std::vector<pp::Rect> rects;
2212 rects = find_results_[current_find_index_.GetIndex()].GetScreenRects(
2213 pp::Point(), 1.0, current_rotation_);
2214 for (size_t i = 0; i < rects.size(); ++i)
2215 bounding_rect = bounding_rect.Union(rects[i]);
2216 if (!visible_rect.Contains(bounding_rect)) {
2217 pp::Point center = bounding_rect.CenterPoint();
2218 // Make the page centered.
2219 int new_y = static_cast<int>(center.y() * current_zoom_) -
2220 static_cast<int>(visible_rect.height() * current_zoom_ / 2);
2221 if (new_y < 0)
2222 new_y = 0;
2223 client_->ScrollToY(new_y);
2225 // Only move horizontally if it's not visible.
2226 if (center.x() < visible_rect.x() || center.x() > visible_rect.right()) {
2227 int new_x = static_cast<int>(center.x() * current_zoom_) -
2228 static_cast<int>(visible_rect.width() * current_zoom_ / 2);
2229 if (new_x < 0)
2230 new_x = 0;
2231 client_->ScrollToX(new_x);
2235 client_->NotifySelectedFindResultChanged(current_find_index_.GetIndex());
2236 return true;
2239 void PDFiumEngine::StopFind() {
2240 SelectionChangeInvalidator selection_invalidator(this);
2242 selection_.clear();
2243 selecting_ = false;
2244 find_results_.clear();
2245 next_page_to_search_ = -1;
2246 last_page_to_search_ = -1;
2247 last_character_index_to_search_ = -1;
2248 current_find_index_.Invalidate();
2249 current_find_text_.clear();
2250 UpdateTickMarks();
2251 find_factory_.CancelAll();
2254 void PDFiumEngine::GetAllScreenRectsUnion(std::vector<PDFiumRange>* rect_range,
2255 const pp::Point& offset_point,
2256 std::vector<pp::Rect>* rect_vector) {
2257 for (std::vector<PDFiumRange>::iterator it = rect_range->begin();
2258 it != rect_range->end(); ++it) {
2259 pp::Rect rect;
2260 std::vector<pp::Rect> rects =
2261 it->GetScreenRects(offset_point, current_zoom_, current_rotation_);
2262 for (size_t j = 0; j < rects.size(); ++j)
2263 rect = rect.Union(rects[j]);
2264 rect_vector->push_back(rect);
2268 void PDFiumEngine::UpdateTickMarks() {
2269 std::vector<pp::Rect> tickmarks;
2270 GetAllScreenRectsUnion(&find_results_, pp::Point(0, 0), &tickmarks);
2271 client_->UpdateTickMarks(tickmarks);
2274 void PDFiumEngine::ZoomUpdated(double new_zoom_level) {
2275 CancelPaints();
2277 current_zoom_ = new_zoom_level;
2279 CalculateVisiblePages();
2280 UpdateTickMarks();
2283 void PDFiumEngine::RotateClockwise() {
2284 current_rotation_ = (current_rotation_ + 1) % 4;
2285 RotateInternal();
2288 void PDFiumEngine::RotateCounterclockwise() {
2289 current_rotation_ = (current_rotation_ - 1) % 4;
2290 RotateInternal();
2293 void PDFiumEngine::InvalidateAllPages() {
2294 CancelPaints();
2295 StopFind();
2296 LoadPageInfo(true);
2297 client_->Invalidate(pp::Rect(plugin_size_));
2300 std::string PDFiumEngine::GetSelectedText() {
2301 if (!HasPermission(PDFEngine::PERMISSION_COPY))
2302 return std::string();
2304 base::string16 result;
2305 base::string16 new_line_char = base::UTF8ToUTF16("\n");
2306 for (size_t i = 0; i < selection_.size(); ++i) {
2307 if (i > 0 &&
2308 selection_[i - 1].page_index() > selection_[i].page_index()) {
2309 result = selection_[i].GetText() + new_line_char + result;
2310 } else {
2311 if (i > 0)
2312 result.append(new_line_char);
2313 result.append(selection_[i].GetText());
2317 FormatStringWithHyphens(&result);
2318 FormatStringForOS(&result);
2319 return base::UTF16ToUTF8(result);
2322 std::string PDFiumEngine::GetLinkAtPosition(const pp::Point& point) {
2323 std::string url;
2324 int temp;
2325 int page_index = -1;
2326 int form_type = FPDF_FORMFIELD_UNKNOWN;
2327 PDFiumPage::LinkTarget target;
2328 PDFiumPage::Area area =
2329 GetCharIndex(point, &page_index, &temp, &form_type, &target);
2330 if (area == PDFiumPage::WEBLINK_AREA)
2331 url = target.url;
2332 return url;
2335 bool PDFiumEngine::IsSelecting() {
2336 return selecting_;
2339 bool PDFiumEngine::HasPermission(DocumentPermission permission) const {
2340 // PDF 1.7 spec, section 3.5.2 says: "If the revision number is 2 or greater,
2341 // the operations to which user access can be controlled are as follows: ..."
2343 // Thus for revision numbers less than 2, permissions are ignored and this
2344 // always returns true.
2345 if (permissions_handler_revision_ < 2)
2346 return true;
2348 // Handle high quality printing permission separately for security handler
2349 // revision 3+. See table 3.20 in the PDF 1.7 spec.
2350 if (permission == PERMISSION_PRINT_HIGH_QUALITY &&
2351 permissions_handler_revision_ >= 3) {
2352 return (permissions_ & kPDFPermissionPrintLowQualityMask) != 0 &&
2353 (permissions_ & kPDFPermissionPrintHighQualityMask) != 0;
2356 switch (permission) {
2357 case PERMISSION_COPY:
2358 return (permissions_ & kPDFPermissionCopyMask) != 0;
2359 case PERMISSION_COPY_ACCESSIBLE:
2360 return (permissions_ & kPDFPermissionCopyAccessibleMask) != 0;
2361 case PERMISSION_PRINT_LOW_QUALITY:
2362 case PERMISSION_PRINT_HIGH_QUALITY:
2363 // With security handler revision 2 rules, check the same bit for high
2364 // and low quality. See table 3.20 in the PDF 1.7 spec.
2365 return (permissions_ & kPDFPermissionPrintLowQualityMask) != 0;
2366 default:
2367 return true;
2371 void PDFiumEngine::SelectAll() {
2372 SelectionChangeInvalidator selection_invalidator(this);
2374 selection_.clear();
2375 for (size_t i = 0; i < pages_.size(); ++i)
2376 if (pages_[i]->available()) {
2377 selection_.push_back(PDFiumRange(pages_[i], 0,
2378 pages_[i]->GetCharCount()));
2382 int PDFiumEngine::GetNumberOfPages() {
2383 return pages_.size();
2386 pp::VarArray PDFiumEngine::GetBookmarks() {
2387 pp::VarDictionary dict = TraverseBookmarks(doc_, NULL);
2388 // The root bookmark contains no useful information.
2389 return pp::VarArray(dict.Get(pp::Var("children")));
2392 int PDFiumEngine::GetNamedDestinationPage(const std::string& destination) {
2393 // Look for the destination.
2394 FPDF_DEST dest = FPDF_GetNamedDestByName(doc_, destination.c_str());
2395 if (!dest) {
2396 // Look for a bookmark with the same name.
2397 base::string16 destination_wide = base::UTF8ToUTF16(destination);
2398 FPDF_WIDESTRING destination_pdf_wide =
2399 reinterpret_cast<FPDF_WIDESTRING>(destination_wide.c_str());
2400 FPDF_BOOKMARK bookmark = FPDFBookmark_Find(doc_, destination_pdf_wide);
2401 if (!bookmark)
2402 return -1;
2403 dest = FPDFBookmark_GetDest(doc_, bookmark);
2405 return dest ? FPDFDest_GetPageIndex(doc_, dest) : -1;
2408 int PDFiumEngine::GetFirstVisiblePage() {
2409 CalculateVisiblePages();
2410 return first_visible_page_;
2413 int PDFiumEngine::GetMostVisiblePage() {
2414 CalculateVisiblePages();
2415 return most_visible_page_;
2418 pp::Rect PDFiumEngine::GetPageRect(int index) {
2419 pp::Rect rc(pages_[index]->rect());
2420 rc.Inset(-kPageShadowLeft, -kPageShadowTop,
2421 -kPageShadowRight, -kPageShadowBottom);
2422 return rc;
2425 pp::Rect PDFiumEngine::GetPageContentsRect(int index) {
2426 return GetScreenRect(pages_[index]->rect());
2429 void PDFiumEngine::PaintThumbnail(pp::ImageData* image_data, int index) {
2430 FPDF_BITMAP bitmap = FPDFBitmap_CreateEx(
2431 image_data->size().width(), image_data->size().height(),
2432 FPDFBitmap_BGRx, image_data->data(), image_data->stride());
2434 if (pages_[index]->available()) {
2435 FPDFBitmap_FillRect(bitmap, 0, 0, image_data->size().width(),
2436 image_data->size().height(), 0xFFFFFFFF);
2438 FPDF_RenderPageBitmap(
2439 bitmap, pages_[index]->GetPage(), 0, 0, image_data->size().width(),
2440 image_data->size().height(), 0, GetRenderingFlags());
2441 } else {
2442 FPDFBitmap_FillRect(bitmap, 0, 0, image_data->size().width(),
2443 image_data->size().height(), kPendingPageColor);
2446 FPDFBitmap_Destroy(bitmap);
2449 void PDFiumEngine::SetGrayscale(bool grayscale) {
2450 render_grayscale_ = grayscale;
2453 void PDFiumEngine::OnCallback(int id) {
2454 if (!timers_.count(id))
2455 return;
2457 timers_[id].second(id);
2458 if (timers_.count(id)) // The callback might delete the timer.
2459 client_->ScheduleCallback(id, timers_[id].first);
2462 std::string PDFiumEngine::GetPageAsJSON(int index) {
2463 if (!(HasPermission(PERMISSION_COPY) ||
2464 HasPermission(PERMISSION_COPY_ACCESSIBLE))) {
2465 return "{}";
2468 if (index < 0 || static_cast<size_t>(index) > pages_.size() - 1)
2469 return "{}";
2471 scoped_ptr<base::Value> node(
2472 pages_[index]->GetAccessibleContentAsValue(current_rotation_));
2473 std::string page_json;
2474 base::JSONWriter::Write(*node, &page_json);
2475 return page_json;
2478 bool PDFiumEngine::GetPrintScaling() {
2479 return !!FPDF_VIEWERREF_GetPrintScaling(doc_);
2482 int PDFiumEngine::GetCopiesToPrint() {
2483 return FPDF_VIEWERREF_GetNumCopies(doc_);
2486 int PDFiumEngine::GetDuplexType() {
2487 return static_cast<int>(FPDF_VIEWERREF_GetDuplex(doc_));
2490 bool PDFiumEngine::GetPageSizeAndUniformity(pp::Size* size) {
2491 if (pages_.empty())
2492 return false;
2494 pp::Size page_size = GetPageSize(0);
2495 for (size_t i = 1; i < pages_.size(); ++i) {
2496 if (page_size != GetPageSize(i))
2497 return false;
2500 // Convert |page_size| back to points.
2501 size->set_width(
2502 ConvertUnit(page_size.width(), kPixelsPerInch, kPointsPerInch));
2503 size->set_height(
2504 ConvertUnit(page_size.height(), kPixelsPerInch, kPointsPerInch));
2505 return true;
2508 void PDFiumEngine::AppendBlankPages(int num_pages) {
2509 DCHECK_NE(num_pages, 0);
2511 if (!doc_)
2512 return;
2514 selection_.clear();
2515 pending_pages_.clear();
2517 // Delete all pages except the first one.
2518 while (pages_.size() > 1) {
2519 delete pages_.back();
2520 pages_.pop_back();
2521 FPDFPage_Delete(doc_, pages_.size());
2524 // Calculate document size and all page sizes.
2525 std::vector<pp::Rect> page_rects;
2526 pp::Size page_size = GetPageSize(0);
2527 page_size.Enlarge(kPageShadowLeft + kPageShadowRight,
2528 kPageShadowTop + kPageShadowBottom);
2529 pp::Size old_document_size = document_size_;
2530 document_size_ = pp::Size(page_size.width(), 0);
2531 for (int i = 0; i < num_pages; ++i) {
2532 if (i != 0) {
2533 // Add space for horizontal separator.
2534 document_size_.Enlarge(0, kPageSeparatorThickness);
2537 pp::Rect rect(pp::Point(0, document_size_.height()), page_size);
2538 page_rects.push_back(rect);
2540 document_size_.Enlarge(0, page_size.height());
2543 // Create blank pages.
2544 for (int i = 1; i < num_pages; ++i) {
2545 pp::Rect page_rect(page_rects[i]);
2546 page_rect.Inset(kPageShadowLeft, kPageShadowTop,
2547 kPageShadowRight, kPageShadowBottom);
2548 double width_in_points = ConvertUnitDouble(page_rect.width(),
2549 kPixelsPerInch,
2550 kPointsPerInch);
2551 double height_in_points = ConvertUnitDouble(page_rect.height(),
2552 kPixelsPerInch,
2553 kPointsPerInch);
2554 FPDFPage_New(doc_, i, width_in_points, height_in_points);
2555 pages_.push_back(new PDFiumPage(this, i, page_rect, true));
2558 CalculateVisiblePages();
2559 if (document_size_ != old_document_size)
2560 client_->DocumentSizeUpdated(document_size_);
2563 void PDFiumEngine::LoadDocument() {
2564 // Check if the document is ready for loading. If it isn't just bail for now,
2565 // we will call LoadDocument() again later.
2566 if (!doc_ && !doc_loader_.IsDocumentComplete() &&
2567 !FPDFAvail_IsDocAvail(fpdf_availability_, &download_hints_)) {
2568 return;
2571 // If we're in the middle of getting a password, just return. We will retry
2572 // loading the document after we get the password anyway.
2573 if (getting_password_)
2574 return;
2576 ScopedUnsupportedFeature scoped_unsupported_feature(this);
2577 bool needs_password = false;
2578 if (TryLoadingDoc(false, std::string(), &needs_password)) {
2579 ContinueLoadingDocument(false, std::string());
2580 return;
2582 if (needs_password)
2583 GetPasswordAndLoad();
2584 else
2585 client_->DocumentLoadFailed();
2588 bool PDFiumEngine::TryLoadingDoc(bool with_password,
2589 const std::string& password,
2590 bool* needs_password) {
2591 *needs_password = false;
2592 if (doc_)
2593 return true;
2595 const char* password_cstr = NULL;
2596 if (with_password) {
2597 password_cstr = password.c_str();
2598 password_tries_remaining_--;
2600 if (doc_loader_.IsDocumentComplete())
2601 doc_ = FPDF_LoadCustomDocument(&file_access_, password_cstr);
2602 else
2603 doc_ = FPDFAvail_GetDocument(fpdf_availability_, password_cstr);
2605 if (!doc_ && FPDF_GetLastError() == FPDF_ERR_PASSWORD)
2606 *needs_password = true;
2608 return doc_ != NULL;
2611 void PDFiumEngine::GetPasswordAndLoad() {
2612 getting_password_ = true;
2613 DCHECK(!doc_ && FPDF_GetLastError() == FPDF_ERR_PASSWORD);
2614 client_->GetDocumentPassword(password_factory_.NewCallbackWithOutput(
2615 &PDFiumEngine::OnGetPasswordComplete));
2618 void PDFiumEngine::OnGetPasswordComplete(int32_t result,
2619 const pp::Var& password) {
2620 getting_password_ = false;
2622 bool password_given = false;
2623 std::string password_text;
2624 if (result == PP_OK && password.is_string()) {
2625 password_text = password.AsString();
2626 if (!password_text.empty())
2627 password_given = true;
2629 ContinueLoadingDocument(password_given, password_text);
2632 void PDFiumEngine::ContinueLoadingDocument(
2633 bool has_password,
2634 const std::string& password) {
2635 ScopedUnsupportedFeature scoped_unsupported_feature(this);
2637 bool needs_password = false;
2638 bool loaded = TryLoadingDoc(has_password, password, &needs_password);
2639 bool password_incorrect = !loaded && has_password && needs_password;
2640 if (password_incorrect && password_tries_remaining_ > 0) {
2641 GetPasswordAndLoad();
2642 return;
2645 if (!doc_) {
2646 client_->DocumentLoadFailed();
2647 return;
2650 if (FPDFDoc_GetPageMode(doc_) == PAGEMODE_USEOUTLINES)
2651 client_->DocumentHasUnsupportedFeature("Bookmarks");
2653 permissions_ = FPDF_GetDocPermissions(doc_);
2654 permissions_handler_revision_ = FPDF_GetSecurityHandlerRevision(doc_);
2656 if (!form_) {
2657 // Only returns 0 when data isn't available. If form data is downloaded, or
2658 // if this isn't a form, returns positive values.
2659 if (!doc_loader_.IsDocumentComplete() &&
2660 !FPDFAvail_IsFormAvail(fpdf_availability_, &download_hints_)) {
2661 return;
2664 form_ = FPDFDOC_InitFormFillEnvironment(
2665 doc_, static_cast<FPDF_FORMFILLINFO*>(this));
2666 #ifdef PDF_USE_XFA
2667 FPDF_LoadXFA(doc_);
2668 #endif
2670 FPDF_SetFormFieldHighlightColor(form_, 0, kFormHighlightColor);
2671 FPDF_SetFormFieldHighlightAlpha(form_, kFormHighlightAlpha);
2674 if (!doc_loader_.IsDocumentComplete()) {
2675 // Check if the first page is available. In a linearized PDF, that is not
2676 // always page 0. Doing this gives us the default page size, since when the
2677 // document is available, the first page is available as well.
2678 CheckPageAvailable(FPDFAvail_GetFirstPageNum(doc_), &pending_pages_);
2681 LoadPageInfo(false);
2683 if (doc_loader_.IsDocumentComplete())
2684 FinishLoadingDocument();
2687 void PDFiumEngine::LoadPageInfo(bool reload) {
2688 pending_pages_.clear();
2689 pp::Size old_document_size = document_size_;
2690 document_size_ = pp::Size();
2691 std::vector<pp::Rect> page_rects;
2692 int page_count = FPDF_GetPageCount(doc_);
2693 bool doc_complete = doc_loader_.IsDocumentComplete();
2694 for (int i = 0; i < page_count; ++i) {
2695 if (i != 0) {
2696 // Add space for horizontal separator.
2697 document_size_.Enlarge(0, kPageSeparatorThickness);
2700 // Get page availability. If reload==false, and document is not loaded yet
2701 // (we are using async loading) - mark all pages as unavailable.
2702 // If reload==true (we have document constructed already), get page
2703 // availability flag from already existing PDFiumPage class.
2704 bool page_available = reload ? pages_[i]->available() : doc_complete;
2706 pp::Size size = page_available ? GetPageSize(i) : default_page_size_;
2707 size.Enlarge(kPageShadowLeft + kPageShadowRight,
2708 kPageShadowTop + kPageShadowBottom);
2709 pp::Rect rect(pp::Point(0, document_size_.height()), size);
2710 page_rects.push_back(rect);
2712 if (size.width() > document_size_.width())
2713 document_size_.set_width(size.width());
2715 document_size_.Enlarge(0, size.height());
2718 for (int i = 0; i < page_count; ++i) {
2719 // Center pages relative to the entire document.
2720 page_rects[i].set_x((document_size_.width() - page_rects[i].width()) / 2);
2721 pp::Rect page_rect(page_rects[i]);
2722 page_rect.Inset(kPageShadowLeft, kPageShadowTop,
2723 kPageShadowRight, kPageShadowBottom);
2724 if (reload) {
2725 pages_[i]->set_rect(page_rect);
2726 } else {
2727 pages_.push_back(new PDFiumPage(this, i, page_rect, doc_complete));
2731 CalculateVisiblePages();
2732 if (document_size_ != old_document_size)
2733 client_->DocumentSizeUpdated(document_size_);
2736 void PDFiumEngine::CalculateVisiblePages() {
2737 // Clear pending requests queue, since it may contain requests to the pages
2738 // that are already invisible (after scrolling for example).
2739 pending_pages_.clear();
2740 doc_loader_.ClearPendingRequests();
2742 visible_pages_.clear();
2743 pp::Rect visible_rect(plugin_size_);
2744 for (size_t i = 0; i < pages_.size(); ++i) {
2745 // Check an entire PageScreenRect, since we might need to repaint side
2746 // borders and shadows even if the page itself is not visible.
2747 // For example, when user use pdf with different page sizes and zoomed in
2748 // outside page area.
2749 if (visible_rect.Intersects(GetPageScreenRect(i))) {
2750 visible_pages_.push_back(i);
2751 CheckPageAvailable(i, &pending_pages_);
2752 } else {
2753 // Need to unload pages when we're not using them, since some PDFs use a
2754 // lot of memory. See http://crbug.com/48791
2755 if (defer_page_unload_) {
2756 deferred_page_unloads_.push_back(i);
2757 } else {
2758 pages_[i]->Unload();
2761 // If the last mouse down was on a page that's no longer visible, reset
2762 // that variable so that we don't send keyboard events to it (the focus
2763 // will be lost when the page is first closed anyways).
2764 if (static_cast<int>(i) == last_page_mouse_down_)
2765 last_page_mouse_down_ = -1;
2769 // Any pending highlighting of form fields will be invalid since these are in
2770 // screen coordinates.
2771 form_highlights_.clear();
2773 if (visible_pages_.size() == 0)
2774 first_visible_page_ = -1;
2775 else
2776 first_visible_page_ = visible_pages_.front();
2778 int most_visible_page = first_visible_page_;
2779 // Check if the next page is more visible than the first one.
2780 if (most_visible_page != -1 &&
2781 pages_.size() > 0 &&
2782 most_visible_page < static_cast<int>(pages_.size()) - 1) {
2783 pp::Rect rc_first =
2784 visible_rect.Intersect(GetPageScreenRect(most_visible_page));
2785 pp::Rect rc_next =
2786 visible_rect.Intersect(GetPageScreenRect(most_visible_page + 1));
2787 if (rc_next.height() > rc_first.height())
2788 most_visible_page++;
2791 SetCurrentPage(most_visible_page);
2794 bool PDFiumEngine::IsPageVisible(int index) const {
2795 for (size_t i = 0; i < visible_pages_.size(); ++i) {
2796 if (visible_pages_[i] == index)
2797 return true;
2800 return false;
2803 bool PDFiumEngine::CheckPageAvailable(int index, std::vector<int>* pending) {
2804 if (!doc_ || !form_)
2805 return false;
2807 if (static_cast<int>(pages_.size()) > index && pages_[index]->available())
2808 return true;
2810 if (!FPDFAvail_IsPageAvail(fpdf_availability_, index, &download_hints_)) {
2811 size_t j;
2812 for (j = 0; j < pending->size(); ++j) {
2813 if ((*pending)[j] == index)
2814 break;
2817 if (j == pending->size())
2818 pending->push_back(index);
2819 return false;
2822 if (static_cast<int>(pages_.size()) > index)
2823 pages_[index]->set_available(true);
2824 if (!default_page_size_.GetArea())
2825 default_page_size_ = GetPageSize(index);
2826 return true;
2829 pp::Size PDFiumEngine::GetPageSize(int index) {
2830 pp::Size size;
2831 double width_in_points = 0;
2832 double height_in_points = 0;
2833 int rv = FPDF_GetPageSizeByIndex(
2834 doc_, index, &width_in_points, &height_in_points);
2836 if (rv) {
2837 int width_in_pixels = static_cast<int>(
2838 ConvertUnitDouble(width_in_points, kPointsPerInch, kPixelsPerInch));
2839 int height_in_pixels = static_cast<int>(
2840 ConvertUnitDouble(height_in_points, kPointsPerInch, kPixelsPerInch));
2841 if (current_rotation_ % 2 == 1)
2842 std::swap(width_in_pixels, height_in_pixels);
2843 size = pp::Size(width_in_pixels, height_in_pixels);
2845 return size;
2848 int PDFiumEngine::StartPaint(int page_index, const pp::Rect& dirty) {
2849 // For the first time we hit paint, do nothing and just record the paint for
2850 // the next callback. This keeps the UI responsive in case the user is doing
2851 // a lot of scrolling.
2852 ProgressivePaint progressive;
2853 progressive.rect = dirty;
2854 progressive.page_index = page_index;
2855 progressive.bitmap = NULL;
2856 progressive.painted_ = false;
2857 progressive_paints_.push_back(progressive);
2858 return progressive_paints_.size() - 1;
2861 bool PDFiumEngine::ContinuePaint(int progressive_index,
2862 pp::ImageData* image_data) {
2863 DCHECK_GE(progressive_index, 0);
2864 DCHECK_LT(static_cast<size_t>(progressive_index), progressive_paints_.size());
2865 DCHECK(image_data);
2867 #if defined(OS_LINUX)
2868 g_last_instance_id = client_->GetPluginInstance()->pp_instance();
2869 #endif
2871 int rv;
2872 FPDF_BITMAP bitmap = progressive_paints_[progressive_index].bitmap;
2873 int page_index = progressive_paints_[progressive_index].page_index;
2874 DCHECK_GE(page_index, 0);
2875 DCHECK_LT(static_cast<size_t>(page_index), pages_.size());
2876 FPDF_PAGE page = pages_[page_index]->GetPage();
2878 last_progressive_start_time_ = base::Time::Now();
2879 if (bitmap) {
2880 rv = FPDF_RenderPage_Continue(page, static_cast<IFSDK_PAUSE*>(this));
2881 } else {
2882 pp::Rect dirty = progressive_paints_[progressive_index].rect;
2883 bitmap = CreateBitmap(dirty, image_data);
2884 int start_x, start_y, size_x, size_y;
2885 GetPDFiumRect(page_index, dirty, &start_x, &start_y, &size_x, &size_y);
2886 FPDFBitmap_FillRect(bitmap, start_x, start_y, size_x, size_y, 0xFFFFFFFF);
2887 rv = FPDF_RenderPageBitmap_Start(
2888 bitmap, page, start_x, start_y, size_x, size_y,
2889 current_rotation_,
2890 GetRenderingFlags(), static_cast<IFSDK_PAUSE*>(this));
2891 progressive_paints_[progressive_index].bitmap = bitmap;
2893 return rv != FPDF_RENDER_TOBECOUNTINUED;
2896 void PDFiumEngine::FinishPaint(int progressive_index,
2897 pp::ImageData* image_data) {
2898 DCHECK_GE(progressive_index, 0);
2899 DCHECK_LT(static_cast<size_t>(progressive_index), progressive_paints_.size());
2900 DCHECK(image_data);
2902 int page_index = progressive_paints_[progressive_index].page_index;
2903 pp::Rect dirty_in_screen = progressive_paints_[progressive_index].rect;
2904 FPDF_BITMAP bitmap = progressive_paints_[progressive_index].bitmap;
2905 int start_x, start_y, size_x, size_y;
2906 GetPDFiumRect(
2907 page_index, dirty_in_screen, &start_x, &start_y, &size_x, &size_y);
2909 // Draw the forms.
2910 FPDF_FFLDraw(
2911 form_, bitmap, pages_[page_index]->GetPage(), start_x, start_y, size_x,
2912 size_y, current_rotation_, GetRenderingFlags());
2914 FillPageSides(progressive_index);
2916 // Paint the page shadows.
2917 PaintPageShadow(progressive_index, image_data);
2919 DrawSelections(progressive_index, image_data);
2921 FPDF_RenderPage_Close(pages_[page_index]->GetPage());
2922 FPDFBitmap_Destroy(bitmap);
2923 progressive_paints_.erase(progressive_paints_.begin() + progressive_index);
2925 client_->DocumentPaintOccurred();
2928 void PDFiumEngine::CancelPaints() {
2929 for (size_t i = 0; i < progressive_paints_.size(); ++i) {
2930 FPDF_RenderPage_Close(pages_[progressive_paints_[i].page_index]->GetPage());
2931 FPDFBitmap_Destroy(progressive_paints_[i].bitmap);
2933 progressive_paints_.clear();
2936 void PDFiumEngine::FillPageSides(int progressive_index) {
2937 DCHECK_GE(progressive_index, 0);
2938 DCHECK_LT(static_cast<size_t>(progressive_index), progressive_paints_.size());
2940 int page_index = progressive_paints_[progressive_index].page_index;
2941 pp::Rect dirty_in_screen = progressive_paints_[progressive_index].rect;
2942 FPDF_BITMAP bitmap = progressive_paints_[progressive_index].bitmap;
2944 pp::Rect page_rect = pages_[page_index]->rect();
2945 if (page_rect.x() > 0) {
2946 pp::Rect left(0,
2947 page_rect.y() - kPageShadowTop,
2948 page_rect.x() - kPageShadowLeft,
2949 page_rect.height() + kPageShadowTop +
2950 kPageShadowBottom + kPageSeparatorThickness);
2951 left = GetScreenRect(left).Intersect(dirty_in_screen);
2953 FPDFBitmap_FillRect(bitmap, left.x() - dirty_in_screen.x(),
2954 left.y() - dirty_in_screen.y(), left.width(),
2955 left.height(), client_->GetBackgroundColor());
2958 if (page_rect.right() < document_size_.width()) {
2959 pp::Rect right(page_rect.right() + kPageShadowRight,
2960 page_rect.y() - kPageShadowTop,
2961 document_size_.width() - page_rect.right() -
2962 kPageShadowRight,
2963 page_rect.height() + kPageShadowTop +
2964 kPageShadowBottom + kPageSeparatorThickness);
2965 right = GetScreenRect(right).Intersect(dirty_in_screen);
2967 FPDFBitmap_FillRect(bitmap, right.x() - dirty_in_screen.x(),
2968 right.y() - dirty_in_screen.y(), right.width(),
2969 right.height(), client_->GetBackgroundColor());
2972 // Paint separator.
2973 pp::Rect bottom(page_rect.x() - kPageShadowLeft,
2974 page_rect.bottom() + kPageShadowBottom,
2975 page_rect.width() + kPageShadowLeft + kPageShadowRight,
2976 kPageSeparatorThickness);
2977 bottom = GetScreenRect(bottom).Intersect(dirty_in_screen);
2979 FPDFBitmap_FillRect(bitmap, bottom.x() - dirty_in_screen.x(),
2980 bottom.y() - dirty_in_screen.y(), bottom.width(),
2981 bottom.height(), client_->GetBackgroundColor());
2984 void PDFiumEngine::PaintPageShadow(int progressive_index,
2985 pp::ImageData* image_data) {
2986 DCHECK_GE(progressive_index, 0);
2987 DCHECK_LT(static_cast<size_t>(progressive_index), progressive_paints_.size());
2988 DCHECK(image_data);
2990 int page_index = progressive_paints_[progressive_index].page_index;
2991 pp::Rect dirty_in_screen = progressive_paints_[progressive_index].rect;
2992 pp::Rect page_rect = pages_[page_index]->rect();
2993 pp::Rect shadow_rect(page_rect);
2994 shadow_rect.Inset(-kPageShadowLeft, -kPageShadowTop,
2995 -kPageShadowRight, -kPageShadowBottom);
2997 // Due to the rounding errors of the GetScreenRect it is possible to get
2998 // different size shadows on the left and right sides even they are defined
2999 // the same. To fix this issue let's calculate shadow rect and then shrink
3000 // it by the size of the shadows.
3001 shadow_rect = GetScreenRect(shadow_rect);
3002 page_rect = shadow_rect;
3004 page_rect.Inset(static_cast<int>(ceil(kPageShadowLeft * current_zoom_)),
3005 static_cast<int>(ceil(kPageShadowTop * current_zoom_)),
3006 static_cast<int>(ceil(kPageShadowRight * current_zoom_)),
3007 static_cast<int>(ceil(kPageShadowBottom * current_zoom_)));
3009 DrawPageShadow(page_rect, shadow_rect, dirty_in_screen, image_data);
3012 void PDFiumEngine::DrawSelections(int progressive_index,
3013 pp::ImageData* image_data) {
3014 DCHECK_GE(progressive_index, 0);
3015 DCHECK_LT(static_cast<size_t>(progressive_index), progressive_paints_.size());
3016 DCHECK(image_data);
3018 int page_index = progressive_paints_[progressive_index].page_index;
3019 pp::Rect dirty_in_screen = progressive_paints_[progressive_index].rect;
3021 void* region = NULL;
3022 int stride;
3023 GetRegion(dirty_in_screen.point(), image_data, &region, &stride);
3025 std::vector<pp::Rect> highlighted_rects;
3026 pp::Rect visible_rect = GetVisibleRect();
3027 for (size_t k = 0; k < selection_.size(); ++k) {
3028 if (selection_[k].page_index() != page_index)
3029 continue;
3030 std::vector<pp::Rect> rects = selection_[k].GetScreenRects(
3031 visible_rect.point(), current_zoom_, current_rotation_);
3032 for (size_t j = 0; j < rects.size(); ++j) {
3033 pp::Rect visible_selection = rects[j].Intersect(dirty_in_screen);
3034 if (visible_selection.IsEmpty())
3035 continue;
3037 visible_selection.Offset(
3038 -dirty_in_screen.point().x(), -dirty_in_screen.point().y());
3039 Highlight(region, stride, visible_selection, &highlighted_rects);
3043 for (size_t k = 0; k < form_highlights_.size(); ++k) {
3044 pp::Rect visible_selection = form_highlights_[k].Intersect(dirty_in_screen);
3045 if (visible_selection.IsEmpty())
3046 continue;
3048 visible_selection.Offset(
3049 -dirty_in_screen.point().x(), -dirty_in_screen.point().y());
3050 Highlight(region, stride, visible_selection, &highlighted_rects);
3052 form_highlights_.clear();
3055 void PDFiumEngine::PaintUnavailablePage(int page_index,
3056 const pp::Rect& dirty,
3057 pp::ImageData* image_data) {
3058 int start_x, start_y, size_x, size_y;
3059 GetPDFiumRect(page_index, dirty, &start_x, &start_y, &size_x, &size_y);
3060 FPDF_BITMAP bitmap = CreateBitmap(dirty, image_data);
3061 FPDFBitmap_FillRect(bitmap, start_x, start_y, size_x, size_y,
3062 kPendingPageColor);
3064 pp::Rect loading_text_in_screen(
3065 pages_[page_index]->rect().width() / 2,
3066 pages_[page_index]->rect().y() + kLoadingTextVerticalOffset, 0, 0);
3067 loading_text_in_screen = GetScreenRect(loading_text_in_screen);
3068 FPDFBitmap_Destroy(bitmap);
3071 int PDFiumEngine::GetProgressiveIndex(int page_index) const {
3072 for (size_t i = 0; i < progressive_paints_.size(); ++i) {
3073 if (progressive_paints_[i].page_index == page_index)
3074 return i;
3076 return -1;
3079 FPDF_BITMAP PDFiumEngine::CreateBitmap(const pp::Rect& rect,
3080 pp::ImageData* image_data) const {
3081 void* region;
3082 int stride;
3083 GetRegion(rect.point(), image_data, &region, &stride);
3084 if (!region)
3085 return NULL;
3086 return FPDFBitmap_CreateEx(
3087 rect.width(), rect.height(), FPDFBitmap_BGRx, region, stride);
3090 void PDFiumEngine::GetPDFiumRect(
3091 int page_index, const pp::Rect& rect, int* start_x, int* start_y,
3092 int* size_x, int* size_y) const {
3093 pp::Rect page_rect = GetScreenRect(pages_[page_index]->rect());
3094 page_rect.Offset(-rect.x(), -rect.y());
3096 *start_x = page_rect.x();
3097 *start_y = page_rect.y();
3098 *size_x = page_rect.width();
3099 *size_y = page_rect.height();
3102 int PDFiumEngine::GetRenderingFlags() const {
3103 int flags = FPDF_LCD_TEXT | FPDF_NO_CATCH;
3104 if (render_grayscale_)
3105 flags |= FPDF_GRAYSCALE;
3106 if (client_->IsPrintPreview())
3107 flags |= FPDF_PRINTING;
3108 return flags;
3111 pp::Rect PDFiumEngine::GetVisibleRect() const {
3112 pp::Rect rv;
3113 rv.set_x(static_cast<int>(position_.x() / current_zoom_));
3114 rv.set_y(static_cast<int>(position_.y() / current_zoom_));
3115 rv.set_width(static_cast<int>(ceil(plugin_size_.width() / current_zoom_)));
3116 rv.set_height(static_cast<int>(ceil(plugin_size_.height() / current_zoom_)));
3117 return rv;
3120 pp::Rect PDFiumEngine::GetPageScreenRect(int page_index) const {
3121 // Since we use this rect for creating the PDFium bitmap, also include other
3122 // areas around the page that we might need to update such as the page
3123 // separator and the sides if the page is narrower than the document.
3124 return GetScreenRect(pp::Rect(
3126 pages_[page_index]->rect().y() - kPageShadowTop,
3127 document_size_.width(),
3128 pages_[page_index]->rect().height() + kPageShadowTop +
3129 kPageShadowBottom + kPageSeparatorThickness));
3132 pp::Rect PDFiumEngine::GetScreenRect(const pp::Rect& rect) const {
3133 pp::Rect rv;
3134 int right =
3135 static_cast<int>(ceil(rect.right() * current_zoom_ - position_.x()));
3136 int bottom =
3137 static_cast<int>(ceil(rect.bottom() * current_zoom_ - position_.y()));
3139 rv.set_x(static_cast<int>(rect.x() * current_zoom_ - position_.x()));
3140 rv.set_y(static_cast<int>(rect.y() * current_zoom_ - position_.y()));
3141 rv.set_width(right - rv.x());
3142 rv.set_height(bottom - rv.y());
3143 return rv;
3146 void PDFiumEngine::Highlight(void* buffer,
3147 int stride,
3148 const pp::Rect& rect,
3149 std::vector<pp::Rect>* highlighted_rects) {
3150 if (!buffer)
3151 return;
3153 pp::Rect new_rect = rect;
3154 for (size_t i = 0; i < highlighted_rects->size(); ++i)
3155 new_rect = new_rect.Subtract((*highlighted_rects)[i]);
3157 highlighted_rects->push_back(new_rect);
3158 int l = new_rect.x();
3159 int t = new_rect.y();
3160 int w = new_rect.width();
3161 int h = new_rect.height();
3163 for (int y = t; y < t + h; ++y) {
3164 for (int x = l; x < l + w; ++x) {
3165 uint8* pixel = static_cast<uint8*>(buffer) + y * stride + x * 4;
3166 // This is our highlight color.
3167 pixel[0] = static_cast<uint8>(
3168 pixel[0] * (kHighlightColorB / 255.0));
3169 pixel[1] = static_cast<uint8>(
3170 pixel[1] * (kHighlightColorG / 255.0));
3171 pixel[2] = static_cast<uint8>(
3172 pixel[2] * (kHighlightColorR / 255.0));
3177 PDFiumEngine::SelectionChangeInvalidator::SelectionChangeInvalidator(
3178 PDFiumEngine* engine) : engine_(engine) {
3179 previous_origin_ = engine_->GetVisibleRect().point();
3180 GetVisibleSelectionsScreenRects(&old_selections_);
3183 PDFiumEngine::SelectionChangeInvalidator::~SelectionChangeInvalidator() {
3184 // Offset the old selections if the document scrolled since we recorded them.
3185 pp::Point offset = previous_origin_ - engine_->GetVisibleRect().point();
3186 for (size_t i = 0; i < old_selections_.size(); ++i)
3187 old_selections_[i].Offset(offset);
3189 std::vector<pp::Rect> new_selections;
3190 GetVisibleSelectionsScreenRects(&new_selections);
3191 for (size_t i = 0; i < new_selections.size(); ++i) {
3192 for (size_t j = 0; j < old_selections_.size(); ++j) {
3193 if (!old_selections_[j].IsEmpty() &&
3194 new_selections[i] == old_selections_[j]) {
3195 // Rectangle was selected before and after, so no need to invalidate it.
3196 // Mark the rectangles by setting them to empty.
3197 new_selections[i] = old_selections_[j] = pp::Rect();
3198 break;
3203 for (size_t i = 0; i < old_selections_.size(); ++i) {
3204 if (!old_selections_[i].IsEmpty())
3205 engine_->client_->Invalidate(old_selections_[i]);
3207 for (size_t i = 0; i < new_selections.size(); ++i) {
3208 if (!new_selections[i].IsEmpty())
3209 engine_->client_->Invalidate(new_selections[i]);
3211 engine_->OnSelectionChanged();
3214 void
3215 PDFiumEngine::SelectionChangeInvalidator::GetVisibleSelectionsScreenRects(
3216 std::vector<pp::Rect>* rects) {
3217 pp::Rect visible_rect = engine_->GetVisibleRect();
3218 for (size_t i = 0; i < engine_->selection_.size(); ++i) {
3219 int page_index = engine_->selection_[i].page_index();
3220 if (!engine_->IsPageVisible(page_index))
3221 continue; // This selection is on a page that's not currently visible.
3223 std::vector<pp::Rect> selection_rects =
3224 engine_->selection_[i].GetScreenRects(
3225 visible_rect.point(),
3226 engine_->current_zoom_,
3227 engine_->current_rotation_);
3228 rects->insert(rects->end(), selection_rects.begin(), selection_rects.end());
3232 PDFiumEngine::MouseDownState::MouseDownState(
3233 const PDFiumPage::Area& area,
3234 const PDFiumPage::LinkTarget& target)
3235 : area_(area), target_(target) {
3238 PDFiumEngine::MouseDownState::~MouseDownState() {
3241 void PDFiumEngine::MouseDownState::Set(const PDFiumPage::Area& area,
3242 const PDFiumPage::LinkTarget& target) {
3243 area_ = area;
3244 target_ = target;
3247 void PDFiumEngine::MouseDownState::Reset() {
3248 area_ = PDFiumPage::NONSELECTABLE_AREA;
3249 target_ = PDFiumPage::LinkTarget();
3252 bool PDFiumEngine::MouseDownState::Matches(
3253 const PDFiumPage::Area& area,
3254 const PDFiumPage::LinkTarget& target) const {
3255 if (area_ == area) {
3256 if (area == PDFiumPage::WEBLINK_AREA)
3257 return target_.url == target.url;
3258 if (area == PDFiumPage::DOCLINK_AREA)
3259 return target_.page == target.page;
3260 return true;
3262 return false;
3265 PDFiumEngine::FindTextIndex::FindTextIndex()
3266 : valid_(false), index_(0) {
3269 PDFiumEngine::FindTextIndex::~FindTextIndex() {
3272 void PDFiumEngine::FindTextIndex::Invalidate() {
3273 valid_ = false;
3276 size_t PDFiumEngine::FindTextIndex::GetIndex() const {
3277 DCHECK(valid_);
3278 return index_;
3281 void PDFiumEngine::FindTextIndex::SetIndex(size_t index) {
3282 valid_ = true;
3283 index_ = index;
3286 size_t PDFiumEngine::FindTextIndex::IncrementIndex() {
3287 DCHECK(valid_);
3288 return ++index_;
3291 void PDFiumEngine::DeviceToPage(int page_index,
3292 float device_x,
3293 float device_y,
3294 double* page_x,
3295 double* page_y) {
3296 *page_x = *page_y = 0;
3297 int temp_x = static_cast<int>((device_x + position_.x())/ current_zoom_ -
3298 pages_[page_index]->rect().x());
3299 int temp_y = static_cast<int>((device_y + position_.y())/ current_zoom_ -
3300 pages_[page_index]->rect().y());
3301 FPDF_DeviceToPage(
3302 pages_[page_index]->GetPage(), 0, 0,
3303 pages_[page_index]->rect().width(), pages_[page_index]->rect().height(),
3304 current_rotation_, temp_x, temp_y, page_x, page_y);
3307 int PDFiumEngine::GetVisiblePageIndex(FPDF_PAGE page) {
3308 for (size_t i = 0; i < visible_pages_.size(); ++i) {
3309 if (pages_[visible_pages_[i]]->GetPage() == page)
3310 return visible_pages_[i];
3312 return -1;
3315 void PDFiumEngine::SetCurrentPage(int index) {
3316 if (index == most_visible_page_ || !form_)
3317 return;
3318 if (most_visible_page_ != -1 && called_do_document_action_) {
3319 FPDF_PAGE old_page = pages_[most_visible_page_]->GetPage();
3320 FORM_DoPageAAction(old_page, form_, FPDFPAGE_AACTION_CLOSE);
3322 most_visible_page_ = index;
3323 #if defined(OS_LINUX)
3324 g_last_instance_id = client_->GetPluginInstance()->pp_instance();
3325 #endif
3326 if (most_visible_page_ != -1 && called_do_document_action_) {
3327 FPDF_PAGE new_page = pages_[most_visible_page_]->GetPage();
3328 FORM_DoPageAAction(new_page, form_, FPDFPAGE_AACTION_OPEN);
3332 void PDFiumEngine::TransformPDFPageForPrinting(
3333 FPDF_PAGE page,
3334 const PP_PrintSettings_Dev& print_settings) {
3335 // Get the source page width and height in points.
3336 const double src_page_width = FPDF_GetPageWidth(page);
3337 const double src_page_height = FPDF_GetPageHeight(page);
3339 const int src_page_rotation = FPDFPage_GetRotation(page);
3340 const bool fit_to_page = print_settings.print_scaling_option ==
3341 PP_PRINTSCALINGOPTION_FIT_TO_PRINTABLE_AREA;
3343 pp::Size page_size(print_settings.paper_size);
3344 pp::Rect content_rect(print_settings.printable_area);
3345 const bool rotated = (src_page_rotation % 2 == 1);
3346 SetPageSizeAndContentRect(rotated,
3347 src_page_width > src_page_height,
3348 &page_size,
3349 &content_rect);
3351 // Compute the screen page width and height in points.
3352 const int actual_page_width =
3353 rotated ? page_size.height() : page_size.width();
3354 const int actual_page_height =
3355 rotated ? page_size.width() : page_size.height();
3357 const double scale_factor = CalculateScaleFactor(fit_to_page, content_rect,
3358 src_page_width,
3359 src_page_height, rotated);
3361 // Calculate positions for the clip box.
3362 ClipBox source_clip_box;
3363 CalculateClipBoxBoundary(page, scale_factor, rotated, &source_clip_box);
3365 // Calculate the translation offset values.
3366 double offset_x = 0;
3367 double offset_y = 0;
3368 if (fit_to_page) {
3369 CalculateScaledClipBoxOffset(content_rect, source_clip_box, &offset_x,
3370 &offset_y);
3371 } else {
3372 CalculateNonScaledClipBoxOffset(content_rect, src_page_rotation,
3373 actual_page_width, actual_page_height,
3374 source_clip_box, &offset_x, &offset_y);
3377 // Reset the media box and crop box. When the page has crop box and media box,
3378 // the plugin will display the crop box contents and not the entire media box.
3379 // If the pages have different crop box values, the plugin will display a
3380 // document of multiple page sizes. To give better user experience, we
3381 // decided to have same crop box and media box values. Hence, the user will
3382 // see a list of uniform pages.
3383 FPDFPage_SetMediaBox(page, 0, 0, page_size.width(), page_size.height());
3384 FPDFPage_SetCropBox(page, 0, 0, page_size.width(), page_size.height());
3386 // Transformation is not required, return. Do this check only after updating
3387 // the media box and crop box. For more detailed information, please refer to
3388 // the comment block right before FPDF_SetMediaBox and FPDF_GetMediaBox calls.
3389 if (scale_factor == 1.0 && offset_x == 0 && offset_y == 0)
3390 return;
3393 // All the positions have been calculated, now manipulate the PDF.
3394 FS_MATRIX matrix = {static_cast<float>(scale_factor),
3397 static_cast<float>(scale_factor),
3398 static_cast<float>(offset_x),
3399 static_cast<float>(offset_y)};
3400 FS_RECTF cliprect = {static_cast<float>(source_clip_box.left+offset_x),
3401 static_cast<float>(source_clip_box.top+offset_y),
3402 static_cast<float>(source_clip_box.right+offset_x),
3403 static_cast<float>(source_clip_box.bottom+offset_y)};
3404 FPDFPage_TransFormWithClip(page, &matrix, &cliprect);
3405 FPDFPage_TransformAnnots(page, scale_factor, 0, 0, scale_factor,
3406 offset_x, offset_y);
3409 void PDFiumEngine::DrawPageShadow(const pp::Rect& page_rc,
3410 const pp::Rect& shadow_rc,
3411 const pp::Rect& clip_rc,
3412 pp::ImageData* image_data) {
3413 pp::Rect page_rect(page_rc);
3414 page_rect.Offset(page_offset_);
3416 pp::Rect shadow_rect(shadow_rc);
3417 shadow_rect.Offset(page_offset_);
3419 pp::Rect clip_rect(clip_rc);
3420 clip_rect.Offset(page_offset_);
3422 // Page drop shadow parameters.
3423 const double factor = 0.5;
3424 uint32 depth = std::max(
3425 std::max(page_rect.x() - shadow_rect.x(),
3426 page_rect.y() - shadow_rect.y()),
3427 std::max(shadow_rect.right() - page_rect.right(),
3428 shadow_rect.bottom() - page_rect.bottom()));
3429 depth = static_cast<uint32>(depth * 1.5) + 1;
3431 // We need to check depth only to verify our copy of shadow matrix is correct.
3432 if (!page_shadow_.get() || page_shadow_->depth() != depth)
3433 page_shadow_.reset(new ShadowMatrix(depth, factor,
3434 client_->GetBackgroundColor()));
3436 DCHECK(!image_data->is_null());
3437 DrawShadow(image_data, shadow_rect, page_rect, clip_rect, *page_shadow_);
3440 void PDFiumEngine::GetRegion(const pp::Point& location,
3441 pp::ImageData* image_data,
3442 void** region,
3443 int* stride) const {
3444 if (image_data->is_null()) {
3445 DCHECK(plugin_size_.IsEmpty());
3446 *stride = 0;
3447 *region = NULL;
3448 return;
3450 char* buffer = static_cast<char*>(image_data->data());
3451 *stride = image_data->stride();
3453 pp::Point offset_location = location + page_offset_;
3454 // TODO: update this when we support BIDI and scrollbars can be on the left.
3455 if (!buffer ||
3456 !pp::Rect(page_offset_, plugin_size_).Contains(offset_location)) {
3457 *region = NULL;
3458 return;
3461 buffer += location.y() * (*stride);
3462 buffer += (location.x() + page_offset_.x()) * 4;
3463 *region = buffer;
3466 void PDFiumEngine::OnSelectionChanged() {
3467 pp::PDF::SetSelectedText(GetPluginInstance(), GetSelectedText().c_str());
3470 void PDFiumEngine::RotateInternal() {
3471 // Store the current find index so that we can resume finding at that
3472 // particular index after we have recomputed the find results.
3473 std::string current_find_text = current_find_text_;
3474 if (current_find_index_.valid())
3475 resume_find_index_.SetIndex(current_find_index_.GetIndex());
3476 else
3477 resume_find_index_.Invalidate();
3479 InvalidateAllPages();
3481 if (!current_find_text.empty()) {
3482 // Clear the UI.
3483 client_->NotifyNumberOfFindResultsChanged(0, false);
3484 StartFind(current_find_text.c_str(), false);
3488 void PDFiumEngine::SetSelecting(bool selecting) {
3489 bool was_selecting = selecting_;
3490 selecting_ = selecting;
3491 if (selecting_ != was_selecting)
3492 client_->IsSelectingChanged(selecting);
3495 void PDFiumEngine::Form_Invalidate(FPDF_FORMFILLINFO* param,
3496 FPDF_PAGE page,
3497 double left,
3498 double top,
3499 double right,
3500 double bottom) {
3501 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3502 int page_index = engine->GetVisiblePageIndex(page);
3503 if (page_index == -1) {
3504 // This can sometime happen when the page is closed because it went off
3505 // screen, and PDFium invalidates the control as it's being deleted.
3506 return;
3509 pp::Rect rect = engine->pages_[page_index]->PageToScreen(
3510 engine->GetVisibleRect().point(), engine->current_zoom_, left, top, right,
3511 bottom, engine->current_rotation_);
3512 engine->client_->Invalidate(rect);
3515 void PDFiumEngine::Form_OutputSelectedRect(FPDF_FORMFILLINFO* param,
3516 FPDF_PAGE page,
3517 double left,
3518 double top,
3519 double right,
3520 double bottom) {
3521 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3522 int page_index = engine->GetVisiblePageIndex(page);
3523 if (page_index == -1) {
3524 NOTREACHED();
3525 return;
3527 pp::Rect rect = engine->pages_[page_index]->PageToScreen(
3528 engine->GetVisibleRect().point(), engine->current_zoom_, left, top, right,
3529 bottom, engine->current_rotation_);
3530 engine->form_highlights_.push_back(rect);
3533 void PDFiumEngine::Form_SetCursor(FPDF_FORMFILLINFO* param, int cursor_type) {
3534 // We don't need this since it's not enough to change the cursor in all
3535 // scenarios. Instead, we check which form field we're under in OnMouseMove.
3538 int PDFiumEngine::Form_SetTimer(FPDF_FORMFILLINFO* param,
3539 int elapse,
3540 TimerCallback timer_func) {
3541 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3542 engine->timers_[++engine->next_timer_id_] =
3543 std::pair<int, TimerCallback>(elapse, timer_func);
3544 engine->client_->ScheduleCallback(engine->next_timer_id_, elapse);
3545 return engine->next_timer_id_;
3548 void PDFiumEngine::Form_KillTimer(FPDF_FORMFILLINFO* param, int timer_id) {
3549 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3550 engine->timers_.erase(timer_id);
3553 FPDF_SYSTEMTIME PDFiumEngine::Form_GetLocalTime(FPDF_FORMFILLINFO* param) {
3554 base::Time time = base::Time::Now();
3555 base::Time::Exploded exploded;
3556 time.LocalExplode(&exploded);
3558 FPDF_SYSTEMTIME rv;
3559 rv.wYear = exploded.year;
3560 rv.wMonth = exploded.month;
3561 rv.wDayOfWeek = exploded.day_of_week;
3562 rv.wDay = exploded.day_of_month;
3563 rv.wHour = exploded.hour;
3564 rv.wMinute = exploded.minute;
3565 rv.wSecond = exploded.second;
3566 rv.wMilliseconds = exploded.millisecond;
3567 return rv;
3570 void PDFiumEngine::Form_OnChange(FPDF_FORMFILLINFO* param) {
3571 // Don't care about.
3574 FPDF_PAGE PDFiumEngine::Form_GetPage(FPDF_FORMFILLINFO* param,
3575 FPDF_DOCUMENT document,
3576 int page_index) {
3577 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3578 if (page_index < 0 || page_index >= static_cast<int>(engine->pages_.size()))
3579 return NULL;
3580 return engine->pages_[page_index]->GetPage();
3583 FPDF_PAGE PDFiumEngine::Form_GetCurrentPage(FPDF_FORMFILLINFO* param,
3584 FPDF_DOCUMENT document) {
3585 // TODO(jam): find out what this is used for.
3586 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3587 int index = engine->last_page_mouse_down_;
3588 if (index == -1) {
3589 index = engine->GetMostVisiblePage();
3590 if (index == -1) {
3591 NOTREACHED();
3592 return NULL;
3596 return engine->pages_[index]->GetPage();
3599 int PDFiumEngine::Form_GetRotation(FPDF_FORMFILLINFO* param, FPDF_PAGE page) {
3600 return 0;
3603 void PDFiumEngine::Form_ExecuteNamedAction(FPDF_FORMFILLINFO* param,
3604 FPDF_BYTESTRING named_action) {
3605 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3606 std::string action(named_action);
3607 if (action == "Print") {
3608 engine->client_->Print();
3609 return;
3612 int index = engine->last_page_mouse_down_;
3613 /* Don't try to calculate the most visible page if we don't have a left click
3614 before this event (this code originally copied Form_GetCurrentPage which of
3615 course needs to do that and which doesn't have recursion). This can end up
3616 causing infinite recursion. See http://crbug.com/240413 for more
3617 information. Either way, it's not necessary for the spec'd list of named
3618 actions.
3619 if (index == -1)
3620 index = engine->GetMostVisiblePage();
3622 if (index == -1)
3623 return;
3625 // This is the only list of named actions per the spec (see 12.6.4.11). Adobe
3626 // Reader supports more, like FitWidth, but since they're not part of the spec
3627 // and we haven't got bugs about them, no need to now.
3628 if (action == "NextPage") {
3629 engine->client_->ScrollToPage(index + 1);
3630 } else if (action == "PrevPage") {
3631 engine->client_->ScrollToPage(index - 1);
3632 } else if (action == "FirstPage") {
3633 engine->client_->ScrollToPage(0);
3634 } else if (action == "LastPage") {
3635 engine->client_->ScrollToPage(engine->pages_.size() - 1);
3639 void PDFiumEngine::Form_SetTextFieldFocus(FPDF_FORMFILLINFO* param,
3640 FPDF_WIDESTRING value,
3641 FPDF_DWORD valueLen,
3642 FPDF_BOOL is_focus) {
3643 // Do nothing for now.
3644 // TODO(gene): use this signal to trigger OSK.
3647 void PDFiumEngine::Form_DoURIAction(FPDF_FORMFILLINFO* param,
3648 FPDF_BYTESTRING uri) {
3649 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3650 engine->client_->NavigateTo(std::string(uri), false);
3653 void PDFiumEngine::Form_DoGoToAction(FPDF_FORMFILLINFO* param,
3654 int page_index,
3655 int zoom_mode,
3656 float* position_array,
3657 int size_of_array) {
3658 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3659 engine->client_->ScrollToPage(page_index);
3662 int PDFiumEngine::Form_Alert(IPDF_JSPLATFORM* param,
3663 FPDF_WIDESTRING message,
3664 FPDF_WIDESTRING title,
3665 int type,
3666 int icon) {
3667 // See fpdfformfill.h for these values.
3668 enum AlertType {
3669 ALERT_TYPE_OK = 0,
3670 ALERT_TYPE_OK_CANCEL,
3671 ALERT_TYPE_YES_ON,
3672 ALERT_TYPE_YES_NO_CANCEL
3675 enum AlertResult {
3676 ALERT_RESULT_OK = 1,
3677 ALERT_RESULT_CANCEL,
3678 ALERT_RESULT_NO,
3679 ALERT_RESULT_YES
3682 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3683 std::string message_str =
3684 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(message));
3685 if (type == ALERT_TYPE_OK) {
3686 engine->client_->Alert(message_str);
3687 return ALERT_RESULT_OK;
3690 bool rv = engine->client_->Confirm(message_str);
3691 if (type == ALERT_TYPE_OK_CANCEL)
3692 return rv ? ALERT_RESULT_OK : ALERT_RESULT_CANCEL;
3693 return rv ? ALERT_RESULT_YES : ALERT_RESULT_NO;
3696 void PDFiumEngine::Form_Beep(IPDF_JSPLATFORM* param, int type) {
3697 // Beeps are annoying, and not possible using javascript, so ignore for now.
3700 int PDFiumEngine::Form_Response(IPDF_JSPLATFORM* param,
3701 FPDF_WIDESTRING question,
3702 FPDF_WIDESTRING title,
3703 FPDF_WIDESTRING default_response,
3704 FPDF_WIDESTRING label,
3705 FPDF_BOOL password,
3706 void* response,
3707 int length) {
3708 std::string question_str = base::UTF16ToUTF8(
3709 reinterpret_cast<const base::char16*>(question));
3710 std::string default_str = base::UTF16ToUTF8(
3711 reinterpret_cast<const base::char16*>(default_response));
3713 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3714 std::string rv = engine->client_->Prompt(question_str, default_str);
3715 base::string16 rv_16 = base::UTF8ToUTF16(rv);
3716 int rv_bytes = rv_16.size() * sizeof(base::char16);
3717 if (response) {
3718 int bytes_to_copy = rv_bytes < length ? rv_bytes : length;
3719 memcpy(response, rv_16.c_str(), bytes_to_copy);
3721 return rv_bytes;
3724 int PDFiumEngine::Form_GetFilePath(IPDF_JSPLATFORM* param,
3725 void* file_path,
3726 int length) {
3727 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3728 std::string rv = engine->client_->GetURL();
3729 if (file_path && rv.size() <= static_cast<size_t>(length))
3730 memcpy(file_path, rv.c_str(), rv.size());
3731 return rv.size();
3734 void PDFiumEngine::Form_Mail(IPDF_JSPLATFORM* param,
3735 void* mail_data,
3736 int length,
3737 FPDF_BOOL ui,
3738 FPDF_WIDESTRING to,
3739 FPDF_WIDESTRING subject,
3740 FPDF_WIDESTRING cc,
3741 FPDF_WIDESTRING bcc,
3742 FPDF_WIDESTRING message) {
3743 // Note: |mail_data| and |length| are ignored. We don't handle attachments;
3744 // there is no way with mailto.
3745 std::string to_str =
3746 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(to));
3747 std::string cc_str =
3748 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(cc));
3749 std::string bcc_str =
3750 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(bcc));
3751 std::string subject_str =
3752 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(subject));
3753 std::string message_str =
3754 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(message));
3756 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3757 engine->client_->Email(to_str, cc_str, bcc_str, subject_str, message_str);
3760 void PDFiumEngine::Form_Print(IPDF_JSPLATFORM* param,
3761 FPDF_BOOL ui,
3762 int start,
3763 int end,
3764 FPDF_BOOL silent,
3765 FPDF_BOOL shrink_to_fit,
3766 FPDF_BOOL print_as_image,
3767 FPDF_BOOL reverse,
3768 FPDF_BOOL annotations) {
3769 // No way to pass the extra information to the print dialog using JavaScript.
3770 // Just opening it is fine for now.
3771 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3772 engine->client_->Print();
3775 void PDFiumEngine::Form_SubmitForm(IPDF_JSPLATFORM* param,
3776 void* form_data,
3777 int length,
3778 FPDF_WIDESTRING url) {
3779 std::string url_str =
3780 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(url));
3781 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3782 engine->client_->SubmitForm(url_str, form_data, length);
3785 void PDFiumEngine::Form_GotoPage(IPDF_JSPLATFORM* param,
3786 int page_number) {
3787 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3788 engine->client_->ScrollToPage(page_number);
3791 int PDFiumEngine::Form_Browse(IPDF_JSPLATFORM* param,
3792 void* file_path,
3793 int length) {
3794 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3795 std::string path = engine->client_->ShowFileSelectionDialog();
3796 if (path.size() + 1 <= static_cast<size_t>(length))
3797 memcpy(file_path, &path[0], path.size() + 1);
3798 return path.size() + 1;
3801 FPDF_BOOL PDFiumEngine::Pause_NeedToPauseNow(IFSDK_PAUSE* param) {
3802 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3803 return (base::Time::Now() - engine->last_progressive_start_time_).
3804 InMilliseconds() > engine->progressive_paint_timeout_;
3807 ScopedUnsupportedFeature::ScopedUnsupportedFeature(PDFiumEngine* engine)
3808 : engine_(engine), old_engine_(g_engine_for_unsupported) {
3809 g_engine_for_unsupported = engine_;
3812 ScopedUnsupportedFeature::~ScopedUnsupportedFeature() {
3813 g_engine_for_unsupported = old_engine_;
3816 PDFEngineExports* PDFEngineExports::Create() {
3817 return new PDFiumEngineExports;
3820 namespace {
3822 int CalculatePosition(FPDF_PAGE page,
3823 const PDFiumEngineExports::RenderingSettings& settings,
3824 pp::Rect* dest) {
3825 int page_width = static_cast<int>(ConvertUnitDouble(FPDF_GetPageWidth(page),
3826 kPointsPerInch,
3827 settings.dpi_x));
3828 int page_height = static_cast<int>(ConvertUnitDouble(FPDF_GetPageHeight(page),
3829 kPointsPerInch,
3830 settings.dpi_y));
3832 // Start by assuming that we will draw exactly to the bounds rect
3833 // specified.
3834 *dest = settings.bounds;
3836 int rotate = 0; // normal orientation.
3838 // Auto-rotate landscape pages to print correctly.
3839 if (settings.autorotate &&
3840 (dest->width() > dest->height()) != (page_width > page_height)) {
3841 rotate = 3; // 90 degrees counter-clockwise.
3842 std::swap(page_width, page_height);
3845 // See if we need to scale the output
3846 bool scale_to_bounds = false;
3847 if (settings.fit_to_bounds &&
3848 ((page_width > dest->width()) || (page_height > dest->height()))) {
3849 scale_to_bounds = true;
3850 } else if (settings.stretch_to_bounds &&
3851 ((page_width < dest->width()) || (page_height < dest->height()))) {
3852 scale_to_bounds = true;
3855 if (scale_to_bounds) {
3856 // If we need to maintain aspect ratio, calculate the actual width and
3857 // height.
3858 if (settings.keep_aspect_ratio) {
3859 double scale_factor_x = page_width;
3860 scale_factor_x /= dest->width();
3861 double scale_factor_y = page_height;
3862 scale_factor_y /= dest->height();
3863 if (scale_factor_x > scale_factor_y) {
3864 dest->set_height(page_height / scale_factor_x);
3865 } else {
3866 dest->set_width(page_width / scale_factor_y);
3869 } else {
3870 // We are not scaling to bounds. Draw in the actual page size. If the
3871 // actual page size is larger than the bounds, the output will be
3872 // clipped.
3873 dest->set_width(page_width);
3874 dest->set_height(page_height);
3877 if (settings.center_in_bounds) {
3878 pp::Point offset((settings.bounds.width() - dest->width()) / 2,
3879 (settings.bounds.height() - dest->height()) / 2);
3880 dest->Offset(offset);
3882 return rotate;
3885 } // namespace
3887 #if defined(OS_WIN)
3888 bool PDFiumEngineExports::RenderPDFPageToDC(const void* pdf_buffer,
3889 int buffer_size,
3890 int page_number,
3891 const RenderingSettings& settings,
3892 HDC dc) {
3893 FPDF_DOCUMENT doc = FPDF_LoadMemDocument(pdf_buffer, buffer_size, NULL);
3894 if (!doc)
3895 return false;
3896 FPDF_PAGE page = FPDF_LoadPage(doc, page_number);
3897 if (!page) {
3898 FPDF_CloseDocument(doc);
3899 return false;
3901 RenderingSettings new_settings = settings;
3902 // calculate the page size
3903 if (new_settings.dpi_x == -1)
3904 new_settings.dpi_x = GetDeviceCaps(dc, LOGPIXELSX);
3905 if (new_settings.dpi_y == -1)
3906 new_settings.dpi_y = GetDeviceCaps(dc, LOGPIXELSY);
3908 pp::Rect dest;
3909 int rotate = CalculatePosition(page, new_settings, &dest);
3911 int save_state = SaveDC(dc);
3912 // The caller wanted all drawing to happen within the bounds specified.
3913 // Based on scale calculations, our destination rect might be larger
3914 // than the bounds. Set the clip rect to the bounds.
3915 IntersectClipRect(dc, settings.bounds.x(), settings.bounds.y(),
3916 settings.bounds.x() + settings.bounds.width(),
3917 settings.bounds.y() + settings.bounds.height());
3919 // A temporary hack. PDFs generated by Cairo (used by Chrome OS to generate
3920 // a PDF output from a webpage) result in very large metafiles and the
3921 // rendering using FPDF_RenderPage is incorrect. In this case, render as a
3922 // bitmap. Note that this code does not kick in for PDFs printed from Chrome
3923 // because in that case we create a temp PDF first before printing and this
3924 // temp PDF does not have a creator string that starts with "cairo".
3925 base::string16 creator;
3926 size_t buffer_bytes = FPDF_GetMetaText(doc, "Creator", NULL, 0);
3927 if (buffer_bytes > 1) {
3928 FPDF_GetMetaText(doc, "Creator",
3929 base::WriteInto(&creator, buffer_bytes + 1), buffer_bytes);
3931 bool use_bitmap = false;
3932 if (base::StartsWith(creator, L"cairo", base::CompareCase::INSENSITIVE_ASCII))
3933 use_bitmap = true;
3935 // Another temporary hack. Some PDFs seems to render very slowly if
3936 // FPDF_RenderPage is directly used on a printer DC. I suspect it is
3937 // because of the code to talk Postscript directly to the printer if
3938 // the printer supports this. Need to discuss this with PDFium. For now,
3939 // render to a bitmap and then blit the bitmap to the DC if we have been
3940 // supplied a printer DC.
3941 int device_type = GetDeviceCaps(dc, TECHNOLOGY);
3942 if (use_bitmap ||
3943 (device_type == DT_RASPRINTER) || (device_type == DT_PLOTTER)) {
3944 FPDF_BITMAP bitmap = FPDFBitmap_Create(dest.width(), dest.height(),
3945 FPDFBitmap_BGRx);
3946 // Clear the bitmap
3947 FPDFBitmap_FillRect(bitmap, 0, 0, dest.width(), dest.height(), 0xFFFFFFFF);
3948 FPDF_RenderPageBitmap(
3949 bitmap, page, 0, 0, dest.width(), dest.height(), rotate,
3950 FPDF_ANNOT | FPDF_PRINTING | FPDF_NO_CATCH);
3951 int stride = FPDFBitmap_GetStride(bitmap);
3952 BITMAPINFO bmi;
3953 memset(&bmi, 0, sizeof(bmi));
3954 bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
3955 bmi.bmiHeader.biWidth = dest.width();
3956 bmi.bmiHeader.biHeight = -dest.height(); // top-down image
3957 bmi.bmiHeader.biPlanes = 1;
3958 bmi.bmiHeader.biBitCount = 32;
3959 bmi.bmiHeader.biCompression = BI_RGB;
3960 bmi.bmiHeader.biSizeImage = stride * dest.height();
3961 StretchDIBits(dc, dest.x(), dest.y(), dest.width(), dest.height(),
3962 0, 0, dest.width(), dest.height(),
3963 FPDFBitmap_GetBuffer(bitmap), &bmi, DIB_RGB_COLORS, SRCCOPY);
3964 FPDFBitmap_Destroy(bitmap);
3965 } else {
3966 FPDF_RenderPage(dc, page, dest.x(), dest.y(), dest.width(), dest.height(),
3967 rotate, FPDF_ANNOT | FPDF_PRINTING | FPDF_NO_CATCH);
3969 RestoreDC(dc, save_state);
3970 FPDF_ClosePage(page);
3971 FPDF_CloseDocument(doc);
3972 return true;
3974 #endif // OS_WIN
3976 bool PDFiumEngineExports::RenderPDFPageToBitmap(
3977 const void* pdf_buffer,
3978 int pdf_buffer_size,
3979 int page_number,
3980 const RenderingSettings& settings,
3981 void* bitmap_buffer) {
3982 FPDF_DOCUMENT doc = FPDF_LoadMemDocument(pdf_buffer, pdf_buffer_size, NULL);
3983 if (!doc)
3984 return false;
3985 FPDF_PAGE page = FPDF_LoadPage(doc, page_number);
3986 if (!page) {
3987 FPDF_CloseDocument(doc);
3988 return false;
3991 pp::Rect dest;
3992 int rotate = CalculatePosition(page, settings, &dest);
3994 FPDF_BITMAP bitmap =
3995 FPDFBitmap_CreateEx(settings.bounds.width(), settings.bounds.height(),
3996 FPDFBitmap_BGRA, bitmap_buffer,
3997 settings.bounds.width() * 4);
3998 // Clear the bitmap
3999 FPDFBitmap_FillRect(bitmap, 0, 0, settings.bounds.width(),
4000 settings.bounds.height(), 0xFFFFFFFF);
4001 // Shift top-left corner of bounds to (0, 0) if it's not there.
4002 dest.set_point(dest.point() - settings.bounds.point());
4003 FPDF_RenderPageBitmap(
4004 bitmap, page, dest.x(), dest.y(), dest.width(), dest.height(), rotate,
4005 FPDF_ANNOT | FPDF_PRINTING | FPDF_NO_CATCH);
4006 FPDFBitmap_Destroy(bitmap);
4007 FPDF_ClosePage(page);
4008 FPDF_CloseDocument(doc);
4009 return true;
4012 bool PDFiumEngineExports::GetPDFDocInfo(const void* pdf_buffer,
4013 int buffer_size,
4014 int* page_count,
4015 double* max_page_width) {
4016 FPDF_DOCUMENT doc = FPDF_LoadMemDocument(pdf_buffer, buffer_size, NULL);
4017 if (!doc)
4018 return false;
4019 int page_count_local = FPDF_GetPageCount(doc);
4020 if (page_count) {
4021 *page_count = page_count_local;
4023 if (max_page_width) {
4024 *max_page_width = 0;
4025 for (int page_number = 0; page_number < page_count_local; page_number++) {
4026 double page_width = 0;
4027 double page_height = 0;
4028 FPDF_GetPageSizeByIndex(doc, page_number, &page_width, &page_height);
4029 if (page_width > *max_page_width) {
4030 *max_page_width = page_width;
4034 FPDF_CloseDocument(doc);
4035 return true;
4038 bool PDFiumEngineExports::GetPDFPageSizeByIndex(
4039 const void* pdf_buffer,
4040 int pdf_buffer_size,
4041 int page_number,
4042 double* width,
4043 double* height) {
4044 FPDF_DOCUMENT doc = FPDF_LoadMemDocument(pdf_buffer, pdf_buffer_size, NULL);
4045 if (!doc)
4046 return false;
4047 bool success = FPDF_GetPageSizeByIndex(doc, page_number, width, height) != 0;
4048 FPDF_CloseDocument(doc);
4049 return success;
4052 } // namespace chrome_pdf