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"
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_mem_buffer_file_read.h"
20 #include "pdf/pdfium/pdfium_mem_buffer_file_write.h"
21 #include "ppapi/c/pp_errors.h"
22 #include "ppapi/c/pp_input_event.h"
23 #include "ppapi/c/ppb_core.h"
24 #include "ppapi/c/private/ppb_pdf.h"
25 #include "ppapi/cpp/dev/memory_dev.h"
26 #include "ppapi/cpp/input_event.h"
27 #include "ppapi/cpp/instance.h"
28 #include "ppapi/cpp/module.h"
29 #include "ppapi/cpp/private/pdf.h"
30 #include "ppapi/cpp/trusted/browser_font_trusted.h"
31 #include "ppapi/cpp/url_response_info.h"
32 #include "ppapi/cpp/var.h"
33 #include "third_party/pdfium/fpdfsdk/include/fpdf_ext.h"
34 #include "third_party/pdfium/fpdfsdk/include/fpdf_flatten.h"
35 #include "third_party/pdfium/fpdfsdk/include/fpdf_searchex.h"
36 #include "third_party/pdfium/fpdfsdk/include/fpdf_sysfontinfo.h"
37 #include "third_party/pdfium/fpdfsdk/include/fpdf_transformpage.h"
38 #include "third_party/pdfium/fpdfsdk/include/fpdfedit.h"
39 #include "third_party/pdfium/fpdfsdk/include/fpdfoom.h"
40 #include "third_party/pdfium/fpdfsdk/include/fpdfppo.h"
41 #include "third_party/pdfium/fpdfsdk/include/fpdfsave.h"
42 #include "third_party/pdfium/fpdfsdk/include/pdfwindow/PDFWindow.h"
43 #include "third_party/pdfium/fpdfsdk/include/pdfwindow/PWL_FontMap.h"
44 #include "ui/events/keycodes/keyboard_codes.h"
46 namespace chrome_pdf {
50 #define kPageShadowTop 3
51 #define kPageShadowBottom 7
52 #define kPageShadowLeft 5
53 #define kPageShadowRight 5
55 #define kPageSeparatorThickness 4
56 #define kHighlightColorR 153
57 #define kHighlightColorG 193
58 #define kHighlightColorB 218
60 const uint32 kPendingPageColor = 0xFFEEEEEE;
62 #define kFormHighlightColor 0xFFE4DD
63 #define kFormHighlightAlpha 100
65 #define kMaxPasswordTries 3
68 // http://www.adobe.com/devnet/acrobat/pdfs/pdf_reference_1-7.pdf
69 #define kPDFPermissionPrintLowQualityMask 1 << 2
70 #define kPDFPermissionPrintHighQualityMask 1 << 11
71 #define kPDFPermissionCopyMask 1 << 4
72 #define kPDFPermissionCopyAccessibleMask 1 << 9
74 #define kLoadingTextVerticalOffset 50
76 // The maximum amount of time we'll spend doing a paint before we give back
77 // control of the thread.
78 #define kMaxProgressivePaintTimeMs 50
80 // The maximum amount of time we'll spend doing the first paint. This is less
81 // than the above to keep things smooth if the user is scrolling quickly. We
82 // try painting a little because with accelerated compositing, we get flushes
83 // only every 16 ms. If we were to wait until the next flush to paint the rest
84 // of the pdf, we would never get to draw the pdf and would only draw the
85 // scrollbars. This value is picked to give enough time for gpu related code to
86 // do its thing and still fit within the timelimit for 60Hz. For the
87 // non-composited case, this doesn't make things worse since we're still
88 // painting the scrollbars > 60 Hz.
89 #define kMaxInitialProgressivePaintTimeMs 10
91 // Copied from printing/units.cc because we don't want to depend on printing
92 // since it brings in libpng which causes duplicate symbols with PDFium.
93 const int kPointsPerInch = 72;
94 const int kPixelsPerInch = 96;
103 int ConvertUnit(int value, int old_unit, int new_unit) {
104 // With integer arithmetic, to divide a value with correct rounding, you need
105 // to add half of the divisor value to the dividend value. You need to do the
106 // reverse with negative number.
108 return ((value * new_unit) + (old_unit / 2)) / old_unit;
110 return ((value * new_unit) - (old_unit / 2)) / old_unit;
114 std::vector<uint32_t> GetPageNumbersFromPrintPageNumberRange(
115 const PP_PrintPageNumberRange_Dev* page_ranges,
116 uint32_t page_range_count) {
117 std::vector<uint32_t> page_numbers;
118 for (uint32_t index = 0; index < page_range_count; ++index) {
119 for (uint32_t page_number = page_ranges[index].first_page_number;
120 page_number <= page_ranges[index].last_page_number; ++page_number) {
121 page_numbers.push_back(page_number);
127 #if defined(OS_LINUX)
129 PP_Instance g_last_instance_id;
131 struct PDFFontSubstitution {
132 const char* pdf_name;
138 PP_BrowserFont_Trusted_Weight WeightToBrowserFontTrustedWeight(int weight) {
139 COMPILE_ASSERT(PP_BROWSERFONT_TRUSTED_WEIGHT_100 == 0,
140 PP_BrowserFont_Trusted_Weight_Min);
141 COMPILE_ASSERT(PP_BROWSERFONT_TRUSTED_WEIGHT_900 == 8,
142 PP_BrowserFont_Trusted_Weight_Max);
143 const int kMinimumWeight = 100;
144 const int kMaximumWeight = 900;
145 int normalized_weight =
146 std::min(std::max(weight, kMinimumWeight), kMaximumWeight);
147 normalized_weight = (normalized_weight / 100) - 1;
148 return static_cast<PP_BrowserFont_Trusted_Weight>(normalized_weight);
151 // This list is for CPWL_FontMap::GetDefaultFontByCharset().
152 // We pretend to have these font natively and let the browser (or underlying
153 // fontconfig) to pick the proper font on the system.
154 void EnumFonts(struct _FPDF_SYSFONTINFO* sysfontinfo, void* mapper) {
155 FPDF_AddInstalledFont(mapper, "Arial", FXFONT_DEFAULT_CHARSET);
158 while (CPWL_FontMap::defaultTTFMap[i].charset != -1) {
159 FPDF_AddInstalledFont(mapper,
160 CPWL_FontMap::defaultTTFMap[i].fontname,
161 CPWL_FontMap::defaultTTFMap[i].charset);
166 const PDFFontSubstitution PDFFontSubstitutions[] = {
167 {"Courier", "Courier New", false, false},
168 {"Courier-Bold", "Courier New", true, false},
169 {"Courier-BoldOblique", "Courier New", true, true},
170 {"Courier-Oblique", "Courier New", false, true},
171 {"Helvetica", "Arial", false, false},
172 {"Helvetica-Bold", "Arial", true, false},
173 {"Helvetica-BoldOblique", "Arial", true, true},
174 {"Helvetica-Oblique", "Arial", false, true},
175 {"Times-Roman", "Times New Roman", false, false},
176 {"Times-Bold", "Times New Roman", true, false},
177 {"Times-BoldItalic", "Times New Roman", true, true},
178 {"Times-Italic", "Times New Roman", false, true},
180 // MS P?(Mincho|Gothic) are the most notable fonts in Japanese PDF files
181 // without embedding the glyphs. Sometimes the font names are encoded
182 // in Japanese Windows's locale (CP932/Shift_JIS) without space.
183 // Most Linux systems don't have the exact font, but for outsourcing
184 // fontconfig to find substitutable font in the system, we pass ASCII
186 {"MS-PGothic", "MS PGothic", false, false},
187 {"MS-Gothic", "MS Gothic", false, false},
188 {"MS-PMincho", "MS PMincho", false, false},
189 {"MS-Mincho", "MS Mincho", false, false},
190 // MS PGothic in Shift_JIS encoding.
191 {"\x82\x6C\x82\x72\x82\x6F\x83\x53\x83\x56\x83\x62\x83\x4E",
192 "MS PGothic", false, false},
193 // MS Gothic in Shift_JIS encoding.
194 {"\x82\x6C\x82\x72\x83\x53\x83\x56\x83\x62\x83\x4E",
195 "MS Gothic", false, false},
196 // MS PMincho in Shift_JIS encoding.
197 {"\x82\x6C\x82\x72\x82\x6F\x96\xBE\x92\xA9",
198 "MS PMincho", false, false},
199 // MS Mincho in Shift_JIS encoding.
200 {"\x82\x6C\x82\x72\x96\xBE\x92\xA9",
201 "MS Mincho", false, false},
204 void* MapFont(struct _FPDF_SYSFONTINFO*, int weight, int italic,
205 int charset, int pitch_family, const char* face, int* exact) {
206 // Do not attempt to map fonts if pepper is not initialized (for privet local
208 // TODO(noamsml): Real font substitution (http://crbug.com/391978)
209 if (!pp::Module::Get())
212 pp::BrowserFontDescription description;
214 // Pretend the system does not have the Symbol font to force a fallback to
215 // the built in Symbol font in CFX_FontMapper::FindSubstFont().
216 if (strcmp(face, "Symbol") == 0)
219 if (pitch_family & FXFONT_FF_FIXEDPITCH) {
220 description.set_family(PP_BROWSERFONT_TRUSTED_FAMILY_MONOSPACE);
221 } else if (pitch_family & FXFONT_FF_ROMAN) {
222 description.set_family(PP_BROWSERFONT_TRUSTED_FAMILY_SERIF);
225 // Map from the standard PDF fonts to TrueType font names.
227 for (i = 0; i < arraysize(PDFFontSubstitutions); ++i) {
228 if (strcmp(face, PDFFontSubstitutions[i].pdf_name) == 0) {
229 description.set_face(PDFFontSubstitutions[i].face);
230 if (PDFFontSubstitutions[i].bold)
231 description.set_weight(PP_BROWSERFONT_TRUSTED_WEIGHT_BOLD);
232 if (PDFFontSubstitutions[i].italic)
233 description.set_italic(true);
238 if (i == arraysize(PDFFontSubstitutions)) {
239 // TODO(kochi): Pass the face in UTF-8. If face is not encoded in UTF-8,
240 // convert to UTF-8 before passing.
241 description.set_face(face);
243 description.set_weight(WeightToBrowserFontTrustedWeight(weight));
244 description.set_italic(italic > 0);
247 if (!pp::PDF::IsAvailable()) {
252 PP_Resource font_resource = pp::PDF::GetFontFileWithFallback(
253 pp::InstanceHandle(g_last_instance_id),
254 &description.pp_font_description(),
255 static_cast<PP_PrivateFontCharset>(charset));
256 long res_id = font_resource;
257 return reinterpret_cast<void*>(res_id);
260 unsigned long GetFontData(struct _FPDF_SYSFONTINFO*, void* font_id,
261 unsigned int table, unsigned char* buffer,
262 unsigned long buf_size) {
263 if (!pp::PDF::IsAvailable()) {
268 uint32_t size = buf_size;
269 long res_id = reinterpret_cast<long>(font_id);
270 if (!pp::PDF::GetFontTableForPrivateFontFile(res_id, table, buffer, &size))
275 void DeleteFont(struct _FPDF_SYSFONTINFO*, void* font_id) {
276 long res_id = reinterpret_cast<long>(font_id);
277 pp::Module::Get()->core()->ReleaseResource(res_id);
280 FPDF_SYSFONTINFO g_font_info = {
291 #endif // defined(OS_LINUX)
293 void OOM_Handler(_OOM_INFO*) {
294 // Kill the process. This is important for security, since the code doesn't
295 // NULL-check many memory allocations. If a malloc fails, returns NULL, and
296 // the buffer is then used, it provides a handy mapping of memory starting at
297 // address 0 for an attacker to utilize.
301 OOM_INFO g_oom_info = {
306 PDFiumEngine* g_engine_for_unsupported;
308 void Unsupported_Handler(UNSUPPORT_INFO*, int type) {
309 if (!g_engine_for_unsupported) {
314 g_engine_for_unsupported->UnsupportedFeature(type);
317 UNSUPPORT_INFO g_unsuppored_info = {
322 // Set the destination page size and content area in points based on source
323 // page rotation and orientation.
325 // |rotated| True if source page is rotated 90 degree or 270 degree.
326 // |is_src_page_landscape| is true if the source page orientation is landscape.
327 // |page_size| has the actual destination page size in points.
328 // |content_rect| has the actual destination page printable area values in
330 void SetPageSizeAndContentRect(bool rotated,
331 bool is_src_page_landscape,
333 pp::Rect* content_rect) {
334 bool is_dst_page_landscape = page_size->width() > page_size->height();
335 bool page_orientation_mismatched = is_src_page_landscape !=
336 is_dst_page_landscape;
337 bool rotate_dst_page = rotated ^ page_orientation_mismatched;
338 if (rotate_dst_page) {
339 page_size->SetSize(page_size->height(), page_size->width());
340 content_rect->SetRect(content_rect->y(), content_rect->x(),
341 content_rect->height(), content_rect->width());
345 // Calculate the scale factor between |content_rect| and a page of size
346 // |src_width| x |src_height|.
348 // |scale_to_fit| is true, if we need to calculate the scale factor.
349 // |content_rect| specifies the printable area of the destination page, with
350 // origin at left-bottom. Values are in points.
351 // |src_width| specifies the source page width in points.
352 // |src_height| specifies the source page height in points.
353 // |rotated| True if source page is rotated 90 degree or 270 degree.
354 double CalculateScaleFactor(bool scale_to_fit,
355 const pp::Rect& content_rect,
356 double src_width, double src_height, bool rotated) {
357 if (!scale_to_fit || src_width == 0 || src_height == 0)
360 double actual_source_page_width = rotated ? src_height : src_width;
361 double actual_source_page_height = rotated ? src_width : src_height;
362 double ratio_x = static_cast<double>(content_rect.width()) /
363 actual_source_page_width;
364 double ratio_y = static_cast<double>(content_rect.height()) /
365 actual_source_page_height;
366 return std::min(ratio_x, ratio_y);
369 // Compute source clip box boundaries based on the crop box / media box of
370 // source page and scale factor.
372 // |page| Handle to the source page. Returned by FPDF_LoadPage function.
373 // |scale_factor| specifies the scale factor that should be applied to source
374 // clip box boundaries.
375 // |rotated| True if source page is rotated 90 degree or 270 degree.
376 // |clip_box| out param to hold the computed source clip box values.
377 void CalculateClipBoxBoundary(FPDF_PAGE page, double scale_factor, bool rotated,
379 if (!FPDFPage_GetCropBox(page, &clip_box->left, &clip_box->bottom,
380 &clip_box->right, &clip_box->top)) {
381 if (!FPDFPage_GetMediaBox(page, &clip_box->left, &clip_box->bottom,
382 &clip_box->right, &clip_box->top)) {
383 // Make the default size to be letter size (8.5" X 11"). We are just
384 // following the PDFium way of handling these corner cases. PDFium always
385 // consider US-Letter as the default page size.
386 float paper_width = 612;
387 float paper_height = 792;
389 clip_box->bottom = 0;
390 clip_box->right = rotated ? paper_height : paper_width;
391 clip_box->top = rotated ? paper_width : paper_height;
394 clip_box->left *= scale_factor;
395 clip_box->right *= scale_factor;
396 clip_box->bottom *= scale_factor;
397 clip_box->top *= scale_factor;
400 // Calculate the clip box translation offset for a page that does need to be
401 // scaled. All parameters are in points.
403 // |content_rect| specifies the printable area of the destination page, with
404 // origin at left-bottom.
405 // |source_clip_box| specifies the source clip box positions, relative to
406 // origin at left-bottom.
407 // |offset_x| and |offset_y| will contain the final translation offsets for the
408 // source clip box, relative to origin at left-bottom.
409 void CalculateScaledClipBoxOffset(const pp::Rect& content_rect,
410 const ClipBox& source_clip_box,
411 double* offset_x, double* offset_y) {
412 const float clip_box_width = source_clip_box.right - source_clip_box.left;
413 const float clip_box_height = source_clip_box.top - source_clip_box.bottom;
415 // Center the intended clip region to real clip region.
416 *offset_x = (content_rect.width() - clip_box_width) / 2 + content_rect.x() -
417 source_clip_box.left;
418 *offset_y = (content_rect.height() - clip_box_height) / 2 + content_rect.y() -
419 source_clip_box.bottom;
422 // Calculate the clip box offset for a page that does not need to be scaled.
423 // All parameters are in points.
425 // |content_rect| specifies the printable area of the destination page, with
426 // origin at left-bottom.
427 // |rotation| specifies the source page rotation values which are N / 90
429 // |page_width| specifies the screen destination page width.
430 // |page_height| specifies the screen destination page height.
431 // |source_clip_box| specifies the source clip box positions, relative to origin
433 // |offset_x| and |offset_y| will contain the final translation offsets for the
434 // source clip box, relative to origin at left-bottom.
435 void CalculateNonScaledClipBoxOffset(const pp::Rect& content_rect, int rotation,
436 int page_width, int page_height,
437 const ClipBox& source_clip_box,
438 double* offset_x, double* offset_y) {
439 // Align the intended clip region to left-top corner of real clip region.
442 *offset_x = -1 * source_clip_box.left;
443 *offset_y = page_height - source_clip_box.top;
447 *offset_y = -1 * source_clip_box.bottom;
450 *offset_x = page_width - source_clip_box.right;
454 *offset_x = page_height - source_clip_box.right;
455 *offset_y = page_width - source_clip_box.top;
463 // This formats a string with special 0xfffe end-of-line hyphens the same way
464 // as Adobe Reader. When a hyphen is encountered, the next non-CR/LF whitespace
465 // becomes CR+LF and the hyphen is erased. If there is no whitespace between
466 // two hyphens, the latter hyphen is erased and ignored.
467 void FormatStringWithHyphens(base::string16* text) {
468 // First pass marks all the hyphen positions.
469 struct HyphenPosition {
470 HyphenPosition() : position(0), next_whitespace_position(0) {}
472 size_t next_whitespace_position; // 0 for none
474 std::vector<HyphenPosition> hyphen_positions;
475 HyphenPosition current_hyphen_position;
476 bool current_hyphen_position_is_valid = false;
477 const base::char16 kPdfiumHyphenEOL = 0xfffe;
479 for (size_t i = 0; i < text->size(); ++i) {
480 const base::char16& current_char = (*text)[i];
481 if (current_char == kPdfiumHyphenEOL) {
482 if (current_hyphen_position_is_valid)
483 hyphen_positions.push_back(current_hyphen_position);
484 current_hyphen_position = HyphenPosition();
485 current_hyphen_position.position = i;
486 current_hyphen_position_is_valid = true;
487 } else if (IsWhitespace(current_char)) {
488 if (current_hyphen_position_is_valid) {
489 if (current_char != L'\r' && current_char != L'\n')
490 current_hyphen_position.next_whitespace_position = i;
491 hyphen_positions.push_back(current_hyphen_position);
492 current_hyphen_position_is_valid = false;
496 if (current_hyphen_position_is_valid)
497 hyphen_positions.push_back(current_hyphen_position);
499 // With all the hyphen positions, do the search and replace.
500 while (!hyphen_positions.empty()) {
501 static const base::char16 kCr[] = {L'\r', L'\0'};
502 const HyphenPosition& position = hyphen_positions.back();
503 if (position.next_whitespace_position != 0) {
504 (*text)[position.next_whitespace_position] = L'\n';
505 text->insert(position.next_whitespace_position, kCr);
507 text->erase(position.position, 1);
508 hyphen_positions.pop_back();
511 // Adobe Reader also get rid of trailing spaces right before a CRLF.
512 static const base::char16 kSpaceCrCn[] = {L' ', L'\r', L'\n', L'\0'};
513 static const base::char16 kCrCn[] = {L'\r', L'\n', L'\0'};
514 ReplaceSubstringsAfterOffset(text, 0, kSpaceCrCn, kCrCn);
517 // Replace CR/LF with just LF on POSIX.
518 void FormatStringForOS(base::string16* text) {
519 #if defined(OS_POSIX)
520 static const base::char16 kCr[] = {L'\r', L'\0'};
521 static const base::char16 kBlank[] = {L'\0'};
522 base::ReplaceChars(*text, kCr, kBlank, text);
523 #elif defined(OS_WIN)
532 bool InitializeSDK(void* data) {
533 FPDF_InitLibrary(data);
535 #if defined(OS_LINUX)
536 // Font loading doesn't work in the renderer sandbox in Linux.
537 FPDF_SetSystemFontInfo(&g_font_info);
540 FSDK_SetOOMHandler(&g_oom_info);
541 FSDK_SetUnSpObjProcessHandler(&g_unsuppored_info);
547 FPDF_DestroyLibrary();
550 PDFEngine* PDFEngine::Create(PDFEngine::Client* client) {
551 return new PDFiumEngine(client);
554 PDFiumEngine::PDFiumEngine(PDFEngine::Client* client)
557 current_rotation_(0),
559 password_tries_remaining_(0),
562 defer_page_unload_(false),
564 mouse_down_state_(PDFiumPage::NONSELECTABLE_AREA,
565 PDFiumPage::LinkTarget()),
566 next_page_to_search_(-1),
567 last_page_to_search_(-1),
568 last_character_index_to_search_(-1),
570 fpdf_availability_(NULL),
572 last_page_mouse_down_(-1),
573 first_visible_page_(-1),
574 most_visible_page_(-1),
575 called_do_document_action_(false),
576 render_grayscale_(false),
577 progressive_paint_timeout_(0),
578 getting_password_(false) {
579 find_factory_.Initialize(this);
580 password_factory_.Initialize(this);
582 file_access_.m_FileLen = 0;
583 file_access_.m_GetBlock = &GetBlock;
584 file_access_.m_Param = &doc_loader_;
586 file_availability_.version = 1;
587 file_availability_.IsDataAvail = &IsDataAvail;
588 file_availability_.loader = &doc_loader_;
590 download_hints_.version = 1;
591 download_hints_.AddSegment = &AddSegment;
592 download_hints_.loader = &doc_loader_;
594 // Initialize FPDF_FORMFILLINFO member variables. Deriving from this struct
595 // allows the static callbacks to be able to cast the FPDF_FORMFILLINFO in
596 // callbacks to ourself instead of maintaining a map of them to
598 FPDF_FORMFILLINFO::version = 1;
599 FPDF_FORMFILLINFO::m_pJsPlatform = this;
600 FPDF_FORMFILLINFO::Release = NULL;
601 FPDF_FORMFILLINFO::FFI_Invalidate = Form_Invalidate;
602 FPDF_FORMFILLINFO::FFI_OutputSelectedRect = Form_OutputSelectedRect;
603 FPDF_FORMFILLINFO::FFI_SetCursor = Form_SetCursor;
604 FPDF_FORMFILLINFO::FFI_SetTimer = Form_SetTimer;
605 FPDF_FORMFILLINFO::FFI_KillTimer = Form_KillTimer;
606 FPDF_FORMFILLINFO::FFI_GetLocalTime = Form_GetLocalTime;
607 FPDF_FORMFILLINFO::FFI_OnChange = Form_OnChange;
608 FPDF_FORMFILLINFO::FFI_GetPage = Form_GetPage;
609 FPDF_FORMFILLINFO::FFI_GetCurrentPage = Form_GetCurrentPage;
610 FPDF_FORMFILLINFO::FFI_GetRotation = Form_GetRotation;
611 FPDF_FORMFILLINFO::FFI_ExecuteNamedAction = Form_ExecuteNamedAction;
612 FPDF_FORMFILLINFO::FFI_SetTextFieldFocus = Form_SetTextFieldFocus;
613 FPDF_FORMFILLINFO::FFI_DoURIAction = Form_DoURIAction;
614 FPDF_FORMFILLINFO::FFI_DoGoToAction = Form_DoGoToAction;
616 IPDF_JSPLATFORM::version = 1;
617 IPDF_JSPLATFORM::app_alert = Form_Alert;
618 IPDF_JSPLATFORM::app_beep = Form_Beep;
619 IPDF_JSPLATFORM::app_response = Form_Response;
620 IPDF_JSPLATFORM::Doc_getFilePath = Form_GetFilePath;
621 IPDF_JSPLATFORM::Doc_mail = Form_Mail;
622 IPDF_JSPLATFORM::Doc_print = Form_Print;
623 IPDF_JSPLATFORM::Doc_submitForm = Form_SubmitForm;
624 IPDF_JSPLATFORM::Doc_gotoPage = Form_GotoPage;
625 IPDF_JSPLATFORM::Field_browse = Form_Browse;
627 IFSDK_PAUSE::version = 1;
628 IFSDK_PAUSE::user = NULL;
629 IFSDK_PAUSE::NeedToPauseNow = Pause_NeedToPauseNow;
632 PDFiumEngine::~PDFiumEngine() {
633 for (size_t i = 0; i < pages_.size(); ++i)
638 FORM_DoDocumentAAction(form_, FPDFDOC_AACTION_WC);
639 FPDFDOC_ExitFormFillEnviroument(form_);
641 FPDF_CloseDocument(doc_);
644 if (fpdf_availability_)
645 FPDFAvail_Destroy(fpdf_availability_);
647 STLDeleteElements(&pages_);
650 int PDFiumEngine::GetBlock(void* param, unsigned long position,
651 unsigned char* buffer, unsigned long size) {
652 DocumentLoader* loader = static_cast<DocumentLoader*>(param);
653 return loader->GetBlock(position, size, buffer);
656 bool PDFiumEngine::IsDataAvail(FX_FILEAVAIL* param,
657 size_t offset, size_t size) {
658 PDFiumEngine::FileAvail* file_avail =
659 static_cast<PDFiumEngine::FileAvail*>(param);
660 return file_avail->loader->IsDataAvailable(offset, size);
663 void PDFiumEngine::AddSegment(FX_DOWNLOADHINTS* param,
664 size_t offset, size_t size) {
665 PDFiumEngine::DownloadHints* download_hints =
666 static_cast<PDFiumEngine::DownloadHints*>(param);
667 return download_hints->loader->RequestData(offset, size);
670 bool PDFiumEngine::New(const char* url) {
672 headers_ = std::string();
676 bool PDFiumEngine::New(const char* url,
677 const char* headers) {
680 headers_ = std::string();
686 void PDFiumEngine::PageOffsetUpdated(const pp::Point& page_offset) {
687 page_offset_ = page_offset;
690 void PDFiumEngine::PluginSizeUpdated(const pp::Size& size) {
694 CalculateVisiblePages();
697 void PDFiumEngine::ScrolledToXPosition(int position) {
700 int old_x = position_.x();
701 position_.set_x(position);
702 CalculateVisiblePages();
703 client_->Scroll(pp::Point(old_x - position, 0));
706 void PDFiumEngine::ScrolledToYPosition(int position) {
709 int old_y = position_.y();
710 position_.set_y(position);
711 CalculateVisiblePages();
712 client_->Scroll(pp::Point(0, old_y - position));
715 void PDFiumEngine::PrePaint() {
716 for (size_t i = 0; i < progressive_paints_.size(); ++i)
717 progressive_paints_[i].painted_ = false;
720 void PDFiumEngine::Paint(const pp::Rect& rect,
721 pp::ImageData* image_data,
722 std::vector<pp::Rect>* ready,
723 std::vector<pp::Rect>* pending) {
724 pp::Rect leftover = rect;
725 for (size_t i = 0; i < visible_pages_.size(); ++i) {
726 int index = visible_pages_[i];
727 pp::Rect page_rect = pages_[index]->rect();
728 // Convert the current page's rectangle to screen rectangle. We do this
729 // instead of the reverse (converting the dirty rectangle from screen to
730 // page coordinates) because then we'd have to convert back to screen
731 // coordinates, and the rounding errors sometime leave pixels dirty or even
732 // move the text up or down a pixel when zoomed.
733 pp::Rect page_rect_in_screen = GetPageScreenRect(index);
734 pp::Rect dirty_in_screen = page_rect_in_screen.Intersect(leftover);
735 if (dirty_in_screen.IsEmpty())
738 leftover = leftover.Subtract(dirty_in_screen);
740 if (pages_[index]->available()) {
741 int progressive = GetProgressiveIndex(index);
742 if (progressive != -1 &&
743 progressive_paints_[progressive].rect != dirty_in_screen) {
744 // The PDFium code can only handle one progressive paint at a time, so
745 // queue this up. Previously we used to merge the rects when this
746 // happened, but it made scrolling up on complex PDFs very slow since
747 // there would be a damaged rect at the top (from scroll) and at the
748 // bottom (from toolbar).
749 pending->push_back(dirty_in_screen);
753 if (progressive == -1) {
754 progressive = StartPaint(index, dirty_in_screen);
755 progressive_paint_timeout_ = kMaxInitialProgressivePaintTimeMs;
757 progressive_paint_timeout_ = kMaxProgressivePaintTimeMs;
760 progressive_paints_[progressive].painted_ = true;
761 if (ContinuePaint(progressive, image_data)) {
762 FinishPaint(progressive, image_data);
763 ready->push_back(dirty_in_screen);
765 pending->push_back(dirty_in_screen);
768 PaintUnavailablePage(index, dirty_in_screen, image_data);
769 ready->push_back(dirty_in_screen);
774 void PDFiumEngine::PostPaint() {
775 for (size_t i = 0; i < progressive_paints_.size(); ++i) {
776 if (progressive_paints_[i].painted_)
779 // This rectangle must have been merged with another one, that's why we
780 // weren't asked to paint it. Remove it or otherwise we'll never finish
782 FPDF_RenderPage_Close(
783 pages_[progressive_paints_[i].page_index]->GetPage());
784 FPDFBitmap_Destroy(progressive_paints_[i].bitmap);
785 progressive_paints_.erase(progressive_paints_.begin() + i);
790 bool PDFiumEngine::HandleDocumentLoad(const pp::URLLoader& loader) {
791 password_tries_remaining_ = kMaxPasswordTries;
792 return doc_loader_.Init(loader, url_, headers_);
795 pp::Instance* PDFiumEngine::GetPluginInstance() {
796 return client_->GetPluginInstance();
799 pp::URLLoader PDFiumEngine::CreateURLLoader() {
800 return client_->CreateURLLoader();
803 void PDFiumEngine::AppendPage(PDFEngine* engine, int index) {
804 // Unload and delete the blank page before appending.
805 pages_[index]->Unload();
806 pages_[index]->set_calculated_links(false);
807 pp::Size curr_page_size = GetPageSize(index);
808 FPDFPage_Delete(doc_, index);
809 FPDF_ImportPages(doc_,
810 static_cast<PDFiumEngine*>(engine)->doc(),
813 pp::Size new_page_size = GetPageSize(index);
814 if (curr_page_size != new_page_size)
816 client_->Invalidate(GetPageScreenRect(index));
819 pp::Point PDFiumEngine::GetScrollPosition() {
823 void PDFiumEngine::SetScrollPosition(const pp::Point& position) {
824 position_ = position;
827 bool PDFiumEngine::IsProgressiveLoad() {
828 return doc_loader_.is_partial_document();
831 void PDFiumEngine::OnPartialDocumentLoaded() {
832 file_access_.m_FileLen = doc_loader_.document_size();
833 fpdf_availability_ = FPDFAvail_Create(&file_availability_, &file_access_);
834 DCHECK(fpdf_availability_);
836 // Currently engine does not deal efficiently with some non-linearized files.
837 // See http://code.google.com/p/chromium/issues/detail?id=59400
838 // To improve user experience we download entire file for non-linearized PDF.
839 if (!FPDFAvail_IsLinearized(fpdf_availability_)) {
840 doc_loader_.RequestData(0, doc_loader_.document_size());
847 void PDFiumEngine::OnPendingRequestComplete() {
848 if (!doc_ || !form_) {
853 // LoadDocument() will result in |pending_pages_| being reset so there's no
854 // need to run the code below in that case.
855 bool update_pages = false;
856 std::vector<int> still_pending;
857 for (size_t i = 0; i < pending_pages_.size(); ++i) {
858 if (CheckPageAvailable(pending_pages_[i], &still_pending)) {
860 if (IsPageVisible(pending_pages_[i]))
861 client_->Invalidate(GetPageScreenRect(pending_pages_[i]));
864 pending_pages_.swap(still_pending);
869 void PDFiumEngine::OnNewDataAvailable() {
870 client_->DocumentLoadProgress(doc_loader_.GetAvailableData(),
871 doc_loader_.document_size());
874 void PDFiumEngine::OnDocumentComplete() {
875 if (!doc_ || !form_) {
876 file_access_.m_FileLen = doc_loader_.document_size();
881 bool need_update = false;
882 for (size_t i = 0; i < pages_.size(); ++i) {
883 if (pages_[i]->available())
886 pages_[i]->set_available(true);
887 // We still need to call IsPageAvail() even if the whole document is
888 // already downloaded.
889 FPDFAvail_IsPageAvail(fpdf_availability_, i, &download_hints_);
891 if (IsPageVisible(i))
892 client_->Invalidate(GetPageScreenRect(i));
897 FinishLoadingDocument();
900 void PDFiumEngine::FinishLoadingDocument() {
901 DCHECK(doc_loader_.IsDocumentComplete() && doc_);
902 if (called_do_document_action_)
904 called_do_document_action_ = true;
906 // These can only be called now, as the JS might end up needing a page.
907 FORM_DoDocumentJSAction(form_);
908 FORM_DoDocumentOpenAction(form_);
909 if (most_visible_page_ != -1) {
910 FPDF_PAGE new_page = pages_[most_visible_page_]->GetPage();
911 FORM_DoPageAAction(new_page, form_, FPDFPAGE_AACTION_OPEN);
914 if (doc_) // This can only happen if loading |doc_| fails.
915 client_->DocumentLoadComplete(pages_.size());
918 void PDFiumEngine::UnsupportedFeature(int type) {
921 case FPDF_UNSP_DOC_XFAFORM:
924 case FPDF_UNSP_DOC_PORTABLECOLLECTION:
925 feature = "Portfolios_Packages";
927 case FPDF_UNSP_DOC_ATTACHMENT:
928 case FPDF_UNSP_ANNOT_ATTACHMENT:
929 feature = "Attachment";
931 case FPDF_UNSP_DOC_SECURITY:
932 feature = "Rights_Management";
934 case FPDF_UNSP_DOC_SHAREDREVIEW:
935 feature = "Shared_Review";
937 case FPDF_UNSP_DOC_SHAREDFORM_ACROBAT:
938 case FPDF_UNSP_DOC_SHAREDFORM_FILESYSTEM:
939 case FPDF_UNSP_DOC_SHAREDFORM_EMAIL:
940 feature = "Shared_Form";
942 case FPDF_UNSP_ANNOT_3DANNOT:
945 case FPDF_UNSP_ANNOT_MOVIE:
948 case FPDF_UNSP_ANNOT_SOUND:
951 case FPDF_UNSP_ANNOT_SCREEN_MEDIA:
952 case FPDF_UNSP_ANNOT_SCREEN_RICHMEDIA:
955 case FPDF_UNSP_ANNOT_SIG:
956 feature = "Digital_Signature";
959 client_->DocumentHasUnsupportedFeature(feature);
962 void PDFiumEngine::ContinueFind(int32_t result) {
963 StartFind(current_find_text_.c_str(), !!result);
966 bool PDFiumEngine::HandleEvent(const pp::InputEvent& event) {
967 DCHECK(!defer_page_unload_);
968 defer_page_unload_ = true;
970 switch (event.GetType()) {
971 case PP_INPUTEVENT_TYPE_MOUSEDOWN:
972 rv = OnMouseDown(pp::MouseInputEvent(event));
974 case PP_INPUTEVENT_TYPE_MOUSEUP:
975 rv = OnMouseUp(pp::MouseInputEvent(event));
977 case PP_INPUTEVENT_TYPE_MOUSEMOVE:
978 rv = OnMouseMove(pp::MouseInputEvent(event));
980 case PP_INPUTEVENT_TYPE_KEYDOWN:
981 rv = OnKeyDown(pp::KeyboardInputEvent(event));
983 case PP_INPUTEVENT_TYPE_KEYUP:
984 rv = OnKeyUp(pp::KeyboardInputEvent(event));
986 case PP_INPUTEVENT_TYPE_CHAR:
987 rv = OnChar(pp::KeyboardInputEvent(event));
993 DCHECK(defer_page_unload_);
994 defer_page_unload_ = false;
995 for (size_t i = 0; i < deferred_page_unloads_.size(); ++i)
996 pages_[deferred_page_unloads_[i]]->Unload();
997 deferred_page_unloads_.clear();
1001 uint32_t PDFiumEngine::QuerySupportedPrintOutputFormats() {
1002 if (!HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY))
1004 return PP_PRINTOUTPUTFORMAT_PDF;
1007 void PDFiumEngine::PrintBegin() {
1008 FORM_DoDocumentAAction(form_, FPDFDOC_AACTION_WP);
1011 pp::Resource PDFiumEngine::PrintPages(
1012 const PP_PrintPageNumberRange_Dev* page_ranges, uint32_t page_range_count,
1013 const PP_PrintSettings_Dev& print_settings) {
1014 if (HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY))
1015 return PrintPagesAsPDF(page_ranges, page_range_count, print_settings);
1016 else if (HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY))
1017 return PrintPagesAsRasterPDF(page_ranges, page_range_count, print_settings);
1018 return pp::Resource();
1021 FPDF_DOCUMENT PDFiumEngine::CreateSinglePageRasterPdf(
1022 double source_page_width,
1023 double source_page_height,
1024 const PP_PrintSettings_Dev& print_settings,
1025 PDFiumPage* page_to_print) {
1026 FPDF_DOCUMENT temp_doc = FPDF_CreateNewDocument();
1030 const pp::Size& bitmap_size(page_to_print->rect().size());
1032 FPDF_PAGE temp_page =
1033 FPDFPage_New(temp_doc, 0, source_page_width, source_page_height);
1035 pp::ImageData image = pp::ImageData(client_->GetPluginInstance(),
1036 PP_IMAGEDATAFORMAT_BGRA_PREMUL,
1040 FPDF_BITMAP bitmap = FPDFBitmap_CreateEx(bitmap_size.width(),
1041 bitmap_size.height(),
1047 FPDFBitmap_FillRect(
1048 bitmap, 0, 0, bitmap_size.width(), bitmap_size.height(), 0xFFFFFFFF);
1050 pp::Rect page_rect = page_to_print->rect();
1051 FPDF_RenderPageBitmap(bitmap,
1052 page_to_print->GetPrintPage(),
1057 print_settings.orientation,
1058 FPDF_ANNOT | FPDF_PRINTING | FPDF_NO_CATCH);
1060 double ratio_x = (static_cast<double>(bitmap_size.width()) * kPointsPerInch) /
1063 (static_cast<double>(bitmap_size.height()) * kPointsPerInch) /
1066 // Add the bitmap to an image object and add the image object to the output
1068 FPDF_PAGEOBJECT temp_img = FPDFPageObj_NewImgeObj(temp_doc);
1069 FPDFImageObj_SetBitmap(&temp_page, 1, temp_img, bitmap);
1070 FPDFImageObj_SetMatrix(temp_img, ratio_x, 0, 0, ratio_y, 0, 0);
1071 FPDFPage_InsertObject(temp_page, temp_img);
1072 FPDFPage_GenerateContent(temp_page);
1073 FPDF_ClosePage(temp_page);
1075 page_to_print->ClosePrintPage();
1076 FPDFBitmap_Destroy(bitmap);
1081 pp::Buffer_Dev PDFiumEngine::PrintPagesAsRasterPDF(
1082 const PP_PrintPageNumberRange_Dev* page_ranges, uint32_t page_range_count,
1083 const PP_PrintSettings_Dev& print_settings) {
1084 if (!page_range_count)
1085 return pp::Buffer_Dev();
1087 // If document is not downloaded yet, disable printing.
1088 if (doc_ && !doc_loader_.IsDocumentComplete())
1089 return pp::Buffer_Dev();
1091 FPDF_DOCUMENT output_doc = FPDF_CreateNewDocument();
1093 return pp::Buffer_Dev();
1095 SaveSelectedFormForPrint();
1097 std::vector<PDFiumPage> pages_to_print;
1098 // width and height of source PDF pages.
1099 std::vector<std::pair<double, double> > source_page_sizes;
1100 // Collect pages to print and sizes of source pages.
1101 std::vector<uint32_t> page_numbers =
1102 GetPageNumbersFromPrintPageNumberRange(page_ranges, page_range_count);
1103 for (size_t i = 0; i < page_numbers.size(); ++i) {
1104 uint32_t page_number = page_numbers[i];
1105 FPDF_PAGE pdf_page = FPDF_LoadPage(doc_, page_number);
1106 double source_page_width = FPDF_GetPageWidth(pdf_page);
1107 double source_page_height = FPDF_GetPageHeight(pdf_page);
1108 source_page_sizes.push_back(std::make_pair(source_page_width,
1109 source_page_height));
1111 int width_in_pixels = ConvertUnit(source_page_width,
1112 static_cast<int>(kPointsPerInch),
1113 print_settings.dpi);
1114 int height_in_pixels = ConvertUnit(source_page_height,
1115 static_cast<int>(kPointsPerInch),
1116 print_settings.dpi);
1118 pp::Rect rect(width_in_pixels, height_in_pixels);
1119 pages_to_print.push_back(PDFiumPage(this, page_number, rect, true));
1120 FPDF_ClosePage(pdf_page);
1123 #if defined(OS_LINUX)
1124 g_last_instance_id = client_->GetPluginInstance()->pp_instance();
1128 for (; i < pages_to_print.size(); ++i) {
1129 double source_page_width = source_page_sizes[i].first;
1130 double source_page_height = source_page_sizes[i].second;
1132 // Use temp_doc to compress image by saving PDF to buffer.
1133 FPDF_DOCUMENT temp_doc = CreateSinglePageRasterPdf(source_page_width,
1136 &pages_to_print[i]);
1141 pp::Buffer_Dev buffer = GetFlattenedPrintData(temp_doc);
1142 FPDF_CloseDocument(temp_doc);
1144 PDFiumMemBufferFileRead file_read(buffer.data(), buffer.size());
1145 temp_doc = FPDF_LoadCustomDocument(&file_read, NULL);
1147 FPDF_BOOL imported = FPDF_ImportPages(output_doc, temp_doc, "1", i);
1148 FPDF_CloseDocument(temp_doc);
1153 pp::Buffer_Dev buffer;
1154 if (i == pages_to_print.size()) {
1155 FPDF_CopyViewerPreferences(output_doc, doc_);
1156 FitContentsToPrintableAreaIfRequired(output_doc, print_settings);
1157 // Now flatten all the output pages.
1158 buffer = GetFlattenedPrintData(output_doc);
1160 FPDF_CloseDocument(output_doc);
1164 pp::Buffer_Dev PDFiumEngine::GetFlattenedPrintData(const FPDF_DOCUMENT& doc) {
1165 int page_count = FPDF_GetPageCount(doc);
1166 bool flatten_succeeded = true;
1167 for (int i = 0; i < page_count; ++i) {
1168 FPDF_PAGE page = FPDF_LoadPage(doc, i);
1171 int flatten_ret = FPDFPage_Flatten(page, FLAT_PRINT);
1172 FPDF_ClosePage(page);
1173 if (flatten_ret == FLATTEN_FAIL) {
1174 flatten_succeeded = false;
1178 flatten_succeeded = false;
1182 if (!flatten_succeeded) {
1183 FPDF_CloseDocument(doc);
1184 return pp::Buffer_Dev();
1187 pp::Buffer_Dev buffer;
1188 PDFiumMemBufferFileWrite output_file_write;
1189 if (FPDF_SaveAsCopy(doc, &output_file_write, 0)) {
1190 buffer = pp::Buffer_Dev(
1191 client_->GetPluginInstance(), output_file_write.size());
1192 if (!buffer.is_null()) {
1193 memcpy(buffer.data(), output_file_write.buffer().c_str(),
1194 output_file_write.size());
1200 pp::Buffer_Dev PDFiumEngine::PrintPagesAsPDF(
1201 const PP_PrintPageNumberRange_Dev* page_ranges, uint32_t page_range_count,
1202 const PP_PrintSettings_Dev& print_settings) {
1203 if (!page_range_count)
1204 return pp::Buffer_Dev();
1207 FPDF_DOCUMENT output_doc = FPDF_CreateNewDocument();
1209 return pp::Buffer_Dev();
1211 SaveSelectedFormForPrint();
1213 std::string page_number_str;
1214 for (uint32_t index = 0; index < page_range_count; ++index) {
1215 if (!page_number_str.empty())
1216 page_number_str.append(",");
1217 page_number_str.append(
1218 base::IntToString(page_ranges[index].first_page_number + 1));
1219 if (page_ranges[index].first_page_number !=
1220 page_ranges[index].last_page_number) {
1221 page_number_str.append("-");
1222 page_number_str.append(
1223 base::IntToString(page_ranges[index].last_page_number + 1));
1227 std::vector<uint32_t> page_numbers =
1228 GetPageNumbersFromPrintPageNumberRange(page_ranges, page_range_count);
1229 for (size_t i = 0; i < page_numbers.size(); ++i) {
1230 uint32_t page_number = page_numbers[i];
1231 pages_[page_number]->GetPage();
1232 if (!IsPageVisible(page_numbers[i]))
1233 pages_[page_number]->Unload();
1236 FPDF_CopyViewerPreferences(output_doc, doc_);
1237 if (!FPDF_ImportPages(output_doc, doc_, page_number_str.c_str(), 0)) {
1238 FPDF_CloseDocument(output_doc);
1239 return pp::Buffer_Dev();
1242 FitContentsToPrintableAreaIfRequired(output_doc, print_settings);
1244 // Now flatten all the output pages.
1245 pp::Buffer_Dev buffer = GetFlattenedPrintData(output_doc);
1246 FPDF_CloseDocument(output_doc);
1250 void PDFiumEngine::FitContentsToPrintableAreaIfRequired(
1251 const FPDF_DOCUMENT& doc, const PP_PrintSettings_Dev& print_settings) {
1252 // Check to see if we need to fit pdf contents to printer paper size.
1253 if (print_settings.print_scaling_option !=
1254 PP_PRINTSCALINGOPTION_SOURCE_SIZE) {
1255 int num_pages = FPDF_GetPageCount(doc);
1256 // In-place transformation is more efficient than creating a new
1257 // transformed document from the source document. Therefore, transform
1258 // every page to fit the contents in the selected printer paper.
1259 for (int i = 0; i < num_pages; ++i) {
1260 FPDF_PAGE page = FPDF_LoadPage(doc, i);
1261 TransformPDFPageForPrinting(page, print_settings);
1262 FPDF_ClosePage(page);
1267 void PDFiumEngine::SaveSelectedFormForPrint() {
1268 FORM_ForceToKillFocus(form_);
1269 client_->FormTextFieldFocusChange(false);
1272 void PDFiumEngine::PrintEnd() {
1273 FORM_DoDocumentAAction(form_, FPDFDOC_AACTION_DP);
1276 PDFiumPage::Area PDFiumEngine::GetCharIndex(
1277 const pp::MouseInputEvent& event, int* page_index,
1278 int* char_index, PDFiumPage::LinkTarget* target) {
1279 // First figure out which page this is in.
1280 pp::Point mouse_point = event.GetPosition();
1282 static_cast<int>((mouse_point.x() + position_.x()) / current_zoom_),
1283 static_cast<int>((mouse_point.y() + position_.y()) / current_zoom_));
1284 return GetCharIndex(point, page_index, char_index, target);
1287 PDFiumPage::Area PDFiumEngine::GetCharIndex(
1288 const pp::Point& point,
1291 PDFiumPage::LinkTarget* target) {
1293 for (size_t i = 0; i < visible_pages_.size(); ++i) {
1294 if (pages_[visible_pages_[i]]->rect().Contains(point)) {
1295 page = visible_pages_[i];
1300 return PDFiumPage::NONSELECTABLE_AREA;
1302 // If the page hasn't finished rendering, calling into the page sometimes
1304 for (size_t i = 0; i < progressive_paints_.size(); ++i) {
1305 if (progressive_paints_[i].page_index == page)
1306 return PDFiumPage::NONSELECTABLE_AREA;
1310 return pages_[page]->GetCharIndex(point, current_rotation_, char_index,
1314 bool PDFiumEngine::OnMouseDown(const pp::MouseInputEvent& event) {
1315 if (event.GetButton() != PP_INPUTEVENT_MOUSEBUTTON_LEFT)
1318 SelectionChangeInvalidator selection_invalidator(this);
1321 int page_index = -1;
1322 int char_index = -1;
1323 PDFiumPage::LinkTarget target;
1324 PDFiumPage::Area area = GetCharIndex(event, &page_index,
1325 &char_index, &target);
1326 mouse_down_state_.Set(area, target);
1328 // Decide whether to open link or not based on user action in mouse up and
1329 // mouse move events.
1330 if (area == PDFiumPage::WEBLINK_AREA)
1333 if (area == PDFiumPage::DOCLINK_AREA) {
1334 client_->ScrollToPage(target.page);
1335 client_->FormTextFieldFocusChange(false);
1339 if (page_index != -1) {
1340 last_page_mouse_down_ = page_index;
1341 double page_x, page_y;
1342 pp::Point point = event.GetPosition();
1343 DeviceToPage(page_index, point.x(), point.y(), &page_x, &page_y);
1345 FORM_OnLButtonDown(form_, pages_[page_index]->GetPage(), 0, page_x, page_y);
1346 int control = FPDPage_HasFormFieldAtPoint(
1347 form_, pages_[page_index]->GetPage(), page_x, page_y);
1348 if (control > FPDF_FORMFIELD_UNKNOWN) { // returns -1 sometimes...
1349 client_->FormTextFieldFocusChange(control == FPDF_FORMFIELD_TEXTFIELD ||
1350 control == FPDF_FORMFIELD_COMBOBOX);
1351 return true; // Return now before we get into the selection code.
1355 client_->FormTextFieldFocusChange(false);
1357 if (area != PDFiumPage::TEXT_AREA)
1358 return true; // Return true so WebKit doesn't do its own highlighting.
1360 if (event.GetClickCount() == 1) {
1361 OnSingleClick(page_index, char_index);
1362 } else if (event.GetClickCount() == 2 ||
1363 event.GetClickCount() == 3) {
1364 OnMultipleClick(event.GetClickCount(), page_index, char_index);
1370 void PDFiumEngine::OnSingleClick(int page_index, int char_index) {
1372 selection_.push_back(PDFiumRange(pages_[page_index], char_index, 0));
1375 void PDFiumEngine::OnMultipleClick(int click_count,
1378 // It would be more efficient if the SDK could support finding a space, but
1380 int start_index = char_index;
1382 base::char16 cur = pages_[page_index]->GetCharAtIndex(start_index);
1383 // For double click, we want to select one word so we look for whitespace
1384 // boundaries. For triple click, we want the whole line.
1385 if (cur == '\n' || (click_count == 2 && (cur == ' ' || cur == '\t')))
1387 } while (--start_index >= 0);
1391 int end_index = char_index;
1392 int total = pages_[page_index]->GetCharCount();
1393 while (end_index++ <= total) {
1394 base::char16 cur = pages_[page_index]->GetCharAtIndex(end_index);
1395 if (cur == '\n' || (click_count == 2 && (cur == ' ' || cur == '\t')))
1399 selection_.push_back(PDFiumRange(
1400 pages_[page_index], start_index, end_index - start_index));
1403 bool PDFiumEngine::OnMouseUp(const pp::MouseInputEvent& event) {
1404 if (event.GetButton() != PP_INPUTEVENT_MOUSEBUTTON_LEFT)
1407 int page_index = -1;
1408 int char_index = -1;
1409 PDFiumPage::LinkTarget target;
1410 PDFiumPage::Area area =
1411 GetCharIndex(event, &page_index, &char_index, &target);
1413 // Open link on mouse up for same link for which mouse down happened earlier.
1414 if (mouse_down_state_.Matches(area, target)) {
1415 if (area == PDFiumPage::WEBLINK_AREA) {
1416 bool open_in_new_tab = !!(event.GetModifiers() & kDefaultKeyModifier);
1417 client_->NavigateTo(target.url, open_in_new_tab);
1418 client_->FormTextFieldFocusChange(false);
1423 if (page_index != -1) {
1424 double page_x, page_y;
1425 pp::Point point = event.GetPosition();
1426 DeviceToPage(page_index, point.x(), point.y(), &page_x, &page_y);
1428 form_, pages_[page_index]->GetPage(), 0, page_x, page_y);
1438 bool PDFiumEngine::OnMouseMove(const pp::MouseInputEvent& event) {
1439 int page_index = -1;
1440 int char_index = -1;
1441 PDFiumPage::LinkTarget target;
1442 PDFiumPage::Area area =
1443 GetCharIndex(event, &page_index, &char_index, &target);
1445 // Clear |mouse_down_state_| if mouse moves away from where the mouse down
1447 if (!mouse_down_state_.Matches(area, target))
1448 mouse_down_state_.Reset();
1451 PP_CursorType_Dev cursor;
1453 case PDFiumPage::TEXT_AREA:
1454 cursor = PP_CURSORTYPE_IBEAM;
1456 case PDFiumPage::WEBLINK_AREA:
1457 case PDFiumPage::DOCLINK_AREA:
1458 cursor = PP_CURSORTYPE_HAND;
1460 case PDFiumPage::NONSELECTABLE_AREA:
1462 cursor = PP_CURSORTYPE_POINTER;
1466 if (page_index != -1) {
1467 double page_x, page_y;
1468 pp::Point point = event.GetPosition();
1469 DeviceToPage(page_index, point.x(), point.y(), &page_x, &page_y);
1471 FORM_OnMouseMove(form_, pages_[page_index]->GetPage(), 0, page_x, page_y);
1472 int control = FPDPage_HasFormFieldAtPoint(
1473 form_, pages_[page_index]->GetPage(), page_x, page_y);
1475 case FPDF_FORMFIELD_PUSHBUTTON:
1476 case FPDF_FORMFIELD_CHECKBOX:
1477 case FPDF_FORMFIELD_RADIOBUTTON:
1478 case FPDF_FORMFIELD_COMBOBOX:
1479 case FPDF_FORMFIELD_LISTBOX:
1480 cursor = PP_CURSORTYPE_HAND;
1482 case FPDF_FORMFIELD_TEXTFIELD:
1483 cursor = PP_CURSORTYPE_IBEAM;
1490 client_->UpdateCursor(cursor);
1491 pp::Point point = event.GetPosition();
1492 std::string url = GetLinkAtPosition(event.GetPosition());
1493 if (url != link_under_cursor_) {
1494 link_under_cursor_ = url;
1495 pp::PDF::SetLinkUnderCursor(GetPluginInstance(), url.c_str());
1497 // No need to swallow the event, since this might interfere with the
1498 // scrollbars if the user is dragging them.
1502 // We're selecting but right now we're not over text, so don't change the
1503 // current selection.
1504 if (area != PDFiumPage::TEXT_AREA && area != PDFiumPage::WEBLINK_AREA &&
1505 area != PDFiumPage::DOCLINK_AREA) {
1509 SelectionChangeInvalidator selection_invalidator(this);
1511 // Check if the user has descreased their selection area and we need to remove
1512 // pages from selection_.
1513 for (size_t i = 0; i < selection_.size(); ++i) {
1514 if (selection_[i].page_index() == page_index) {
1515 // There should be no other pages after this.
1516 selection_.erase(selection_.begin() + i + 1, selection_.end());
1521 if (selection_.size() == 0)
1524 int last = selection_.size() - 1;
1525 if (selection_[last].page_index() == page_index) {
1526 // Selecting within a page.
1528 if (char_index >= selection_[last].char_index()) {
1529 // Selecting forward.
1530 count = char_index - selection_[last].char_index() + 1;
1532 count = char_index - selection_[last].char_index() - 1;
1534 selection_[last].SetCharCount(count);
1535 } else if (selection_[last].page_index() < page_index) {
1536 // Selecting into the next page.
1538 // First make sure that there are no gaps in selection, i.e. if mousedown on
1539 // page one but we only get mousemove over page three, we want page two.
1540 for (int i = selection_[last].page_index() + 1; i < page_index; ++i) {
1541 selection_.push_back(PDFiumRange(pages_[i], 0,
1542 pages_[i]->GetCharCount()));
1545 int count = pages_[selection_[last].page_index()]->GetCharCount();
1546 selection_[last].SetCharCount(count - selection_[last].char_index());
1547 selection_.push_back(PDFiumRange(pages_[page_index], 0, char_index));
1549 // Selecting into the previous page.
1550 selection_[last].SetCharCount(-selection_[last].char_index());
1552 // First make sure that there are no gaps in selection, i.e. if mousedown on
1553 // page three but we only get mousemove over page one, we want page two.
1554 for (int i = selection_[last].page_index() - 1; i > page_index; --i) {
1555 selection_.push_back(PDFiumRange(pages_[i], 0,
1556 pages_[i]->GetCharCount()));
1559 int count = pages_[page_index]->GetCharCount();
1560 selection_.push_back(
1561 PDFiumRange(pages_[page_index], count, count - char_index));
1567 bool PDFiumEngine::OnKeyDown(const pp::KeyboardInputEvent& event) {
1568 if (last_page_mouse_down_ == -1)
1571 bool rv = !!FORM_OnKeyDown(
1572 form_, pages_[last_page_mouse_down_]->GetPage(),
1573 event.GetKeyCode(), event.GetModifiers());
1575 if (event.GetKeyCode() == ui::VKEY_BACK ||
1576 event.GetKeyCode() == ui::VKEY_ESCAPE) {
1577 // Chrome doesn't send char events for backspace or escape keys, see
1578 // PlatformKeyboardEventBuilder::isCharacterKey() and
1579 // http://chrome-corpsvn.mtv.corp.google.com/viewvc?view=rev&root=chrome&revision=31805
1580 // for more information. So just fake one since PDFium uses it.
1582 str.push_back(event.GetKeyCode());
1583 pp::KeyboardInputEvent synthesized(pp::KeyboardInputEvent(
1584 client_->GetPluginInstance(),
1585 PP_INPUTEVENT_TYPE_CHAR,
1586 event.GetTimeStamp(),
1587 event.GetModifiers(),
1590 OnChar(synthesized);
1596 bool PDFiumEngine::OnKeyUp(const pp::KeyboardInputEvent& event) {
1597 if (last_page_mouse_down_ == -1)
1600 return !!FORM_OnKeyUp(
1601 form_, pages_[last_page_mouse_down_]->GetPage(),
1602 event.GetKeyCode(), event.GetModifiers());
1605 bool PDFiumEngine::OnChar(const pp::KeyboardInputEvent& event) {
1606 if (last_page_mouse_down_ == -1)
1609 base::string16 str = base::UTF8ToUTF16(event.GetCharacterText().AsString());
1610 return !!FORM_OnChar(
1611 form_, pages_[last_page_mouse_down_]->GetPage(),
1613 event.GetModifiers());
1616 void PDFiumEngine::StartFind(const char* text, bool case_sensitive) {
1617 // We can get a call to StartFind before we have any page information (i.e.
1618 // before the first call to LoadDocument has happened). Handle this case.
1622 bool first_search = false;
1623 int character_to_start_searching_from = 0;
1624 if (current_find_text_ != text) { // First time we search for this text.
1625 first_search = true;
1626 std::vector<PDFiumRange> old_selection = selection_;
1628 current_find_text_ = text;
1630 if (old_selection.empty()) {
1631 // Start searching from the beginning of the document.
1632 next_page_to_search_ = 0;
1633 last_page_to_search_ = pages_.size() - 1;
1634 last_character_index_to_search_ = -1;
1636 // There's a current selection, so start from it.
1637 next_page_to_search_ = old_selection[0].page_index();
1638 last_character_index_to_search_ = old_selection[0].char_index();
1639 character_to_start_searching_from = old_selection[0].char_index();
1640 last_page_to_search_ = next_page_to_search_;
1644 int current_page = next_page_to_search_;
1646 if (pages_[current_page]->available()) {
1647 base::string16 str = base::UTF8ToUTF16(text);
1648 // Don't use PDFium to search for now, since it doesn't support unicode text.
1649 // Leave the code for now to avoid bit-rot, in case it's fixed later.
1652 str, case_sensitive, first_search, character_to_start_searching_from,
1656 str, case_sensitive, first_search, character_to_start_searching_from,
1660 if (!IsPageVisible(current_page))
1661 pages_[current_page]->Unload();
1664 if (next_page_to_search_ != last_page_to_search_ ||
1665 (first_search && last_character_index_to_search_ != -1)) {
1666 ++next_page_to_search_;
1669 if (next_page_to_search_ == static_cast<int>(pages_.size()))
1670 next_page_to_search_ = 0;
1671 // If there's only one page in the document and we start searching midway,
1672 // then we'll want to search the page one more time.
1673 bool end_of_search =
1674 next_page_to_search_ == last_page_to_search_ &&
1675 // Only one page but didn't start midway.
1676 ((pages_.size() == 1 && last_character_index_to_search_ == -1) ||
1677 // Started midway, but only 1 page and we already looped around.
1678 (pages_.size() == 1 && !first_search) ||
1679 // Started midway, and we've just looped around.
1680 (pages_.size() > 1 && current_page == next_page_to_search_));
1682 if (end_of_search) {
1683 // Send the final notification.
1684 client_->NotifyNumberOfFindResultsChanged(find_results_.size(), true);
1686 // When searching is complete, resume finding at a particular index.
1687 // Assuming the user has not clicked the find button in the meanwhile.
1688 if (resume_find_index_.valid() && !current_find_index_.valid()) {
1689 size_t resume_index = resume_find_index_.GetIndex();
1690 if (resume_index >= find_results_.size()) {
1691 // This might happen if the PDF has some dynamically generated text?
1694 current_find_index_.SetIndex(resume_index);
1695 client_->NotifySelectedFindResultChanged(resume_index);
1697 resume_find_index_.Invalidate();
1699 pp::CompletionCallback callback =
1700 find_factory_.NewCallback(&PDFiumEngine::ContinueFind);
1701 pp::Module::Get()->core()->CallOnMainThread(
1702 0, callback, case_sensitive ? 1 : 0);
1706 void PDFiumEngine::SearchUsingPDFium(const base::string16& term,
1707 bool case_sensitive,
1709 int character_to_start_searching_from,
1711 // Find all the matches in the current page.
1712 unsigned long flags = case_sensitive ? FPDF_MATCHCASE : 0;
1713 FPDF_SCHHANDLE find = FPDFText_FindStart(
1714 pages_[current_page]->GetTextPage(),
1715 reinterpret_cast<const unsigned short*>(term.c_str()),
1716 flags, character_to_start_searching_from);
1718 // Note: since we search one page at a time, we don't find matches across
1719 // page boundaries. We could do this manually ourself, but it seems low
1720 // priority since Reader itself doesn't do it.
1721 while (FPDFText_FindNext(find)) {
1722 PDFiumRange result(pages_[current_page],
1723 FPDFText_GetSchResultIndex(find),
1724 FPDFText_GetSchCount(find));
1726 if (!first_search &&
1727 last_character_index_to_search_ != -1 &&
1728 result.page_index() == last_page_to_search_ &&
1729 result.char_index() >= last_character_index_to_search_) {
1733 AddFindResult(result);
1736 FPDFText_FindClose(find);
1739 void PDFiumEngine::SearchUsingICU(const base::string16& term,
1740 bool case_sensitive,
1742 int character_to_start_searching_from,
1744 base::string16 page_text;
1745 int text_length = pages_[current_page]->GetCharCount();
1746 if (character_to_start_searching_from) {
1747 text_length -= character_to_start_searching_from;
1748 } else if (!first_search &&
1749 last_character_index_to_search_ != -1 &&
1750 current_page == last_page_to_search_) {
1751 text_length = last_character_index_to_search_;
1753 if (text_length <= 0)
1755 unsigned short* data =
1756 reinterpret_cast<unsigned short*>(WriteInto(&page_text, text_length + 1));
1757 FPDFText_GetText(pages_[current_page]->GetTextPage(),
1758 character_to_start_searching_from,
1761 std::vector<PDFEngine::Client::SearchStringResult> results;
1762 client_->SearchString(
1763 page_text.c_str(), term.c_str(), case_sensitive, &results);
1764 for (size_t i = 0; i < results.size(); ++i) {
1765 // Need to map the indexes from the page text, which may have generated
1766 // characters like space etc, to character indices from the page.
1767 int temp_start = results[i].start_index + character_to_start_searching_from;
1768 int start = FPDFText_GetCharIndexFromTextIndex(
1769 pages_[current_page]->GetTextPage(), temp_start);
1770 int end = FPDFText_GetCharIndexFromTextIndex(
1771 pages_[current_page]->GetTextPage(),
1772 temp_start + results[i].length);
1773 AddFindResult(PDFiumRange(pages_[current_page], start, end - start));
1777 void PDFiumEngine::AddFindResult(const PDFiumRange& result) {
1778 // Figure out where to insert the new location, since we could have
1779 // started searching midway and now we wrapped.
1780 size_t result_index;
1781 int page_index = result.page_index();
1782 int char_index = result.char_index();
1783 for (result_index = 0; result_index < find_results_.size(); ++result_index) {
1784 if (find_results_[result_index].page_index() > page_index ||
1785 (find_results_[result_index].page_index() == page_index &&
1786 find_results_[result_index].char_index() > char_index)) {
1790 find_results_.insert(find_results_.begin() + result_index, result);
1793 if (current_find_index_.valid()) {
1794 if (result_index <= current_find_index_.GetIndex()) {
1795 // Update the current match index
1796 size_t find_index = current_find_index_.IncrementIndex();
1797 DCHECK_LT(find_index, find_results_.size());
1798 client_->NotifySelectedFindResultChanged(current_find_index_.GetIndex());
1800 } else if (!resume_find_index_.valid()) {
1801 // Both indices are invalid. Select the first match.
1802 SelectFindResult(true);
1804 client_->NotifyNumberOfFindResultsChanged(find_results_.size(), false);
1807 bool PDFiumEngine::SelectFindResult(bool forward) {
1808 if (find_results_.empty()) {
1813 SelectionChangeInvalidator selection_invalidator(this);
1815 // Move back/forward through the search locations we previously found.
1817 const size_t last_index = find_results_.size() - 1;
1818 if (current_find_index_.valid()) {
1819 size_t current_index = current_find_index_.GetIndex();
1821 new_index = (current_index >= last_index) ? 0 : current_index + 1;
1823 new_index = (current_find_index_.GetIndex() == 0) ?
1824 last_index : current_index - 1;
1827 new_index = forward ? 0 : last_index;
1829 current_find_index_.SetIndex(new_index);
1831 // Update the selection before telling the client to scroll, since it could
1834 selection_.push_back(find_results_[current_find_index_.GetIndex()]);
1836 // If the result is not in view, scroll to it.
1837 pp::Rect bounding_rect;
1838 pp::Rect visible_rect = GetVisibleRect();
1839 // Use zoom of 1.0 since visible_rect is without zoom.
1840 std::vector<pp::Rect> rects;
1841 rects = find_results_[current_find_index_.GetIndex()].GetScreenRects(
1842 pp::Point(), 1.0, current_rotation_);
1843 for (size_t i = 0; i < rects.size(); ++i)
1844 bounding_rect = bounding_rect.Union(rects[i]);
1845 if (!visible_rect.Contains(bounding_rect)) {
1846 pp::Point center = bounding_rect.CenterPoint();
1847 // Make the page centered.
1848 int new_y = static_cast<int>(center.y() * current_zoom_) -
1849 static_cast<int>(visible_rect.height() * current_zoom_ / 2);
1852 client_->ScrollToY(new_y);
1854 // Only move horizontally if it's not visible.
1855 if (center.x() < visible_rect.x() || center.x() > visible_rect.right()) {
1856 int new_x = static_cast<int>(center.x() * current_zoom_) -
1857 static_cast<int>(visible_rect.width() * current_zoom_ / 2);
1860 client_->ScrollToX(new_x);
1864 client_->NotifySelectedFindResultChanged(current_find_index_.GetIndex());
1868 void PDFiumEngine::StopFind() {
1869 SelectionChangeInvalidator selection_invalidator(this);
1873 find_results_.clear();
1874 next_page_to_search_ = -1;
1875 last_page_to_search_ = -1;
1876 last_character_index_to_search_ = -1;
1877 current_find_index_.Invalidate();
1878 current_find_text_.clear();
1880 find_factory_.CancelAll();
1883 void PDFiumEngine::UpdateTickMarks() {
1884 std::vector<pp::Rect> tickmarks;
1885 for (size_t i = 0; i < find_results_.size(); ++i) {
1887 // Always use an origin of 0,0 since scroll positions don't affect tickmark.
1888 std::vector<pp::Rect> rects = find_results_[i].GetScreenRects(
1889 pp::Point(0, 0), current_zoom_, current_rotation_);
1890 for (size_t j = 0; j < rects.size(); ++j)
1891 rect = rect.Union(rects[j]);
1892 tickmarks.push_back(rect);
1895 client_->UpdateTickMarks(tickmarks);
1898 void PDFiumEngine::ZoomUpdated(double new_zoom_level) {
1901 current_zoom_ = new_zoom_level;
1903 CalculateVisiblePages();
1907 void PDFiumEngine::RotateClockwise() {
1908 current_rotation_ = (current_rotation_ + 1) % 4;
1912 void PDFiumEngine::RotateCounterclockwise() {
1913 current_rotation_ = (current_rotation_ - 1) % 4;
1917 void PDFiumEngine::InvalidateAllPages() {
1921 client_->Invalidate(pp::Rect(plugin_size_));
1924 std::string PDFiumEngine::GetSelectedText() {
1925 base::string16 result;
1926 for (size_t i = 0; i < selection_.size(); ++i) {
1928 selection_[i - 1].page_index() > selection_[i].page_index()) {
1929 result = selection_[i].GetText() + result;
1931 result.append(selection_[i].GetText());
1935 FormatStringWithHyphens(&result);
1936 FormatStringForOS(&result);
1937 return base::UTF16ToUTF8(result);
1940 std::string PDFiumEngine::GetLinkAtPosition(const pp::Point& point) {
1942 PDFiumPage::LinkTarget target;
1943 pp::Point point_in_page(
1944 static_cast<int>((point.x() + position_.x()) / current_zoom_),
1945 static_cast<int>((point.y() + position_.y()) / current_zoom_));
1946 PDFiumPage::Area area = GetCharIndex(point_in_page, &temp, &temp, &target);
1947 if (area == PDFiumPage::WEBLINK_AREA)
1949 return std::string();
1952 bool PDFiumEngine::IsSelecting() {
1956 bool PDFiumEngine::HasPermission(DocumentPermission permission) const {
1957 switch (permission) {
1958 case PERMISSION_COPY:
1959 return (permissions_ & kPDFPermissionCopyMask) != 0;
1960 case PERMISSION_COPY_ACCESSIBLE:
1961 return (permissions_ & kPDFPermissionCopyAccessibleMask) != 0;
1962 case PERMISSION_PRINT_LOW_QUALITY:
1963 return (permissions_ & kPDFPermissionPrintLowQualityMask) != 0;
1964 case PERMISSION_PRINT_HIGH_QUALITY:
1965 return (permissions_ & kPDFPermissionPrintLowQualityMask) != 0 &&
1966 (permissions_ & kPDFPermissionPrintHighQualityMask) != 0;
1972 void PDFiumEngine::SelectAll() {
1973 SelectionChangeInvalidator selection_invalidator(this);
1976 for (size_t i = 0; i < pages_.size(); ++i)
1977 if (pages_[i]->available()) {
1978 selection_.push_back(PDFiumRange(pages_[i], 0,
1979 pages_[i]->GetCharCount()));
1983 int PDFiumEngine::GetNumberOfPages() {
1984 return pages_.size();
1987 int PDFiumEngine::GetNamedDestinationPage(const std::string& destination) {
1988 // Look for the destination.
1989 FPDF_DEST dest = FPDF_GetNamedDestByName(doc_, destination.c_str());
1991 // Look for a bookmark with the same name.
1992 base::string16 destination_wide = base::UTF8ToUTF16(destination);
1993 FPDF_WIDESTRING destination_pdf_wide =
1994 reinterpret_cast<FPDF_WIDESTRING>(destination_wide.c_str());
1995 FPDF_BOOKMARK bookmark = FPDFBookmark_Find(doc_, destination_pdf_wide);
1998 dest = FPDFBookmark_GetDest(doc_, bookmark);
2000 return dest ? FPDFDest_GetPageIndex(doc_, dest) : -1;
2003 int PDFiumEngine::GetFirstVisiblePage() {
2004 CalculateVisiblePages();
2005 return first_visible_page_;
2008 int PDFiumEngine::GetMostVisiblePage() {
2009 CalculateVisiblePages();
2010 return most_visible_page_;
2013 pp::Rect PDFiumEngine::GetPageRect(int index) {
2014 pp::Rect rc(pages_[index]->rect());
2015 rc.Inset(-kPageShadowLeft, -kPageShadowTop,
2016 -kPageShadowRight, -kPageShadowBottom);
2020 pp::Rect PDFiumEngine::GetPageContentsRect(int index) {
2021 return GetScreenRect(pages_[index]->rect());
2024 void PDFiumEngine::PaintThumbnail(pp::ImageData* image_data, int index) {
2025 FPDF_BITMAP bitmap = FPDFBitmap_CreateEx(
2026 image_data->size().width(), image_data->size().height(),
2027 FPDFBitmap_BGRx, image_data->data(), image_data->stride());
2029 if (pages_[index]->available()) {
2030 FPDFBitmap_FillRect(bitmap, 0, 0, image_data->size().width(),
2031 image_data->size().height(), 0xFFFFFFFF);
2033 FPDF_RenderPageBitmap(
2034 bitmap, pages_[index]->GetPage(), 0, 0, image_data->size().width(),
2035 image_data->size().height(), 0, GetRenderingFlags());
2037 FPDFBitmap_FillRect(bitmap, 0, 0, image_data->size().width(),
2038 image_data->size().height(), kPendingPageColor);
2041 FPDFBitmap_Destroy(bitmap);
2044 void PDFiumEngine::SetGrayscale(bool grayscale) {
2045 render_grayscale_ = grayscale;
2048 void PDFiumEngine::OnCallback(int id) {
2049 if (!timers_.count(id))
2052 timers_[id].second(id);
2053 if (timers_.count(id)) // The callback might delete the timer.
2054 client_->ScheduleCallback(id, timers_[id].first);
2057 std::string PDFiumEngine::GetPageAsJSON(int index) {
2058 if (!(HasPermission(PERMISSION_COPY) ||
2059 HasPermission(PERMISSION_COPY_ACCESSIBLE))) {
2063 if (index < 0 || static_cast<size_t>(index) > pages_.size() - 1)
2066 scoped_ptr<base::Value> node(
2067 pages_[index]->GetAccessibleContentAsValue(current_rotation_));
2068 std::string page_json;
2069 base::JSONWriter::Write(node.get(), &page_json);
2073 bool PDFiumEngine::GetPrintScaling() {
2074 return !!FPDF_VIEWERREF_GetPrintScaling(doc_);
2077 void PDFiumEngine::AppendBlankPages(int num_pages) {
2078 DCHECK(num_pages != 0);
2084 pending_pages_.clear();
2086 // Delete all pages except the first one.
2087 while (pages_.size() > 1) {
2088 delete pages_.back();
2090 FPDFPage_Delete(doc_, pages_.size());
2093 // Calculate document size and all page sizes.
2094 std::vector<pp::Rect> page_rects;
2095 pp::Size page_size = GetPageSize(0);
2096 page_size.Enlarge(kPageShadowLeft + kPageShadowRight,
2097 kPageShadowTop + kPageShadowBottom);
2098 pp::Size old_document_size = document_size_;
2099 document_size_ = pp::Size(page_size.width(), 0);
2100 for (int i = 0; i < num_pages; ++i) {
2102 // Add space for horizontal separator.
2103 document_size_.Enlarge(0, kPageSeparatorThickness);
2106 pp::Rect rect(pp::Point(0, document_size_.height()), page_size);
2107 page_rects.push_back(rect);
2109 document_size_.Enlarge(0, page_size.height());
2112 // Create blank pages.
2113 for (int i = 1; i < num_pages; ++i) {
2114 pp::Rect page_rect(page_rects[i]);
2115 page_rect.Inset(kPageShadowLeft, kPageShadowTop,
2116 kPageShadowRight, kPageShadowBottom);
2117 double width_in_points =
2118 page_rect.width() * kPointsPerInch / kPixelsPerInch;
2119 double height_in_points =
2120 page_rect.height() * kPointsPerInch / kPixelsPerInch;
2121 FPDFPage_New(doc_, i, width_in_points, height_in_points);
2122 pages_.push_back(new PDFiumPage(this, i, page_rect, true));
2125 CalculateVisiblePages();
2126 if (document_size_ != old_document_size)
2127 client_->DocumentSizeUpdated(document_size_);
2130 void PDFiumEngine::LoadDocument() {
2131 // Check if the document is ready for loading. If it isn't just bail for now,
2132 // we will call LoadDocument() again later.
2133 if (!doc_ && !doc_loader_.IsDocumentComplete() &&
2134 !FPDFAvail_IsDocAvail(fpdf_availability_, &download_hints_)) {
2138 // If we're in the middle of getting a password, just return. We will retry
2139 // loading the document after we get the password anyway.
2140 if (getting_password_)
2143 ScopedUnsupportedFeature scoped_unsupported_feature(this);
2144 bool needs_password = false;
2145 if (TryLoadingDoc(false, std::string(), &needs_password)) {
2146 ContinueLoadingDocument(false, std::string());
2150 GetPasswordAndLoad();
2152 client_->DocumentLoadFailed();
2155 bool PDFiumEngine::TryLoadingDoc(bool with_password,
2156 const std::string& password,
2157 bool* needs_password) {
2158 *needs_password = false;
2162 const char* password_cstr = NULL;
2163 if (with_password) {
2164 password_cstr = password.c_str();
2165 password_tries_remaining_--;
2167 if (doc_loader_.IsDocumentComplete())
2168 doc_ = FPDF_LoadCustomDocument(&file_access_, password_cstr);
2170 doc_ = FPDFAvail_GetDocument(fpdf_availability_, password_cstr);
2172 if (!doc_ && FPDF_GetLastError() == FPDF_ERR_PASSWORD)
2173 *needs_password = true;
2175 return doc_ != NULL;
2178 void PDFiumEngine::GetPasswordAndLoad() {
2179 getting_password_ = true;
2180 DCHECK(!doc_ && FPDF_GetLastError() == FPDF_ERR_PASSWORD);
2181 client_->GetDocumentPassword(password_factory_.NewCallbackWithOutput(
2182 &PDFiumEngine::OnGetPasswordComplete));
2185 void PDFiumEngine::OnGetPasswordComplete(int32_t result,
2186 const pp::Var& password) {
2187 getting_password_ = false;
2189 bool password_given = false;
2190 std::string password_text;
2191 if (result == PP_OK && password.is_string()) {
2192 password_text = password.AsString();
2193 if (!password_text.empty())
2194 password_given = true;
2196 ContinueLoadingDocument(password_given, password_text);
2199 void PDFiumEngine::ContinueLoadingDocument(
2201 const std::string& password) {
2202 ScopedUnsupportedFeature scoped_unsupported_feature(this);
2204 bool needs_password = false;
2205 bool loaded = TryLoadingDoc(has_password, password, &needs_password);
2206 bool password_incorrect = !loaded && has_password && needs_password;
2207 if (password_incorrect && password_tries_remaining_ > 0) {
2208 GetPasswordAndLoad();
2213 client_->DocumentLoadFailed();
2217 if (FPDFDoc_GetPageMode(doc_) == PAGEMODE_USEOUTLINES)
2218 client_->DocumentHasUnsupportedFeature("Bookmarks");
2220 permissions_ = FPDF_GetDocPermissions(doc_);
2223 // Only returns 0 when data isn't available. If form data is downloaded, or
2224 // if this isn't a form, returns positive values.
2225 if (!doc_loader_.IsDocumentComplete() &&
2226 !FPDFAvail_IsFormAvail(fpdf_availability_, &download_hints_)) {
2230 form_ = FPDFDOC_InitFormFillEnviroument(
2231 doc_, static_cast<FPDF_FORMFILLINFO*>(this));
2232 FPDF_SetFormFieldHighlightColor(form_, 0, kFormHighlightColor);
2233 FPDF_SetFormFieldHighlightAlpha(form_, kFormHighlightAlpha);
2236 if (!doc_loader_.IsDocumentComplete()) {
2237 // Check if the first page is available. In a linearized PDF, that is not
2238 // always page 0. Doing this gives us the default page size, since when the
2239 // document is available, the first page is available as well.
2240 CheckPageAvailable(FPDFAvail_GetFirstPageNum(doc_), &pending_pages_);
2243 LoadPageInfo(false);
2245 if (doc_loader_.IsDocumentComplete())
2246 FinishLoadingDocument();
2249 void PDFiumEngine::LoadPageInfo(bool reload) {
2250 pending_pages_.clear();
2251 pp::Size old_document_size = document_size_;
2252 document_size_ = pp::Size();
2253 std::vector<pp::Rect> page_rects;
2254 int page_count = FPDF_GetPageCount(doc_);
2255 bool doc_complete = doc_loader_.IsDocumentComplete();
2256 for (int i = 0; i < page_count; ++i) {
2258 // Add space for horizontal separator.
2259 document_size_.Enlarge(0, kPageSeparatorThickness);
2262 // Get page availability. If reload==false, and document is not loaded yet
2263 // (we are using async loading) - mark all pages as unavailable.
2264 // If reload==true (we have document constructed already), get page
2265 // availability flag from already existing PDFiumPage class.
2266 bool page_available = reload ? pages_[i]->available() : doc_complete;
2268 pp::Size size = page_available ? GetPageSize(i) : default_page_size_;
2269 size.Enlarge(kPageShadowLeft + kPageShadowRight,
2270 kPageShadowTop + kPageShadowBottom);
2271 pp::Rect rect(pp::Point(0, document_size_.height()), size);
2272 page_rects.push_back(rect);
2274 if (size.width() > document_size_.width())
2275 document_size_.set_width(size.width());
2277 document_size_.Enlarge(0, size.height());
2280 for (int i = 0; i < page_count; ++i) {
2281 // Center pages relative to the entire document.
2282 page_rects[i].set_x((document_size_.width() - page_rects[i].width()) / 2);
2283 pp::Rect page_rect(page_rects[i]);
2284 page_rect.Inset(kPageShadowLeft, kPageShadowTop,
2285 kPageShadowRight, kPageShadowBottom);
2287 pages_[i]->set_rect(page_rect);
2289 pages_.push_back(new PDFiumPage(this, i, page_rect, doc_complete));
2293 CalculateVisiblePages();
2294 if (document_size_ != old_document_size)
2295 client_->DocumentSizeUpdated(document_size_);
2298 void PDFiumEngine::CalculateVisiblePages() {
2299 // Clear pending requests queue, since it may contain requests to the pages
2300 // that are already invisible (after scrolling for example).
2301 pending_pages_.clear();
2302 doc_loader_.ClearPendingRequests();
2304 visible_pages_.clear();
2305 pp::Rect visible_rect(plugin_size_);
2306 for (size_t i = 0; i < pages_.size(); ++i) {
2307 // Check an entire PageScreenRect, since we might need to repaint side
2308 // borders and shadows even if the page itself is not visible.
2309 // For example, when user use pdf with different page sizes and zoomed in
2310 // outside page area.
2311 if (visible_rect.Intersects(GetPageScreenRect(i))) {
2312 visible_pages_.push_back(i);
2313 CheckPageAvailable(i, &pending_pages_);
2315 // Need to unload pages when we're not using them, since some PDFs use a
2316 // lot of memory. See http://crbug.com/48791
2317 if (defer_page_unload_) {
2318 deferred_page_unloads_.push_back(i);
2320 pages_[i]->Unload();
2323 // If the last mouse down was on a page that's no longer visible, reset
2324 // that variable so that we don't send keyboard events to it (the focus
2325 // will be lost when the page is first closed anyways).
2326 if (static_cast<int>(i) == last_page_mouse_down_)
2327 last_page_mouse_down_ = -1;
2331 // Any pending highlighting of form fields will be invalid since these are in
2332 // screen coordinates.
2333 form_highlights_.clear();
2335 if (visible_pages_.size() == 0)
2336 first_visible_page_ = -1;
2338 first_visible_page_ = visible_pages_.front();
2340 int most_visible_page = first_visible_page_;
2341 // Check if the next page is more visible than the first one.
2342 if (most_visible_page != -1 &&
2343 pages_.size() > 0 &&
2344 most_visible_page < static_cast<int>(pages_.size()) - 1) {
2346 visible_rect.Intersect(GetPageScreenRect(most_visible_page));
2348 visible_rect.Intersect(GetPageScreenRect(most_visible_page + 1));
2349 if (rc_next.height() > rc_first.height())
2350 most_visible_page++;
2353 SetCurrentPage(most_visible_page);
2356 bool PDFiumEngine::IsPageVisible(int index) const {
2357 for (size_t i = 0; i < visible_pages_.size(); ++i) {
2358 if (visible_pages_[i] == index)
2365 bool PDFiumEngine::CheckPageAvailable(int index, std::vector<int>* pending) {
2366 if (!doc_ || !form_)
2369 if (static_cast<int>(pages_.size()) > index && pages_[index]->available())
2372 if (!FPDFAvail_IsPageAvail(fpdf_availability_, index, &download_hints_)) {
2374 for (j = 0; j < pending->size(); ++j) {
2375 if ((*pending)[j] == index)
2379 if (j == pending->size())
2380 pending->push_back(index);
2384 if (static_cast<int>(pages_.size()) > index)
2385 pages_[index]->set_available(true);
2386 if (!default_page_size_.GetArea())
2387 default_page_size_ = GetPageSize(index);
2391 pp::Size PDFiumEngine::GetPageSize(int index) {
2393 double width_in_points = 0;
2394 double height_in_points = 0;
2395 int rv = FPDF_GetPageSizeByIndex(
2396 doc_, index, &width_in_points, &height_in_points);
2399 int width_in_pixels = static_cast<int>(
2400 width_in_points * kPixelsPerInch / kPointsPerInch);
2401 int height_in_pixels = static_cast<int>(
2402 height_in_points * kPixelsPerInch / kPointsPerInch);
2403 if (current_rotation_ % 2 == 1)
2404 std::swap(width_in_pixels, height_in_pixels);
2405 size = pp::Size(width_in_pixels, height_in_pixels);
2410 int PDFiumEngine::StartPaint(int page_index, const pp::Rect& dirty) {
2411 // For the first time we hit paint, do nothing and just record the paint for
2412 // the next callback. This keeps the UI responsive in case the user is doing
2413 // a lot of scrolling.
2414 ProgressivePaint progressive;
2415 progressive.rect = dirty;
2416 progressive.page_index = page_index;
2417 progressive.bitmap = NULL;
2418 progressive.painted_ = false;
2419 progressive_paints_.push_back(progressive);
2420 return progressive_paints_.size() - 1;
2423 bool PDFiumEngine::ContinuePaint(int progressive_index,
2424 pp::ImageData* image_data) {
2425 #if defined(OS_LINUX)
2426 g_last_instance_id = client_->GetPluginInstance()->pp_instance();
2430 int page_index = progressive_paints_[progressive_index].page_index;
2431 last_progressive_start_time_ = base::Time::Now();
2432 if (progressive_paints_[progressive_index].bitmap) {
2433 rv = FPDF_RenderPage_Continue(
2434 pages_[page_index]->GetPage(), static_cast<IFSDK_PAUSE*>(this));
2436 pp::Rect dirty = progressive_paints_[progressive_index].rect;
2437 progressive_paints_[progressive_index].bitmap = CreateBitmap(dirty,
2439 int start_x, start_y, size_x, size_y;
2441 page_index, dirty, &start_x, &start_y, &size_x, &size_y);
2442 FPDFBitmap_FillRect(progressive_paints_[progressive_index].bitmap, start_x,
2443 start_y, size_x, size_y, 0xFFFFFFFF);
2444 rv = FPDF_RenderPageBitmap_Start(
2445 progressive_paints_[progressive_index].bitmap,
2446 pages_[page_index]->GetPage(), start_x, start_y, size_x, size_y,
2448 GetRenderingFlags(), static_cast<IFSDK_PAUSE*>(this));
2450 return rv != FPDF_RENDER_TOBECOUNTINUED;
2453 void PDFiumEngine::FinishPaint(int progressive_index,
2454 pp::ImageData* image_data) {
2455 int page_index = progressive_paints_[progressive_index].page_index;
2456 pp::Rect dirty_in_screen = progressive_paints_[progressive_index].rect;
2457 FPDF_BITMAP bitmap = progressive_paints_[progressive_index].bitmap;
2458 int start_x, start_y, size_x, size_y;
2460 page_index, dirty_in_screen, &start_x, &start_y, &size_x, &size_y);
2464 form_, bitmap, pages_[page_index]->GetPage(), start_x, start_y, size_x,
2465 size_y, current_rotation_, GetRenderingFlags());
2467 FillPageSides(progressive_index);
2469 // Paint the page shadows.
2470 PaintPageShadow(progressive_index, image_data);
2472 DrawSelections(progressive_index, image_data);
2474 FPDF_RenderPage_Close(pages_[page_index]->GetPage());
2475 FPDFBitmap_Destroy(bitmap);
2476 progressive_paints_.erase(progressive_paints_.begin() + progressive_index);
2478 client_->DocumentPaintOccurred();
2481 void PDFiumEngine::CancelPaints() {
2482 for (size_t i = 0; i < progressive_paints_.size(); ++i) {
2483 FPDF_RenderPage_Close(pages_[progressive_paints_[i].page_index]->GetPage());
2484 FPDFBitmap_Destroy(progressive_paints_[i].bitmap);
2486 progressive_paints_.clear();
2489 void PDFiumEngine::FillPageSides(int progressive_index) {
2490 int page_index = progressive_paints_[progressive_index].page_index;
2491 pp::Rect dirty_in_screen = progressive_paints_[progressive_index].rect;
2492 FPDF_BITMAP bitmap = progressive_paints_[progressive_index].bitmap;
2494 pp::Rect page_rect = pages_[page_index]->rect();
2495 if (page_rect.x() > 0) {
2497 page_rect.y() - kPageShadowTop,
2498 page_rect.x() - kPageShadowLeft,
2499 page_rect.height() + kPageShadowTop +
2500 kPageShadowBottom + kPageSeparatorThickness);
2501 left = GetScreenRect(left).Intersect(dirty_in_screen);
2503 FPDFBitmap_FillRect(bitmap, left.x() - dirty_in_screen.x(),
2504 left.y() - dirty_in_screen.y(), left.width(),
2505 left.height(), kBackgroundColor);
2508 if (page_rect.right() < document_size_.width()) {
2509 pp::Rect right(page_rect.right() + kPageShadowRight,
2510 page_rect.y() - kPageShadowTop,
2511 document_size_.width() - page_rect.right() -
2513 page_rect.height() + kPageShadowTop +
2514 kPageShadowBottom + kPageSeparatorThickness);
2515 right = GetScreenRect(right).Intersect(dirty_in_screen);
2517 FPDFBitmap_FillRect(bitmap, right.x() - dirty_in_screen.x(),
2518 right.y() - dirty_in_screen.y(), right.width(),
2519 right.height(), kBackgroundColor);
2523 pp::Rect bottom(page_rect.x() - kPageShadowLeft,
2524 page_rect.bottom() + kPageShadowBottom,
2525 page_rect.width() + kPageShadowLeft + kPageShadowRight,
2526 kPageSeparatorThickness);
2527 bottom = GetScreenRect(bottom).Intersect(dirty_in_screen);
2529 FPDFBitmap_FillRect(bitmap, bottom.x() - dirty_in_screen.x(),
2530 bottom.y() - dirty_in_screen.y(), bottom.width(),
2531 bottom.height(), kBackgroundColor);
2534 void PDFiumEngine::PaintPageShadow(int progressive_index,
2535 pp::ImageData* image_data) {
2536 int page_index = progressive_paints_[progressive_index].page_index;
2537 pp::Rect dirty_in_screen = progressive_paints_[progressive_index].rect;
2538 pp::Rect page_rect = pages_[page_index]->rect();
2539 pp::Rect shadow_rect(page_rect);
2540 shadow_rect.Inset(-kPageShadowLeft, -kPageShadowTop,
2541 -kPageShadowRight, -kPageShadowBottom);
2543 // Due to the rounding errors of the GetScreenRect it is possible to get
2544 // different size shadows on the left and right sides even they are defined
2545 // the same. To fix this issue let's calculate shadow rect and then shrink
2546 // it by the size of the shadows.
2547 shadow_rect = GetScreenRect(shadow_rect);
2548 page_rect = shadow_rect;
2550 page_rect.Inset(static_cast<int>(ceil(kPageShadowLeft * current_zoom_)),
2551 static_cast<int>(ceil(kPageShadowTop * current_zoom_)),
2552 static_cast<int>(ceil(kPageShadowRight * current_zoom_)),
2553 static_cast<int>(ceil(kPageShadowBottom * current_zoom_)));
2555 DrawPageShadow(page_rect, shadow_rect, dirty_in_screen, image_data);
2558 void PDFiumEngine::DrawSelections(int progressive_index,
2559 pp::ImageData* image_data) {
2560 int page_index = progressive_paints_[progressive_index].page_index;
2561 pp::Rect dirty_in_screen = progressive_paints_[progressive_index].rect;
2563 void* region = NULL;
2565 GetRegion(dirty_in_screen.point(), image_data, ®ion, &stride);
2567 std::vector<pp::Rect> highlighted_rects;
2568 pp::Rect visible_rect = GetVisibleRect();
2569 for (size_t k = 0; k < selection_.size(); ++k) {
2570 if (selection_[k].page_index() != page_index)
2572 std::vector<pp::Rect> rects = selection_[k].GetScreenRects(
2573 visible_rect.point(), current_zoom_, current_rotation_);
2574 for (size_t j = 0; j < rects.size(); ++j) {
2575 pp::Rect visible_selection = rects[j].Intersect(dirty_in_screen);
2576 if (visible_selection.IsEmpty())
2579 visible_selection.Offset(
2580 -dirty_in_screen.point().x(), -dirty_in_screen.point().y());
2581 Highlight(region, stride, visible_selection, &highlighted_rects);
2585 for (size_t k = 0; k < form_highlights_.size(); ++k) {
2586 pp::Rect visible_selection = form_highlights_[k].Intersect(dirty_in_screen);
2587 if (visible_selection.IsEmpty())
2590 visible_selection.Offset(
2591 -dirty_in_screen.point().x(), -dirty_in_screen.point().y());
2592 Highlight(region, stride, visible_selection, &highlighted_rects);
2594 form_highlights_.clear();
2597 void PDFiumEngine::PaintUnavailablePage(int page_index,
2598 const pp::Rect& dirty,
2599 pp::ImageData* image_data) {
2600 int start_x, start_y, size_x, size_y;
2601 GetPDFiumRect(page_index, dirty, &start_x, &start_y, &size_x, &size_y);
2602 FPDF_BITMAP bitmap = CreateBitmap(dirty, image_data);
2603 FPDFBitmap_FillRect(bitmap, start_x, start_y, size_x, size_y,
2606 pp::Rect loading_text_in_screen(
2607 pages_[page_index]->rect().width() / 2,
2608 pages_[page_index]->rect().y() + kLoadingTextVerticalOffset, 0, 0);
2609 loading_text_in_screen = GetScreenRect(loading_text_in_screen);
2610 FPDFBitmap_Destroy(bitmap);
2613 int PDFiumEngine::GetProgressiveIndex(int page_index) const {
2614 for (size_t i = 0; i < progressive_paints_.size(); ++i) {
2615 if (progressive_paints_[i].page_index == page_index)
2621 FPDF_BITMAP PDFiumEngine::CreateBitmap(const pp::Rect& rect,
2622 pp::ImageData* image_data) const {
2625 GetRegion(rect.point(), image_data, ®ion, &stride);
2628 return FPDFBitmap_CreateEx(
2629 rect.width(), rect.height(), FPDFBitmap_BGRx, region, stride);
2632 void PDFiumEngine::GetPDFiumRect(
2633 int page_index, const pp::Rect& rect, int* start_x, int* start_y,
2634 int* size_x, int* size_y) const {
2635 pp::Rect page_rect = GetScreenRect(pages_[page_index]->rect());
2636 page_rect.Offset(-rect.x(), -rect.y());
2638 *start_x = page_rect.x();
2639 *start_y = page_rect.y();
2640 *size_x = page_rect.width();
2641 *size_y = page_rect.height();
2644 int PDFiumEngine::GetRenderingFlags() const {
2645 int flags = FPDF_LCD_TEXT | FPDF_NO_CATCH;
2646 if (render_grayscale_)
2647 flags |= FPDF_GRAYSCALE;
2648 if (client_->IsPrintPreview())
2649 flags |= FPDF_PRINTING;
2653 pp::Rect PDFiumEngine::GetVisibleRect() const {
2655 rv.set_x(static_cast<int>(position_.x() / current_zoom_));
2656 rv.set_y(static_cast<int>(position_.y() / current_zoom_));
2657 rv.set_width(static_cast<int>(ceil(plugin_size_.width() / current_zoom_)));
2658 rv.set_height(static_cast<int>(ceil(plugin_size_.height() / current_zoom_)));
2662 pp::Rect PDFiumEngine::GetPageScreenRect(int page_index) const {
2663 // Since we use this rect for creating the PDFium bitmap, also include other
2664 // areas around the page that we might need to update such as the page
2665 // separator and the sides if the page is narrower than the document.
2666 return GetScreenRect(pp::Rect(
2668 pages_[page_index]->rect().y() - kPageShadowTop,
2669 document_size_.width(),
2670 pages_[page_index]->rect().height() + kPageShadowTop +
2671 kPageShadowBottom + kPageSeparatorThickness));
2674 pp::Rect PDFiumEngine::GetScreenRect(const pp::Rect& rect) const {
2677 static_cast<int>(ceil(rect.right() * current_zoom_ - position_.x()));
2679 static_cast<int>(ceil(rect.bottom() * current_zoom_ - position_.y()));
2681 rv.set_x(static_cast<int>(rect.x() * current_zoom_ - position_.x()));
2682 rv.set_y(static_cast<int>(rect.y() * current_zoom_ - position_.y()));
2683 rv.set_width(right - rv.x());
2684 rv.set_height(bottom - rv.y());
2688 void PDFiumEngine::Highlight(void* buffer,
2690 const pp::Rect& rect,
2691 std::vector<pp::Rect>* highlighted_rects) {
2695 pp::Rect new_rect = rect;
2696 for (size_t i = 0; i < highlighted_rects->size(); ++i)
2697 new_rect = new_rect.Subtract((*highlighted_rects)[i]);
2699 highlighted_rects->push_back(new_rect);
2700 int l = new_rect.x();
2701 int t = new_rect.y();
2702 int w = new_rect.width();
2703 int h = new_rect.height();
2705 for (int y = t; y < t + h; ++y) {
2706 for (int x = l; x < l + w; ++x) {
2707 uint8* pixel = static_cast<uint8*>(buffer) + y * stride + x * 4;
2708 // This is our highlight color.
2709 pixel[0] = static_cast<uint8>(
2710 pixel[0] * (kHighlightColorB / 255.0));
2711 pixel[1] = static_cast<uint8>(
2712 pixel[1] * (kHighlightColorG / 255.0));
2713 pixel[2] = static_cast<uint8>(
2714 pixel[2] * (kHighlightColorR / 255.0));
2719 PDFiumEngine::SelectionChangeInvalidator::SelectionChangeInvalidator(
2720 PDFiumEngine* engine) : engine_(engine) {
2721 previous_origin_ = engine_->GetVisibleRect().point();
2722 GetVisibleSelectionsScreenRects(&old_selections_);
2725 PDFiumEngine::SelectionChangeInvalidator::~SelectionChangeInvalidator() {
2726 // Offset the old selections if the document scrolled since we recorded them.
2727 pp::Point offset = previous_origin_ - engine_->GetVisibleRect().point();
2728 for (size_t i = 0; i < old_selections_.size(); ++i)
2729 old_selections_[i].Offset(offset);
2731 std::vector<pp::Rect> new_selections;
2732 GetVisibleSelectionsScreenRects(&new_selections);
2733 for (size_t i = 0; i < new_selections.size(); ++i) {
2734 for (size_t j = 0; j < old_selections_.size(); ++j) {
2735 if (!old_selections_[j].IsEmpty() &&
2736 new_selections[i] == old_selections_[j]) {
2737 // Rectangle was selected before and after, so no need to invalidate it.
2738 // Mark the rectangles by setting them to empty.
2739 new_selections[i] = old_selections_[j] = pp::Rect();
2745 for (size_t i = 0; i < old_selections_.size(); ++i) {
2746 if (!old_selections_[i].IsEmpty())
2747 engine_->client_->Invalidate(old_selections_[i]);
2749 for (size_t i = 0; i < new_selections.size(); ++i) {
2750 if (!new_selections[i].IsEmpty())
2751 engine_->client_->Invalidate(new_selections[i]);
2753 engine_->OnSelectionChanged();
2757 PDFiumEngine::SelectionChangeInvalidator::GetVisibleSelectionsScreenRects(
2758 std::vector<pp::Rect>* rects) {
2759 pp::Rect visible_rect = engine_->GetVisibleRect();
2760 for (size_t i = 0; i < engine_->selection_.size(); ++i) {
2761 int page_index = engine_->selection_[i].page_index();
2762 if (!engine_->IsPageVisible(page_index))
2763 continue; // This selection is on a page that's not currently visible.
2765 std::vector<pp::Rect> selection_rects =
2766 engine_->selection_[i].GetScreenRects(
2767 visible_rect.point(),
2768 engine_->current_zoom_,
2769 engine_->current_rotation_);
2770 rects->insert(rects->end(), selection_rects.begin(), selection_rects.end());
2774 PDFiumEngine::MouseDownState::MouseDownState(
2775 const PDFiumPage::Area& area,
2776 const PDFiumPage::LinkTarget& target)
2777 : area_(area), target_(target) {
2780 PDFiumEngine::MouseDownState::~MouseDownState() {
2783 void PDFiumEngine::MouseDownState::Set(const PDFiumPage::Area& area,
2784 const PDFiumPage::LinkTarget& target) {
2789 void PDFiumEngine::MouseDownState::Reset() {
2790 area_ = PDFiumPage::NONSELECTABLE_AREA;
2791 target_ = PDFiumPage::LinkTarget();
2794 bool PDFiumEngine::MouseDownState::Matches(
2795 const PDFiumPage::Area& area,
2796 const PDFiumPage::LinkTarget& target) const {
2797 if (area_ == area) {
2798 if (area == PDFiumPage::WEBLINK_AREA)
2799 return target_.url == target.url;
2800 if (area == PDFiumPage::DOCLINK_AREA)
2801 return target_.page == target.page;
2807 PDFiumEngine::FindTextIndex::FindTextIndex()
2808 : valid_(false), index_(0) {
2811 PDFiumEngine::FindTextIndex::~FindTextIndex() {
2814 void PDFiumEngine::FindTextIndex::Invalidate() {
2818 size_t PDFiumEngine::FindTextIndex::GetIndex() const {
2823 void PDFiumEngine::FindTextIndex::SetIndex(size_t index) {
2828 size_t PDFiumEngine::FindTextIndex::IncrementIndex() {
2833 void PDFiumEngine::DeviceToPage(int page_index,
2838 *page_x = *page_y = 0;
2839 int temp_x = static_cast<int>((device_x + position_.x())/ current_zoom_ -
2840 pages_[page_index]->rect().x());
2841 int temp_y = static_cast<int>((device_y + position_.y())/ current_zoom_ -
2842 pages_[page_index]->rect().y());
2844 pages_[page_index]->GetPage(), 0, 0,
2845 pages_[page_index]->rect().width(), pages_[page_index]->rect().height(),
2846 current_rotation_, temp_x, temp_y, page_x, page_y);
2849 int PDFiumEngine::GetVisiblePageIndex(FPDF_PAGE page) {
2850 for (size_t i = 0; i < visible_pages_.size(); ++i) {
2851 if (pages_[visible_pages_[i]]->GetPage() == page)
2852 return visible_pages_[i];
2857 void PDFiumEngine::SetCurrentPage(int index) {
2858 if (index == most_visible_page_ || !form_)
2860 if (most_visible_page_ != -1 && called_do_document_action_) {
2861 FPDF_PAGE old_page = pages_[most_visible_page_]->GetPage();
2862 FORM_DoPageAAction(old_page, form_, FPDFPAGE_AACTION_CLOSE);
2864 most_visible_page_ = index;
2865 #if defined(OS_LINUX)
2866 g_last_instance_id = client_->GetPluginInstance()->pp_instance();
2868 if (most_visible_page_ != -1 && called_do_document_action_) {
2869 FPDF_PAGE new_page = pages_[most_visible_page_]->GetPage();
2870 FORM_DoPageAAction(new_page, form_, FPDFPAGE_AACTION_OPEN);
2874 void PDFiumEngine::TransformPDFPageForPrinting(
2876 const PP_PrintSettings_Dev& print_settings) {
2877 // Get the source page width and height in points.
2878 const double src_page_width = FPDF_GetPageWidth(page);
2879 const double src_page_height = FPDF_GetPageHeight(page);
2881 const int src_page_rotation = FPDFPage_GetRotation(page);
2882 const bool fit_to_page = print_settings.print_scaling_option ==
2883 PP_PRINTSCALINGOPTION_FIT_TO_PRINTABLE_AREA;
2885 pp::Size page_size(print_settings.paper_size);
2886 pp::Rect content_rect(print_settings.printable_area);
2887 const bool rotated = (src_page_rotation % 2 == 1);
2888 SetPageSizeAndContentRect(rotated,
2889 src_page_width > src_page_height,
2893 // Compute the screen page width and height in points.
2894 const int actual_page_width =
2895 rotated ? page_size.height() : page_size.width();
2896 const int actual_page_height =
2897 rotated ? page_size.width() : page_size.height();
2899 const double scale_factor = CalculateScaleFactor(fit_to_page, content_rect,
2901 src_page_height, rotated);
2903 // Calculate positions for the clip box.
2904 ClipBox source_clip_box;
2905 CalculateClipBoxBoundary(page, scale_factor, rotated, &source_clip_box);
2907 // Calculate the translation offset values.
2908 double offset_x = 0;
2909 double offset_y = 0;
2911 CalculateScaledClipBoxOffset(content_rect, source_clip_box, &offset_x,
2914 CalculateNonScaledClipBoxOffset(content_rect, src_page_rotation,
2915 actual_page_width, actual_page_height,
2916 source_clip_box, &offset_x, &offset_y);
2919 // Reset the media box and crop box. When the page has crop box and media box,
2920 // the plugin will display the crop box contents and not the entire media box.
2921 // If the pages have different crop box values, the plugin will display a
2922 // document of multiple page sizes. To give better user experience, we
2923 // decided to have same crop box and media box values. Hence, the user will
2924 // see a list of uniform pages.
2925 FPDFPage_SetMediaBox(page, 0, 0, page_size.width(), page_size.height());
2926 FPDFPage_SetCropBox(page, 0, 0, page_size.width(), page_size.height());
2928 // Transformation is not required, return. Do this check only after updating
2929 // the media box and crop box. For more detailed information, please refer to
2930 // the comment block right before FPDF_SetMediaBox and FPDF_GetMediaBox calls.
2931 if (scale_factor == 1.0 && offset_x == 0 && offset_y == 0)
2935 // All the positions have been calculated, now manipulate the PDF.
2936 FS_MATRIX matrix = {static_cast<float>(scale_factor),
2939 static_cast<float>(scale_factor),
2940 static_cast<float>(offset_x),
2941 static_cast<float>(offset_y)};
2942 FS_RECTF cliprect = {static_cast<float>(source_clip_box.left+offset_x),
2943 static_cast<float>(source_clip_box.top+offset_y),
2944 static_cast<float>(source_clip_box.right+offset_x),
2945 static_cast<float>(source_clip_box.bottom+offset_y)};
2946 FPDFPage_TransFormWithClip(page, &matrix, &cliprect);
2947 FPDFPage_TransformAnnots(page, scale_factor, 0, 0, scale_factor,
2948 offset_x, offset_y);
2951 void PDFiumEngine::DrawPageShadow(const pp::Rect& page_rc,
2952 const pp::Rect& shadow_rc,
2953 const pp::Rect& clip_rc,
2954 pp::ImageData* image_data) {
2955 pp::Rect page_rect(page_rc);
2956 page_rect.Offset(page_offset_);
2958 pp::Rect shadow_rect(shadow_rc);
2959 shadow_rect.Offset(page_offset_);
2961 pp::Rect clip_rect(clip_rc);
2962 clip_rect.Offset(page_offset_);
2964 // Page drop shadow parameters.
2965 const double factor = 0.5;
2966 uint32 depth = std::max(
2967 std::max(page_rect.x() - shadow_rect.x(),
2968 page_rect.y() - shadow_rect.y()),
2969 std::max(shadow_rect.right() - page_rect.right(),
2970 shadow_rect.bottom() - page_rect.bottom()));
2971 depth = static_cast<uint32>(depth * 1.5) + 1;
2973 // We need to check depth only to verify our copy of shadow matrix is correct.
2974 if (!page_shadow_.get() || page_shadow_->depth() != depth)
2975 page_shadow_.reset(new ShadowMatrix(depth, factor, kBackgroundColor));
2977 DCHECK(!image_data->is_null());
2978 DrawShadow(image_data, shadow_rect, page_rect, clip_rect, *page_shadow_);
2981 void PDFiumEngine::GetRegion(const pp::Point& location,
2982 pp::ImageData* image_data,
2984 int* stride) const {
2985 if (image_data->is_null()) {
2986 DCHECK(plugin_size_.IsEmpty());
2991 char* buffer = static_cast<char*>(image_data->data());
2992 *stride = image_data->stride();
2994 pp::Point offset_location = location + page_offset_;
2995 // TODO: update this when we support BIDI and scrollbars can be on the left.
2997 !pp::Rect(page_offset_, plugin_size_).Contains(offset_location)) {
3002 buffer += location.y() * (*stride);
3003 buffer += (location.x() + page_offset_.x()) * 4;
3007 void PDFiumEngine::OnSelectionChanged() {
3008 if (HasPermission(PDFEngine::PERMISSION_COPY))
3009 pp::PDF::SetSelectedText(GetPluginInstance(), GetSelectedText().c_str());
3012 void PDFiumEngine::RotateInternal() {
3013 // Store the current find index so that we can resume finding at that
3014 // particular index after we have recomputed the find results.
3015 std::string current_find_text = current_find_text_;
3016 if (current_find_index_.valid())
3017 resume_find_index_.SetIndex(current_find_index_.GetIndex());
3019 resume_find_index_.Invalidate();
3021 InvalidateAllPages();
3023 if (!current_find_text.empty()) {
3025 client_->NotifyNumberOfFindResultsChanged(0, false);
3026 StartFind(current_find_text.c_str(), false);
3030 void PDFiumEngine::Form_Invalidate(FPDF_FORMFILLINFO* param,
3036 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3037 int page_index = engine->GetVisiblePageIndex(page);
3038 if (page_index == -1) {
3039 // This can sometime happen when the page is closed because it went off
3040 // screen, and PDFium invalidates the control as it's being deleted.
3044 pp::Rect rect = engine->pages_[page_index]->PageToScreen(
3045 engine->GetVisibleRect().point(), engine->current_zoom_, left, top, right,
3046 bottom, engine->current_rotation_);
3047 engine->client_->Invalidate(rect);
3050 void PDFiumEngine::Form_OutputSelectedRect(FPDF_FORMFILLINFO* param,
3056 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3057 int page_index = engine->GetVisiblePageIndex(page);
3058 if (page_index == -1) {
3062 pp::Rect rect = engine->pages_[page_index]->PageToScreen(
3063 engine->GetVisibleRect().point(), engine->current_zoom_, left, top, right,
3064 bottom, engine->current_rotation_);
3065 engine->form_highlights_.push_back(rect);
3068 void PDFiumEngine::Form_SetCursor(FPDF_FORMFILLINFO* param, int cursor_type) {
3069 // We don't need this since it's not enough to change the cursor in all
3070 // scenarios. Instead, we check which form field we're under in OnMouseMove.
3073 int PDFiumEngine::Form_SetTimer(FPDF_FORMFILLINFO* param,
3075 TimerCallback timer_func) {
3076 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3077 engine->timers_[++engine->next_timer_id_] =
3078 std::pair<int, TimerCallback>(elapse, timer_func);
3079 engine->client_->ScheduleCallback(engine->next_timer_id_, elapse);
3080 return engine->next_timer_id_;
3083 void PDFiumEngine::Form_KillTimer(FPDF_FORMFILLINFO* param, int timer_id) {
3084 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3085 engine->timers_.erase(timer_id);
3088 FPDF_SYSTEMTIME PDFiumEngine::Form_GetLocalTime(FPDF_FORMFILLINFO* param) {
3089 base::Time time = base::Time::Now();
3090 base::Time::Exploded exploded;
3091 time.LocalExplode(&exploded);
3094 rv.wYear = exploded.year;
3095 rv.wMonth = exploded.month;
3096 rv.wDayOfWeek = exploded.day_of_week;
3097 rv.wDay = exploded.day_of_month;
3098 rv.wHour = exploded.hour;
3099 rv.wMinute = exploded.minute;
3100 rv.wSecond = exploded.second;
3101 rv.wMilliseconds = exploded.millisecond;
3105 void PDFiumEngine::Form_OnChange(FPDF_FORMFILLINFO* param) {
3106 // Don't care about.
3109 FPDF_PAGE PDFiumEngine::Form_GetPage(FPDF_FORMFILLINFO* param,
3110 FPDF_DOCUMENT document,
3112 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3113 if (page_index < 0 || page_index >= static_cast<int>(engine->pages_.size()))
3115 return engine->pages_[page_index]->GetPage();
3118 FPDF_PAGE PDFiumEngine::Form_GetCurrentPage(FPDF_FORMFILLINFO* param,
3119 FPDF_DOCUMENT document) {
3120 // TODO(jam): find out what this is used for.
3121 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3122 int index = engine->last_page_mouse_down_;
3124 index = engine->GetMostVisiblePage();
3131 return engine->pages_[index]->GetPage();
3134 int PDFiumEngine::Form_GetRotation(FPDF_FORMFILLINFO* param, FPDF_PAGE page) {
3138 void PDFiumEngine::Form_ExecuteNamedAction(FPDF_FORMFILLINFO* param,
3139 FPDF_BYTESTRING named_action) {
3140 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3141 std::string action(named_action);
3142 if (action == "Print") {
3143 engine->client_->Print();
3147 int index = engine->last_page_mouse_down_;
3148 /* Don't try to calculate the most visible page if we don't have a left click
3149 before this event (this code originally copied Form_GetCurrentPage which of
3150 course needs to do that and which doesn't have recursion). This can end up
3151 causing infinite recursion. See http://crbug.com/240413 for more
3152 information. Either way, it's not necessary for the spec'd list of named
3155 index = engine->GetMostVisiblePage();
3160 // This is the only list of named actions per the spec (see 12.6.4.11). Adobe
3161 // Reader supports more, like FitWidth, but since they're not part of the spec
3162 // and we haven't got bugs about them, no need to now.
3163 if (action == "NextPage") {
3164 engine->client_->ScrollToPage(index + 1);
3165 } else if (action == "PrevPage") {
3166 engine->client_->ScrollToPage(index - 1);
3167 } else if (action == "FirstPage") {
3168 engine->client_->ScrollToPage(0);
3169 } else if (action == "LastPage") {
3170 engine->client_->ScrollToPage(engine->pages_.size() - 1);
3174 void PDFiumEngine::Form_SetTextFieldFocus(FPDF_FORMFILLINFO* param,
3175 FPDF_WIDESTRING value,
3176 FPDF_DWORD valueLen,
3177 FPDF_BOOL is_focus) {
3178 // Do nothing for now.
3179 // TODO(gene): use this signal to trigger OSK.
3182 void PDFiumEngine::Form_DoURIAction(FPDF_FORMFILLINFO* param,
3183 FPDF_BYTESTRING uri) {
3184 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3185 engine->client_->NavigateTo(std::string(uri), false);
3188 void PDFiumEngine::Form_DoGoToAction(FPDF_FORMFILLINFO* param,
3191 float* position_array,
3192 int size_of_array) {
3193 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3194 engine->client_->ScrollToPage(page_index);
3197 int PDFiumEngine::Form_Alert(IPDF_JSPLATFORM* param,
3198 FPDF_WIDESTRING message,
3199 FPDF_WIDESTRING title,
3202 // See fpdfformfill.h for these values.
3205 ALERT_TYPE_OK_CANCEL,
3207 ALERT_TYPE_YES_NO_CANCEL
3211 ALERT_RESULT_OK = 1,
3212 ALERT_RESULT_CANCEL,
3217 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3218 std::string message_str =
3219 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(message));
3220 if (type == ALERT_TYPE_OK) {
3221 engine->client_->Alert(message_str);
3222 return ALERT_RESULT_OK;
3225 bool rv = engine->client_->Confirm(message_str);
3226 if (type == ALERT_TYPE_OK_CANCEL)
3227 return rv ? ALERT_RESULT_OK : ALERT_RESULT_CANCEL;
3228 return rv ? ALERT_RESULT_YES : ALERT_RESULT_NO;
3231 void PDFiumEngine::Form_Beep(IPDF_JSPLATFORM* param, int type) {
3232 // Beeps are annoying, and not possible using javascript, so ignore for now.
3235 int PDFiumEngine::Form_Response(IPDF_JSPLATFORM* param,
3236 FPDF_WIDESTRING question,
3237 FPDF_WIDESTRING title,
3238 FPDF_WIDESTRING default_response,
3239 FPDF_WIDESTRING label,
3243 std::string question_str = base::UTF16ToUTF8(
3244 reinterpret_cast<const base::char16*>(question));
3245 std::string default_str = base::UTF16ToUTF8(
3246 reinterpret_cast<const base::char16*>(default_response));
3248 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3249 std::string rv = engine->client_->Prompt(question_str, default_str);
3250 base::string16 rv_16 = base::UTF8ToUTF16(rv);
3251 int rv_bytes = rv_16.size() * sizeof(base::char16);
3253 int bytes_to_copy = rv_bytes < length ? rv_bytes : length;
3254 memcpy(response, rv_16.c_str(), bytes_to_copy);
3259 int PDFiumEngine::Form_GetFilePath(IPDF_JSPLATFORM* param,
3262 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3263 std::string rv = engine->client_->GetURL();
3264 if (file_path && rv.size() <= static_cast<size_t>(length))
3265 memcpy(file_path, rv.c_str(), rv.size());
3269 void PDFiumEngine::Form_Mail(IPDF_JSPLATFORM* param,
3274 FPDF_WIDESTRING subject,
3276 FPDF_WIDESTRING bcc,
3277 FPDF_WIDESTRING message) {
3278 DCHECK(length == 0); // Don't handle attachments; no way with mailto.
3279 std::string to_str =
3280 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(to));
3281 std::string cc_str =
3282 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(cc));
3283 std::string bcc_str =
3284 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(bcc));
3285 std::string subject_str =
3286 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(subject));
3287 std::string message_str =
3288 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(message));
3290 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3291 engine->client_->Email(to_str, cc_str, bcc_str, subject_str, message_str);
3294 void PDFiumEngine::Form_Print(IPDF_JSPLATFORM* param,
3299 FPDF_BOOL shrink_to_fit,
3300 FPDF_BOOL print_as_image,
3302 FPDF_BOOL annotations) {
3303 // No way to pass the extra information to the print dialog using JavaScript.
3304 // Just opening it is fine for now.
3305 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3306 engine->client_->Print();
3309 void PDFiumEngine::Form_SubmitForm(IPDF_JSPLATFORM* param,
3312 FPDF_WIDESTRING url) {
3313 std::string url_str =
3314 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(url));
3315 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3316 engine->client_->SubmitForm(url_str, form_data, length);
3319 void PDFiumEngine::Form_GotoPage(IPDF_JSPLATFORM* param,
3321 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3322 engine->client_->ScrollToPage(page_number);
3325 int PDFiumEngine::Form_Browse(IPDF_JSPLATFORM* param,
3328 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3329 std::string path = engine->client_->ShowFileSelectionDialog();
3330 if (path.size() + 1 <= static_cast<size_t>(length))
3331 memcpy(file_path, &path[0], path.size() + 1);
3332 return path.size() + 1;
3335 FPDF_BOOL PDFiumEngine::Pause_NeedToPauseNow(IFSDK_PAUSE* param) {
3336 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3337 return (base::Time::Now() - engine->last_progressive_start_time_).
3338 InMilliseconds() > engine->progressive_paint_timeout_;
3341 ScopedUnsupportedFeature::ScopedUnsupportedFeature(PDFiumEngine* engine)
3342 : engine_(engine), old_engine_(g_engine_for_unsupported) {
3343 g_engine_for_unsupported = engine_;
3346 ScopedUnsupportedFeature::~ScopedUnsupportedFeature() {
3347 g_engine_for_unsupported = old_engine_;
3350 PDFEngineExports* PDFEngineExports::Create() {
3351 return new PDFiumEngineExports;
3356 int CalculatePosition(FPDF_PAGE page,
3357 const PDFiumEngineExports::RenderingSettings& settings,
3359 int page_width = static_cast<int>(
3360 FPDF_GetPageWidth(page) * settings.dpi_x / kPointsPerInch);
3361 int page_height = static_cast<int>(
3362 FPDF_GetPageHeight(page) * settings.dpi_y / kPointsPerInch);
3364 // Start by assuming that we will draw exactly to the bounds rect
3366 *dest = settings.bounds;
3368 int rotate = 0; // normal orientation.
3370 // Auto-rotate landscape pages to print correctly.
3371 if (settings.autorotate &&
3372 (dest->width() > dest->height()) != (page_width > page_height)) {
3373 rotate = 3; // 90 degrees counter-clockwise.
3374 std::swap(page_width, page_height);
3377 // See if we need to scale the output
3378 bool scale_to_bounds = false;
3379 if (settings.fit_to_bounds &&
3380 ((page_width > dest->width()) || (page_height > dest->height()))) {
3381 scale_to_bounds = true;
3382 } else if (settings.stretch_to_bounds &&
3383 ((page_width < dest->width()) || (page_height < dest->height()))) {
3384 scale_to_bounds = true;
3387 if (scale_to_bounds) {
3388 // If we need to maintain aspect ratio, calculate the actual width and
3390 if (settings.keep_aspect_ratio) {
3391 double scale_factor_x = page_width;
3392 scale_factor_x /= dest->width();
3393 double scale_factor_y = page_height;
3394 scale_factor_y /= dest->height();
3395 if (scale_factor_x > scale_factor_y) {
3396 dest->set_height(page_height / scale_factor_x);
3398 dest->set_width(page_width / scale_factor_y);
3402 // We are not scaling to bounds. Draw in the actual page size. If the
3403 // actual page size is larger than the bounds, the output will be
3405 dest->set_width(page_width);
3406 dest->set_height(page_height);
3409 if (settings.center_in_bounds) {
3410 pp::Point offset((settings.bounds.width() - dest->width()) / 2,
3411 (settings.bounds.height() - dest->height()) / 2);
3412 dest->Offset(offset);
3420 bool PDFiumEngineExports::RenderPDFPageToDC(const void* pdf_buffer,
3423 const RenderingSettings& settings,
3425 FPDF_DOCUMENT doc = FPDF_LoadMemDocument(pdf_buffer, buffer_size, NULL);
3428 FPDF_PAGE page = FPDF_LoadPage(doc, page_number);
3430 FPDF_CloseDocument(doc);
3433 RenderingSettings new_settings = settings;
3434 // calculate the page size
3435 if (new_settings.dpi_x == -1)
3436 new_settings.dpi_x = GetDeviceCaps(dc, LOGPIXELSX);
3437 if (new_settings.dpi_y == -1)
3438 new_settings.dpi_y = GetDeviceCaps(dc, LOGPIXELSY);
3441 int rotate = CalculatePosition(page, new_settings, &dest);
3443 int save_state = SaveDC(dc);
3444 // The caller wanted all drawing to happen within the bounds specified.
3445 // Based on scale calculations, our destination rect might be larger
3446 // than the bounds. Set the clip rect to the bounds.
3447 IntersectClipRect(dc, settings.bounds.x(), settings.bounds.y(),
3448 settings.bounds.x() + settings.bounds.width(),
3449 settings.bounds.y() + settings.bounds.height());
3451 // A temporary hack. PDFs generated by Cairo (used by Chrome OS to generate
3452 // a PDF output from a webpage) result in very large metafiles and the
3453 // rendering using FPDF_RenderPage is incorrect. In this case, render as a
3454 // bitmap. Note that this code does not kick in for PDFs printed from Chrome
3455 // because in that case we create a temp PDF first before printing and this
3456 // temp PDF does not have a creator string that starts with "cairo".
3457 base::string16 creator;
3458 size_t buffer_bytes = FPDF_GetMetaText(doc, "Creator", NULL, 0);
3459 if (buffer_bytes > 1) {
3461 doc, "Creator", WriteInto(&creator, buffer_bytes + 1), buffer_bytes);
3463 bool use_bitmap = false;
3464 if (StartsWith(creator, L"cairo", false))
3467 // Another temporary hack. Some PDFs seems to render very slowly if
3468 // FPDF_RenderPage is directly used on a printer DC. I suspect it is
3469 // because of the code to talk Postscript directly to the printer if
3470 // the printer supports this. Need to discuss this with PDFium. For now,
3471 // render to a bitmap and then blit the bitmap to the DC if we have been
3472 // supplied a printer DC.
3473 int device_type = GetDeviceCaps(dc, TECHNOLOGY);
3475 (device_type == DT_RASPRINTER) || (device_type == DT_PLOTTER)) {
3476 FPDF_BITMAP bitmap = FPDFBitmap_Create(dest.width(), dest.height(),
3479 FPDFBitmap_FillRect(bitmap, 0, 0, dest.width(), dest.height(), 0xFFFFFFFF);
3480 FPDF_RenderPageBitmap(
3481 bitmap, page, 0, 0, dest.width(), dest.height(), rotate,
3482 FPDF_ANNOT | FPDF_PRINTING | FPDF_NO_CATCH);
3483 int stride = FPDFBitmap_GetStride(bitmap);
3485 memset(&bmi, 0, sizeof(bmi));
3486 bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
3487 bmi.bmiHeader.biWidth = dest.width();
3488 bmi.bmiHeader.biHeight = -dest.height(); // top-down image
3489 bmi.bmiHeader.biPlanes = 1;
3490 bmi.bmiHeader.biBitCount = 32;
3491 bmi.bmiHeader.biCompression = BI_RGB;
3492 bmi.bmiHeader.biSizeImage = stride * dest.height();
3493 StretchDIBits(dc, dest.x(), dest.y(), dest.width(), dest.height(),
3494 0, 0, dest.width(), dest.height(),
3495 FPDFBitmap_GetBuffer(bitmap), &bmi, DIB_RGB_COLORS, SRCCOPY);
3496 FPDFBitmap_Destroy(bitmap);
3498 FPDF_RenderPage(dc, page, dest.x(), dest.y(), dest.width(), dest.height(),
3499 rotate, FPDF_ANNOT | FPDF_PRINTING | FPDF_NO_CATCH);
3501 RestoreDC(dc, save_state);
3502 FPDF_ClosePage(page);
3503 FPDF_CloseDocument(doc);
3508 bool PDFiumEngineExports::RenderPDFPageToBitmap(
3509 const void* pdf_buffer,
3510 int pdf_buffer_size,
3512 const RenderingSettings& settings,
3513 void* bitmap_buffer) {
3514 FPDF_DOCUMENT doc = FPDF_LoadMemDocument(pdf_buffer, pdf_buffer_size, NULL);
3517 FPDF_PAGE page = FPDF_LoadPage(doc, page_number);
3519 FPDF_CloseDocument(doc);
3524 int rotate = CalculatePosition(page, settings, &dest);
3526 FPDF_BITMAP bitmap =
3527 FPDFBitmap_CreateEx(settings.bounds.width(), settings.bounds.height(),
3528 FPDFBitmap_BGRA, bitmap_buffer,
3529 settings.bounds.width() * 4);
3531 FPDFBitmap_FillRect(bitmap, 0, 0, settings.bounds.width(),
3532 settings.bounds.height(), 0xFFFFFFFF);
3533 // Shift top-left corner of bounds to (0, 0) if it's not there.
3534 dest.set_point(dest.point() - settings.bounds.point());
3535 FPDF_RenderPageBitmap(
3536 bitmap, page, dest.x(), dest.y(), dest.width(), dest.height(), rotate,
3537 FPDF_ANNOT | FPDF_PRINTING | FPDF_NO_CATCH);
3538 FPDFBitmap_Destroy(bitmap);
3539 FPDF_ClosePage(page);
3540 FPDF_CloseDocument(doc);
3544 bool PDFiumEngineExports::GetPDFDocInfo(const void* pdf_buffer,
3547 double* max_page_width) {
3548 FPDF_DOCUMENT doc = FPDF_LoadMemDocument(pdf_buffer, buffer_size, NULL);
3551 int page_count_local = FPDF_GetPageCount(doc);
3553 *page_count = page_count_local;
3555 if (max_page_width) {
3556 *max_page_width = 0;
3557 for (int page_number = 0; page_number < page_count_local; page_number++) {
3558 double page_width = 0;
3559 double page_height = 0;
3560 FPDF_GetPageSizeByIndex(doc, page_number, &page_width, &page_height);
3561 if (page_width > *max_page_width) {
3562 *max_page_width = page_width;
3566 FPDF_CloseDocument(doc);
3570 bool PDFiumEngineExports::GetPDFPageSizeByIndex(
3571 const void* pdf_buffer,
3572 int pdf_buffer_size,
3576 FPDF_DOCUMENT doc = FPDF_LoadMemDocument(pdf_buffer, pdf_buffer_size, NULL);
3579 bool success = FPDF_GetPageSizeByIndex(doc, page_number, width, height) != 0;
3580 FPDF_CloseDocument(doc);
3584 } // namespace chrome_pdf