cygprofile: increase timeouts to allow showing web contents
[chromium-blink-merge.git] / pdf / pdfium / pdfium_engine.cc
blobae3fb3e3b51d30593b803967cb2cbea9c34626dd
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 if (buffer_size > 0) {
529 PDFiumAPIStringBufferSizeInBytesAdapter<base::string16> api_string_adapter(
530 &title, buffer_size, true);
531 api_string_adapter.Close(FPDFBookmark_GetTitle(
532 bookmark, api_string_adapter.GetData(), buffer_size));
534 dict.Set(pp::Var("title"), pp::Var(base::UTF16ToUTF8(title)));
536 FPDF_DEST dest = FPDFBookmark_GetDest(doc, bookmark);
537 // Some bookmarks don't have a page to select.
538 if (dest) {
539 int page_index = FPDFDest_GetPageIndex(doc, dest);
540 dict.Set(pp::Var("page"), pp::Var(page_index));
543 pp::VarArray children;
544 int child_index = 0;
545 for (FPDF_BOOKMARK child_bookmark = FPDFBookmark_GetFirstChild(doc, bookmark);
546 child_bookmark != NULL;
547 child_bookmark = FPDFBookmark_GetNextSibling(doc, child_bookmark)) {
548 children.Set(child_index, TraverseBookmarks(doc, child_bookmark));
549 child_index++;
551 dict.Set(pp::Var("children"), children);
552 return dict;
555 std::string GetDocumentMetadata(FPDF_DOCUMENT doc, const std::string& key) {
556 size_t size = FPDF_GetMetaText(doc, key.c_str(), nullptr, 0);
557 if (size == 0)
558 return std::string();
560 base::string16 value;
561 PDFiumAPIStringBufferSizeInBytesAdapter<base::string16> string_adapter(
562 &value, size, false);
563 string_adapter.Close(
564 FPDF_GetMetaText(doc, key.c_str(), string_adapter.GetData(), size));
565 return base::UTF16ToUTF8(value);
568 } // namespace
570 bool InitializeSDK() {
571 FPDF_InitLibrary();
573 #if defined(OS_LINUX)
574 // Font loading doesn't work in the renderer sandbox in Linux.
575 FPDF_SetSystemFontInfo(&g_font_info);
576 #endif
578 FSDK_SetUnSpObjProcessHandler(&g_unsuppored_info);
580 return true;
583 void ShutdownSDK() {
584 FPDF_DestroyLibrary();
587 PDFEngine* PDFEngine::Create(PDFEngine::Client* client) {
588 return new PDFiumEngine(client);
591 PDFiumEngine::PDFiumEngine(PDFEngine::Client* client)
592 : client_(client),
593 current_zoom_(1.0),
594 current_rotation_(0),
595 doc_loader_(this),
596 password_tries_remaining_(0),
597 doc_(NULL),
598 form_(NULL),
599 defer_page_unload_(false),
600 selecting_(false),
601 mouse_down_state_(PDFiumPage::NONSELECTABLE_AREA,
602 PDFiumPage::LinkTarget()),
603 next_page_to_search_(-1),
604 last_page_to_search_(-1),
605 last_character_index_to_search_(-1),
606 permissions_(0),
607 permissions_handler_revision_(-1),
608 fpdf_availability_(NULL),
609 next_timer_id_(0),
610 last_page_mouse_down_(-1),
611 first_visible_page_(-1),
612 most_visible_page_(-1),
613 called_do_document_action_(false),
614 render_grayscale_(false),
615 progressive_paint_timeout_(0),
616 getting_password_(false) {
617 find_factory_.Initialize(this);
618 password_factory_.Initialize(this);
620 file_access_.m_FileLen = 0;
621 file_access_.m_GetBlock = &GetBlock;
622 file_access_.m_Param = &doc_loader_;
624 file_availability_.version = 1;
625 file_availability_.IsDataAvail = &IsDataAvail;
626 file_availability_.loader = &doc_loader_;
628 download_hints_.version = 1;
629 download_hints_.AddSegment = &AddSegment;
630 download_hints_.loader = &doc_loader_;
632 // Initialize FPDF_FORMFILLINFO member variables. Deriving from this struct
633 // allows the static callbacks to be able to cast the FPDF_FORMFILLINFO in
634 // callbacks to ourself instead of maintaining a map of them to
635 // PDFiumEngine.
636 FPDF_FORMFILLINFO::version = 1;
637 FPDF_FORMFILLINFO::m_pJsPlatform = this;
638 FPDF_FORMFILLINFO::Release = NULL;
639 FPDF_FORMFILLINFO::FFI_Invalidate = Form_Invalidate;
640 FPDF_FORMFILLINFO::FFI_OutputSelectedRect = Form_OutputSelectedRect;
641 FPDF_FORMFILLINFO::FFI_SetCursor = Form_SetCursor;
642 FPDF_FORMFILLINFO::FFI_SetTimer = Form_SetTimer;
643 FPDF_FORMFILLINFO::FFI_KillTimer = Form_KillTimer;
644 FPDF_FORMFILLINFO::FFI_GetLocalTime = Form_GetLocalTime;
645 FPDF_FORMFILLINFO::FFI_OnChange = Form_OnChange;
646 FPDF_FORMFILLINFO::FFI_GetPage = Form_GetPage;
647 FPDF_FORMFILLINFO::FFI_GetCurrentPage = Form_GetCurrentPage;
648 FPDF_FORMFILLINFO::FFI_GetRotation = Form_GetRotation;
649 FPDF_FORMFILLINFO::FFI_ExecuteNamedAction = Form_ExecuteNamedAction;
650 FPDF_FORMFILLINFO::FFI_SetTextFieldFocus = Form_SetTextFieldFocus;
651 FPDF_FORMFILLINFO::FFI_DoURIAction = Form_DoURIAction;
652 FPDF_FORMFILLINFO::FFI_DoGoToAction = Form_DoGoToAction;
653 #ifdef PDF_USE_XFA
654 FPDF_FORMFILLINFO::version = 2;
655 FPDF_FORMFILLINFO::FFI_EmailTo = Form_EmailTo;
656 FPDF_FORMFILLINFO::FFI_DisplayCaret = Form_DisplayCaret;
657 FPDF_FORMFILLINFO::FFI_SetCurrentPage = Form_SetCurrentPage;
658 FPDF_FORMFILLINFO::FFI_GetCurrentPageIndex = Form_GetCurrentPageIndex;
659 FPDF_FORMFILLINFO::FFI_GetPageViewRect = Form_GetPageViewRect;
660 FPDF_FORMFILLINFO::FFI_GetPlatform = Form_GetPlatform;
661 FPDF_FORMFILLINFO::FFI_PopupMenu = Form_PopupMenu;
662 FPDF_FORMFILLINFO::FFI_PostRequestURL = Form_PostRequestURL;
663 FPDF_FORMFILLINFO::FFI_PutRequestURL = Form_PutRequestURL;
664 FPDF_FORMFILLINFO::FFI_UploadTo = Form_UploadTo;
665 FPDF_FORMFILLINFO::FFI_DownloadFromURL = Form_DownloadFromURL;
666 FPDF_FORMFILLINFO::FFI_OpenFile = Form_OpenFile;
667 FPDF_FORMFILLINFO::FFI_GotoURL = Form_GotoURL;
668 FPDF_FORMFILLINFO::FFI_GetLanguage = Form_GetLanguage;
669 #endif // PDF_USE_XFA
670 IPDF_JSPLATFORM::version = 2;
671 IPDF_JSPLATFORM::app_alert = Form_Alert;
672 IPDF_JSPLATFORM::app_beep = Form_Beep;
673 IPDF_JSPLATFORM::app_response = Form_Response;
674 IPDF_JSPLATFORM::Doc_getFilePath = Form_GetFilePath;
675 IPDF_JSPLATFORM::Doc_mail = Form_Mail;
676 IPDF_JSPLATFORM::Doc_print = Form_Print;
677 IPDF_JSPLATFORM::Doc_submitForm = Form_SubmitForm;
678 IPDF_JSPLATFORM::Doc_gotoPage = Form_GotoPage;
679 IPDF_JSPLATFORM::Field_browse = Form_Browse;
680 IPDF_JSPLATFORM::m_isolate = v8::Isolate::GetCurrent();
681 IPDF_JSPLATFORM::m_v8EmbedderSlot = gin::kEmbedderPDFium;
683 IFSDK_PAUSE::version = 1;
684 IFSDK_PAUSE::user = NULL;
685 IFSDK_PAUSE::NeedToPauseNow = Pause_NeedToPauseNow;
688 PDFiumEngine::~PDFiumEngine() {
689 for (size_t i = 0; i < pages_.size(); ++i)
690 pages_[i]->Unload();
692 if (doc_) {
693 FORM_DoDocumentAAction(form_, FPDFDOC_AACTION_WC);
695 #ifdef PDF_USE_XFA
696 // XFA may require |form_| to outlive |doc_|, so shut down in that order.
697 FPDF_CloseDocument(doc_);
698 FPDFDOC_ExitFormFillEnvironment(form_);
699 #else
700 // Normally |doc_| should outlive |form_|.
701 FPDFDOC_ExitFormFillEnvironment(form_);
702 FPDF_CloseDocument(doc_);
703 #endif
705 FPDFAvail_Destroy(fpdf_availability_);
707 STLDeleteElements(&pages_);
710 #ifdef PDF_USE_XFA
712 // This is just for testing, needs to be removed later
713 #if defined(WIN32)
714 #define XFA_TESTFILE(filename) "E:/"#filename
715 #else
716 #define XFA_TESTFILE(filename) "/home/"#filename
717 #endif
719 struct FPDF_FILE {
720 FPDF_FILEHANDLER file_handler;
721 FILE* file;
724 void Sample_Release(FPDF_LPVOID client_data) {
725 if (!client_data)
726 return;
727 FPDF_FILE* file_wrapper = (FPDF_FILE*)client_data;
728 fclose(file_wrapper->file);
729 delete file_wrapper;
732 FPDF_DWORD Sample_GetSize(FPDF_LPVOID client_data) {
733 if (!client_data)
734 return 0;
735 FPDF_FILE* file_wrapper = (FPDF_FILE*)client_data;
736 long cur_pos = ftell(file_wrapper->file);
737 if (cur_pos == -1)
738 return 0;
739 if (fseek(file_wrapper->file, 0, SEEK_END))
740 return 0;
741 long size = ftell(file_wrapper->file);
742 fseek(file_wrapper->file, cur_pos, SEEK_SET);
743 return (FPDF_DWORD)size;
746 FPDF_RESULT Sample_ReadBlock(FPDF_LPVOID client_data,
747 FPDF_DWORD offset,
748 FPDF_LPVOID buffer,
749 FPDF_DWORD size) {
750 if (!client_data)
751 return -1;
752 FPDF_FILE* file_wrapper = (FPDF_FILE*)client_data;
753 if (fseek(file_wrapper->file, (long)offset, SEEK_SET))
754 return -1;
755 size_t read_size = fread(buffer, 1, size, file_wrapper->file);
756 return read_size == size ? 0 : -1;
759 FPDF_RESULT Sample_WriteBlock(FPDF_LPVOID client_data,
760 FPDF_DWORD offset,
761 FPDF_LPCVOID buffer,
762 FPDF_DWORD size) {
763 if (!client_data)
764 return -1;
765 FPDF_FILE* file_wrapper = (FPDF_FILE*)client_data;
766 if (fseek(file_wrapper->file, (long)offset, SEEK_SET))
767 return -1;
768 // Write data
769 size_t write_size = fwrite(buffer, 1, size, file_wrapper->file);
770 return write_size == size ? 0 : -1;
773 FPDF_RESULT Sample_Flush(FPDF_LPVOID client_data) {
774 if (!client_data)
775 return -1;
776 // Flush file
777 fflush(((FPDF_FILE*)client_data)->file);
778 return 0;
781 FPDF_RESULT Sample_Truncate(FPDF_LPVOID client_data, FPDF_DWORD size) {
782 return 0;
785 void PDFiumEngine::Form_EmailTo(FPDF_FORMFILLINFO* param,
786 FPDF_FILEHANDLER* file_handler,
787 FPDF_WIDESTRING to,
788 FPDF_WIDESTRING subject,
789 FPDF_WIDESTRING cc,
790 FPDF_WIDESTRING bcc,
791 FPDF_WIDESTRING message) {
792 std::string to_str =
793 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(to));
794 std::string subject_str =
795 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(subject));
796 std::string cc_str =
797 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(cc));
798 std::string bcc_str =
799 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(bcc));
800 std::string message_str =
801 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(message));
803 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
804 engine->client_->Email(to_str, cc_str, bcc_str, subject_str, message_str);
807 void PDFiumEngine::Form_DisplayCaret(FPDF_FORMFILLINFO* param,
808 FPDF_PAGE page,
809 FPDF_BOOL visible,
810 double left,
811 double top,
812 double right,
813 double bottom) {
814 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
815 engine->client_->UpdateCursor(PP_CURSORTYPE_IBEAM);
816 std::vector<pp::Rect> tickmarks;
817 pp::Rect rect(left, top, right, bottom);
818 tickmarks.push_back(rect);
819 engine->client_->UpdateTickMarks(tickmarks);
822 void PDFiumEngine::Form_SetCurrentPage(FPDF_FORMFILLINFO* param,
823 FPDF_DOCUMENT document,
824 int page) {
825 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
826 pp::Rect page_view_rect = engine->GetPageContentsRect(page);
827 engine->ScrolledToYPosition(page_view_rect.height());
828 pp::Point pos(1, page_view_rect.height());
829 engine->SetScrollPosition(pos);
832 int PDFiumEngine::Form_GetCurrentPageIndex(FPDF_FORMFILLINFO* param,
833 FPDF_DOCUMENT document) {
834 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
835 return engine->GetMostVisiblePage();
838 void PDFiumEngine::Form_GetPageViewRect(FPDF_FORMFILLINFO* param,
839 FPDF_PAGE page,
840 double* left,
841 double* top,
842 double* right,
843 double* bottom) {
844 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
845 int page_index = engine->GetMostVisiblePage();
846 pp::Rect page_view_rect = engine->GetPageContentsRect(page_index);
848 *left = page_view_rect.x();
849 *right = page_view_rect.right();
850 *top = page_view_rect.y();
851 *bottom = page_view_rect.bottom();
854 int PDFiumEngine::Form_GetPlatform(FPDF_FORMFILLINFO* param,
855 void* platform,
856 int length) {
857 int platform_flag = -1;
859 #if defined(WIN32)
860 platform_flag = 0;
861 #elif defined(__linux__)
862 platform_flag = 1;
863 #else
864 platform_flag = 2;
865 #endif
867 std::string javascript = "alert(\"Platform:"
868 + base::DoubleToString(platform_flag)
869 + "\")";
871 return platform_flag;
874 FPDF_BOOL PDFiumEngine::Form_PopupMenu(FPDF_FORMFILLINFO* param,
875 FPDF_PAGE page,
876 FPDF_WIDGET widget,
877 int menu_flag,
878 float x,
879 float y) {
880 return false;
883 FPDF_BOOL PDFiumEngine::Form_PostRequestURL(FPDF_FORMFILLINFO* param,
884 FPDF_WIDESTRING url,
885 FPDF_WIDESTRING data,
886 FPDF_WIDESTRING content_type,
887 FPDF_WIDESTRING encode,
888 FPDF_WIDESTRING header,
889 FPDF_BSTR* response) {
890 std::string url_str =
891 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(url));
892 std::string data_str =
893 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(data));
894 std::string content_type_str =
895 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(content_type));
896 std::string encode_str =
897 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(encode));
898 std::string header_str =
899 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(header));
901 std::string javascript = "alert(\"Post:"
902 + url_str + "," + data_str + "," + content_type_str + ","
903 + encode_str + "," + header_str
904 + "\")";
905 return true;
908 FPDF_BOOL PDFiumEngine::Form_PutRequestURL(FPDF_FORMFILLINFO* param,
909 FPDF_WIDESTRING url,
910 FPDF_WIDESTRING data,
911 FPDF_WIDESTRING encode) {
912 std::string url_str =
913 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(url));
914 std::string data_str =
915 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(data));
916 std::string encode_str =
917 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(encode));
919 std::string javascript = "alert(\"Put:"
920 + url_str + "," + data_str + "," + encode_str
921 + "\")";
923 return true;
926 void PDFiumEngine::Form_UploadTo(FPDF_FORMFILLINFO* param,
927 FPDF_FILEHANDLER* file_handle,
928 int file_flag,
929 FPDF_WIDESTRING to) {
930 std::string to_str =
931 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(to));
932 // TODO: needs the full implementation of form uploading
935 FPDF_LPFILEHANDLER PDFiumEngine::Form_DownloadFromURL(FPDF_FORMFILLINFO* param,
936 FPDF_WIDESTRING url) {
937 std::string url_str =
938 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(url));
940 // Now should get data from url.
941 // For testing purpose, use data read from file
942 // TODO: needs the full implementation here
943 FILE* file = fopen(XFA_TESTFILE("downloadtest.tem"), "w");
945 FPDF_FILE* file_wrapper = new FPDF_FILE;
946 file_wrapper->file = file;
947 file_wrapper->file_handler.clientData = file_wrapper;
948 file_wrapper->file_handler.Flush = Sample_Flush;
949 file_wrapper->file_handler.GetSize = Sample_GetSize;
950 file_wrapper->file_handler.ReadBlock = Sample_ReadBlock;
951 file_wrapper->file_handler.Release = Sample_Release;
952 file_wrapper->file_handler.Truncate = Sample_Truncate;
953 file_wrapper->file_handler.WriteBlock = Sample_WriteBlock;
955 return &file_wrapper->file_handler;
958 FPDF_FILEHANDLER* PDFiumEngine::Form_OpenFile(FPDF_FORMFILLINFO* param,
959 int file_flag,
960 FPDF_WIDESTRING url,
961 const char* mode) {
962 std::string url_str = "NULL";
963 if (url != NULL) {
964 url_str =
965 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(url));
967 // TODO: need to implement open file from the url
968 // Use a file path for the ease of testing
969 FILE* file = fopen(XFA_TESTFILE("tem.txt"), mode);
970 FPDF_FILE* file_wrapper = new FPDF_FILE;
971 file_wrapper->file = file;
972 file_wrapper->file_handler.clientData = file_wrapper;
973 file_wrapper->file_handler.Flush = Sample_Flush;
974 file_wrapper->file_handler.GetSize = Sample_GetSize;
975 file_wrapper->file_handler.ReadBlock = Sample_ReadBlock;
976 file_wrapper->file_handler.Release = Sample_Release;
977 file_wrapper->file_handler.Truncate = Sample_Truncate;
978 file_wrapper->file_handler.WriteBlock = Sample_WriteBlock;
979 return &file_wrapper->file_handler;
982 void PDFiumEngine::Form_GotoURL(FPDF_FORMFILLINFO* param,
983 FPDF_DOCUMENT document,
984 FPDF_WIDESTRING url) {
985 std::string url_str =
986 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(url));
987 // TODO: needs to implement GOTO URL action
990 int PDFiumEngine::Form_GetLanguage(FPDF_FORMFILLINFO* param,
991 void* language,
992 int length) {
993 return 0;
996 #endif // PDF_USE_XFA
998 int PDFiumEngine::GetBlock(void* param, unsigned long position,
999 unsigned char* buffer, unsigned long size) {
1000 DocumentLoader* loader = static_cast<DocumentLoader*>(param);
1001 return loader->GetBlock(position, size, buffer);
1004 FPDF_BOOL PDFiumEngine::IsDataAvail(FX_FILEAVAIL* param,
1005 size_t offset, size_t size) {
1006 PDFiumEngine::FileAvail* file_avail =
1007 static_cast<PDFiumEngine::FileAvail*>(param);
1008 return file_avail->loader->IsDataAvailable(offset, size);
1011 void PDFiumEngine::AddSegment(FX_DOWNLOADHINTS* param,
1012 size_t offset, size_t size) {
1013 PDFiumEngine::DownloadHints* download_hints =
1014 static_cast<PDFiumEngine::DownloadHints*>(param);
1015 return download_hints->loader->RequestData(offset, size);
1018 bool PDFiumEngine::New(const char* url,
1019 const char* headers) {
1020 url_ = url;
1021 if (!headers)
1022 headers_.clear();
1023 else
1024 headers_ = headers;
1025 return true;
1028 void PDFiumEngine::PageOffsetUpdated(const pp::Point& page_offset) {
1029 page_offset_ = page_offset;
1032 void PDFiumEngine::PluginSizeUpdated(const pp::Size& size) {
1033 CancelPaints();
1035 plugin_size_ = size;
1036 CalculateVisiblePages();
1039 void PDFiumEngine::ScrolledToXPosition(int position) {
1040 CancelPaints();
1042 int old_x = position_.x();
1043 position_.set_x(position);
1044 CalculateVisiblePages();
1045 client_->Scroll(pp::Point(old_x - position, 0));
1048 void PDFiumEngine::ScrolledToYPosition(int position) {
1049 CancelPaints();
1051 int old_y = position_.y();
1052 position_.set_y(position);
1053 CalculateVisiblePages();
1054 client_->Scroll(pp::Point(0, old_y - position));
1057 void PDFiumEngine::PrePaint() {
1058 for (size_t i = 0; i < progressive_paints_.size(); ++i)
1059 progressive_paints_[i].painted_ = false;
1062 void PDFiumEngine::Paint(const pp::Rect& rect,
1063 pp::ImageData* image_data,
1064 std::vector<pp::Rect>* ready,
1065 std::vector<pp::Rect>* pending) {
1066 DCHECK(image_data);
1067 DCHECK(ready);
1068 DCHECK(pending);
1070 pp::Rect leftover = rect;
1071 for (size_t i = 0; i < visible_pages_.size(); ++i) {
1072 int index = visible_pages_[i];
1073 pp::Rect page_rect = pages_[index]->rect();
1074 // Convert the current page's rectangle to screen rectangle. We do this
1075 // instead of the reverse (converting the dirty rectangle from screen to
1076 // page coordinates) because then we'd have to convert back to screen
1077 // coordinates, and the rounding errors sometime leave pixels dirty or even
1078 // move the text up or down a pixel when zoomed.
1079 pp::Rect page_rect_in_screen = GetPageScreenRect(index);
1080 pp::Rect dirty_in_screen = page_rect_in_screen.Intersect(leftover);
1081 if (dirty_in_screen.IsEmpty())
1082 continue;
1084 // Compute the leftover dirty region. The first page may have blank space
1085 // above it, in which case we also need to subtract that space from the
1086 // dirty region.
1087 if (i == 0) {
1088 pp::Rect blank_space_in_screen = dirty_in_screen;
1089 blank_space_in_screen.set_y(0);
1090 blank_space_in_screen.set_height(dirty_in_screen.y());
1091 leftover = leftover.Subtract(blank_space_in_screen);
1093 leftover = leftover.Subtract(dirty_in_screen);
1095 if (pages_[index]->available()) {
1096 int progressive = GetProgressiveIndex(index);
1097 if (progressive != -1) {
1098 DCHECK_GE(progressive, 0);
1099 DCHECK_LT(static_cast<size_t>(progressive), progressive_paints_.size());
1100 if (progressive_paints_[progressive].rect != dirty_in_screen) {
1101 // The PDFium code can only handle one progressive paint at a time, so
1102 // queue this up. Previously we used to merge the rects when this
1103 // happened, but it made scrolling up on complex PDFs very slow since
1104 // there would be a damaged rect at the top (from scroll) and at the
1105 // bottom (from toolbar).
1106 pending->push_back(dirty_in_screen);
1107 continue;
1111 if (progressive == -1) {
1112 progressive = StartPaint(index, dirty_in_screen);
1113 progressive_paint_timeout_ = kMaxInitialProgressivePaintTimeMs;
1114 } else {
1115 progressive_paint_timeout_ = kMaxProgressivePaintTimeMs;
1118 progressive_paints_[progressive].painted_ = true;
1119 if (ContinuePaint(progressive, image_data)) {
1120 FinishPaint(progressive, image_data);
1121 ready->push_back(dirty_in_screen);
1122 } else {
1123 pending->push_back(dirty_in_screen);
1125 } else {
1126 PaintUnavailablePage(index, dirty_in_screen, image_data);
1127 ready->push_back(dirty_in_screen);
1132 void PDFiumEngine::PostPaint() {
1133 for (size_t i = 0; i < progressive_paints_.size(); ++i) {
1134 if (progressive_paints_[i].painted_)
1135 continue;
1137 // This rectangle must have been merged with another one, that's why we
1138 // weren't asked to paint it. Remove it or otherwise we'll never finish
1139 // painting.
1140 FPDF_RenderPage_Close(
1141 pages_[progressive_paints_[i].page_index]->GetPage());
1142 FPDFBitmap_Destroy(progressive_paints_[i].bitmap);
1143 progressive_paints_.erase(progressive_paints_.begin() + i);
1144 --i;
1148 bool PDFiumEngine::HandleDocumentLoad(const pp::URLLoader& loader) {
1149 password_tries_remaining_ = kMaxPasswordTries;
1150 return doc_loader_.Init(loader, url_, headers_);
1153 pp::Instance* PDFiumEngine::GetPluginInstance() {
1154 return client_->GetPluginInstance();
1157 pp::URLLoader PDFiumEngine::CreateURLLoader() {
1158 return client_->CreateURLLoader();
1161 void PDFiumEngine::AppendPage(PDFEngine* engine, int index) {
1162 // Unload and delete the blank page before appending.
1163 pages_[index]->Unload();
1164 pages_[index]->set_calculated_links(false);
1165 pp::Size curr_page_size = GetPageSize(index);
1166 FPDFPage_Delete(doc_, index);
1167 FPDF_ImportPages(doc_,
1168 static_cast<PDFiumEngine*>(engine)->doc(),
1169 "1",
1170 index);
1171 pp::Size new_page_size = GetPageSize(index);
1172 if (curr_page_size != new_page_size)
1173 LoadPageInfo(true);
1174 client_->Invalidate(GetPageScreenRect(index));
1177 pp::Point PDFiumEngine::GetScrollPosition() {
1178 return position_;
1181 void PDFiumEngine::SetScrollPosition(const pp::Point& position) {
1182 position_ = position;
1185 bool PDFiumEngine::IsProgressiveLoad() {
1186 return doc_loader_.is_partial_document();
1189 std::string PDFiumEngine::GetMetadata(const std::string& key) {
1190 return GetDocumentMetadata(doc(), key);
1193 void PDFiumEngine::OnPartialDocumentLoaded() {
1194 file_access_.m_FileLen = doc_loader_.document_size();
1195 fpdf_availability_ = FPDFAvail_Create(&file_availability_, &file_access_);
1196 DCHECK(fpdf_availability_);
1198 // Currently engine does not deal efficiently with some non-linearized files.
1199 // See http://code.google.com/p/chromium/issues/detail?id=59400
1200 // To improve user experience we download entire file for non-linearized PDF.
1201 if (!FPDFAvail_IsLinearized(fpdf_availability_)) {
1202 doc_loader_.RequestData(0, doc_loader_.document_size());
1203 return;
1206 LoadDocument();
1209 void PDFiumEngine::OnPendingRequestComplete() {
1210 if (!doc_ || !form_) {
1211 LoadDocument();
1212 return;
1215 // LoadDocument() will result in |pending_pages_| being reset so there's no
1216 // need to run the code below in that case.
1217 bool update_pages = false;
1218 std::vector<int> still_pending;
1219 for (size_t i = 0; i < pending_pages_.size(); ++i) {
1220 if (CheckPageAvailable(pending_pages_[i], &still_pending)) {
1221 update_pages = true;
1222 if (IsPageVisible(pending_pages_[i]))
1223 client_->Invalidate(GetPageScreenRect(pending_pages_[i]));
1226 pending_pages_.swap(still_pending);
1227 if (update_pages)
1228 LoadPageInfo(true);
1231 void PDFiumEngine::OnNewDataAvailable() {
1232 client_->DocumentLoadProgress(doc_loader_.GetAvailableData(),
1233 doc_loader_.document_size());
1236 void PDFiumEngine::OnDocumentComplete() {
1237 if (!doc_ || !form_) {
1238 file_access_.m_FileLen = doc_loader_.document_size();
1239 LoadDocument();
1240 return;
1243 bool need_update = false;
1244 for (size_t i = 0; i < pages_.size(); ++i) {
1245 if (pages_[i]->available())
1246 continue;
1248 pages_[i]->set_available(true);
1249 // We still need to call IsPageAvail() even if the whole document is
1250 // already downloaded.
1251 FPDFAvail_IsPageAvail(fpdf_availability_, i, &download_hints_);
1252 need_update = true;
1253 if (IsPageVisible(i))
1254 client_->Invalidate(GetPageScreenRect(i));
1256 if (need_update)
1257 LoadPageInfo(true);
1259 FinishLoadingDocument();
1262 void PDFiumEngine::FinishLoadingDocument() {
1263 DCHECK(doc_loader_.IsDocumentComplete() && doc_);
1264 if (called_do_document_action_)
1265 return;
1266 called_do_document_action_ = true;
1268 // These can only be called now, as the JS might end up needing a page.
1269 FORM_DoDocumentJSAction(form_);
1270 FORM_DoDocumentOpenAction(form_);
1271 if (most_visible_page_ != -1) {
1272 FPDF_PAGE new_page = pages_[most_visible_page_]->GetPage();
1273 FORM_DoPageAAction(new_page, form_, FPDFPAGE_AACTION_OPEN);
1276 if (doc_) // This can only happen if loading |doc_| fails.
1277 client_->DocumentLoadComplete(pages_.size());
1280 void PDFiumEngine::UnsupportedFeature(int type) {
1281 std::string feature;
1282 switch (type) {
1283 #ifndef PDF_USE_XFA
1284 case FPDF_UNSP_DOC_XFAFORM:
1285 feature = "XFA";
1286 break;
1287 #endif
1288 case FPDF_UNSP_DOC_PORTABLECOLLECTION:
1289 feature = "Portfolios_Packages";
1290 break;
1291 case FPDF_UNSP_DOC_ATTACHMENT:
1292 case FPDF_UNSP_ANNOT_ATTACHMENT:
1293 feature = "Attachment";
1294 break;
1295 case FPDF_UNSP_DOC_SECURITY:
1296 feature = "Rights_Management";
1297 break;
1298 case FPDF_UNSP_DOC_SHAREDREVIEW:
1299 feature = "Shared_Review";
1300 break;
1301 case FPDF_UNSP_DOC_SHAREDFORM_ACROBAT:
1302 case FPDF_UNSP_DOC_SHAREDFORM_FILESYSTEM:
1303 case FPDF_UNSP_DOC_SHAREDFORM_EMAIL:
1304 feature = "Shared_Form";
1305 break;
1306 case FPDF_UNSP_ANNOT_3DANNOT:
1307 feature = "3D";
1308 break;
1309 case FPDF_UNSP_ANNOT_MOVIE:
1310 feature = "Movie";
1311 break;
1312 case FPDF_UNSP_ANNOT_SOUND:
1313 feature = "Sound";
1314 break;
1315 case FPDF_UNSP_ANNOT_SCREEN_MEDIA:
1316 case FPDF_UNSP_ANNOT_SCREEN_RICHMEDIA:
1317 feature = "Screen";
1318 break;
1319 case FPDF_UNSP_ANNOT_SIG:
1320 feature = "Digital_Signature";
1321 break;
1323 client_->DocumentHasUnsupportedFeature(feature);
1326 void PDFiumEngine::ContinueFind(int32_t result) {
1327 StartFind(current_find_text_.c_str(), !!result);
1330 bool PDFiumEngine::HandleEvent(const pp::InputEvent& event) {
1331 DCHECK(!defer_page_unload_);
1332 defer_page_unload_ = true;
1333 bool rv = false;
1334 switch (event.GetType()) {
1335 case PP_INPUTEVENT_TYPE_MOUSEDOWN:
1336 rv = OnMouseDown(pp::MouseInputEvent(event));
1337 break;
1338 case PP_INPUTEVENT_TYPE_MOUSEUP:
1339 rv = OnMouseUp(pp::MouseInputEvent(event));
1340 break;
1341 case PP_INPUTEVENT_TYPE_MOUSEMOVE:
1342 rv = OnMouseMove(pp::MouseInputEvent(event));
1343 break;
1344 case PP_INPUTEVENT_TYPE_KEYDOWN:
1345 rv = OnKeyDown(pp::KeyboardInputEvent(event));
1346 break;
1347 case PP_INPUTEVENT_TYPE_KEYUP:
1348 rv = OnKeyUp(pp::KeyboardInputEvent(event));
1349 break;
1350 case PP_INPUTEVENT_TYPE_CHAR:
1351 rv = OnChar(pp::KeyboardInputEvent(event));
1352 break;
1353 default:
1354 break;
1357 DCHECK(defer_page_unload_);
1358 defer_page_unload_ = false;
1359 for (size_t i = 0; i < deferred_page_unloads_.size(); ++i)
1360 pages_[deferred_page_unloads_[i]]->Unload();
1361 deferred_page_unloads_.clear();
1362 return rv;
1365 uint32_t PDFiumEngine::QuerySupportedPrintOutputFormats() {
1366 if (!HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY))
1367 return 0;
1368 return PP_PRINTOUTPUTFORMAT_PDF;
1371 void PDFiumEngine::PrintBegin() {
1372 FORM_DoDocumentAAction(form_, FPDFDOC_AACTION_WP);
1375 pp::Resource PDFiumEngine::PrintPages(
1376 const PP_PrintPageNumberRange_Dev* page_ranges, uint32_t page_range_count,
1377 const PP_PrintSettings_Dev& print_settings) {
1378 if (HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY))
1379 return PrintPagesAsPDF(page_ranges, page_range_count, print_settings);
1380 else if (HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY))
1381 return PrintPagesAsRasterPDF(page_ranges, page_range_count, print_settings);
1382 return pp::Resource();
1385 FPDF_DOCUMENT PDFiumEngine::CreateSinglePageRasterPdf(
1386 double source_page_width,
1387 double source_page_height,
1388 const PP_PrintSettings_Dev& print_settings,
1389 PDFiumPage* page_to_print) {
1390 FPDF_DOCUMENT temp_doc = FPDF_CreateNewDocument();
1391 if (!temp_doc)
1392 return temp_doc;
1394 const pp::Size& bitmap_size(page_to_print->rect().size());
1396 FPDF_PAGE temp_page =
1397 FPDFPage_New(temp_doc, 0, source_page_width, source_page_height);
1399 pp::ImageData image = pp::ImageData(client_->GetPluginInstance(),
1400 PP_IMAGEDATAFORMAT_BGRA_PREMUL,
1401 bitmap_size,
1402 false);
1404 FPDF_BITMAP bitmap = FPDFBitmap_CreateEx(bitmap_size.width(),
1405 bitmap_size.height(),
1406 FPDFBitmap_BGRx,
1407 image.data(),
1408 image.stride());
1410 // Clear the bitmap
1411 FPDFBitmap_FillRect(
1412 bitmap, 0, 0, bitmap_size.width(), bitmap_size.height(), 0xFFFFFFFF);
1414 pp::Rect page_rect = page_to_print->rect();
1415 FPDF_RenderPageBitmap(bitmap,
1416 page_to_print->GetPrintPage(),
1417 page_rect.x(),
1418 page_rect.y(),
1419 page_rect.width(),
1420 page_rect.height(),
1421 print_settings.orientation,
1422 FPDF_ANNOT | FPDF_PRINTING | FPDF_NO_CATCH);
1424 double ratio_x = ConvertUnitDouble(bitmap_size.width(),
1425 print_settings.dpi,
1426 kPointsPerInch);
1427 double ratio_y = ConvertUnitDouble(bitmap_size.height(),
1428 print_settings.dpi,
1429 kPointsPerInch);
1431 // Add the bitmap to an image object and add the image object to the output
1432 // page.
1433 FPDF_PAGEOBJECT temp_img = FPDFPageObj_NewImgeObj(temp_doc);
1434 FPDFImageObj_SetBitmap(&temp_page, 1, temp_img, bitmap);
1435 FPDFImageObj_SetMatrix(temp_img, ratio_x, 0, 0, ratio_y, 0, 0);
1436 FPDFPage_InsertObject(temp_page, temp_img);
1437 FPDFPage_GenerateContent(temp_page);
1438 FPDF_ClosePage(temp_page);
1440 page_to_print->ClosePrintPage();
1441 FPDFBitmap_Destroy(bitmap);
1443 return temp_doc;
1446 pp::Buffer_Dev PDFiumEngine::PrintPagesAsRasterPDF(
1447 const PP_PrintPageNumberRange_Dev* page_ranges, uint32_t page_range_count,
1448 const PP_PrintSettings_Dev& print_settings) {
1449 if (!page_range_count)
1450 return pp::Buffer_Dev();
1452 // If document is not downloaded yet, disable printing.
1453 if (doc_ && !doc_loader_.IsDocumentComplete())
1454 return pp::Buffer_Dev();
1456 FPDF_DOCUMENT output_doc = FPDF_CreateNewDocument();
1457 if (!output_doc)
1458 return pp::Buffer_Dev();
1460 SaveSelectedFormForPrint();
1462 std::vector<PDFiumPage> pages_to_print;
1463 // width and height of source PDF pages.
1464 std::vector<std::pair<double, double> > source_page_sizes;
1465 // Collect pages to print and sizes of source pages.
1466 std::vector<uint32_t> page_numbers =
1467 GetPageNumbersFromPrintPageNumberRange(page_ranges, page_range_count);
1468 for (size_t i = 0; i < page_numbers.size(); ++i) {
1469 uint32_t page_number = page_numbers[i];
1470 FPDF_PAGE pdf_page = FPDF_LoadPage(doc_, page_number);
1471 double source_page_width = FPDF_GetPageWidth(pdf_page);
1472 double source_page_height = FPDF_GetPageHeight(pdf_page);
1473 source_page_sizes.push_back(std::make_pair(source_page_width,
1474 source_page_height));
1476 int width_in_pixels = ConvertUnit(source_page_width,
1477 kPointsPerInch,
1478 print_settings.dpi);
1479 int height_in_pixels = ConvertUnit(source_page_height,
1480 kPointsPerInch,
1481 print_settings.dpi);
1483 pp::Rect rect(width_in_pixels, height_in_pixels);
1484 pages_to_print.push_back(PDFiumPage(this, page_number, rect, true));
1485 FPDF_ClosePage(pdf_page);
1488 #if defined(OS_LINUX)
1489 g_last_instance_id = client_->GetPluginInstance()->pp_instance();
1490 #endif
1492 size_t i = 0;
1493 for (; i < pages_to_print.size(); ++i) {
1494 double source_page_width = source_page_sizes[i].first;
1495 double source_page_height = source_page_sizes[i].second;
1497 // Use temp_doc to compress image by saving PDF to buffer.
1498 FPDF_DOCUMENT temp_doc = CreateSinglePageRasterPdf(source_page_width,
1499 source_page_height,
1500 print_settings,
1501 &pages_to_print[i]);
1503 if (!temp_doc)
1504 break;
1506 pp::Buffer_Dev buffer = GetFlattenedPrintData(temp_doc);
1507 FPDF_CloseDocument(temp_doc);
1509 PDFiumMemBufferFileRead file_read(buffer.data(), buffer.size());
1510 temp_doc = FPDF_LoadCustomDocument(&file_read, NULL);
1512 FPDF_BOOL imported = FPDF_ImportPages(output_doc, temp_doc, "1", i);
1513 FPDF_CloseDocument(temp_doc);
1514 if (!imported)
1515 break;
1518 pp::Buffer_Dev buffer;
1519 if (i == pages_to_print.size()) {
1520 FPDF_CopyViewerPreferences(output_doc, doc_);
1521 FitContentsToPrintableAreaIfRequired(output_doc, print_settings);
1522 // Now flatten all the output pages.
1523 buffer = GetFlattenedPrintData(output_doc);
1525 FPDF_CloseDocument(output_doc);
1526 return buffer;
1529 pp::Buffer_Dev PDFiumEngine::GetFlattenedPrintData(const FPDF_DOCUMENT& doc) {
1530 int page_count = FPDF_GetPageCount(doc);
1531 bool flatten_succeeded = true;
1532 for (int i = 0; i < page_count; ++i) {
1533 FPDF_PAGE page = FPDF_LoadPage(doc, i);
1534 DCHECK(page);
1535 if (page) {
1536 int flatten_ret = FPDFPage_Flatten(page, FLAT_PRINT);
1537 FPDF_ClosePage(page);
1538 if (flatten_ret == FLATTEN_FAIL) {
1539 flatten_succeeded = false;
1540 break;
1542 } else {
1543 flatten_succeeded = false;
1544 break;
1547 if (!flatten_succeeded) {
1548 FPDF_CloseDocument(doc);
1549 return pp::Buffer_Dev();
1552 pp::Buffer_Dev buffer;
1553 PDFiumMemBufferFileWrite output_file_write;
1554 if (FPDF_SaveAsCopy(doc, &output_file_write, 0)) {
1555 buffer = pp::Buffer_Dev(
1556 client_->GetPluginInstance(), output_file_write.size());
1557 if (!buffer.is_null()) {
1558 memcpy(buffer.data(), output_file_write.buffer().c_str(),
1559 output_file_write.size());
1562 return buffer;
1565 pp::Buffer_Dev PDFiumEngine::PrintPagesAsPDF(
1566 const PP_PrintPageNumberRange_Dev* page_ranges, uint32_t page_range_count,
1567 const PP_PrintSettings_Dev& print_settings) {
1568 if (!page_range_count)
1569 return pp::Buffer_Dev();
1571 DCHECK(doc_);
1572 FPDF_DOCUMENT output_doc = FPDF_CreateNewDocument();
1573 if (!output_doc)
1574 return pp::Buffer_Dev();
1576 SaveSelectedFormForPrint();
1578 std::string page_number_str;
1579 for (uint32_t index = 0; index < page_range_count; ++index) {
1580 if (!page_number_str.empty())
1581 page_number_str.append(",");
1582 page_number_str.append(
1583 base::IntToString(page_ranges[index].first_page_number + 1));
1584 if (page_ranges[index].first_page_number !=
1585 page_ranges[index].last_page_number) {
1586 page_number_str.append("-");
1587 page_number_str.append(
1588 base::IntToString(page_ranges[index].last_page_number + 1));
1592 std::vector<uint32_t> page_numbers =
1593 GetPageNumbersFromPrintPageNumberRange(page_ranges, page_range_count);
1594 for (size_t i = 0; i < page_numbers.size(); ++i) {
1595 uint32_t page_number = page_numbers[i];
1596 pages_[page_number]->GetPage();
1597 if (!IsPageVisible(page_numbers[i]))
1598 pages_[page_number]->Unload();
1601 FPDF_CopyViewerPreferences(output_doc, doc_);
1602 if (!FPDF_ImportPages(output_doc, doc_, page_number_str.c_str(), 0)) {
1603 FPDF_CloseDocument(output_doc);
1604 return pp::Buffer_Dev();
1607 FitContentsToPrintableAreaIfRequired(output_doc, print_settings);
1609 // Now flatten all the output pages.
1610 pp::Buffer_Dev buffer = GetFlattenedPrintData(output_doc);
1611 FPDF_CloseDocument(output_doc);
1612 return buffer;
1615 void PDFiumEngine::FitContentsToPrintableAreaIfRequired(
1616 const FPDF_DOCUMENT& doc, const PP_PrintSettings_Dev& print_settings) {
1617 // Check to see if we need to fit pdf contents to printer paper size.
1618 if (print_settings.print_scaling_option !=
1619 PP_PRINTSCALINGOPTION_SOURCE_SIZE) {
1620 int num_pages = FPDF_GetPageCount(doc);
1621 // In-place transformation is more efficient than creating a new
1622 // transformed document from the source document. Therefore, transform
1623 // every page to fit the contents in the selected printer paper.
1624 for (int i = 0; i < num_pages; ++i) {
1625 FPDF_PAGE page = FPDF_LoadPage(doc, i);
1626 TransformPDFPageForPrinting(page, print_settings);
1627 FPDF_ClosePage(page);
1632 void PDFiumEngine::SaveSelectedFormForPrint() {
1633 FORM_ForceToKillFocus(form_);
1634 client_->FormTextFieldFocusChange(false);
1637 void PDFiumEngine::PrintEnd() {
1638 FORM_DoDocumentAAction(form_, FPDFDOC_AACTION_DP);
1641 PDFiumPage::Area PDFiumEngine::GetCharIndex(const pp::MouseInputEvent& event,
1642 int* page_index,
1643 int* char_index,
1644 int* form_type,
1645 PDFiumPage::LinkTarget* target) {
1646 // First figure out which page this is in.
1647 pp::Point mouse_point = event.GetPosition();
1648 return GetCharIndex(mouse_point, page_index, char_index, form_type, target);
1651 PDFiumPage::Area PDFiumEngine::GetCharIndex(const pp::Point& point,
1652 int* page_index,
1653 int* char_index,
1654 int* form_type,
1655 PDFiumPage::LinkTarget* target) {
1656 int page = -1;
1657 pp::Point point_in_page(
1658 static_cast<int>((point.x() + position_.x()) / current_zoom_),
1659 static_cast<int>((point.y() + position_.y()) / current_zoom_));
1660 for (size_t i = 0; i < visible_pages_.size(); ++i) {
1661 if (pages_[visible_pages_[i]]->rect().Contains(point_in_page)) {
1662 page = visible_pages_[i];
1663 break;
1666 if (page == -1)
1667 return PDFiumPage::NONSELECTABLE_AREA;
1669 // If the page hasn't finished rendering, calling into the page sometimes
1670 // leads to hangs.
1671 for (size_t i = 0; i < progressive_paints_.size(); ++i) {
1672 if (progressive_paints_[i].page_index == page)
1673 return PDFiumPage::NONSELECTABLE_AREA;
1676 *page_index = page;
1677 return pages_[page]->GetCharIndex(
1678 point_in_page, current_rotation_, char_index, form_type, target);
1681 bool PDFiumEngine::OnMouseDown(const pp::MouseInputEvent& event) {
1682 if (event.GetButton() == PP_INPUTEVENT_MOUSEBUTTON_RIGHT) {
1683 if (!selection_.size())
1684 return false;
1685 std::vector<pp::Rect> selection_rect_vector;
1686 GetAllScreenRectsUnion(&selection_, GetVisibleRect().point(),
1687 &selection_rect_vector);
1688 pp::Point point = event.GetPosition();
1689 for (size_t i = 0; i < selection_rect_vector.size(); ++i) {
1690 if (selection_rect_vector[i].Contains(point.x(), point.y()))
1691 return false;
1693 SelectionChangeInvalidator selection_invalidator(this);
1694 selection_.clear();
1695 return true;
1697 if (event.GetButton() != PP_INPUTEVENT_MOUSEBUTTON_LEFT)
1698 return false;
1700 SelectionChangeInvalidator selection_invalidator(this);
1701 selection_.clear();
1703 int page_index = -1;
1704 int char_index = -1;
1705 int form_type = FPDF_FORMFIELD_UNKNOWN;
1706 PDFiumPage::LinkTarget target;
1707 PDFiumPage::Area area =
1708 GetCharIndex(event, &page_index, &char_index, &form_type, &target);
1709 mouse_down_state_.Set(area, target);
1711 // Decide whether to open link or not based on user action in mouse up and
1712 // mouse move events.
1713 if (area == PDFiumPage::WEBLINK_AREA)
1714 return true;
1716 if (area == PDFiumPage::DOCLINK_AREA) {
1717 client_->ScrollToPage(target.page);
1718 client_->FormTextFieldFocusChange(false);
1719 return true;
1722 if (page_index != -1) {
1723 last_page_mouse_down_ = page_index;
1724 double page_x, page_y;
1725 pp::Point point = event.GetPosition();
1726 DeviceToPage(page_index, point.x(), point.y(), &page_x, &page_y);
1728 FORM_OnLButtonDown(form_, pages_[page_index]->GetPage(), 0, page_x, page_y);
1729 if (form_type > FPDF_FORMFIELD_UNKNOWN) { // returns -1 sometimes...
1730 mouse_down_state_.Set(PDFiumPage::NONSELECTABLE_AREA, target);
1731 bool is_valid_control = (form_type == FPDF_FORMFIELD_TEXTFIELD ||
1732 form_type == FPDF_FORMFIELD_COMBOBOX);
1733 #ifdef PDF_USE_XFA
1734 is_valid_control |= (form_type == FPDF_FORMFIELD_XFA);
1735 #endif
1736 client_->FormTextFieldFocusChange(is_valid_control);
1737 return true; // Return now before we get into the selection code.
1741 client_->FormTextFieldFocusChange(false);
1743 if (area != PDFiumPage::TEXT_AREA)
1744 return true; // Return true so WebKit doesn't do its own highlighting.
1746 if (event.GetClickCount() == 1) {
1747 OnSingleClick(page_index, char_index);
1748 } else if (event.GetClickCount() == 2 ||
1749 event.GetClickCount() == 3) {
1750 OnMultipleClick(event.GetClickCount(), page_index, char_index);
1753 return true;
1756 void PDFiumEngine::OnSingleClick(int page_index, int char_index) {
1757 SetSelecting(true);
1758 selection_.push_back(PDFiumRange(pages_[page_index], char_index, 0));
1761 void PDFiumEngine::OnMultipleClick(int click_count,
1762 int page_index,
1763 int char_index) {
1764 // It would be more efficient if the SDK could support finding a space, but
1765 // now it doesn't.
1766 int start_index = char_index;
1767 do {
1768 base::char16 cur = pages_[page_index]->GetCharAtIndex(start_index);
1769 // For double click, we want to select one word so we look for whitespace
1770 // boundaries. For triple click, we want the whole line.
1771 if (cur == '\n' || (click_count == 2 && (cur == ' ' || cur == '\t')))
1772 break;
1773 } while (--start_index >= 0);
1774 if (start_index)
1775 start_index++;
1777 int end_index = char_index;
1778 int total = pages_[page_index]->GetCharCount();
1779 while (end_index++ <= total) {
1780 base::char16 cur = pages_[page_index]->GetCharAtIndex(end_index);
1781 if (cur == '\n' || (click_count == 2 && (cur == ' ' || cur == '\t')))
1782 break;
1785 selection_.push_back(PDFiumRange(
1786 pages_[page_index], start_index, end_index - start_index));
1789 bool PDFiumEngine::OnMouseUp(const pp::MouseInputEvent& event) {
1790 if (event.GetButton() != PP_INPUTEVENT_MOUSEBUTTON_LEFT)
1791 return false;
1793 int page_index = -1;
1794 int char_index = -1;
1795 int form_type = FPDF_FORMFIELD_UNKNOWN;
1796 PDFiumPage::LinkTarget target;
1797 PDFiumPage::Area area =
1798 GetCharIndex(event, &page_index, &char_index, &form_type, &target);
1800 // Open link on mouse up for same link for which mouse down happened earlier.
1801 if (mouse_down_state_.Matches(area, target)) {
1802 if (area == PDFiumPage::WEBLINK_AREA) {
1803 bool open_in_new_tab = !!(event.GetModifiers() & kDefaultKeyModifier);
1804 client_->NavigateTo(target.url, open_in_new_tab);
1805 client_->FormTextFieldFocusChange(false);
1806 return true;
1810 if (page_index != -1) {
1811 double page_x, page_y;
1812 pp::Point point = event.GetPosition();
1813 DeviceToPage(page_index, point.x(), point.y(), &page_x, &page_y);
1814 FORM_OnLButtonUp(
1815 form_, pages_[page_index]->GetPage(), 0, page_x, page_y);
1818 if (!selecting_)
1819 return false;
1821 SetSelecting(false);
1822 return true;
1825 bool PDFiumEngine::OnMouseMove(const pp::MouseInputEvent& event) {
1826 int page_index = -1;
1827 int char_index = -1;
1828 int form_type = FPDF_FORMFIELD_UNKNOWN;
1829 PDFiumPage::LinkTarget target;
1830 PDFiumPage::Area area =
1831 GetCharIndex(event, &page_index, &char_index, &form_type, &target);
1833 // Clear |mouse_down_state_| if mouse moves away from where the mouse down
1834 // happened.
1835 if (!mouse_down_state_.Matches(area, target))
1836 mouse_down_state_.Reset();
1838 if (!selecting_) {
1839 PP_CursorType_Dev cursor;
1840 switch (area) {
1841 case PDFiumPage::TEXT_AREA:
1842 cursor = PP_CURSORTYPE_IBEAM;
1843 break;
1844 case PDFiumPage::WEBLINK_AREA:
1845 case PDFiumPage::DOCLINK_AREA:
1846 cursor = PP_CURSORTYPE_HAND;
1847 break;
1848 case PDFiumPage::NONSELECTABLE_AREA:
1849 default:
1850 switch (form_type) {
1851 case FPDF_FORMFIELD_PUSHBUTTON:
1852 case FPDF_FORMFIELD_CHECKBOX:
1853 case FPDF_FORMFIELD_RADIOBUTTON:
1854 case FPDF_FORMFIELD_COMBOBOX:
1855 case FPDF_FORMFIELD_LISTBOX:
1856 cursor = PP_CURSORTYPE_HAND;
1857 break;
1858 case FPDF_FORMFIELD_TEXTFIELD:
1859 cursor = PP_CURSORTYPE_IBEAM;
1860 break;
1861 default:
1862 cursor = PP_CURSORTYPE_POINTER;
1863 break;
1865 break;
1868 if (page_index != -1) {
1869 double page_x, page_y;
1870 pp::Point point = event.GetPosition();
1871 DeviceToPage(page_index, point.x(), point.y(), &page_x, &page_y);
1872 FORM_OnMouseMove(form_, pages_[page_index]->GetPage(), 0, page_x, page_y);
1875 client_->UpdateCursor(cursor);
1876 pp::Point point = event.GetPosition();
1877 std::string url = GetLinkAtPosition(event.GetPosition());
1878 if (url != link_under_cursor_) {
1879 link_under_cursor_ = url;
1880 pp::PDF::SetLinkUnderCursor(GetPluginInstance(), url.c_str());
1882 // No need to swallow the event, since this might interfere with the
1883 // scrollbars if the user is dragging them.
1884 return false;
1887 // We're selecting but right now we're not over text, so don't change the
1888 // current selection.
1889 if (area != PDFiumPage::TEXT_AREA && area != PDFiumPage::WEBLINK_AREA &&
1890 area != PDFiumPage::DOCLINK_AREA) {
1891 return false;
1894 SelectionChangeInvalidator selection_invalidator(this);
1896 // Check if the user has descreased their selection area and we need to remove
1897 // pages from selection_.
1898 for (size_t i = 0; i < selection_.size(); ++i) {
1899 if (selection_[i].page_index() == page_index) {
1900 // There should be no other pages after this.
1901 selection_.erase(selection_.begin() + i + 1, selection_.end());
1902 break;
1906 if (selection_.size() == 0)
1907 return false;
1909 int last = selection_.size() - 1;
1910 if (selection_[last].page_index() == page_index) {
1911 // Selecting within a page.
1912 int count;
1913 if (char_index >= selection_[last].char_index()) {
1914 // Selecting forward.
1915 count = char_index - selection_[last].char_index() + 1;
1916 } else {
1917 count = char_index - selection_[last].char_index() - 1;
1919 selection_[last].SetCharCount(count);
1920 } else if (selection_[last].page_index() < page_index) {
1921 // Selecting into the next page.
1923 // First make sure that there are no gaps in selection, i.e. if mousedown on
1924 // page one but we only get mousemove over page three, we want page two.
1925 for (int i = selection_[last].page_index() + 1; i < page_index; ++i) {
1926 selection_.push_back(PDFiumRange(pages_[i], 0,
1927 pages_[i]->GetCharCount()));
1930 int count = pages_[selection_[last].page_index()]->GetCharCount();
1931 selection_[last].SetCharCount(count - selection_[last].char_index());
1932 selection_.push_back(PDFiumRange(pages_[page_index], 0, char_index));
1933 } else {
1934 // Selecting into the previous page.
1935 // The selection's char_index is 0-based, so the character count is one
1936 // more than the index. The character count needs to be negative to
1937 // indicate a backwards selection.
1938 selection_[last].SetCharCount(-(selection_[last].char_index() + 1));
1940 // First make sure that there are no gaps in selection, i.e. if mousedown on
1941 // page three but we only get mousemove over page one, we want page two.
1942 for (int i = selection_[last].page_index() - 1; i > page_index; --i) {
1943 selection_.push_back(PDFiumRange(pages_[i], 0,
1944 pages_[i]->GetCharCount()));
1947 int count = pages_[page_index]->GetCharCount();
1948 selection_.push_back(
1949 PDFiumRange(pages_[page_index], count, count - char_index));
1952 return true;
1955 bool PDFiumEngine::OnKeyDown(const pp::KeyboardInputEvent& event) {
1956 if (last_page_mouse_down_ == -1)
1957 return false;
1959 bool rv = !!FORM_OnKeyDown(
1960 form_, pages_[last_page_mouse_down_]->GetPage(),
1961 event.GetKeyCode(), event.GetModifiers());
1963 if (event.GetKeyCode() == ui::VKEY_BACK ||
1964 event.GetKeyCode() == ui::VKEY_ESCAPE) {
1965 // Chrome doesn't send char events for backspace or escape keys, see
1966 // PlatformKeyboardEventBuilder::isCharacterKey() and
1967 // http://chrome-corpsvn.mtv.corp.google.com/viewvc?view=rev&root=chrome&revision=31805
1968 // for more information. So just fake one since PDFium uses it.
1969 std::string str;
1970 str.push_back(event.GetKeyCode());
1971 pp::KeyboardInputEvent synthesized(pp::KeyboardInputEvent(
1972 client_->GetPluginInstance(),
1973 PP_INPUTEVENT_TYPE_CHAR,
1974 event.GetTimeStamp(),
1975 event.GetModifiers(),
1976 event.GetKeyCode(),
1977 str));
1978 OnChar(synthesized);
1981 return rv;
1984 bool PDFiumEngine::OnKeyUp(const pp::KeyboardInputEvent& event) {
1985 if (last_page_mouse_down_ == -1)
1986 return false;
1988 return !!FORM_OnKeyUp(
1989 form_, pages_[last_page_mouse_down_]->GetPage(),
1990 event.GetKeyCode(), event.GetModifiers());
1993 bool PDFiumEngine::OnChar(const pp::KeyboardInputEvent& event) {
1994 if (last_page_mouse_down_ == -1)
1995 return false;
1997 base::string16 str = base::UTF8ToUTF16(event.GetCharacterText().AsString());
1998 return !!FORM_OnChar(
1999 form_, pages_[last_page_mouse_down_]->GetPage(),
2000 str[0],
2001 event.GetModifiers());
2004 void PDFiumEngine::StartFind(const char* text, bool case_sensitive) {
2005 // We can get a call to StartFind before we have any page information (i.e.
2006 // before the first call to LoadDocument has happened). Handle this case.
2007 if (pages_.empty())
2008 return;
2010 bool first_search = false;
2011 int character_to_start_searching_from = 0;
2012 if (current_find_text_ != text) { // First time we search for this text.
2013 first_search = true;
2014 std::vector<PDFiumRange> old_selection = selection_;
2015 StopFind();
2016 current_find_text_ = text;
2018 if (old_selection.empty()) {
2019 // Start searching from the beginning of the document.
2020 next_page_to_search_ = 0;
2021 last_page_to_search_ = pages_.size() - 1;
2022 last_character_index_to_search_ = -1;
2023 } else {
2024 // There's a current selection, so start from it.
2025 next_page_to_search_ = old_selection[0].page_index();
2026 last_character_index_to_search_ = old_selection[0].char_index();
2027 character_to_start_searching_from = old_selection[0].char_index();
2028 last_page_to_search_ = next_page_to_search_;
2032 int current_page = next_page_to_search_;
2034 if (pages_[current_page]->available()) {
2035 base::string16 str = base::UTF8ToUTF16(text);
2036 // Don't use PDFium to search for now, since it doesn't support unicode
2037 // text. Leave the code for now to avoid bit-rot, in case it's fixed later.
2038 if (0) {
2039 SearchUsingPDFium(
2040 str, case_sensitive, first_search, character_to_start_searching_from,
2041 current_page);
2042 } else {
2043 SearchUsingICU(
2044 str, case_sensitive, first_search, character_to_start_searching_from,
2045 current_page);
2048 if (!IsPageVisible(current_page))
2049 pages_[current_page]->Unload();
2052 if (next_page_to_search_ != last_page_to_search_ ||
2053 (first_search && last_character_index_to_search_ != -1)) {
2054 ++next_page_to_search_;
2057 if (next_page_to_search_ == static_cast<int>(pages_.size()))
2058 next_page_to_search_ = 0;
2059 // If there's only one page in the document and we start searching midway,
2060 // then we'll want to search the page one more time.
2061 bool end_of_search =
2062 next_page_to_search_ == last_page_to_search_ &&
2063 // Only one page but didn't start midway.
2064 ((pages_.size() == 1 && last_character_index_to_search_ == -1) ||
2065 // Started midway, but only 1 page and we already looped around.
2066 (pages_.size() == 1 && !first_search) ||
2067 // Started midway, and we've just looped around.
2068 (pages_.size() > 1 && current_page == next_page_to_search_));
2070 if (end_of_search) {
2071 // Send the final notification.
2072 client_->NotifyNumberOfFindResultsChanged(find_results_.size(), true);
2074 // When searching is complete, resume finding at a particular index.
2075 // Assuming the user has not clicked the find button in the meanwhile.
2076 if (resume_find_index_.valid() && !current_find_index_.valid()) {
2077 size_t resume_index = resume_find_index_.GetIndex();
2078 if (resume_index >= find_results_.size()) {
2079 // This might happen if the PDF has some dynamically generated text?
2080 resume_index = 0;
2082 current_find_index_.SetIndex(resume_index);
2083 client_->NotifySelectedFindResultChanged(resume_index);
2085 resume_find_index_.Invalidate();
2086 } else {
2087 pp::CompletionCallback callback =
2088 find_factory_.NewCallback(&PDFiumEngine::ContinueFind);
2089 pp::Module::Get()->core()->CallOnMainThread(
2090 0, callback, case_sensitive ? 1 : 0);
2094 void PDFiumEngine::SearchUsingPDFium(const base::string16& term,
2095 bool case_sensitive,
2096 bool first_search,
2097 int character_to_start_searching_from,
2098 int current_page) {
2099 // Find all the matches in the current page.
2100 unsigned long flags = case_sensitive ? FPDF_MATCHCASE : 0;
2101 FPDF_SCHHANDLE find = FPDFText_FindStart(
2102 pages_[current_page]->GetTextPage(),
2103 reinterpret_cast<const unsigned short*>(term.c_str()),
2104 flags, character_to_start_searching_from);
2106 // Note: since we search one page at a time, we don't find matches across
2107 // page boundaries. We could do this manually ourself, but it seems low
2108 // priority since Reader itself doesn't do it.
2109 while (FPDFText_FindNext(find)) {
2110 PDFiumRange result(pages_[current_page],
2111 FPDFText_GetSchResultIndex(find),
2112 FPDFText_GetSchCount(find));
2114 if (!first_search &&
2115 last_character_index_to_search_ != -1 &&
2116 result.page_index() == last_page_to_search_ &&
2117 result.char_index() >= last_character_index_to_search_) {
2118 break;
2121 AddFindResult(result);
2124 FPDFText_FindClose(find);
2127 void PDFiumEngine::SearchUsingICU(const base::string16& term,
2128 bool case_sensitive,
2129 bool first_search,
2130 int character_to_start_searching_from,
2131 int current_page) {
2132 base::string16 page_text;
2133 int text_length = pages_[current_page]->GetCharCount();
2134 if (character_to_start_searching_from) {
2135 text_length -= character_to_start_searching_from;
2136 } else if (!first_search &&
2137 last_character_index_to_search_ != -1 &&
2138 current_page == last_page_to_search_) {
2139 text_length = last_character_index_to_search_;
2141 if (text_length <= 0)
2142 return;
2144 PDFiumAPIStringBufferAdapter<base::string16> api_string_adapter(&page_text,
2145 text_length,
2146 false);
2147 unsigned short* data =
2148 reinterpret_cast<unsigned short*>(api_string_adapter.GetData());
2149 int written = FPDFText_GetText(pages_[current_page]->GetTextPage(),
2150 character_to_start_searching_from,
2151 text_length,
2152 data);
2153 api_string_adapter.Close(written);
2155 std::vector<PDFEngine::Client::SearchStringResult> results;
2156 client_->SearchString(
2157 page_text.c_str(), term.c_str(), case_sensitive, &results);
2158 for (size_t i = 0; i < results.size(); ++i) {
2159 // Need to map the indexes from the page text, which may have generated
2160 // characters like space etc, to character indices from the page.
2161 int temp_start = results[i].start_index + character_to_start_searching_from;
2162 int start = FPDFText_GetCharIndexFromTextIndex(
2163 pages_[current_page]->GetTextPage(), temp_start);
2164 int end = FPDFText_GetCharIndexFromTextIndex(
2165 pages_[current_page]->GetTextPage(),
2166 temp_start + results[i].length);
2167 AddFindResult(PDFiumRange(pages_[current_page], start, end - start));
2171 void PDFiumEngine::AddFindResult(const PDFiumRange& result) {
2172 // Figure out where to insert the new location, since we could have
2173 // started searching midway and now we wrapped.
2174 size_t result_index;
2175 int page_index = result.page_index();
2176 int char_index = result.char_index();
2177 for (result_index = 0; result_index < find_results_.size(); ++result_index) {
2178 if (find_results_[result_index].page_index() > page_index ||
2179 (find_results_[result_index].page_index() == page_index &&
2180 find_results_[result_index].char_index() > char_index)) {
2181 break;
2184 find_results_.insert(find_results_.begin() + result_index, result);
2185 UpdateTickMarks();
2187 if (current_find_index_.valid()) {
2188 if (result_index <= current_find_index_.GetIndex()) {
2189 // Update the current match index
2190 size_t find_index = current_find_index_.IncrementIndex();
2191 DCHECK_LT(find_index, find_results_.size());
2192 client_->NotifySelectedFindResultChanged(current_find_index_.GetIndex());
2194 } else if (!resume_find_index_.valid()) {
2195 // Both indices are invalid. Select the first match.
2196 SelectFindResult(true);
2198 client_->NotifyNumberOfFindResultsChanged(find_results_.size(), false);
2201 bool PDFiumEngine::SelectFindResult(bool forward) {
2202 if (find_results_.empty()) {
2203 NOTREACHED();
2204 return false;
2207 SelectionChangeInvalidator selection_invalidator(this);
2209 // Move back/forward through the search locations we previously found.
2210 size_t new_index;
2211 const size_t last_index = find_results_.size() - 1;
2212 if (current_find_index_.valid()) {
2213 size_t current_index = current_find_index_.GetIndex();
2214 if (forward) {
2215 new_index = (current_index >= last_index) ? 0 : current_index + 1;
2216 } else {
2217 new_index = (current_find_index_.GetIndex() == 0) ?
2218 last_index : current_index - 1;
2220 } else {
2221 new_index = forward ? 0 : last_index;
2223 current_find_index_.SetIndex(new_index);
2225 // Update the selection before telling the client to scroll, since it could
2226 // paint then.
2227 selection_.clear();
2228 selection_.push_back(find_results_[current_find_index_.GetIndex()]);
2230 // If the result is not in view, scroll to it.
2231 pp::Rect bounding_rect;
2232 pp::Rect visible_rect = GetVisibleRect();
2233 // Use zoom of 1.0 since visible_rect is without zoom.
2234 std::vector<pp::Rect> rects;
2235 rects = find_results_[current_find_index_.GetIndex()].GetScreenRects(
2236 pp::Point(), 1.0, current_rotation_);
2237 for (size_t i = 0; i < rects.size(); ++i)
2238 bounding_rect = bounding_rect.Union(rects[i]);
2239 if (!visible_rect.Contains(bounding_rect)) {
2240 pp::Point center = bounding_rect.CenterPoint();
2241 // Make the page centered.
2242 int new_y = static_cast<int>(center.y() * current_zoom_) -
2243 static_cast<int>(visible_rect.height() * current_zoom_ / 2);
2244 if (new_y < 0)
2245 new_y = 0;
2246 client_->ScrollToY(new_y);
2248 // Only move horizontally if it's not visible.
2249 if (center.x() < visible_rect.x() || center.x() > visible_rect.right()) {
2250 int new_x = static_cast<int>(center.x() * current_zoom_) -
2251 static_cast<int>(visible_rect.width() * current_zoom_ / 2);
2252 if (new_x < 0)
2253 new_x = 0;
2254 client_->ScrollToX(new_x);
2258 client_->NotifySelectedFindResultChanged(current_find_index_.GetIndex());
2259 return true;
2262 void PDFiumEngine::StopFind() {
2263 SelectionChangeInvalidator selection_invalidator(this);
2265 selection_.clear();
2266 selecting_ = false;
2267 find_results_.clear();
2268 next_page_to_search_ = -1;
2269 last_page_to_search_ = -1;
2270 last_character_index_to_search_ = -1;
2271 current_find_index_.Invalidate();
2272 current_find_text_.clear();
2273 UpdateTickMarks();
2274 find_factory_.CancelAll();
2277 void PDFiumEngine::GetAllScreenRectsUnion(std::vector<PDFiumRange>* rect_range,
2278 const pp::Point& offset_point,
2279 std::vector<pp::Rect>* rect_vector) {
2280 for (std::vector<PDFiumRange>::iterator it = rect_range->begin();
2281 it != rect_range->end(); ++it) {
2282 pp::Rect rect;
2283 std::vector<pp::Rect> rects =
2284 it->GetScreenRects(offset_point, current_zoom_, current_rotation_);
2285 for (size_t j = 0; j < rects.size(); ++j)
2286 rect = rect.Union(rects[j]);
2287 rect_vector->push_back(rect);
2291 void PDFiumEngine::UpdateTickMarks() {
2292 std::vector<pp::Rect> tickmarks;
2293 GetAllScreenRectsUnion(&find_results_, pp::Point(0, 0), &tickmarks);
2294 client_->UpdateTickMarks(tickmarks);
2297 void PDFiumEngine::ZoomUpdated(double new_zoom_level) {
2298 CancelPaints();
2300 current_zoom_ = new_zoom_level;
2302 CalculateVisiblePages();
2303 UpdateTickMarks();
2306 void PDFiumEngine::RotateClockwise() {
2307 current_rotation_ = (current_rotation_ + 1) % 4;
2308 RotateInternal();
2311 void PDFiumEngine::RotateCounterclockwise() {
2312 current_rotation_ = (current_rotation_ - 1) % 4;
2313 RotateInternal();
2316 void PDFiumEngine::InvalidateAllPages() {
2317 CancelPaints();
2318 StopFind();
2319 LoadPageInfo(true);
2320 client_->Invalidate(pp::Rect(plugin_size_));
2323 std::string PDFiumEngine::GetSelectedText() {
2324 if (!HasPermission(PDFEngine::PERMISSION_COPY))
2325 return std::string();
2327 base::string16 result;
2328 base::string16 new_line_char = base::UTF8ToUTF16("\n");
2329 for (size_t i = 0; i < selection_.size(); ++i) {
2330 if (i > 0 &&
2331 selection_[i - 1].page_index() > selection_[i].page_index()) {
2332 result = selection_[i].GetText() + new_line_char + result;
2333 } else {
2334 if (i > 0)
2335 result.append(new_line_char);
2336 result.append(selection_[i].GetText());
2340 FormatStringWithHyphens(&result);
2341 FormatStringForOS(&result);
2342 return base::UTF16ToUTF8(result);
2345 std::string PDFiumEngine::GetLinkAtPosition(const pp::Point& point) {
2346 std::string url;
2347 int temp;
2348 int page_index = -1;
2349 int form_type = FPDF_FORMFIELD_UNKNOWN;
2350 PDFiumPage::LinkTarget target;
2351 PDFiumPage::Area area =
2352 GetCharIndex(point, &page_index, &temp, &form_type, &target);
2353 if (area == PDFiumPage::WEBLINK_AREA)
2354 url = target.url;
2355 return url;
2358 bool PDFiumEngine::IsSelecting() {
2359 return selecting_;
2362 bool PDFiumEngine::HasPermission(DocumentPermission permission) const {
2363 // PDF 1.7 spec, section 3.5.2 says: "If the revision number is 2 or greater,
2364 // the operations to which user access can be controlled are as follows: ..."
2366 // Thus for revision numbers less than 2, permissions are ignored and this
2367 // always returns true.
2368 if (permissions_handler_revision_ < 2)
2369 return true;
2371 // Handle high quality printing permission separately for security handler
2372 // revision 3+. See table 3.20 in the PDF 1.7 spec.
2373 if (permission == PERMISSION_PRINT_HIGH_QUALITY &&
2374 permissions_handler_revision_ >= 3) {
2375 return (permissions_ & kPDFPermissionPrintLowQualityMask) != 0 &&
2376 (permissions_ & kPDFPermissionPrintHighQualityMask) != 0;
2379 switch (permission) {
2380 case PERMISSION_COPY:
2381 return (permissions_ & kPDFPermissionCopyMask) != 0;
2382 case PERMISSION_COPY_ACCESSIBLE:
2383 return (permissions_ & kPDFPermissionCopyAccessibleMask) != 0;
2384 case PERMISSION_PRINT_LOW_QUALITY:
2385 case PERMISSION_PRINT_HIGH_QUALITY:
2386 // With security handler revision 2 rules, check the same bit for high
2387 // and low quality. See table 3.20 in the PDF 1.7 spec.
2388 return (permissions_ & kPDFPermissionPrintLowQualityMask) != 0;
2389 default:
2390 return true;
2394 void PDFiumEngine::SelectAll() {
2395 SelectionChangeInvalidator selection_invalidator(this);
2397 selection_.clear();
2398 for (size_t i = 0; i < pages_.size(); ++i)
2399 if (pages_[i]->available()) {
2400 selection_.push_back(PDFiumRange(pages_[i], 0,
2401 pages_[i]->GetCharCount()));
2405 int PDFiumEngine::GetNumberOfPages() {
2406 return pages_.size();
2409 pp::VarArray PDFiumEngine::GetBookmarks() {
2410 pp::VarDictionary dict = TraverseBookmarks(doc_, NULL);
2411 // The root bookmark contains no useful information.
2412 return pp::VarArray(dict.Get(pp::Var("children")));
2415 int PDFiumEngine::GetNamedDestinationPage(const std::string& destination) {
2416 // Look for the destination.
2417 FPDF_DEST dest = FPDF_GetNamedDestByName(doc_, destination.c_str());
2418 if (!dest) {
2419 // Look for a bookmark with the same name.
2420 base::string16 destination_wide = base::UTF8ToUTF16(destination);
2421 FPDF_WIDESTRING destination_pdf_wide =
2422 reinterpret_cast<FPDF_WIDESTRING>(destination_wide.c_str());
2423 FPDF_BOOKMARK bookmark = FPDFBookmark_Find(doc_, destination_pdf_wide);
2424 if (!bookmark)
2425 return -1;
2426 dest = FPDFBookmark_GetDest(doc_, bookmark);
2428 return dest ? FPDFDest_GetPageIndex(doc_, dest) : -1;
2431 int PDFiumEngine::GetFirstVisiblePage() {
2432 CalculateVisiblePages();
2433 return first_visible_page_;
2436 int PDFiumEngine::GetMostVisiblePage() {
2437 CalculateVisiblePages();
2438 return most_visible_page_;
2441 pp::Rect PDFiumEngine::GetPageRect(int index) {
2442 pp::Rect rc(pages_[index]->rect());
2443 rc.Inset(-kPageShadowLeft, -kPageShadowTop,
2444 -kPageShadowRight, -kPageShadowBottom);
2445 return rc;
2448 pp::Rect PDFiumEngine::GetPageContentsRect(int index) {
2449 return GetScreenRect(pages_[index]->rect());
2452 void PDFiumEngine::PaintThumbnail(pp::ImageData* image_data, int index) {
2453 FPDF_BITMAP bitmap = FPDFBitmap_CreateEx(
2454 image_data->size().width(), image_data->size().height(),
2455 FPDFBitmap_BGRx, image_data->data(), image_data->stride());
2457 if (pages_[index]->available()) {
2458 FPDFBitmap_FillRect(bitmap, 0, 0, image_data->size().width(),
2459 image_data->size().height(), 0xFFFFFFFF);
2461 FPDF_RenderPageBitmap(
2462 bitmap, pages_[index]->GetPage(), 0, 0, image_data->size().width(),
2463 image_data->size().height(), 0, GetRenderingFlags());
2464 } else {
2465 FPDFBitmap_FillRect(bitmap, 0, 0, image_data->size().width(),
2466 image_data->size().height(), kPendingPageColor);
2469 FPDFBitmap_Destroy(bitmap);
2472 void PDFiumEngine::SetGrayscale(bool grayscale) {
2473 render_grayscale_ = grayscale;
2476 void PDFiumEngine::OnCallback(int id) {
2477 if (!timers_.count(id))
2478 return;
2480 timers_[id].second(id);
2481 if (timers_.count(id)) // The callback might delete the timer.
2482 client_->ScheduleCallback(id, timers_[id].first);
2485 std::string PDFiumEngine::GetPageAsJSON(int index) {
2486 if (!(HasPermission(PERMISSION_COPY) ||
2487 HasPermission(PERMISSION_COPY_ACCESSIBLE))) {
2488 return "{}";
2491 if (index < 0 || static_cast<size_t>(index) > pages_.size() - 1)
2492 return "{}";
2494 scoped_ptr<base::Value> node(
2495 pages_[index]->GetAccessibleContentAsValue(current_rotation_));
2496 std::string page_json;
2497 base::JSONWriter::Write(*node, &page_json);
2498 return page_json;
2501 bool PDFiumEngine::GetPrintScaling() {
2502 return !!FPDF_VIEWERREF_GetPrintScaling(doc_);
2505 int PDFiumEngine::GetCopiesToPrint() {
2506 return FPDF_VIEWERREF_GetNumCopies(doc_);
2509 int PDFiumEngine::GetDuplexType() {
2510 return static_cast<int>(FPDF_VIEWERREF_GetDuplex(doc_));
2513 bool PDFiumEngine::GetPageSizeAndUniformity(pp::Size* size) {
2514 if (pages_.empty())
2515 return false;
2517 pp::Size page_size = GetPageSize(0);
2518 for (size_t i = 1; i < pages_.size(); ++i) {
2519 if (page_size != GetPageSize(i))
2520 return false;
2523 // Convert |page_size| back to points.
2524 size->set_width(
2525 ConvertUnit(page_size.width(), kPixelsPerInch, kPointsPerInch));
2526 size->set_height(
2527 ConvertUnit(page_size.height(), kPixelsPerInch, kPointsPerInch));
2528 return true;
2531 void PDFiumEngine::AppendBlankPages(int num_pages) {
2532 DCHECK_NE(num_pages, 0);
2534 if (!doc_)
2535 return;
2537 selection_.clear();
2538 pending_pages_.clear();
2540 // Delete all pages except the first one.
2541 while (pages_.size() > 1) {
2542 delete pages_.back();
2543 pages_.pop_back();
2544 FPDFPage_Delete(doc_, pages_.size());
2547 // Calculate document size and all page sizes.
2548 std::vector<pp::Rect> page_rects;
2549 pp::Size page_size = GetPageSize(0);
2550 page_size.Enlarge(kPageShadowLeft + kPageShadowRight,
2551 kPageShadowTop + kPageShadowBottom);
2552 pp::Size old_document_size = document_size_;
2553 document_size_ = pp::Size(page_size.width(), 0);
2554 for (int i = 0; i < num_pages; ++i) {
2555 if (i != 0) {
2556 // Add space for horizontal separator.
2557 document_size_.Enlarge(0, kPageSeparatorThickness);
2560 pp::Rect rect(pp::Point(0, document_size_.height()), page_size);
2561 page_rects.push_back(rect);
2563 document_size_.Enlarge(0, page_size.height());
2566 // Create blank pages.
2567 for (int i = 1; i < num_pages; ++i) {
2568 pp::Rect page_rect(page_rects[i]);
2569 page_rect.Inset(kPageShadowLeft, kPageShadowTop,
2570 kPageShadowRight, kPageShadowBottom);
2571 double width_in_points = ConvertUnitDouble(page_rect.width(),
2572 kPixelsPerInch,
2573 kPointsPerInch);
2574 double height_in_points = ConvertUnitDouble(page_rect.height(),
2575 kPixelsPerInch,
2576 kPointsPerInch);
2577 FPDFPage_New(doc_, i, width_in_points, height_in_points);
2578 pages_.push_back(new PDFiumPage(this, i, page_rect, true));
2581 CalculateVisiblePages();
2582 if (document_size_ != old_document_size)
2583 client_->DocumentSizeUpdated(document_size_);
2586 void PDFiumEngine::LoadDocument() {
2587 // Check if the document is ready for loading. If it isn't just bail for now,
2588 // we will call LoadDocument() again later.
2589 if (!doc_ && !doc_loader_.IsDocumentComplete() &&
2590 !FPDFAvail_IsDocAvail(fpdf_availability_, &download_hints_)) {
2591 return;
2594 // If we're in the middle of getting a password, just return. We will retry
2595 // loading the document after we get the password anyway.
2596 if (getting_password_)
2597 return;
2599 ScopedUnsupportedFeature scoped_unsupported_feature(this);
2600 bool needs_password = false;
2601 if (TryLoadingDoc(false, std::string(), &needs_password)) {
2602 ContinueLoadingDocument(false, std::string());
2603 return;
2605 if (needs_password)
2606 GetPasswordAndLoad();
2607 else
2608 client_->DocumentLoadFailed();
2611 bool PDFiumEngine::TryLoadingDoc(bool with_password,
2612 const std::string& password,
2613 bool* needs_password) {
2614 *needs_password = false;
2615 if (doc_)
2616 return true;
2618 const char* password_cstr = NULL;
2619 if (with_password) {
2620 password_cstr = password.c_str();
2621 password_tries_remaining_--;
2623 if (doc_loader_.IsDocumentComplete())
2624 doc_ = FPDF_LoadCustomDocument(&file_access_, password_cstr);
2625 else
2626 doc_ = FPDFAvail_GetDocument(fpdf_availability_, password_cstr);
2628 if (!doc_ && FPDF_GetLastError() == FPDF_ERR_PASSWORD)
2629 *needs_password = true;
2631 return doc_ != NULL;
2634 void PDFiumEngine::GetPasswordAndLoad() {
2635 getting_password_ = true;
2636 DCHECK(!doc_ && FPDF_GetLastError() == FPDF_ERR_PASSWORD);
2637 client_->GetDocumentPassword(password_factory_.NewCallbackWithOutput(
2638 &PDFiumEngine::OnGetPasswordComplete));
2641 void PDFiumEngine::OnGetPasswordComplete(int32_t result,
2642 const pp::Var& password) {
2643 getting_password_ = false;
2645 bool password_given = false;
2646 std::string password_text;
2647 if (result == PP_OK && password.is_string()) {
2648 password_text = password.AsString();
2649 if (!password_text.empty())
2650 password_given = true;
2652 ContinueLoadingDocument(password_given, password_text);
2655 void PDFiumEngine::ContinueLoadingDocument(
2656 bool has_password,
2657 const std::string& password) {
2658 ScopedUnsupportedFeature scoped_unsupported_feature(this);
2660 bool needs_password = false;
2661 bool loaded = TryLoadingDoc(has_password, password, &needs_password);
2662 bool password_incorrect = !loaded && has_password && needs_password;
2663 if (password_incorrect && password_tries_remaining_ > 0) {
2664 GetPasswordAndLoad();
2665 return;
2668 if (!doc_) {
2669 client_->DocumentLoadFailed();
2670 return;
2673 if (FPDFDoc_GetPageMode(doc_) == PAGEMODE_USEOUTLINES)
2674 client_->DocumentHasUnsupportedFeature("Bookmarks");
2676 permissions_ = FPDF_GetDocPermissions(doc_);
2677 permissions_handler_revision_ = FPDF_GetSecurityHandlerRevision(doc_);
2679 if (!form_) {
2680 // Only returns 0 when data isn't available. If form data is downloaded, or
2681 // if this isn't a form, returns positive values.
2682 if (!doc_loader_.IsDocumentComplete() &&
2683 !FPDFAvail_IsFormAvail(fpdf_availability_, &download_hints_)) {
2684 return;
2687 form_ = FPDFDOC_InitFormFillEnvironment(
2688 doc_, static_cast<FPDF_FORMFILLINFO*>(this));
2689 #ifdef PDF_USE_XFA
2690 FPDF_LoadXFA(doc_);
2691 #endif
2693 FPDF_SetFormFieldHighlightColor(form_, 0, kFormHighlightColor);
2694 FPDF_SetFormFieldHighlightAlpha(form_, kFormHighlightAlpha);
2697 if (!doc_loader_.IsDocumentComplete()) {
2698 // Check if the first page is available. In a linearized PDF, that is not
2699 // always page 0. Doing this gives us the default page size, since when the
2700 // document is available, the first page is available as well.
2701 CheckPageAvailable(FPDFAvail_GetFirstPageNum(doc_), &pending_pages_);
2704 LoadPageInfo(false);
2706 if (doc_loader_.IsDocumentComplete())
2707 FinishLoadingDocument();
2710 void PDFiumEngine::LoadPageInfo(bool reload) {
2711 pending_pages_.clear();
2712 pp::Size old_document_size = document_size_;
2713 document_size_ = pp::Size();
2714 std::vector<pp::Rect> page_rects;
2715 int page_count = FPDF_GetPageCount(doc_);
2716 bool doc_complete = doc_loader_.IsDocumentComplete();
2717 for (int i = 0; i < page_count; ++i) {
2718 if (i != 0) {
2719 // Add space for horizontal separator.
2720 document_size_.Enlarge(0, kPageSeparatorThickness);
2723 // Get page availability. If reload==false, and document is not loaded yet
2724 // (we are using async loading) - mark all pages as unavailable.
2725 // If reload==true (we have document constructed already), get page
2726 // availability flag from already existing PDFiumPage class.
2727 bool page_available = reload ? pages_[i]->available() : doc_complete;
2729 pp::Size size = page_available ? GetPageSize(i) : default_page_size_;
2730 size.Enlarge(kPageShadowLeft + kPageShadowRight,
2731 kPageShadowTop + kPageShadowBottom);
2732 pp::Rect rect(pp::Point(0, document_size_.height()), size);
2733 page_rects.push_back(rect);
2735 if (size.width() > document_size_.width())
2736 document_size_.set_width(size.width());
2738 document_size_.Enlarge(0, size.height());
2741 for (int i = 0; i < page_count; ++i) {
2742 // Center pages relative to the entire document.
2743 page_rects[i].set_x((document_size_.width() - page_rects[i].width()) / 2);
2744 pp::Rect page_rect(page_rects[i]);
2745 page_rect.Inset(kPageShadowLeft, kPageShadowTop,
2746 kPageShadowRight, kPageShadowBottom);
2747 if (reload) {
2748 pages_[i]->set_rect(page_rect);
2749 } else {
2750 pages_.push_back(new PDFiumPage(this, i, page_rect, doc_complete));
2754 CalculateVisiblePages();
2755 if (document_size_ != old_document_size)
2756 client_->DocumentSizeUpdated(document_size_);
2759 void PDFiumEngine::CalculateVisiblePages() {
2760 // Clear pending requests queue, since it may contain requests to the pages
2761 // that are already invisible (after scrolling for example).
2762 pending_pages_.clear();
2763 doc_loader_.ClearPendingRequests();
2765 visible_pages_.clear();
2766 pp::Rect visible_rect(plugin_size_);
2767 for (size_t i = 0; i < pages_.size(); ++i) {
2768 // Check an entire PageScreenRect, since we might need to repaint side
2769 // borders and shadows even if the page itself is not visible.
2770 // For example, when user use pdf with different page sizes and zoomed in
2771 // outside page area.
2772 if (visible_rect.Intersects(GetPageScreenRect(i))) {
2773 visible_pages_.push_back(i);
2774 CheckPageAvailable(i, &pending_pages_);
2775 } else {
2776 // Need to unload pages when we're not using them, since some PDFs use a
2777 // lot of memory. See http://crbug.com/48791
2778 if (defer_page_unload_) {
2779 deferred_page_unloads_.push_back(i);
2780 } else {
2781 pages_[i]->Unload();
2784 // If the last mouse down was on a page that's no longer visible, reset
2785 // that variable so that we don't send keyboard events to it (the focus
2786 // will be lost when the page is first closed anyways).
2787 if (static_cast<int>(i) == last_page_mouse_down_)
2788 last_page_mouse_down_ = -1;
2792 // Any pending highlighting of form fields will be invalid since these are in
2793 // screen coordinates.
2794 form_highlights_.clear();
2796 if (visible_pages_.size() == 0)
2797 first_visible_page_ = -1;
2798 else
2799 first_visible_page_ = visible_pages_.front();
2801 int most_visible_page = first_visible_page_;
2802 // Check if the next page is more visible than the first one.
2803 if (most_visible_page != -1 &&
2804 pages_.size() > 0 &&
2805 most_visible_page < static_cast<int>(pages_.size()) - 1) {
2806 pp::Rect rc_first =
2807 visible_rect.Intersect(GetPageScreenRect(most_visible_page));
2808 pp::Rect rc_next =
2809 visible_rect.Intersect(GetPageScreenRect(most_visible_page + 1));
2810 if (rc_next.height() > rc_first.height())
2811 most_visible_page++;
2814 SetCurrentPage(most_visible_page);
2817 bool PDFiumEngine::IsPageVisible(int index) const {
2818 for (size_t i = 0; i < visible_pages_.size(); ++i) {
2819 if (visible_pages_[i] == index)
2820 return true;
2823 return false;
2826 bool PDFiumEngine::CheckPageAvailable(int index, std::vector<int>* pending) {
2827 if (!doc_ || !form_)
2828 return false;
2830 if (static_cast<int>(pages_.size()) > index && pages_[index]->available())
2831 return true;
2833 if (!FPDFAvail_IsPageAvail(fpdf_availability_, index, &download_hints_)) {
2834 size_t j;
2835 for (j = 0; j < pending->size(); ++j) {
2836 if ((*pending)[j] == index)
2837 break;
2840 if (j == pending->size())
2841 pending->push_back(index);
2842 return false;
2845 if (static_cast<int>(pages_.size()) > index)
2846 pages_[index]->set_available(true);
2847 if (!default_page_size_.GetArea())
2848 default_page_size_ = GetPageSize(index);
2849 return true;
2852 pp::Size PDFiumEngine::GetPageSize(int index) {
2853 pp::Size size;
2854 double width_in_points = 0;
2855 double height_in_points = 0;
2856 int rv = FPDF_GetPageSizeByIndex(
2857 doc_, index, &width_in_points, &height_in_points);
2859 if (rv) {
2860 int width_in_pixels = static_cast<int>(
2861 ConvertUnitDouble(width_in_points, kPointsPerInch, kPixelsPerInch));
2862 int height_in_pixels = static_cast<int>(
2863 ConvertUnitDouble(height_in_points, kPointsPerInch, kPixelsPerInch));
2864 if (current_rotation_ % 2 == 1)
2865 std::swap(width_in_pixels, height_in_pixels);
2866 size = pp::Size(width_in_pixels, height_in_pixels);
2868 return size;
2871 int PDFiumEngine::StartPaint(int page_index, const pp::Rect& dirty) {
2872 // For the first time we hit paint, do nothing and just record the paint for
2873 // the next callback. This keeps the UI responsive in case the user is doing
2874 // a lot of scrolling.
2875 ProgressivePaint progressive;
2876 progressive.rect = dirty;
2877 progressive.page_index = page_index;
2878 progressive.bitmap = NULL;
2879 progressive.painted_ = false;
2880 progressive_paints_.push_back(progressive);
2881 return progressive_paints_.size() - 1;
2884 bool PDFiumEngine::ContinuePaint(int progressive_index,
2885 pp::ImageData* image_data) {
2886 DCHECK_GE(progressive_index, 0);
2887 DCHECK_LT(static_cast<size_t>(progressive_index), progressive_paints_.size());
2888 DCHECK(image_data);
2890 #if defined(OS_LINUX)
2891 g_last_instance_id = client_->GetPluginInstance()->pp_instance();
2892 #endif
2894 int rv;
2895 FPDF_BITMAP bitmap = progressive_paints_[progressive_index].bitmap;
2896 int page_index = progressive_paints_[progressive_index].page_index;
2897 DCHECK_GE(page_index, 0);
2898 DCHECK_LT(static_cast<size_t>(page_index), pages_.size());
2899 FPDF_PAGE page = pages_[page_index]->GetPage();
2901 last_progressive_start_time_ = base::Time::Now();
2902 if (bitmap) {
2903 rv = FPDF_RenderPage_Continue(page, static_cast<IFSDK_PAUSE*>(this));
2904 } else {
2905 pp::Rect dirty = progressive_paints_[progressive_index].rect;
2906 bitmap = CreateBitmap(dirty, image_data);
2907 int start_x, start_y, size_x, size_y;
2908 GetPDFiumRect(page_index, dirty, &start_x, &start_y, &size_x, &size_y);
2909 FPDFBitmap_FillRect(bitmap, start_x, start_y, size_x, size_y, 0xFFFFFFFF);
2910 rv = FPDF_RenderPageBitmap_Start(
2911 bitmap, page, start_x, start_y, size_x, size_y,
2912 current_rotation_,
2913 GetRenderingFlags(), static_cast<IFSDK_PAUSE*>(this));
2914 progressive_paints_[progressive_index].bitmap = bitmap;
2916 return rv != FPDF_RENDER_TOBECOUNTINUED;
2919 void PDFiumEngine::FinishPaint(int progressive_index,
2920 pp::ImageData* image_data) {
2921 DCHECK_GE(progressive_index, 0);
2922 DCHECK_LT(static_cast<size_t>(progressive_index), progressive_paints_.size());
2923 DCHECK(image_data);
2925 int page_index = progressive_paints_[progressive_index].page_index;
2926 pp::Rect dirty_in_screen = progressive_paints_[progressive_index].rect;
2927 FPDF_BITMAP bitmap = progressive_paints_[progressive_index].bitmap;
2928 int start_x, start_y, size_x, size_y;
2929 GetPDFiumRect(
2930 page_index, dirty_in_screen, &start_x, &start_y, &size_x, &size_y);
2932 // Draw the forms.
2933 FPDF_FFLDraw(
2934 form_, bitmap, pages_[page_index]->GetPage(), start_x, start_y, size_x,
2935 size_y, current_rotation_, GetRenderingFlags());
2937 FillPageSides(progressive_index);
2939 // Paint the page shadows.
2940 PaintPageShadow(progressive_index, image_data);
2942 DrawSelections(progressive_index, image_data);
2944 FPDF_RenderPage_Close(pages_[page_index]->GetPage());
2945 FPDFBitmap_Destroy(bitmap);
2946 progressive_paints_.erase(progressive_paints_.begin() + progressive_index);
2948 client_->DocumentPaintOccurred();
2951 void PDFiumEngine::CancelPaints() {
2952 for (size_t i = 0; i < progressive_paints_.size(); ++i) {
2953 FPDF_RenderPage_Close(pages_[progressive_paints_[i].page_index]->GetPage());
2954 FPDFBitmap_Destroy(progressive_paints_[i].bitmap);
2956 progressive_paints_.clear();
2959 void PDFiumEngine::FillPageSides(int progressive_index) {
2960 DCHECK_GE(progressive_index, 0);
2961 DCHECK_LT(static_cast<size_t>(progressive_index), progressive_paints_.size());
2963 int page_index = progressive_paints_[progressive_index].page_index;
2964 pp::Rect dirty_in_screen = progressive_paints_[progressive_index].rect;
2965 FPDF_BITMAP bitmap = progressive_paints_[progressive_index].bitmap;
2967 pp::Rect page_rect = pages_[page_index]->rect();
2968 if (page_rect.x() > 0) {
2969 pp::Rect left(0,
2970 page_rect.y() - kPageShadowTop,
2971 page_rect.x() - kPageShadowLeft,
2972 page_rect.height() + kPageShadowTop +
2973 kPageShadowBottom + kPageSeparatorThickness);
2974 left = GetScreenRect(left).Intersect(dirty_in_screen);
2976 FPDFBitmap_FillRect(bitmap, left.x() - dirty_in_screen.x(),
2977 left.y() - dirty_in_screen.y(), left.width(),
2978 left.height(), client_->GetBackgroundColor());
2981 if (page_rect.right() < document_size_.width()) {
2982 pp::Rect right(page_rect.right() + kPageShadowRight,
2983 page_rect.y() - kPageShadowTop,
2984 document_size_.width() - page_rect.right() -
2985 kPageShadowRight,
2986 page_rect.height() + kPageShadowTop +
2987 kPageShadowBottom + kPageSeparatorThickness);
2988 right = GetScreenRect(right).Intersect(dirty_in_screen);
2990 FPDFBitmap_FillRect(bitmap, right.x() - dirty_in_screen.x(),
2991 right.y() - dirty_in_screen.y(), right.width(),
2992 right.height(), client_->GetBackgroundColor());
2995 // Paint separator.
2996 pp::Rect bottom(page_rect.x() - kPageShadowLeft,
2997 page_rect.bottom() + kPageShadowBottom,
2998 page_rect.width() + kPageShadowLeft + kPageShadowRight,
2999 kPageSeparatorThickness);
3000 bottom = GetScreenRect(bottom).Intersect(dirty_in_screen);
3002 FPDFBitmap_FillRect(bitmap, bottom.x() - dirty_in_screen.x(),
3003 bottom.y() - dirty_in_screen.y(), bottom.width(),
3004 bottom.height(), client_->GetBackgroundColor());
3007 void PDFiumEngine::PaintPageShadow(int progressive_index,
3008 pp::ImageData* image_data) {
3009 DCHECK_GE(progressive_index, 0);
3010 DCHECK_LT(static_cast<size_t>(progressive_index), progressive_paints_.size());
3011 DCHECK(image_data);
3013 int page_index = progressive_paints_[progressive_index].page_index;
3014 pp::Rect dirty_in_screen = progressive_paints_[progressive_index].rect;
3015 pp::Rect page_rect = pages_[page_index]->rect();
3016 pp::Rect shadow_rect(page_rect);
3017 shadow_rect.Inset(-kPageShadowLeft, -kPageShadowTop,
3018 -kPageShadowRight, -kPageShadowBottom);
3020 // Due to the rounding errors of the GetScreenRect it is possible to get
3021 // different size shadows on the left and right sides even they are defined
3022 // the same. To fix this issue let's calculate shadow rect and then shrink
3023 // it by the size of the shadows.
3024 shadow_rect = GetScreenRect(shadow_rect);
3025 page_rect = shadow_rect;
3027 page_rect.Inset(static_cast<int>(ceil(kPageShadowLeft * current_zoom_)),
3028 static_cast<int>(ceil(kPageShadowTop * current_zoom_)),
3029 static_cast<int>(ceil(kPageShadowRight * current_zoom_)),
3030 static_cast<int>(ceil(kPageShadowBottom * current_zoom_)));
3032 DrawPageShadow(page_rect, shadow_rect, dirty_in_screen, image_data);
3035 void PDFiumEngine::DrawSelections(int progressive_index,
3036 pp::ImageData* image_data) {
3037 DCHECK_GE(progressive_index, 0);
3038 DCHECK_LT(static_cast<size_t>(progressive_index), progressive_paints_.size());
3039 DCHECK(image_data);
3041 int page_index = progressive_paints_[progressive_index].page_index;
3042 pp::Rect dirty_in_screen = progressive_paints_[progressive_index].rect;
3044 void* region = NULL;
3045 int stride;
3046 GetRegion(dirty_in_screen.point(), image_data, &region, &stride);
3048 std::vector<pp::Rect> highlighted_rects;
3049 pp::Rect visible_rect = GetVisibleRect();
3050 for (size_t k = 0; k < selection_.size(); ++k) {
3051 if (selection_[k].page_index() != page_index)
3052 continue;
3053 std::vector<pp::Rect> rects = selection_[k].GetScreenRects(
3054 visible_rect.point(), current_zoom_, current_rotation_);
3055 for (size_t j = 0; j < rects.size(); ++j) {
3056 pp::Rect visible_selection = rects[j].Intersect(dirty_in_screen);
3057 if (visible_selection.IsEmpty())
3058 continue;
3060 visible_selection.Offset(
3061 -dirty_in_screen.point().x(), -dirty_in_screen.point().y());
3062 Highlight(region, stride, visible_selection, &highlighted_rects);
3066 for (size_t k = 0; k < form_highlights_.size(); ++k) {
3067 pp::Rect visible_selection = form_highlights_[k].Intersect(dirty_in_screen);
3068 if (visible_selection.IsEmpty())
3069 continue;
3071 visible_selection.Offset(
3072 -dirty_in_screen.point().x(), -dirty_in_screen.point().y());
3073 Highlight(region, stride, visible_selection, &highlighted_rects);
3075 form_highlights_.clear();
3078 void PDFiumEngine::PaintUnavailablePage(int page_index,
3079 const pp::Rect& dirty,
3080 pp::ImageData* image_data) {
3081 int start_x, start_y, size_x, size_y;
3082 GetPDFiumRect(page_index, dirty, &start_x, &start_y, &size_x, &size_y);
3083 FPDF_BITMAP bitmap = CreateBitmap(dirty, image_data);
3084 FPDFBitmap_FillRect(bitmap, start_x, start_y, size_x, size_y,
3085 kPendingPageColor);
3087 pp::Rect loading_text_in_screen(
3088 pages_[page_index]->rect().width() / 2,
3089 pages_[page_index]->rect().y() + kLoadingTextVerticalOffset, 0, 0);
3090 loading_text_in_screen = GetScreenRect(loading_text_in_screen);
3091 FPDFBitmap_Destroy(bitmap);
3094 int PDFiumEngine::GetProgressiveIndex(int page_index) const {
3095 for (size_t i = 0; i < progressive_paints_.size(); ++i) {
3096 if (progressive_paints_[i].page_index == page_index)
3097 return i;
3099 return -1;
3102 FPDF_BITMAP PDFiumEngine::CreateBitmap(const pp::Rect& rect,
3103 pp::ImageData* image_data) const {
3104 void* region;
3105 int stride;
3106 GetRegion(rect.point(), image_data, &region, &stride);
3107 if (!region)
3108 return NULL;
3109 return FPDFBitmap_CreateEx(
3110 rect.width(), rect.height(), FPDFBitmap_BGRx, region, stride);
3113 void PDFiumEngine::GetPDFiumRect(
3114 int page_index, const pp::Rect& rect, int* start_x, int* start_y,
3115 int* size_x, int* size_y) const {
3116 pp::Rect page_rect = GetScreenRect(pages_[page_index]->rect());
3117 page_rect.Offset(-rect.x(), -rect.y());
3119 *start_x = page_rect.x();
3120 *start_y = page_rect.y();
3121 *size_x = page_rect.width();
3122 *size_y = page_rect.height();
3125 int PDFiumEngine::GetRenderingFlags() const {
3126 int flags = FPDF_LCD_TEXT | FPDF_NO_CATCH;
3127 if (render_grayscale_)
3128 flags |= FPDF_GRAYSCALE;
3129 if (client_->IsPrintPreview())
3130 flags |= FPDF_PRINTING;
3131 return flags;
3134 pp::Rect PDFiumEngine::GetVisibleRect() const {
3135 pp::Rect rv;
3136 rv.set_x(static_cast<int>(position_.x() / current_zoom_));
3137 rv.set_y(static_cast<int>(position_.y() / current_zoom_));
3138 rv.set_width(static_cast<int>(ceil(plugin_size_.width() / current_zoom_)));
3139 rv.set_height(static_cast<int>(ceil(plugin_size_.height() / current_zoom_)));
3140 return rv;
3143 pp::Rect PDFiumEngine::GetPageScreenRect(int page_index) const {
3144 // Since we use this rect for creating the PDFium bitmap, also include other
3145 // areas around the page that we might need to update such as the page
3146 // separator and the sides if the page is narrower than the document.
3147 return GetScreenRect(pp::Rect(
3149 pages_[page_index]->rect().y() - kPageShadowTop,
3150 document_size_.width(),
3151 pages_[page_index]->rect().height() + kPageShadowTop +
3152 kPageShadowBottom + kPageSeparatorThickness));
3155 pp::Rect PDFiumEngine::GetScreenRect(const pp::Rect& rect) const {
3156 pp::Rect rv;
3157 int right =
3158 static_cast<int>(ceil(rect.right() * current_zoom_ - position_.x()));
3159 int bottom =
3160 static_cast<int>(ceil(rect.bottom() * current_zoom_ - position_.y()));
3162 rv.set_x(static_cast<int>(rect.x() * current_zoom_ - position_.x()));
3163 rv.set_y(static_cast<int>(rect.y() * current_zoom_ - position_.y()));
3164 rv.set_width(right - rv.x());
3165 rv.set_height(bottom - rv.y());
3166 return rv;
3169 void PDFiumEngine::Highlight(void* buffer,
3170 int stride,
3171 const pp::Rect& rect,
3172 std::vector<pp::Rect>* highlighted_rects) {
3173 if (!buffer)
3174 return;
3176 pp::Rect new_rect = rect;
3177 for (size_t i = 0; i < highlighted_rects->size(); ++i)
3178 new_rect = new_rect.Subtract((*highlighted_rects)[i]);
3180 highlighted_rects->push_back(new_rect);
3181 int l = new_rect.x();
3182 int t = new_rect.y();
3183 int w = new_rect.width();
3184 int h = new_rect.height();
3186 for (int y = t; y < t + h; ++y) {
3187 for (int x = l; x < l + w; ++x) {
3188 uint8* pixel = static_cast<uint8*>(buffer) + y * stride + x * 4;
3189 // This is our highlight color.
3190 pixel[0] = static_cast<uint8>(
3191 pixel[0] * (kHighlightColorB / 255.0));
3192 pixel[1] = static_cast<uint8>(
3193 pixel[1] * (kHighlightColorG / 255.0));
3194 pixel[2] = static_cast<uint8>(
3195 pixel[2] * (kHighlightColorR / 255.0));
3200 PDFiumEngine::SelectionChangeInvalidator::SelectionChangeInvalidator(
3201 PDFiumEngine* engine) : engine_(engine) {
3202 previous_origin_ = engine_->GetVisibleRect().point();
3203 GetVisibleSelectionsScreenRects(&old_selections_);
3206 PDFiumEngine::SelectionChangeInvalidator::~SelectionChangeInvalidator() {
3207 // Offset the old selections if the document scrolled since we recorded them.
3208 pp::Point offset = previous_origin_ - engine_->GetVisibleRect().point();
3209 for (size_t i = 0; i < old_selections_.size(); ++i)
3210 old_selections_[i].Offset(offset);
3212 std::vector<pp::Rect> new_selections;
3213 GetVisibleSelectionsScreenRects(&new_selections);
3214 for (size_t i = 0; i < new_selections.size(); ++i) {
3215 for (size_t j = 0; j < old_selections_.size(); ++j) {
3216 if (!old_selections_[j].IsEmpty() &&
3217 new_selections[i] == old_selections_[j]) {
3218 // Rectangle was selected before and after, so no need to invalidate it.
3219 // Mark the rectangles by setting them to empty.
3220 new_selections[i] = old_selections_[j] = pp::Rect();
3221 break;
3226 for (size_t i = 0; i < old_selections_.size(); ++i) {
3227 if (!old_selections_[i].IsEmpty())
3228 engine_->client_->Invalidate(old_selections_[i]);
3230 for (size_t i = 0; i < new_selections.size(); ++i) {
3231 if (!new_selections[i].IsEmpty())
3232 engine_->client_->Invalidate(new_selections[i]);
3234 engine_->OnSelectionChanged();
3237 void
3238 PDFiumEngine::SelectionChangeInvalidator::GetVisibleSelectionsScreenRects(
3239 std::vector<pp::Rect>* rects) {
3240 pp::Rect visible_rect = engine_->GetVisibleRect();
3241 for (size_t i = 0; i < engine_->selection_.size(); ++i) {
3242 int page_index = engine_->selection_[i].page_index();
3243 if (!engine_->IsPageVisible(page_index))
3244 continue; // This selection is on a page that's not currently visible.
3246 std::vector<pp::Rect> selection_rects =
3247 engine_->selection_[i].GetScreenRects(
3248 visible_rect.point(),
3249 engine_->current_zoom_,
3250 engine_->current_rotation_);
3251 rects->insert(rects->end(), selection_rects.begin(), selection_rects.end());
3255 PDFiumEngine::MouseDownState::MouseDownState(
3256 const PDFiumPage::Area& area,
3257 const PDFiumPage::LinkTarget& target)
3258 : area_(area), target_(target) {
3261 PDFiumEngine::MouseDownState::~MouseDownState() {
3264 void PDFiumEngine::MouseDownState::Set(const PDFiumPage::Area& area,
3265 const PDFiumPage::LinkTarget& target) {
3266 area_ = area;
3267 target_ = target;
3270 void PDFiumEngine::MouseDownState::Reset() {
3271 area_ = PDFiumPage::NONSELECTABLE_AREA;
3272 target_ = PDFiumPage::LinkTarget();
3275 bool PDFiumEngine::MouseDownState::Matches(
3276 const PDFiumPage::Area& area,
3277 const PDFiumPage::LinkTarget& target) const {
3278 if (area_ == area) {
3279 if (area == PDFiumPage::WEBLINK_AREA)
3280 return target_.url == target.url;
3281 if (area == PDFiumPage::DOCLINK_AREA)
3282 return target_.page == target.page;
3283 return true;
3285 return false;
3288 PDFiumEngine::FindTextIndex::FindTextIndex()
3289 : valid_(false), index_(0) {
3292 PDFiumEngine::FindTextIndex::~FindTextIndex() {
3295 void PDFiumEngine::FindTextIndex::Invalidate() {
3296 valid_ = false;
3299 size_t PDFiumEngine::FindTextIndex::GetIndex() const {
3300 DCHECK(valid_);
3301 return index_;
3304 void PDFiumEngine::FindTextIndex::SetIndex(size_t index) {
3305 valid_ = true;
3306 index_ = index;
3309 size_t PDFiumEngine::FindTextIndex::IncrementIndex() {
3310 DCHECK(valid_);
3311 return ++index_;
3314 void PDFiumEngine::DeviceToPage(int page_index,
3315 float device_x,
3316 float device_y,
3317 double* page_x,
3318 double* page_y) {
3319 *page_x = *page_y = 0;
3320 int temp_x = static_cast<int>((device_x + position_.x())/ current_zoom_ -
3321 pages_[page_index]->rect().x());
3322 int temp_y = static_cast<int>((device_y + position_.y())/ current_zoom_ -
3323 pages_[page_index]->rect().y());
3324 FPDF_DeviceToPage(
3325 pages_[page_index]->GetPage(), 0, 0,
3326 pages_[page_index]->rect().width(), pages_[page_index]->rect().height(),
3327 current_rotation_, temp_x, temp_y, page_x, page_y);
3330 int PDFiumEngine::GetVisiblePageIndex(FPDF_PAGE page) {
3331 for (size_t i = 0; i < visible_pages_.size(); ++i) {
3332 if (pages_[visible_pages_[i]]->GetPage() == page)
3333 return visible_pages_[i];
3335 return -1;
3338 void PDFiumEngine::SetCurrentPage(int index) {
3339 if (index == most_visible_page_ || !form_)
3340 return;
3341 if (most_visible_page_ != -1 && called_do_document_action_) {
3342 FPDF_PAGE old_page = pages_[most_visible_page_]->GetPage();
3343 FORM_DoPageAAction(old_page, form_, FPDFPAGE_AACTION_CLOSE);
3345 most_visible_page_ = index;
3346 #if defined(OS_LINUX)
3347 g_last_instance_id = client_->GetPluginInstance()->pp_instance();
3348 #endif
3349 if (most_visible_page_ != -1 && called_do_document_action_) {
3350 FPDF_PAGE new_page = pages_[most_visible_page_]->GetPage();
3351 FORM_DoPageAAction(new_page, form_, FPDFPAGE_AACTION_OPEN);
3355 void PDFiumEngine::TransformPDFPageForPrinting(
3356 FPDF_PAGE page,
3357 const PP_PrintSettings_Dev& print_settings) {
3358 // Get the source page width and height in points.
3359 const double src_page_width = FPDF_GetPageWidth(page);
3360 const double src_page_height = FPDF_GetPageHeight(page);
3362 const int src_page_rotation = FPDFPage_GetRotation(page);
3363 const bool fit_to_page = print_settings.print_scaling_option ==
3364 PP_PRINTSCALINGOPTION_FIT_TO_PRINTABLE_AREA;
3366 pp::Size page_size(print_settings.paper_size);
3367 pp::Rect content_rect(print_settings.printable_area);
3368 const bool rotated = (src_page_rotation % 2 == 1);
3369 SetPageSizeAndContentRect(rotated,
3370 src_page_width > src_page_height,
3371 &page_size,
3372 &content_rect);
3374 // Compute the screen page width and height in points.
3375 const int actual_page_width =
3376 rotated ? page_size.height() : page_size.width();
3377 const int actual_page_height =
3378 rotated ? page_size.width() : page_size.height();
3380 const double scale_factor = CalculateScaleFactor(fit_to_page, content_rect,
3381 src_page_width,
3382 src_page_height, rotated);
3384 // Calculate positions for the clip box.
3385 ClipBox source_clip_box;
3386 CalculateClipBoxBoundary(page, scale_factor, rotated, &source_clip_box);
3388 // Calculate the translation offset values.
3389 double offset_x = 0;
3390 double offset_y = 0;
3391 if (fit_to_page) {
3392 CalculateScaledClipBoxOffset(content_rect, source_clip_box, &offset_x,
3393 &offset_y);
3394 } else {
3395 CalculateNonScaledClipBoxOffset(content_rect, src_page_rotation,
3396 actual_page_width, actual_page_height,
3397 source_clip_box, &offset_x, &offset_y);
3400 // Reset the media box and crop box. When the page has crop box and media box,
3401 // the plugin will display the crop box contents and not the entire media box.
3402 // If the pages have different crop box values, the plugin will display a
3403 // document of multiple page sizes. To give better user experience, we
3404 // decided to have same crop box and media box values. Hence, the user will
3405 // see a list of uniform pages.
3406 FPDFPage_SetMediaBox(page, 0, 0, page_size.width(), page_size.height());
3407 FPDFPage_SetCropBox(page, 0, 0, page_size.width(), page_size.height());
3409 // Transformation is not required, return. Do this check only after updating
3410 // the media box and crop box. For more detailed information, please refer to
3411 // the comment block right before FPDF_SetMediaBox and FPDF_GetMediaBox calls.
3412 if (scale_factor == 1.0 && offset_x == 0 && offset_y == 0)
3413 return;
3416 // All the positions have been calculated, now manipulate the PDF.
3417 FS_MATRIX matrix = {static_cast<float>(scale_factor),
3420 static_cast<float>(scale_factor),
3421 static_cast<float>(offset_x),
3422 static_cast<float>(offset_y)};
3423 FS_RECTF cliprect = {static_cast<float>(source_clip_box.left+offset_x),
3424 static_cast<float>(source_clip_box.top+offset_y),
3425 static_cast<float>(source_clip_box.right+offset_x),
3426 static_cast<float>(source_clip_box.bottom+offset_y)};
3427 FPDFPage_TransFormWithClip(page, &matrix, &cliprect);
3428 FPDFPage_TransformAnnots(page, scale_factor, 0, 0, scale_factor,
3429 offset_x, offset_y);
3432 void PDFiumEngine::DrawPageShadow(const pp::Rect& page_rc,
3433 const pp::Rect& shadow_rc,
3434 const pp::Rect& clip_rc,
3435 pp::ImageData* image_data) {
3436 pp::Rect page_rect(page_rc);
3437 page_rect.Offset(page_offset_);
3439 pp::Rect shadow_rect(shadow_rc);
3440 shadow_rect.Offset(page_offset_);
3442 pp::Rect clip_rect(clip_rc);
3443 clip_rect.Offset(page_offset_);
3445 // Page drop shadow parameters.
3446 const double factor = 0.5;
3447 uint32 depth = std::max(
3448 std::max(page_rect.x() - shadow_rect.x(),
3449 page_rect.y() - shadow_rect.y()),
3450 std::max(shadow_rect.right() - page_rect.right(),
3451 shadow_rect.bottom() - page_rect.bottom()));
3452 depth = static_cast<uint32>(depth * 1.5) + 1;
3454 // We need to check depth only to verify our copy of shadow matrix is correct.
3455 if (!page_shadow_.get() || page_shadow_->depth() != depth)
3456 page_shadow_.reset(new ShadowMatrix(depth, factor,
3457 client_->GetBackgroundColor()));
3459 DCHECK(!image_data->is_null());
3460 DrawShadow(image_data, shadow_rect, page_rect, clip_rect, *page_shadow_);
3463 void PDFiumEngine::GetRegion(const pp::Point& location,
3464 pp::ImageData* image_data,
3465 void** region,
3466 int* stride) const {
3467 if (image_data->is_null()) {
3468 DCHECK(plugin_size_.IsEmpty());
3469 *stride = 0;
3470 *region = NULL;
3471 return;
3473 char* buffer = static_cast<char*>(image_data->data());
3474 *stride = image_data->stride();
3476 pp::Point offset_location = location + page_offset_;
3477 // TODO: update this when we support BIDI and scrollbars can be on the left.
3478 if (!buffer ||
3479 !pp::Rect(page_offset_, plugin_size_).Contains(offset_location)) {
3480 *region = NULL;
3481 return;
3484 buffer += location.y() * (*stride);
3485 buffer += (location.x() + page_offset_.x()) * 4;
3486 *region = buffer;
3489 void PDFiumEngine::OnSelectionChanged() {
3490 pp::PDF::SetSelectedText(GetPluginInstance(), GetSelectedText().c_str());
3493 void PDFiumEngine::RotateInternal() {
3494 // Store the current find index so that we can resume finding at that
3495 // particular index after we have recomputed the find results.
3496 std::string current_find_text = current_find_text_;
3497 if (current_find_index_.valid())
3498 resume_find_index_.SetIndex(current_find_index_.GetIndex());
3499 else
3500 resume_find_index_.Invalidate();
3502 InvalidateAllPages();
3504 if (!current_find_text.empty()) {
3505 // Clear the UI.
3506 client_->NotifyNumberOfFindResultsChanged(0, false);
3507 StartFind(current_find_text.c_str(), false);
3511 void PDFiumEngine::SetSelecting(bool selecting) {
3512 bool was_selecting = selecting_;
3513 selecting_ = selecting;
3514 if (selecting_ != was_selecting)
3515 client_->IsSelectingChanged(selecting);
3518 void PDFiumEngine::Form_Invalidate(FPDF_FORMFILLINFO* param,
3519 FPDF_PAGE page,
3520 double left,
3521 double top,
3522 double right,
3523 double bottom) {
3524 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3525 int page_index = engine->GetVisiblePageIndex(page);
3526 if (page_index == -1) {
3527 // This can sometime happen when the page is closed because it went off
3528 // screen, and PDFium invalidates the control as it's being deleted.
3529 return;
3532 pp::Rect rect = engine->pages_[page_index]->PageToScreen(
3533 engine->GetVisibleRect().point(), engine->current_zoom_, left, top, right,
3534 bottom, engine->current_rotation_);
3535 engine->client_->Invalidate(rect);
3538 void PDFiumEngine::Form_OutputSelectedRect(FPDF_FORMFILLINFO* param,
3539 FPDF_PAGE page,
3540 double left,
3541 double top,
3542 double right,
3543 double bottom) {
3544 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3545 int page_index = engine->GetVisiblePageIndex(page);
3546 if (page_index == -1) {
3547 NOTREACHED();
3548 return;
3550 pp::Rect rect = engine->pages_[page_index]->PageToScreen(
3551 engine->GetVisibleRect().point(), engine->current_zoom_, left, top, right,
3552 bottom, engine->current_rotation_);
3553 engine->form_highlights_.push_back(rect);
3556 void PDFiumEngine::Form_SetCursor(FPDF_FORMFILLINFO* param, int cursor_type) {
3557 // We don't need this since it's not enough to change the cursor in all
3558 // scenarios. Instead, we check which form field we're under in OnMouseMove.
3561 int PDFiumEngine::Form_SetTimer(FPDF_FORMFILLINFO* param,
3562 int elapse,
3563 TimerCallback timer_func) {
3564 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3565 engine->timers_[++engine->next_timer_id_] =
3566 std::pair<int, TimerCallback>(elapse, timer_func);
3567 engine->client_->ScheduleCallback(engine->next_timer_id_, elapse);
3568 return engine->next_timer_id_;
3571 void PDFiumEngine::Form_KillTimer(FPDF_FORMFILLINFO* param, int timer_id) {
3572 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3573 engine->timers_.erase(timer_id);
3576 FPDF_SYSTEMTIME PDFiumEngine::Form_GetLocalTime(FPDF_FORMFILLINFO* param) {
3577 base::Time time = base::Time::Now();
3578 base::Time::Exploded exploded;
3579 time.LocalExplode(&exploded);
3581 FPDF_SYSTEMTIME rv;
3582 rv.wYear = exploded.year;
3583 rv.wMonth = exploded.month;
3584 rv.wDayOfWeek = exploded.day_of_week;
3585 rv.wDay = exploded.day_of_month;
3586 rv.wHour = exploded.hour;
3587 rv.wMinute = exploded.minute;
3588 rv.wSecond = exploded.second;
3589 rv.wMilliseconds = exploded.millisecond;
3590 return rv;
3593 void PDFiumEngine::Form_OnChange(FPDF_FORMFILLINFO* param) {
3594 // Don't care about.
3597 FPDF_PAGE PDFiumEngine::Form_GetPage(FPDF_FORMFILLINFO* param,
3598 FPDF_DOCUMENT document,
3599 int page_index) {
3600 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3601 if (page_index < 0 || page_index >= static_cast<int>(engine->pages_.size()))
3602 return NULL;
3603 return engine->pages_[page_index]->GetPage();
3606 FPDF_PAGE PDFiumEngine::Form_GetCurrentPage(FPDF_FORMFILLINFO* param,
3607 FPDF_DOCUMENT document) {
3608 // TODO(jam): find out what this is used for.
3609 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3610 int index = engine->last_page_mouse_down_;
3611 if (index == -1) {
3612 index = engine->GetMostVisiblePage();
3613 if (index == -1) {
3614 NOTREACHED();
3615 return NULL;
3619 return engine->pages_[index]->GetPage();
3622 int PDFiumEngine::Form_GetRotation(FPDF_FORMFILLINFO* param, FPDF_PAGE page) {
3623 return 0;
3626 void PDFiumEngine::Form_ExecuteNamedAction(FPDF_FORMFILLINFO* param,
3627 FPDF_BYTESTRING named_action) {
3628 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3629 std::string action(named_action);
3630 if (action == "Print") {
3631 engine->client_->Print();
3632 return;
3635 int index = engine->last_page_mouse_down_;
3636 /* Don't try to calculate the most visible page if we don't have a left click
3637 before this event (this code originally copied Form_GetCurrentPage which of
3638 course needs to do that and which doesn't have recursion). This can end up
3639 causing infinite recursion. See http://crbug.com/240413 for more
3640 information. Either way, it's not necessary for the spec'd list of named
3641 actions.
3642 if (index == -1)
3643 index = engine->GetMostVisiblePage();
3645 if (index == -1)
3646 return;
3648 // This is the only list of named actions per the spec (see 12.6.4.11). Adobe
3649 // Reader supports more, like FitWidth, but since they're not part of the spec
3650 // and we haven't got bugs about them, no need to now.
3651 if (action == "NextPage") {
3652 engine->client_->ScrollToPage(index + 1);
3653 } else if (action == "PrevPage") {
3654 engine->client_->ScrollToPage(index - 1);
3655 } else if (action == "FirstPage") {
3656 engine->client_->ScrollToPage(0);
3657 } else if (action == "LastPage") {
3658 engine->client_->ScrollToPage(engine->pages_.size() - 1);
3662 void PDFiumEngine::Form_SetTextFieldFocus(FPDF_FORMFILLINFO* param,
3663 FPDF_WIDESTRING value,
3664 FPDF_DWORD valueLen,
3665 FPDF_BOOL is_focus) {
3666 // Do nothing for now.
3667 // TODO(gene): use this signal to trigger OSK.
3670 void PDFiumEngine::Form_DoURIAction(FPDF_FORMFILLINFO* param,
3671 FPDF_BYTESTRING uri) {
3672 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3673 engine->client_->NavigateTo(std::string(uri), false);
3676 void PDFiumEngine::Form_DoGoToAction(FPDF_FORMFILLINFO* param,
3677 int page_index,
3678 int zoom_mode,
3679 float* position_array,
3680 int size_of_array) {
3681 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3682 engine->client_->ScrollToPage(page_index);
3685 int PDFiumEngine::Form_Alert(IPDF_JSPLATFORM* param,
3686 FPDF_WIDESTRING message,
3687 FPDF_WIDESTRING title,
3688 int type,
3689 int icon) {
3690 // See fpdfformfill.h for these values.
3691 enum AlertType {
3692 ALERT_TYPE_OK = 0,
3693 ALERT_TYPE_OK_CANCEL,
3694 ALERT_TYPE_YES_ON,
3695 ALERT_TYPE_YES_NO_CANCEL
3698 enum AlertResult {
3699 ALERT_RESULT_OK = 1,
3700 ALERT_RESULT_CANCEL,
3701 ALERT_RESULT_NO,
3702 ALERT_RESULT_YES
3705 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3706 std::string message_str =
3707 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(message));
3708 if (type == ALERT_TYPE_OK) {
3709 engine->client_->Alert(message_str);
3710 return ALERT_RESULT_OK;
3713 bool rv = engine->client_->Confirm(message_str);
3714 if (type == ALERT_TYPE_OK_CANCEL)
3715 return rv ? ALERT_RESULT_OK : ALERT_RESULT_CANCEL;
3716 return rv ? ALERT_RESULT_YES : ALERT_RESULT_NO;
3719 void PDFiumEngine::Form_Beep(IPDF_JSPLATFORM* param, int type) {
3720 // Beeps are annoying, and not possible using javascript, so ignore for now.
3723 int PDFiumEngine::Form_Response(IPDF_JSPLATFORM* param,
3724 FPDF_WIDESTRING question,
3725 FPDF_WIDESTRING title,
3726 FPDF_WIDESTRING default_response,
3727 FPDF_WIDESTRING label,
3728 FPDF_BOOL password,
3729 void* response,
3730 int length) {
3731 std::string question_str = base::UTF16ToUTF8(
3732 reinterpret_cast<const base::char16*>(question));
3733 std::string default_str = base::UTF16ToUTF8(
3734 reinterpret_cast<const base::char16*>(default_response));
3736 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3737 std::string rv = engine->client_->Prompt(question_str, default_str);
3738 base::string16 rv_16 = base::UTF8ToUTF16(rv);
3739 int rv_bytes = rv_16.size() * sizeof(base::char16);
3740 if (response) {
3741 int bytes_to_copy = rv_bytes < length ? rv_bytes : length;
3742 memcpy(response, rv_16.c_str(), bytes_to_copy);
3744 return rv_bytes;
3747 int PDFiumEngine::Form_GetFilePath(IPDF_JSPLATFORM* param,
3748 void* file_path,
3749 int length) {
3750 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3751 std::string rv = engine->client_->GetURL();
3752 if (file_path && rv.size() <= static_cast<size_t>(length))
3753 memcpy(file_path, rv.c_str(), rv.size());
3754 return rv.size();
3757 void PDFiumEngine::Form_Mail(IPDF_JSPLATFORM* param,
3758 void* mail_data,
3759 int length,
3760 FPDF_BOOL ui,
3761 FPDF_WIDESTRING to,
3762 FPDF_WIDESTRING subject,
3763 FPDF_WIDESTRING cc,
3764 FPDF_WIDESTRING bcc,
3765 FPDF_WIDESTRING message) {
3766 // Note: |mail_data| and |length| are ignored. We don't handle attachments;
3767 // there is no way with mailto.
3768 std::string to_str =
3769 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(to));
3770 std::string cc_str =
3771 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(cc));
3772 std::string bcc_str =
3773 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(bcc));
3774 std::string subject_str =
3775 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(subject));
3776 std::string message_str =
3777 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(message));
3779 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3780 engine->client_->Email(to_str, cc_str, bcc_str, subject_str, message_str);
3783 void PDFiumEngine::Form_Print(IPDF_JSPLATFORM* param,
3784 FPDF_BOOL ui,
3785 int start,
3786 int end,
3787 FPDF_BOOL silent,
3788 FPDF_BOOL shrink_to_fit,
3789 FPDF_BOOL print_as_image,
3790 FPDF_BOOL reverse,
3791 FPDF_BOOL annotations) {
3792 // No way to pass the extra information to the print dialog using JavaScript.
3793 // Just opening it is fine for now.
3794 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3795 engine->client_->Print();
3798 void PDFiumEngine::Form_SubmitForm(IPDF_JSPLATFORM* param,
3799 void* form_data,
3800 int length,
3801 FPDF_WIDESTRING url) {
3802 std::string url_str =
3803 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(url));
3804 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3805 engine->client_->SubmitForm(url_str, form_data, length);
3808 void PDFiumEngine::Form_GotoPage(IPDF_JSPLATFORM* param,
3809 int page_number) {
3810 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3811 engine->client_->ScrollToPage(page_number);
3814 int PDFiumEngine::Form_Browse(IPDF_JSPLATFORM* param,
3815 void* file_path,
3816 int length) {
3817 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3818 std::string path = engine->client_->ShowFileSelectionDialog();
3819 if (path.size() + 1 <= static_cast<size_t>(length))
3820 memcpy(file_path, &path[0], path.size() + 1);
3821 return path.size() + 1;
3824 FPDF_BOOL PDFiumEngine::Pause_NeedToPauseNow(IFSDK_PAUSE* param) {
3825 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3826 return (base::Time::Now() - engine->last_progressive_start_time_).
3827 InMilliseconds() > engine->progressive_paint_timeout_;
3830 ScopedUnsupportedFeature::ScopedUnsupportedFeature(PDFiumEngine* engine)
3831 : engine_(engine), old_engine_(g_engine_for_unsupported) {
3832 g_engine_for_unsupported = engine_;
3835 ScopedUnsupportedFeature::~ScopedUnsupportedFeature() {
3836 g_engine_for_unsupported = old_engine_;
3839 PDFEngineExports* PDFEngineExports::Create() {
3840 return new PDFiumEngineExports;
3843 namespace {
3845 int CalculatePosition(FPDF_PAGE page,
3846 const PDFiumEngineExports::RenderingSettings& settings,
3847 pp::Rect* dest) {
3848 int page_width = static_cast<int>(ConvertUnitDouble(FPDF_GetPageWidth(page),
3849 kPointsPerInch,
3850 settings.dpi_x));
3851 int page_height = static_cast<int>(ConvertUnitDouble(FPDF_GetPageHeight(page),
3852 kPointsPerInch,
3853 settings.dpi_y));
3855 // Start by assuming that we will draw exactly to the bounds rect
3856 // specified.
3857 *dest = settings.bounds;
3859 int rotate = 0; // normal orientation.
3861 // Auto-rotate landscape pages to print correctly.
3862 if (settings.autorotate &&
3863 (dest->width() > dest->height()) != (page_width > page_height)) {
3864 rotate = 3; // 90 degrees counter-clockwise.
3865 std::swap(page_width, page_height);
3868 // See if we need to scale the output
3869 bool scale_to_bounds = false;
3870 if (settings.fit_to_bounds &&
3871 ((page_width > dest->width()) || (page_height > dest->height()))) {
3872 scale_to_bounds = true;
3873 } else if (settings.stretch_to_bounds &&
3874 ((page_width < dest->width()) || (page_height < dest->height()))) {
3875 scale_to_bounds = true;
3878 if (scale_to_bounds) {
3879 // If we need to maintain aspect ratio, calculate the actual width and
3880 // height.
3881 if (settings.keep_aspect_ratio) {
3882 double scale_factor_x = page_width;
3883 scale_factor_x /= dest->width();
3884 double scale_factor_y = page_height;
3885 scale_factor_y /= dest->height();
3886 if (scale_factor_x > scale_factor_y) {
3887 dest->set_height(page_height / scale_factor_x);
3888 } else {
3889 dest->set_width(page_width / scale_factor_y);
3892 } else {
3893 // We are not scaling to bounds. Draw in the actual page size. If the
3894 // actual page size is larger than the bounds, the output will be
3895 // clipped.
3896 dest->set_width(page_width);
3897 dest->set_height(page_height);
3900 if (settings.center_in_bounds) {
3901 pp::Point offset((settings.bounds.width() - dest->width()) / 2,
3902 (settings.bounds.height() - dest->height()) / 2);
3903 dest->Offset(offset);
3905 return rotate;
3908 } // namespace
3910 #if defined(OS_WIN)
3911 bool PDFiumEngineExports::RenderPDFPageToDC(const void* pdf_buffer,
3912 int buffer_size,
3913 int page_number,
3914 const RenderingSettings& settings,
3915 HDC dc) {
3916 FPDF_DOCUMENT doc = FPDF_LoadMemDocument(pdf_buffer, buffer_size, NULL);
3917 if (!doc)
3918 return false;
3919 FPDF_PAGE page = FPDF_LoadPage(doc, page_number);
3920 if (!page) {
3921 FPDF_CloseDocument(doc);
3922 return false;
3924 RenderingSettings new_settings = settings;
3925 // calculate the page size
3926 if (new_settings.dpi_x == -1)
3927 new_settings.dpi_x = GetDeviceCaps(dc, LOGPIXELSX);
3928 if (new_settings.dpi_y == -1)
3929 new_settings.dpi_y = GetDeviceCaps(dc, LOGPIXELSY);
3931 pp::Rect dest;
3932 int rotate = CalculatePosition(page, new_settings, &dest);
3934 int save_state = SaveDC(dc);
3935 // The caller wanted all drawing to happen within the bounds specified.
3936 // Based on scale calculations, our destination rect might be larger
3937 // than the bounds. Set the clip rect to the bounds.
3938 IntersectClipRect(dc, settings.bounds.x(), settings.bounds.y(),
3939 settings.bounds.x() + settings.bounds.width(),
3940 settings.bounds.y() + settings.bounds.height());
3942 // A temporary hack. PDFs generated by Cairo (used by Chrome OS to generate
3943 // a PDF output from a webpage) result in very large metafiles and the
3944 // rendering using FPDF_RenderPage is incorrect. In this case, render as a
3945 // bitmap. Note that this code does not kick in for PDFs printed from Chrome
3946 // because in that case we create a temp PDF first before printing and this
3947 // temp PDF does not have a creator string that starts with "cairo".
3948 bool use_bitmap = false;
3949 if (base::StartsWith(GetDocumentMetadata(doc, "Creator"), "cairo",
3950 base::CompareCase::INSENSITIVE_ASCII)) {
3951 use_bitmap = true;
3954 // Another temporary hack. Some PDFs seems to render very slowly if
3955 // FPDF_RenderPage is directly used on a printer DC. I suspect it is
3956 // because of the code to talk Postscript directly to the printer if
3957 // the printer supports this. Need to discuss this with PDFium. For now,
3958 // render to a bitmap and then blit the bitmap to the DC if we have been
3959 // supplied a printer DC.
3960 int device_type = GetDeviceCaps(dc, TECHNOLOGY);
3961 if (use_bitmap ||
3962 (device_type == DT_RASPRINTER) || (device_type == DT_PLOTTER)) {
3963 FPDF_BITMAP bitmap = FPDFBitmap_Create(dest.width(), dest.height(),
3964 FPDFBitmap_BGRx);
3965 // Clear the bitmap
3966 FPDFBitmap_FillRect(bitmap, 0, 0, dest.width(), dest.height(), 0xFFFFFFFF);
3967 FPDF_RenderPageBitmap(
3968 bitmap, page, 0, 0, dest.width(), dest.height(), rotate,
3969 FPDF_ANNOT | FPDF_PRINTING | FPDF_NO_CATCH);
3970 int stride = FPDFBitmap_GetStride(bitmap);
3971 BITMAPINFO bmi;
3972 memset(&bmi, 0, sizeof(bmi));
3973 bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
3974 bmi.bmiHeader.biWidth = dest.width();
3975 bmi.bmiHeader.biHeight = -dest.height(); // top-down image
3976 bmi.bmiHeader.biPlanes = 1;
3977 bmi.bmiHeader.biBitCount = 32;
3978 bmi.bmiHeader.biCompression = BI_RGB;
3979 bmi.bmiHeader.biSizeImage = stride * dest.height();
3980 StretchDIBits(dc, dest.x(), dest.y(), dest.width(), dest.height(),
3981 0, 0, dest.width(), dest.height(),
3982 FPDFBitmap_GetBuffer(bitmap), &bmi, DIB_RGB_COLORS, SRCCOPY);
3983 FPDFBitmap_Destroy(bitmap);
3984 } else {
3985 FPDF_RenderPage(dc, page, dest.x(), dest.y(), dest.width(), dest.height(),
3986 rotate, FPDF_ANNOT | FPDF_PRINTING | FPDF_NO_CATCH);
3988 RestoreDC(dc, save_state);
3989 FPDF_ClosePage(page);
3990 FPDF_CloseDocument(doc);
3991 return true;
3993 #endif // OS_WIN
3995 bool PDFiumEngineExports::RenderPDFPageToBitmap(
3996 const void* pdf_buffer,
3997 int pdf_buffer_size,
3998 int page_number,
3999 const RenderingSettings& settings,
4000 void* bitmap_buffer) {
4001 FPDF_DOCUMENT doc = FPDF_LoadMemDocument(pdf_buffer, pdf_buffer_size, NULL);
4002 if (!doc)
4003 return false;
4004 FPDF_PAGE page = FPDF_LoadPage(doc, page_number);
4005 if (!page) {
4006 FPDF_CloseDocument(doc);
4007 return false;
4010 pp::Rect dest;
4011 int rotate = CalculatePosition(page, settings, &dest);
4013 FPDF_BITMAP bitmap =
4014 FPDFBitmap_CreateEx(settings.bounds.width(), settings.bounds.height(),
4015 FPDFBitmap_BGRA, bitmap_buffer,
4016 settings.bounds.width() * 4);
4017 // Clear the bitmap
4018 FPDFBitmap_FillRect(bitmap, 0, 0, settings.bounds.width(),
4019 settings.bounds.height(), 0xFFFFFFFF);
4020 // Shift top-left corner of bounds to (0, 0) if it's not there.
4021 dest.set_point(dest.point() - settings.bounds.point());
4022 FPDF_RenderPageBitmap(
4023 bitmap, page, dest.x(), dest.y(), dest.width(), dest.height(), rotate,
4024 FPDF_ANNOT | FPDF_PRINTING | FPDF_NO_CATCH);
4025 FPDFBitmap_Destroy(bitmap);
4026 FPDF_ClosePage(page);
4027 FPDF_CloseDocument(doc);
4028 return true;
4031 bool PDFiumEngineExports::GetPDFDocInfo(const void* pdf_buffer,
4032 int buffer_size,
4033 int* page_count,
4034 double* max_page_width) {
4035 FPDF_DOCUMENT doc = FPDF_LoadMemDocument(pdf_buffer, buffer_size, NULL);
4036 if (!doc)
4037 return false;
4038 int page_count_local = FPDF_GetPageCount(doc);
4039 if (page_count) {
4040 *page_count = page_count_local;
4042 if (max_page_width) {
4043 *max_page_width = 0;
4044 for (int page_number = 0; page_number < page_count_local; page_number++) {
4045 double page_width = 0;
4046 double page_height = 0;
4047 FPDF_GetPageSizeByIndex(doc, page_number, &page_width, &page_height);
4048 if (page_width > *max_page_width) {
4049 *max_page_width = page_width;
4053 FPDF_CloseDocument(doc);
4054 return true;
4057 bool PDFiumEngineExports::GetPDFPageSizeByIndex(
4058 const void* pdf_buffer,
4059 int pdf_buffer_size,
4060 int page_number,
4061 double* width,
4062 double* height) {
4063 FPDF_DOCUMENT doc = FPDF_LoadMemDocument(pdf_buffer, pdf_buffer_size, NULL);
4064 if (!doc)
4065 return false;
4066 bool success = FPDF_GetPageSizeByIndex(doc, page_number, width, height) != 0;
4067 FPDF_CloseDocument(doc);
4068 return success;
4071 } // namespace chrome_pdf