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
{
48 #define kPageShadowTop 3
49 #define kPageShadowBottom 7
50 #define kPageShadowLeft 5
51 #define kPageShadowRight 5
53 #define kPageSeparatorThickness 4
54 #define kHighlightColorR 153
55 #define kHighlightColorG 193
56 #define kHighlightColorB 218
58 #define kPendingPageColorR 238
59 #define kPendingPageColorG 238
60 #define kPendingPageColorB 238
61 #define kPendingPageColorA 255
63 #define kFormHighlightColor 0xFFE4DD
64 #define kFormHighlightAlpha 100
66 #define kMaxPasswordTries 3
69 // http://www.adobe.com/devnet/acrobat/pdfs/pdf_reference_1-7.pdf
70 #define kPDFPermissionPrintLowQualityMask 1 << 2
71 #define kPDFPermissionPrintHighQualityMask 1 << 11
72 #define kPDFPermissionCopyMask 1 << 4
73 #define kPDFPermissionCopyAccessibleMask 1 << 9
75 #define kLoadingTextVerticalOffset 50
77 // The maximum amount of time we'll spend doing a paint before we give back
78 // control of the thread.
79 #define kMaxProgressivePaintTimeMs 50
81 // The maximum amount of time we'll spend doing the first paint. This is less
82 // than the above to keep things smooth if the user is scrolling quickly. We
83 // try painting a little because with accelerated compositing, we get flushes
84 // only every 16 ms. If we were to wait until the next flush to paint the rest
85 // of the pdf, we would never get to draw the pdf and would only draw the
86 // scrollbars. This value is picked to give enough time for gpu related code to
87 // do its thing and still fit within the timelimit for 60Hz. For the
88 // non-composited case, this doesn't make things worse since we're still
89 // painting the scrollbars > 60 Hz.
90 #define kMaxInitialProgressivePaintTimeMs 10
92 // Copied from printing/units.cc because we don't want to depend on printing
93 // since it brings in libpng which causes duplicate symbols with PDFium.
94 const int kPointsPerInch
= 72;
95 const int kPixelsPerInch
= 96;
104 int ConvertUnit(int value
, int old_unit
, int new_unit
) {
105 // With integer arithmetic, to divide a value with correct rounding, you need
106 // to add half of the divisor value to the dividend value. You need to do the
107 // reverse with negative number.
109 return ((value
* new_unit
) + (old_unit
/ 2)) / old_unit
;
111 return ((value
* new_unit
) - (old_unit
/ 2)) / old_unit
;
115 std::vector
<uint32_t> GetPageNumbersFromPrintPageNumberRange(
116 const PP_PrintPageNumberRange_Dev
* page_ranges
,
117 uint32_t page_range_count
) {
118 std::vector
<uint32_t> page_numbers
;
119 for (uint32_t index
= 0; index
< page_range_count
; ++index
) {
120 for (uint32_t page_number
= page_ranges
[index
].first_page_number
;
121 page_number
<= page_ranges
[index
].last_page_number
; ++page_number
) {
122 page_numbers
.push_back(page_number
);
128 #if defined(OS_LINUX)
130 PP_Instance g_last_instance_id
;
132 struct PDFFontSubstitution
{
133 const char* pdf_name
;
139 PP_BrowserFont_Trusted_Weight
WeightToBrowserFontTrustedWeight(int weight
) {
140 COMPILE_ASSERT(PP_BROWSERFONT_TRUSTED_WEIGHT_100
== 0,
141 PP_BrowserFont_Trusted_Weight_Min
);
142 COMPILE_ASSERT(PP_BROWSERFONT_TRUSTED_WEIGHT_900
== 8,
143 PP_BrowserFont_Trusted_Weight_Max
);
144 const int kMinimumWeight
= 100;
145 const int kMaximumWeight
= 900;
146 int normalized_weight
=
147 std::min(std::max(weight
, kMinimumWeight
), kMaximumWeight
);
148 normalized_weight
= (normalized_weight
/ 100) - 1;
149 return static_cast<PP_BrowserFont_Trusted_Weight
>(normalized_weight
);
152 // This list is for CPWL_FontMap::GetDefaultFontByCharset().
153 // We pretend to have these font natively and let the browser (or underlying
154 // fontconfig) to pick the proper font on the system.
155 void EnumFonts(struct _FPDF_SYSFONTINFO
* sysfontinfo
, void* mapper
) {
156 FPDF_AddInstalledFont(mapper
, "Arial", FXFONT_DEFAULT_CHARSET
);
159 while (CPWL_FontMap::defaultTTFMap
[i
].charset
!= -1) {
160 FPDF_AddInstalledFont(mapper
,
161 CPWL_FontMap::defaultTTFMap
[i
].fontname
,
162 CPWL_FontMap::defaultTTFMap
[i
].charset
);
167 const PDFFontSubstitution PDFFontSubstitutions
[] = {
168 {"Courier", "Courier New", false, false},
169 {"Courier-Bold", "Courier New", true, false},
170 {"Courier-BoldOblique", "Courier New", true, true},
171 {"Courier-Oblique", "Courier New", false, true},
172 {"Helvetica", "Arial", false, false},
173 {"Helvetica-Bold", "Arial", true, false},
174 {"Helvetica-BoldOblique", "Arial", true, true},
175 {"Helvetica-Oblique", "Arial", false, true},
176 {"Times-Roman", "Times New Roman", false, false},
177 {"Times-Bold", "Times New Roman", true, false},
178 {"Times-BoldItalic", "Times New Roman", true, true},
179 {"Times-Italic", "Times New Roman", false, true},
181 // MS P?(Mincho|Gothic) are the most notable fonts in Japanese PDF files
182 // without embedding the glyphs. Sometimes the font names are encoded
183 // in Japanese Windows's locale (CP932/Shift_JIS) without space.
184 // Most Linux systems don't have the exact font, but for outsourcing
185 // fontconfig to find substitutable font in the system, we pass ASCII
187 {"MS-PGothic", "MS PGothic", false, false},
188 {"MS-Gothic", "MS Gothic", false, false},
189 {"MS-PMincho", "MS PMincho", false, false},
190 {"MS-Mincho", "MS Mincho", false, false},
191 // MS PGothic in Shift_JIS encoding.
192 {"\x82\x6C\x82\x72\x82\x6F\x83\x53\x83\x56\x83\x62\x83\x4E",
193 "MS PGothic", false, false},
194 // MS Gothic in Shift_JIS encoding.
195 {"\x82\x6C\x82\x72\x83\x53\x83\x56\x83\x62\x83\x4E",
196 "MS Gothic", false, false},
197 // MS PMincho in Shift_JIS encoding.
198 {"\x82\x6C\x82\x72\x82\x6F\x96\xBE\x92\xA9",
199 "MS PMincho", false, false},
200 // MS Mincho in Shift_JIS encoding.
201 {"\x82\x6C\x82\x72\x96\xBE\x92\xA9",
202 "MS Mincho", false, false},
205 void* MapFont(struct _FPDF_SYSFONTINFO
*, int weight
, int italic
,
206 int charset
, int pitch_family
, const char* face
, int* exact
) {
207 pp::BrowserFontDescription description
;
209 // Pretend the system does not have the Symbol font to force a fallback to
210 // the built in Symbol font in CFX_FontMapper::FindSubstFont().
211 if (strcmp(face
, "Symbol") == 0)
214 if (pitch_family
& FXFONT_FF_FIXEDPITCH
) {
215 description
.set_family(PP_BROWSERFONT_TRUSTED_FAMILY_MONOSPACE
);
216 } else if (pitch_family
& FXFONT_FF_ROMAN
) {
217 description
.set_family(PP_BROWSERFONT_TRUSTED_FAMILY_SERIF
);
220 // Map from the standard PDF fonts to TrueType font names.
222 for (i
= 0; i
< arraysize(PDFFontSubstitutions
); ++i
) {
223 if (strcmp(face
, PDFFontSubstitutions
[i
].pdf_name
) == 0) {
224 description
.set_face(PDFFontSubstitutions
[i
].face
);
225 if (PDFFontSubstitutions
[i
].bold
)
226 description
.set_weight(PP_BROWSERFONT_TRUSTED_WEIGHT_BOLD
);
227 if (PDFFontSubstitutions
[i
].italic
)
228 description
.set_italic(true);
233 if (i
== arraysize(PDFFontSubstitutions
)) {
234 // TODO(kochi): Pass the face in UTF-8. If face is not encoded in UTF-8,
235 // convert to UTF-8 before passing.
236 description
.set_face(face
);
238 description
.set_weight(WeightToBrowserFontTrustedWeight(weight
));
239 description
.set_italic(italic
> 0);
242 if (!pp::PDF::IsAvailable()) {
247 PP_Resource font_resource
= pp::PDF::GetFontFileWithFallback(
248 pp::InstanceHandle(g_last_instance_id
),
249 &description
.pp_font_description(),
250 static_cast<PP_PrivateFontCharset
>(charset
));
251 long res_id
= font_resource
;
252 return reinterpret_cast<void*>(res_id
);
255 unsigned long GetFontData(struct _FPDF_SYSFONTINFO
*, void* font_id
,
256 unsigned int table
, unsigned char* buffer
,
257 unsigned long buf_size
) {
258 if (!pp::PDF::IsAvailable()) {
263 uint32_t size
= buf_size
;
264 long res_id
= reinterpret_cast<long>(font_id
);
265 if (!pp::PDF::GetFontTableForPrivateFontFile(res_id
, table
, buffer
, &size
))
270 void DeleteFont(struct _FPDF_SYSFONTINFO
*, void* font_id
) {
271 long res_id
= reinterpret_cast<long>(font_id
);
272 pp::Module::Get()->core()->ReleaseResource(res_id
);
275 FPDF_SYSFONTINFO g_font_info
= {
286 #endif // defined(OS_LINUX)
288 void OOM_Handler(_OOM_INFO
*) {
289 // Kill the process. This is important for security, since the code doesn't
290 // NULL-check many memory allocations. If a malloc fails, returns NULL, and
291 // the buffer is then used, it provides a handy mapping of memory starting at
292 // address 0 for an attacker to utilize.
296 OOM_INFO g_oom_info
= {
301 PDFiumEngine
* g_engine_for_unsupported
;
303 void Unsupported_Handler(UNSUPPORT_INFO
*, int type
) {
304 if (!g_engine_for_unsupported
) {
309 g_engine_for_unsupported
->UnsupportedFeature(type
);
312 UNSUPPORT_INFO g_unsuppored_info
= {
317 // Set the destination page size and content area in points based on source
318 // page rotation and orientation.
320 // |rotated| True if source page is rotated 90 degree or 270 degree.
321 // |is_src_page_landscape| is true if the source page orientation is landscape.
322 // |page_size| has the actual destination page size in points.
323 // |content_rect| has the actual destination page printable area values in
325 void SetPageSizeAndContentRect(bool rotated
,
326 bool is_src_page_landscape
,
328 pp::Rect
* content_rect
) {
329 bool is_dst_page_landscape
= page_size
->width() > page_size
->height();
330 bool page_orientation_mismatched
= is_src_page_landscape
!=
331 is_dst_page_landscape
;
332 bool rotate_dst_page
= rotated
^ page_orientation_mismatched
;
333 if (rotate_dst_page
) {
334 page_size
->SetSize(page_size
->height(), page_size
->width());
335 content_rect
->SetRect(content_rect
->y(), content_rect
->x(),
336 content_rect
->height(), content_rect
->width());
340 // Calculate the scale factor between |content_rect| and a page of size
341 // |src_width| x |src_height|.
343 // |scale_to_fit| is true, if we need to calculate the scale factor.
344 // |content_rect| specifies the printable area of the destination page, with
345 // origin at left-bottom. Values are in points.
346 // |src_width| specifies the source page width in points.
347 // |src_height| specifies the source page height in points.
348 // |rotated| True if source page is rotated 90 degree or 270 degree.
349 double CalculateScaleFactor(bool scale_to_fit
,
350 const pp::Rect
& content_rect
,
351 double src_width
, double src_height
, bool rotated
) {
352 if (!scale_to_fit
|| src_width
== 0 || src_height
== 0)
355 double actual_source_page_width
= rotated
? src_height
: src_width
;
356 double actual_source_page_height
= rotated
? src_width
: src_height
;
357 double ratio_x
= static_cast<double>(content_rect
.width()) /
358 actual_source_page_width
;
359 double ratio_y
= static_cast<double>(content_rect
.height()) /
360 actual_source_page_height
;
361 return std::min(ratio_x
, ratio_y
);
364 // Compute source clip box boundaries based on the crop box / media box of
365 // source page and scale factor.
367 // |page| Handle to the source page. Returned by FPDF_LoadPage function.
368 // |scale_factor| specifies the scale factor that should be applied to source
369 // clip box boundaries.
370 // |rotated| True if source page is rotated 90 degree or 270 degree.
371 // |clip_box| out param to hold the computed source clip box values.
372 void CalculateClipBoxBoundary(FPDF_PAGE page
, double scale_factor
, bool rotated
,
374 if (!FPDFPage_GetCropBox(page
, &clip_box
->left
, &clip_box
->bottom
,
375 &clip_box
->right
, &clip_box
->top
)) {
376 if (!FPDFPage_GetMediaBox(page
, &clip_box
->left
, &clip_box
->bottom
,
377 &clip_box
->right
, &clip_box
->top
)) {
378 // Make the default size to be letter size (8.5" X 11"). We are just
379 // following the PDFium way of handling these corner cases. PDFium always
380 // consider US-Letter as the default page size.
381 float paper_width
= 612;
382 float paper_height
= 792;
384 clip_box
->bottom
= 0;
385 clip_box
->right
= rotated
? paper_height
: paper_width
;
386 clip_box
->top
= rotated
? paper_width
: paper_height
;
389 clip_box
->left
*= scale_factor
;
390 clip_box
->right
*= scale_factor
;
391 clip_box
->bottom
*= scale_factor
;
392 clip_box
->top
*= scale_factor
;
395 // Calculate the clip box translation offset for a page that does need to be
396 // scaled. All parameters are in points.
398 // |content_rect| specifies the printable area of the destination page, with
399 // origin at left-bottom.
400 // |source_clip_box| specifies the source clip box positions, relative to
401 // origin at left-bottom.
402 // |offset_x| and |offset_y| will contain the final translation offsets for the
403 // source clip box, relative to origin at left-bottom.
404 void CalculateScaledClipBoxOffset(const pp::Rect
& content_rect
,
405 const ClipBox
& source_clip_box
,
406 double* offset_x
, double* offset_y
) {
407 const float clip_box_width
= source_clip_box
.right
- source_clip_box
.left
;
408 const float clip_box_height
= source_clip_box
.top
- source_clip_box
.bottom
;
410 // Center the intended clip region to real clip region.
411 *offset_x
= (content_rect
.width() - clip_box_width
) / 2 + content_rect
.x() -
412 source_clip_box
.left
;
413 *offset_y
= (content_rect
.height() - clip_box_height
) / 2 + content_rect
.y() -
414 source_clip_box
.bottom
;
417 // Calculate the clip box offset for a page that does not need to be scaled.
418 // All parameters are in points.
420 // |content_rect| specifies the printable area of the destination page, with
421 // origin at left-bottom.
422 // |rotation| specifies the source page rotation values which are N / 90
424 // |page_width| specifies the screen destination page width.
425 // |page_height| specifies the screen destination page height.
426 // |source_clip_box| specifies the source clip box positions, relative to origin
428 // |offset_x| and |offset_y| will contain the final translation offsets for the
429 // source clip box, relative to origin at left-bottom.
430 void CalculateNonScaledClipBoxOffset(const pp::Rect
& content_rect
, int rotation
,
431 int page_width
, int page_height
,
432 const ClipBox
& source_clip_box
,
433 double* offset_x
, double* offset_y
) {
434 // Align the intended clip region to left-top corner of real clip region.
437 *offset_x
= -1 * source_clip_box
.left
;
438 *offset_y
= page_height
- source_clip_box
.top
;
442 *offset_y
= -1 * source_clip_box
.bottom
;
445 *offset_x
= page_width
- source_clip_box
.right
;
449 *offset_x
= page_height
- source_clip_box
.right
;
450 *offset_y
= page_width
- source_clip_box
.top
;
458 // Do an in-place transformation of objects on |page|. Translate all objects on
459 // |page| in |source_clip_box| by (|offset_x|, |offset_y|) and scale them by
462 // |page| Handle to the page. Returned by FPDF_LoadPage function.
463 // |source_clip_box| specifies the source clip box positions, relative to
464 // origin at left-bottom.
465 // |scale_factor| specifies the scale factor that should be applied to page
467 // |offset_x| and |offset_y| specifies the translation offsets for the page
468 // objects, relative to origin at left-bottom.
470 void TransformPageObjects(FPDF_PAGE page
, const ClipBox
& source_clip_box
,
471 const double scale_factor
, double offset_x
,
473 const int obj_count
= FPDFPage_CountObject(page
);
475 // Create a new clip path.
476 FPDF_CLIPPATH clip_path
= FPDF_CreateClipPath(
477 source_clip_box
.left
+ offset_x
, source_clip_box
.bottom
+ offset_y
,
478 source_clip_box
.right
+ offset_x
, source_clip_box
.top
+ offset_y
);
480 for (int obj_idx
= 0; obj_idx
< obj_count
; ++obj_idx
) {
481 FPDF_PAGEOBJECT page_obj
= FPDFPage_GetObject(page
, obj_idx
);
482 FPDFPageObj_Transform(page_obj
, scale_factor
, 0, 0, scale_factor
,
484 FPDFPageObj_TransformClipPath(page_obj
, scale_factor
, 0, 0, scale_factor
,
487 FPDFPage_TransformAnnots(page
, scale_factor
, 0, 0, scale_factor
,
489 FPDFPage_GenerateContent(page
);
491 // Add a extra clip path to the new pdf page here.
492 FPDFPage_InsertClipPath(page
, clip_path
);
494 // Destroy the clip path.
495 FPDF_DestroyClipPath(clip_path
);
498 bool InitializeSDK(void* data
) {
499 FPDF_InitLibrary(data
);
501 #if defined(OS_LINUX)
502 // Font loading doesn't work in the renderer sandbox in Linux.
503 FPDF_SetSystemFontInfo(&g_font_info
);
506 FSDK_SetOOMHandler(&g_oom_info
);
507 FSDK_SetUnSpObjProcessHandler(&g_unsuppored_info
);
513 FPDF_DestroyLibrary();
516 PDFEngine
* PDFEngine::Create(PDFEngine::Client
* client
) {
517 return new PDFiumEngine(client
);
520 PDFiumEngine::PDFiumEngine(PDFEngine::Client
* client
)
523 current_rotation_(0),
525 password_tries_remaining_(0),
528 defer_page_unload_(false),
530 next_page_to_search_(-1),
531 last_page_to_search_(-1),
532 last_character_index_to_search_(-1),
533 current_find_index_(-1),
535 fpdf_availability_(NULL
),
537 last_page_mouse_down_(-1),
538 first_visible_page_(-1),
539 most_visible_page_(-1),
540 called_do_document_action_(false),
541 render_grayscale_(false),
542 progressive_paint_timeout_(0),
543 getting_password_(false) {
544 find_factory_
.Initialize(this);
545 password_factory_
.Initialize(this);
547 file_access_
.m_FileLen
= 0;
548 file_access_
.m_GetBlock
= &GetBlock
;
549 file_access_
.m_Param
= &doc_loader_
;
551 file_availability_
.version
= 1;
552 file_availability_
.IsDataAvail
= &IsDataAvail
;
553 file_availability_
.loader
= &doc_loader_
;
555 download_hints_
.version
= 1;
556 download_hints_
.AddSegment
= &AddSegment
;
557 download_hints_
.loader
= &doc_loader_
;
559 // Initialize FPDF_FORMFILLINFO member variables. Deriving from this struct
560 // allows the static callbacks to be able to cast the FPDF_FORMFILLINFO in
561 // callbacks to ourself instead of maintaining a map of them to
563 FPDF_FORMFILLINFO::version
= 1;
564 FPDF_FORMFILLINFO::m_pJsPlatform
= this;
565 FPDF_FORMFILLINFO::Release
= NULL
;
566 FPDF_FORMFILLINFO::FFI_Invalidate
= Form_Invalidate
;
567 FPDF_FORMFILLINFO::FFI_OutputSelectedRect
= Form_OutputSelectedRect
;
568 FPDF_FORMFILLINFO::FFI_SetCursor
= Form_SetCursor
;
569 FPDF_FORMFILLINFO::FFI_SetTimer
= Form_SetTimer
;
570 FPDF_FORMFILLINFO::FFI_KillTimer
= Form_KillTimer
;
571 FPDF_FORMFILLINFO::FFI_GetLocalTime
= Form_GetLocalTime
;
572 FPDF_FORMFILLINFO::FFI_OnChange
= Form_OnChange
;
573 FPDF_FORMFILLINFO::FFI_GetPage
= Form_GetPage
;
574 FPDF_FORMFILLINFO::FFI_GetCurrentPage
= Form_GetCurrentPage
;
575 FPDF_FORMFILLINFO::FFI_GetRotation
= Form_GetRotation
;
576 FPDF_FORMFILLINFO::FFI_ExecuteNamedAction
= Form_ExecuteNamedAction
;
577 FPDF_FORMFILLINFO::FFI_SetTextFieldFocus
= Form_SetTextFieldFocus
;
578 FPDF_FORMFILLINFO::FFI_DoURIAction
= Form_DoURIAction
;
579 FPDF_FORMFILLINFO::FFI_DoGoToAction
= Form_DoGoToAction
;
581 IPDF_JSPLATFORM::version
= 1;
582 IPDF_JSPLATFORM::app_alert
= Form_Alert
;
583 IPDF_JSPLATFORM::app_beep
= Form_Beep
;
584 IPDF_JSPLATFORM::app_response
= Form_Response
;
585 IPDF_JSPLATFORM::Doc_getFilePath
= Form_GetFilePath
;
586 IPDF_JSPLATFORM::Doc_mail
= Form_Mail
;
587 IPDF_JSPLATFORM::Doc_print
= Form_Print
;
588 IPDF_JSPLATFORM::Doc_submitForm
= Form_SubmitForm
;
589 IPDF_JSPLATFORM::Doc_gotoPage
= Form_GotoPage
;
590 IPDF_JSPLATFORM::Field_browse
= Form_Browse
;
592 IFSDK_PAUSE::version
= 1;
593 IFSDK_PAUSE::user
= NULL
;
594 IFSDK_PAUSE::NeedToPauseNow
= Pause_NeedToPauseNow
;
597 PDFiumEngine::~PDFiumEngine() {
598 STLDeleteElements(&pages_
);
601 FORM_DoDocumentAAction(form_
, FPDFDOC_AACTION_WC
);
602 FPDFDOC_ExitFormFillEnviroument(form_
);
604 FPDF_CloseDocument(doc_
);
607 if (fpdf_availability_
)
608 FPDFAvail_Destroy(fpdf_availability_
);
611 int PDFiumEngine::GetBlock(void* param
, unsigned long position
,
612 unsigned char* buffer
, unsigned long size
) {
613 DocumentLoader
* loader
= static_cast<DocumentLoader
*>(param
);
614 return loader
->GetBlock(position
, size
, buffer
);
617 bool PDFiumEngine::IsDataAvail(FX_FILEAVAIL
* param
,
618 size_t offset
, size_t size
) {
619 PDFiumEngine::FileAvail
* file_avail
=
620 static_cast<PDFiumEngine::FileAvail
*>(param
);
621 return file_avail
->loader
->IsDataAvailable(offset
, size
);
624 void PDFiumEngine::AddSegment(FX_DOWNLOADHINTS
* param
,
625 size_t offset
, size_t size
) {
626 PDFiumEngine::DownloadHints
* download_hints
=
627 static_cast<PDFiumEngine::DownloadHints
*>(param
);
628 return download_hints
->loader
->RequestData(offset
, size
);
631 bool PDFiumEngine::New(const char* url
) {
633 headers_
= std::string();
637 bool PDFiumEngine::New(const char* url
,
638 const char* headers
) {
641 headers_
= std::string();
647 void PDFiumEngine::PageOffsetUpdated(const pp::Point
& page_offset
) {
648 page_offset_
= page_offset
;
651 void PDFiumEngine::PluginSizeUpdated(const pp::Size
& size
) {
655 CalculateVisiblePages();
658 void PDFiumEngine::ScrolledToXPosition(int position
) {
661 int old_x
= position_
.x();
662 position_
.set_x(position
);
663 CalculateVisiblePages();
664 client_
->Scroll(pp::Point(old_x
- position
, 0));
667 void PDFiumEngine::ScrolledToYPosition(int position
) {
670 int old_y
= position_
.y();
671 position_
.set_y(position
);
672 CalculateVisiblePages();
673 client_
->Scroll(pp::Point(0, old_y
- position
));
676 void PDFiumEngine::PrePaint() {
677 for (size_t i
= 0; i
< progressive_paints_
.size(); ++i
)
678 progressive_paints_
[i
].painted_
= false;
681 void PDFiumEngine::Paint(const pp::Rect
& rect
,
682 pp::ImageData
* image_data
,
683 std::vector
<pp::Rect
>* ready
,
684 std::vector
<pp::Rect
>* pending
) {
685 pp::Rect leftover
= rect
;
686 for (size_t i
= 0; i
< visible_pages_
.size(); ++i
) {
687 int index
= visible_pages_
[i
];
688 pp::Rect page_rect
= pages_
[index
]->rect();
689 // Convert the current page's rectangle to screen rectangle. We do this
690 // instead of the reverse (converting the dirty rectangle from screen to
691 // page coordinates) because then we'd have to convert back to screen
692 // coordinates, and the rounding errors sometime leave pixels dirty or even
693 // move the text up or down a pixel when zoomed.
694 pp::Rect page_rect_in_screen
= GetPageScreenRect(index
);
695 pp::Rect dirty_in_screen
= page_rect_in_screen
.Intersect(leftover
);
696 if (dirty_in_screen
.IsEmpty())
699 leftover
= leftover
.Subtract(dirty_in_screen
);
701 if (pages_
[index
]->available()) {
702 int progressive
= GetProgressiveIndex(index
);
703 if (progressive
!= -1 &&
704 progressive_paints_
[progressive
].rect
!= dirty_in_screen
) {
705 // The PDFium code can only handle one progressive paint at a time, so
706 // queue this up. Previously we used to merge the rects when this
707 // happened, but it made scrolling up on complex PDFs very slow since
708 // there would be a damaged rect at the top (from scroll) and at the
709 // bottom (from toolbar).
710 pending
->push_back(dirty_in_screen
);
714 if (progressive
== -1) {
715 progressive
= StartPaint(index
, dirty_in_screen
);
716 progressive_paint_timeout_
= kMaxInitialProgressivePaintTimeMs
;
718 progressive_paint_timeout_
= kMaxProgressivePaintTimeMs
;
721 progressive_paints_
[progressive
].painted_
= true;
722 if (ContinuePaint(progressive
, image_data
)) {
723 FinishPaint(progressive
, image_data
);
724 ready
->push_back(dirty_in_screen
);
726 pending
->push_back(dirty_in_screen
);
729 PaintUnavailablePage(index
, dirty_in_screen
, image_data
);
730 ready
->push_back(dirty_in_screen
);
735 void PDFiumEngine::PostPaint() {
736 for (size_t i
= 0; i
< progressive_paints_
.size(); ++i
) {
737 if (progressive_paints_
[i
].painted_
)
740 // This rectangle must have been merged with another one, that's why we
741 // weren't asked to paint it. Remove it or otherwise we'll never finish
743 FPDF_RenderPage_Close(
744 pages_
[progressive_paints_
[i
].page_index
]->GetPage());
745 FPDFBitmap_Destroy(progressive_paints_
[i
].bitmap
);
746 progressive_paints_
.erase(progressive_paints_
.begin() + i
);
751 bool PDFiumEngine::HandleDocumentLoad(const pp::URLLoader
& loader
) {
752 password_tries_remaining_
= kMaxPasswordTries
;
753 return doc_loader_
.Init(loader
, url_
, headers_
);
756 pp::Instance
* PDFiumEngine::GetPluginInstance() {
757 return client_
->GetPluginInstance();
760 pp::URLLoader
PDFiumEngine::CreateURLLoader() {
761 return client_
->CreateURLLoader();
764 void PDFiumEngine::AppendPage(PDFEngine
* engine
, int index
) {
765 // Unload and delete the blank page before appending.
766 pages_
[index
]->Unload();
767 pages_
[index
]->set_calculated_links(false);
768 pp::Size curr_page_size
= GetPageSize(index
);
769 FPDFPage_Delete(doc_
, index
);
770 FPDF_ImportPages(doc_
,
771 static_cast<PDFiumEngine
*>(engine
)->doc(),
774 pp::Size new_page_size
= GetPageSize(index
);
775 if (curr_page_size
!= new_page_size
)
777 client_
->Invalidate(GetPageScreenRect(index
));
780 pp::Point
PDFiumEngine::GetScrollPosition() {
784 void PDFiumEngine::SetScrollPosition(const pp::Point
& position
) {
785 position_
= position
;
788 bool PDFiumEngine::IsProgressiveLoad() {
789 return doc_loader_
.is_partial_document();
792 void PDFiumEngine::OnPartialDocumentLoaded() {
793 file_access_
.m_FileLen
= doc_loader_
.document_size();
794 fpdf_availability_
= FPDFAvail_Create(&file_availability_
, &file_access_
);
795 DCHECK(fpdf_availability_
);
797 // Currently engine does not deal efficiently with some non-linearized files.
798 // See http://code.google.com/p/chromium/issues/detail?id=59400
799 // To improve user experience we download entire file for non-linearized PDF.
800 if (!FPDFAvail_IsLinearized(fpdf_availability_
)) {
801 doc_loader_
.RequestData(0, doc_loader_
.document_size());
808 void PDFiumEngine::OnPendingRequestComplete() {
809 if (!doc_
|| !form_
) {
814 // LoadDocument() will result in |pending_pages_| being reset so there's no
815 // need to run the code below in that case.
816 bool update_pages
= false;
817 std::vector
<int> still_pending
;
818 for (size_t i
= 0; i
< pending_pages_
.size(); ++i
) {
819 if (CheckPageAvailable(pending_pages_
[i
], &still_pending
)) {
821 if (IsPageVisible(pending_pages_
[i
]))
822 client_
->Invalidate(GetPageScreenRect(pending_pages_
[i
]));
825 pending_pages_
.swap(still_pending
);
830 void PDFiumEngine::OnNewDataAvailable() {
831 client_
->DocumentLoadProgress(doc_loader_
.GetAvailableData(),
832 doc_loader_
.document_size());
835 void PDFiumEngine::OnDocumentComplete() {
836 if (!doc_
|| !form_
) {
837 file_access_
.m_FileLen
= doc_loader_
.document_size();
842 bool need_update
= false;
843 for (size_t i
= 0; i
< pages_
.size(); ++i
) {
844 if (pages_
[i
]->available())
847 pages_
[i
]->set_available(true);
848 // We still need to call IsPageAvail() even if the whole document is
849 // already downloaded.
850 FPDFAvail_IsPageAvail(fpdf_availability_
, i
, &download_hints_
);
852 if (IsPageVisible(i
))
853 client_
->Invalidate(GetPageScreenRect(i
));
858 FinishLoadingDocument();
861 void PDFiumEngine::FinishLoadingDocument() {
862 DCHECK(doc_loader_
.IsDocumentComplete() && doc_
);
863 if (called_do_document_action_
)
865 called_do_document_action_
= true;
867 // These can only be called now, as the JS might end up needing a page.
868 FORM_DoDocumentJSAction(form_
);
869 FORM_DoDocumentOpenAction(form_
);
870 if (most_visible_page_
!= -1) {
871 FPDF_PAGE new_page
= pages_
[most_visible_page_
]->GetPage();
872 FORM_DoPageAAction(new_page
, form_
, FPDFPAGE_AACTION_OPEN
);
875 if (doc_
) // This can only happen if loading |doc_| fails.
876 client_
->DocumentLoadComplete(pages_
.size());
879 void PDFiumEngine::UnsupportedFeature(int type
) {
882 case FPDF_UNSP_DOC_XFAFORM
:
885 case FPDF_UNSP_DOC_PORTABLECOLLECTION
:
886 feature
= "Portfolios_Packages";
888 case FPDF_UNSP_DOC_ATTACHMENT
:
889 case FPDF_UNSP_ANNOT_ATTACHMENT
:
890 feature
= "Attachment";
892 case FPDF_UNSP_DOC_SECURITY
:
893 feature
= "Rights_Management";
895 case FPDF_UNSP_DOC_SHAREDREVIEW
:
896 feature
= "Shared_Review";
898 case FPDF_UNSP_DOC_SHAREDFORM_ACROBAT
:
899 case FPDF_UNSP_DOC_SHAREDFORM_FILESYSTEM
:
900 case FPDF_UNSP_DOC_SHAREDFORM_EMAIL
:
901 feature
= "Shared_Form";
903 case FPDF_UNSP_ANNOT_3DANNOT
:
906 case FPDF_UNSP_ANNOT_MOVIE
:
909 case FPDF_UNSP_ANNOT_SOUND
:
912 case FPDF_UNSP_ANNOT_SCREEN_MEDIA
:
913 case FPDF_UNSP_ANNOT_SCREEN_RICHMEDIA
:
916 case FPDF_UNSP_ANNOT_SIG
:
917 feature
= "Digital_Signature";
920 client_
->DocumentHasUnsupportedFeature(feature
);
923 void PDFiumEngine::ContinueFind(int32_t result
) {
924 StartFind(current_find_text_
.c_str(), !!result
);
927 bool PDFiumEngine::HandleEvent(const pp::InputEvent
& event
) {
928 DCHECK(!defer_page_unload_
);
929 defer_page_unload_
= true;
931 switch (event
.GetType()) {
932 case PP_INPUTEVENT_TYPE_MOUSEDOWN
:
933 rv
= OnMouseDown(pp::MouseInputEvent(event
));
935 case PP_INPUTEVENT_TYPE_MOUSEUP
:
936 rv
= OnMouseUp(pp::MouseInputEvent(event
));
938 case PP_INPUTEVENT_TYPE_MOUSEMOVE
:
939 rv
= OnMouseMove(pp::MouseInputEvent(event
));
941 case PP_INPUTEVENT_TYPE_KEYDOWN
:
942 rv
= OnKeyDown(pp::KeyboardInputEvent(event
));
944 case PP_INPUTEVENT_TYPE_KEYUP
:
945 rv
= OnKeyUp(pp::KeyboardInputEvent(event
));
947 case PP_INPUTEVENT_TYPE_CHAR
:
948 rv
= OnChar(pp::KeyboardInputEvent(event
));
954 DCHECK(defer_page_unload_
);
955 defer_page_unload_
= false;
956 for (size_t i
= 0; i
< deferred_page_unloads_
.size(); ++i
)
957 pages_
[deferred_page_unloads_
[i
]]->Unload();
958 deferred_page_unloads_
.clear();
962 uint32_t PDFiumEngine::QuerySupportedPrintOutputFormats() {
963 if (!HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
))
965 return PP_PRINTOUTPUTFORMAT_PDF
;
968 void PDFiumEngine::PrintBegin() {
969 FORM_DoDocumentAAction(form_
, FPDFDOC_AACTION_WP
);
972 pp::Resource
PDFiumEngine::PrintPages(
973 const PP_PrintPageNumberRange_Dev
* page_ranges
, uint32_t page_range_count
,
974 const PP_PrintSettings_Dev
& print_settings
) {
975 if (HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY
))
976 return PrintPagesAsPDF(page_ranges
, page_range_count
, print_settings
);
977 else if (HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
))
978 return PrintPagesAsRasterPDF(page_ranges
, page_range_count
, print_settings
);
979 return pp::Resource();
982 pp::Buffer_Dev
PDFiumEngine::PrintPagesAsRasterPDF(
983 const PP_PrintPageNumberRange_Dev
* page_ranges
, uint32_t page_range_count
,
984 const PP_PrintSettings_Dev
& print_settings
) {
985 if (!page_range_count
)
986 return pp::Buffer_Dev();
988 // If document is not downloaded yet, disable printing.
989 if (doc_
&& !doc_loader_
.IsDocumentComplete())
990 return pp::Buffer_Dev();
992 FPDF_DOCUMENT output_doc
= FPDF_CreateNewDocument();
994 return pp::Buffer_Dev();
996 SaveSelectedFormForPrint();
998 std::vector
<PDFiumPage
> pages_to_print
;
999 // width and height of source PDF pages.
1000 std::vector
<std::pair
<double, double> > source_page_sizes
;
1001 // Collect pages to print and sizes of source pages.
1002 std::vector
<uint32_t> page_numbers
=
1003 GetPageNumbersFromPrintPageNumberRange(page_ranges
, page_range_count
);
1004 for (size_t i
= 0; i
< page_numbers
.size(); ++i
) {
1005 uint32_t page_number
= page_numbers
[i
];
1006 FPDF_PAGE pdf_page
= FPDF_LoadPage(doc_
, page_number
);
1007 double source_page_width
= FPDF_GetPageWidth(pdf_page
);
1008 double source_page_height
= FPDF_GetPageHeight(pdf_page
);
1009 source_page_sizes
.push_back(std::make_pair(source_page_width
,
1010 source_page_height
));
1012 int width_in_pixels
= ConvertUnit(source_page_width
,
1013 static_cast<int>(kPointsPerInch
),
1014 print_settings
.dpi
);
1015 int height_in_pixels
= ConvertUnit(source_page_height
,
1016 static_cast<int>(kPointsPerInch
),
1017 print_settings
.dpi
);
1019 pp::Rect
rect(width_in_pixels
, height_in_pixels
);
1020 pages_to_print
.push_back(PDFiumPage(this, page_number
, rect
, true));
1021 FPDF_ClosePage(pdf_page
);
1024 #if defined(OS_LINUX)
1025 g_last_instance_id
= client_
->GetPluginInstance()->pp_instance();
1029 for (; i
< pages_to_print
.size(); ++i
) {
1030 double source_page_width
= source_page_sizes
[i
].first
;
1031 double source_page_height
= source_page_sizes
[i
].second
;
1032 const pp::Size
& bitmap_size(pages_to_print
[i
].rect().size());
1034 // Use temp_doc to compress image by saving PDF to buffer.
1035 FPDF_DOCUMENT temp_doc
= FPDF_CreateNewDocument();
1039 FPDF_PAGE output_page
= FPDFPage_New(temp_doc
, 0, source_page_width
,
1040 source_page_height
);
1042 pp::ImageData image
= pp::ImageData(client_
->GetPluginInstance(),
1043 PP_IMAGEDATAFORMAT_BGRA_PREMUL
,
1047 FPDF_BITMAP bitmap
= FPDFBitmap_CreateEx(bitmap_size
.width(),
1048 bitmap_size
.height(),
1054 FPDFBitmap_FillRect(bitmap
, 0, 0, bitmap_size
.width(),
1055 bitmap_size
.height(), 255, 255, 255, 255);
1057 pp::Rect page_rect
= pages_to_print
[i
].rect();
1058 FPDF_RenderPageBitmap(bitmap
, pages_to_print
[i
].GetPrintPage(),
1059 page_rect
.x(), page_rect
.y(),
1060 page_rect
.width(), page_rect
.height(),
1061 print_settings
.orientation
,
1062 FPDF_ANNOT
| FPDF_PRINTING
| FPDF_NO_CATCH
);
1064 double ratio_x
= (static_cast<double>(bitmap_size
.width()) *
1065 kPointsPerInch
) / print_settings
.dpi
;
1066 double ratio_y
= (static_cast<double>(bitmap_size
.height()) *
1067 kPointsPerInch
) / print_settings
.dpi
;
1069 // Add the bitmap to an image object and add the image object to the output
1071 FPDF_PAGEOBJECT img_obj
= FPDFPageObj_NewImgeObj(output_doc
);
1072 FPDFImageObj_SetBitmap(&output_page
, 1, img_obj
, bitmap
);
1073 FPDFImageObj_SetMatrix(img_obj
, ratio_x
, 0, 0, ratio_y
, 0, 0);
1074 FPDFPage_InsertObject(output_page
, img_obj
);
1075 FPDFPage_GenerateContent(output_page
);
1076 FPDF_ClosePage(output_page
);
1078 pages_to_print
[i
].ClosePrintPage();
1079 FPDFBitmap_Destroy(bitmap
);
1081 pp::Buffer_Dev buffer
= GetFlattenedPrintData(temp_doc
);
1082 FPDF_CloseDocument(temp_doc
);
1084 PDFiumMemBufferFileRead
file_read(buffer
.data(), buffer
.size());
1085 temp_doc
= FPDF_LoadCustomDocument(&file_read
, NULL
);
1089 FPDF_BOOL imported
= FPDF_ImportPages(output_doc
, temp_doc
, "1", i
);
1090 FPDF_CloseDocument(temp_doc
);
1095 pp::Buffer_Dev buffer
;
1096 if (i
== pages_to_print
.size()) {
1097 FPDF_CopyViewerPreferences(output_doc
, doc_
);
1098 FitContentsToPrintableAreaIfRequired(output_doc
, print_settings
);
1099 // Now flatten all the output pages.
1100 buffer
= GetFlattenedPrintData(output_doc
);
1102 FPDF_CloseDocument(output_doc
);
1106 pp::Buffer_Dev
PDFiumEngine::GetFlattenedPrintData(const FPDF_DOCUMENT
& doc
) {
1107 int page_count
= FPDF_GetPageCount(doc
);
1108 bool flatten_succeeded
= true;
1109 for (int i
= 0; i
< page_count
; ++i
) {
1110 FPDF_PAGE page
= FPDF_LoadPage(doc
, i
);
1113 int flatten_ret
= FPDFPage_Flatten(page
, FLAT_PRINT
);
1114 FPDF_ClosePage(page
);
1115 if (flatten_ret
== FLATTEN_FAIL
) {
1116 flatten_succeeded
= false;
1120 flatten_succeeded
= false;
1124 if (!flatten_succeeded
) {
1125 FPDF_CloseDocument(doc
);
1126 return pp::Buffer_Dev();
1129 pp::Buffer_Dev buffer
;
1130 PDFiumMemBufferFileWrite output_file_write
;
1131 if (FPDF_SaveAsCopy(doc
, &output_file_write
, 0)) {
1132 buffer
= pp::Buffer_Dev(
1133 client_
->GetPluginInstance(), output_file_write
.size());
1134 if (!buffer
.is_null()) {
1135 memcpy(buffer
.data(), output_file_write
.buffer().c_str(),
1136 output_file_write
.size());
1142 pp::Buffer_Dev
PDFiumEngine::PrintPagesAsPDF(
1143 const PP_PrintPageNumberRange_Dev
* page_ranges
, uint32_t page_range_count
,
1144 const PP_PrintSettings_Dev
& print_settings
) {
1145 if (!page_range_count
)
1146 return pp::Buffer_Dev();
1149 FPDF_DOCUMENT output_doc
= FPDF_CreateNewDocument();
1151 return pp::Buffer_Dev();
1153 SaveSelectedFormForPrint();
1155 std::string page_number_str
;
1156 for (uint32_t index
= 0; index
< page_range_count
; ++index
) {
1157 if (!page_number_str
.empty())
1158 page_number_str
.append(",");
1159 page_number_str
.append(
1160 base::IntToString(page_ranges
[index
].first_page_number
+ 1));
1161 if (page_ranges
[index
].first_page_number
!=
1162 page_ranges
[index
].last_page_number
) {
1163 page_number_str
.append("-");
1164 page_number_str
.append(
1165 base::IntToString(page_ranges
[index
].last_page_number
+ 1));
1169 std::vector
<uint32_t> page_numbers
=
1170 GetPageNumbersFromPrintPageNumberRange(page_ranges
, page_range_count
);
1171 for (size_t i
= 0; i
< page_numbers
.size(); ++i
) {
1172 uint32_t page_number
= page_numbers
[i
];
1173 pages_
[page_number
]->GetPage();
1174 if (!IsPageVisible(page_numbers
[i
]))
1175 pages_
[page_number
]->Unload();
1178 FPDF_CopyViewerPreferences(output_doc
, doc_
);
1179 if (!FPDF_ImportPages(output_doc
, doc_
, page_number_str
.c_str(), 0)) {
1180 FPDF_CloseDocument(output_doc
);
1181 return pp::Buffer_Dev();
1184 FitContentsToPrintableAreaIfRequired(output_doc
, print_settings
);
1186 // Now flatten all the output pages.
1187 pp::Buffer_Dev buffer
= GetFlattenedPrintData(output_doc
);
1188 FPDF_CloseDocument(output_doc
);
1192 void PDFiumEngine::FitContentsToPrintableAreaIfRequired(
1193 const FPDF_DOCUMENT
& doc
, const PP_PrintSettings_Dev
& print_settings
) {
1194 // Check to see if we need to fit pdf contents to printer paper size.
1195 if (print_settings
.print_scaling_option
!=
1196 PP_PRINTSCALINGOPTION_SOURCE_SIZE
) {
1197 int num_pages
= FPDF_GetPageCount(doc
);
1198 // In-place transformation is more efficient than creating a new
1199 // transformed document from the source document. Therefore, transform
1200 // every page to fit the contents in the selected printer paper.
1201 for (int i
= 0; i
< num_pages
; ++i
) {
1202 FPDF_PAGE page
= FPDF_LoadPage(doc
, i
);
1203 TransformPDFPageForPrinting(page
, print_settings
);
1204 FPDF_ClosePage(page
);
1209 void PDFiumEngine::SaveSelectedFormForPrint() {
1210 FORM_ForceToKillFocus(form_
);
1211 client_
->FormTextFieldFocusChange(false);
1214 void PDFiumEngine::PrintEnd() {
1215 FORM_DoDocumentAAction(form_
, FPDFDOC_AACTION_DP
);
1218 PDFiumPage::Area
PDFiumEngine::GetCharIndex(
1219 const pp::MouseInputEvent
& event
, int* page_index
,
1220 int* char_index
, PDFiumPage::LinkTarget
* target
) {
1221 // First figure out which page this is in.
1222 pp::Point mouse_point
= event
.GetPosition();
1224 static_cast<int>((mouse_point
.x() + position_
.x()) / current_zoom_
),
1225 static_cast<int>((mouse_point
.y() + position_
.y()) / current_zoom_
));
1226 return GetCharIndex(point
, page_index
, char_index
, target
);
1229 PDFiumPage::Area
PDFiumEngine::GetCharIndex(
1230 const pp::Point
& point
,
1233 PDFiumPage::LinkTarget
* target
) {
1235 for (size_t i
= 0; i
< visible_pages_
.size(); ++i
) {
1236 if (pages_
[visible_pages_
[i
]]->rect().Contains(point
)) {
1237 page
= visible_pages_
[i
];
1242 return PDFiumPage::NONSELECTABLE_AREA
;
1244 // If the page hasn't finished rendering, calling into the page sometimes
1246 for (size_t i
= 0; i
< progressive_paints_
.size(); ++i
) {
1247 if (progressive_paints_
[i
].page_index
== page
)
1248 return PDFiumPage::NONSELECTABLE_AREA
;
1252 return pages_
[page
]->GetCharIndex(point
, current_rotation_
, char_index
,
1256 bool PDFiumEngine::OnMouseDown(const pp::MouseInputEvent
& event
) {
1257 if (event
.GetButton() != PP_INPUTEVENT_MOUSEBUTTON_LEFT
)
1260 SelectionChangeInvalidator
selection_invalidator(this);
1263 int page_index
= -1;
1264 int char_index
= -1;
1265 PDFiumPage::LinkTarget target
;
1266 PDFiumPage::Area area
= GetCharIndex(event
, &page_index
,
1267 &char_index
, &target
);
1268 if (area
== PDFiumPage::WEBLINK_AREA
) {
1269 bool open_in_new_tab
= !!(event
.GetModifiers() & kDefaultKeyModifier
);
1270 client_
->NavigateTo(target
.url
, open_in_new_tab
);
1271 client_
->FormTextFieldFocusChange(false);
1275 if (area
== PDFiumPage::DOCLINK_AREA
) {
1276 client_
->ScrollToPage(target
.page
);
1277 client_
->FormTextFieldFocusChange(false);
1281 if (page_index
!= -1) {
1282 last_page_mouse_down_
= page_index
;
1283 double page_x
, page_y
;
1284 pp::Point point
= event
.GetPosition();
1285 DeviceToPage(page_index
, point
.x(), point
.y(), &page_x
, &page_y
);
1287 FORM_OnLButtonDown(form_
, pages_
[page_index
]->GetPage(), 0, page_x
, page_y
);
1288 int control
= FPDPage_HasFormFieldAtPoint(
1289 form_
, pages_
[page_index
]->GetPage(), page_x
, page_y
);
1290 if (control
> FPDF_FORMFIELD_UNKNOWN
) { // returns -1 sometimes...
1291 client_
->FormTextFieldFocusChange(control
== FPDF_FORMFIELD_TEXTFIELD
||
1292 control
== FPDF_FORMFIELD_COMBOBOX
);
1293 return true; // Return now before we get into the selection code.
1297 client_
->FormTextFieldFocusChange(false);
1299 if (area
!= PDFiumPage::TEXT_AREA
)
1300 return true; // Return true so WebKit doesn't do its own highlighting.
1302 if (event
.GetClickCount() == 1) {
1303 OnSingleClick(page_index
, char_index
);
1304 } else if (event
.GetClickCount() == 2 ||
1305 event
.GetClickCount() == 3) {
1306 OnMultipleClick(event
.GetClickCount(), page_index
, char_index
);
1312 void PDFiumEngine::OnSingleClick(int page_index
, int char_index
) {
1314 selection_
.push_back(PDFiumRange(pages_
[page_index
], char_index
, 0));
1317 void PDFiumEngine::OnMultipleClick(int click_count
,
1320 // It would be more efficient if the SDK could support finding a space, but
1322 int start_index
= char_index
;
1324 base::char16 cur
= pages_
[page_index
]->GetCharAtIndex(start_index
);
1325 // For double click, we want to select one word so we look for whitespace
1326 // boundaries. For triple click, we want the whole line.
1327 if (cur
== '\n' || (click_count
== 2 && (cur
== ' ' || cur
== '\t')))
1329 } while (--start_index
>= 0);
1333 int end_index
= char_index
;
1334 int total
= pages_
[page_index
]->GetCharCount();
1335 while (end_index
++ <= total
) {
1336 base::char16 cur
= pages_
[page_index
]->GetCharAtIndex(end_index
);
1337 if (cur
== '\n' || (click_count
== 2 && (cur
== ' ' || cur
== '\t')))
1341 selection_
.push_back(PDFiumRange(
1342 pages_
[page_index
], start_index
, end_index
- start_index
));
1345 bool PDFiumEngine::OnMouseUp(const pp::MouseInputEvent
& event
) {
1346 if (event
.GetButton() != PP_INPUTEVENT_MOUSEBUTTON_LEFT
)
1349 int page_index
= -1;
1350 int char_index
= -1;
1351 GetCharIndex(event
, &page_index
, &char_index
, NULL
);
1352 if (page_index
!= -1) {
1353 double page_x
, page_y
;
1354 pp::Point point
= event
.GetPosition();
1355 DeviceToPage(page_index
, point
.x(), point
.y(), &page_x
, &page_y
);
1357 form_
, pages_
[page_index
]->GetPage(), 0, page_x
, page_y
);
1367 bool PDFiumEngine::OnMouseMove(const pp::MouseInputEvent
& event
) {
1368 int page_index
= -1;
1369 int char_index
= -1;
1370 PDFiumPage::Area area
= GetCharIndex(event
, &page_index
, &char_index
, NULL
);
1372 PP_CursorType_Dev cursor
;
1374 case PDFiumPage::TEXT_AREA
:
1375 cursor
= PP_CURSORTYPE_IBEAM
;
1377 case PDFiumPage::WEBLINK_AREA
:
1378 case PDFiumPage::DOCLINK_AREA
:
1379 cursor
= PP_CURSORTYPE_HAND
;
1381 case PDFiumPage::NONSELECTABLE_AREA
:
1383 cursor
= PP_CURSORTYPE_POINTER
;
1387 if (page_index
!= -1) {
1388 double page_x
, page_y
;
1389 pp::Point point
= event
.GetPosition();
1390 DeviceToPage(page_index
, point
.x(), point
.y(), &page_x
, &page_y
);
1392 FORM_OnMouseMove(form_
, pages_
[page_index
]->GetPage(), 0, page_x
, page_y
);
1393 int control
= FPDPage_HasFormFieldAtPoint(
1394 form_
, pages_
[page_index
]->GetPage(), page_x
, page_y
);
1396 case FPDF_FORMFIELD_PUSHBUTTON
:
1397 case FPDF_FORMFIELD_CHECKBOX
:
1398 case FPDF_FORMFIELD_RADIOBUTTON
:
1399 case FPDF_FORMFIELD_COMBOBOX
:
1400 case FPDF_FORMFIELD_LISTBOX
:
1401 cursor
= PP_CURSORTYPE_HAND
;
1403 case FPDF_FORMFIELD_TEXTFIELD
:
1404 cursor
= PP_CURSORTYPE_IBEAM
;
1411 client_
->UpdateCursor(cursor
);
1412 pp::Point point
= event
.GetPosition();
1413 std::string url
= GetLinkAtPosition(event
.GetPosition());
1414 if (url
!= link_under_cursor_
) {
1415 link_under_cursor_
= url
;
1416 pp::PDF::SetLinkUnderCursor(GetPluginInstance(), url
.c_str());
1418 // No need to swallow the event, since this might interfere with the
1419 // scrollbars if the user is dragging them.
1423 // We're selecting but right now we're not over text, so don't change the
1424 // current selection.
1425 if (area
!= PDFiumPage::TEXT_AREA
&& area
!= PDFiumPage::WEBLINK_AREA
&&
1426 area
!= PDFiumPage::DOCLINK_AREA
) {
1430 SelectionChangeInvalidator
selection_invalidator(this);
1432 // Check if the user has descreased their selection area and we need to remove
1433 // pages from selection_.
1434 for (size_t i
= 0; i
< selection_
.size(); ++i
) {
1435 if (selection_
[i
].page_index() == page_index
) {
1436 // There should be no other pages after this.
1437 selection_
.erase(selection_
.begin() + i
+ 1, selection_
.end());
1442 if (selection_
.size() == 0)
1445 int last
= selection_
.size() - 1;
1446 if (selection_
[last
].page_index() == page_index
) {
1447 // Selecting within a page.
1449 if (char_index
>= selection_
[last
].char_index()) {
1450 // Selecting forward.
1451 count
= char_index
- selection_
[last
].char_index() + 1;
1453 count
= char_index
- selection_
[last
].char_index() - 1;
1455 selection_
[last
].SetCharCount(count
);
1456 } else if (selection_
[last
].page_index() < page_index
) {
1457 // Selecting into the next page.
1459 // First make sure that there are no gaps in selection, i.e. if mousedown on
1460 // page one but we only get mousemove over page three, we want page two.
1461 for (int i
= selection_
[last
].page_index() + 1; i
< page_index
; ++i
) {
1462 selection_
.push_back(PDFiumRange(pages_
[i
], 0,
1463 pages_
[i
]->GetCharCount()));
1466 int count
= pages_
[selection_
[last
].page_index()]->GetCharCount();
1467 selection_
[last
].SetCharCount(count
- selection_
[last
].char_index());
1468 selection_
.push_back(PDFiumRange(pages_
[page_index
], 0, char_index
));
1470 // Selecting into the previous page.
1471 selection_
[last
].SetCharCount(-selection_
[last
].char_index());
1473 // First make sure that there are no gaps in selection, i.e. if mousedown on
1474 // page three but we only get mousemove over page one, we want page two.
1475 for (int i
= selection_
[last
].page_index() - 1; i
> page_index
; --i
) {
1476 selection_
.push_back(PDFiumRange(pages_
[i
], 0,
1477 pages_
[i
]->GetCharCount()));
1480 int count
= pages_
[page_index
]->GetCharCount();
1481 selection_
.push_back(
1482 PDFiumRange(pages_
[page_index
], count
, count
- char_index
));
1488 bool PDFiumEngine::OnKeyDown(const pp::KeyboardInputEvent
& event
) {
1489 if (last_page_mouse_down_
== -1)
1492 bool rv
= !!FORM_OnKeyDown(
1493 form_
, pages_
[last_page_mouse_down_
]->GetPage(),
1494 event
.GetKeyCode(), event
.GetModifiers());
1496 if (event
.GetKeyCode() == ui::VKEY_BACK
||
1497 event
.GetKeyCode() == ui::VKEY_ESCAPE
) {
1498 // Chrome doesn't send char events for backspace or escape keys, see
1499 // PlatformKeyboardEventBuilder::isCharacterKey() and
1500 // http://chrome-corpsvn.mtv.corp.google.com/viewvc?view=rev&root=chrome&revision=31805
1501 // for more information. So just fake one since PDFium uses it.
1503 str
.push_back(event
.GetKeyCode());
1504 pp::KeyboardInputEvent
synthesized(pp::KeyboardInputEvent(
1505 client_
->GetPluginInstance(),
1506 PP_INPUTEVENT_TYPE_CHAR
,
1507 event
.GetTimeStamp(),
1508 event
.GetModifiers(),
1511 OnChar(synthesized
);
1517 bool PDFiumEngine::OnKeyUp(const pp::KeyboardInputEvent
& event
) {
1518 if (last_page_mouse_down_
== -1)
1521 return !!FORM_OnKeyUp(
1522 form_
, pages_
[last_page_mouse_down_
]->GetPage(),
1523 event
.GetKeyCode(), event
.GetModifiers());
1526 bool PDFiumEngine::OnChar(const pp::KeyboardInputEvent
& event
) {
1527 if (last_page_mouse_down_
== -1)
1530 base::string16 str
= base::UTF8ToUTF16(event
.GetCharacterText().AsString());
1531 return !!FORM_OnChar(
1532 form_
, pages_
[last_page_mouse_down_
]->GetPage(),
1534 event
.GetModifiers());
1537 void PDFiumEngine::StartFind(const char* text
, bool case_sensitive
) {
1538 // We can get a call to StartFind before we have any page information (i.e.
1539 // before the first call to LoadDocument has happened). Handle this case.
1543 bool first_search
= false;
1544 int character_to_start_searching_from
= 0;
1545 if (current_find_text_
!= text
) { // First time we search for this text.
1546 first_search
= true;
1547 std::vector
<PDFiumRange
> old_selection
= selection_
;
1549 current_find_text_
= text
;
1551 if (old_selection
.empty()) {
1552 // Start searching from the beginning of the document.
1553 next_page_to_search_
= 0;
1554 last_page_to_search_
= pages_
.size() - 1;
1555 last_character_index_to_search_
= -1;
1557 // There's a current selection, so start from it.
1558 next_page_to_search_
= old_selection
[0].page_index();
1559 last_character_index_to_search_
= old_selection
[0].char_index();
1560 character_to_start_searching_from
= old_selection
[0].char_index();
1561 last_page_to_search_
= next_page_to_search_
;
1565 int current_page
= next_page_to_search_
;
1567 if (pages_
[current_page
]->available()) {
1568 base::string16 str
= base::UTF8ToUTF16(text
);
1569 // Don't use PDFium to search for now, since it doesn't support unicode text.
1570 // Leave the code for now to avoid bit-rot, in case it's fixed later.
1573 str
, case_sensitive
, first_search
, character_to_start_searching_from
,
1577 str
, case_sensitive
, first_search
, character_to_start_searching_from
,
1581 if (!IsPageVisible(current_page
))
1582 pages_
[current_page
]->Unload();
1585 if (next_page_to_search_
!= last_page_to_search_
||
1586 (first_search
&& last_character_index_to_search_
!= -1)) {
1587 ++next_page_to_search_
;
1590 if (next_page_to_search_
== static_cast<int>(pages_
.size()))
1591 next_page_to_search_
= 0;
1592 // If there's only one page in the document and we start searching midway,
1593 // then we'll want to search the page one more time.
1594 bool end_of_search
=
1595 next_page_to_search_
== last_page_to_search_
&&
1596 // Only one page but didn't start midway.
1597 ((pages_
.size() == 1 && last_character_index_to_search_
== -1) ||
1598 // Started midway, but only 1 page and we already looped around.
1599 (pages_
.size() == 1 && !first_search
) ||
1600 // Started midway, and we've just looped around.
1601 (pages_
.size() > 1 && current_page
== next_page_to_search_
));
1603 if (end_of_search
) {
1604 // Send the final notification.
1605 client_
->NotifyNumberOfFindResultsChanged(find_results_
.size(), true);
1607 pp::CompletionCallback callback
=
1608 find_factory_
.NewCallback(&PDFiumEngine::ContinueFind
);
1609 pp::Module::Get()->core()->CallOnMainThread(
1610 0, callback
, case_sensitive
? 1 : 0);
1614 void PDFiumEngine::SearchUsingPDFium(const base::string16
& term
,
1615 bool case_sensitive
,
1617 int character_to_start_searching_from
,
1619 // Find all the matches in the current page.
1620 unsigned long flags
= case_sensitive
? FPDF_MATCHCASE
: 0;
1621 FPDF_SCHHANDLE find
= FPDFText_FindStart(
1622 pages_
[current_page
]->GetTextPage(),
1623 reinterpret_cast<const unsigned short*>(term
.c_str()),
1624 flags
, character_to_start_searching_from
);
1626 // Note: since we search one page at a time, we don't find matches across
1627 // page boundaries. We could do this manually ourself, but it seems low
1628 // priority since Reader itself doesn't do it.
1629 while (FPDFText_FindNext(find
)) {
1630 PDFiumRange
result(pages_
[current_page
],
1631 FPDFText_GetSchResultIndex(find
),
1632 FPDFText_GetSchCount(find
));
1634 if (!first_search
&&
1635 last_character_index_to_search_
!= -1 &&
1636 result
.page_index() == last_page_to_search_
&&
1637 result
.char_index() >= last_character_index_to_search_
) {
1641 AddFindResult(result
);
1644 FPDFText_FindClose(find
);
1647 void PDFiumEngine::SearchUsingICU(const base::string16
& term
,
1648 bool case_sensitive
,
1650 int character_to_start_searching_from
,
1652 base::string16 page_text
;
1653 int text_length
= pages_
[current_page
]->GetCharCount();
1654 if (character_to_start_searching_from
) {
1655 text_length
-= character_to_start_searching_from
;
1656 } else if (!first_search
&&
1657 last_character_index_to_search_
!= -1 &&
1658 current_page
== last_page_to_search_
) {
1659 text_length
= last_character_index_to_search_
;
1661 if (text_length
<= 0)
1663 unsigned short* data
=
1664 reinterpret_cast<unsigned short*>(WriteInto(&page_text
, text_length
+ 1));
1665 FPDFText_GetText(pages_
[current_page
]->GetTextPage(),
1666 character_to_start_searching_from
,
1669 std::vector
<PDFEngine::Client::SearchStringResult
> results
;
1670 client_
->SearchString(
1671 page_text
.c_str(), term
.c_str(), case_sensitive
, &results
);
1672 for (size_t i
= 0; i
< results
.size(); ++i
) {
1673 // Need to map the indexes from the page text, which may have generated
1674 // characters like space etc, to character indices from the page.
1675 int temp_start
= results
[i
].start_index
+ character_to_start_searching_from
;
1676 int start
= FPDFText_GetCharIndexFromTextIndex(
1677 pages_
[current_page
]->GetTextPage(), temp_start
);
1678 int end
= FPDFText_GetCharIndexFromTextIndex(
1679 pages_
[current_page
]->GetTextPage(),
1680 temp_start
+ results
[i
].length
);
1681 AddFindResult(PDFiumRange(pages_
[current_page
], start
, end
- start
));
1685 void PDFiumEngine::AddFindResult(const PDFiumRange
& result
) {
1686 // Figure out where to insert the new location, since we could have
1687 // started searching midway and now we wrapped.
1689 int page_index
= result
.page_index();
1690 int char_index
= result
.char_index();
1691 for (i
= 0; i
< find_results_
.size(); ++i
) {
1692 if (find_results_
[i
].page_index() > page_index
||
1693 (find_results_
[i
].page_index() == page_index
&&
1694 find_results_
[i
].char_index() > char_index
)) {
1698 find_results_
.insert(find_results_
.begin() + i
, result
);
1701 if (current_find_index_
== -1) {
1702 // Select the first match.
1703 SelectFindResult(true);
1704 } else if (static_cast<int>(i
) <= current_find_index_
) {
1705 // Update the current match index
1706 current_find_index_
++;
1707 client_
->NotifySelectedFindResultChanged(current_find_index_
);
1709 client_
->NotifyNumberOfFindResultsChanged(find_results_
.size(), false);
1712 bool PDFiumEngine::SelectFindResult(bool forward
) {
1713 if (find_results_
.empty()) {
1718 SelectionChangeInvalidator
selection_invalidator(this);
1720 // Move back/forward through the search locations we previously found.
1722 if (++current_find_index_
== static_cast<int>(find_results_
.size()))
1723 current_find_index_
= 0;
1725 if (--current_find_index_
< 0) {
1726 current_find_index_
= find_results_
.size() - 1;
1730 // Update the selection before telling the client to scroll, since it could
1733 selection_
.push_back(find_results_
[current_find_index_
]);
1735 // If the result is not in view, scroll to it.
1737 pp::Rect bounding_rect
;
1738 pp::Rect visible_rect
= GetVisibleRect();
1739 // Use zoom of 1.0 since visible_rect is without zoom.
1740 std::vector
<pp::Rect
> rects
= find_results_
[current_find_index_
].
1741 GetScreenRects(pp::Point(), 1.0, current_rotation_
);
1742 for (i
= 0; i
< rects
.size(); ++i
)
1743 bounding_rect
= bounding_rect
.Union(rects
[i
]);
1744 if (!visible_rect
.Contains(bounding_rect
)) {
1745 pp::Point center
= bounding_rect
.CenterPoint();
1746 // Make the page centered.
1747 int new_y
= static_cast<int>(center
.y() * current_zoom_
) -
1748 static_cast<int>(visible_rect
.height() * current_zoom_
/ 2);
1751 client_
->ScrollToY(new_y
);
1753 // Only move horizontally if it's not visible.
1754 if (center
.x() < visible_rect
.x() || center
.x() > visible_rect
.right()) {
1755 int new_x
= static_cast<int>(center
.x() * current_zoom_
) -
1756 static_cast<int>(visible_rect
.width() * current_zoom_
/ 2);
1759 client_
->ScrollToX(new_x
);
1763 client_
->NotifySelectedFindResultChanged(current_find_index_
);
1768 void PDFiumEngine::StopFind() {
1769 SelectionChangeInvalidator
selection_invalidator(this);
1773 find_results_
.clear();
1774 next_page_to_search_
= -1;
1775 last_page_to_search_
= -1;
1776 last_character_index_to_search_
= -1;
1777 current_find_index_
= -1;
1778 current_find_text_
.clear();
1780 find_factory_
.CancelAll();
1783 void PDFiumEngine::UpdateTickMarks() {
1784 std::vector
<pp::Rect
> tickmarks
;
1785 for (size_t i
= 0; i
< find_results_
.size(); ++i
) {
1787 // Always use an origin of 0,0 since scroll positions don't affect tickmark.
1788 std::vector
<pp::Rect
> rects
= find_results_
[i
].GetScreenRects(
1789 pp::Point(0, 0), current_zoom_
, current_rotation_
);
1790 for (size_t j
= 0; j
< rects
.size(); ++j
)
1791 rect
= rect
.Union(rects
[j
]);
1792 tickmarks
.push_back(rect
);
1795 client_
->UpdateTickMarks(tickmarks
);
1798 void PDFiumEngine::ZoomUpdated(double new_zoom_level
) {
1801 current_zoom_
= new_zoom_level
;
1803 CalculateVisiblePages();
1807 void PDFiumEngine::RotateClockwise() {
1808 current_rotation_
= (current_rotation_
+ 1) % 4;
1809 InvalidateAllPages();
1812 void PDFiumEngine::RotateCounterclockwise() {
1813 current_rotation_
= (current_rotation_
- 1) % 4;
1814 InvalidateAllPages();
1817 void PDFiumEngine::InvalidateAllPages() {
1819 find_results_
.clear();
1824 client_
->Invalidate(pp::Rect(plugin_size_
));
1827 std::string
PDFiumEngine::GetSelectedText() {
1828 base::string16 result
;
1829 for (size_t i
= 0; i
< selection_
.size(); ++i
) {
1831 selection_
[i
- 1].page_index() > selection_
[i
].page_index()) {
1832 result
= selection_
[i
].GetText() + result
;
1834 result
.append(selection_
[i
].GetText());
1838 return base::UTF16ToUTF8(result
);
1841 std::string
PDFiumEngine::GetLinkAtPosition(const pp::Point
& point
) {
1843 PDFiumPage::LinkTarget target
;
1844 PDFiumPage::Area area
= GetCharIndex(point
, &temp
, &temp
, &target
);
1845 if (area
== PDFiumPage::WEBLINK_AREA
)
1847 return std::string();
1850 bool PDFiumEngine::IsSelecting() {
1854 bool PDFiumEngine::HasPermission(DocumentPermission permission
) const {
1855 switch (permission
) {
1856 case PERMISSION_COPY
:
1857 return (permissions_
& kPDFPermissionCopyMask
) != 0;
1858 case PERMISSION_COPY_ACCESSIBLE
:
1859 return (permissions_
& kPDFPermissionCopyAccessibleMask
) != 0;
1860 case PERMISSION_PRINT_LOW_QUALITY
:
1861 return (permissions_
& kPDFPermissionPrintLowQualityMask
) != 0;
1862 case PERMISSION_PRINT_HIGH_QUALITY
:
1863 return (permissions_
& kPDFPermissionPrintLowQualityMask
) != 0 &&
1864 (permissions_
& kPDFPermissionPrintHighQualityMask
) != 0;
1870 void PDFiumEngine::SelectAll() {
1871 SelectionChangeInvalidator
selection_invalidator(this);
1874 for (size_t i
= 0; i
< pages_
.size(); ++i
)
1875 if (pages_
[i
]->available()) {
1876 selection_
.push_back(PDFiumRange(pages_
[i
], 0,
1877 pages_
[i
]->GetCharCount()));
1881 int PDFiumEngine::GetNumberOfPages() {
1882 return pages_
.size();
1885 int PDFiumEngine::GetNamedDestinationPage(const std::string
& destination
) {
1886 // Look for the destination.
1887 FPDF_DEST dest
= FPDF_GetNamedDestByName(doc_
, destination
.c_str());
1889 // Look for a bookmark with the same name.
1890 base::string16 destination_wide
= base::UTF8ToUTF16(destination
);
1891 FPDF_WIDESTRING destination_pdf_wide
=
1892 reinterpret_cast<FPDF_WIDESTRING
>(destination_wide
.c_str());
1893 FPDF_BOOKMARK bookmark
= FPDFBookmark_Find(doc_
, destination_pdf_wide
);
1896 dest
= FPDFBookmark_GetDest(doc_
, bookmark
);
1898 return dest
? FPDFDest_GetPageIndex(doc_
, dest
) : -1;
1901 int PDFiumEngine::GetFirstVisiblePage() {
1902 CalculateVisiblePages();
1903 return first_visible_page_
;
1906 int PDFiumEngine::GetMostVisiblePage() {
1907 CalculateVisiblePages();
1908 return most_visible_page_
;
1911 pp::Rect
PDFiumEngine::GetPageRect(int index
) {
1912 pp::Rect
rc(pages_
[index
]->rect());
1913 rc
.Inset(-kPageShadowLeft
, -kPageShadowTop
,
1914 -kPageShadowRight
, -kPageShadowBottom
);
1918 pp::Rect
PDFiumEngine::GetPageContentsRect(int index
) {
1919 return GetScreenRect(pages_
[index
]->rect());
1922 void PDFiumEngine::PaintThumbnail(pp::ImageData
* image_data
, int index
) {
1923 FPDF_BITMAP bitmap
= FPDFBitmap_CreateEx(
1924 image_data
->size().width(), image_data
->size().height(),
1925 FPDFBitmap_BGRx
, image_data
->data(), image_data
->stride());
1927 if (pages_
[index
]->available()) {
1928 FPDFBitmap_FillRect(
1929 bitmap
, 0, 0, image_data
->size().width(), image_data
->size().height(),
1930 255, 255, 255, 255);
1932 FPDF_RenderPageBitmap(
1933 bitmap
, pages_
[index
]->GetPage(), 0, 0, image_data
->size().width(),
1934 image_data
->size().height(), 0, GetRenderingFlags());
1936 FPDFBitmap_FillRect(
1937 bitmap
, 0, 0, image_data
->size().width(), image_data
->size().height(),
1938 kPendingPageColorR
, kPendingPageColorG
, kPendingPageColorB
,
1939 kPendingPageColorA
);
1942 FPDFBitmap_Destroy(bitmap
);
1945 void PDFiumEngine::SetGrayscale(bool grayscale
) {
1946 render_grayscale_
= grayscale
;
1949 void PDFiumEngine::OnCallback(int id
) {
1950 if (!timers_
.count(id
))
1953 timers_
[id
].second(id
);
1954 if (timers_
.count(id
)) // The callback might delete the timer.
1955 client_
->ScheduleCallback(id
, timers_
[id
].first
);
1958 std::string
PDFiumEngine::GetPageAsJSON(int index
) {
1959 if (!(HasPermission(PERMISSION_COPY
) ||
1960 HasPermission(PERMISSION_COPY_ACCESSIBLE
))) {
1964 if (index
< 0 || static_cast<size_t>(index
) > pages_
.size() - 1)
1967 scoped_ptr
<base::Value
> node(
1968 pages_
[index
]->GetAccessibleContentAsValue(current_rotation_
));
1969 std::string page_json
;
1970 base::JSONWriter::Write(node
.get(), &page_json
);
1974 bool PDFiumEngine::GetPrintScaling() {
1975 return !!FPDF_VIEWERREF_GetPrintScaling(doc_
);
1978 void PDFiumEngine::AppendBlankPages(int num_pages
) {
1979 DCHECK(num_pages
!= 0);
1985 pending_pages_
.clear();
1987 // Delete all pages except the first one.
1988 while (pages_
.size() > 1) {
1989 delete pages_
.back();
1991 FPDFPage_Delete(doc_
, pages_
.size());
1994 // Calculate document size and all page sizes.
1995 std::vector
<pp::Rect
> page_rects
;
1996 pp::Size page_size
= GetPageSize(0);
1997 page_size
.Enlarge(kPageShadowLeft
+ kPageShadowRight
,
1998 kPageShadowTop
+ kPageShadowBottom
);
1999 pp::Size old_document_size
= document_size_
;
2000 document_size_
= pp::Size(page_size
.width(), 0);
2001 for (int i
= 0; i
< num_pages
; ++i
) {
2003 // Add space for horizontal separator.
2004 document_size_
.Enlarge(0, kPageSeparatorThickness
);
2007 pp::Rect
rect(pp::Point(0, document_size_
.height()), page_size
);
2008 page_rects
.push_back(rect
);
2010 document_size_
.Enlarge(0, page_size
.height());
2013 // Create blank pages.
2014 for (int i
= 1; i
< num_pages
; ++i
) {
2015 pp::Rect
page_rect(page_rects
[i
]);
2016 page_rect
.Inset(kPageShadowLeft
, kPageShadowTop
,
2017 kPageShadowRight
, kPageShadowBottom
);
2018 double width_in_points
=
2019 page_rect
.width() * kPointsPerInch
/ kPixelsPerInch
;
2020 double height_in_points
=
2021 page_rect
.height() * kPointsPerInch
/ kPixelsPerInch
;
2022 FPDFPage_New(doc_
, i
, width_in_points
, height_in_points
);
2023 pages_
.push_back(new PDFiumPage(this, i
, page_rect
, true));
2026 CalculateVisiblePages();
2027 if (document_size_
!= old_document_size
)
2028 client_
->DocumentSizeUpdated(document_size_
);
2031 void PDFiumEngine::LoadDocument() {
2032 // Check if the document is ready for loading. If it isn't just bail for now,
2033 // we will call LoadDocument() again later.
2034 if (!doc_
&& !doc_loader_
.IsDocumentComplete() &&
2035 !FPDFAvail_IsDocAvail(fpdf_availability_
, &download_hints_
)) {
2039 // If we're in the middle of getting a password, just return. We will retry
2040 // loading the document after we get the password anyway.
2041 if (getting_password_
)
2044 ScopedUnsupportedFeature
scoped_unsupported_feature(this);
2045 bool needs_password
= false;
2046 if (TryLoadingDoc(false, std::string(), &needs_password
)) {
2047 ContinueLoadingDocument(false, std::string());
2051 GetPasswordAndLoad();
2053 client_
->DocumentLoadFailed();
2056 bool PDFiumEngine::TryLoadingDoc(bool with_password
,
2057 const std::string
& password
,
2058 bool* needs_password
) {
2059 *needs_password
= false;
2063 const char* password_cstr
= NULL
;
2064 if (with_password
) {
2065 password_cstr
= password
.c_str();
2066 password_tries_remaining_
--;
2068 if (doc_loader_
.IsDocumentComplete())
2069 doc_
= FPDF_LoadCustomDocument(&file_access_
, password_cstr
);
2071 doc_
= FPDFAvail_GetDocument(fpdf_availability_
, password_cstr
);
2073 if (!doc_
&& FPDF_GetLastError() == FPDF_ERR_PASSWORD
)
2074 *needs_password
= true;
2076 return doc_
!= NULL
;
2079 void PDFiumEngine::GetPasswordAndLoad() {
2080 getting_password_
= true;
2081 DCHECK(!doc_
&& FPDF_GetLastError() == FPDF_ERR_PASSWORD
);
2082 client_
->GetDocumentPassword(password_factory_
.NewCallbackWithOutput(
2083 &PDFiumEngine::OnGetPasswordComplete
));
2086 void PDFiumEngine::OnGetPasswordComplete(int32_t result
,
2087 const pp::Var
& password
) {
2088 getting_password_
= false;
2090 bool password_given
= false;
2091 std::string password_text
;
2092 if (result
== PP_OK
&& password
.is_string()) {
2093 password_text
= password
.AsString();
2094 if (!password_text
.empty())
2095 password_given
= true;
2097 ContinueLoadingDocument(password_given
, password_text
);
2100 void PDFiumEngine::ContinueLoadingDocument(
2102 const std::string
& password
) {
2103 ScopedUnsupportedFeature
scoped_unsupported_feature(this);
2105 bool needs_password
= false;
2106 bool loaded
= TryLoadingDoc(has_password
, password
, &needs_password
);
2107 bool password_incorrect
= !loaded
&& has_password
&& needs_password
;
2108 if (password_incorrect
&& password_tries_remaining_
> 0) {
2109 GetPasswordAndLoad();
2114 client_
->DocumentLoadFailed();
2118 if (FPDFDoc_GetPageMode(doc_
) == PAGEMODE_USEOUTLINES
)
2119 client_
->DocumentHasUnsupportedFeature("Bookmarks");
2121 permissions_
= FPDF_GetDocPermissions(doc_
);
2124 // Only returns 0 when data isn't available. If form data is downloaded, or
2125 // if this isn't a form, returns positive values.
2126 if (!doc_loader_
.IsDocumentComplete() &&
2127 !FPDFAvail_IsFormAvail(fpdf_availability_
, &download_hints_
)) {
2131 form_
= FPDFDOC_InitFormFillEnviroument(
2132 doc_
, static_cast<FPDF_FORMFILLINFO
*>(this));
2133 FPDF_SetFormFieldHighlightColor(form_
, 0, kFormHighlightColor
);
2134 FPDF_SetFormFieldHighlightAlpha(form_
, kFormHighlightAlpha
);
2137 if (!doc_loader_
.IsDocumentComplete()) {
2138 // Check if the first page is available. In a linearized PDF, that is not
2139 // always page 0. Doing this gives us the default page size, since when the
2140 // document is available, the first page is available as well.
2141 CheckPageAvailable(FPDFAvail_GetFirstPageNum(doc_
), &pending_pages_
);
2144 LoadPageInfo(false);
2146 if (doc_loader_
.IsDocumentComplete())
2147 FinishLoadingDocument();
2150 void PDFiumEngine::LoadPageInfo(bool reload
) {
2151 pending_pages_
.clear();
2152 pp::Size old_document_size
= document_size_
;
2153 document_size_
= pp::Size();
2154 std::vector
<pp::Rect
> page_rects
;
2155 int page_count
= FPDF_GetPageCount(doc_
);
2156 bool doc_complete
= doc_loader_
.IsDocumentComplete();
2157 for (int i
= 0; i
< page_count
; ++i
) {
2159 // Add space for horizontal separator.
2160 document_size_
.Enlarge(0, kPageSeparatorThickness
);
2163 // Get page availability. If reload==false, and document is not loaded yet
2164 // (we are using async loading) - mark all pages as unavailable.
2165 // If reload==true (we have document constructed already), get page
2166 // availability flag from already existing PDFiumPage class.
2167 bool page_available
= reload
? pages_
[i
]->available() : doc_complete
;
2169 pp::Size size
= page_available
? GetPageSize(i
) : default_page_size_
;
2170 size
.Enlarge(kPageShadowLeft
+ kPageShadowRight
,
2171 kPageShadowTop
+ kPageShadowBottom
);
2172 pp::Rect
rect(pp::Point(0, document_size_
.height()), size
);
2173 page_rects
.push_back(rect
);
2175 if (size
.width() > document_size_
.width())
2176 document_size_
.set_width(size
.width());
2178 document_size_
.Enlarge(0, size
.height());
2181 for (int i
= 0; i
< page_count
; ++i
) {
2182 // Center pages relative to the entire document.
2183 page_rects
[i
].set_x((document_size_
.width() - page_rects
[i
].width()) / 2);
2184 pp::Rect
page_rect(page_rects
[i
]);
2185 page_rect
.Inset(kPageShadowLeft
, kPageShadowTop
,
2186 kPageShadowRight
, kPageShadowBottom
);
2188 pages_
[i
]->set_rect(page_rect
);
2190 pages_
.push_back(new PDFiumPage(this, i
, page_rect
, doc_complete
));
2194 CalculateVisiblePages();
2195 if (document_size_
!= old_document_size
)
2196 client_
->DocumentSizeUpdated(document_size_
);
2199 void PDFiumEngine::CalculateVisiblePages() {
2200 // Clear pending requests queue, since it may contain requests to the pages
2201 // that are already invisible (after scrolling for example).
2202 pending_pages_
.clear();
2203 doc_loader_
.ClearPendingRequests();
2205 visible_pages_
.clear();
2206 pp::Rect
visible_rect(plugin_size_
);
2207 for (size_t i
= 0; i
< pages_
.size(); ++i
) {
2208 // Check an entire PageScreenRect, since we might need to repaint side
2209 // borders and shadows even if the page itself is not visible.
2210 // For example, when user use pdf with different page sizes and zoomed in
2211 // outside page area.
2212 if (visible_rect
.Intersects(GetPageScreenRect(i
))) {
2213 visible_pages_
.push_back(i
);
2214 CheckPageAvailable(i
, &pending_pages_
);
2216 // Need to unload pages when we're not using them, since some PDFs use a
2217 // lot of memory. See http://crbug.com/48791
2218 if (defer_page_unload_
) {
2219 deferred_page_unloads_
.push_back(i
);
2221 pages_
[i
]->Unload();
2224 // If the last mouse down was on a page that's no longer visible, reset
2225 // that variable so that we don't send keyboard events to it (the focus
2226 // will be lost when the page is first closed anyways).
2227 if (static_cast<int>(i
) == last_page_mouse_down_
)
2228 last_page_mouse_down_
= -1;
2232 // Any pending highlighting of form fields will be invalid since these are in
2233 // screen coordinates.
2234 form_highlights_
.clear();
2236 if (visible_pages_
.size() == 0)
2237 first_visible_page_
= -1;
2239 first_visible_page_
= visible_pages_
.front();
2241 int most_visible_page
= first_visible_page_
;
2242 // Check if the next page is more visible than the first one.
2243 if (most_visible_page
!= -1 &&
2244 pages_
.size() > 0 &&
2245 most_visible_page
< static_cast<int>(pages_
.size()) - 1) {
2247 visible_rect
.Intersect(GetPageScreenRect(most_visible_page
));
2249 visible_rect
.Intersect(GetPageScreenRect(most_visible_page
+ 1));
2250 if (rc_next
.height() > rc_first
.height())
2251 most_visible_page
++;
2254 SetCurrentPage(most_visible_page
);
2257 bool PDFiumEngine::IsPageVisible(int index
) const {
2258 for (size_t i
= 0; i
< visible_pages_
.size(); ++i
) {
2259 if (visible_pages_
[i
] == index
)
2266 bool PDFiumEngine::CheckPageAvailable(int index
, std::vector
<int>* pending
) {
2267 if (!doc_
|| !form_
)
2270 if (static_cast<int>(pages_
.size()) > index
&& pages_
[index
]->available())
2273 if (!FPDFAvail_IsPageAvail(fpdf_availability_
, index
, &download_hints_
)) {
2275 for (j
= 0; j
< pending
->size(); ++j
) {
2276 if ((*pending
)[j
] == index
)
2280 if (j
== pending
->size())
2281 pending
->push_back(index
);
2285 if (static_cast<int>(pages_
.size()) > index
)
2286 pages_
[index
]->set_available(true);
2287 if (!default_page_size_
.GetArea())
2288 default_page_size_
= GetPageSize(index
);
2292 pp::Size
PDFiumEngine::GetPageSize(int index
) {
2294 double width_in_points
= 0;
2295 double height_in_points
= 0;
2296 int rv
= FPDF_GetPageSizeByIndex(
2297 doc_
, index
, &width_in_points
, &height_in_points
);
2300 int width_in_pixels
= static_cast<int>(
2301 width_in_points
* kPixelsPerInch
/ kPointsPerInch
);
2302 int height_in_pixels
= static_cast<int>(
2303 height_in_points
* kPixelsPerInch
/ kPointsPerInch
);
2304 if (current_rotation_
% 2 == 1)
2305 std::swap(width_in_pixels
, height_in_pixels
);
2306 size
= pp::Size(width_in_pixels
, height_in_pixels
);
2311 int PDFiumEngine::StartPaint(int page_index
, const pp::Rect
& dirty
) {
2312 // For the first time we hit paint, do nothing and just record the paint for
2313 // the next callback. This keeps the UI responsive in case the user is doing
2314 // a lot of scrolling.
2315 ProgressivePaint progressive
;
2316 progressive
.rect
= dirty
;
2317 progressive
.page_index
= page_index
;
2318 progressive
.bitmap
= NULL
;
2319 progressive
.painted_
= false;
2320 progressive_paints_
.push_back(progressive
);
2321 return progressive_paints_
.size() - 1;
2324 bool PDFiumEngine::ContinuePaint(int progressive_index
,
2325 pp::ImageData
* image_data
) {
2326 #if defined(OS_LINUX)
2327 g_last_instance_id
= client_
->GetPluginInstance()->pp_instance();
2331 int page_index
= progressive_paints_
[progressive_index
].page_index
;
2332 last_progressive_start_time_
= base::Time::Now();
2333 if (progressive_paints_
[progressive_index
].bitmap
) {
2334 rv
= FPDF_RenderPage_Continue(
2335 pages_
[page_index
]->GetPage(), static_cast<IFSDK_PAUSE
*>(this));
2337 pp::Rect dirty
= progressive_paints_
[progressive_index
].rect
;
2338 progressive_paints_
[progressive_index
].bitmap
= CreateBitmap(dirty
,
2340 int start_x
, start_y
, size_x
, size_y
;
2342 page_index
, dirty
, &start_x
, &start_y
, &size_x
, &size_y
);
2343 FPDFBitmap_FillRect(
2344 progressive_paints_
[progressive_index
].bitmap
, start_x
, start_y
, size_x
,
2345 size_y
, 255, 255, 255, 255);
2346 rv
= FPDF_RenderPageBitmap_Start(
2347 progressive_paints_
[progressive_index
].bitmap
,
2348 pages_
[page_index
]->GetPage(), start_x
, start_y
, size_x
, size_y
,
2350 GetRenderingFlags(), static_cast<IFSDK_PAUSE
*>(this));
2352 return rv
!= FPDF_RENDER_TOBECOUNTINUED
;
2355 void PDFiumEngine::FinishPaint(int progressive_index
,
2356 pp::ImageData
* image_data
) {
2357 int page_index
= progressive_paints_
[progressive_index
].page_index
;
2358 pp::Rect dirty_in_screen
= progressive_paints_
[progressive_index
].rect
;
2359 FPDF_BITMAP bitmap
= progressive_paints_
[progressive_index
].bitmap
;
2360 int start_x
, start_y
, size_x
, size_y
;
2362 page_index
, dirty_in_screen
, &start_x
, &start_y
, &size_x
, &size_y
);
2366 form_
, bitmap
, pages_
[page_index
]->GetPage(), start_x
, start_y
, size_x
,
2367 size_y
, current_rotation_
, GetRenderingFlags());
2369 FillPageSides(progressive_index
);
2371 // Paint the page shadows.
2372 PaintPageShadow(progressive_index
, image_data
);
2374 DrawSelections(progressive_index
, image_data
);
2376 FPDF_RenderPage_Close(pages_
[page_index
]->GetPage());
2377 FPDFBitmap_Destroy(bitmap
);
2378 progressive_paints_
.erase(progressive_paints_
.begin() + progressive_index
);
2380 client_
->DocumentPaintOccurred();
2383 void PDFiumEngine::CancelPaints() {
2384 for (size_t i
= 0; i
< progressive_paints_
.size(); ++i
) {
2385 FPDF_RenderPage_Close(pages_
[progressive_paints_
[i
].page_index
]->GetPage());
2386 FPDFBitmap_Destroy(progressive_paints_
[i
].bitmap
);
2388 progressive_paints_
.clear();
2391 void PDFiumEngine::FillPageSides(int progressive_index
) {
2392 int page_index
= progressive_paints_
[progressive_index
].page_index
;
2393 pp::Rect dirty_in_screen
= progressive_paints_
[progressive_index
].rect
;
2394 FPDF_BITMAP bitmap
= progressive_paints_
[progressive_index
].bitmap
;
2396 pp::Rect page_rect
= pages_
[page_index
]->rect();
2397 if (page_rect
.x() > 0) {
2399 page_rect
.y() - kPageShadowTop
,
2400 page_rect
.x() - kPageShadowLeft
,
2401 page_rect
.height() + kPageShadowTop
+
2402 kPageShadowBottom
+ kPageSeparatorThickness
);
2403 left
= GetScreenRect(left
).Intersect(dirty_in_screen
);
2405 FPDFBitmap_FillRect(
2406 bitmap
, left
.x() - dirty_in_screen
.x(),
2407 left
.y() - dirty_in_screen
.y(), left
.width(), left
.height(),
2408 kBackgroundColorR
, kBackgroundColorG
, kBackgroundColorB
,
2412 if (page_rect
.right() < document_size_
.width()) {
2413 pp::Rect
right(page_rect
.right() + kPageShadowRight
,
2414 page_rect
.y() - kPageShadowTop
,
2415 document_size_
.width() - page_rect
.right() -
2417 page_rect
.height() + kPageShadowTop
+
2418 kPageShadowBottom
+ kPageSeparatorThickness
);
2419 right
= GetScreenRect(right
).Intersect(dirty_in_screen
);
2421 FPDFBitmap_FillRect(
2422 bitmap
, right
.x() - dirty_in_screen
.x(),
2423 right
.y() - dirty_in_screen
.y(), right
.width(), right
.height(),
2424 kBackgroundColorR
, kBackgroundColorG
, kBackgroundColorB
,
2429 pp::Rect
bottom(page_rect
.x() - kPageShadowLeft
,
2430 page_rect
.bottom() + kPageShadowBottom
,
2431 page_rect
.width() + kPageShadowLeft
+ kPageShadowRight
,
2432 kPageSeparatorThickness
);
2433 bottom
= GetScreenRect(bottom
).Intersect(dirty_in_screen
);
2435 FPDFBitmap_FillRect(
2436 bitmap
, bottom
.x() - dirty_in_screen
.x(),
2437 bottom
.y() - dirty_in_screen
.y(), bottom
.width(), bottom
.height(),
2438 kBackgroundColorR
, kBackgroundColorG
, kBackgroundColorB
,
2442 void PDFiumEngine::PaintPageShadow(int progressive_index
,
2443 pp::ImageData
* image_data
) {
2444 int page_index
= progressive_paints_
[progressive_index
].page_index
;
2445 pp::Rect dirty_in_screen
= progressive_paints_
[progressive_index
].rect
;
2446 pp::Rect page_rect
= pages_
[page_index
]->rect();
2447 pp::Rect
shadow_rect(page_rect
);
2448 shadow_rect
.Inset(-kPageShadowLeft
, -kPageShadowTop
,
2449 -kPageShadowRight
, -kPageShadowBottom
);
2451 // Due to the rounding errors of the GetScreenRect it is possible to get
2452 // different size shadows on the left and right sides even they are defined
2453 // the same. To fix this issue let's calculate shadow rect and then shrink
2454 // it by the size of the shadows.
2455 shadow_rect
= GetScreenRect(shadow_rect
);
2456 page_rect
= shadow_rect
;
2458 page_rect
.Inset(static_cast<int>(ceil(kPageShadowLeft
* current_zoom_
)),
2459 static_cast<int>(ceil(kPageShadowTop
* current_zoom_
)),
2460 static_cast<int>(ceil(kPageShadowRight
* current_zoom_
)),
2461 static_cast<int>(ceil(kPageShadowBottom
* current_zoom_
)));
2463 DrawPageShadow(page_rect
, shadow_rect
, dirty_in_screen
, image_data
);
2466 void PDFiumEngine::DrawSelections(int progressive_index
,
2467 pp::ImageData
* image_data
) {
2468 int page_index
= progressive_paints_
[progressive_index
].page_index
;
2469 pp::Rect dirty_in_screen
= progressive_paints_
[progressive_index
].rect
;
2471 void* region
= NULL
;
2473 GetRegion(dirty_in_screen
.point(), image_data
, ®ion
, &stride
);
2475 std::vector
<pp::Rect
> highlighted_rects
;
2476 pp::Rect visible_rect
= GetVisibleRect();
2477 for (size_t k
= 0; k
< selection_
.size(); ++k
) {
2478 if (selection_
[k
].page_index() != page_index
)
2480 std::vector
<pp::Rect
> rects
= selection_
[k
].GetScreenRects(
2481 visible_rect
.point(), current_zoom_
, current_rotation_
);
2482 for (size_t j
= 0; j
< rects
.size(); ++j
) {
2483 pp::Rect visible_selection
= rects
[j
].Intersect(dirty_in_screen
);
2484 if (visible_selection
.IsEmpty())
2487 visible_selection
.Offset(
2488 -dirty_in_screen
.point().x(), -dirty_in_screen
.point().y());
2489 Highlight(region
, stride
, visible_selection
, &highlighted_rects
);
2493 for (size_t k
= 0; k
< form_highlights_
.size(); ++k
) {
2494 pp::Rect visible_selection
= form_highlights_
[k
].Intersect(dirty_in_screen
);
2495 if (visible_selection
.IsEmpty())
2498 visible_selection
.Offset(
2499 -dirty_in_screen
.point().x(), -dirty_in_screen
.point().y());
2500 Highlight(region
, stride
, visible_selection
, &highlighted_rects
);
2502 form_highlights_
.clear();
2505 void PDFiumEngine::PaintUnavailablePage(int page_index
,
2506 const pp::Rect
& dirty
,
2507 pp::ImageData
* image_data
) {
2508 int start_x
, start_y
, size_x
, size_y
;
2509 GetPDFiumRect(page_index
, dirty
, &start_x
, &start_y
, &size_x
, &size_y
);
2510 FPDF_BITMAP bitmap
= CreateBitmap(dirty
, image_data
);
2511 FPDFBitmap_FillRect(bitmap
, start_x
, start_y
, size_x
, size_y
,
2512 kPendingPageColorR
, kPendingPageColorG
, kPendingPageColorB
,
2513 kPendingPageColorA
);
2515 pp::Rect
loading_text_in_screen(
2516 pages_
[page_index
]->rect().width() / 2,
2517 pages_
[page_index
]->rect().y() + kLoadingTextVerticalOffset
, 0, 0);
2518 loading_text_in_screen
= GetScreenRect(loading_text_in_screen
);
2519 FPDFBitmap_Destroy(bitmap
);
2522 int PDFiumEngine::GetProgressiveIndex(int page_index
) const {
2523 for (size_t i
= 0; i
< progressive_paints_
.size(); ++i
) {
2524 if (progressive_paints_
[i
].page_index
== page_index
)
2530 FPDF_BITMAP
PDFiumEngine::CreateBitmap(const pp::Rect
& rect
,
2531 pp::ImageData
* image_data
) const {
2534 GetRegion(rect
.point(), image_data
, ®ion
, &stride
);
2537 return FPDFBitmap_CreateEx(
2538 rect
.width(), rect
.height(), FPDFBitmap_BGRx
, region
, stride
);
2541 void PDFiumEngine::GetPDFiumRect(
2542 int page_index
, const pp::Rect
& rect
, int* start_x
, int* start_y
,
2543 int* size_x
, int* size_y
) const {
2544 pp::Rect page_rect
= GetScreenRect(pages_
[page_index
]->rect());
2545 page_rect
.Offset(-rect
.x(), -rect
.y());
2547 *start_x
= page_rect
.x();
2548 *start_y
= page_rect
.y();
2549 *size_x
= page_rect
.width();
2550 *size_y
= page_rect
.height();
2553 int PDFiumEngine::GetRenderingFlags() const {
2554 int flags
= FPDF_LCD_TEXT
| FPDF_NO_CATCH
;
2555 if (render_grayscale_
)
2556 flags
|= FPDF_GRAYSCALE
;
2557 if (client_
->IsPrintPreview())
2558 flags
|= FPDF_PRINTING
;
2562 pp::Rect
PDFiumEngine::GetVisibleRect() const {
2564 rv
.set_x(static_cast<int>(position_
.x() / current_zoom_
));
2565 rv
.set_y(static_cast<int>(position_
.y() / current_zoom_
));
2566 rv
.set_width(static_cast<int>(ceil(plugin_size_
.width() / current_zoom_
)));
2567 rv
.set_height(static_cast<int>(ceil(plugin_size_
.height() / current_zoom_
)));
2571 pp::Rect
PDFiumEngine::GetPageScreenRect(int page_index
) const {
2572 // Since we use this rect for creating the PDFium bitmap, also include other
2573 // areas around the page that we might need to update such as the page
2574 // separator and the sides if the page is narrower than the document.
2575 return GetScreenRect(pp::Rect(
2577 pages_
[page_index
]->rect().y() - kPageShadowTop
,
2578 document_size_
.width(),
2579 pages_
[page_index
]->rect().height() + kPageShadowTop
+
2580 kPageShadowBottom
+ kPageSeparatorThickness
));
2583 pp::Rect
PDFiumEngine::GetScreenRect(const pp::Rect
& rect
) const {
2586 static_cast<int>(ceil(rect
.right() * current_zoom_
- position_
.x()));
2588 static_cast<int>(ceil(rect
.bottom() * current_zoom_
- position_
.y()));
2590 rv
.set_x(static_cast<int>(rect
.x() * current_zoom_
- position_
.x()));
2591 rv
.set_y(static_cast<int>(rect
.y() * current_zoom_
- position_
.y()));
2592 rv
.set_width(right
- rv
.x());
2593 rv
.set_height(bottom
- rv
.y());
2597 void PDFiumEngine::Highlight(void* buffer
,
2599 const pp::Rect
& rect
,
2600 std::vector
<pp::Rect
>* highlighted_rects
) {
2604 pp::Rect new_rect
= rect
;
2605 for (size_t i
= 0; i
< highlighted_rects
->size(); ++i
)
2606 new_rect
= new_rect
.Subtract((*highlighted_rects
)[i
]);
2608 highlighted_rects
->push_back(new_rect
);
2609 int l
= new_rect
.x();
2610 int t
= new_rect
.y();
2611 int w
= new_rect
.width();
2612 int h
= new_rect
.height();
2614 for (int y
= t
; y
< t
+ h
; ++y
) {
2615 for (int x
= l
; x
< l
+ w
; ++x
) {
2616 uint8
* pixel
= static_cast<uint8
*>(buffer
) + y
* stride
+ x
* 4;
2617 // This is our highlight color.
2618 pixel
[0] = static_cast<uint8
>(
2619 pixel
[0] * (kHighlightColorB
/ 255.0));
2620 pixel
[1] = static_cast<uint8
>(
2621 pixel
[1] * (kHighlightColorG
/ 255.0));
2622 pixel
[2] = static_cast<uint8
>(
2623 pixel
[2] * (kHighlightColorR
/ 255.0));
2628 PDFiumEngine::SelectionChangeInvalidator::SelectionChangeInvalidator(
2629 PDFiumEngine
* engine
) : engine_(engine
) {
2630 previous_origin_
= engine_
->GetVisibleRect().point();
2631 GetVisibleSelectionsScreenRects(&old_selections_
);
2634 PDFiumEngine::SelectionChangeInvalidator::~SelectionChangeInvalidator() {
2635 // Offset the old selections if the document scrolled since we recorded them.
2636 pp::Point offset
= previous_origin_
- engine_
->GetVisibleRect().point();
2637 for (size_t i
= 0; i
< old_selections_
.size(); ++i
)
2638 old_selections_
[i
].Offset(offset
);
2640 std::vector
<pp::Rect
> new_selections
;
2641 GetVisibleSelectionsScreenRects(&new_selections
);
2642 for (size_t i
= 0; i
< new_selections
.size(); ++i
) {
2643 for (size_t j
= 0; j
< old_selections_
.size(); ++j
) {
2644 if (new_selections
[i
] == old_selections_
[j
]) {
2645 // Rectangle was selected before and after, so no need to invalidate it.
2646 // Mark the rectangles by setting them to empty.
2647 new_selections
[i
] = old_selections_
[j
] = pp::Rect();
2652 for (size_t i
= 0; i
< old_selections_
.size(); ++i
) {
2653 if (!old_selections_
[i
].IsEmpty())
2654 engine_
->client_
->Invalidate(old_selections_
[i
]);
2656 for (size_t i
= 0; i
< new_selections
.size(); ++i
) {
2657 if (!new_selections
[i
].IsEmpty())
2658 engine_
->client_
->Invalidate(new_selections
[i
]);
2660 engine_
->OnSelectionChanged();
2664 PDFiumEngine::SelectionChangeInvalidator::GetVisibleSelectionsScreenRects(
2665 std::vector
<pp::Rect
>* rects
) {
2666 pp::Rect visible_rect
= engine_
->GetVisibleRect();
2667 for (size_t i
= 0; i
< engine_
->selection_
.size(); ++i
) {
2668 int page_index
= engine_
->selection_
[i
].page_index();
2669 if (!engine_
->IsPageVisible(page_index
))
2670 continue; // This selection is on a page that's not currently visible.
2672 std::vector
<pp::Rect
> selection_rects
=
2673 engine_
->selection_
[i
].GetScreenRects(
2674 visible_rect
.point(),
2675 engine_
->current_zoom_
,
2676 engine_
->current_rotation_
);
2677 rects
->insert(rects
->end(), selection_rects
.begin(), selection_rects
.end());
2681 void PDFiumEngine::DeviceToPage(int page_index
,
2686 *page_x
= *page_y
= 0;
2687 int temp_x
= static_cast<int>((device_x
+ position_
.x())/ current_zoom_
-
2688 pages_
[page_index
]->rect().x());
2689 int temp_y
= static_cast<int>((device_y
+ position_
.y())/ current_zoom_
-
2690 pages_
[page_index
]->rect().y());
2692 pages_
[page_index
]->GetPage(), 0, 0,
2693 pages_
[page_index
]->rect().width(), pages_
[page_index
]->rect().height(),
2694 current_rotation_
, temp_x
, temp_y
, page_x
, page_y
);
2697 int PDFiumEngine::GetVisiblePageIndex(FPDF_PAGE page
) {
2698 for (size_t i
= 0; i
< visible_pages_
.size(); ++i
) {
2699 if (pages_
[visible_pages_
[i
]]->GetPage() == page
)
2700 return visible_pages_
[i
];
2705 void PDFiumEngine::SetCurrentPage(int index
) {
2706 if (index
== most_visible_page_
|| !form_
)
2708 if (most_visible_page_
!= -1 && called_do_document_action_
) {
2709 FPDF_PAGE old_page
= pages_
[most_visible_page_
]->GetPage();
2710 FORM_DoPageAAction(old_page
, form_
, FPDFPAGE_AACTION_CLOSE
);
2712 most_visible_page_
= index
;
2713 #if defined(OS_LINUX)
2714 g_last_instance_id
= client_
->GetPluginInstance()->pp_instance();
2716 if (most_visible_page_
!= -1 && called_do_document_action_
) {
2717 FPDF_PAGE new_page
= pages_
[most_visible_page_
]->GetPage();
2718 FORM_DoPageAAction(new_page
, form_
, FPDFPAGE_AACTION_OPEN
);
2722 void PDFiumEngine::TransformPDFPageForPrinting(
2724 const PP_PrintSettings_Dev
& print_settings
) {
2725 // Get the source page width and height in points.
2726 const double src_page_width
= FPDF_GetPageWidth(page
);
2727 const double src_page_height
= FPDF_GetPageHeight(page
);
2729 const int src_page_rotation
= FPDFPage_GetRotation(page
);
2730 const bool fit_to_page
= print_settings
.print_scaling_option
==
2731 PP_PRINTSCALINGOPTION_FIT_TO_PRINTABLE_AREA
;
2733 pp::Size
page_size(print_settings
.paper_size
);
2734 pp::Rect
content_rect(print_settings
.printable_area
);
2735 const bool rotated
= (src_page_rotation
% 2 == 1);
2736 SetPageSizeAndContentRect(rotated
,
2737 src_page_width
> src_page_height
,
2741 // Compute the screen page width and height in points.
2742 const int actual_page_width
=
2743 rotated
? page_size
.height() : page_size
.width();
2744 const int actual_page_height
=
2745 rotated
? page_size
.width() : page_size
.height();
2747 const double scale_factor
= CalculateScaleFactor(fit_to_page
, content_rect
,
2749 src_page_height
, rotated
);
2751 // Calculate positions for the clip box.
2752 ClipBox source_clip_box
;
2753 CalculateClipBoxBoundary(page
, scale_factor
, rotated
, &source_clip_box
);
2755 // Calculate the translation offset values.
2756 double offset_x
= 0;
2757 double offset_y
= 0;
2759 CalculateScaledClipBoxOffset(content_rect
, source_clip_box
, &offset_x
,
2762 CalculateNonScaledClipBoxOffset(content_rect
, src_page_rotation
,
2763 actual_page_width
, actual_page_height
,
2764 source_clip_box
, &offset_x
, &offset_y
);
2767 // Reset the media box and crop box. When the page has crop box and media box,
2768 // the plugin will display the crop box contents and not the entire media box.
2769 // If the pages have different crop box values, the plugin will display a
2770 // document of multiple page sizes. To give better user experience, we
2771 // decided to have same crop box and media box values. Hence, the user will
2772 // see a list of uniform pages.
2773 FPDFPage_SetMediaBox(page
, 0, 0, page_size
.width(), page_size
.height());
2774 FPDFPage_SetCropBox(page
, 0, 0, page_size
.width(), page_size
.height());
2776 // Transformation is not required, return. Do this check only after updating
2777 // the media box and crop box. For more detailed information, please refer to
2778 // the comment block right before FPDF_SetMediaBox and FPDF_GetMediaBox calls.
2779 if (scale_factor
== 1.0 && offset_x
== 0 && offset_y
== 0)
2783 // All the positions have been calculated, now manipulate the PDF.
2784 FS_MATRIX matrix
= {static_cast<float>(scale_factor
),
2787 static_cast<float>(scale_factor
),
2788 static_cast<float>(offset_x
),
2789 static_cast<float>(offset_y
)};
2790 FS_RECTF cliprect
= {static_cast<float>(source_clip_box
.left
+offset_x
),
2791 static_cast<float>(source_clip_box
.top
+offset_y
),
2792 static_cast<float>(source_clip_box
.right
+offset_x
),
2793 static_cast<float>(source_clip_box
.bottom
+offset_y
)};
2794 FPDFPage_TransFormWithClip(page
, &matrix
, &cliprect
);
2795 FPDFPage_TransformAnnots(page
, scale_factor
, 0, 0, scale_factor
,
2796 offset_x
, offset_y
);
2799 void PDFiumEngine::DrawPageShadow(const pp::Rect
& page_rc
,
2800 const pp::Rect
& shadow_rc
,
2801 const pp::Rect
& clip_rc
,
2802 pp::ImageData
* image_data
) {
2803 pp::Rect
page_rect(page_rc
);
2804 page_rect
.Offset(page_offset_
);
2806 pp::Rect
shadow_rect(shadow_rc
);
2807 shadow_rect
.Offset(page_offset_
);
2809 pp::Rect
clip_rect(clip_rc
);
2810 clip_rect
.Offset(page_offset_
);
2812 // Page drop shadow parameters.
2813 const double factor
= 0.5;
2814 const uint32 background
= (kBackgroundColorA
<< 24) |
2815 (kBackgroundColorR
<< 16) |
2816 (kBackgroundColorG
<< 8) |
2818 uint32 depth
= std::max(
2819 std::max(page_rect
.x() - shadow_rect
.x(),
2820 page_rect
.y() - shadow_rect
.y()),
2821 std::max(shadow_rect
.right() - page_rect
.right(),
2822 shadow_rect
.bottom() - page_rect
.bottom()));
2823 depth
= static_cast<uint32
>(depth
* 1.5) + 1;
2825 // We need to check depth only to verify our copy of shadow matrix is correct.
2826 if (!page_shadow_
.get() || page_shadow_
->depth() != depth
)
2827 page_shadow_
.reset(new ShadowMatrix(depth
, factor
, background
));
2829 DCHECK(!image_data
->is_null());
2830 DrawShadow(image_data
, shadow_rect
, page_rect
, clip_rect
, *page_shadow_
);
2833 void PDFiumEngine::GetRegion(const pp::Point
& location
,
2834 pp::ImageData
* image_data
,
2836 int* stride
) const {
2837 if (image_data
->is_null()) {
2838 DCHECK(plugin_size_
.IsEmpty());
2843 char* buffer
= static_cast<char*>(image_data
->data());
2844 *stride
= image_data
->stride();
2846 pp::Point offset_location
= location
+ page_offset_
;
2847 // TODO: update this when we support BIDI and scrollbars can be on the left.
2849 !pp::Rect(page_offset_
, plugin_size_
).Contains(offset_location
)) {
2854 buffer
+= location
.y() * (*stride
);
2855 buffer
+= (location
.x() + page_offset_
.x()) * 4;
2859 void PDFiumEngine::OnSelectionChanged() {
2860 if (HasPermission(PDFEngine::PERMISSION_COPY
))
2861 pp::PDF::SetSelectedText(GetPluginInstance(), GetSelectedText().c_str());
2864 void PDFiumEngine::Form_Invalidate(FPDF_FORMFILLINFO
* param
,
2870 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
2871 int page_index
= engine
->GetVisiblePageIndex(page
);
2872 if (page_index
== -1) {
2873 // This can sometime happen when the page is closed because it went off
2874 // screen, and PDFium invalidates the control as it's being deleted.
2878 pp::Rect rect
= engine
->pages_
[page_index
]->PageToScreen(
2879 engine
->GetVisibleRect().point(), engine
->current_zoom_
, left
, top
, right
,
2880 bottom
, engine
->current_rotation_
);
2881 engine
->client_
->Invalidate(rect
);
2884 void PDFiumEngine::Form_OutputSelectedRect(FPDF_FORMFILLINFO
* param
,
2890 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
2891 int page_index
= engine
->GetVisiblePageIndex(page
);
2892 if (page_index
== -1) {
2896 pp::Rect rect
= engine
->pages_
[page_index
]->PageToScreen(
2897 engine
->GetVisibleRect().point(), engine
->current_zoom_
, left
, top
, right
,
2898 bottom
, engine
->current_rotation_
);
2899 engine
->form_highlights_
.push_back(rect
);
2902 void PDFiumEngine::Form_SetCursor(FPDF_FORMFILLINFO
* param
, int cursor_type
) {
2903 // We don't need this since it's not enough to change the cursor in all
2904 // scenarios. Instead, we check which form field we're under in OnMouseMove.
2907 int PDFiumEngine::Form_SetTimer(FPDF_FORMFILLINFO
* param
,
2909 TimerCallback timer_func
) {
2910 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
2911 engine
->timers_
[++engine
->next_timer_id_
] =
2912 std::pair
<int, TimerCallback
>(elapse
, timer_func
);
2913 engine
->client_
->ScheduleCallback(engine
->next_timer_id_
, elapse
);
2914 return engine
->next_timer_id_
;
2917 void PDFiumEngine::Form_KillTimer(FPDF_FORMFILLINFO
* param
, int timer_id
) {
2918 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
2919 engine
->timers_
.erase(timer_id
);
2922 FPDF_SYSTEMTIME
PDFiumEngine::Form_GetLocalTime(FPDF_FORMFILLINFO
* param
) {
2923 base::Time time
= base::Time::Now();
2924 base::Time::Exploded exploded
;
2925 time
.LocalExplode(&exploded
);
2928 rv
.wYear
= exploded
.year
;
2929 rv
.wMonth
= exploded
.month
;
2930 rv
.wDayOfWeek
= exploded
.day_of_week
;
2931 rv
.wDay
= exploded
.day_of_month
;
2932 rv
.wHour
= exploded
.hour
;
2933 rv
.wMinute
= exploded
.minute
;
2934 rv
.wSecond
= exploded
.second
;
2935 rv
.wMilliseconds
= exploded
.millisecond
;
2939 void PDFiumEngine::Form_OnChange(FPDF_FORMFILLINFO
* param
) {
2940 // Don't care about.
2943 FPDF_PAGE
PDFiumEngine::Form_GetPage(FPDF_FORMFILLINFO
* param
,
2944 FPDF_DOCUMENT document
,
2946 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
2947 if (page_index
< 0 || page_index
>= static_cast<int>(engine
->pages_
.size()))
2949 return engine
->pages_
[page_index
]->GetPage();
2952 FPDF_PAGE
PDFiumEngine::Form_GetCurrentPage(FPDF_FORMFILLINFO
* param
,
2953 FPDF_DOCUMENT document
) {
2954 // TODO(jam): find out what this is used for.
2955 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
2956 int index
= engine
->last_page_mouse_down_
;
2958 index
= engine
->GetMostVisiblePage();
2965 return engine
->pages_
[index
]->GetPage();
2968 int PDFiumEngine::Form_GetRotation(FPDF_FORMFILLINFO
* param
, FPDF_PAGE page
) {
2972 void PDFiumEngine::Form_ExecuteNamedAction(FPDF_FORMFILLINFO
* param
,
2973 FPDF_BYTESTRING named_action
) {
2974 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
2975 std::string
action(named_action
);
2976 if (action
== "Print") {
2977 engine
->client_
->Print();
2981 int index
= engine
->last_page_mouse_down_
;
2982 /* Don't try to calculate the most visible page if we don't have a left click
2983 before this event (this code originally copied Form_GetCurrentPage which of
2984 course needs to do that and which doesn't have recursion). This can end up
2985 causing infinite recursion. See http://crbug.com/240413 for more
2986 information. Either way, it's not necessary for the spec'd list of named
2989 index = engine->GetMostVisiblePage();
2994 // This is the only list of named actions per the spec (see 12.6.4.11). Adobe
2995 // Reader supports more, like FitWidth, but since they're not part of the spec
2996 // and we haven't got bugs about them, no need to now.
2997 if (action
== "NextPage") {
2998 engine
->client_
->ScrollToPage(index
+ 1);
2999 } else if (action
== "PrevPage") {
3000 engine
->client_
->ScrollToPage(index
- 1);
3001 } else if (action
== "FirstPage") {
3002 engine
->client_
->ScrollToPage(0);
3003 } else if (action
== "LastPage") {
3004 engine
->client_
->ScrollToPage(engine
->pages_
.size() - 1);
3008 void PDFiumEngine::Form_SetTextFieldFocus(FPDF_FORMFILLINFO
* param
,
3009 FPDF_WIDESTRING value
,
3010 FPDF_DWORD valueLen
,
3011 FPDF_BOOL is_focus
) {
3012 // Do nothing for now.
3013 // TODO(gene): use this signal to trigger OSK.
3016 void PDFiumEngine::Form_DoURIAction(FPDF_FORMFILLINFO
* param
,
3017 FPDF_BYTESTRING uri
) {
3018 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3019 engine
->client_
->NavigateTo(std::string(uri
), false);
3022 void PDFiumEngine::Form_DoGoToAction(FPDF_FORMFILLINFO
* param
,
3025 float* position_array
,
3026 int size_of_array
) {
3027 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3028 engine
->client_
->ScrollToPage(page_index
);
3031 int PDFiumEngine::Form_Alert(IPDF_JSPLATFORM
* param
,
3032 FPDF_WIDESTRING message
,
3033 FPDF_WIDESTRING title
,
3036 // See fpdfformfill.h for these values.
3039 ALERT_TYPE_OK_CANCEL
,
3041 ALERT_TYPE_YES_NO_CANCEL
3045 ALERT_RESULT_OK
= 1,
3046 ALERT_RESULT_CANCEL
,
3051 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3052 std::string message_str
=
3053 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(message
));
3054 if (type
== ALERT_TYPE_OK
) {
3055 engine
->client_
->Alert(message_str
);
3056 return ALERT_RESULT_OK
;
3059 bool rv
= engine
->client_
->Confirm(message_str
);
3060 if (type
== ALERT_TYPE_OK_CANCEL
)
3061 return rv
? ALERT_RESULT_OK
: ALERT_RESULT_CANCEL
;
3062 return rv
? ALERT_RESULT_YES
: ALERT_RESULT_NO
;
3065 void PDFiumEngine::Form_Beep(IPDF_JSPLATFORM
* param
, int type
) {
3066 // Beeps are annoying, and not possible using javascript, so ignore for now.
3069 int PDFiumEngine::Form_Response(IPDF_JSPLATFORM
* param
,
3070 FPDF_WIDESTRING question
,
3071 FPDF_WIDESTRING title
,
3072 FPDF_WIDESTRING default_response
,
3073 FPDF_WIDESTRING label
,
3077 std::string question_str
= base::UTF16ToUTF8(
3078 reinterpret_cast<const base::char16
*>(question
));
3079 std::string default_str
= base::UTF16ToUTF8(
3080 reinterpret_cast<const base::char16
*>(default_response
));
3082 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3083 std::string rv
= engine
->client_
->Prompt(question_str
, default_str
);
3084 base::string16 rv_16
= base::UTF8ToUTF16(rv
);
3085 int rv_bytes
= rv_16
.size() * sizeof(base::char16
);
3086 if (response
&& rv_bytes
<= length
)
3087 memcpy(response
, rv_16
.c_str(), rv_bytes
);
3091 int PDFiumEngine::Form_GetFilePath(IPDF_JSPLATFORM
* param
,
3094 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3095 std::string rv
= engine
->client_
->GetURL();
3096 if (file_path
&& rv
.size() <= static_cast<size_t>(length
))
3097 memcpy(file_path
, rv
.c_str(), rv
.size());
3101 void PDFiumEngine::Form_Mail(IPDF_JSPLATFORM
* param
,
3106 FPDF_WIDESTRING subject
,
3108 FPDF_WIDESTRING bcc
,
3109 FPDF_WIDESTRING message
) {
3110 DCHECK(length
== 0); // Don't handle attachments; no way with mailto.
3111 std::string to_str
=
3112 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(to
));
3113 std::string cc_str
=
3114 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(cc
));
3115 std::string bcc_str
=
3116 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(bcc
));
3117 std::string subject_str
=
3118 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(subject
));
3119 std::string message_str
=
3120 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(message
));
3122 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3123 engine
->client_
->Email(to_str
, cc_str
, bcc_str
, subject_str
, message_str
);
3126 void PDFiumEngine::Form_Print(IPDF_JSPLATFORM
* param
,
3131 FPDF_BOOL shrink_to_fit
,
3132 FPDF_BOOL print_as_image
,
3134 FPDF_BOOL annotations
) {
3135 // No way to pass the extra information to the print dialog using JavaScript.
3136 // Just opening it is fine for now.
3137 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3138 engine
->client_
->Print();
3141 void PDFiumEngine::Form_SubmitForm(IPDF_JSPLATFORM
* param
,
3144 FPDF_WIDESTRING url
) {
3145 std::string url_str
=
3146 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(url
));
3147 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3148 engine
->client_
->SubmitForm(url_str
, form_data
, length
);
3151 void PDFiumEngine::Form_GotoPage(IPDF_JSPLATFORM
* param
,
3153 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3154 engine
->client_
->ScrollToPage(page_number
);
3157 int PDFiumEngine::Form_Browse(IPDF_JSPLATFORM
* param
,
3160 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3161 std::string path
= engine
->client_
->ShowFileSelectionDialog();
3162 if (path
.size() + 1 <= static_cast<size_t>(length
))
3163 memcpy(file_path
, &path
[0], path
.size() + 1);
3164 return path
.size() + 1;
3167 FPDF_BOOL
PDFiumEngine::Pause_NeedToPauseNow(IFSDK_PAUSE
* param
) {
3168 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3169 return (base::Time::Now() - engine
->last_progressive_start_time_
).
3170 InMilliseconds() > engine
->progressive_paint_timeout_
;
3173 ScopedUnsupportedFeature::ScopedUnsupportedFeature(PDFiumEngine
* engine
)
3174 : engine_(engine
), old_engine_(g_engine_for_unsupported
) {
3175 g_engine_for_unsupported
= engine_
;
3178 ScopedUnsupportedFeature::~ScopedUnsupportedFeature() {
3179 g_engine_for_unsupported
= old_engine_
;
3182 PDFEngineExports
* PDFEngineExports::Create() {
3183 return new PDFiumEngineExports
;
3188 int CalculatePosition(FPDF_PAGE page
,
3189 const PDFiumEngineExports::RenderingSettings
& settings
,
3191 int page_width
= static_cast<int>(
3192 FPDF_GetPageWidth(page
) * settings
.dpi_x
/ kPointsPerInch
);
3193 int page_height
= static_cast<int>(
3194 FPDF_GetPageHeight(page
) * settings
.dpi_y
/ kPointsPerInch
);
3196 // Start by assuming that we will draw exactly to the bounds rect
3198 *dest
= settings
.bounds
;
3200 int rotate
= 0; // normal orientation.
3202 // Auto-rotate landscape pages to print correctly.
3203 if (settings
.autorotate
&&
3204 (dest
->width() > dest
->height()) != (page_width
> page_height
)) {
3205 rotate
= 1; // 90 degrees clockwise.
3206 std::swap(page_width
, page_height
);
3209 // See if we need to scale the output
3210 bool scale_to_bounds
= false;
3211 if (settings
.fit_to_bounds
&&
3212 ((page_width
> dest
->width()) || (page_height
> dest
->height()))) {
3213 scale_to_bounds
= true;
3214 } else if (settings
.stretch_to_bounds
&&
3215 ((page_width
< dest
->width()) || (page_height
< dest
->height()))) {
3216 scale_to_bounds
= true;
3219 if (scale_to_bounds
) {
3220 // If we need to maintain aspect ratio, calculate the actual width and
3222 if (settings
.keep_aspect_ratio
) {
3223 double scale_factor_x
= page_width
;
3224 scale_factor_x
/= dest
->width();
3225 double scale_factor_y
= page_height
;
3226 scale_factor_y
/= dest
->height();
3227 if (scale_factor_x
> scale_factor_y
) {
3228 dest
->set_height(page_height
/ scale_factor_x
);
3230 dest
->set_width(page_width
/ scale_factor_y
);
3234 // We are not scaling to bounds. Draw in the actual page size. If the
3235 // actual page size is larger than the bounds, the output will be
3237 dest
->set_width(page_width
);
3238 dest
->set_height(page_height
);
3241 if (settings
.center_in_bounds
) {
3242 pp::Point
offset((settings
.bounds
.width() - dest
->width()) / 2,
3243 (settings
.bounds
.height() - dest
->height()) / 2);
3244 dest
->Offset(offset
);
3252 bool PDFiumEngineExports::RenderPDFPageToDC(const void* pdf_buffer
,
3255 const RenderingSettings
& settings
,
3257 FPDF_DOCUMENT doc
= FPDF_LoadMemDocument(pdf_buffer
, buffer_size
, NULL
);
3260 FPDF_PAGE page
= FPDF_LoadPage(doc
, page_number
);
3262 FPDF_CloseDocument(doc
);
3265 RenderingSettings new_settings
= settings
;
3266 // calculate the page size
3267 if (new_settings
.dpi_x
== -1)
3268 new_settings
.dpi_x
= GetDeviceCaps(dc
, LOGPIXELSX
);
3269 if (new_settings
.dpi_y
== -1)
3270 new_settings
.dpi_y
= GetDeviceCaps(dc
, LOGPIXELSY
);
3273 int rotate
= CalculatePosition(page
, new_settings
, &dest
);
3275 int save_state
= SaveDC(dc
);
3276 // The caller wanted all drawing to happen within the bounds specified.
3277 // Based on scale calculations, our destination rect might be larger
3278 // than the bounds. Set the clip rect to the bounds.
3279 IntersectClipRect(dc
, settings
.bounds
.x(), settings
.bounds
.y(),
3280 settings
.bounds
.x() + settings
.bounds
.width(),
3281 settings
.bounds
.y() + settings
.bounds
.height());
3283 // A temporary hack. PDFs generated by Cairo (used by Chrome OS to generate
3284 // a PDF output from a webpage) result in very large metafiles and the
3285 // rendering using FPDF_RenderPage is incorrect. In this case, render as a
3286 // bitmap. Note that this code does not kick in for PDFs printed from Chrome
3287 // because in that case we create a temp PDF first before printing and this
3288 // temp PDF does not have a creator string that starts with "cairo".
3289 base::string16 creator
;
3290 size_t buffer_bytes
= FPDF_GetMetaText(doc
, "Creator", NULL
, 0);
3291 if (buffer_bytes
> 1) {
3292 FPDF_GetMetaText(doc
, "Creator", WriteInto(&creator
, buffer_bytes
),
3295 bool use_bitmap
= false;
3296 if (StartsWith(creator
, L
"cairo", false))
3299 // Another temporary hack. Some PDFs seems to render very slowly if
3300 // FPDF_RenderPage is directly used on a printer DC. I suspect it is
3301 // because of the code to talk Postscript directly to the printer if
3302 // the printer supports this. Need to discuss this with PDFium. For now,
3303 // render to a bitmap and then blit the bitmap to the DC if we have been
3304 // supplied a printer DC.
3305 int device_type
= GetDeviceCaps(dc
, TECHNOLOGY
);
3307 (device_type
== DT_RASPRINTER
) || (device_type
== DT_PLOTTER
)) {
3308 FPDF_BITMAP bitmap
= FPDFBitmap_Create(dest
.width(), dest
.height(),
3311 FPDFBitmap_FillRect(bitmap
, 0, 0, dest
.width(), dest
.height(), 255, 255,
3313 FPDF_RenderPageBitmap(
3314 bitmap
, page
, 0, 0, dest
.width(), dest
.height(), rotate
,
3315 FPDF_ANNOT
| FPDF_PRINTING
| FPDF_NO_CATCH
);
3316 int stride
= FPDFBitmap_GetStride(bitmap
);
3318 memset(&bmi
, 0, sizeof(bmi
));
3319 bmi
.bmiHeader
.biSize
= sizeof(BITMAPINFOHEADER
);
3320 bmi
.bmiHeader
.biWidth
= dest
.width();
3321 bmi
.bmiHeader
.biHeight
= -dest
.height(); // top-down image
3322 bmi
.bmiHeader
.biPlanes
= 1;
3323 bmi
.bmiHeader
.biBitCount
= 32;
3324 bmi
.bmiHeader
.biCompression
= BI_RGB
;
3325 bmi
.bmiHeader
.biSizeImage
= stride
* dest
.height();
3326 StretchDIBits(dc
, dest
.x(), dest
.y(), dest
.width(), dest
.height(),
3327 0, 0, dest
.width(), dest
.height(),
3328 FPDFBitmap_GetBuffer(bitmap
), &bmi
, DIB_RGB_COLORS
, SRCCOPY
);
3329 FPDFBitmap_Destroy(bitmap
);
3331 FPDF_RenderPage(dc
, page
, dest
.x(), dest
.y(), dest
.width(), dest
.height(),
3332 rotate
, FPDF_ANNOT
| FPDF_PRINTING
| FPDF_NO_CATCH
);
3334 RestoreDC(dc
, save_state
);
3335 FPDF_ClosePage(page
);
3336 FPDF_CloseDocument(doc
);
3341 bool PDFiumEngineExports::RenderPDFPageToBitmap(
3342 const void* pdf_buffer
,
3343 int pdf_buffer_size
,
3345 const RenderingSettings
& settings
,
3346 void* bitmap_buffer
) {
3347 FPDF_DOCUMENT doc
= FPDF_LoadMemDocument(pdf_buffer
, pdf_buffer_size
, NULL
);
3350 FPDF_PAGE page
= FPDF_LoadPage(doc
, page_number
);
3352 FPDF_CloseDocument(doc
);
3357 int rotate
= CalculatePosition(page
, settings
, &dest
);
3359 FPDF_BITMAP bitmap
=
3360 FPDFBitmap_CreateEx(settings
.bounds
.width(), settings
.bounds
.height(),
3361 FPDFBitmap_BGRA
, bitmap_buffer
,
3362 settings
.bounds
.width() * 4);
3364 FPDFBitmap_FillRect(bitmap
, 0, 0, settings
.bounds
.width(),
3365 settings
.bounds
.height(), 255, 255, 255, 255);
3366 // Shift top-left corner of bounds to (0, 0) if it's not there.
3367 dest
.set_point(dest
.point() - settings
.bounds
.point());
3368 FPDF_RenderPageBitmap(
3369 bitmap
, page
, dest
.x(), dest
.y(), dest
.width(), dest
.height(), rotate
,
3370 FPDF_ANNOT
| FPDF_PRINTING
| FPDF_NO_CATCH
);
3371 FPDFBitmap_Destroy(bitmap
);
3372 FPDF_ClosePage(page
);
3373 FPDF_CloseDocument(doc
);
3377 bool PDFiumEngineExports::GetPDFDocInfo(const void* pdf_buffer
,
3380 double* max_page_width
) {
3381 FPDF_DOCUMENT doc
= FPDF_LoadMemDocument(pdf_buffer
, buffer_size
, NULL
);
3384 int page_count_local
= FPDF_GetPageCount(doc
);
3386 *page_count
= page_count_local
;
3388 if (max_page_width
) {
3389 *max_page_width
= 0;
3390 for (int page_number
= 0; page_number
< page_count_local
; page_number
++) {
3391 double page_width
= 0;
3392 double page_height
= 0;
3393 FPDF_GetPageSizeByIndex(doc
, page_number
, &page_width
, &page_height
);
3394 if (page_width
> *max_page_width
) {
3395 *max_page_width
= page_width
;
3399 FPDF_CloseDocument(doc
);
3403 } // namespace chrome_pdf