Delete chrome.mediaGalleriesPrivate because the functionality unique to it has since...
[chromium-blink-merge.git] / pdf / pdfium / pdfium_engine.cc
blob86485e0c8a696628c301cd27ea9420a81bfd4db2
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/json/json_writer.h"
10 #include "base/logging.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/stl_util.h"
13 #include "base/strings/string_number_conversions.h"
14 #include "base/strings/string_piece.h"
15 #include "base/strings/string_util.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "base/values.h"
18 #include "pdf/draw_utils.h"
19 #include "pdf/pdfium/pdfium_api_string_buffer_adapter.h"
20 #include "pdf/pdfium/pdfium_mem_buffer_file_read.h"
21 #include "pdf/pdfium/pdfium_mem_buffer_file_write.h"
22 #include "ppapi/c/pp_errors.h"
23 #include "ppapi/c/pp_input_event.h"
24 #include "ppapi/c/ppb_core.h"
25 #include "ppapi/c/private/ppb_pdf.h"
26 #include "ppapi/cpp/dev/memory_dev.h"
27 #include "ppapi/cpp/input_event.h"
28 #include "ppapi/cpp/instance.h"
29 #include "ppapi/cpp/module.h"
30 #include "ppapi/cpp/private/pdf.h"
31 #include "ppapi/cpp/trusted/browser_font_trusted.h"
32 #include "ppapi/cpp/url_response_info.h"
33 #include "ppapi/cpp/var.h"
34 #include "ppapi/cpp/var_dictionary.h"
35 #include "third_party/pdfium/fpdfsdk/include/fpdf_ext.h"
36 #include "third_party/pdfium/fpdfsdk/include/fpdf_flatten.h"
37 #include "third_party/pdfium/fpdfsdk/include/fpdf_searchex.h"
38 #include "third_party/pdfium/fpdfsdk/include/fpdf_sysfontinfo.h"
39 #include "third_party/pdfium/fpdfsdk/include/fpdf_transformpage.h"
40 #include "third_party/pdfium/fpdfsdk/include/fpdfedit.h"
41 #include "third_party/pdfium/fpdfsdk/include/fpdfppo.h"
42 #include "third_party/pdfium/fpdfsdk/include/fpdfsave.h"
43 #include "third_party/pdfium/fpdfsdk/include/pdfwindow/PDFWindow.h"
44 #include "third_party/pdfium/fpdfsdk/include/pdfwindow/PWL_FontMap.h"
45 #include "ui/events/keycodes/keyboard_codes.h"
47 namespace chrome_pdf {
49 namespace {
51 #define kPageShadowTop 3
52 #define kPageShadowBottom 7
53 #define kPageShadowLeft 5
54 #define kPageShadowRight 5
56 #define kPageSeparatorThickness 4
57 #define kHighlightColorR 153
58 #define kHighlightColorG 193
59 #define kHighlightColorB 218
61 const uint32 kPendingPageColor = 0xFFEEEEEE;
63 #define kFormHighlightColor 0xFFE4DD
64 #define kFormHighlightAlpha 100
66 #define kMaxPasswordTries 3
68 // See Table 3.20 in
69 // http://www.adobe.com/devnet/acrobat/pdfs/pdf_reference_1-7.pdf
70 #define kPDFPermissionPrintLowQualityMask 1 << 2
71 #define kPDFPermissionPrintHighQualityMask 1 << 11
72 #define kPDFPermissionCopyMask 1 << 4
73 #define kPDFPermissionCopyAccessibleMask 1 << 9
75 #define kLoadingTextVerticalOffset 50
77 // The maximum amount of time we'll spend doing a paint before we give back
78 // control of the thread.
79 #define kMaxProgressivePaintTimeMs 50
81 // The maximum amount of time we'll spend doing the first paint. This is less
82 // than the above to keep things smooth if the user is scrolling quickly. We
83 // try painting a little because with accelerated compositing, we get flushes
84 // only every 16 ms. If we were to wait until the next flush to paint the rest
85 // of the pdf, we would never get to draw the pdf and would only draw the
86 // scrollbars. This value is picked to give enough time for gpu related code to
87 // do its thing and still fit within the timelimit for 60Hz. For the
88 // non-composited case, this doesn't make things worse since we're still
89 // painting the scrollbars > 60 Hz.
90 #define kMaxInitialProgressivePaintTimeMs 10
92 // Copied from printing/units.cc because we don't want to depend on printing
93 // since it brings in libpng which causes duplicate symbols with PDFium.
94 const int kPointsPerInch = 72;
95 const int kPixelsPerInch = 96;
97 struct ClipBox {
98 float left;
99 float right;
100 float top;
101 float bottom;
104 int ConvertUnit(int value, int old_unit, int new_unit) {
105 // With integer arithmetic, to divide a value with correct rounding, you need
106 // to add half of the divisor value to the dividend value. You need to do the
107 // reverse with negative number.
108 if (value >= 0) {
109 return ((value * new_unit) + (old_unit / 2)) / old_unit;
110 } else {
111 return ((value * new_unit) - (old_unit / 2)) / old_unit;
115 std::vector<uint32_t> GetPageNumbersFromPrintPageNumberRange(
116 const PP_PrintPageNumberRange_Dev* page_ranges,
117 uint32_t page_range_count) {
118 std::vector<uint32_t> page_numbers;
119 for (uint32_t index = 0; index < page_range_count; ++index) {
120 for (uint32_t page_number = page_ranges[index].first_page_number;
121 page_number <= page_ranges[index].last_page_number; ++page_number) {
122 page_numbers.push_back(page_number);
125 return page_numbers;
128 #if defined(OS_LINUX)
130 PP_Instance g_last_instance_id;
132 struct PDFFontSubstitution {
133 const char* pdf_name;
134 const char* face;
135 bool bold;
136 bool italic;
139 PP_BrowserFont_Trusted_Weight WeightToBrowserFontTrustedWeight(int weight) {
140 static_assert(PP_BROWSERFONT_TRUSTED_WEIGHT_100 == 0,
141 "PP_BrowserFont_Trusted_Weight min");
142 static_assert(PP_BROWSERFONT_TRUSTED_WEIGHT_900 == 8,
143 "PP_BrowserFont_Trusted_Weight max");
144 const int kMinimumWeight = 100;
145 const int kMaximumWeight = 900;
146 int normalized_weight =
147 std::min(std::max(weight, kMinimumWeight), kMaximumWeight);
148 normalized_weight = (normalized_weight / 100) - 1;
149 return static_cast<PP_BrowserFont_Trusted_Weight>(normalized_weight);
152 // This list is for CPWL_FontMap::GetDefaultFontByCharset().
153 // We pretend to have these font natively and let the browser (or underlying
154 // fontconfig) to pick the proper font on the system.
155 void EnumFonts(struct _FPDF_SYSFONTINFO* sysfontinfo, void* mapper) {
156 FPDF_AddInstalledFont(mapper, "Arial", FXFONT_DEFAULT_CHARSET);
158 int i = 0;
159 while (CPWL_FontMap::defaultTTFMap[i].charset != -1) {
160 FPDF_AddInstalledFont(mapper,
161 CPWL_FontMap::defaultTTFMap[i].fontname,
162 CPWL_FontMap::defaultTTFMap[i].charset);
163 ++i;
167 const PDFFontSubstitution PDFFontSubstitutions[] = {
168 {"Courier", "Courier New", false, false},
169 {"Courier-Bold", "Courier New", true, false},
170 {"Courier-BoldOblique", "Courier New", true, true},
171 {"Courier-Oblique", "Courier New", false, true},
172 {"Helvetica", "Arial", false, false},
173 {"Helvetica-Bold", "Arial", true, false},
174 {"Helvetica-BoldOblique", "Arial", true, true},
175 {"Helvetica-Oblique", "Arial", false, true},
176 {"Times-Roman", "Times New Roman", false, false},
177 {"Times-Bold", "Times New Roman", true, false},
178 {"Times-BoldItalic", "Times New Roman", true, true},
179 {"Times-Italic", "Times New Roman", false, true},
181 // MS P?(Mincho|Gothic) are the most notable fonts in Japanese PDF files
182 // without embedding the glyphs. Sometimes the font names are encoded
183 // in Japanese Windows's locale (CP932/Shift_JIS) without space.
184 // Most Linux systems don't have the exact font, but for outsourcing
185 // fontconfig to find substitutable font in the system, we pass ASCII
186 // font names to it.
187 {"MS-PGothic", "MS PGothic", false, false},
188 {"MS-Gothic", "MS Gothic", false, false},
189 {"MS-PMincho", "MS PMincho", false, false},
190 {"MS-Mincho", "MS Mincho", false, false},
191 // MS PGothic in Shift_JIS encoding.
192 {"\x82\x6C\x82\x72\x82\x6F\x83\x53\x83\x56\x83\x62\x83\x4E",
193 "MS PGothic", false, false},
194 // MS Gothic in Shift_JIS encoding.
195 {"\x82\x6C\x82\x72\x83\x53\x83\x56\x83\x62\x83\x4E",
196 "MS Gothic", false, false},
197 // MS PMincho in Shift_JIS encoding.
198 {"\x82\x6C\x82\x72\x82\x6F\x96\xBE\x92\xA9",
199 "MS PMincho", false, false},
200 // MS Mincho in Shift_JIS encoding.
201 {"\x82\x6C\x82\x72\x96\xBE\x92\xA9",
202 "MS Mincho", false, false},
205 void* MapFont(struct _FPDF_SYSFONTINFO*, int weight, int italic,
206 int charset, int pitch_family, const char* face, int* exact) {
207 // Do not attempt to map fonts if pepper is not initialized (for privet local
208 // printing).
209 // TODO(noamsml): Real font substitution (http://crbug.com/391978)
210 if (!pp::Module::Get())
211 return NULL;
213 pp::BrowserFontDescription description;
215 // Pretend the system does not have the Symbol font to force a fallback to
216 // the built in Symbol font in CFX_FontMapper::FindSubstFont().
217 if (strcmp(face, "Symbol") == 0)
218 return NULL;
220 if (pitch_family & FXFONT_FF_FIXEDPITCH) {
221 description.set_family(PP_BROWSERFONT_TRUSTED_FAMILY_MONOSPACE);
222 } else if (pitch_family & FXFONT_FF_ROMAN) {
223 description.set_family(PP_BROWSERFONT_TRUSTED_FAMILY_SERIF);
226 // Map from the standard PDF fonts to TrueType font names.
227 size_t i;
228 for (i = 0; i < arraysize(PDFFontSubstitutions); ++i) {
229 if (strcmp(face, PDFFontSubstitutions[i].pdf_name) == 0) {
230 description.set_face(PDFFontSubstitutions[i].face);
231 if (PDFFontSubstitutions[i].bold)
232 description.set_weight(PP_BROWSERFONT_TRUSTED_WEIGHT_BOLD);
233 if (PDFFontSubstitutions[i].italic)
234 description.set_italic(true);
235 break;
239 if (i == arraysize(PDFFontSubstitutions)) {
240 // TODO(kochi): Pass the face in UTF-8. If face is not encoded in UTF-8,
241 // convert to UTF-8 before passing.
242 description.set_face(face);
244 description.set_weight(WeightToBrowserFontTrustedWeight(weight));
245 description.set_italic(italic > 0);
248 if (!pp::PDF::IsAvailable()) {
249 NOTREACHED();
250 return NULL;
253 PP_Resource font_resource = pp::PDF::GetFontFileWithFallback(
254 pp::InstanceHandle(g_last_instance_id),
255 &description.pp_font_description(),
256 static_cast<PP_PrivateFontCharset>(charset));
257 long res_id = font_resource;
258 return reinterpret_cast<void*>(res_id);
261 unsigned long GetFontData(struct _FPDF_SYSFONTINFO*, void* font_id,
262 unsigned int table, unsigned char* buffer,
263 unsigned long buf_size) {
264 if (!pp::PDF::IsAvailable()) {
265 NOTREACHED();
266 return 0;
269 uint32_t size = buf_size;
270 long res_id = reinterpret_cast<long>(font_id);
271 if (!pp::PDF::GetFontTableForPrivateFontFile(res_id, table, buffer, &size))
272 return 0;
273 return size;
276 void DeleteFont(struct _FPDF_SYSFONTINFO*, void* font_id) {
277 long res_id = reinterpret_cast<long>(font_id);
278 pp::Module::Get()->core()->ReleaseResource(res_id);
281 FPDF_SYSFONTINFO g_font_info = {
284 EnumFonts,
285 MapFont,
287 GetFontData,
290 DeleteFont
292 #endif // defined(OS_LINUX)
294 PDFiumEngine* g_engine_for_unsupported;
296 void Unsupported_Handler(UNSUPPORT_INFO*, int type) {
297 if (!g_engine_for_unsupported) {
298 NOTREACHED();
299 return;
302 g_engine_for_unsupported->UnsupportedFeature(type);
305 UNSUPPORT_INFO g_unsuppored_info = {
307 Unsupported_Handler
310 // Set the destination page size and content area in points based on source
311 // page rotation and orientation.
313 // |rotated| True if source page is rotated 90 degree or 270 degree.
314 // |is_src_page_landscape| is true if the source page orientation is landscape.
315 // |page_size| has the actual destination page size in points.
316 // |content_rect| has the actual destination page printable area values in
317 // points.
318 void SetPageSizeAndContentRect(bool rotated,
319 bool is_src_page_landscape,
320 pp::Size* page_size,
321 pp::Rect* content_rect) {
322 bool is_dst_page_landscape = page_size->width() > page_size->height();
323 bool page_orientation_mismatched = is_src_page_landscape !=
324 is_dst_page_landscape;
325 bool rotate_dst_page = rotated ^ page_orientation_mismatched;
326 if (rotate_dst_page) {
327 page_size->SetSize(page_size->height(), page_size->width());
328 content_rect->SetRect(content_rect->y(), content_rect->x(),
329 content_rect->height(), content_rect->width());
333 // Calculate the scale factor between |content_rect| and a page of size
334 // |src_width| x |src_height|.
336 // |scale_to_fit| is true, if we need to calculate the scale factor.
337 // |content_rect| specifies the printable area of the destination page, with
338 // origin at left-bottom. Values are in points.
339 // |src_width| specifies the source page width in points.
340 // |src_height| specifies the source page height in points.
341 // |rotated| True if source page is rotated 90 degree or 270 degree.
342 double CalculateScaleFactor(bool scale_to_fit,
343 const pp::Rect& content_rect,
344 double src_width, double src_height, bool rotated) {
345 if (!scale_to_fit || src_width == 0 || src_height == 0)
346 return 1.0;
348 double actual_source_page_width = rotated ? src_height : src_width;
349 double actual_source_page_height = rotated ? src_width : src_height;
350 double ratio_x = static_cast<double>(content_rect.width()) /
351 actual_source_page_width;
352 double ratio_y = static_cast<double>(content_rect.height()) /
353 actual_source_page_height;
354 return std::min(ratio_x, ratio_y);
357 // Compute source clip box boundaries based on the crop box / media box of
358 // source page and scale factor.
360 // |page| Handle to the source page. Returned by FPDF_LoadPage function.
361 // |scale_factor| specifies the scale factor that should be applied to source
362 // clip box boundaries.
363 // |rotated| True if source page is rotated 90 degree or 270 degree.
364 // |clip_box| out param to hold the computed source clip box values.
365 void CalculateClipBoxBoundary(FPDF_PAGE page, double scale_factor, bool rotated,
366 ClipBox* clip_box) {
367 if (!FPDFPage_GetCropBox(page, &clip_box->left, &clip_box->bottom,
368 &clip_box->right, &clip_box->top)) {
369 if (!FPDFPage_GetMediaBox(page, &clip_box->left, &clip_box->bottom,
370 &clip_box->right, &clip_box->top)) {
371 // Make the default size to be letter size (8.5" X 11"). We are just
372 // following the PDFium way of handling these corner cases. PDFium always
373 // consider US-Letter as the default page size.
374 float paper_width = 612;
375 float paper_height = 792;
376 clip_box->left = 0;
377 clip_box->bottom = 0;
378 clip_box->right = rotated ? paper_height : paper_width;
379 clip_box->top = rotated ? paper_width : paper_height;
382 clip_box->left *= scale_factor;
383 clip_box->right *= scale_factor;
384 clip_box->bottom *= scale_factor;
385 clip_box->top *= scale_factor;
388 // Calculate the clip box translation offset for a page that does need to be
389 // scaled. All parameters are in points.
391 // |content_rect| specifies the printable area of the destination page, with
392 // origin at left-bottom.
393 // |source_clip_box| specifies the source clip box positions, relative to
394 // origin at left-bottom.
395 // |offset_x| and |offset_y| will contain the final translation offsets for the
396 // source clip box, relative to origin at left-bottom.
397 void CalculateScaledClipBoxOffset(const pp::Rect& content_rect,
398 const ClipBox& source_clip_box,
399 double* offset_x, double* offset_y) {
400 const float clip_box_width = source_clip_box.right - source_clip_box.left;
401 const float clip_box_height = source_clip_box.top - source_clip_box.bottom;
403 // Center the intended clip region to real clip region.
404 *offset_x = (content_rect.width() - clip_box_width) / 2 + content_rect.x() -
405 source_clip_box.left;
406 *offset_y = (content_rect.height() - clip_box_height) / 2 + content_rect.y() -
407 source_clip_box.bottom;
410 // Calculate the clip box offset for a page that does not need to be scaled.
411 // All parameters are in points.
413 // |content_rect| specifies the printable area of the destination page, with
414 // origin at left-bottom.
415 // |rotation| specifies the source page rotation values which are N / 90
416 // degrees.
417 // |page_width| specifies the screen destination page width.
418 // |page_height| specifies the screen destination page height.
419 // |source_clip_box| specifies the source clip box positions, relative to origin
420 // at left-bottom.
421 // |offset_x| and |offset_y| will contain the final translation offsets for the
422 // source clip box, relative to origin at left-bottom.
423 void CalculateNonScaledClipBoxOffset(const pp::Rect& content_rect, int rotation,
424 int page_width, int page_height,
425 const ClipBox& source_clip_box,
426 double* offset_x, double* offset_y) {
427 // Align the intended clip region to left-top corner of real clip region.
428 switch (rotation) {
429 case 0:
430 *offset_x = -1 * source_clip_box.left;
431 *offset_y = page_height - source_clip_box.top;
432 break;
433 case 1:
434 *offset_x = 0;
435 *offset_y = -1 * source_clip_box.bottom;
436 break;
437 case 2:
438 *offset_x = page_width - source_clip_box.right;
439 *offset_y = 0;
440 break;
441 case 3:
442 *offset_x = page_height - source_clip_box.right;
443 *offset_y = page_width - source_clip_box.top;
444 break;
445 default:
446 NOTREACHED();
447 break;
451 // This formats a string with special 0xfffe end-of-line hyphens the same way
452 // as Adobe Reader. When a hyphen is encountered, the next non-CR/LF whitespace
453 // becomes CR+LF and the hyphen is erased. If there is no whitespace between
454 // two hyphens, the latter hyphen is erased and ignored.
455 void FormatStringWithHyphens(base::string16* text) {
456 // First pass marks all the hyphen positions.
457 struct HyphenPosition {
458 HyphenPosition() : position(0), next_whitespace_position(0) {}
459 size_t position;
460 size_t next_whitespace_position; // 0 for none
462 std::vector<HyphenPosition> hyphen_positions;
463 HyphenPosition current_hyphen_position;
464 bool current_hyphen_position_is_valid = false;
465 const base::char16 kPdfiumHyphenEOL = 0xfffe;
467 for (size_t i = 0; i < text->size(); ++i) {
468 const base::char16& current_char = (*text)[i];
469 if (current_char == kPdfiumHyphenEOL) {
470 if (current_hyphen_position_is_valid)
471 hyphen_positions.push_back(current_hyphen_position);
472 current_hyphen_position = HyphenPosition();
473 current_hyphen_position.position = i;
474 current_hyphen_position_is_valid = true;
475 } else if (IsWhitespace(current_char)) {
476 if (current_hyphen_position_is_valid) {
477 if (current_char != L'\r' && current_char != L'\n')
478 current_hyphen_position.next_whitespace_position = i;
479 hyphen_positions.push_back(current_hyphen_position);
480 current_hyphen_position_is_valid = false;
484 if (current_hyphen_position_is_valid)
485 hyphen_positions.push_back(current_hyphen_position);
487 // With all the hyphen positions, do the search and replace.
488 while (!hyphen_positions.empty()) {
489 static const base::char16 kCr[] = {L'\r', L'\0'};
490 const HyphenPosition& position = hyphen_positions.back();
491 if (position.next_whitespace_position != 0) {
492 (*text)[position.next_whitespace_position] = L'\n';
493 text->insert(position.next_whitespace_position, kCr);
495 text->erase(position.position, 1);
496 hyphen_positions.pop_back();
499 // Adobe Reader also get rid of trailing spaces right before a CRLF.
500 static const base::char16 kSpaceCrCn[] = {L' ', L'\r', L'\n', L'\0'};
501 static const base::char16 kCrCn[] = {L'\r', L'\n', L'\0'};
502 ReplaceSubstringsAfterOffset(text, 0, kSpaceCrCn, kCrCn);
505 // Replace CR/LF with just LF on POSIX.
506 void FormatStringForOS(base::string16* text) {
507 #if defined(OS_POSIX)
508 static const base::char16 kCr[] = {L'\r', L'\0'};
509 static const base::char16 kBlank[] = {L'\0'};
510 base::ReplaceChars(*text, kCr, kBlank, text);
511 #elif defined(OS_WIN)
512 // Do nothing
513 #else
514 NOTIMPLEMENTED();
515 #endif
518 // Returns a VarDictionary (representing a bookmark), which in turn contains
519 // child VarDictionaries (representing the child bookmarks).
520 // If NULL is passed in as the bookmark then we traverse from the "root".
521 // Note that the "root" bookmark contains no useful information.
522 pp::VarDictionary TraverseBookmarks(FPDF_DOCUMENT doc, FPDF_BOOKMARK bookmark) {
523 pp::VarDictionary dict;
524 base::string16 title;
525 unsigned long buffer_size = FPDFBookmark_GetTitle(bookmark, NULL, 0);
526 size_t title_length = buffer_size / sizeof(base::string16::value_type);
528 if (title_length > 0) {
529 PDFiumAPIStringBufferAdapter<base::string16> api_string_adapter(
530 &title, title_length, true);
531 void* data = api_string_adapter.GetData();
532 FPDFBookmark_GetTitle(bookmark, data, buffer_size);
533 api_string_adapter.Close(title_length);
535 dict.Set(pp::Var("title"), pp::Var(base::UTF16ToUTF8(title)));
537 FPDF_DEST dest = FPDFBookmark_GetDest(doc, bookmark);
538 // Some bookmarks don't have a page to select.
539 if (dest) {
540 int page_index = FPDFDest_GetPageIndex(doc, dest);
541 dict.Set(pp::Var("page"), pp::Var(page_index));
544 pp::VarArray children;
545 int child_index = 0;
546 for (FPDF_BOOKMARK child_bookmark = FPDFBookmark_GetFirstChild(doc, bookmark);
547 child_bookmark != NULL;
548 child_bookmark = FPDFBookmark_GetNextSibling(doc, child_bookmark)) {
549 children.Set(child_index, TraverseBookmarks(doc, child_bookmark));
550 child_index++;
552 dict.Set(pp::Var("children"), children);
553 return dict;
556 } // namespace
558 bool InitializeSDK() {
559 FPDF_InitLibrary();
561 #if defined(OS_LINUX)
562 // Font loading doesn't work in the renderer sandbox in Linux.
563 FPDF_SetSystemFontInfo(&g_font_info);
564 #endif
566 FSDK_SetUnSpObjProcessHandler(&g_unsuppored_info);
568 return true;
571 void ShutdownSDK() {
572 FPDF_DestroyLibrary();
575 PDFEngine* PDFEngine::Create(PDFEngine::Client* client) {
576 return new PDFiumEngine(client);
579 PDFiumEngine::PDFiumEngine(PDFEngine::Client* client)
580 : client_(client),
581 current_zoom_(1.0),
582 current_rotation_(0),
583 doc_loader_(this),
584 password_tries_remaining_(0),
585 doc_(NULL),
586 form_(NULL),
587 defer_page_unload_(false),
588 selecting_(false),
589 mouse_down_state_(PDFiumPage::NONSELECTABLE_AREA,
590 PDFiumPage::LinkTarget()),
591 next_page_to_search_(-1),
592 last_page_to_search_(-1),
593 last_character_index_to_search_(-1),
594 permissions_(0),
595 fpdf_availability_(NULL),
596 next_timer_id_(0),
597 last_page_mouse_down_(-1),
598 first_visible_page_(-1),
599 most_visible_page_(-1),
600 called_do_document_action_(false),
601 render_grayscale_(false),
602 progressive_paint_timeout_(0),
603 getting_password_(false) {
604 find_factory_.Initialize(this);
605 password_factory_.Initialize(this);
607 file_access_.m_FileLen = 0;
608 file_access_.m_GetBlock = &GetBlock;
609 file_access_.m_Param = &doc_loader_;
611 file_availability_.version = 1;
612 file_availability_.IsDataAvail = &IsDataAvail;
613 file_availability_.loader = &doc_loader_;
615 download_hints_.version = 1;
616 download_hints_.AddSegment = &AddSegment;
617 download_hints_.loader = &doc_loader_;
619 // Initialize FPDF_FORMFILLINFO member variables. Deriving from this struct
620 // allows the static callbacks to be able to cast the FPDF_FORMFILLINFO in
621 // callbacks to ourself instead of maintaining a map of them to
622 // PDFiumEngine.
623 FPDF_FORMFILLINFO::version = 1;
624 FPDF_FORMFILLINFO::m_pJsPlatform = this;
625 FPDF_FORMFILLINFO::Release = NULL;
626 FPDF_FORMFILLINFO::FFI_Invalidate = Form_Invalidate;
627 FPDF_FORMFILLINFO::FFI_OutputSelectedRect = Form_OutputSelectedRect;
628 FPDF_FORMFILLINFO::FFI_SetCursor = Form_SetCursor;
629 FPDF_FORMFILLINFO::FFI_SetTimer = Form_SetTimer;
630 FPDF_FORMFILLINFO::FFI_KillTimer = Form_KillTimer;
631 FPDF_FORMFILLINFO::FFI_GetLocalTime = Form_GetLocalTime;
632 FPDF_FORMFILLINFO::FFI_OnChange = Form_OnChange;
633 FPDF_FORMFILLINFO::FFI_GetPage = Form_GetPage;
634 FPDF_FORMFILLINFO::FFI_GetCurrentPage = Form_GetCurrentPage;
635 FPDF_FORMFILLINFO::FFI_GetRotation = Form_GetRotation;
636 FPDF_FORMFILLINFO::FFI_ExecuteNamedAction = Form_ExecuteNamedAction;
637 FPDF_FORMFILLINFO::FFI_SetTextFieldFocus = Form_SetTextFieldFocus;
638 FPDF_FORMFILLINFO::FFI_DoURIAction = Form_DoURIAction;
639 FPDF_FORMFILLINFO::FFI_DoGoToAction = Form_DoGoToAction;
640 #ifdef PDF_USE_XFA
641 FPDF_FORMFILLINFO::version = 2;
642 FPDF_FORMFILLINFO::FFI_EmailTo = Form_EmailTo;
643 FPDF_FORMFILLINFO::FFI_DisplayCaret = Form_DisplayCaret;
644 FPDF_FORMFILLINFO::FFI_SetCurrentPage = Form_SetCurrentPage;
645 FPDF_FORMFILLINFO::FFI_GetCurrentPageIndex = Form_GetCurrentPageIndex;
646 FPDF_FORMFILLINFO::FFI_GetPageViewRect = Form_GetPageViewRect;
647 FPDF_FORMFILLINFO::FFI_GetPlatform = Form_GetPlatform;
648 FPDF_FORMFILLINFO::FFI_PopupMenu = Form_PopupMenu;
649 FPDF_FORMFILLINFO::FFI_PostRequestURL = Form_PostRequestURL;
650 FPDF_FORMFILLINFO::FFI_PutRequestURL = Form_PutRequestURL;
651 FPDF_FORMFILLINFO::FFI_UploadTo = Form_UploadTo;
652 FPDF_FORMFILLINFO::FFI_DownloadFromURL = Form_DownloadFromURL;
653 FPDF_FORMFILLINFO::FFI_OpenFile = Form_OpenFile;
654 FPDF_FORMFILLINFO::FFI_GotoURL = Form_GotoURL;
655 FPDF_FORMFILLINFO::FFI_GetLanguage = Form_GetLanguage;
656 #endif // PDF_USE_XFA
657 IPDF_JSPLATFORM::version = 1;
658 IPDF_JSPLATFORM::app_alert = Form_Alert;
659 IPDF_JSPLATFORM::app_beep = Form_Beep;
660 IPDF_JSPLATFORM::app_response = Form_Response;
661 IPDF_JSPLATFORM::Doc_getFilePath = Form_GetFilePath;
662 IPDF_JSPLATFORM::Doc_mail = Form_Mail;
663 IPDF_JSPLATFORM::Doc_print = Form_Print;
664 IPDF_JSPLATFORM::Doc_submitForm = Form_SubmitForm;
665 IPDF_JSPLATFORM::Doc_gotoPage = Form_GotoPage;
666 IPDF_JSPLATFORM::Field_browse = Form_Browse;
668 IFSDK_PAUSE::version = 1;
669 IFSDK_PAUSE::user = NULL;
670 IFSDK_PAUSE::NeedToPauseNow = Pause_NeedToPauseNow;
673 PDFiumEngine::~PDFiumEngine() {
674 for (size_t i = 0; i < pages_.size(); ++i)
675 pages_[i]->Unload();
677 if (doc_) {
678 if (form_) {
679 FORM_DoDocumentAAction(form_, FPDFDOC_AACTION_WC);
681 FPDF_CloseDocument(doc_);
682 if (form_) {
683 FPDFDOC_ExitFormFillEnvironment(form_);
687 if (fpdf_availability_)
688 FPDFAvail_Destroy(fpdf_availability_);
690 STLDeleteElements(&pages_);
693 #ifdef PDF_USE_XFA
695 // This is just for testing, needs to be removed later
696 #if defined(WIN32)
697 #define XFA_TESTFILE(filename) "E:/"#filename
698 #else
699 #define XFA_TESTFILE(filename) "/home/"#filename
700 #endif
702 struct FPDF_FILE {
703 FPDF_FILEHANDLER file_handler;
704 FILE* file;
707 void Sample_Release(FPDF_LPVOID client_data) {
708 if (!client_data)
709 return;
710 FPDF_FILE* file_wrapper = (FPDF_FILE*)client_data;
711 fclose(file_wrapper->file);
712 delete file_wrapper;
715 FPDF_DWORD Sample_GetSize(FPDF_LPVOID client_data) {
716 if (!client_data)
717 return 0;
718 FPDF_FILE* file_wrapper = (FPDF_FILE*)client_data;
719 long cur_pos = ftell(file_wrapper->file);
720 if (cur_pos == -1)
721 return 0;
722 if (fseek(file_wrapper->file, 0, SEEK_END))
723 return 0;
724 long size = ftell(file_wrapper->file);
725 fseek(file_wrapper->file, cur_pos, SEEK_SET);
726 return (FPDF_DWORD)size;
729 FPDF_RESULT Sample_ReadBlock(FPDF_LPVOID client_data,
730 FPDF_DWORD offset,
731 FPDF_LPVOID buffer,
732 FPDF_DWORD size) {
733 if (!client_data)
734 return -1;
735 FPDF_FILE* file_wrapper = (FPDF_FILE*)client_data;
736 if (fseek(file_wrapper->file, (long)offset, SEEK_SET))
737 return -1;
738 size_t read_size = fread(buffer, 1, size, file_wrapper->file);
739 return read_size == size ? 0 : -1;
742 FPDF_RESULT Sample_WriteBlock(FPDF_LPVOID client_data,
743 FPDF_DWORD offset,
744 FPDF_LPCVOID buffer,
745 FPDF_DWORD size) {
746 if (!client_data)
747 return -1;
748 FPDF_FILE* file_wrapper = (FPDF_FILE*)client_data;
749 if (fseek(file_wrapper->file, (long)offset, SEEK_SET))
750 return -1;
751 // Write data
752 size_t write_size = fwrite(buffer, 1, size, file_wrapper->file);
753 return write_size == size ? 0 : -1;
756 FPDF_RESULT Sample_Flush(FPDF_LPVOID client_data) {
757 if (!client_data)
758 return -1;
759 // Flush file
760 fflush(((FPDF_FILE*)client_data)->file);
761 return 0;
764 FPDF_RESULT Sample_Truncate(FPDF_LPVOID client_data, FPDF_DWORD size) {
765 return 0;
768 void PDFiumEngine::Form_EmailTo(FPDF_FORMFILLINFO* param,
769 FPDF_FILEHANDLER* file_handler,
770 FPDF_WIDESTRING to,
771 FPDF_WIDESTRING subject,
772 FPDF_WIDESTRING cc,
773 FPDF_WIDESTRING bcc,
774 FPDF_WIDESTRING message) {
775 std::string to_str =
776 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(to));
777 std::string subject_str =
778 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(subject));
779 std::string cc_str =
780 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(cc));
781 std::string bcc_str =
782 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(bcc));
783 std::string message_str =
784 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(message));
786 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
787 engine->client_->Email(to_str, cc_str, bcc_str, subject_str, message_str);
790 void PDFiumEngine::Form_DisplayCaret(FPDF_FORMFILLINFO* param,
791 FPDF_PAGE page,
792 FPDF_BOOL visible,
793 double left,
794 double top,
795 double right,
796 double bottom) {
797 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
798 engine->client_->UpdateCursor(PP_CURSORTYPE_IBEAM);
799 std::vector<pp::Rect> tickmarks;
800 pp::Rect rect(left, top, right, bottom);
801 tickmarks.push_back(rect);
802 engine->client_->UpdateTickMarks(tickmarks);
805 void PDFiumEngine::Form_SetCurrentPage(FPDF_FORMFILLINFO* param,
806 FPDF_DOCUMENT document,
807 int page) {
808 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
809 pp::Rect page_view_rect = engine->GetPageContentsRect(page);
810 engine->ScrolledToYPosition(page_view_rect.height());
811 pp::Point pos(1, page_view_rect.height());
812 engine->SetScrollPosition(pos);
815 int PDFiumEngine::Form_GetCurrentPageIndex(FPDF_FORMFILLINFO* param,
816 FPDF_DOCUMENT document) {
817 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
818 return engine->GetMostVisiblePage();
821 void PDFiumEngine::Form_GetPageViewRect(FPDF_FORMFILLINFO* param,
822 FPDF_PAGE page,
823 double* left,
824 double* top,
825 double* right,
826 double* bottom) {
827 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
828 int page_index = engine->GetMostVisiblePage();
829 pp::Rect page_view_rect = engine->GetPageContentsRect(page_index);
831 *left = page_view_rect.x();
832 *right = page_view_rect.right();
833 *top = page_view_rect.y();
834 *bottom = page_view_rect.bottom();
837 int PDFiumEngine::Form_GetPlatform(FPDF_FORMFILLINFO* param,
838 void* platform,
839 int length) {
840 int platform_flag = -1;
842 #if defined(WIN32)
843 platform_flag = 0;
844 #elif defined(__linux__)
845 platform_flag = 1;
846 #else
847 platform_flag = 2;
848 #endif
850 std::string javascript = "alert(\"Platform:"
851 + base::DoubleToString(platform_flag)
852 + "\")";
854 return platform_flag;
857 FPDF_BOOL PDFiumEngine::Form_PopupMenu(FPDF_FORMFILLINFO* param,
858 FPDF_PAGE page,
859 FPDF_WIDGET widget,
860 int menu_flag,
861 float x,
862 float y) {
863 return false;
866 FPDF_BOOL PDFiumEngine::Form_PostRequestURL(FPDF_FORMFILLINFO* param,
867 FPDF_WIDESTRING url,
868 FPDF_WIDESTRING data,
869 FPDF_WIDESTRING content_type,
870 FPDF_WIDESTRING encode,
871 FPDF_WIDESTRING header,
872 FPDF_BSTR* response) {
873 std::string url_str =
874 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(url));
875 std::string data_str =
876 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(data));
877 std::string content_type_str =
878 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(content_type));
879 std::string encode_str =
880 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(encode));
881 std::string header_str =
882 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(header));
884 std::string javascript = "alert(\"Post:"
885 + url_str + "," + data_str + "," + content_type_str + ","
886 + encode_str + "," + header_str
887 + "\")";
888 return true;
891 FPDF_BOOL PDFiumEngine::Form_PutRequestURL(FPDF_FORMFILLINFO* param,
892 FPDF_WIDESTRING url,
893 FPDF_WIDESTRING data,
894 FPDF_WIDESTRING encode) {
895 std::string url_str =
896 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(url));
897 std::string data_str =
898 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(data));
899 std::string encode_str =
900 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(encode));
902 std::string javascript = "alert(\"Put:"
903 + url_str + "," + data_str + "," + encode_str
904 + "\")";
906 return true;
909 void PDFiumEngine::Form_UploadTo(FPDF_FORMFILLINFO* param,
910 FPDF_FILEHANDLER* file_handle,
911 int file_flag,
912 FPDF_WIDESTRING to) {
913 std::string to_str =
914 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(to));
915 // TODO: needs the full implementation of form uploading
918 FPDF_LPFILEHANDLER PDFiumEngine::Form_DownloadFromURL(FPDF_FORMFILLINFO* param,
919 FPDF_WIDESTRING url) {
920 std::string url_str =
921 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(url));
923 // Now should get data from url.
924 // For testing purpose, use data read from file
925 // TODO: needs the full implementation here
926 FILE* file = fopen(XFA_TESTFILE("downloadtest.tem"), "w");
928 FPDF_FILE* file_wrapper = new FPDF_FILE;
929 file_wrapper->file = file;
930 file_wrapper->file_handler.clientData = file_wrapper;
931 file_wrapper->file_handler.Flush = Sample_Flush;
932 file_wrapper->file_handler.GetSize = Sample_GetSize;
933 file_wrapper->file_handler.ReadBlock = Sample_ReadBlock;
934 file_wrapper->file_handler.Release = Sample_Release;
935 file_wrapper->file_handler.Truncate = Sample_Truncate;
936 file_wrapper->file_handler.WriteBlock = Sample_WriteBlock;
938 return &file_wrapper->file_handler;
941 FPDF_FILEHANDLER* PDFiumEngine::Form_OpenFile(FPDF_FORMFILLINFO* param,
942 int file_flag,
943 FPDF_WIDESTRING url,
944 const char* mode) {
945 std::string url_str = "NULL";
946 if (url != NULL) {
947 url_str =
948 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(url));
950 // TODO: need to implement open file from the url
951 // Use a file path for the ease of testing
952 FILE* file = fopen(XFA_TESTFILE("tem.txt"), mode);
953 FPDF_FILE* file_wrapper = new FPDF_FILE;
954 file_wrapper->file = file;
955 file_wrapper->file_handler.clientData = file_wrapper;
956 file_wrapper->file_handler.Flush = Sample_Flush;
957 file_wrapper->file_handler.GetSize = Sample_GetSize;
958 file_wrapper->file_handler.ReadBlock = Sample_ReadBlock;
959 file_wrapper->file_handler.Release = Sample_Release;
960 file_wrapper->file_handler.Truncate = Sample_Truncate;
961 file_wrapper->file_handler.WriteBlock = Sample_WriteBlock;
962 return &file_wrapper->file_handler;
965 void PDFiumEngine::Form_GotoURL(FPDF_FORMFILLINFO* param,
966 FPDF_DOCUMENT document,
967 FPDF_WIDESTRING url) {
968 std::string url_str =
969 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(url));
970 // TODO: needs to implement GOTO URL action
973 int PDFiumEngine::Form_GetLanguage(FPDF_FORMFILLINFO* param,
974 void* language,
975 int length) {
976 return 0;
979 #endif // PDF_USE_XFA
981 int PDFiumEngine::GetBlock(void* param, unsigned long position,
982 unsigned char* buffer, unsigned long size) {
983 DocumentLoader* loader = static_cast<DocumentLoader*>(param);
984 return loader->GetBlock(position, size, buffer);
987 bool PDFiumEngine::IsDataAvail(FX_FILEAVAIL* param,
988 size_t offset, size_t size) {
989 PDFiumEngine::FileAvail* file_avail =
990 static_cast<PDFiumEngine::FileAvail*>(param);
991 return file_avail->loader->IsDataAvailable(offset, size);
994 void PDFiumEngine::AddSegment(FX_DOWNLOADHINTS* param,
995 size_t offset, size_t size) {
996 PDFiumEngine::DownloadHints* download_hints =
997 static_cast<PDFiumEngine::DownloadHints*>(param);
998 return download_hints->loader->RequestData(offset, size);
1001 bool PDFiumEngine::New(const char* url) {
1002 url_ = url;
1003 headers_ = std::string();
1004 return true;
1007 bool PDFiumEngine::New(const char* url,
1008 const char* headers) {
1009 url_ = url;
1010 if (!headers)
1011 headers_ = std::string();
1012 else
1013 headers_ = headers;
1014 return true;
1017 void PDFiumEngine::PageOffsetUpdated(const pp::Point& page_offset) {
1018 page_offset_ = page_offset;
1021 void PDFiumEngine::PluginSizeUpdated(const pp::Size& size) {
1022 CancelPaints();
1024 plugin_size_ = size;
1025 CalculateVisiblePages();
1028 void PDFiumEngine::ScrolledToXPosition(int position) {
1029 CancelPaints();
1031 int old_x = position_.x();
1032 position_.set_x(position);
1033 CalculateVisiblePages();
1034 client_->Scroll(pp::Point(old_x - position, 0));
1037 void PDFiumEngine::ScrolledToYPosition(int position) {
1038 CancelPaints();
1040 int old_y = position_.y();
1041 position_.set_y(position);
1042 CalculateVisiblePages();
1043 client_->Scroll(pp::Point(0, old_y - position));
1046 void PDFiumEngine::PrePaint() {
1047 for (size_t i = 0; i < progressive_paints_.size(); ++i)
1048 progressive_paints_[i].painted_ = false;
1051 void PDFiumEngine::Paint(const pp::Rect& rect,
1052 pp::ImageData* image_data,
1053 std::vector<pp::Rect>* ready,
1054 std::vector<pp::Rect>* pending) {
1055 pp::Rect leftover = rect;
1056 for (size_t i = 0; i < visible_pages_.size(); ++i) {
1057 int index = visible_pages_[i];
1058 pp::Rect page_rect = pages_[index]->rect();
1059 // Convert the current page's rectangle to screen rectangle. We do this
1060 // instead of the reverse (converting the dirty rectangle from screen to
1061 // page coordinates) because then we'd have to convert back to screen
1062 // coordinates, and the rounding errors sometime leave pixels dirty or even
1063 // move the text up or down a pixel when zoomed.
1064 pp::Rect page_rect_in_screen = GetPageScreenRect(index);
1065 pp::Rect dirty_in_screen = page_rect_in_screen.Intersect(leftover);
1066 if (dirty_in_screen.IsEmpty())
1067 continue;
1069 leftover = leftover.Subtract(dirty_in_screen);
1071 if (pages_[index]->available()) {
1072 int progressive = GetProgressiveIndex(index);
1073 if (progressive != -1 &&
1074 progressive_paints_[progressive].rect != dirty_in_screen) {
1075 // The PDFium code can only handle one progressive paint at a time, so
1076 // queue this up. Previously we used to merge the rects when this
1077 // happened, but it made scrolling up on complex PDFs very slow since
1078 // there would be a damaged rect at the top (from scroll) and at the
1079 // bottom (from toolbar).
1080 pending->push_back(dirty_in_screen);
1081 continue;
1084 if (progressive == -1) {
1085 progressive = StartPaint(index, dirty_in_screen);
1086 progressive_paint_timeout_ = kMaxInitialProgressivePaintTimeMs;
1087 } else {
1088 progressive_paint_timeout_ = kMaxProgressivePaintTimeMs;
1091 progressive_paints_[progressive].painted_ = true;
1092 if (ContinuePaint(progressive, image_data)) {
1093 FinishPaint(progressive, image_data);
1094 ready->push_back(dirty_in_screen);
1095 } else {
1096 pending->push_back(dirty_in_screen);
1098 } else {
1099 PaintUnavailablePage(index, dirty_in_screen, image_data);
1100 ready->push_back(dirty_in_screen);
1105 void PDFiumEngine::PostPaint() {
1106 for (size_t i = 0; i < progressive_paints_.size(); ++i) {
1107 if (progressive_paints_[i].painted_)
1108 continue;
1110 // This rectangle must have been merged with another one, that's why we
1111 // weren't asked to paint it. Remove it or otherwise we'll never finish
1112 // painting.
1113 FPDF_RenderPage_Close(
1114 pages_[progressive_paints_[i].page_index]->GetPage());
1115 FPDFBitmap_Destroy(progressive_paints_[i].bitmap);
1116 progressive_paints_.erase(progressive_paints_.begin() + i);
1117 --i;
1121 bool PDFiumEngine::HandleDocumentLoad(const pp::URLLoader& loader) {
1122 password_tries_remaining_ = kMaxPasswordTries;
1123 return doc_loader_.Init(loader, url_, headers_);
1126 pp::Instance* PDFiumEngine::GetPluginInstance() {
1127 return client_->GetPluginInstance();
1130 pp::URLLoader PDFiumEngine::CreateURLLoader() {
1131 return client_->CreateURLLoader();
1134 void PDFiumEngine::AppendPage(PDFEngine* engine, int index) {
1135 // Unload and delete the blank page before appending.
1136 pages_[index]->Unload();
1137 pages_[index]->set_calculated_links(false);
1138 pp::Size curr_page_size = GetPageSize(index);
1139 FPDFPage_Delete(doc_, index);
1140 FPDF_ImportPages(doc_,
1141 static_cast<PDFiumEngine*>(engine)->doc(),
1142 "1",
1143 index);
1144 pp::Size new_page_size = GetPageSize(index);
1145 if (curr_page_size != new_page_size)
1146 LoadPageInfo(true);
1147 client_->Invalidate(GetPageScreenRect(index));
1150 pp::Point PDFiumEngine::GetScrollPosition() {
1151 return position_;
1154 void PDFiumEngine::SetScrollPosition(const pp::Point& position) {
1155 position_ = position;
1158 bool PDFiumEngine::IsProgressiveLoad() {
1159 return doc_loader_.is_partial_document();
1162 void PDFiumEngine::OnPartialDocumentLoaded() {
1163 file_access_.m_FileLen = doc_loader_.document_size();
1164 fpdf_availability_ = FPDFAvail_Create(&file_availability_, &file_access_);
1165 DCHECK(fpdf_availability_);
1167 // Currently engine does not deal efficiently with some non-linearized files.
1168 // See http://code.google.com/p/chromium/issues/detail?id=59400
1169 // To improve user experience we download entire file for non-linearized PDF.
1170 if (!FPDFAvail_IsLinearized(fpdf_availability_)) {
1171 doc_loader_.RequestData(0, doc_loader_.document_size());
1172 return;
1175 LoadDocument();
1178 void PDFiumEngine::OnPendingRequestComplete() {
1179 if (!doc_ || !form_) {
1180 LoadDocument();
1181 return;
1184 // LoadDocument() will result in |pending_pages_| being reset so there's no
1185 // need to run the code below in that case.
1186 bool update_pages = false;
1187 std::vector<int> still_pending;
1188 for (size_t i = 0; i < pending_pages_.size(); ++i) {
1189 if (CheckPageAvailable(pending_pages_[i], &still_pending)) {
1190 update_pages = true;
1191 if (IsPageVisible(pending_pages_[i]))
1192 client_->Invalidate(GetPageScreenRect(pending_pages_[i]));
1195 pending_pages_.swap(still_pending);
1196 if (update_pages)
1197 LoadPageInfo(true);
1200 void PDFiumEngine::OnNewDataAvailable() {
1201 client_->DocumentLoadProgress(doc_loader_.GetAvailableData(),
1202 doc_loader_.document_size());
1205 void PDFiumEngine::OnDocumentComplete() {
1206 if (!doc_ || !form_) {
1207 file_access_.m_FileLen = doc_loader_.document_size();
1208 LoadDocument();
1209 return;
1212 bool need_update = false;
1213 for (size_t i = 0; i < pages_.size(); ++i) {
1214 if (pages_[i]->available())
1215 continue;
1217 pages_[i]->set_available(true);
1218 // We still need to call IsPageAvail() even if the whole document is
1219 // already downloaded.
1220 FPDFAvail_IsPageAvail(fpdf_availability_, i, &download_hints_);
1221 need_update = true;
1222 if (IsPageVisible(i))
1223 client_->Invalidate(GetPageScreenRect(i));
1225 if (need_update)
1226 LoadPageInfo(true);
1228 FinishLoadingDocument();
1231 void PDFiumEngine::FinishLoadingDocument() {
1232 DCHECK(doc_loader_.IsDocumentComplete() && doc_);
1233 if (called_do_document_action_)
1234 return;
1235 called_do_document_action_ = true;
1237 // These can only be called now, as the JS might end up needing a page.
1238 FORM_DoDocumentJSAction(form_);
1239 FORM_DoDocumentOpenAction(form_);
1240 if (most_visible_page_ != -1) {
1241 FPDF_PAGE new_page = pages_[most_visible_page_]->GetPage();
1242 FORM_DoPageAAction(new_page, form_, FPDFPAGE_AACTION_OPEN);
1245 if (doc_) // This can only happen if loading |doc_| fails.
1246 client_->DocumentLoadComplete(pages_.size());
1249 void PDFiumEngine::UnsupportedFeature(int type) {
1250 std::string feature;
1251 switch (type) {
1252 #ifndef PDF_USE_XFA
1253 case FPDF_UNSP_DOC_XFAFORM:
1254 feature = "XFA";
1255 break;
1256 #endif
1257 case FPDF_UNSP_DOC_PORTABLECOLLECTION:
1258 feature = "Portfolios_Packages";
1259 break;
1260 case FPDF_UNSP_DOC_ATTACHMENT:
1261 case FPDF_UNSP_ANNOT_ATTACHMENT:
1262 feature = "Attachment";
1263 break;
1264 case FPDF_UNSP_DOC_SECURITY:
1265 feature = "Rights_Management";
1266 break;
1267 case FPDF_UNSP_DOC_SHAREDREVIEW:
1268 feature = "Shared_Review";
1269 break;
1270 case FPDF_UNSP_DOC_SHAREDFORM_ACROBAT:
1271 case FPDF_UNSP_DOC_SHAREDFORM_FILESYSTEM:
1272 case FPDF_UNSP_DOC_SHAREDFORM_EMAIL:
1273 feature = "Shared_Form";
1274 break;
1275 case FPDF_UNSP_ANNOT_3DANNOT:
1276 feature = "3D";
1277 break;
1278 case FPDF_UNSP_ANNOT_MOVIE:
1279 feature = "Movie";
1280 break;
1281 case FPDF_UNSP_ANNOT_SOUND:
1282 feature = "Sound";
1283 break;
1284 case FPDF_UNSP_ANNOT_SCREEN_MEDIA:
1285 case FPDF_UNSP_ANNOT_SCREEN_RICHMEDIA:
1286 feature = "Screen";
1287 break;
1288 case FPDF_UNSP_ANNOT_SIG:
1289 feature = "Digital_Signature";
1290 break;
1292 client_->DocumentHasUnsupportedFeature(feature);
1295 void PDFiumEngine::ContinueFind(int32_t result) {
1296 StartFind(current_find_text_.c_str(), !!result);
1299 bool PDFiumEngine::HandleEvent(const pp::InputEvent& event) {
1300 DCHECK(!defer_page_unload_);
1301 defer_page_unload_ = true;
1302 bool rv = false;
1303 switch (event.GetType()) {
1304 case PP_INPUTEVENT_TYPE_MOUSEDOWN:
1305 rv = OnMouseDown(pp::MouseInputEvent(event));
1306 break;
1307 case PP_INPUTEVENT_TYPE_MOUSEUP:
1308 rv = OnMouseUp(pp::MouseInputEvent(event));
1309 break;
1310 case PP_INPUTEVENT_TYPE_MOUSEMOVE:
1311 rv = OnMouseMove(pp::MouseInputEvent(event));
1312 break;
1313 case PP_INPUTEVENT_TYPE_KEYDOWN:
1314 rv = OnKeyDown(pp::KeyboardInputEvent(event));
1315 break;
1316 case PP_INPUTEVENT_TYPE_KEYUP:
1317 rv = OnKeyUp(pp::KeyboardInputEvent(event));
1318 break;
1319 case PP_INPUTEVENT_TYPE_CHAR:
1320 rv = OnChar(pp::KeyboardInputEvent(event));
1321 break;
1322 default:
1323 break;
1326 DCHECK(defer_page_unload_);
1327 defer_page_unload_ = false;
1328 for (size_t i = 0; i < deferred_page_unloads_.size(); ++i)
1329 pages_[deferred_page_unloads_[i]]->Unload();
1330 deferred_page_unloads_.clear();
1331 return rv;
1334 uint32_t PDFiumEngine::QuerySupportedPrintOutputFormats() {
1335 if (!HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY))
1336 return 0;
1337 return PP_PRINTOUTPUTFORMAT_PDF;
1340 void PDFiumEngine::PrintBegin() {
1341 FORM_DoDocumentAAction(form_, FPDFDOC_AACTION_WP);
1344 pp::Resource PDFiumEngine::PrintPages(
1345 const PP_PrintPageNumberRange_Dev* page_ranges, uint32_t page_range_count,
1346 const PP_PrintSettings_Dev& print_settings) {
1347 if (HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY))
1348 return PrintPagesAsPDF(page_ranges, page_range_count, print_settings);
1349 else if (HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY))
1350 return PrintPagesAsRasterPDF(page_ranges, page_range_count, print_settings);
1351 return pp::Resource();
1354 FPDF_DOCUMENT PDFiumEngine::CreateSinglePageRasterPdf(
1355 double source_page_width,
1356 double source_page_height,
1357 const PP_PrintSettings_Dev& print_settings,
1358 PDFiumPage* page_to_print) {
1359 FPDF_DOCUMENT temp_doc = FPDF_CreateNewDocument();
1360 if (!temp_doc)
1361 return temp_doc;
1363 const pp::Size& bitmap_size(page_to_print->rect().size());
1365 FPDF_PAGE temp_page =
1366 FPDFPage_New(temp_doc, 0, source_page_width, source_page_height);
1368 pp::ImageData image = pp::ImageData(client_->GetPluginInstance(),
1369 PP_IMAGEDATAFORMAT_BGRA_PREMUL,
1370 bitmap_size,
1371 false);
1373 FPDF_BITMAP bitmap = FPDFBitmap_CreateEx(bitmap_size.width(),
1374 bitmap_size.height(),
1375 FPDFBitmap_BGRx,
1376 image.data(),
1377 image.stride());
1379 // Clear the bitmap
1380 FPDFBitmap_FillRect(
1381 bitmap, 0, 0, bitmap_size.width(), bitmap_size.height(), 0xFFFFFFFF);
1383 pp::Rect page_rect = page_to_print->rect();
1384 FPDF_RenderPageBitmap(bitmap,
1385 page_to_print->GetPrintPage(),
1386 page_rect.x(),
1387 page_rect.y(),
1388 page_rect.width(),
1389 page_rect.height(),
1390 print_settings.orientation,
1391 FPDF_ANNOT | FPDF_PRINTING | FPDF_NO_CATCH);
1393 double ratio_x = (static_cast<double>(bitmap_size.width()) * kPointsPerInch) /
1394 print_settings.dpi;
1395 double ratio_y =
1396 (static_cast<double>(bitmap_size.height()) * kPointsPerInch) /
1397 print_settings.dpi;
1399 // Add the bitmap to an image object and add the image object to the output
1400 // page.
1401 FPDF_PAGEOBJECT temp_img = FPDFPageObj_NewImgeObj(temp_doc);
1402 FPDFImageObj_SetBitmap(&temp_page, 1, temp_img, bitmap);
1403 FPDFImageObj_SetMatrix(temp_img, ratio_x, 0, 0, ratio_y, 0, 0);
1404 FPDFPage_InsertObject(temp_page, temp_img);
1405 FPDFPage_GenerateContent(temp_page);
1406 FPDF_ClosePage(temp_page);
1408 page_to_print->ClosePrintPage();
1409 FPDFBitmap_Destroy(bitmap);
1411 return temp_doc;
1414 pp::Buffer_Dev PDFiumEngine::PrintPagesAsRasterPDF(
1415 const PP_PrintPageNumberRange_Dev* page_ranges, uint32_t page_range_count,
1416 const PP_PrintSettings_Dev& print_settings) {
1417 if (!page_range_count)
1418 return pp::Buffer_Dev();
1420 // If document is not downloaded yet, disable printing.
1421 if (doc_ && !doc_loader_.IsDocumentComplete())
1422 return pp::Buffer_Dev();
1424 FPDF_DOCUMENT output_doc = FPDF_CreateNewDocument();
1425 if (!output_doc)
1426 return pp::Buffer_Dev();
1428 SaveSelectedFormForPrint();
1430 std::vector<PDFiumPage> pages_to_print;
1431 // width and height of source PDF pages.
1432 std::vector<std::pair<double, double> > source_page_sizes;
1433 // Collect pages to print and sizes of source pages.
1434 std::vector<uint32_t> page_numbers =
1435 GetPageNumbersFromPrintPageNumberRange(page_ranges, page_range_count);
1436 for (size_t i = 0; i < page_numbers.size(); ++i) {
1437 uint32_t page_number = page_numbers[i];
1438 FPDF_PAGE pdf_page = FPDF_LoadPage(doc_, page_number);
1439 double source_page_width = FPDF_GetPageWidth(pdf_page);
1440 double source_page_height = FPDF_GetPageHeight(pdf_page);
1441 source_page_sizes.push_back(std::make_pair(source_page_width,
1442 source_page_height));
1444 int width_in_pixels = ConvertUnit(source_page_width,
1445 static_cast<int>(kPointsPerInch),
1446 print_settings.dpi);
1447 int height_in_pixels = ConvertUnit(source_page_height,
1448 static_cast<int>(kPointsPerInch),
1449 print_settings.dpi);
1451 pp::Rect rect(width_in_pixels, height_in_pixels);
1452 pages_to_print.push_back(PDFiumPage(this, page_number, rect, true));
1453 FPDF_ClosePage(pdf_page);
1456 #if defined(OS_LINUX)
1457 g_last_instance_id = client_->GetPluginInstance()->pp_instance();
1458 #endif
1460 size_t i = 0;
1461 for (; i < pages_to_print.size(); ++i) {
1462 double source_page_width = source_page_sizes[i].first;
1463 double source_page_height = source_page_sizes[i].second;
1465 // Use temp_doc to compress image by saving PDF to buffer.
1466 FPDF_DOCUMENT temp_doc = CreateSinglePageRasterPdf(source_page_width,
1467 source_page_height,
1468 print_settings,
1469 &pages_to_print[i]);
1471 if (!temp_doc)
1472 break;
1474 pp::Buffer_Dev buffer = GetFlattenedPrintData(temp_doc);
1475 FPDF_CloseDocument(temp_doc);
1477 PDFiumMemBufferFileRead file_read(buffer.data(), buffer.size());
1478 temp_doc = FPDF_LoadCustomDocument(&file_read, NULL);
1480 FPDF_BOOL imported = FPDF_ImportPages(output_doc, temp_doc, "1", i);
1481 FPDF_CloseDocument(temp_doc);
1482 if (!imported)
1483 break;
1486 pp::Buffer_Dev buffer;
1487 if (i == pages_to_print.size()) {
1488 FPDF_CopyViewerPreferences(output_doc, doc_);
1489 FitContentsToPrintableAreaIfRequired(output_doc, print_settings);
1490 // Now flatten all the output pages.
1491 buffer = GetFlattenedPrintData(output_doc);
1493 FPDF_CloseDocument(output_doc);
1494 return buffer;
1497 pp::Buffer_Dev PDFiumEngine::GetFlattenedPrintData(const FPDF_DOCUMENT& doc) {
1498 int page_count = FPDF_GetPageCount(doc);
1499 bool flatten_succeeded = true;
1500 for (int i = 0; i < page_count; ++i) {
1501 FPDF_PAGE page = FPDF_LoadPage(doc, i);
1502 DCHECK(page);
1503 if (page) {
1504 int flatten_ret = FPDFPage_Flatten(page, FLAT_PRINT);
1505 FPDF_ClosePage(page);
1506 if (flatten_ret == FLATTEN_FAIL) {
1507 flatten_succeeded = false;
1508 break;
1510 } else {
1511 flatten_succeeded = false;
1512 break;
1515 if (!flatten_succeeded) {
1516 FPDF_CloseDocument(doc);
1517 return pp::Buffer_Dev();
1520 pp::Buffer_Dev buffer;
1521 PDFiumMemBufferFileWrite output_file_write;
1522 if (FPDF_SaveAsCopy(doc, &output_file_write, 0)) {
1523 buffer = pp::Buffer_Dev(
1524 client_->GetPluginInstance(), output_file_write.size());
1525 if (!buffer.is_null()) {
1526 memcpy(buffer.data(), output_file_write.buffer().c_str(),
1527 output_file_write.size());
1530 return buffer;
1533 pp::Buffer_Dev PDFiumEngine::PrintPagesAsPDF(
1534 const PP_PrintPageNumberRange_Dev* page_ranges, uint32_t page_range_count,
1535 const PP_PrintSettings_Dev& print_settings) {
1536 if (!page_range_count)
1537 return pp::Buffer_Dev();
1539 DCHECK(doc_);
1540 FPDF_DOCUMENT output_doc = FPDF_CreateNewDocument();
1541 if (!output_doc)
1542 return pp::Buffer_Dev();
1544 SaveSelectedFormForPrint();
1546 std::string page_number_str;
1547 for (uint32_t index = 0; index < page_range_count; ++index) {
1548 if (!page_number_str.empty())
1549 page_number_str.append(",");
1550 page_number_str.append(
1551 base::IntToString(page_ranges[index].first_page_number + 1));
1552 if (page_ranges[index].first_page_number !=
1553 page_ranges[index].last_page_number) {
1554 page_number_str.append("-");
1555 page_number_str.append(
1556 base::IntToString(page_ranges[index].last_page_number + 1));
1560 std::vector<uint32_t> page_numbers =
1561 GetPageNumbersFromPrintPageNumberRange(page_ranges, page_range_count);
1562 for (size_t i = 0; i < page_numbers.size(); ++i) {
1563 uint32_t page_number = page_numbers[i];
1564 pages_[page_number]->GetPage();
1565 if (!IsPageVisible(page_numbers[i]))
1566 pages_[page_number]->Unload();
1569 FPDF_CopyViewerPreferences(output_doc, doc_);
1570 if (!FPDF_ImportPages(output_doc, doc_, page_number_str.c_str(), 0)) {
1571 FPDF_CloseDocument(output_doc);
1572 return pp::Buffer_Dev();
1575 FitContentsToPrintableAreaIfRequired(output_doc, print_settings);
1577 // Now flatten all the output pages.
1578 pp::Buffer_Dev buffer = GetFlattenedPrintData(output_doc);
1579 FPDF_CloseDocument(output_doc);
1580 return buffer;
1583 void PDFiumEngine::FitContentsToPrintableAreaIfRequired(
1584 const FPDF_DOCUMENT& doc, const PP_PrintSettings_Dev& print_settings) {
1585 // Check to see if we need to fit pdf contents to printer paper size.
1586 if (print_settings.print_scaling_option !=
1587 PP_PRINTSCALINGOPTION_SOURCE_SIZE) {
1588 int num_pages = FPDF_GetPageCount(doc);
1589 // In-place transformation is more efficient than creating a new
1590 // transformed document from the source document. Therefore, transform
1591 // every page to fit the contents in the selected printer paper.
1592 for (int i = 0; i < num_pages; ++i) {
1593 FPDF_PAGE page = FPDF_LoadPage(doc, i);
1594 TransformPDFPageForPrinting(page, print_settings);
1595 FPDF_ClosePage(page);
1600 void PDFiumEngine::SaveSelectedFormForPrint() {
1601 FORM_ForceToKillFocus(form_);
1602 client_->FormTextFieldFocusChange(false);
1605 void PDFiumEngine::PrintEnd() {
1606 FORM_DoDocumentAAction(form_, FPDFDOC_AACTION_DP);
1609 PDFiumPage::Area PDFiumEngine::GetCharIndex(
1610 const pp::MouseInputEvent& event, int* page_index,
1611 int* char_index, PDFiumPage::LinkTarget* target) {
1612 // First figure out which page this is in.
1613 pp::Point mouse_point = event.GetPosition();
1614 pp::Point point(
1615 static_cast<int>((mouse_point.x() + position_.x()) / current_zoom_),
1616 static_cast<int>((mouse_point.y() + position_.y()) / current_zoom_));
1617 return GetCharIndex(point, page_index, char_index, target);
1620 PDFiumPage::Area PDFiumEngine::GetCharIndex(
1621 const pp::Point& point,
1622 int* page_index,
1623 int* char_index,
1624 PDFiumPage::LinkTarget* target) {
1625 int page = -1;
1626 for (size_t i = 0; i < visible_pages_.size(); ++i) {
1627 if (pages_[visible_pages_[i]]->rect().Contains(point)) {
1628 page = visible_pages_[i];
1629 break;
1632 if (page == -1)
1633 return PDFiumPage::NONSELECTABLE_AREA;
1635 // If the page hasn't finished rendering, calling into the page sometimes
1636 // leads to hangs.
1637 for (size_t i = 0; i < progressive_paints_.size(); ++i) {
1638 if (progressive_paints_[i].page_index == page)
1639 return PDFiumPage::NONSELECTABLE_AREA;
1642 *page_index = page;
1643 return pages_[page]->GetCharIndex(point, current_rotation_, char_index,
1644 target);
1647 bool PDFiumEngine::OnMouseDown(const pp::MouseInputEvent& event) {
1648 if (event.GetButton() != PP_INPUTEVENT_MOUSEBUTTON_LEFT &&
1649 event.GetButton() != PP_INPUTEVENT_MOUSEBUTTON_RIGHT) {
1650 return false;
1652 if (event.GetButton() == PP_INPUTEVENT_MOUSEBUTTON_RIGHT) {
1653 if (!selection_.size())
1654 return false;
1655 std::vector<pp::Rect> selection_rect_vector;
1656 GetAllScreenRectsUnion(&selection_, GetVisibleRect().point(),
1657 &selection_rect_vector);
1658 pp::Point point = event.GetPosition();
1659 for (size_t i = 0; i < selection_rect_vector.size(); ++i) {
1660 if (selection_rect_vector[i].Contains(point.x(), point.y()))
1661 return false;
1663 SelectionChangeInvalidator selection_invalidator(this);
1664 selection_.clear();
1665 return true;
1668 SelectionChangeInvalidator selection_invalidator(this);
1669 selection_.clear();
1671 int page_index = -1;
1672 int char_index = -1;
1673 PDFiumPage::LinkTarget target;
1674 PDFiumPage::Area area = GetCharIndex(event, &page_index,
1675 &char_index, &target);
1676 mouse_down_state_.Set(area, target);
1678 // Decide whether to open link or not based on user action in mouse up and
1679 // mouse move events.
1680 if (area == PDFiumPage::WEBLINK_AREA)
1681 return true;
1683 if (area == PDFiumPage::DOCLINK_AREA) {
1684 client_->ScrollToPage(target.page);
1685 client_->FormTextFieldFocusChange(false);
1686 return true;
1689 if (page_index != -1) {
1690 last_page_mouse_down_ = page_index;
1691 double page_x, page_y;
1692 pp::Point point = event.GetPosition();
1693 DeviceToPage(page_index, point.x(), point.y(), &page_x, &page_y);
1695 FORM_OnLButtonDown(form_, pages_[page_index]->GetPage(), 0, page_x, page_y);
1696 int control = FPDPage_HasFormFieldAtPoint(
1697 form_, pages_[page_index]->GetPage(), page_x, page_y);
1698 if (control > FPDF_FORMFIELD_UNKNOWN) { // returns -1 sometimes...
1699 #ifdef PDF_USE_XFA
1700 client_->FormTextFieldFocusChange(control == FPDF_FORMFIELD_TEXTFIELD ||
1701 control == FPDF_FORMFIELD_COMBOBOX || control == FPDF_FORMFIELD_XFA);
1702 #else
1703 client_->FormTextFieldFocusChange(control == FPDF_FORMFIELD_TEXTFIELD ||
1704 control == FPDF_FORMFIELD_COMBOBOX);
1705 #endif
1706 return true; // Return now before we get into the selection code.
1710 client_->FormTextFieldFocusChange(false);
1712 if (area != PDFiumPage::TEXT_AREA)
1713 return true; // Return true so WebKit doesn't do its own highlighting.
1715 if (event.GetClickCount() == 1) {
1716 OnSingleClick(page_index, char_index);
1717 } else if (event.GetClickCount() == 2 ||
1718 event.GetClickCount() == 3) {
1719 OnMultipleClick(event.GetClickCount(), page_index, char_index);
1722 return true;
1725 void PDFiumEngine::OnSingleClick(int page_index, int char_index) {
1726 selecting_ = true;
1727 selection_.push_back(PDFiumRange(pages_[page_index], char_index, 0));
1730 void PDFiumEngine::OnMultipleClick(int click_count,
1731 int page_index,
1732 int char_index) {
1733 // It would be more efficient if the SDK could support finding a space, but
1734 // now it doesn't.
1735 int start_index = char_index;
1736 do {
1737 base::char16 cur = pages_[page_index]->GetCharAtIndex(start_index);
1738 // For double click, we want to select one word so we look for whitespace
1739 // boundaries. For triple click, we want the whole line.
1740 if (cur == '\n' || (click_count == 2 && (cur == ' ' || cur == '\t')))
1741 break;
1742 } while (--start_index >= 0);
1743 if (start_index)
1744 start_index++;
1746 int end_index = char_index;
1747 int total = pages_[page_index]->GetCharCount();
1748 while (end_index++ <= total) {
1749 base::char16 cur = pages_[page_index]->GetCharAtIndex(end_index);
1750 if (cur == '\n' || (click_count == 2 && (cur == ' ' || cur == '\t')))
1751 break;
1754 selection_.push_back(PDFiumRange(
1755 pages_[page_index], start_index, end_index - start_index));
1758 bool PDFiumEngine::OnMouseUp(const pp::MouseInputEvent& event) {
1759 if (event.GetButton() != PP_INPUTEVENT_MOUSEBUTTON_LEFT)
1760 return false;
1762 int page_index = -1;
1763 int char_index = -1;
1764 PDFiumPage::LinkTarget target;
1765 PDFiumPage::Area area =
1766 GetCharIndex(event, &page_index, &char_index, &target);
1768 // Open link on mouse up for same link for which mouse down happened earlier.
1769 if (mouse_down_state_.Matches(area, target)) {
1770 if (area == PDFiumPage::WEBLINK_AREA) {
1771 bool open_in_new_tab = !!(event.GetModifiers() & kDefaultKeyModifier);
1772 client_->NavigateTo(target.url, open_in_new_tab);
1773 client_->FormTextFieldFocusChange(false);
1774 return true;
1778 if (page_index != -1) {
1779 double page_x, page_y;
1780 pp::Point point = event.GetPosition();
1781 DeviceToPage(page_index, point.x(), point.y(), &page_x, &page_y);
1782 FORM_OnLButtonUp(
1783 form_, pages_[page_index]->GetPage(), 0, page_x, page_y);
1786 if (!selecting_)
1787 return false;
1789 selecting_ = false;
1790 return true;
1793 bool PDFiumEngine::OnMouseMove(const pp::MouseInputEvent& event) {
1794 int page_index = -1;
1795 int char_index = -1;
1796 PDFiumPage::LinkTarget target;
1797 PDFiumPage::Area area =
1798 GetCharIndex(event, &page_index, &char_index, &target);
1800 // Clear |mouse_down_state_| if mouse moves away from where the mouse down
1801 // happened.
1802 if (!mouse_down_state_.Matches(area, target))
1803 mouse_down_state_.Reset();
1805 if (!selecting_) {
1806 PP_CursorType_Dev cursor;
1807 switch (area) {
1808 case PDFiumPage::TEXT_AREA:
1809 cursor = PP_CURSORTYPE_IBEAM;
1810 break;
1811 case PDFiumPage::WEBLINK_AREA:
1812 case PDFiumPage::DOCLINK_AREA:
1813 cursor = PP_CURSORTYPE_HAND;
1814 break;
1815 case PDFiumPage::NONSELECTABLE_AREA:
1816 default:
1817 cursor = PP_CURSORTYPE_POINTER;
1818 break;
1821 if (page_index != -1) {
1822 double page_x, page_y;
1823 pp::Point point = event.GetPosition();
1824 DeviceToPage(page_index, point.x(), point.y(), &page_x, &page_y);
1826 FORM_OnMouseMove(form_, pages_[page_index]->GetPage(), 0, page_x, page_y);
1827 int control = FPDPage_HasFormFieldAtPoint(
1828 form_, pages_[page_index]->GetPage(), page_x, page_y);
1829 switch (control) {
1830 case FPDF_FORMFIELD_PUSHBUTTON:
1831 case FPDF_FORMFIELD_CHECKBOX:
1832 case FPDF_FORMFIELD_RADIOBUTTON:
1833 case FPDF_FORMFIELD_COMBOBOX:
1834 case FPDF_FORMFIELD_LISTBOX:
1835 cursor = PP_CURSORTYPE_HAND;
1836 break;
1837 case FPDF_FORMFIELD_TEXTFIELD:
1838 cursor = PP_CURSORTYPE_IBEAM;
1839 break;
1840 default:
1841 break;
1845 client_->UpdateCursor(cursor);
1846 pp::Point point = event.GetPosition();
1847 std::string url = GetLinkAtPosition(event.GetPosition());
1848 if (url != link_under_cursor_) {
1849 link_under_cursor_ = url;
1850 pp::PDF::SetLinkUnderCursor(GetPluginInstance(), url.c_str());
1852 // No need to swallow the event, since this might interfere with the
1853 // scrollbars if the user is dragging them.
1854 return false;
1857 // We're selecting but right now we're not over text, so don't change the
1858 // current selection.
1859 if (area != PDFiumPage::TEXT_AREA && area != PDFiumPage::WEBLINK_AREA &&
1860 area != PDFiumPage::DOCLINK_AREA) {
1861 return false;
1864 SelectionChangeInvalidator selection_invalidator(this);
1866 // Check if the user has descreased their selection area and we need to remove
1867 // pages from selection_.
1868 for (size_t i = 0; i < selection_.size(); ++i) {
1869 if (selection_[i].page_index() == page_index) {
1870 // There should be no other pages after this.
1871 selection_.erase(selection_.begin() + i + 1, selection_.end());
1872 break;
1876 if (selection_.size() == 0)
1877 return false;
1879 int last = selection_.size() - 1;
1880 if (selection_[last].page_index() == page_index) {
1881 // Selecting within a page.
1882 int count;
1883 if (char_index >= selection_[last].char_index()) {
1884 // Selecting forward.
1885 count = char_index - selection_[last].char_index() + 1;
1886 } else {
1887 count = char_index - selection_[last].char_index() - 1;
1889 selection_[last].SetCharCount(count);
1890 } else if (selection_[last].page_index() < page_index) {
1891 // Selecting into the next page.
1893 // First make sure that there are no gaps in selection, i.e. if mousedown on
1894 // page one but we only get mousemove over page three, we want page two.
1895 for (int i = selection_[last].page_index() + 1; i < page_index; ++i) {
1896 selection_.push_back(PDFiumRange(pages_[i], 0,
1897 pages_[i]->GetCharCount()));
1900 int count = pages_[selection_[last].page_index()]->GetCharCount();
1901 selection_[last].SetCharCount(count - selection_[last].char_index());
1902 selection_.push_back(PDFiumRange(pages_[page_index], 0, char_index));
1903 } else {
1904 // Selecting into the previous page.
1905 // The selection's char_index is 0-based, so the character count is one
1906 // more than the index. The character count needs to be negative to
1907 // indicate a backwards selection.
1908 selection_[last].SetCharCount(-(selection_[last].char_index() + 1));
1910 // First make sure that there are no gaps in selection, i.e. if mousedown on
1911 // page three but we only get mousemove over page one, we want page two.
1912 for (int i = selection_[last].page_index() - 1; i > page_index; --i) {
1913 selection_.push_back(PDFiumRange(pages_[i], 0,
1914 pages_[i]->GetCharCount()));
1917 int count = pages_[page_index]->GetCharCount();
1918 selection_.push_back(
1919 PDFiumRange(pages_[page_index], count, count - char_index));
1922 return true;
1925 bool PDFiumEngine::OnKeyDown(const pp::KeyboardInputEvent& event) {
1926 if (last_page_mouse_down_ == -1)
1927 return false;
1929 bool rv = !!FORM_OnKeyDown(
1930 form_, pages_[last_page_mouse_down_]->GetPage(),
1931 event.GetKeyCode(), event.GetModifiers());
1933 if (event.GetKeyCode() == ui::VKEY_BACK ||
1934 event.GetKeyCode() == ui::VKEY_ESCAPE) {
1935 // Chrome doesn't send char events for backspace or escape keys, see
1936 // PlatformKeyboardEventBuilder::isCharacterKey() and
1937 // http://chrome-corpsvn.mtv.corp.google.com/viewvc?view=rev&root=chrome&revision=31805
1938 // for more information. So just fake one since PDFium uses it.
1939 std::string str;
1940 str.push_back(event.GetKeyCode());
1941 pp::KeyboardInputEvent synthesized(pp::KeyboardInputEvent(
1942 client_->GetPluginInstance(),
1943 PP_INPUTEVENT_TYPE_CHAR,
1944 event.GetTimeStamp(),
1945 event.GetModifiers(),
1946 event.GetKeyCode(),
1947 str));
1948 OnChar(synthesized);
1951 return rv;
1954 bool PDFiumEngine::OnKeyUp(const pp::KeyboardInputEvent& event) {
1955 if (last_page_mouse_down_ == -1)
1956 return false;
1958 return !!FORM_OnKeyUp(
1959 form_, pages_[last_page_mouse_down_]->GetPage(),
1960 event.GetKeyCode(), event.GetModifiers());
1963 bool PDFiumEngine::OnChar(const pp::KeyboardInputEvent& event) {
1964 if (last_page_mouse_down_ == -1)
1965 return false;
1967 base::string16 str = base::UTF8ToUTF16(event.GetCharacterText().AsString());
1968 return !!FORM_OnChar(
1969 form_, pages_[last_page_mouse_down_]->GetPage(),
1970 str[0],
1971 event.GetModifiers());
1974 void PDFiumEngine::StartFind(const char* text, bool case_sensitive) {
1975 // We can get a call to StartFind before we have any page information (i.e.
1976 // before the first call to LoadDocument has happened). Handle this case.
1977 if (pages_.empty())
1978 return;
1980 bool first_search = false;
1981 int character_to_start_searching_from = 0;
1982 if (current_find_text_ != text) { // First time we search for this text.
1983 first_search = true;
1984 std::vector<PDFiumRange> old_selection = selection_;
1985 StopFind();
1986 current_find_text_ = text;
1988 if (old_selection.empty()) {
1989 // Start searching from the beginning of the document.
1990 next_page_to_search_ = 0;
1991 last_page_to_search_ = pages_.size() - 1;
1992 last_character_index_to_search_ = -1;
1993 } else {
1994 // There's a current selection, so start from it.
1995 next_page_to_search_ = old_selection[0].page_index();
1996 last_character_index_to_search_ = old_selection[0].char_index();
1997 character_to_start_searching_from = old_selection[0].char_index();
1998 last_page_to_search_ = next_page_to_search_;
2002 int current_page = next_page_to_search_;
2004 if (pages_[current_page]->available()) {
2005 base::string16 str = base::UTF8ToUTF16(text);
2006 // Don't use PDFium to search for now, since it doesn't support unicode text.
2007 // Leave the code for now to avoid bit-rot, in case it's fixed later.
2008 if (0) {
2009 SearchUsingPDFium(
2010 str, case_sensitive, first_search, character_to_start_searching_from,
2011 current_page);
2012 } else {
2013 SearchUsingICU(
2014 str, case_sensitive, first_search, character_to_start_searching_from,
2015 current_page);
2018 if (!IsPageVisible(current_page))
2019 pages_[current_page]->Unload();
2022 if (next_page_to_search_ != last_page_to_search_ ||
2023 (first_search && last_character_index_to_search_ != -1)) {
2024 ++next_page_to_search_;
2027 if (next_page_to_search_ == static_cast<int>(pages_.size()))
2028 next_page_to_search_ = 0;
2029 // If there's only one page in the document and we start searching midway,
2030 // then we'll want to search the page one more time.
2031 bool end_of_search =
2032 next_page_to_search_ == last_page_to_search_ &&
2033 // Only one page but didn't start midway.
2034 ((pages_.size() == 1 && last_character_index_to_search_ == -1) ||
2035 // Started midway, but only 1 page and we already looped around.
2036 (pages_.size() == 1 && !first_search) ||
2037 // Started midway, and we've just looped around.
2038 (pages_.size() > 1 && current_page == next_page_to_search_));
2040 if (end_of_search) {
2041 // Send the final notification.
2042 client_->NotifyNumberOfFindResultsChanged(find_results_.size(), true);
2044 // When searching is complete, resume finding at a particular index.
2045 // Assuming the user has not clicked the find button in the meanwhile.
2046 if (resume_find_index_.valid() && !current_find_index_.valid()) {
2047 size_t resume_index = resume_find_index_.GetIndex();
2048 if (resume_index >= find_results_.size()) {
2049 // This might happen if the PDF has some dynamically generated text?
2050 resume_index = 0;
2052 current_find_index_.SetIndex(resume_index);
2053 client_->NotifySelectedFindResultChanged(resume_index);
2055 resume_find_index_.Invalidate();
2056 } else {
2057 pp::CompletionCallback callback =
2058 find_factory_.NewCallback(&PDFiumEngine::ContinueFind);
2059 pp::Module::Get()->core()->CallOnMainThread(
2060 0, callback, case_sensitive ? 1 : 0);
2064 void PDFiumEngine::SearchUsingPDFium(const base::string16& term,
2065 bool case_sensitive,
2066 bool first_search,
2067 int character_to_start_searching_from,
2068 int current_page) {
2069 // Find all the matches in the current page.
2070 unsigned long flags = case_sensitive ? FPDF_MATCHCASE : 0;
2071 FPDF_SCHHANDLE find = FPDFText_FindStart(
2072 pages_[current_page]->GetTextPage(),
2073 reinterpret_cast<const unsigned short*>(term.c_str()),
2074 flags, character_to_start_searching_from);
2076 // Note: since we search one page at a time, we don't find matches across
2077 // page boundaries. We could do this manually ourself, but it seems low
2078 // priority since Reader itself doesn't do it.
2079 while (FPDFText_FindNext(find)) {
2080 PDFiumRange result(pages_[current_page],
2081 FPDFText_GetSchResultIndex(find),
2082 FPDFText_GetSchCount(find));
2084 if (!first_search &&
2085 last_character_index_to_search_ != -1 &&
2086 result.page_index() == last_page_to_search_ &&
2087 result.char_index() >= last_character_index_to_search_) {
2088 break;
2091 AddFindResult(result);
2094 FPDFText_FindClose(find);
2097 void PDFiumEngine::SearchUsingICU(const base::string16& term,
2098 bool case_sensitive,
2099 bool first_search,
2100 int character_to_start_searching_from,
2101 int current_page) {
2102 base::string16 page_text;
2103 int text_length = pages_[current_page]->GetCharCount();
2104 if (character_to_start_searching_from) {
2105 text_length -= character_to_start_searching_from;
2106 } else if (!first_search &&
2107 last_character_index_to_search_ != -1 &&
2108 current_page == last_page_to_search_) {
2109 text_length = last_character_index_to_search_;
2111 if (text_length <= 0)
2112 return;
2114 PDFiumAPIStringBufferAdapter<base::string16> api_string_adapter(&page_text,
2115 text_length,
2116 false);
2117 unsigned short* data =
2118 reinterpret_cast<unsigned short*>(api_string_adapter.GetData());
2119 int written = FPDFText_GetText(pages_[current_page]->GetTextPage(),
2120 character_to_start_searching_from,
2121 text_length,
2122 data);
2123 api_string_adapter.Close(written);
2125 std::vector<PDFEngine::Client::SearchStringResult> results;
2126 client_->SearchString(
2127 page_text.c_str(), term.c_str(), case_sensitive, &results);
2128 for (size_t i = 0; i < results.size(); ++i) {
2129 // Need to map the indexes from the page text, which may have generated
2130 // characters like space etc, to character indices from the page.
2131 int temp_start = results[i].start_index + character_to_start_searching_from;
2132 int start = FPDFText_GetCharIndexFromTextIndex(
2133 pages_[current_page]->GetTextPage(), temp_start);
2134 int end = FPDFText_GetCharIndexFromTextIndex(
2135 pages_[current_page]->GetTextPage(),
2136 temp_start + results[i].length);
2137 AddFindResult(PDFiumRange(pages_[current_page], start, end - start));
2141 void PDFiumEngine::AddFindResult(const PDFiumRange& result) {
2142 // Figure out where to insert the new location, since we could have
2143 // started searching midway and now we wrapped.
2144 size_t result_index;
2145 int page_index = result.page_index();
2146 int char_index = result.char_index();
2147 for (result_index = 0; result_index < find_results_.size(); ++result_index) {
2148 if (find_results_[result_index].page_index() > page_index ||
2149 (find_results_[result_index].page_index() == page_index &&
2150 find_results_[result_index].char_index() > char_index)) {
2151 break;
2154 find_results_.insert(find_results_.begin() + result_index, result);
2155 UpdateTickMarks();
2157 if (current_find_index_.valid()) {
2158 if (result_index <= current_find_index_.GetIndex()) {
2159 // Update the current match index
2160 size_t find_index = current_find_index_.IncrementIndex();
2161 DCHECK_LT(find_index, find_results_.size());
2162 client_->NotifySelectedFindResultChanged(current_find_index_.GetIndex());
2164 } else if (!resume_find_index_.valid()) {
2165 // Both indices are invalid. Select the first match.
2166 SelectFindResult(true);
2168 client_->NotifyNumberOfFindResultsChanged(find_results_.size(), false);
2171 bool PDFiumEngine::SelectFindResult(bool forward) {
2172 if (find_results_.empty()) {
2173 NOTREACHED();
2174 return false;
2177 SelectionChangeInvalidator selection_invalidator(this);
2179 // Move back/forward through the search locations we previously found.
2180 size_t new_index;
2181 const size_t last_index = find_results_.size() - 1;
2182 if (current_find_index_.valid()) {
2183 size_t current_index = current_find_index_.GetIndex();
2184 if (forward) {
2185 new_index = (current_index >= last_index) ? 0 : current_index + 1;
2186 } else {
2187 new_index = (current_find_index_.GetIndex() == 0) ?
2188 last_index : current_index - 1;
2190 } else {
2191 new_index = forward ? 0 : last_index;
2193 current_find_index_.SetIndex(new_index);
2195 // Update the selection before telling the client to scroll, since it could
2196 // paint then.
2197 selection_.clear();
2198 selection_.push_back(find_results_[current_find_index_.GetIndex()]);
2200 // If the result is not in view, scroll to it.
2201 pp::Rect bounding_rect;
2202 pp::Rect visible_rect = GetVisibleRect();
2203 // Use zoom of 1.0 since visible_rect is without zoom.
2204 std::vector<pp::Rect> rects;
2205 rects = find_results_[current_find_index_.GetIndex()].GetScreenRects(
2206 pp::Point(), 1.0, current_rotation_);
2207 for (size_t i = 0; i < rects.size(); ++i)
2208 bounding_rect = bounding_rect.Union(rects[i]);
2209 if (!visible_rect.Contains(bounding_rect)) {
2210 pp::Point center = bounding_rect.CenterPoint();
2211 // Make the page centered.
2212 int new_y = static_cast<int>(center.y() * current_zoom_) -
2213 static_cast<int>(visible_rect.height() * current_zoom_ / 2);
2214 if (new_y < 0)
2215 new_y = 0;
2216 client_->ScrollToY(new_y);
2218 // Only move horizontally if it's not visible.
2219 if (center.x() < visible_rect.x() || center.x() > visible_rect.right()) {
2220 int new_x = static_cast<int>(center.x() * current_zoom_) -
2221 static_cast<int>(visible_rect.width() * current_zoom_ / 2);
2222 if (new_x < 0)
2223 new_x = 0;
2224 client_->ScrollToX(new_x);
2228 client_->NotifySelectedFindResultChanged(current_find_index_.GetIndex());
2229 return true;
2232 void PDFiumEngine::StopFind() {
2233 SelectionChangeInvalidator selection_invalidator(this);
2235 selection_.clear();
2236 selecting_ = false;
2237 find_results_.clear();
2238 next_page_to_search_ = -1;
2239 last_page_to_search_ = -1;
2240 last_character_index_to_search_ = -1;
2241 current_find_index_.Invalidate();
2242 current_find_text_.clear();
2243 UpdateTickMarks();
2244 find_factory_.CancelAll();
2247 void PDFiumEngine::GetAllScreenRectsUnion(std::vector<PDFiumRange>* rect_range,
2248 const pp::Point& offset_point,
2249 std::vector<pp::Rect>* rect_vector) {
2250 for (std::vector<PDFiumRange>::iterator it = rect_range->begin();
2251 it != rect_range->end(); ++it) {
2252 pp::Rect rect;
2253 std::vector<pp::Rect> rects =
2254 it->GetScreenRects(offset_point, current_zoom_, current_rotation_);
2255 for (size_t j = 0; j < rects.size(); ++j)
2256 rect = rect.Union(rects[j]);
2257 rect_vector->push_back(rect);
2261 void PDFiumEngine::UpdateTickMarks() {
2262 std::vector<pp::Rect> tickmarks;
2263 GetAllScreenRectsUnion(&find_results_, pp::Point(0, 0), &tickmarks);
2264 client_->UpdateTickMarks(tickmarks);
2267 void PDFiumEngine::ZoomUpdated(double new_zoom_level) {
2268 CancelPaints();
2270 current_zoom_ = new_zoom_level;
2272 CalculateVisiblePages();
2273 UpdateTickMarks();
2276 void PDFiumEngine::RotateClockwise() {
2277 current_rotation_ = (current_rotation_ + 1) % 4;
2278 RotateInternal();
2281 void PDFiumEngine::RotateCounterclockwise() {
2282 current_rotation_ = (current_rotation_ - 1) % 4;
2283 RotateInternal();
2286 void PDFiumEngine::InvalidateAllPages() {
2287 CancelPaints();
2288 StopFind();
2289 LoadPageInfo(true);
2290 client_->Invalidate(pp::Rect(plugin_size_));
2293 std::string PDFiumEngine::GetSelectedText() {
2294 if (!HasPermission(PDFEngine::PERMISSION_COPY))
2295 return std::string();
2297 base::string16 result;
2298 base::string16 new_line_char = base::UTF8ToUTF16("\n");
2299 for (size_t i = 0; i < selection_.size(); ++i) {
2300 if (i > 0 &&
2301 selection_[i - 1].page_index() > selection_[i].page_index()) {
2302 result = selection_[i].GetText() + new_line_char + result;
2303 } else {
2304 if (i > 0)
2305 result.append(new_line_char);
2306 result.append(selection_[i].GetText());
2310 FormatStringWithHyphens(&result);
2311 FormatStringForOS(&result);
2312 return base::UTF16ToUTF8(result);
2315 std::string PDFiumEngine::GetLinkAtPosition(const pp::Point& point) {
2316 int temp;
2317 PDFiumPage::LinkTarget target;
2318 pp::Point point_in_page(
2319 static_cast<int>((point.x() + position_.x()) / current_zoom_),
2320 static_cast<int>((point.y() + position_.y()) / current_zoom_));
2321 PDFiumPage::Area area = GetCharIndex(point_in_page, &temp, &temp, &target);
2322 if (area == PDFiumPage::WEBLINK_AREA)
2323 return target.url;
2324 return std::string();
2327 bool PDFiumEngine::IsSelecting() {
2328 return selecting_;
2331 bool PDFiumEngine::HasPermission(DocumentPermission permission) const {
2332 switch (permission) {
2333 case PERMISSION_COPY:
2334 return (permissions_ & kPDFPermissionCopyMask) != 0;
2335 case PERMISSION_COPY_ACCESSIBLE:
2336 return (permissions_ & kPDFPermissionCopyAccessibleMask) != 0;
2337 case PERMISSION_PRINT_LOW_QUALITY:
2338 return (permissions_ & kPDFPermissionPrintLowQualityMask) != 0;
2339 case PERMISSION_PRINT_HIGH_QUALITY:
2340 return (permissions_ & kPDFPermissionPrintLowQualityMask) != 0 &&
2341 (permissions_ & kPDFPermissionPrintHighQualityMask) != 0;
2342 default:
2343 return true;
2347 void PDFiumEngine::SelectAll() {
2348 SelectionChangeInvalidator selection_invalidator(this);
2350 selection_.clear();
2351 for (size_t i = 0; i < pages_.size(); ++i)
2352 if (pages_[i]->available()) {
2353 selection_.push_back(PDFiumRange(pages_[i], 0,
2354 pages_[i]->GetCharCount()));
2358 int PDFiumEngine::GetNumberOfPages() {
2359 return pages_.size();
2363 pp::VarArray PDFiumEngine::GetBookmarks() {
2364 pp::VarDictionary dict = TraverseBookmarks(doc_, NULL);
2365 // The root bookmark contains no useful information.
2366 return pp::VarArray(dict.Get(pp::Var("children")));
2369 int PDFiumEngine::GetNamedDestinationPage(const std::string& destination) {
2370 // Look for the destination.
2371 FPDF_DEST dest = FPDF_GetNamedDestByName(doc_, destination.c_str());
2372 if (!dest) {
2373 // Look for a bookmark with the same name.
2374 base::string16 destination_wide = base::UTF8ToUTF16(destination);
2375 FPDF_WIDESTRING destination_pdf_wide =
2376 reinterpret_cast<FPDF_WIDESTRING>(destination_wide.c_str());
2377 FPDF_BOOKMARK bookmark = FPDFBookmark_Find(doc_, destination_pdf_wide);
2378 if (!bookmark)
2379 return -1;
2380 dest = FPDFBookmark_GetDest(doc_, bookmark);
2382 return dest ? FPDFDest_GetPageIndex(doc_, dest) : -1;
2385 pp::VarDictionary PDFiumEngine::GetNamedDestinations() {
2386 pp::VarDictionary named_destinations;
2387 for (unsigned long i = 0; i < FPDF_CountNamedDests(doc_); i++) {
2388 base::string16 name;
2389 unsigned long buffer_bytes;
2390 FPDF_GetNamedDest(doc_, i, NULL, buffer_bytes);
2391 size_t name_length = buffer_bytes / sizeof(base::string16::value_type);
2392 if (name_length > 0) {
2393 PDFiumAPIStringBufferAdapter<base::string16> api_string_adapter(
2394 &name, name_length, true);
2395 FPDF_DEST dest = FPDF_GetNamedDest(doc_, i, api_string_adapter.GetData(),
2396 buffer_bytes);
2397 api_string_adapter.Close(name_length);
2398 if (dest) {
2399 std::string named_dest = base::UTF16ToUTF8(name);
2400 int page_number = GetNamedDestinationPage(named_dest);
2401 if (page_number >= 0) {
2402 named_destinations.Set(pp::Var(named_dest.c_str()),
2403 pp::Var(page_number));
2408 return named_destinations;
2411 int PDFiumEngine::GetFirstVisiblePage() {
2412 CalculateVisiblePages();
2413 return first_visible_page_;
2416 int PDFiumEngine::GetMostVisiblePage() {
2417 CalculateVisiblePages();
2418 return most_visible_page_;
2421 pp::Rect PDFiumEngine::GetPageRect(int index) {
2422 pp::Rect rc(pages_[index]->rect());
2423 rc.Inset(-kPageShadowLeft, -kPageShadowTop,
2424 -kPageShadowRight, -kPageShadowBottom);
2425 return rc;
2428 pp::Rect PDFiumEngine::GetPageContentsRect(int index) {
2429 return GetScreenRect(pages_[index]->rect());
2432 void PDFiumEngine::PaintThumbnail(pp::ImageData* image_data, int index) {
2433 FPDF_BITMAP bitmap = FPDFBitmap_CreateEx(
2434 image_data->size().width(), image_data->size().height(),
2435 FPDFBitmap_BGRx, image_data->data(), image_data->stride());
2437 if (pages_[index]->available()) {
2438 FPDFBitmap_FillRect(bitmap, 0, 0, image_data->size().width(),
2439 image_data->size().height(), 0xFFFFFFFF);
2441 FPDF_RenderPageBitmap(
2442 bitmap, pages_[index]->GetPage(), 0, 0, image_data->size().width(),
2443 image_data->size().height(), 0, GetRenderingFlags());
2444 } else {
2445 FPDFBitmap_FillRect(bitmap, 0, 0, image_data->size().width(),
2446 image_data->size().height(), kPendingPageColor);
2449 FPDFBitmap_Destroy(bitmap);
2452 void PDFiumEngine::SetGrayscale(bool grayscale) {
2453 render_grayscale_ = grayscale;
2456 void PDFiumEngine::OnCallback(int id) {
2457 if (!timers_.count(id))
2458 return;
2460 timers_[id].second(id);
2461 if (timers_.count(id)) // The callback might delete the timer.
2462 client_->ScheduleCallback(id, timers_[id].first);
2465 std::string PDFiumEngine::GetPageAsJSON(int index) {
2466 if (!(HasPermission(PERMISSION_COPY) ||
2467 HasPermission(PERMISSION_COPY_ACCESSIBLE))) {
2468 return "{}";
2471 if (index < 0 || static_cast<size_t>(index) > pages_.size() - 1)
2472 return "{}";
2474 scoped_ptr<base::Value> node(
2475 pages_[index]->GetAccessibleContentAsValue(current_rotation_));
2476 std::string page_json;
2477 base::JSONWriter::Write(node.get(), &page_json);
2478 return page_json;
2481 bool PDFiumEngine::GetPrintScaling() {
2482 return !!FPDF_VIEWERREF_GetPrintScaling(doc_);
2485 int PDFiumEngine::GetCopiesToPrint() {
2486 return FPDF_VIEWERREF_GetNumCopies(doc_);
2489 void PDFiumEngine::AppendBlankPages(int num_pages) {
2490 DCHECK(num_pages != 0);
2492 if (!doc_)
2493 return;
2495 selection_.clear();
2496 pending_pages_.clear();
2498 // Delete all pages except the first one.
2499 while (pages_.size() > 1) {
2500 delete pages_.back();
2501 pages_.pop_back();
2502 FPDFPage_Delete(doc_, pages_.size());
2505 // Calculate document size and all page sizes.
2506 std::vector<pp::Rect> page_rects;
2507 pp::Size page_size = GetPageSize(0);
2508 page_size.Enlarge(kPageShadowLeft + kPageShadowRight,
2509 kPageShadowTop + kPageShadowBottom);
2510 pp::Size old_document_size = document_size_;
2511 document_size_ = pp::Size(page_size.width(), 0);
2512 for (int i = 0; i < num_pages; ++i) {
2513 if (i != 0) {
2514 // Add space for horizontal separator.
2515 document_size_.Enlarge(0, kPageSeparatorThickness);
2518 pp::Rect rect(pp::Point(0, document_size_.height()), page_size);
2519 page_rects.push_back(rect);
2521 document_size_.Enlarge(0, page_size.height());
2524 // Create blank pages.
2525 for (int i = 1; i < num_pages; ++i) {
2526 pp::Rect page_rect(page_rects[i]);
2527 page_rect.Inset(kPageShadowLeft, kPageShadowTop,
2528 kPageShadowRight, kPageShadowBottom);
2529 double width_in_points =
2530 page_rect.width() * kPointsPerInch / kPixelsPerInch;
2531 double height_in_points =
2532 page_rect.height() * kPointsPerInch / kPixelsPerInch;
2533 FPDFPage_New(doc_, i, width_in_points, height_in_points);
2534 pages_.push_back(new PDFiumPage(this, i, page_rect, true));
2537 CalculateVisiblePages();
2538 if (document_size_ != old_document_size)
2539 client_->DocumentSizeUpdated(document_size_);
2542 void PDFiumEngine::LoadDocument() {
2543 // Check if the document is ready for loading. If it isn't just bail for now,
2544 // we will call LoadDocument() again later.
2545 if (!doc_ && !doc_loader_.IsDocumentComplete() &&
2546 !FPDFAvail_IsDocAvail(fpdf_availability_, &download_hints_)) {
2547 return;
2550 // If we're in the middle of getting a password, just return. We will retry
2551 // loading the document after we get the password anyway.
2552 if (getting_password_)
2553 return;
2555 ScopedUnsupportedFeature scoped_unsupported_feature(this);
2556 bool needs_password = false;
2557 if (TryLoadingDoc(false, std::string(), &needs_password)) {
2558 ContinueLoadingDocument(false, std::string());
2559 return;
2561 if (needs_password)
2562 GetPasswordAndLoad();
2563 else
2564 client_->DocumentLoadFailed();
2567 bool PDFiumEngine::TryLoadingDoc(bool with_password,
2568 const std::string& password,
2569 bool* needs_password) {
2570 *needs_password = false;
2571 if (doc_)
2572 return true;
2574 const char* password_cstr = NULL;
2575 if (with_password) {
2576 password_cstr = password.c_str();
2577 password_tries_remaining_--;
2579 if (doc_loader_.IsDocumentComplete())
2580 doc_ = FPDF_LoadCustomDocument(&file_access_, password_cstr);
2581 else
2582 doc_ = FPDFAvail_GetDocument(fpdf_availability_, password_cstr);
2584 if (!doc_ && FPDF_GetLastError() == FPDF_ERR_PASSWORD)
2585 *needs_password = true;
2587 return doc_ != NULL;
2590 void PDFiumEngine::GetPasswordAndLoad() {
2591 getting_password_ = true;
2592 DCHECK(!doc_ && FPDF_GetLastError() == FPDF_ERR_PASSWORD);
2593 client_->GetDocumentPassword(password_factory_.NewCallbackWithOutput(
2594 &PDFiumEngine::OnGetPasswordComplete));
2597 void PDFiumEngine::OnGetPasswordComplete(int32_t result,
2598 const pp::Var& password) {
2599 getting_password_ = false;
2601 bool password_given = false;
2602 std::string password_text;
2603 if (result == PP_OK && password.is_string()) {
2604 password_text = password.AsString();
2605 if (!password_text.empty())
2606 password_given = true;
2608 ContinueLoadingDocument(password_given, password_text);
2611 void PDFiumEngine::ContinueLoadingDocument(
2612 bool has_password,
2613 const std::string& password) {
2614 ScopedUnsupportedFeature scoped_unsupported_feature(this);
2616 bool needs_password = false;
2617 bool loaded = TryLoadingDoc(has_password, password, &needs_password);
2618 bool password_incorrect = !loaded && has_password && needs_password;
2619 if (password_incorrect && password_tries_remaining_ > 0) {
2620 GetPasswordAndLoad();
2621 return;
2624 if (!doc_) {
2625 client_->DocumentLoadFailed();
2626 return;
2629 if (FPDFDoc_GetPageMode(doc_) == PAGEMODE_USEOUTLINES)
2630 client_->DocumentHasUnsupportedFeature("Bookmarks");
2632 permissions_ = FPDF_GetDocPermissions(doc_);
2634 if (!form_) {
2635 // Only returns 0 when data isn't available. If form data is downloaded, or
2636 // if this isn't a form, returns positive values.
2637 if (!doc_loader_.IsDocumentComplete() &&
2638 !FPDFAvail_IsFormAvail(fpdf_availability_, &download_hints_)) {
2639 return;
2642 form_ = FPDFDOC_InitFormFillEnvironment(
2643 doc_, static_cast<FPDF_FORMFILLINFO*>(this));
2644 #ifdef PDF_USE_XFA
2645 FPDF_LoadXFA(doc_);
2646 #endif
2648 FPDF_SetFormFieldHighlightColor(form_, 0, kFormHighlightColor);
2649 FPDF_SetFormFieldHighlightAlpha(form_, kFormHighlightAlpha);
2652 if (!doc_loader_.IsDocumentComplete()) {
2653 // Check if the first page is available. In a linearized PDF, that is not
2654 // always page 0. Doing this gives us the default page size, since when the
2655 // document is available, the first page is available as well.
2656 CheckPageAvailable(FPDFAvail_GetFirstPageNum(doc_), &pending_pages_);
2659 LoadPageInfo(false);
2661 if (doc_loader_.IsDocumentComplete())
2662 FinishLoadingDocument();
2665 void PDFiumEngine::LoadPageInfo(bool reload) {
2666 pending_pages_.clear();
2667 pp::Size old_document_size = document_size_;
2668 document_size_ = pp::Size();
2669 std::vector<pp::Rect> page_rects;
2670 int page_count = FPDF_GetPageCount(doc_);
2671 bool doc_complete = doc_loader_.IsDocumentComplete();
2672 for (int i = 0; i < page_count; ++i) {
2673 if (i != 0) {
2674 // Add space for horizontal separator.
2675 document_size_.Enlarge(0, kPageSeparatorThickness);
2678 // Get page availability. If reload==false, and document is not loaded yet
2679 // (we are using async loading) - mark all pages as unavailable.
2680 // If reload==true (we have document constructed already), get page
2681 // availability flag from already existing PDFiumPage class.
2682 bool page_available = reload ? pages_[i]->available() : doc_complete;
2684 pp::Size size = page_available ? GetPageSize(i) : default_page_size_;
2685 size.Enlarge(kPageShadowLeft + kPageShadowRight,
2686 kPageShadowTop + kPageShadowBottom);
2687 pp::Rect rect(pp::Point(0, document_size_.height()), size);
2688 page_rects.push_back(rect);
2690 if (size.width() > document_size_.width())
2691 document_size_.set_width(size.width());
2693 document_size_.Enlarge(0, size.height());
2696 for (int i = 0; i < page_count; ++i) {
2697 // Center pages relative to the entire document.
2698 page_rects[i].set_x((document_size_.width() - page_rects[i].width()) / 2);
2699 pp::Rect page_rect(page_rects[i]);
2700 page_rect.Inset(kPageShadowLeft, kPageShadowTop,
2701 kPageShadowRight, kPageShadowBottom);
2702 if (reload) {
2703 pages_[i]->set_rect(page_rect);
2704 } else {
2705 pages_.push_back(new PDFiumPage(this, i, page_rect, doc_complete));
2709 CalculateVisiblePages();
2710 if (document_size_ != old_document_size)
2711 client_->DocumentSizeUpdated(document_size_);
2714 void PDFiumEngine::CalculateVisiblePages() {
2715 // Clear pending requests queue, since it may contain requests to the pages
2716 // that are already invisible (after scrolling for example).
2717 pending_pages_.clear();
2718 doc_loader_.ClearPendingRequests();
2720 visible_pages_.clear();
2721 pp::Rect visible_rect(plugin_size_);
2722 for (size_t i = 0; i < pages_.size(); ++i) {
2723 // Check an entire PageScreenRect, since we might need to repaint side
2724 // borders and shadows even if the page itself is not visible.
2725 // For example, when user use pdf with different page sizes and zoomed in
2726 // outside page area.
2727 if (visible_rect.Intersects(GetPageScreenRect(i))) {
2728 visible_pages_.push_back(i);
2729 CheckPageAvailable(i, &pending_pages_);
2730 } else {
2731 // Need to unload pages when we're not using them, since some PDFs use a
2732 // lot of memory. See http://crbug.com/48791
2733 if (defer_page_unload_) {
2734 deferred_page_unloads_.push_back(i);
2735 } else {
2736 pages_[i]->Unload();
2739 // If the last mouse down was on a page that's no longer visible, reset
2740 // that variable so that we don't send keyboard events to it (the focus
2741 // will be lost when the page is first closed anyways).
2742 if (static_cast<int>(i) == last_page_mouse_down_)
2743 last_page_mouse_down_ = -1;
2747 // Any pending highlighting of form fields will be invalid since these are in
2748 // screen coordinates.
2749 form_highlights_.clear();
2751 if (visible_pages_.size() == 0)
2752 first_visible_page_ = -1;
2753 else
2754 first_visible_page_ = visible_pages_.front();
2756 int most_visible_page = first_visible_page_;
2757 // Check if the next page is more visible than the first one.
2758 if (most_visible_page != -1 &&
2759 pages_.size() > 0 &&
2760 most_visible_page < static_cast<int>(pages_.size()) - 1) {
2761 pp::Rect rc_first =
2762 visible_rect.Intersect(GetPageScreenRect(most_visible_page));
2763 pp::Rect rc_next =
2764 visible_rect.Intersect(GetPageScreenRect(most_visible_page + 1));
2765 if (rc_next.height() > rc_first.height())
2766 most_visible_page++;
2769 SetCurrentPage(most_visible_page);
2772 bool PDFiumEngine::IsPageVisible(int index) const {
2773 for (size_t i = 0; i < visible_pages_.size(); ++i) {
2774 if (visible_pages_[i] == index)
2775 return true;
2778 return false;
2781 bool PDFiumEngine::CheckPageAvailable(int index, std::vector<int>* pending) {
2782 if (!doc_ || !form_)
2783 return false;
2785 if (static_cast<int>(pages_.size()) > index && pages_[index]->available())
2786 return true;
2788 if (!FPDFAvail_IsPageAvail(fpdf_availability_, index, &download_hints_)) {
2789 size_t j;
2790 for (j = 0; j < pending->size(); ++j) {
2791 if ((*pending)[j] == index)
2792 break;
2795 if (j == pending->size())
2796 pending->push_back(index);
2797 return false;
2800 if (static_cast<int>(pages_.size()) > index)
2801 pages_[index]->set_available(true);
2802 if (!default_page_size_.GetArea())
2803 default_page_size_ = GetPageSize(index);
2804 return true;
2807 pp::Size PDFiumEngine::GetPageSize(int index) {
2808 pp::Size size;
2809 double width_in_points = 0;
2810 double height_in_points = 0;
2811 int rv = FPDF_GetPageSizeByIndex(
2812 doc_, index, &width_in_points, &height_in_points);
2814 if (rv) {
2815 int width_in_pixels = static_cast<int>(
2816 width_in_points * kPixelsPerInch / kPointsPerInch);
2817 int height_in_pixels = static_cast<int>(
2818 height_in_points * kPixelsPerInch / kPointsPerInch);
2819 if (current_rotation_ % 2 == 1)
2820 std::swap(width_in_pixels, height_in_pixels);
2821 size = pp::Size(width_in_pixels, height_in_pixels);
2823 return size;
2826 int PDFiumEngine::StartPaint(int page_index, const pp::Rect& dirty) {
2827 // For the first time we hit paint, do nothing and just record the paint for
2828 // the next callback. This keeps the UI responsive in case the user is doing
2829 // a lot of scrolling.
2830 ProgressivePaint progressive;
2831 progressive.rect = dirty;
2832 progressive.page_index = page_index;
2833 progressive.bitmap = NULL;
2834 progressive.painted_ = false;
2835 progressive_paints_.push_back(progressive);
2836 return progressive_paints_.size() - 1;
2839 bool PDFiumEngine::ContinuePaint(int progressive_index,
2840 pp::ImageData* image_data) {
2841 #if defined(OS_LINUX)
2842 g_last_instance_id = client_->GetPluginInstance()->pp_instance();
2843 #endif
2845 int rv;
2846 int page_index = progressive_paints_[progressive_index].page_index;
2847 last_progressive_start_time_ = base::Time::Now();
2848 if (progressive_paints_[progressive_index].bitmap) {
2849 rv = FPDF_RenderPage_Continue(
2850 pages_[page_index]->GetPage(), static_cast<IFSDK_PAUSE*>(this));
2851 } else {
2852 pp::Rect dirty = progressive_paints_[progressive_index].rect;
2853 progressive_paints_[progressive_index].bitmap = CreateBitmap(dirty,
2854 image_data);
2855 int start_x, start_y, size_x, size_y;
2856 GetPDFiumRect(
2857 page_index, dirty, &start_x, &start_y, &size_x, &size_y);
2858 FPDFBitmap_FillRect(progressive_paints_[progressive_index].bitmap, start_x,
2859 start_y, size_x, size_y, 0xFFFFFFFF);
2860 rv = FPDF_RenderPageBitmap_Start(
2861 progressive_paints_[progressive_index].bitmap,
2862 pages_[page_index]->GetPage(), start_x, start_y, size_x, size_y,
2863 current_rotation_,
2864 GetRenderingFlags(), static_cast<IFSDK_PAUSE*>(this));
2866 return rv != FPDF_RENDER_TOBECOUNTINUED;
2869 void PDFiumEngine::FinishPaint(int progressive_index,
2870 pp::ImageData* image_data) {
2871 int page_index = progressive_paints_[progressive_index].page_index;
2872 pp::Rect dirty_in_screen = progressive_paints_[progressive_index].rect;
2873 FPDF_BITMAP bitmap = progressive_paints_[progressive_index].bitmap;
2874 int start_x, start_y, size_x, size_y;
2875 GetPDFiumRect(
2876 page_index, dirty_in_screen, &start_x, &start_y, &size_x, &size_y);
2878 // Draw the forms.
2879 FPDF_FFLDraw(
2880 form_, bitmap, pages_[page_index]->GetPage(), start_x, start_y, size_x,
2881 size_y, current_rotation_, GetRenderingFlags());
2883 FillPageSides(progressive_index);
2885 // Paint the page shadows.
2886 PaintPageShadow(progressive_index, image_data);
2888 DrawSelections(progressive_index, image_data);
2890 FPDF_RenderPage_Close(pages_[page_index]->GetPage());
2891 FPDFBitmap_Destroy(bitmap);
2892 progressive_paints_.erase(progressive_paints_.begin() + progressive_index);
2894 client_->DocumentPaintOccurred();
2897 void PDFiumEngine::CancelPaints() {
2898 for (size_t i = 0; i < progressive_paints_.size(); ++i) {
2899 FPDF_RenderPage_Close(pages_[progressive_paints_[i].page_index]->GetPage());
2900 FPDFBitmap_Destroy(progressive_paints_[i].bitmap);
2902 progressive_paints_.clear();
2905 void PDFiumEngine::FillPageSides(int progressive_index) {
2906 int page_index = progressive_paints_[progressive_index].page_index;
2907 pp::Rect dirty_in_screen = progressive_paints_[progressive_index].rect;
2908 FPDF_BITMAP bitmap = progressive_paints_[progressive_index].bitmap;
2910 pp::Rect page_rect = pages_[page_index]->rect();
2911 if (page_rect.x() > 0) {
2912 pp::Rect left(0,
2913 page_rect.y() - kPageShadowTop,
2914 page_rect.x() - kPageShadowLeft,
2915 page_rect.height() + kPageShadowTop +
2916 kPageShadowBottom + kPageSeparatorThickness);
2917 left = GetScreenRect(left).Intersect(dirty_in_screen);
2919 FPDFBitmap_FillRect(bitmap, left.x() - dirty_in_screen.x(),
2920 left.y() - dirty_in_screen.y(), left.width(),
2921 left.height(), kBackgroundColor);
2924 if (page_rect.right() < document_size_.width()) {
2925 pp::Rect right(page_rect.right() + kPageShadowRight,
2926 page_rect.y() - kPageShadowTop,
2927 document_size_.width() - page_rect.right() -
2928 kPageShadowRight,
2929 page_rect.height() + kPageShadowTop +
2930 kPageShadowBottom + kPageSeparatorThickness);
2931 right = GetScreenRect(right).Intersect(dirty_in_screen);
2933 FPDFBitmap_FillRect(bitmap, right.x() - dirty_in_screen.x(),
2934 right.y() - dirty_in_screen.y(), right.width(),
2935 right.height(), kBackgroundColor);
2938 // Paint separator.
2939 pp::Rect bottom(page_rect.x() - kPageShadowLeft,
2940 page_rect.bottom() + kPageShadowBottom,
2941 page_rect.width() + kPageShadowLeft + kPageShadowRight,
2942 kPageSeparatorThickness);
2943 bottom = GetScreenRect(bottom).Intersect(dirty_in_screen);
2945 FPDFBitmap_FillRect(bitmap, bottom.x() - dirty_in_screen.x(),
2946 bottom.y() - dirty_in_screen.y(), bottom.width(),
2947 bottom.height(), kBackgroundColor);
2950 void PDFiumEngine::PaintPageShadow(int progressive_index,
2951 pp::ImageData* image_data) {
2952 int page_index = progressive_paints_[progressive_index].page_index;
2953 pp::Rect dirty_in_screen = progressive_paints_[progressive_index].rect;
2954 pp::Rect page_rect = pages_[page_index]->rect();
2955 pp::Rect shadow_rect(page_rect);
2956 shadow_rect.Inset(-kPageShadowLeft, -kPageShadowTop,
2957 -kPageShadowRight, -kPageShadowBottom);
2959 // Due to the rounding errors of the GetScreenRect it is possible to get
2960 // different size shadows on the left and right sides even they are defined
2961 // the same. To fix this issue let's calculate shadow rect and then shrink
2962 // it by the size of the shadows.
2963 shadow_rect = GetScreenRect(shadow_rect);
2964 page_rect = shadow_rect;
2966 page_rect.Inset(static_cast<int>(ceil(kPageShadowLeft * current_zoom_)),
2967 static_cast<int>(ceil(kPageShadowTop * current_zoom_)),
2968 static_cast<int>(ceil(kPageShadowRight * current_zoom_)),
2969 static_cast<int>(ceil(kPageShadowBottom * current_zoom_)));
2971 DrawPageShadow(page_rect, shadow_rect, dirty_in_screen, image_data);
2974 void PDFiumEngine::DrawSelections(int progressive_index,
2975 pp::ImageData* image_data) {
2976 int page_index = progressive_paints_[progressive_index].page_index;
2977 pp::Rect dirty_in_screen = progressive_paints_[progressive_index].rect;
2979 void* region = NULL;
2980 int stride;
2981 GetRegion(dirty_in_screen.point(), image_data, &region, &stride);
2983 std::vector<pp::Rect> highlighted_rects;
2984 pp::Rect visible_rect = GetVisibleRect();
2985 for (size_t k = 0; k < selection_.size(); ++k) {
2986 if (selection_[k].page_index() != page_index)
2987 continue;
2988 std::vector<pp::Rect> rects = selection_[k].GetScreenRects(
2989 visible_rect.point(), current_zoom_, current_rotation_);
2990 for (size_t j = 0; j < rects.size(); ++j) {
2991 pp::Rect visible_selection = rects[j].Intersect(dirty_in_screen);
2992 if (visible_selection.IsEmpty())
2993 continue;
2995 visible_selection.Offset(
2996 -dirty_in_screen.point().x(), -dirty_in_screen.point().y());
2997 Highlight(region, stride, visible_selection, &highlighted_rects);
3001 for (size_t k = 0; k < form_highlights_.size(); ++k) {
3002 pp::Rect visible_selection = form_highlights_[k].Intersect(dirty_in_screen);
3003 if (visible_selection.IsEmpty())
3004 continue;
3006 visible_selection.Offset(
3007 -dirty_in_screen.point().x(), -dirty_in_screen.point().y());
3008 Highlight(region, stride, visible_selection, &highlighted_rects);
3010 form_highlights_.clear();
3013 void PDFiumEngine::PaintUnavailablePage(int page_index,
3014 const pp::Rect& dirty,
3015 pp::ImageData* image_data) {
3016 int start_x, start_y, size_x, size_y;
3017 GetPDFiumRect(page_index, dirty, &start_x, &start_y, &size_x, &size_y);
3018 FPDF_BITMAP bitmap = CreateBitmap(dirty, image_data);
3019 FPDFBitmap_FillRect(bitmap, start_x, start_y, size_x, size_y,
3020 kPendingPageColor);
3022 pp::Rect loading_text_in_screen(
3023 pages_[page_index]->rect().width() / 2,
3024 pages_[page_index]->rect().y() + kLoadingTextVerticalOffset, 0, 0);
3025 loading_text_in_screen = GetScreenRect(loading_text_in_screen);
3026 FPDFBitmap_Destroy(bitmap);
3029 int PDFiumEngine::GetProgressiveIndex(int page_index) const {
3030 for (size_t i = 0; i < progressive_paints_.size(); ++i) {
3031 if (progressive_paints_[i].page_index == page_index)
3032 return i;
3034 return -1;
3037 FPDF_BITMAP PDFiumEngine::CreateBitmap(const pp::Rect& rect,
3038 pp::ImageData* image_data) const {
3039 void* region;
3040 int stride;
3041 GetRegion(rect.point(), image_data, &region, &stride);
3042 if (!region)
3043 return NULL;
3044 return FPDFBitmap_CreateEx(
3045 rect.width(), rect.height(), FPDFBitmap_BGRx, region, stride);
3048 void PDFiumEngine::GetPDFiumRect(
3049 int page_index, const pp::Rect& rect, int* start_x, int* start_y,
3050 int* size_x, int* size_y) const {
3051 pp::Rect page_rect = GetScreenRect(pages_[page_index]->rect());
3052 page_rect.Offset(-rect.x(), -rect.y());
3054 *start_x = page_rect.x();
3055 *start_y = page_rect.y();
3056 *size_x = page_rect.width();
3057 *size_y = page_rect.height();
3060 int PDFiumEngine::GetRenderingFlags() const {
3061 int flags = FPDF_LCD_TEXT | FPDF_NO_CATCH;
3062 if (render_grayscale_)
3063 flags |= FPDF_GRAYSCALE;
3064 if (client_->IsPrintPreview())
3065 flags |= FPDF_PRINTING;
3066 return flags;
3069 pp::Rect PDFiumEngine::GetVisibleRect() const {
3070 pp::Rect rv;
3071 rv.set_x(static_cast<int>(position_.x() / current_zoom_));
3072 rv.set_y(static_cast<int>(position_.y() / current_zoom_));
3073 rv.set_width(static_cast<int>(ceil(plugin_size_.width() / current_zoom_)));
3074 rv.set_height(static_cast<int>(ceil(plugin_size_.height() / current_zoom_)));
3075 return rv;
3078 pp::Rect PDFiumEngine::GetPageScreenRect(int page_index) const {
3079 // Since we use this rect for creating the PDFium bitmap, also include other
3080 // areas around the page that we might need to update such as the page
3081 // separator and the sides if the page is narrower than the document.
3082 return GetScreenRect(pp::Rect(
3084 pages_[page_index]->rect().y() - kPageShadowTop,
3085 document_size_.width(),
3086 pages_[page_index]->rect().height() + kPageShadowTop +
3087 kPageShadowBottom + kPageSeparatorThickness));
3090 pp::Rect PDFiumEngine::GetScreenRect(const pp::Rect& rect) const {
3091 pp::Rect rv;
3092 int right =
3093 static_cast<int>(ceil(rect.right() * current_zoom_ - position_.x()));
3094 int bottom =
3095 static_cast<int>(ceil(rect.bottom() * current_zoom_ - position_.y()));
3097 rv.set_x(static_cast<int>(rect.x() * current_zoom_ - position_.x()));
3098 rv.set_y(static_cast<int>(rect.y() * current_zoom_ - position_.y()));
3099 rv.set_width(right - rv.x());
3100 rv.set_height(bottom - rv.y());
3101 return rv;
3104 void PDFiumEngine::Highlight(void* buffer,
3105 int stride,
3106 const pp::Rect& rect,
3107 std::vector<pp::Rect>* highlighted_rects) {
3108 if (!buffer)
3109 return;
3111 pp::Rect new_rect = rect;
3112 for (size_t i = 0; i < highlighted_rects->size(); ++i)
3113 new_rect = new_rect.Subtract((*highlighted_rects)[i]);
3115 highlighted_rects->push_back(new_rect);
3116 int l = new_rect.x();
3117 int t = new_rect.y();
3118 int w = new_rect.width();
3119 int h = new_rect.height();
3121 for (int y = t; y < t + h; ++y) {
3122 for (int x = l; x < l + w; ++x) {
3123 uint8* pixel = static_cast<uint8*>(buffer) + y * stride + x * 4;
3124 // This is our highlight color.
3125 pixel[0] = static_cast<uint8>(
3126 pixel[0] * (kHighlightColorB / 255.0));
3127 pixel[1] = static_cast<uint8>(
3128 pixel[1] * (kHighlightColorG / 255.0));
3129 pixel[2] = static_cast<uint8>(
3130 pixel[2] * (kHighlightColorR / 255.0));
3135 PDFiumEngine::SelectionChangeInvalidator::SelectionChangeInvalidator(
3136 PDFiumEngine* engine) : engine_(engine) {
3137 previous_origin_ = engine_->GetVisibleRect().point();
3138 GetVisibleSelectionsScreenRects(&old_selections_);
3141 PDFiumEngine::SelectionChangeInvalidator::~SelectionChangeInvalidator() {
3142 // Offset the old selections if the document scrolled since we recorded them.
3143 pp::Point offset = previous_origin_ - engine_->GetVisibleRect().point();
3144 for (size_t i = 0; i < old_selections_.size(); ++i)
3145 old_selections_[i].Offset(offset);
3147 std::vector<pp::Rect> new_selections;
3148 GetVisibleSelectionsScreenRects(&new_selections);
3149 for (size_t i = 0; i < new_selections.size(); ++i) {
3150 for (size_t j = 0; j < old_selections_.size(); ++j) {
3151 if (!old_selections_[j].IsEmpty() &&
3152 new_selections[i] == old_selections_[j]) {
3153 // Rectangle was selected before and after, so no need to invalidate it.
3154 // Mark the rectangles by setting them to empty.
3155 new_selections[i] = old_selections_[j] = pp::Rect();
3156 break;
3161 for (size_t i = 0; i < old_selections_.size(); ++i) {
3162 if (!old_selections_[i].IsEmpty())
3163 engine_->client_->Invalidate(old_selections_[i]);
3165 for (size_t i = 0; i < new_selections.size(); ++i) {
3166 if (!new_selections[i].IsEmpty())
3167 engine_->client_->Invalidate(new_selections[i]);
3169 engine_->OnSelectionChanged();
3172 void
3173 PDFiumEngine::SelectionChangeInvalidator::GetVisibleSelectionsScreenRects(
3174 std::vector<pp::Rect>* rects) {
3175 pp::Rect visible_rect = engine_->GetVisibleRect();
3176 for (size_t i = 0; i < engine_->selection_.size(); ++i) {
3177 int page_index = engine_->selection_[i].page_index();
3178 if (!engine_->IsPageVisible(page_index))
3179 continue; // This selection is on a page that's not currently visible.
3181 std::vector<pp::Rect> selection_rects =
3182 engine_->selection_[i].GetScreenRects(
3183 visible_rect.point(),
3184 engine_->current_zoom_,
3185 engine_->current_rotation_);
3186 rects->insert(rects->end(), selection_rects.begin(), selection_rects.end());
3190 PDFiumEngine::MouseDownState::MouseDownState(
3191 const PDFiumPage::Area& area,
3192 const PDFiumPage::LinkTarget& target)
3193 : area_(area), target_(target) {
3196 PDFiumEngine::MouseDownState::~MouseDownState() {
3199 void PDFiumEngine::MouseDownState::Set(const PDFiumPage::Area& area,
3200 const PDFiumPage::LinkTarget& target) {
3201 area_ = area;
3202 target_ = target;
3205 void PDFiumEngine::MouseDownState::Reset() {
3206 area_ = PDFiumPage::NONSELECTABLE_AREA;
3207 target_ = PDFiumPage::LinkTarget();
3210 bool PDFiumEngine::MouseDownState::Matches(
3211 const PDFiumPage::Area& area,
3212 const PDFiumPage::LinkTarget& target) const {
3213 if (area_ == area) {
3214 if (area == PDFiumPage::WEBLINK_AREA)
3215 return target_.url == target.url;
3216 if (area == PDFiumPage::DOCLINK_AREA)
3217 return target_.page == target.page;
3218 return true;
3220 return false;
3223 PDFiumEngine::FindTextIndex::FindTextIndex()
3224 : valid_(false), index_(0) {
3227 PDFiumEngine::FindTextIndex::~FindTextIndex() {
3230 void PDFiumEngine::FindTextIndex::Invalidate() {
3231 valid_ = false;
3234 size_t PDFiumEngine::FindTextIndex::GetIndex() const {
3235 DCHECK(valid_);
3236 return index_;
3239 void PDFiumEngine::FindTextIndex::SetIndex(size_t index) {
3240 valid_ = true;
3241 index_ = index;
3244 size_t PDFiumEngine::FindTextIndex::IncrementIndex() {
3245 DCHECK(valid_);
3246 return ++index_;
3249 void PDFiumEngine::DeviceToPage(int page_index,
3250 float device_x,
3251 float device_y,
3252 double* page_x,
3253 double* page_y) {
3254 *page_x = *page_y = 0;
3255 int temp_x = static_cast<int>((device_x + position_.x())/ current_zoom_ -
3256 pages_[page_index]->rect().x());
3257 int temp_y = static_cast<int>((device_y + position_.y())/ current_zoom_ -
3258 pages_[page_index]->rect().y());
3259 FPDF_DeviceToPage(
3260 pages_[page_index]->GetPage(), 0, 0,
3261 pages_[page_index]->rect().width(), pages_[page_index]->rect().height(),
3262 current_rotation_, temp_x, temp_y, page_x, page_y);
3265 int PDFiumEngine::GetVisiblePageIndex(FPDF_PAGE page) {
3266 for (size_t i = 0; i < visible_pages_.size(); ++i) {
3267 if (pages_[visible_pages_[i]]->GetPage() == page)
3268 return visible_pages_[i];
3270 return -1;
3273 void PDFiumEngine::SetCurrentPage(int index) {
3274 if (index == most_visible_page_ || !form_)
3275 return;
3276 if (most_visible_page_ != -1 && called_do_document_action_) {
3277 FPDF_PAGE old_page = pages_[most_visible_page_]->GetPage();
3278 FORM_DoPageAAction(old_page, form_, FPDFPAGE_AACTION_CLOSE);
3280 most_visible_page_ = index;
3281 #if defined(OS_LINUX)
3282 g_last_instance_id = client_->GetPluginInstance()->pp_instance();
3283 #endif
3284 if (most_visible_page_ != -1 && called_do_document_action_) {
3285 FPDF_PAGE new_page = pages_[most_visible_page_]->GetPage();
3286 FORM_DoPageAAction(new_page, form_, FPDFPAGE_AACTION_OPEN);
3290 void PDFiumEngine::TransformPDFPageForPrinting(
3291 FPDF_PAGE page,
3292 const PP_PrintSettings_Dev& print_settings) {
3293 // Get the source page width and height in points.
3294 const double src_page_width = FPDF_GetPageWidth(page);
3295 const double src_page_height = FPDF_GetPageHeight(page);
3297 const int src_page_rotation = FPDFPage_GetRotation(page);
3298 const bool fit_to_page = print_settings.print_scaling_option ==
3299 PP_PRINTSCALINGOPTION_FIT_TO_PRINTABLE_AREA;
3301 pp::Size page_size(print_settings.paper_size);
3302 pp::Rect content_rect(print_settings.printable_area);
3303 const bool rotated = (src_page_rotation % 2 == 1);
3304 SetPageSizeAndContentRect(rotated,
3305 src_page_width > src_page_height,
3306 &page_size,
3307 &content_rect);
3309 // Compute the screen page width and height in points.
3310 const int actual_page_width =
3311 rotated ? page_size.height() : page_size.width();
3312 const int actual_page_height =
3313 rotated ? page_size.width() : page_size.height();
3315 const double scale_factor = CalculateScaleFactor(fit_to_page, content_rect,
3316 src_page_width,
3317 src_page_height, rotated);
3319 // Calculate positions for the clip box.
3320 ClipBox source_clip_box;
3321 CalculateClipBoxBoundary(page, scale_factor, rotated, &source_clip_box);
3323 // Calculate the translation offset values.
3324 double offset_x = 0;
3325 double offset_y = 0;
3326 if (fit_to_page) {
3327 CalculateScaledClipBoxOffset(content_rect, source_clip_box, &offset_x,
3328 &offset_y);
3329 } else {
3330 CalculateNonScaledClipBoxOffset(content_rect, src_page_rotation,
3331 actual_page_width, actual_page_height,
3332 source_clip_box, &offset_x, &offset_y);
3335 // Reset the media box and crop box. When the page has crop box and media box,
3336 // the plugin will display the crop box contents and not the entire media box.
3337 // If the pages have different crop box values, the plugin will display a
3338 // document of multiple page sizes. To give better user experience, we
3339 // decided to have same crop box and media box values. Hence, the user will
3340 // see a list of uniform pages.
3341 FPDFPage_SetMediaBox(page, 0, 0, page_size.width(), page_size.height());
3342 FPDFPage_SetCropBox(page, 0, 0, page_size.width(), page_size.height());
3344 // Transformation is not required, return. Do this check only after updating
3345 // the media box and crop box. For more detailed information, please refer to
3346 // the comment block right before FPDF_SetMediaBox and FPDF_GetMediaBox calls.
3347 if (scale_factor == 1.0 && offset_x == 0 && offset_y == 0)
3348 return;
3351 // All the positions have been calculated, now manipulate the PDF.
3352 FS_MATRIX matrix = {static_cast<float>(scale_factor),
3355 static_cast<float>(scale_factor),
3356 static_cast<float>(offset_x),
3357 static_cast<float>(offset_y)};
3358 FS_RECTF cliprect = {static_cast<float>(source_clip_box.left+offset_x),
3359 static_cast<float>(source_clip_box.top+offset_y),
3360 static_cast<float>(source_clip_box.right+offset_x),
3361 static_cast<float>(source_clip_box.bottom+offset_y)};
3362 FPDFPage_TransFormWithClip(page, &matrix, &cliprect);
3363 FPDFPage_TransformAnnots(page, scale_factor, 0, 0, scale_factor,
3364 offset_x, offset_y);
3367 void PDFiumEngine::DrawPageShadow(const pp::Rect& page_rc,
3368 const pp::Rect& shadow_rc,
3369 const pp::Rect& clip_rc,
3370 pp::ImageData* image_data) {
3371 pp::Rect page_rect(page_rc);
3372 page_rect.Offset(page_offset_);
3374 pp::Rect shadow_rect(shadow_rc);
3375 shadow_rect.Offset(page_offset_);
3377 pp::Rect clip_rect(clip_rc);
3378 clip_rect.Offset(page_offset_);
3380 // Page drop shadow parameters.
3381 const double factor = 0.5;
3382 uint32 depth = std::max(
3383 std::max(page_rect.x() - shadow_rect.x(),
3384 page_rect.y() - shadow_rect.y()),
3385 std::max(shadow_rect.right() - page_rect.right(),
3386 shadow_rect.bottom() - page_rect.bottom()));
3387 depth = static_cast<uint32>(depth * 1.5) + 1;
3389 // We need to check depth only to verify our copy of shadow matrix is correct.
3390 if (!page_shadow_.get() || page_shadow_->depth() != depth)
3391 page_shadow_.reset(new ShadowMatrix(depth, factor, kBackgroundColor));
3393 DCHECK(!image_data->is_null());
3394 DrawShadow(image_data, shadow_rect, page_rect, clip_rect, *page_shadow_);
3397 void PDFiumEngine::GetRegion(const pp::Point& location,
3398 pp::ImageData* image_data,
3399 void** region,
3400 int* stride) const {
3401 if (image_data->is_null()) {
3402 DCHECK(plugin_size_.IsEmpty());
3403 *stride = 0;
3404 *region = NULL;
3405 return;
3407 char* buffer = static_cast<char*>(image_data->data());
3408 *stride = image_data->stride();
3410 pp::Point offset_location = location + page_offset_;
3411 // TODO: update this when we support BIDI and scrollbars can be on the left.
3412 if (!buffer ||
3413 !pp::Rect(page_offset_, plugin_size_).Contains(offset_location)) {
3414 *region = NULL;
3415 return;
3418 buffer += location.y() * (*stride);
3419 buffer += (location.x() + page_offset_.x()) * 4;
3420 *region = buffer;
3423 void PDFiumEngine::OnSelectionChanged() {
3424 pp::PDF::SetSelectedText(GetPluginInstance(), GetSelectedText().c_str());
3427 void PDFiumEngine::RotateInternal() {
3428 // Store the current find index so that we can resume finding at that
3429 // particular index after we have recomputed the find results.
3430 std::string current_find_text = current_find_text_;
3431 if (current_find_index_.valid())
3432 resume_find_index_.SetIndex(current_find_index_.GetIndex());
3433 else
3434 resume_find_index_.Invalidate();
3436 InvalidateAllPages();
3438 if (!current_find_text.empty()) {
3439 // Clear the UI.
3440 client_->NotifyNumberOfFindResultsChanged(0, false);
3441 StartFind(current_find_text.c_str(), false);
3445 void PDFiumEngine::Form_Invalidate(FPDF_FORMFILLINFO* param,
3446 FPDF_PAGE page,
3447 double left,
3448 double top,
3449 double right,
3450 double bottom) {
3451 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3452 int page_index = engine->GetVisiblePageIndex(page);
3453 if (page_index == -1) {
3454 // This can sometime happen when the page is closed because it went off
3455 // screen, and PDFium invalidates the control as it's being deleted.
3456 return;
3459 pp::Rect rect = engine->pages_[page_index]->PageToScreen(
3460 engine->GetVisibleRect().point(), engine->current_zoom_, left, top, right,
3461 bottom, engine->current_rotation_);
3462 engine->client_->Invalidate(rect);
3465 void PDFiumEngine::Form_OutputSelectedRect(FPDF_FORMFILLINFO* param,
3466 FPDF_PAGE page,
3467 double left,
3468 double top,
3469 double right,
3470 double bottom) {
3471 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3472 int page_index = engine->GetVisiblePageIndex(page);
3473 if (page_index == -1) {
3474 NOTREACHED();
3475 return;
3477 pp::Rect rect = engine->pages_[page_index]->PageToScreen(
3478 engine->GetVisibleRect().point(), engine->current_zoom_, left, top, right,
3479 bottom, engine->current_rotation_);
3480 engine->form_highlights_.push_back(rect);
3483 void PDFiumEngine::Form_SetCursor(FPDF_FORMFILLINFO* param, int cursor_type) {
3484 // We don't need this since it's not enough to change the cursor in all
3485 // scenarios. Instead, we check which form field we're under in OnMouseMove.
3488 int PDFiumEngine::Form_SetTimer(FPDF_FORMFILLINFO* param,
3489 int elapse,
3490 TimerCallback timer_func) {
3491 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3492 engine->timers_[++engine->next_timer_id_] =
3493 std::pair<int, TimerCallback>(elapse, timer_func);
3494 engine->client_->ScheduleCallback(engine->next_timer_id_, elapse);
3495 return engine->next_timer_id_;
3498 void PDFiumEngine::Form_KillTimer(FPDF_FORMFILLINFO* param, int timer_id) {
3499 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3500 engine->timers_.erase(timer_id);
3503 FPDF_SYSTEMTIME PDFiumEngine::Form_GetLocalTime(FPDF_FORMFILLINFO* param) {
3504 base::Time time = base::Time::Now();
3505 base::Time::Exploded exploded;
3506 time.LocalExplode(&exploded);
3508 FPDF_SYSTEMTIME rv;
3509 rv.wYear = exploded.year;
3510 rv.wMonth = exploded.month;
3511 rv.wDayOfWeek = exploded.day_of_week;
3512 rv.wDay = exploded.day_of_month;
3513 rv.wHour = exploded.hour;
3514 rv.wMinute = exploded.minute;
3515 rv.wSecond = exploded.second;
3516 rv.wMilliseconds = exploded.millisecond;
3517 return rv;
3520 void PDFiumEngine::Form_OnChange(FPDF_FORMFILLINFO* param) {
3521 // Don't care about.
3524 FPDF_PAGE PDFiumEngine::Form_GetPage(FPDF_FORMFILLINFO* param,
3525 FPDF_DOCUMENT document,
3526 int page_index) {
3527 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3528 if (page_index < 0 || page_index >= static_cast<int>(engine->pages_.size()))
3529 return NULL;
3530 return engine->pages_[page_index]->GetPage();
3533 FPDF_PAGE PDFiumEngine::Form_GetCurrentPage(FPDF_FORMFILLINFO* param,
3534 FPDF_DOCUMENT document) {
3535 // TODO(jam): find out what this is used for.
3536 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3537 int index = engine->last_page_mouse_down_;
3538 if (index == -1) {
3539 index = engine->GetMostVisiblePage();
3540 if (index == -1) {
3541 NOTREACHED();
3542 return NULL;
3546 return engine->pages_[index]->GetPage();
3549 int PDFiumEngine::Form_GetRotation(FPDF_FORMFILLINFO* param, FPDF_PAGE page) {
3550 return 0;
3553 void PDFiumEngine::Form_ExecuteNamedAction(FPDF_FORMFILLINFO* param,
3554 FPDF_BYTESTRING named_action) {
3555 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3556 std::string action(named_action);
3557 if (action == "Print") {
3558 engine->client_->Print();
3559 return;
3562 int index = engine->last_page_mouse_down_;
3563 /* Don't try to calculate the most visible page if we don't have a left click
3564 before this event (this code originally copied Form_GetCurrentPage which of
3565 course needs to do that and which doesn't have recursion). This can end up
3566 causing infinite recursion. See http://crbug.com/240413 for more
3567 information. Either way, it's not necessary for the spec'd list of named
3568 actions.
3569 if (index == -1)
3570 index = engine->GetMostVisiblePage();
3572 if (index == -1)
3573 return;
3575 // This is the only list of named actions per the spec (see 12.6.4.11). Adobe
3576 // Reader supports more, like FitWidth, but since they're not part of the spec
3577 // and we haven't got bugs about them, no need to now.
3578 if (action == "NextPage") {
3579 engine->client_->ScrollToPage(index + 1);
3580 } else if (action == "PrevPage") {
3581 engine->client_->ScrollToPage(index - 1);
3582 } else if (action == "FirstPage") {
3583 engine->client_->ScrollToPage(0);
3584 } else if (action == "LastPage") {
3585 engine->client_->ScrollToPage(engine->pages_.size() - 1);
3589 void PDFiumEngine::Form_SetTextFieldFocus(FPDF_FORMFILLINFO* param,
3590 FPDF_WIDESTRING value,
3591 FPDF_DWORD valueLen,
3592 FPDF_BOOL is_focus) {
3593 // Do nothing for now.
3594 // TODO(gene): use this signal to trigger OSK.
3597 void PDFiumEngine::Form_DoURIAction(FPDF_FORMFILLINFO* param,
3598 FPDF_BYTESTRING uri) {
3599 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3600 engine->client_->NavigateTo(std::string(uri), false);
3603 void PDFiumEngine::Form_DoGoToAction(FPDF_FORMFILLINFO* param,
3604 int page_index,
3605 int zoom_mode,
3606 float* position_array,
3607 int size_of_array) {
3608 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3609 engine->client_->ScrollToPage(page_index);
3612 int PDFiumEngine::Form_Alert(IPDF_JSPLATFORM* param,
3613 FPDF_WIDESTRING message,
3614 FPDF_WIDESTRING title,
3615 int type,
3616 int icon) {
3617 // See fpdfformfill.h for these values.
3618 enum AlertType {
3619 ALERT_TYPE_OK = 0,
3620 ALERT_TYPE_OK_CANCEL,
3621 ALERT_TYPE_YES_ON,
3622 ALERT_TYPE_YES_NO_CANCEL
3625 enum AlertResult {
3626 ALERT_RESULT_OK = 1,
3627 ALERT_RESULT_CANCEL,
3628 ALERT_RESULT_NO,
3629 ALERT_RESULT_YES
3632 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3633 std::string message_str =
3634 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(message));
3635 if (type == ALERT_TYPE_OK) {
3636 engine->client_->Alert(message_str);
3637 return ALERT_RESULT_OK;
3640 bool rv = engine->client_->Confirm(message_str);
3641 if (type == ALERT_TYPE_OK_CANCEL)
3642 return rv ? ALERT_RESULT_OK : ALERT_RESULT_CANCEL;
3643 return rv ? ALERT_RESULT_YES : ALERT_RESULT_NO;
3646 void PDFiumEngine::Form_Beep(IPDF_JSPLATFORM* param, int type) {
3647 // Beeps are annoying, and not possible using javascript, so ignore for now.
3650 int PDFiumEngine::Form_Response(IPDF_JSPLATFORM* param,
3651 FPDF_WIDESTRING question,
3652 FPDF_WIDESTRING title,
3653 FPDF_WIDESTRING default_response,
3654 FPDF_WIDESTRING label,
3655 FPDF_BOOL password,
3656 void* response,
3657 int length) {
3658 std::string question_str = base::UTF16ToUTF8(
3659 reinterpret_cast<const base::char16*>(question));
3660 std::string default_str = base::UTF16ToUTF8(
3661 reinterpret_cast<const base::char16*>(default_response));
3663 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3664 std::string rv = engine->client_->Prompt(question_str, default_str);
3665 base::string16 rv_16 = base::UTF8ToUTF16(rv);
3666 int rv_bytes = rv_16.size() * sizeof(base::char16);
3667 if (response) {
3668 int bytes_to_copy = rv_bytes < length ? rv_bytes : length;
3669 memcpy(response, rv_16.c_str(), bytes_to_copy);
3671 return rv_bytes;
3674 int PDFiumEngine::Form_GetFilePath(IPDF_JSPLATFORM* param,
3675 void* file_path,
3676 int length) {
3677 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3678 std::string rv = engine->client_->GetURL();
3679 if (file_path && rv.size() <= static_cast<size_t>(length))
3680 memcpy(file_path, rv.c_str(), rv.size());
3681 return rv.size();
3684 void PDFiumEngine::Form_Mail(IPDF_JSPLATFORM* param,
3685 void* mail_data,
3686 int length,
3687 FPDF_BOOL ui,
3688 FPDF_WIDESTRING to,
3689 FPDF_WIDESTRING subject,
3690 FPDF_WIDESTRING cc,
3691 FPDF_WIDESTRING bcc,
3692 FPDF_WIDESTRING message) {
3693 // Note: |mail_data| and |length| are ignored. We don't handle attachments;
3694 // there is no way with mailto.
3695 std::string to_str =
3696 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(to));
3697 std::string cc_str =
3698 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(cc));
3699 std::string bcc_str =
3700 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(bcc));
3701 std::string subject_str =
3702 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(subject));
3703 std::string message_str =
3704 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(message));
3706 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3707 engine->client_->Email(to_str, cc_str, bcc_str, subject_str, message_str);
3710 void PDFiumEngine::Form_Print(IPDF_JSPLATFORM* param,
3711 FPDF_BOOL ui,
3712 int start,
3713 int end,
3714 FPDF_BOOL silent,
3715 FPDF_BOOL shrink_to_fit,
3716 FPDF_BOOL print_as_image,
3717 FPDF_BOOL reverse,
3718 FPDF_BOOL annotations) {
3719 // No way to pass the extra information to the print dialog using JavaScript.
3720 // Just opening it is fine for now.
3721 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3722 engine->client_->Print();
3725 void PDFiumEngine::Form_SubmitForm(IPDF_JSPLATFORM* param,
3726 void* form_data,
3727 int length,
3728 FPDF_WIDESTRING url) {
3729 std::string url_str =
3730 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(url));
3731 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3732 engine->client_->SubmitForm(url_str, form_data, length);
3735 void PDFiumEngine::Form_GotoPage(IPDF_JSPLATFORM* param,
3736 int page_number) {
3737 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3738 engine->client_->ScrollToPage(page_number);
3741 int PDFiumEngine::Form_Browse(IPDF_JSPLATFORM* param,
3742 void* file_path,
3743 int length) {
3744 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3745 std::string path = engine->client_->ShowFileSelectionDialog();
3746 if (path.size() + 1 <= static_cast<size_t>(length))
3747 memcpy(file_path, &path[0], path.size() + 1);
3748 return path.size() + 1;
3751 FPDF_BOOL PDFiumEngine::Pause_NeedToPauseNow(IFSDK_PAUSE* param) {
3752 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3753 return (base::Time::Now() - engine->last_progressive_start_time_).
3754 InMilliseconds() > engine->progressive_paint_timeout_;
3757 ScopedUnsupportedFeature::ScopedUnsupportedFeature(PDFiumEngine* engine)
3758 : engine_(engine), old_engine_(g_engine_for_unsupported) {
3759 g_engine_for_unsupported = engine_;
3762 ScopedUnsupportedFeature::~ScopedUnsupportedFeature() {
3763 g_engine_for_unsupported = old_engine_;
3766 PDFEngineExports* PDFEngineExports::Create() {
3767 return new PDFiumEngineExports;
3770 namespace {
3772 int CalculatePosition(FPDF_PAGE page,
3773 const PDFiumEngineExports::RenderingSettings& settings,
3774 pp::Rect* dest) {
3775 int page_width = static_cast<int>(
3776 FPDF_GetPageWidth(page) * settings.dpi_x / kPointsPerInch);
3777 int page_height = static_cast<int>(
3778 FPDF_GetPageHeight(page) * settings.dpi_y / kPointsPerInch);
3780 // Start by assuming that we will draw exactly to the bounds rect
3781 // specified.
3782 *dest = settings.bounds;
3784 int rotate = 0; // normal orientation.
3786 // Auto-rotate landscape pages to print correctly.
3787 if (settings.autorotate &&
3788 (dest->width() > dest->height()) != (page_width > page_height)) {
3789 rotate = 3; // 90 degrees counter-clockwise.
3790 std::swap(page_width, page_height);
3793 // See if we need to scale the output
3794 bool scale_to_bounds = false;
3795 if (settings.fit_to_bounds &&
3796 ((page_width > dest->width()) || (page_height > dest->height()))) {
3797 scale_to_bounds = true;
3798 } else if (settings.stretch_to_bounds &&
3799 ((page_width < dest->width()) || (page_height < dest->height()))) {
3800 scale_to_bounds = true;
3803 if (scale_to_bounds) {
3804 // If we need to maintain aspect ratio, calculate the actual width and
3805 // height.
3806 if (settings.keep_aspect_ratio) {
3807 double scale_factor_x = page_width;
3808 scale_factor_x /= dest->width();
3809 double scale_factor_y = page_height;
3810 scale_factor_y /= dest->height();
3811 if (scale_factor_x > scale_factor_y) {
3812 dest->set_height(page_height / scale_factor_x);
3813 } else {
3814 dest->set_width(page_width / scale_factor_y);
3817 } else {
3818 // We are not scaling to bounds. Draw in the actual page size. If the
3819 // actual page size is larger than the bounds, the output will be
3820 // clipped.
3821 dest->set_width(page_width);
3822 dest->set_height(page_height);
3825 if (settings.center_in_bounds) {
3826 pp::Point offset((settings.bounds.width() - dest->width()) / 2,
3827 (settings.bounds.height() - dest->height()) / 2);
3828 dest->Offset(offset);
3830 return rotate;
3833 } // namespace
3835 #if defined(OS_WIN)
3836 bool PDFiumEngineExports::RenderPDFPageToDC(const void* pdf_buffer,
3837 int buffer_size,
3838 int page_number,
3839 const RenderingSettings& settings,
3840 HDC dc) {
3841 FPDF_DOCUMENT doc = FPDF_LoadMemDocument(pdf_buffer, buffer_size, NULL);
3842 if (!doc)
3843 return false;
3844 FPDF_PAGE page = FPDF_LoadPage(doc, page_number);
3845 if (!page) {
3846 FPDF_CloseDocument(doc);
3847 return false;
3849 RenderingSettings new_settings = settings;
3850 // calculate the page size
3851 if (new_settings.dpi_x == -1)
3852 new_settings.dpi_x = GetDeviceCaps(dc, LOGPIXELSX);
3853 if (new_settings.dpi_y == -1)
3854 new_settings.dpi_y = GetDeviceCaps(dc, LOGPIXELSY);
3856 pp::Rect dest;
3857 int rotate = CalculatePosition(page, new_settings, &dest);
3859 int save_state = SaveDC(dc);
3860 // The caller wanted all drawing to happen within the bounds specified.
3861 // Based on scale calculations, our destination rect might be larger
3862 // than the bounds. Set the clip rect to the bounds.
3863 IntersectClipRect(dc, settings.bounds.x(), settings.bounds.y(),
3864 settings.bounds.x() + settings.bounds.width(),
3865 settings.bounds.y() + settings.bounds.height());
3867 // A temporary hack. PDFs generated by Cairo (used by Chrome OS to generate
3868 // a PDF output from a webpage) result in very large metafiles and the
3869 // rendering using FPDF_RenderPage is incorrect. In this case, render as a
3870 // bitmap. Note that this code does not kick in for PDFs printed from Chrome
3871 // because in that case we create a temp PDF first before printing and this
3872 // temp PDF does not have a creator string that starts with "cairo".
3873 base::string16 creator;
3874 size_t buffer_bytes = FPDF_GetMetaText(doc, "Creator", NULL, 0);
3875 if (buffer_bytes > 1) {
3876 FPDF_GetMetaText(
3877 doc, "Creator", WriteInto(&creator, buffer_bytes + 1), buffer_bytes);
3879 bool use_bitmap = false;
3880 if (StartsWith(creator, L"cairo", false))
3881 use_bitmap = true;
3883 // Another temporary hack. Some PDFs seems to render very slowly if
3884 // FPDF_RenderPage is directly used on a printer DC. I suspect it is
3885 // because of the code to talk Postscript directly to the printer if
3886 // the printer supports this. Need to discuss this with PDFium. For now,
3887 // render to a bitmap and then blit the bitmap to the DC if we have been
3888 // supplied a printer DC.
3889 int device_type = GetDeviceCaps(dc, TECHNOLOGY);
3890 if (use_bitmap ||
3891 (device_type == DT_RASPRINTER) || (device_type == DT_PLOTTER)) {
3892 FPDF_BITMAP bitmap = FPDFBitmap_Create(dest.width(), dest.height(),
3893 FPDFBitmap_BGRx);
3894 // Clear the bitmap
3895 FPDFBitmap_FillRect(bitmap, 0, 0, dest.width(), dest.height(), 0xFFFFFFFF);
3896 FPDF_RenderPageBitmap(
3897 bitmap, page, 0, 0, dest.width(), dest.height(), rotate,
3898 FPDF_ANNOT | FPDF_PRINTING | FPDF_NO_CATCH);
3899 int stride = FPDFBitmap_GetStride(bitmap);
3900 BITMAPINFO bmi;
3901 memset(&bmi, 0, sizeof(bmi));
3902 bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
3903 bmi.bmiHeader.biWidth = dest.width();
3904 bmi.bmiHeader.biHeight = -dest.height(); // top-down image
3905 bmi.bmiHeader.biPlanes = 1;
3906 bmi.bmiHeader.biBitCount = 32;
3907 bmi.bmiHeader.biCompression = BI_RGB;
3908 bmi.bmiHeader.biSizeImage = stride * dest.height();
3909 StretchDIBits(dc, dest.x(), dest.y(), dest.width(), dest.height(),
3910 0, 0, dest.width(), dest.height(),
3911 FPDFBitmap_GetBuffer(bitmap), &bmi, DIB_RGB_COLORS, SRCCOPY);
3912 FPDFBitmap_Destroy(bitmap);
3913 } else {
3914 FPDF_RenderPage(dc, page, dest.x(), dest.y(), dest.width(), dest.height(),
3915 rotate, FPDF_ANNOT | FPDF_PRINTING | FPDF_NO_CATCH);
3917 RestoreDC(dc, save_state);
3918 FPDF_ClosePage(page);
3919 FPDF_CloseDocument(doc);
3920 return true;
3922 #endif // OS_WIN
3924 bool PDFiumEngineExports::RenderPDFPageToBitmap(
3925 const void* pdf_buffer,
3926 int pdf_buffer_size,
3927 int page_number,
3928 const RenderingSettings& settings,
3929 void* bitmap_buffer) {
3930 FPDF_DOCUMENT doc = FPDF_LoadMemDocument(pdf_buffer, pdf_buffer_size, NULL);
3931 if (!doc)
3932 return false;
3933 FPDF_PAGE page = FPDF_LoadPage(doc, page_number);
3934 if (!page) {
3935 FPDF_CloseDocument(doc);
3936 return false;
3939 pp::Rect dest;
3940 int rotate = CalculatePosition(page, settings, &dest);
3942 FPDF_BITMAP bitmap =
3943 FPDFBitmap_CreateEx(settings.bounds.width(), settings.bounds.height(),
3944 FPDFBitmap_BGRA, bitmap_buffer,
3945 settings.bounds.width() * 4);
3946 // Clear the bitmap
3947 FPDFBitmap_FillRect(bitmap, 0, 0, settings.bounds.width(),
3948 settings.bounds.height(), 0xFFFFFFFF);
3949 // Shift top-left corner of bounds to (0, 0) if it's not there.
3950 dest.set_point(dest.point() - settings.bounds.point());
3951 FPDF_RenderPageBitmap(
3952 bitmap, page, dest.x(), dest.y(), dest.width(), dest.height(), rotate,
3953 FPDF_ANNOT | FPDF_PRINTING | FPDF_NO_CATCH);
3954 FPDFBitmap_Destroy(bitmap);
3955 FPDF_ClosePage(page);
3956 FPDF_CloseDocument(doc);
3957 return true;
3960 bool PDFiumEngineExports::GetPDFDocInfo(const void* pdf_buffer,
3961 int buffer_size,
3962 int* page_count,
3963 double* max_page_width) {
3964 FPDF_DOCUMENT doc = FPDF_LoadMemDocument(pdf_buffer, buffer_size, NULL);
3965 if (!doc)
3966 return false;
3967 int page_count_local = FPDF_GetPageCount(doc);
3968 if (page_count) {
3969 *page_count = page_count_local;
3971 if (max_page_width) {
3972 *max_page_width = 0;
3973 for (int page_number = 0; page_number < page_count_local; page_number++) {
3974 double page_width = 0;
3975 double page_height = 0;
3976 FPDF_GetPageSizeByIndex(doc, page_number, &page_width, &page_height);
3977 if (page_width > *max_page_width) {
3978 *max_page_width = page_width;
3982 FPDF_CloseDocument(doc);
3983 return true;
3986 bool PDFiumEngineExports::GetPDFPageSizeByIndex(
3987 const void* pdf_buffer,
3988 int pdf_buffer_size,
3989 int page_number,
3990 double* width,
3991 double* height) {
3992 FPDF_DOCUMENT doc = FPDF_LoadMemDocument(pdf_buffer, pdf_buffer_size, NULL);
3993 if (!doc)
3994 return false;
3995 bool success = FPDF_GetPageSizeByIndex(doc, page_number, width, height) != 0;
3996 FPDF_CloseDocument(doc);
3997 return success;
4000 } // namespace chrome_pdf