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 const uint32 kPendingPageColor
= 0xFFEEEEEE;
60 #define kFormHighlightColor 0xFFE4DD
61 #define kFormHighlightAlpha 100
63 #define kMaxPasswordTries 3
66 // http://www.adobe.com/devnet/acrobat/pdfs/pdf_reference_1-7.pdf
67 #define kPDFPermissionPrintLowQualityMask 1 << 2
68 #define kPDFPermissionPrintHighQualityMask 1 << 11
69 #define kPDFPermissionCopyMask 1 << 4
70 #define kPDFPermissionCopyAccessibleMask 1 << 9
72 #define kLoadingTextVerticalOffset 50
74 // The maximum amount of time we'll spend doing a paint before we give back
75 // control of the thread.
76 #define kMaxProgressivePaintTimeMs 50
78 // The maximum amount of time we'll spend doing the first paint. This is less
79 // than the above to keep things smooth if the user is scrolling quickly. We
80 // try painting a little because with accelerated compositing, we get flushes
81 // only every 16 ms. If we were to wait until the next flush to paint the rest
82 // of the pdf, we would never get to draw the pdf and would only draw the
83 // scrollbars. This value is picked to give enough time for gpu related code to
84 // do its thing and still fit within the timelimit for 60Hz. For the
85 // non-composited case, this doesn't make things worse since we're still
86 // painting the scrollbars > 60 Hz.
87 #define kMaxInitialProgressivePaintTimeMs 10
89 // Copied from printing/units.cc because we don't want to depend on printing
90 // since it brings in libpng which causes duplicate symbols with PDFium.
91 const int kPointsPerInch
= 72;
92 const int kPixelsPerInch
= 96;
101 int ConvertUnit(int value
, int old_unit
, int new_unit
) {
102 // With integer arithmetic, to divide a value with correct rounding, you need
103 // to add half of the divisor value to the dividend value. You need to do the
104 // reverse with negative number.
106 return ((value
* new_unit
) + (old_unit
/ 2)) / old_unit
;
108 return ((value
* new_unit
) - (old_unit
/ 2)) / old_unit
;
112 std::vector
<uint32_t> GetPageNumbersFromPrintPageNumberRange(
113 const PP_PrintPageNumberRange_Dev
* page_ranges
,
114 uint32_t page_range_count
) {
115 std::vector
<uint32_t> page_numbers
;
116 for (uint32_t index
= 0; index
< page_range_count
; ++index
) {
117 for (uint32_t page_number
= page_ranges
[index
].first_page_number
;
118 page_number
<= page_ranges
[index
].last_page_number
; ++page_number
) {
119 page_numbers
.push_back(page_number
);
125 #if defined(OS_LINUX)
127 PP_Instance g_last_instance_id
;
129 struct PDFFontSubstitution
{
130 const char* pdf_name
;
136 PP_BrowserFont_Trusted_Weight
WeightToBrowserFontTrustedWeight(int weight
) {
137 COMPILE_ASSERT(PP_BROWSERFONT_TRUSTED_WEIGHT_100
== 0,
138 PP_BrowserFont_Trusted_Weight_Min
);
139 COMPILE_ASSERT(PP_BROWSERFONT_TRUSTED_WEIGHT_900
== 8,
140 PP_BrowserFont_Trusted_Weight_Max
);
141 const int kMinimumWeight
= 100;
142 const int kMaximumWeight
= 900;
143 int normalized_weight
=
144 std::min(std::max(weight
, kMinimumWeight
), kMaximumWeight
);
145 normalized_weight
= (normalized_weight
/ 100) - 1;
146 return static_cast<PP_BrowserFont_Trusted_Weight
>(normalized_weight
);
149 // This list is for CPWL_FontMap::GetDefaultFontByCharset().
150 // We pretend to have these font natively and let the browser (or underlying
151 // fontconfig) to pick the proper font on the system.
152 void EnumFonts(struct _FPDF_SYSFONTINFO
* sysfontinfo
, void* mapper
) {
153 FPDF_AddInstalledFont(mapper
, "Arial", FXFONT_DEFAULT_CHARSET
);
156 while (CPWL_FontMap::defaultTTFMap
[i
].charset
!= -1) {
157 FPDF_AddInstalledFont(mapper
,
158 CPWL_FontMap::defaultTTFMap
[i
].fontname
,
159 CPWL_FontMap::defaultTTFMap
[i
].charset
);
164 const PDFFontSubstitution PDFFontSubstitutions
[] = {
165 {"Courier", "Courier New", false, false},
166 {"Courier-Bold", "Courier New", true, false},
167 {"Courier-BoldOblique", "Courier New", true, true},
168 {"Courier-Oblique", "Courier New", false, true},
169 {"Helvetica", "Arial", false, false},
170 {"Helvetica-Bold", "Arial", true, false},
171 {"Helvetica-BoldOblique", "Arial", true, true},
172 {"Helvetica-Oblique", "Arial", false, true},
173 {"Times-Roman", "Times New Roman", false, false},
174 {"Times-Bold", "Times New Roman", true, false},
175 {"Times-BoldItalic", "Times New Roman", true, true},
176 {"Times-Italic", "Times New Roman", false, true},
178 // MS P?(Mincho|Gothic) are the most notable fonts in Japanese PDF files
179 // without embedding the glyphs. Sometimes the font names are encoded
180 // in Japanese Windows's locale (CP932/Shift_JIS) without space.
181 // Most Linux systems don't have the exact font, but for outsourcing
182 // fontconfig to find substitutable font in the system, we pass ASCII
184 {"MS-PGothic", "MS PGothic", false, false},
185 {"MS-Gothic", "MS Gothic", false, false},
186 {"MS-PMincho", "MS PMincho", false, false},
187 {"MS-Mincho", "MS Mincho", false, false},
188 // MS PGothic in Shift_JIS encoding.
189 {"\x82\x6C\x82\x72\x82\x6F\x83\x53\x83\x56\x83\x62\x83\x4E",
190 "MS PGothic", false, false},
191 // MS Gothic in Shift_JIS encoding.
192 {"\x82\x6C\x82\x72\x83\x53\x83\x56\x83\x62\x83\x4E",
193 "MS Gothic", false, false},
194 // MS PMincho in Shift_JIS encoding.
195 {"\x82\x6C\x82\x72\x82\x6F\x96\xBE\x92\xA9",
196 "MS PMincho", false, false},
197 // MS Mincho in Shift_JIS encoding.
198 {"\x82\x6C\x82\x72\x96\xBE\x92\xA9",
199 "MS Mincho", false, false},
202 void* MapFont(struct _FPDF_SYSFONTINFO
*, int weight
, int italic
,
203 int charset
, int pitch_family
, const char* face
, int* exact
) {
204 // Do not attempt to map fonts if pepper is not initialized (for privet local
206 // TODO(noamsml): Real font substitution (http://crbug.com/391978)
207 if (!pp::Module::Get())
210 pp::BrowserFontDescription description
;
212 // Pretend the system does not have the Symbol font to force a fallback to
213 // the built in Symbol font in CFX_FontMapper::FindSubstFont().
214 if (strcmp(face
, "Symbol") == 0)
217 if (pitch_family
& FXFONT_FF_FIXEDPITCH
) {
218 description
.set_family(PP_BROWSERFONT_TRUSTED_FAMILY_MONOSPACE
);
219 } else if (pitch_family
& FXFONT_FF_ROMAN
) {
220 description
.set_family(PP_BROWSERFONT_TRUSTED_FAMILY_SERIF
);
223 // Map from the standard PDF fonts to TrueType font names.
225 for (i
= 0; i
< arraysize(PDFFontSubstitutions
); ++i
) {
226 if (strcmp(face
, PDFFontSubstitutions
[i
].pdf_name
) == 0) {
227 description
.set_face(PDFFontSubstitutions
[i
].face
);
228 if (PDFFontSubstitutions
[i
].bold
)
229 description
.set_weight(PP_BROWSERFONT_TRUSTED_WEIGHT_BOLD
);
230 if (PDFFontSubstitutions
[i
].italic
)
231 description
.set_italic(true);
236 if (i
== arraysize(PDFFontSubstitutions
)) {
237 // TODO(kochi): Pass the face in UTF-8. If face is not encoded in UTF-8,
238 // convert to UTF-8 before passing.
239 description
.set_face(face
);
241 description
.set_weight(WeightToBrowserFontTrustedWeight(weight
));
242 description
.set_italic(italic
> 0);
245 if (!pp::PDF::IsAvailable()) {
250 PP_Resource font_resource
= pp::PDF::GetFontFileWithFallback(
251 pp::InstanceHandle(g_last_instance_id
),
252 &description
.pp_font_description(),
253 static_cast<PP_PrivateFontCharset
>(charset
));
254 long res_id
= font_resource
;
255 return reinterpret_cast<void*>(res_id
);
258 unsigned long GetFontData(struct _FPDF_SYSFONTINFO
*, void* font_id
,
259 unsigned int table
, unsigned char* buffer
,
260 unsigned long buf_size
) {
261 if (!pp::PDF::IsAvailable()) {
266 uint32_t size
= buf_size
;
267 long res_id
= reinterpret_cast<long>(font_id
);
268 if (!pp::PDF::GetFontTableForPrivateFontFile(res_id
, table
, buffer
, &size
))
273 void DeleteFont(struct _FPDF_SYSFONTINFO
*, void* font_id
) {
274 long res_id
= reinterpret_cast<long>(font_id
);
275 pp::Module::Get()->core()->ReleaseResource(res_id
);
278 FPDF_SYSFONTINFO g_font_info
= {
289 #endif // defined(OS_LINUX)
291 void OOM_Handler(_OOM_INFO
*) {
292 // Kill the process. This is important for security, since the code doesn't
293 // NULL-check many memory allocations. If a malloc fails, returns NULL, and
294 // the buffer is then used, it provides a handy mapping of memory starting at
295 // address 0 for an attacker to utilize.
299 OOM_INFO g_oom_info
= {
304 PDFiumEngine
* g_engine_for_unsupported
;
306 void Unsupported_Handler(UNSUPPORT_INFO
*, int type
) {
307 if (!g_engine_for_unsupported
) {
312 g_engine_for_unsupported
->UnsupportedFeature(type
);
315 UNSUPPORT_INFO g_unsuppored_info
= {
320 // Set the destination page size and content area in points based on source
321 // page rotation and orientation.
323 // |rotated| True if source page is rotated 90 degree or 270 degree.
324 // |is_src_page_landscape| is true if the source page orientation is landscape.
325 // |page_size| has the actual destination page size in points.
326 // |content_rect| has the actual destination page printable area values in
328 void SetPageSizeAndContentRect(bool rotated
,
329 bool is_src_page_landscape
,
331 pp::Rect
* content_rect
) {
332 bool is_dst_page_landscape
= page_size
->width() > page_size
->height();
333 bool page_orientation_mismatched
= is_src_page_landscape
!=
334 is_dst_page_landscape
;
335 bool rotate_dst_page
= rotated
^ page_orientation_mismatched
;
336 if (rotate_dst_page
) {
337 page_size
->SetSize(page_size
->height(), page_size
->width());
338 content_rect
->SetRect(content_rect
->y(), content_rect
->x(),
339 content_rect
->height(), content_rect
->width());
343 // Calculate the scale factor between |content_rect| and a page of size
344 // |src_width| x |src_height|.
346 // |scale_to_fit| is true, if we need to calculate the scale factor.
347 // |content_rect| specifies the printable area of the destination page, with
348 // origin at left-bottom. Values are in points.
349 // |src_width| specifies the source page width in points.
350 // |src_height| specifies the source page height in points.
351 // |rotated| True if source page is rotated 90 degree or 270 degree.
352 double CalculateScaleFactor(bool scale_to_fit
,
353 const pp::Rect
& content_rect
,
354 double src_width
, double src_height
, bool rotated
) {
355 if (!scale_to_fit
|| src_width
== 0 || src_height
== 0)
358 double actual_source_page_width
= rotated
? src_height
: src_width
;
359 double actual_source_page_height
= rotated
? src_width
: src_height
;
360 double ratio_x
= static_cast<double>(content_rect
.width()) /
361 actual_source_page_width
;
362 double ratio_y
= static_cast<double>(content_rect
.height()) /
363 actual_source_page_height
;
364 return std::min(ratio_x
, ratio_y
);
367 // Compute source clip box boundaries based on the crop box / media box of
368 // source page and scale factor.
370 // |page| Handle to the source page. Returned by FPDF_LoadPage function.
371 // |scale_factor| specifies the scale factor that should be applied to source
372 // clip box boundaries.
373 // |rotated| True if source page is rotated 90 degree or 270 degree.
374 // |clip_box| out param to hold the computed source clip box values.
375 void CalculateClipBoxBoundary(FPDF_PAGE page
, double scale_factor
, bool rotated
,
377 if (!FPDFPage_GetCropBox(page
, &clip_box
->left
, &clip_box
->bottom
,
378 &clip_box
->right
, &clip_box
->top
)) {
379 if (!FPDFPage_GetMediaBox(page
, &clip_box
->left
, &clip_box
->bottom
,
380 &clip_box
->right
, &clip_box
->top
)) {
381 // Make the default size to be letter size (8.5" X 11"). We are just
382 // following the PDFium way of handling these corner cases. PDFium always
383 // consider US-Letter as the default page size.
384 float paper_width
= 612;
385 float paper_height
= 792;
387 clip_box
->bottom
= 0;
388 clip_box
->right
= rotated
? paper_height
: paper_width
;
389 clip_box
->top
= rotated
? paper_width
: paper_height
;
392 clip_box
->left
*= scale_factor
;
393 clip_box
->right
*= scale_factor
;
394 clip_box
->bottom
*= scale_factor
;
395 clip_box
->top
*= scale_factor
;
398 // Calculate the clip box translation offset for a page that does need to be
399 // scaled. All parameters are in points.
401 // |content_rect| specifies the printable area of the destination page, with
402 // origin at left-bottom.
403 // |source_clip_box| specifies the source clip box positions, relative to
404 // origin at left-bottom.
405 // |offset_x| and |offset_y| will contain the final translation offsets for the
406 // source clip box, relative to origin at left-bottom.
407 void CalculateScaledClipBoxOffset(const pp::Rect
& content_rect
,
408 const ClipBox
& source_clip_box
,
409 double* offset_x
, double* offset_y
) {
410 const float clip_box_width
= source_clip_box
.right
- source_clip_box
.left
;
411 const float clip_box_height
= source_clip_box
.top
- source_clip_box
.bottom
;
413 // Center the intended clip region to real clip region.
414 *offset_x
= (content_rect
.width() - clip_box_width
) / 2 + content_rect
.x() -
415 source_clip_box
.left
;
416 *offset_y
= (content_rect
.height() - clip_box_height
) / 2 + content_rect
.y() -
417 source_clip_box
.bottom
;
420 // Calculate the clip box offset for a page that does not need to be scaled.
421 // All parameters are in points.
423 // |content_rect| specifies the printable area of the destination page, with
424 // origin at left-bottom.
425 // |rotation| specifies the source page rotation values which are N / 90
427 // |page_width| specifies the screen destination page width.
428 // |page_height| specifies the screen destination page height.
429 // |source_clip_box| specifies the source clip box positions, relative to origin
431 // |offset_x| and |offset_y| will contain the final translation offsets for the
432 // source clip box, relative to origin at left-bottom.
433 void CalculateNonScaledClipBoxOffset(const pp::Rect
& content_rect
, int rotation
,
434 int page_width
, int page_height
,
435 const ClipBox
& source_clip_box
,
436 double* offset_x
, double* offset_y
) {
437 // Align the intended clip region to left-top corner of real clip region.
440 *offset_x
= -1 * source_clip_box
.left
;
441 *offset_y
= page_height
- source_clip_box
.top
;
445 *offset_y
= -1 * source_clip_box
.bottom
;
448 *offset_x
= page_width
- source_clip_box
.right
;
452 *offset_x
= page_height
- source_clip_box
.right
;
453 *offset_y
= page_width
- source_clip_box
.top
;
461 // Do an in-place transformation of objects on |page|. Translate all objects on
462 // |page| in |source_clip_box| by (|offset_x|, |offset_y|) and scale them by
465 // |page| Handle to the page. Returned by FPDF_LoadPage function.
466 // |source_clip_box| specifies the source clip box positions, relative to
467 // origin at left-bottom.
468 // |scale_factor| specifies the scale factor that should be applied to page
470 // |offset_x| and |offset_y| specifies the translation offsets for the page
471 // objects, relative to origin at left-bottom.
473 void TransformPageObjects(FPDF_PAGE page
, const ClipBox
& source_clip_box
,
474 const double scale_factor
, double offset_x
,
476 const int obj_count
= FPDFPage_CountObject(page
);
478 // Create a new clip path.
479 FPDF_CLIPPATH clip_path
= FPDF_CreateClipPath(
480 source_clip_box
.left
+ offset_x
, source_clip_box
.bottom
+ offset_y
,
481 source_clip_box
.right
+ offset_x
, source_clip_box
.top
+ offset_y
);
483 for (int obj_idx
= 0; obj_idx
< obj_count
; ++obj_idx
) {
484 FPDF_PAGEOBJECT page_obj
= FPDFPage_GetObject(page
, obj_idx
);
485 FPDFPageObj_Transform(page_obj
, scale_factor
, 0, 0, scale_factor
,
487 FPDFPageObj_TransformClipPath(page_obj
, scale_factor
, 0, 0, scale_factor
,
490 FPDFPage_TransformAnnots(page
, scale_factor
, 0, 0, scale_factor
,
492 FPDFPage_GenerateContent(page
);
494 // Add a extra clip path to the new pdf page here.
495 FPDFPage_InsertClipPath(page
, clip_path
);
497 // Destroy the clip path.
498 FPDF_DestroyClipPath(clip_path
);
501 bool InitializeSDK(void* data
) {
502 FPDF_InitLibrary(data
);
504 #if defined(OS_LINUX)
505 // Font loading doesn't work in the renderer sandbox in Linux.
506 FPDF_SetSystemFontInfo(&g_font_info
);
509 FSDK_SetOOMHandler(&g_oom_info
);
510 FSDK_SetUnSpObjProcessHandler(&g_unsuppored_info
);
516 FPDF_DestroyLibrary();
519 PDFEngine
* PDFEngine::Create(PDFEngine::Client
* client
) {
520 return new PDFiumEngine(client
);
523 PDFiumEngine::PDFiumEngine(PDFEngine::Client
* client
)
526 current_rotation_(0),
528 password_tries_remaining_(0),
531 defer_page_unload_(false),
533 next_page_to_search_(-1),
534 last_page_to_search_(-1),
535 last_character_index_to_search_(-1),
536 current_find_index_(-1),
538 fpdf_availability_(NULL
),
540 last_page_mouse_down_(-1),
541 first_visible_page_(-1),
542 most_visible_page_(-1),
543 called_do_document_action_(false),
544 render_grayscale_(false),
545 progressive_paint_timeout_(0),
546 getting_password_(false) {
547 find_factory_
.Initialize(this);
548 password_factory_
.Initialize(this);
550 file_access_
.m_FileLen
= 0;
551 file_access_
.m_GetBlock
= &GetBlock
;
552 file_access_
.m_Param
= &doc_loader_
;
554 file_availability_
.version
= 1;
555 file_availability_
.IsDataAvail
= &IsDataAvail
;
556 file_availability_
.loader
= &doc_loader_
;
558 download_hints_
.version
= 1;
559 download_hints_
.AddSegment
= &AddSegment
;
560 download_hints_
.loader
= &doc_loader_
;
562 // Initialize FPDF_FORMFILLINFO member variables. Deriving from this struct
563 // allows the static callbacks to be able to cast the FPDF_FORMFILLINFO in
564 // callbacks to ourself instead of maintaining a map of them to
566 FPDF_FORMFILLINFO::version
= 1;
567 FPDF_FORMFILLINFO::m_pJsPlatform
= this;
568 FPDF_FORMFILLINFO::Release
= NULL
;
569 FPDF_FORMFILLINFO::FFI_Invalidate
= Form_Invalidate
;
570 FPDF_FORMFILLINFO::FFI_OutputSelectedRect
= Form_OutputSelectedRect
;
571 FPDF_FORMFILLINFO::FFI_SetCursor
= Form_SetCursor
;
572 FPDF_FORMFILLINFO::FFI_SetTimer
= Form_SetTimer
;
573 FPDF_FORMFILLINFO::FFI_KillTimer
= Form_KillTimer
;
574 FPDF_FORMFILLINFO::FFI_GetLocalTime
= Form_GetLocalTime
;
575 FPDF_FORMFILLINFO::FFI_OnChange
= Form_OnChange
;
576 FPDF_FORMFILLINFO::FFI_GetPage
= Form_GetPage
;
577 FPDF_FORMFILLINFO::FFI_GetCurrentPage
= Form_GetCurrentPage
;
578 FPDF_FORMFILLINFO::FFI_GetRotation
= Form_GetRotation
;
579 FPDF_FORMFILLINFO::FFI_ExecuteNamedAction
= Form_ExecuteNamedAction
;
580 FPDF_FORMFILLINFO::FFI_SetTextFieldFocus
= Form_SetTextFieldFocus
;
581 FPDF_FORMFILLINFO::FFI_DoURIAction
= Form_DoURIAction
;
582 FPDF_FORMFILLINFO::FFI_DoGoToAction
= Form_DoGoToAction
;
584 IPDF_JSPLATFORM::version
= 1;
585 IPDF_JSPLATFORM::app_alert
= Form_Alert
;
586 IPDF_JSPLATFORM::app_beep
= Form_Beep
;
587 IPDF_JSPLATFORM::app_response
= Form_Response
;
588 IPDF_JSPLATFORM::Doc_getFilePath
= Form_GetFilePath
;
589 IPDF_JSPLATFORM::Doc_mail
= Form_Mail
;
590 IPDF_JSPLATFORM::Doc_print
= Form_Print
;
591 IPDF_JSPLATFORM::Doc_submitForm
= Form_SubmitForm
;
592 IPDF_JSPLATFORM::Doc_gotoPage
= Form_GotoPage
;
593 IPDF_JSPLATFORM::Field_browse
= Form_Browse
;
595 IFSDK_PAUSE::version
= 1;
596 IFSDK_PAUSE::user
= NULL
;
597 IFSDK_PAUSE::NeedToPauseNow
= Pause_NeedToPauseNow
;
600 PDFiumEngine::~PDFiumEngine() {
601 STLDeleteElements(&pages_
);
604 FORM_DoDocumentAAction(form_
, FPDFDOC_AACTION_WC
);
605 FPDFDOC_ExitFormFillEnviroument(form_
);
607 FPDF_CloseDocument(doc_
);
610 if (fpdf_availability_
)
611 FPDFAvail_Destroy(fpdf_availability_
);
614 int PDFiumEngine::GetBlock(void* param
, unsigned long position
,
615 unsigned char* buffer
, unsigned long size
) {
616 DocumentLoader
* loader
= static_cast<DocumentLoader
*>(param
);
617 return loader
->GetBlock(position
, size
, buffer
);
620 bool PDFiumEngine::IsDataAvail(FX_FILEAVAIL
* param
,
621 size_t offset
, size_t size
) {
622 PDFiumEngine::FileAvail
* file_avail
=
623 static_cast<PDFiumEngine::FileAvail
*>(param
);
624 return file_avail
->loader
->IsDataAvailable(offset
, size
);
627 void PDFiumEngine::AddSegment(FX_DOWNLOADHINTS
* param
,
628 size_t offset
, size_t size
) {
629 PDFiumEngine::DownloadHints
* download_hints
=
630 static_cast<PDFiumEngine::DownloadHints
*>(param
);
631 return download_hints
->loader
->RequestData(offset
, size
);
634 bool PDFiumEngine::New(const char* url
) {
636 headers_
= std::string();
640 bool PDFiumEngine::New(const char* url
,
641 const char* headers
) {
644 headers_
= std::string();
650 void PDFiumEngine::PageOffsetUpdated(const pp::Point
& page_offset
) {
651 page_offset_
= page_offset
;
654 void PDFiumEngine::PluginSizeUpdated(const pp::Size
& size
) {
658 CalculateVisiblePages();
661 void PDFiumEngine::ScrolledToXPosition(int position
) {
664 int old_x
= position_
.x();
665 position_
.set_x(position
);
666 CalculateVisiblePages();
667 client_
->Scroll(pp::Point(old_x
- position
, 0));
670 void PDFiumEngine::ScrolledToYPosition(int position
) {
673 int old_y
= position_
.y();
674 position_
.set_y(position
);
675 CalculateVisiblePages();
676 client_
->Scroll(pp::Point(0, old_y
- position
));
679 void PDFiumEngine::PrePaint() {
680 for (size_t i
= 0; i
< progressive_paints_
.size(); ++i
)
681 progressive_paints_
[i
].painted_
= false;
684 void PDFiumEngine::Paint(const pp::Rect
& rect
,
685 pp::ImageData
* image_data
,
686 std::vector
<pp::Rect
>* ready
,
687 std::vector
<pp::Rect
>* pending
) {
688 pp::Rect leftover
= rect
;
689 for (size_t i
= 0; i
< visible_pages_
.size(); ++i
) {
690 int index
= visible_pages_
[i
];
691 pp::Rect page_rect
= pages_
[index
]->rect();
692 // Convert the current page's rectangle to screen rectangle. We do this
693 // instead of the reverse (converting the dirty rectangle from screen to
694 // page coordinates) because then we'd have to convert back to screen
695 // coordinates, and the rounding errors sometime leave pixels dirty or even
696 // move the text up or down a pixel when zoomed.
697 pp::Rect page_rect_in_screen
= GetPageScreenRect(index
);
698 pp::Rect dirty_in_screen
= page_rect_in_screen
.Intersect(leftover
);
699 if (dirty_in_screen
.IsEmpty())
702 leftover
= leftover
.Subtract(dirty_in_screen
);
704 if (pages_
[index
]->available()) {
705 int progressive
= GetProgressiveIndex(index
);
706 if (progressive
!= -1 &&
707 progressive_paints_
[progressive
].rect
!= dirty_in_screen
) {
708 // The PDFium code can only handle one progressive paint at a time, so
709 // queue this up. Previously we used to merge the rects when this
710 // happened, but it made scrolling up on complex PDFs very slow since
711 // there would be a damaged rect at the top (from scroll) and at the
712 // bottom (from toolbar).
713 pending
->push_back(dirty_in_screen
);
717 if (progressive
== -1) {
718 progressive
= StartPaint(index
, dirty_in_screen
);
719 progressive_paint_timeout_
= kMaxInitialProgressivePaintTimeMs
;
721 progressive_paint_timeout_
= kMaxProgressivePaintTimeMs
;
724 progressive_paints_
[progressive
].painted_
= true;
725 if (ContinuePaint(progressive
, image_data
)) {
726 FinishPaint(progressive
, image_data
);
727 ready
->push_back(dirty_in_screen
);
729 pending
->push_back(dirty_in_screen
);
732 PaintUnavailablePage(index
, dirty_in_screen
, image_data
);
733 ready
->push_back(dirty_in_screen
);
738 void PDFiumEngine::PostPaint() {
739 for (size_t i
= 0; i
< progressive_paints_
.size(); ++i
) {
740 if (progressive_paints_
[i
].painted_
)
743 // This rectangle must have been merged with another one, that's why we
744 // weren't asked to paint it. Remove it or otherwise we'll never finish
746 FPDF_RenderPage_Close(
747 pages_
[progressive_paints_
[i
].page_index
]->GetPage());
748 FPDFBitmap_Destroy(progressive_paints_
[i
].bitmap
);
749 progressive_paints_
.erase(progressive_paints_
.begin() + i
);
754 bool PDFiumEngine::HandleDocumentLoad(const pp::URLLoader
& loader
) {
755 password_tries_remaining_
= kMaxPasswordTries
;
756 return doc_loader_
.Init(loader
, url_
, headers_
);
759 pp::Instance
* PDFiumEngine::GetPluginInstance() {
760 return client_
->GetPluginInstance();
763 pp::URLLoader
PDFiumEngine::CreateURLLoader() {
764 return client_
->CreateURLLoader();
767 void PDFiumEngine::AppendPage(PDFEngine
* engine
, int index
) {
768 // Unload and delete the blank page before appending.
769 pages_
[index
]->Unload();
770 pages_
[index
]->set_calculated_links(false);
771 pp::Size curr_page_size
= GetPageSize(index
);
772 FPDFPage_Delete(doc_
, index
);
773 FPDF_ImportPages(doc_
,
774 static_cast<PDFiumEngine
*>(engine
)->doc(),
777 pp::Size new_page_size
= GetPageSize(index
);
778 if (curr_page_size
!= new_page_size
)
780 client_
->Invalidate(GetPageScreenRect(index
));
783 pp::Point
PDFiumEngine::GetScrollPosition() {
787 void PDFiumEngine::SetScrollPosition(const pp::Point
& position
) {
788 position_
= position
;
791 bool PDFiumEngine::IsProgressiveLoad() {
792 return doc_loader_
.is_partial_document();
795 void PDFiumEngine::OnPartialDocumentLoaded() {
796 file_access_
.m_FileLen
= doc_loader_
.document_size();
797 fpdf_availability_
= FPDFAvail_Create(&file_availability_
, &file_access_
);
798 DCHECK(fpdf_availability_
);
800 // Currently engine does not deal efficiently with some non-linearized files.
801 // See http://code.google.com/p/chromium/issues/detail?id=59400
802 // To improve user experience we download entire file for non-linearized PDF.
803 if (!FPDFAvail_IsLinearized(fpdf_availability_
)) {
804 doc_loader_
.RequestData(0, doc_loader_
.document_size());
811 void PDFiumEngine::OnPendingRequestComplete() {
812 if (!doc_
|| !form_
) {
817 // LoadDocument() will result in |pending_pages_| being reset so there's no
818 // need to run the code below in that case.
819 bool update_pages
= false;
820 std::vector
<int> still_pending
;
821 for (size_t i
= 0; i
< pending_pages_
.size(); ++i
) {
822 if (CheckPageAvailable(pending_pages_
[i
], &still_pending
)) {
824 if (IsPageVisible(pending_pages_
[i
]))
825 client_
->Invalidate(GetPageScreenRect(pending_pages_
[i
]));
828 pending_pages_
.swap(still_pending
);
833 void PDFiumEngine::OnNewDataAvailable() {
834 client_
->DocumentLoadProgress(doc_loader_
.GetAvailableData(),
835 doc_loader_
.document_size());
838 void PDFiumEngine::OnDocumentComplete() {
839 if (!doc_
|| !form_
) {
840 file_access_
.m_FileLen
= doc_loader_
.document_size();
845 bool need_update
= false;
846 for (size_t i
= 0; i
< pages_
.size(); ++i
) {
847 if (pages_
[i
]->available())
850 pages_
[i
]->set_available(true);
851 // We still need to call IsPageAvail() even if the whole document is
852 // already downloaded.
853 FPDFAvail_IsPageAvail(fpdf_availability_
, i
, &download_hints_
);
855 if (IsPageVisible(i
))
856 client_
->Invalidate(GetPageScreenRect(i
));
861 FinishLoadingDocument();
864 void PDFiumEngine::FinishLoadingDocument() {
865 DCHECK(doc_loader_
.IsDocumentComplete() && doc_
);
866 if (called_do_document_action_
)
868 called_do_document_action_
= true;
870 // These can only be called now, as the JS might end up needing a page.
871 FORM_DoDocumentJSAction(form_
);
872 FORM_DoDocumentOpenAction(form_
);
873 if (most_visible_page_
!= -1) {
874 FPDF_PAGE new_page
= pages_
[most_visible_page_
]->GetPage();
875 FORM_DoPageAAction(new_page
, form_
, FPDFPAGE_AACTION_OPEN
);
878 if (doc_
) // This can only happen if loading |doc_| fails.
879 client_
->DocumentLoadComplete(pages_
.size());
882 void PDFiumEngine::UnsupportedFeature(int type
) {
885 case FPDF_UNSP_DOC_XFAFORM
:
888 case FPDF_UNSP_DOC_PORTABLECOLLECTION
:
889 feature
= "Portfolios_Packages";
891 case FPDF_UNSP_DOC_ATTACHMENT
:
892 case FPDF_UNSP_ANNOT_ATTACHMENT
:
893 feature
= "Attachment";
895 case FPDF_UNSP_DOC_SECURITY
:
896 feature
= "Rights_Management";
898 case FPDF_UNSP_DOC_SHAREDREVIEW
:
899 feature
= "Shared_Review";
901 case FPDF_UNSP_DOC_SHAREDFORM_ACROBAT
:
902 case FPDF_UNSP_DOC_SHAREDFORM_FILESYSTEM
:
903 case FPDF_UNSP_DOC_SHAREDFORM_EMAIL
:
904 feature
= "Shared_Form";
906 case FPDF_UNSP_ANNOT_3DANNOT
:
909 case FPDF_UNSP_ANNOT_MOVIE
:
912 case FPDF_UNSP_ANNOT_SOUND
:
915 case FPDF_UNSP_ANNOT_SCREEN_MEDIA
:
916 case FPDF_UNSP_ANNOT_SCREEN_RICHMEDIA
:
919 case FPDF_UNSP_ANNOT_SIG
:
920 feature
= "Digital_Signature";
923 client_
->DocumentHasUnsupportedFeature(feature
);
926 void PDFiumEngine::ContinueFind(int32_t result
) {
927 StartFind(current_find_text_
.c_str(), !!result
);
930 bool PDFiumEngine::HandleEvent(const pp::InputEvent
& event
) {
931 DCHECK(!defer_page_unload_
);
932 defer_page_unload_
= true;
934 switch (event
.GetType()) {
935 case PP_INPUTEVENT_TYPE_MOUSEDOWN
:
936 rv
= OnMouseDown(pp::MouseInputEvent(event
));
938 case PP_INPUTEVENT_TYPE_MOUSEUP
:
939 rv
= OnMouseUp(pp::MouseInputEvent(event
));
941 case PP_INPUTEVENT_TYPE_MOUSEMOVE
:
942 rv
= OnMouseMove(pp::MouseInputEvent(event
));
944 case PP_INPUTEVENT_TYPE_KEYDOWN
:
945 rv
= OnKeyDown(pp::KeyboardInputEvent(event
));
947 case PP_INPUTEVENT_TYPE_KEYUP
:
948 rv
= OnKeyUp(pp::KeyboardInputEvent(event
));
950 case PP_INPUTEVENT_TYPE_CHAR
:
951 rv
= OnChar(pp::KeyboardInputEvent(event
));
957 DCHECK(defer_page_unload_
);
958 defer_page_unload_
= false;
959 for (size_t i
= 0; i
< deferred_page_unloads_
.size(); ++i
)
960 pages_
[deferred_page_unloads_
[i
]]->Unload();
961 deferred_page_unloads_
.clear();
965 uint32_t PDFiumEngine::QuerySupportedPrintOutputFormats() {
966 if (!HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
))
968 return PP_PRINTOUTPUTFORMAT_PDF
;
971 void PDFiumEngine::PrintBegin() {
972 FORM_DoDocumentAAction(form_
, FPDFDOC_AACTION_WP
);
975 pp::Resource
PDFiumEngine::PrintPages(
976 const PP_PrintPageNumberRange_Dev
* page_ranges
, uint32_t page_range_count
,
977 const PP_PrintSettings_Dev
& print_settings
) {
978 if (HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY
))
979 return PrintPagesAsPDF(page_ranges
, page_range_count
, print_settings
);
980 else if (HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
))
981 return PrintPagesAsRasterPDF(page_ranges
, page_range_count
, print_settings
);
982 return pp::Resource();
985 FPDF_DOCUMENT
PDFiumEngine::CreateSinglePageRasterPdf(
986 double source_page_width
,
987 double source_page_height
,
988 const PP_PrintSettings_Dev
& print_settings
,
989 PDFiumPage
* page_to_print
) {
990 FPDF_DOCUMENT temp_doc
= FPDF_CreateNewDocument();
994 const pp::Size
& bitmap_size(page_to_print
->rect().size());
996 FPDF_PAGE temp_page
=
997 FPDFPage_New(temp_doc
, 0, source_page_width
, source_page_height
);
999 pp::ImageData image
= pp::ImageData(client_
->GetPluginInstance(),
1000 PP_IMAGEDATAFORMAT_BGRA_PREMUL
,
1004 FPDF_BITMAP bitmap
= FPDFBitmap_CreateEx(bitmap_size
.width(),
1005 bitmap_size
.height(),
1011 FPDFBitmap_FillRect(
1012 bitmap
, 0, 0, bitmap_size
.width(), bitmap_size
.height(), 0xFFFFFFFF);
1014 pp::Rect page_rect
= page_to_print
->rect();
1015 FPDF_RenderPageBitmap(bitmap
,
1016 page_to_print
->GetPrintPage(),
1021 print_settings
.orientation
,
1022 FPDF_ANNOT
| FPDF_PRINTING
| FPDF_NO_CATCH
);
1024 double ratio_x
= (static_cast<double>(bitmap_size
.width()) * kPointsPerInch
) /
1027 (static_cast<double>(bitmap_size
.height()) * kPointsPerInch
) /
1030 // Add the bitmap to an image object and add the image object to the output
1032 FPDF_PAGEOBJECT temp_img
= FPDFPageObj_NewImgeObj(temp_doc
);
1033 FPDFImageObj_SetBitmap(&temp_page
, 1, temp_img
, bitmap
);
1034 FPDFImageObj_SetMatrix(temp_img
, ratio_x
, 0, 0, ratio_y
, 0, 0);
1035 FPDFPage_InsertObject(temp_page
, temp_img
);
1036 FPDFPage_GenerateContent(temp_page
);
1037 FPDF_ClosePage(temp_page
);
1039 page_to_print
->ClosePrintPage();
1040 FPDFBitmap_Destroy(bitmap
);
1045 pp::Buffer_Dev
PDFiumEngine::PrintPagesAsRasterPDF(
1046 const PP_PrintPageNumberRange_Dev
* page_ranges
, uint32_t page_range_count
,
1047 const PP_PrintSettings_Dev
& print_settings
) {
1048 if (!page_range_count
)
1049 return pp::Buffer_Dev();
1051 // If document is not downloaded yet, disable printing.
1052 if (doc_
&& !doc_loader_
.IsDocumentComplete())
1053 return pp::Buffer_Dev();
1055 FPDF_DOCUMENT output_doc
= FPDF_CreateNewDocument();
1057 return pp::Buffer_Dev();
1059 SaveSelectedFormForPrint();
1061 std::vector
<PDFiumPage
> pages_to_print
;
1062 // width and height of source PDF pages.
1063 std::vector
<std::pair
<double, double> > source_page_sizes
;
1064 // Collect pages to print and sizes of source pages.
1065 std::vector
<uint32_t> page_numbers
=
1066 GetPageNumbersFromPrintPageNumberRange(page_ranges
, page_range_count
);
1067 for (size_t i
= 0; i
< page_numbers
.size(); ++i
) {
1068 uint32_t page_number
= page_numbers
[i
];
1069 FPDF_PAGE pdf_page
= FPDF_LoadPage(doc_
, page_number
);
1070 double source_page_width
= FPDF_GetPageWidth(pdf_page
);
1071 double source_page_height
= FPDF_GetPageHeight(pdf_page
);
1072 source_page_sizes
.push_back(std::make_pair(source_page_width
,
1073 source_page_height
));
1075 int width_in_pixels
= ConvertUnit(source_page_width
,
1076 static_cast<int>(kPointsPerInch
),
1077 print_settings
.dpi
);
1078 int height_in_pixels
= ConvertUnit(source_page_height
,
1079 static_cast<int>(kPointsPerInch
),
1080 print_settings
.dpi
);
1082 pp::Rect
rect(width_in_pixels
, height_in_pixels
);
1083 pages_to_print
.push_back(PDFiumPage(this, page_number
, rect
, true));
1084 FPDF_ClosePage(pdf_page
);
1087 #if defined(OS_LINUX)
1088 g_last_instance_id
= client_
->GetPluginInstance()->pp_instance();
1092 for (; i
< pages_to_print
.size(); ++i
) {
1093 double source_page_width
= source_page_sizes
[i
].first
;
1094 double source_page_height
= source_page_sizes
[i
].second
;
1096 // Use temp_doc to compress image by saving PDF to buffer.
1097 FPDF_DOCUMENT temp_doc
= CreateSinglePageRasterPdf(source_page_width
,
1100 &pages_to_print
[i
]);
1105 pp::Buffer_Dev buffer
= GetFlattenedPrintData(temp_doc
);
1106 FPDF_CloseDocument(temp_doc
);
1108 PDFiumMemBufferFileRead
file_read(buffer
.data(), buffer
.size());
1109 temp_doc
= FPDF_LoadCustomDocument(&file_read
, NULL
);
1111 FPDF_BOOL imported
= FPDF_ImportPages(output_doc
, temp_doc
, "1", i
);
1112 FPDF_CloseDocument(temp_doc
);
1117 pp::Buffer_Dev buffer
;
1118 if (i
== pages_to_print
.size()) {
1119 FPDF_CopyViewerPreferences(output_doc
, doc_
);
1120 FitContentsToPrintableAreaIfRequired(output_doc
, print_settings
);
1121 // Now flatten all the output pages.
1122 buffer
= GetFlattenedPrintData(output_doc
);
1124 FPDF_CloseDocument(output_doc
);
1128 pp::Buffer_Dev
PDFiumEngine::GetFlattenedPrintData(const FPDF_DOCUMENT
& doc
) {
1129 int page_count
= FPDF_GetPageCount(doc
);
1130 bool flatten_succeeded
= true;
1131 for (int i
= 0; i
< page_count
; ++i
) {
1132 FPDF_PAGE page
= FPDF_LoadPage(doc
, i
);
1135 int flatten_ret
= FPDFPage_Flatten(page
, FLAT_PRINT
);
1136 FPDF_ClosePage(page
);
1137 if (flatten_ret
== FLATTEN_FAIL
) {
1138 flatten_succeeded
= false;
1142 flatten_succeeded
= false;
1146 if (!flatten_succeeded
) {
1147 FPDF_CloseDocument(doc
);
1148 return pp::Buffer_Dev();
1151 pp::Buffer_Dev buffer
;
1152 PDFiumMemBufferFileWrite output_file_write
;
1153 if (FPDF_SaveAsCopy(doc
, &output_file_write
, 0)) {
1154 buffer
= pp::Buffer_Dev(
1155 client_
->GetPluginInstance(), output_file_write
.size());
1156 if (!buffer
.is_null()) {
1157 memcpy(buffer
.data(), output_file_write
.buffer().c_str(),
1158 output_file_write
.size());
1164 pp::Buffer_Dev
PDFiumEngine::PrintPagesAsPDF(
1165 const PP_PrintPageNumberRange_Dev
* page_ranges
, uint32_t page_range_count
,
1166 const PP_PrintSettings_Dev
& print_settings
) {
1167 if (!page_range_count
)
1168 return pp::Buffer_Dev();
1171 FPDF_DOCUMENT output_doc
= FPDF_CreateNewDocument();
1173 return pp::Buffer_Dev();
1175 SaveSelectedFormForPrint();
1177 std::string page_number_str
;
1178 for (uint32_t index
= 0; index
< page_range_count
; ++index
) {
1179 if (!page_number_str
.empty())
1180 page_number_str
.append(",");
1181 page_number_str
.append(
1182 base::IntToString(page_ranges
[index
].first_page_number
+ 1));
1183 if (page_ranges
[index
].first_page_number
!=
1184 page_ranges
[index
].last_page_number
) {
1185 page_number_str
.append("-");
1186 page_number_str
.append(
1187 base::IntToString(page_ranges
[index
].last_page_number
+ 1));
1191 std::vector
<uint32_t> page_numbers
=
1192 GetPageNumbersFromPrintPageNumberRange(page_ranges
, page_range_count
);
1193 for (size_t i
= 0; i
< page_numbers
.size(); ++i
) {
1194 uint32_t page_number
= page_numbers
[i
];
1195 pages_
[page_number
]->GetPage();
1196 if (!IsPageVisible(page_numbers
[i
]))
1197 pages_
[page_number
]->Unload();
1200 FPDF_CopyViewerPreferences(output_doc
, doc_
);
1201 if (!FPDF_ImportPages(output_doc
, doc_
, page_number_str
.c_str(), 0)) {
1202 FPDF_CloseDocument(output_doc
);
1203 return pp::Buffer_Dev();
1206 FitContentsToPrintableAreaIfRequired(output_doc
, print_settings
);
1208 // Now flatten all the output pages.
1209 pp::Buffer_Dev buffer
= GetFlattenedPrintData(output_doc
);
1210 FPDF_CloseDocument(output_doc
);
1214 void PDFiumEngine::FitContentsToPrintableAreaIfRequired(
1215 const FPDF_DOCUMENT
& doc
, const PP_PrintSettings_Dev
& print_settings
) {
1216 // Check to see if we need to fit pdf contents to printer paper size.
1217 if (print_settings
.print_scaling_option
!=
1218 PP_PRINTSCALINGOPTION_SOURCE_SIZE
) {
1219 int num_pages
= FPDF_GetPageCount(doc
);
1220 // In-place transformation is more efficient than creating a new
1221 // transformed document from the source document. Therefore, transform
1222 // every page to fit the contents in the selected printer paper.
1223 for (int i
= 0; i
< num_pages
; ++i
) {
1224 FPDF_PAGE page
= FPDF_LoadPage(doc
, i
);
1225 TransformPDFPageForPrinting(page
, print_settings
);
1226 FPDF_ClosePage(page
);
1231 void PDFiumEngine::SaveSelectedFormForPrint() {
1232 FORM_ForceToKillFocus(form_
);
1233 client_
->FormTextFieldFocusChange(false);
1236 void PDFiumEngine::PrintEnd() {
1237 FORM_DoDocumentAAction(form_
, FPDFDOC_AACTION_DP
);
1240 PDFiumPage::Area
PDFiumEngine::GetCharIndex(
1241 const pp::MouseInputEvent
& event
, int* page_index
,
1242 int* char_index
, PDFiumPage::LinkTarget
* target
) {
1243 // First figure out which page this is in.
1244 pp::Point mouse_point
= event
.GetPosition();
1246 static_cast<int>((mouse_point
.x() + position_
.x()) / current_zoom_
),
1247 static_cast<int>((mouse_point
.y() + position_
.y()) / current_zoom_
));
1248 return GetCharIndex(point
, page_index
, char_index
, target
);
1251 PDFiumPage::Area
PDFiumEngine::GetCharIndex(
1252 const pp::Point
& point
,
1255 PDFiumPage::LinkTarget
* target
) {
1257 for (size_t i
= 0; i
< visible_pages_
.size(); ++i
) {
1258 if (pages_
[visible_pages_
[i
]]->rect().Contains(point
)) {
1259 page
= visible_pages_
[i
];
1264 return PDFiumPage::NONSELECTABLE_AREA
;
1266 // If the page hasn't finished rendering, calling into the page sometimes
1268 for (size_t i
= 0; i
< progressive_paints_
.size(); ++i
) {
1269 if (progressive_paints_
[i
].page_index
== page
)
1270 return PDFiumPage::NONSELECTABLE_AREA
;
1274 return pages_
[page
]->GetCharIndex(point
, current_rotation_
, char_index
,
1278 bool PDFiumEngine::OnMouseDown(const pp::MouseInputEvent
& event
) {
1279 if (event
.GetButton() != PP_INPUTEVENT_MOUSEBUTTON_LEFT
)
1282 SelectionChangeInvalidator
selection_invalidator(this);
1285 int page_index
= -1;
1286 int char_index
= -1;
1287 PDFiumPage::LinkTarget target
;
1288 PDFiumPage::Area area
= GetCharIndex(event
, &page_index
,
1289 &char_index
, &target
);
1290 if (area
== PDFiumPage::WEBLINK_AREA
) {
1291 bool open_in_new_tab
= !!(event
.GetModifiers() & kDefaultKeyModifier
);
1292 client_
->NavigateTo(target
.url
, open_in_new_tab
);
1293 client_
->FormTextFieldFocusChange(false);
1297 if (area
== PDFiumPage::DOCLINK_AREA
) {
1298 client_
->ScrollToPage(target
.page
);
1299 client_
->FormTextFieldFocusChange(false);
1303 if (page_index
!= -1) {
1304 last_page_mouse_down_
= page_index
;
1305 double page_x
, page_y
;
1306 pp::Point point
= event
.GetPosition();
1307 DeviceToPage(page_index
, point
.x(), point
.y(), &page_x
, &page_y
);
1309 FORM_OnLButtonDown(form_
, pages_
[page_index
]->GetPage(), 0, page_x
, page_y
);
1310 int control
= FPDPage_HasFormFieldAtPoint(
1311 form_
, pages_
[page_index
]->GetPage(), page_x
, page_y
);
1312 if (control
> FPDF_FORMFIELD_UNKNOWN
) { // returns -1 sometimes...
1313 client_
->FormTextFieldFocusChange(control
== FPDF_FORMFIELD_TEXTFIELD
||
1314 control
== FPDF_FORMFIELD_COMBOBOX
);
1315 return true; // Return now before we get into the selection code.
1319 client_
->FormTextFieldFocusChange(false);
1321 if (area
!= PDFiumPage::TEXT_AREA
)
1322 return true; // Return true so WebKit doesn't do its own highlighting.
1324 if (event
.GetClickCount() == 1) {
1325 OnSingleClick(page_index
, char_index
);
1326 } else if (event
.GetClickCount() == 2 ||
1327 event
.GetClickCount() == 3) {
1328 OnMultipleClick(event
.GetClickCount(), page_index
, char_index
);
1334 void PDFiumEngine::OnSingleClick(int page_index
, int char_index
) {
1336 selection_
.push_back(PDFiumRange(pages_
[page_index
], char_index
, 0));
1339 void PDFiumEngine::OnMultipleClick(int click_count
,
1342 // It would be more efficient if the SDK could support finding a space, but
1344 int start_index
= char_index
;
1346 base::char16 cur
= pages_
[page_index
]->GetCharAtIndex(start_index
);
1347 // For double click, we want to select one word so we look for whitespace
1348 // boundaries. For triple click, we want the whole line.
1349 if (cur
== '\n' || (click_count
== 2 && (cur
== ' ' || cur
== '\t')))
1351 } while (--start_index
>= 0);
1355 int end_index
= char_index
;
1356 int total
= pages_
[page_index
]->GetCharCount();
1357 while (end_index
++ <= total
) {
1358 base::char16 cur
= pages_
[page_index
]->GetCharAtIndex(end_index
);
1359 if (cur
== '\n' || (click_count
== 2 && (cur
== ' ' || cur
== '\t')))
1363 selection_
.push_back(PDFiumRange(
1364 pages_
[page_index
], start_index
, end_index
- start_index
));
1367 bool PDFiumEngine::OnMouseUp(const pp::MouseInputEvent
& event
) {
1368 if (event
.GetButton() != PP_INPUTEVENT_MOUSEBUTTON_LEFT
)
1371 int page_index
= -1;
1372 int char_index
= -1;
1373 GetCharIndex(event
, &page_index
, &char_index
, NULL
);
1374 if (page_index
!= -1) {
1375 double page_x
, page_y
;
1376 pp::Point point
= event
.GetPosition();
1377 DeviceToPage(page_index
, point
.x(), point
.y(), &page_x
, &page_y
);
1379 form_
, pages_
[page_index
]->GetPage(), 0, page_x
, page_y
);
1389 bool PDFiumEngine::OnMouseMove(const pp::MouseInputEvent
& event
) {
1390 int page_index
= -1;
1391 int char_index
= -1;
1392 PDFiumPage::Area area
= GetCharIndex(event
, &page_index
, &char_index
, NULL
);
1394 PP_CursorType_Dev cursor
;
1396 case PDFiumPage::TEXT_AREA
:
1397 cursor
= PP_CURSORTYPE_IBEAM
;
1399 case PDFiumPage::WEBLINK_AREA
:
1400 case PDFiumPage::DOCLINK_AREA
:
1401 cursor
= PP_CURSORTYPE_HAND
;
1403 case PDFiumPage::NONSELECTABLE_AREA
:
1405 cursor
= PP_CURSORTYPE_POINTER
;
1409 if (page_index
!= -1) {
1410 double page_x
, page_y
;
1411 pp::Point point
= event
.GetPosition();
1412 DeviceToPage(page_index
, point
.x(), point
.y(), &page_x
, &page_y
);
1414 FORM_OnMouseMove(form_
, pages_
[page_index
]->GetPage(), 0, page_x
, page_y
);
1415 int control
= FPDPage_HasFormFieldAtPoint(
1416 form_
, pages_
[page_index
]->GetPage(), page_x
, page_y
);
1418 case FPDF_FORMFIELD_PUSHBUTTON
:
1419 case FPDF_FORMFIELD_CHECKBOX
:
1420 case FPDF_FORMFIELD_RADIOBUTTON
:
1421 case FPDF_FORMFIELD_COMBOBOX
:
1422 case FPDF_FORMFIELD_LISTBOX
:
1423 cursor
= PP_CURSORTYPE_HAND
;
1425 case FPDF_FORMFIELD_TEXTFIELD
:
1426 cursor
= PP_CURSORTYPE_IBEAM
;
1433 client_
->UpdateCursor(cursor
);
1434 pp::Point point
= event
.GetPosition();
1435 std::string url
= GetLinkAtPosition(event
.GetPosition());
1436 if (url
!= link_under_cursor_
) {
1437 link_under_cursor_
= url
;
1438 pp::PDF::SetLinkUnderCursor(GetPluginInstance(), url
.c_str());
1440 // No need to swallow the event, since this might interfere with the
1441 // scrollbars if the user is dragging them.
1445 // We're selecting but right now we're not over text, so don't change the
1446 // current selection.
1447 if (area
!= PDFiumPage::TEXT_AREA
&& area
!= PDFiumPage::WEBLINK_AREA
&&
1448 area
!= PDFiumPage::DOCLINK_AREA
) {
1452 SelectionChangeInvalidator
selection_invalidator(this);
1454 // Check if the user has descreased their selection area and we need to remove
1455 // pages from selection_.
1456 for (size_t i
= 0; i
< selection_
.size(); ++i
) {
1457 if (selection_
[i
].page_index() == page_index
) {
1458 // There should be no other pages after this.
1459 selection_
.erase(selection_
.begin() + i
+ 1, selection_
.end());
1464 if (selection_
.size() == 0)
1467 int last
= selection_
.size() - 1;
1468 if (selection_
[last
].page_index() == page_index
) {
1469 // Selecting within a page.
1471 if (char_index
>= selection_
[last
].char_index()) {
1472 // Selecting forward.
1473 count
= char_index
- selection_
[last
].char_index() + 1;
1475 count
= char_index
- selection_
[last
].char_index() - 1;
1477 selection_
[last
].SetCharCount(count
);
1478 } else if (selection_
[last
].page_index() < page_index
) {
1479 // Selecting into the next page.
1481 // First make sure that there are no gaps in selection, i.e. if mousedown on
1482 // page one but we only get mousemove over page three, we want page two.
1483 for (int i
= selection_
[last
].page_index() + 1; i
< page_index
; ++i
) {
1484 selection_
.push_back(PDFiumRange(pages_
[i
], 0,
1485 pages_
[i
]->GetCharCount()));
1488 int count
= pages_
[selection_
[last
].page_index()]->GetCharCount();
1489 selection_
[last
].SetCharCount(count
- selection_
[last
].char_index());
1490 selection_
.push_back(PDFiumRange(pages_
[page_index
], 0, char_index
));
1492 // Selecting into the previous page.
1493 selection_
[last
].SetCharCount(-selection_
[last
].char_index());
1495 // First make sure that there are no gaps in selection, i.e. if mousedown on
1496 // page three but we only get mousemove over page one, we want page two.
1497 for (int i
= selection_
[last
].page_index() - 1; i
> page_index
; --i
) {
1498 selection_
.push_back(PDFiumRange(pages_
[i
], 0,
1499 pages_
[i
]->GetCharCount()));
1502 int count
= pages_
[page_index
]->GetCharCount();
1503 selection_
.push_back(
1504 PDFiumRange(pages_
[page_index
], count
, count
- char_index
));
1510 bool PDFiumEngine::OnKeyDown(const pp::KeyboardInputEvent
& event
) {
1511 if (last_page_mouse_down_
== -1)
1514 bool rv
= !!FORM_OnKeyDown(
1515 form_
, pages_
[last_page_mouse_down_
]->GetPage(),
1516 event
.GetKeyCode(), event
.GetModifiers());
1518 if (event
.GetKeyCode() == ui::VKEY_BACK
||
1519 event
.GetKeyCode() == ui::VKEY_ESCAPE
) {
1520 // Chrome doesn't send char events for backspace or escape keys, see
1521 // PlatformKeyboardEventBuilder::isCharacterKey() and
1522 // http://chrome-corpsvn.mtv.corp.google.com/viewvc?view=rev&root=chrome&revision=31805
1523 // for more information. So just fake one since PDFium uses it.
1525 str
.push_back(event
.GetKeyCode());
1526 pp::KeyboardInputEvent
synthesized(pp::KeyboardInputEvent(
1527 client_
->GetPluginInstance(),
1528 PP_INPUTEVENT_TYPE_CHAR
,
1529 event
.GetTimeStamp(),
1530 event
.GetModifiers(),
1533 OnChar(synthesized
);
1539 bool PDFiumEngine::OnKeyUp(const pp::KeyboardInputEvent
& event
) {
1540 if (last_page_mouse_down_
== -1)
1543 return !!FORM_OnKeyUp(
1544 form_
, pages_
[last_page_mouse_down_
]->GetPage(),
1545 event
.GetKeyCode(), event
.GetModifiers());
1548 bool PDFiumEngine::OnChar(const pp::KeyboardInputEvent
& event
) {
1549 if (last_page_mouse_down_
== -1)
1552 base::string16 str
= base::UTF8ToUTF16(event
.GetCharacterText().AsString());
1553 return !!FORM_OnChar(
1554 form_
, pages_
[last_page_mouse_down_
]->GetPage(),
1556 event
.GetModifiers());
1559 void PDFiumEngine::StartFind(const char* text
, bool case_sensitive
) {
1560 // We can get a call to StartFind before we have any page information (i.e.
1561 // before the first call to LoadDocument has happened). Handle this case.
1565 bool first_search
= false;
1566 int character_to_start_searching_from
= 0;
1567 if (current_find_text_
!= text
) { // First time we search for this text.
1568 first_search
= true;
1569 std::vector
<PDFiumRange
> old_selection
= selection_
;
1571 current_find_text_
= text
;
1573 if (old_selection
.empty()) {
1574 // Start searching from the beginning of the document.
1575 next_page_to_search_
= 0;
1576 last_page_to_search_
= pages_
.size() - 1;
1577 last_character_index_to_search_
= -1;
1579 // There's a current selection, so start from it.
1580 next_page_to_search_
= old_selection
[0].page_index();
1581 last_character_index_to_search_
= old_selection
[0].char_index();
1582 character_to_start_searching_from
= old_selection
[0].char_index();
1583 last_page_to_search_
= next_page_to_search_
;
1587 int current_page
= next_page_to_search_
;
1589 if (pages_
[current_page
]->available()) {
1590 base::string16 str
= base::UTF8ToUTF16(text
);
1591 // Don't use PDFium to search for now, since it doesn't support unicode text.
1592 // Leave the code for now to avoid bit-rot, in case it's fixed later.
1595 str
, case_sensitive
, first_search
, character_to_start_searching_from
,
1599 str
, case_sensitive
, first_search
, character_to_start_searching_from
,
1603 if (!IsPageVisible(current_page
))
1604 pages_
[current_page
]->Unload();
1607 if (next_page_to_search_
!= last_page_to_search_
||
1608 (first_search
&& last_character_index_to_search_
!= -1)) {
1609 ++next_page_to_search_
;
1612 if (next_page_to_search_
== static_cast<int>(pages_
.size()))
1613 next_page_to_search_
= 0;
1614 // If there's only one page in the document and we start searching midway,
1615 // then we'll want to search the page one more time.
1616 bool end_of_search
=
1617 next_page_to_search_
== last_page_to_search_
&&
1618 // Only one page but didn't start midway.
1619 ((pages_
.size() == 1 && last_character_index_to_search_
== -1) ||
1620 // Started midway, but only 1 page and we already looped around.
1621 (pages_
.size() == 1 && !first_search
) ||
1622 // Started midway, and we've just looped around.
1623 (pages_
.size() > 1 && current_page
== next_page_to_search_
));
1625 if (end_of_search
) {
1626 // Send the final notification.
1627 client_
->NotifyNumberOfFindResultsChanged(find_results_
.size(), true);
1629 pp::CompletionCallback callback
=
1630 find_factory_
.NewCallback(&PDFiumEngine::ContinueFind
);
1631 pp::Module::Get()->core()->CallOnMainThread(
1632 0, callback
, case_sensitive
? 1 : 0);
1636 void PDFiumEngine::SearchUsingPDFium(const base::string16
& term
,
1637 bool case_sensitive
,
1639 int character_to_start_searching_from
,
1641 // Find all the matches in the current page.
1642 unsigned long flags
= case_sensitive
? FPDF_MATCHCASE
: 0;
1643 FPDF_SCHHANDLE find
= FPDFText_FindStart(
1644 pages_
[current_page
]->GetTextPage(),
1645 reinterpret_cast<const unsigned short*>(term
.c_str()),
1646 flags
, character_to_start_searching_from
);
1648 // Note: since we search one page at a time, we don't find matches across
1649 // page boundaries. We could do this manually ourself, but it seems low
1650 // priority since Reader itself doesn't do it.
1651 while (FPDFText_FindNext(find
)) {
1652 PDFiumRange
result(pages_
[current_page
],
1653 FPDFText_GetSchResultIndex(find
),
1654 FPDFText_GetSchCount(find
));
1656 if (!first_search
&&
1657 last_character_index_to_search_
!= -1 &&
1658 result
.page_index() == last_page_to_search_
&&
1659 result
.char_index() >= last_character_index_to_search_
) {
1663 AddFindResult(result
);
1666 FPDFText_FindClose(find
);
1669 void PDFiumEngine::SearchUsingICU(const base::string16
& term
,
1670 bool case_sensitive
,
1672 int character_to_start_searching_from
,
1674 base::string16 page_text
;
1675 int text_length
= pages_
[current_page
]->GetCharCount();
1676 if (character_to_start_searching_from
) {
1677 text_length
-= character_to_start_searching_from
;
1678 } else if (!first_search
&&
1679 last_character_index_to_search_
!= -1 &&
1680 current_page
== last_page_to_search_
) {
1681 text_length
= last_character_index_to_search_
;
1683 if (text_length
<= 0)
1685 unsigned short* data
=
1686 reinterpret_cast<unsigned short*>(WriteInto(&page_text
, text_length
+ 1));
1687 FPDFText_GetText(pages_
[current_page
]->GetTextPage(),
1688 character_to_start_searching_from
,
1691 std::vector
<PDFEngine::Client::SearchStringResult
> results
;
1692 client_
->SearchString(
1693 page_text
.c_str(), term
.c_str(), case_sensitive
, &results
);
1694 for (size_t i
= 0; i
< results
.size(); ++i
) {
1695 // Need to map the indexes from the page text, which may have generated
1696 // characters like space etc, to character indices from the page.
1697 int temp_start
= results
[i
].start_index
+ character_to_start_searching_from
;
1698 int start
= FPDFText_GetCharIndexFromTextIndex(
1699 pages_
[current_page
]->GetTextPage(), temp_start
);
1700 int end
= FPDFText_GetCharIndexFromTextIndex(
1701 pages_
[current_page
]->GetTextPage(),
1702 temp_start
+ results
[i
].length
);
1703 AddFindResult(PDFiumRange(pages_
[current_page
], start
, end
- start
));
1707 void PDFiumEngine::AddFindResult(const PDFiumRange
& result
) {
1708 // Figure out where to insert the new location, since we could have
1709 // started searching midway and now we wrapped.
1711 int page_index
= result
.page_index();
1712 int char_index
= result
.char_index();
1713 for (i
= 0; i
< find_results_
.size(); ++i
) {
1714 if (find_results_
[i
].page_index() > page_index
||
1715 (find_results_
[i
].page_index() == page_index
&&
1716 find_results_
[i
].char_index() > char_index
)) {
1720 find_results_
.insert(find_results_
.begin() + i
, result
);
1723 if (current_find_index_
== -1) {
1724 // Select the first match.
1725 SelectFindResult(true);
1726 } else if (static_cast<int>(i
) <= current_find_index_
) {
1727 // Update the current match index
1728 current_find_index_
++;
1729 client_
->NotifySelectedFindResultChanged(current_find_index_
);
1731 client_
->NotifyNumberOfFindResultsChanged(find_results_
.size(), false);
1734 bool PDFiumEngine::SelectFindResult(bool forward
) {
1735 if (find_results_
.empty()) {
1740 SelectionChangeInvalidator
selection_invalidator(this);
1742 // Move back/forward through the search locations we previously found.
1744 if (++current_find_index_
== static_cast<int>(find_results_
.size()))
1745 current_find_index_
= 0;
1747 if (--current_find_index_
< 0) {
1748 current_find_index_
= find_results_
.size() - 1;
1752 // Update the selection before telling the client to scroll, since it could
1755 selection_
.push_back(find_results_
[current_find_index_
]);
1757 // If the result is not in view, scroll to it.
1759 pp::Rect bounding_rect
;
1760 pp::Rect visible_rect
= GetVisibleRect();
1761 // Use zoom of 1.0 since visible_rect is without zoom.
1762 std::vector
<pp::Rect
> rects
= find_results_
[current_find_index_
].
1763 GetScreenRects(pp::Point(), 1.0, current_rotation_
);
1764 for (i
= 0; i
< rects
.size(); ++i
)
1765 bounding_rect
= bounding_rect
.Union(rects
[i
]);
1766 if (!visible_rect
.Contains(bounding_rect
)) {
1767 pp::Point center
= bounding_rect
.CenterPoint();
1768 // Make the page centered.
1769 int new_y
= static_cast<int>(center
.y() * current_zoom_
) -
1770 static_cast<int>(visible_rect
.height() * current_zoom_
/ 2);
1773 client_
->ScrollToY(new_y
);
1775 // Only move horizontally if it's not visible.
1776 if (center
.x() < visible_rect
.x() || center
.x() > visible_rect
.right()) {
1777 int new_x
= static_cast<int>(center
.x() * current_zoom_
) -
1778 static_cast<int>(visible_rect
.width() * current_zoom_
/ 2);
1781 client_
->ScrollToX(new_x
);
1785 client_
->NotifySelectedFindResultChanged(current_find_index_
);
1790 void PDFiumEngine::StopFind() {
1791 SelectionChangeInvalidator
selection_invalidator(this);
1795 find_results_
.clear();
1796 next_page_to_search_
= -1;
1797 last_page_to_search_
= -1;
1798 last_character_index_to_search_
= -1;
1799 current_find_index_
= -1;
1800 current_find_text_
.clear();
1802 find_factory_
.CancelAll();
1805 void PDFiumEngine::UpdateTickMarks() {
1806 std::vector
<pp::Rect
> tickmarks
;
1807 for (size_t i
= 0; i
< find_results_
.size(); ++i
) {
1809 // Always use an origin of 0,0 since scroll positions don't affect tickmark.
1810 std::vector
<pp::Rect
> rects
= find_results_
[i
].GetScreenRects(
1811 pp::Point(0, 0), current_zoom_
, current_rotation_
);
1812 for (size_t j
= 0; j
< rects
.size(); ++j
)
1813 rect
= rect
.Union(rects
[j
]);
1814 tickmarks
.push_back(rect
);
1817 client_
->UpdateTickMarks(tickmarks
);
1820 void PDFiumEngine::ZoomUpdated(double new_zoom_level
) {
1823 current_zoom_
= new_zoom_level
;
1825 CalculateVisiblePages();
1829 void PDFiumEngine::RotateClockwise() {
1830 current_rotation_
= (current_rotation_
+ 1) % 4;
1831 InvalidateAllPages();
1834 void PDFiumEngine::RotateCounterclockwise() {
1835 current_rotation_
= (current_rotation_
- 1) % 4;
1836 InvalidateAllPages();
1839 void PDFiumEngine::InvalidateAllPages() {
1841 find_results_
.clear();
1846 client_
->Invalidate(pp::Rect(plugin_size_
));
1849 std::string
PDFiumEngine::GetSelectedText() {
1850 base::string16 result
;
1851 for (size_t i
= 0; i
< selection_
.size(); ++i
) {
1853 selection_
[i
- 1].page_index() > selection_
[i
].page_index()) {
1854 result
= selection_
[i
].GetText() + result
;
1856 result
.append(selection_
[i
].GetText());
1860 return base::UTF16ToUTF8(result
);
1863 std::string
PDFiumEngine::GetLinkAtPosition(const pp::Point
& point
) {
1865 PDFiumPage::LinkTarget target
;
1866 PDFiumPage::Area area
= GetCharIndex(point
, &temp
, &temp
, &target
);
1867 if (area
== PDFiumPage::WEBLINK_AREA
)
1869 return std::string();
1872 bool PDFiumEngine::IsSelecting() {
1876 bool PDFiumEngine::HasPermission(DocumentPermission permission
) const {
1877 switch (permission
) {
1878 case PERMISSION_COPY
:
1879 return (permissions_
& kPDFPermissionCopyMask
) != 0;
1880 case PERMISSION_COPY_ACCESSIBLE
:
1881 return (permissions_
& kPDFPermissionCopyAccessibleMask
) != 0;
1882 case PERMISSION_PRINT_LOW_QUALITY
:
1883 return (permissions_
& kPDFPermissionPrintLowQualityMask
) != 0;
1884 case PERMISSION_PRINT_HIGH_QUALITY
:
1885 return (permissions_
& kPDFPermissionPrintLowQualityMask
) != 0 &&
1886 (permissions_
& kPDFPermissionPrintHighQualityMask
) != 0;
1892 void PDFiumEngine::SelectAll() {
1893 SelectionChangeInvalidator
selection_invalidator(this);
1896 for (size_t i
= 0; i
< pages_
.size(); ++i
)
1897 if (pages_
[i
]->available()) {
1898 selection_
.push_back(PDFiumRange(pages_
[i
], 0,
1899 pages_
[i
]->GetCharCount()));
1903 int PDFiumEngine::GetNumberOfPages() {
1904 return pages_
.size();
1907 int PDFiumEngine::GetNamedDestinationPage(const std::string
& destination
) {
1908 // Look for the destination.
1909 FPDF_DEST dest
= FPDF_GetNamedDestByName(doc_
, destination
.c_str());
1911 // Look for a bookmark with the same name.
1912 base::string16 destination_wide
= base::UTF8ToUTF16(destination
);
1913 FPDF_WIDESTRING destination_pdf_wide
=
1914 reinterpret_cast<FPDF_WIDESTRING
>(destination_wide
.c_str());
1915 FPDF_BOOKMARK bookmark
= FPDFBookmark_Find(doc_
, destination_pdf_wide
);
1918 dest
= FPDFBookmark_GetDest(doc_
, bookmark
);
1920 return dest
? FPDFDest_GetPageIndex(doc_
, dest
) : -1;
1923 int PDFiumEngine::GetFirstVisiblePage() {
1924 CalculateVisiblePages();
1925 return first_visible_page_
;
1928 int PDFiumEngine::GetMostVisiblePage() {
1929 CalculateVisiblePages();
1930 return most_visible_page_
;
1933 pp::Rect
PDFiumEngine::GetPageRect(int index
) {
1934 pp::Rect
rc(pages_
[index
]->rect());
1935 rc
.Inset(-kPageShadowLeft
, -kPageShadowTop
,
1936 -kPageShadowRight
, -kPageShadowBottom
);
1940 pp::Rect
PDFiumEngine::GetPageContentsRect(int index
) {
1941 return GetScreenRect(pages_
[index
]->rect());
1944 void PDFiumEngine::PaintThumbnail(pp::ImageData
* image_data
, int index
) {
1945 FPDF_BITMAP bitmap
= FPDFBitmap_CreateEx(
1946 image_data
->size().width(), image_data
->size().height(),
1947 FPDFBitmap_BGRx
, image_data
->data(), image_data
->stride());
1949 if (pages_
[index
]->available()) {
1950 FPDFBitmap_FillRect(bitmap
, 0, 0, image_data
->size().width(),
1951 image_data
->size().height(), 0xFFFFFFFF);
1953 FPDF_RenderPageBitmap(
1954 bitmap
, pages_
[index
]->GetPage(), 0, 0, image_data
->size().width(),
1955 image_data
->size().height(), 0, GetRenderingFlags());
1957 FPDFBitmap_FillRect(bitmap
, 0, 0, image_data
->size().width(),
1958 image_data
->size().height(), kPendingPageColor
);
1961 FPDFBitmap_Destroy(bitmap
);
1964 void PDFiumEngine::SetGrayscale(bool grayscale
) {
1965 render_grayscale_
= grayscale
;
1968 void PDFiumEngine::OnCallback(int id
) {
1969 if (!timers_
.count(id
))
1972 timers_
[id
].second(id
);
1973 if (timers_
.count(id
)) // The callback might delete the timer.
1974 client_
->ScheduleCallback(id
, timers_
[id
].first
);
1977 std::string
PDFiumEngine::GetPageAsJSON(int index
) {
1978 if (!(HasPermission(PERMISSION_COPY
) ||
1979 HasPermission(PERMISSION_COPY_ACCESSIBLE
))) {
1983 if (index
< 0 || static_cast<size_t>(index
) > pages_
.size() - 1)
1986 // TODO(thestig) Remove after debugging http://crbug.com/402035
1987 CHECK(pages_
[index
]);
1988 scoped_ptr
<base::Value
> node(
1989 pages_
[index
]->GetAccessibleContentAsValue(current_rotation_
));
1990 std::string page_json
;
1991 base::JSONWriter::Write(node
.get(), &page_json
);
1995 bool PDFiumEngine::GetPrintScaling() {
1996 return !!FPDF_VIEWERREF_GetPrintScaling(doc_
);
1999 void PDFiumEngine::AppendBlankPages(int num_pages
) {
2000 DCHECK(num_pages
!= 0);
2006 pending_pages_
.clear();
2008 // Delete all pages except the first one.
2009 while (pages_
.size() > 1) {
2010 delete pages_
.back();
2012 FPDFPage_Delete(doc_
, pages_
.size());
2015 // Calculate document size and all page sizes.
2016 std::vector
<pp::Rect
> page_rects
;
2017 pp::Size page_size
= GetPageSize(0);
2018 page_size
.Enlarge(kPageShadowLeft
+ kPageShadowRight
,
2019 kPageShadowTop
+ kPageShadowBottom
);
2020 pp::Size old_document_size
= document_size_
;
2021 document_size_
= pp::Size(page_size
.width(), 0);
2022 for (int i
= 0; i
< num_pages
; ++i
) {
2024 // Add space for horizontal separator.
2025 document_size_
.Enlarge(0, kPageSeparatorThickness
);
2028 pp::Rect
rect(pp::Point(0, document_size_
.height()), page_size
);
2029 page_rects
.push_back(rect
);
2031 document_size_
.Enlarge(0, page_size
.height());
2034 // Create blank pages.
2035 for (int i
= 1; i
< num_pages
; ++i
) {
2036 pp::Rect
page_rect(page_rects
[i
]);
2037 page_rect
.Inset(kPageShadowLeft
, kPageShadowTop
,
2038 kPageShadowRight
, kPageShadowBottom
);
2039 double width_in_points
=
2040 page_rect
.width() * kPointsPerInch
/ kPixelsPerInch
;
2041 double height_in_points
=
2042 page_rect
.height() * kPointsPerInch
/ kPixelsPerInch
;
2043 FPDFPage_New(doc_
, i
, width_in_points
, height_in_points
);
2044 pages_
.push_back(new PDFiumPage(this, i
, page_rect
, true));
2045 // TODO(thestig) Remove after debugging http://crbug.com/402035
2046 CHECK(pages_
.back());
2049 CalculateVisiblePages();
2050 if (document_size_
!= old_document_size
)
2051 client_
->DocumentSizeUpdated(document_size_
);
2054 void PDFiumEngine::LoadDocument() {
2055 // Check if the document is ready for loading. If it isn't just bail for now,
2056 // we will call LoadDocument() again later.
2057 if (!doc_
&& !doc_loader_
.IsDocumentComplete() &&
2058 !FPDFAvail_IsDocAvail(fpdf_availability_
, &download_hints_
)) {
2062 // If we're in the middle of getting a password, just return. We will retry
2063 // loading the document after we get the password anyway.
2064 if (getting_password_
)
2067 ScopedUnsupportedFeature
scoped_unsupported_feature(this);
2068 bool needs_password
= false;
2069 if (TryLoadingDoc(false, std::string(), &needs_password
)) {
2070 ContinueLoadingDocument(false, std::string());
2074 GetPasswordAndLoad();
2076 client_
->DocumentLoadFailed();
2079 bool PDFiumEngine::TryLoadingDoc(bool with_password
,
2080 const std::string
& password
,
2081 bool* needs_password
) {
2082 *needs_password
= false;
2086 const char* password_cstr
= NULL
;
2087 if (with_password
) {
2088 password_cstr
= password
.c_str();
2089 password_tries_remaining_
--;
2091 if (doc_loader_
.IsDocumentComplete())
2092 doc_
= FPDF_LoadCustomDocument(&file_access_
, password_cstr
);
2094 doc_
= FPDFAvail_GetDocument(fpdf_availability_
, password_cstr
);
2096 if (!doc_
&& FPDF_GetLastError() == FPDF_ERR_PASSWORD
)
2097 *needs_password
= true;
2099 return doc_
!= NULL
;
2102 void PDFiumEngine::GetPasswordAndLoad() {
2103 getting_password_
= true;
2104 DCHECK(!doc_
&& FPDF_GetLastError() == FPDF_ERR_PASSWORD
);
2105 client_
->GetDocumentPassword(password_factory_
.NewCallbackWithOutput(
2106 &PDFiumEngine::OnGetPasswordComplete
));
2109 void PDFiumEngine::OnGetPasswordComplete(int32_t result
,
2110 const pp::Var
& password
) {
2111 getting_password_
= false;
2113 bool password_given
= false;
2114 std::string password_text
;
2115 if (result
== PP_OK
&& password
.is_string()) {
2116 password_text
= password
.AsString();
2117 if (!password_text
.empty())
2118 password_given
= true;
2120 ContinueLoadingDocument(password_given
, password_text
);
2123 void PDFiumEngine::ContinueLoadingDocument(
2125 const std::string
& password
) {
2126 ScopedUnsupportedFeature
scoped_unsupported_feature(this);
2128 bool needs_password
= false;
2129 bool loaded
= TryLoadingDoc(has_password
, password
, &needs_password
);
2130 bool password_incorrect
= !loaded
&& has_password
&& needs_password
;
2131 if (password_incorrect
&& password_tries_remaining_
> 0) {
2132 GetPasswordAndLoad();
2137 client_
->DocumentLoadFailed();
2141 if (FPDFDoc_GetPageMode(doc_
) == PAGEMODE_USEOUTLINES
)
2142 client_
->DocumentHasUnsupportedFeature("Bookmarks");
2144 permissions_
= FPDF_GetDocPermissions(doc_
);
2147 // Only returns 0 when data isn't available. If form data is downloaded, or
2148 // if this isn't a form, returns positive values.
2149 if (!doc_loader_
.IsDocumentComplete() &&
2150 !FPDFAvail_IsFormAvail(fpdf_availability_
, &download_hints_
)) {
2154 form_
= FPDFDOC_InitFormFillEnviroument(
2155 doc_
, static_cast<FPDF_FORMFILLINFO
*>(this));
2156 FPDF_SetFormFieldHighlightColor(form_
, 0, kFormHighlightColor
);
2157 FPDF_SetFormFieldHighlightAlpha(form_
, kFormHighlightAlpha
);
2160 if (!doc_loader_
.IsDocumentComplete()) {
2161 // Check if the first page is available. In a linearized PDF, that is not
2162 // always page 0. Doing this gives us the default page size, since when the
2163 // document is available, the first page is available as well.
2164 CheckPageAvailable(FPDFAvail_GetFirstPageNum(doc_
), &pending_pages_
);
2167 LoadPageInfo(false);
2169 if (doc_loader_
.IsDocumentComplete())
2170 FinishLoadingDocument();
2173 void PDFiumEngine::LoadPageInfo(bool reload
) {
2174 pending_pages_
.clear();
2175 pp::Size old_document_size
= document_size_
;
2176 document_size_
= pp::Size();
2177 std::vector
<pp::Rect
> page_rects
;
2178 int page_count
= FPDF_GetPageCount(doc_
);
2179 bool doc_complete
= doc_loader_
.IsDocumentComplete();
2180 for (int i
= 0; i
< page_count
; ++i
) {
2182 // Add space for horizontal separator.
2183 document_size_
.Enlarge(0, kPageSeparatorThickness
);
2186 // Get page availability. If reload==false, and document is not loaded yet
2187 // (we are using async loading) - mark all pages as unavailable.
2188 // If reload==true (we have document constructed already), get page
2189 // availability flag from already existing PDFiumPage class.
2190 bool page_available
= reload
? pages_
[i
]->available() : doc_complete
;
2192 pp::Size size
= page_available
? GetPageSize(i
) : default_page_size_
;
2193 size
.Enlarge(kPageShadowLeft
+ kPageShadowRight
,
2194 kPageShadowTop
+ kPageShadowBottom
);
2195 pp::Rect
rect(pp::Point(0, document_size_
.height()), size
);
2196 page_rects
.push_back(rect
);
2198 if (size
.width() > document_size_
.width())
2199 document_size_
.set_width(size
.width());
2201 document_size_
.Enlarge(0, size
.height());
2204 for (int i
= 0; i
< page_count
; ++i
) {
2205 // Center pages relative to the entire document.
2206 page_rects
[i
].set_x((document_size_
.width() - page_rects
[i
].width()) / 2);
2207 pp::Rect
page_rect(page_rects
[i
]);
2208 page_rect
.Inset(kPageShadowLeft
, kPageShadowTop
,
2209 kPageShadowRight
, kPageShadowBottom
);
2211 pages_
[i
]->set_rect(page_rect
);
2213 pages_
.push_back(new PDFiumPage(this, i
, page_rect
, doc_complete
));
2214 // TODO(thestig) Remove after debugging http://crbug.com/402035
2215 CHECK(pages_
.back());
2219 CalculateVisiblePages();
2220 if (document_size_
!= old_document_size
)
2221 client_
->DocumentSizeUpdated(document_size_
);
2224 void PDFiumEngine::CalculateVisiblePages() {
2225 // Clear pending requests queue, since it may contain requests to the pages
2226 // that are already invisible (after scrolling for example).
2227 pending_pages_
.clear();
2228 doc_loader_
.ClearPendingRequests();
2230 visible_pages_
.clear();
2231 pp::Rect
visible_rect(plugin_size_
);
2232 for (size_t i
= 0; i
< pages_
.size(); ++i
) {
2233 // Check an entire PageScreenRect, since we might need to repaint side
2234 // borders and shadows even if the page itself is not visible.
2235 // For example, when user use pdf with different page sizes and zoomed in
2236 // outside page area.
2237 if (visible_rect
.Intersects(GetPageScreenRect(i
))) {
2238 visible_pages_
.push_back(i
);
2239 CheckPageAvailable(i
, &pending_pages_
);
2241 // Need to unload pages when we're not using them, since some PDFs use a
2242 // lot of memory. See http://crbug.com/48791
2243 if (defer_page_unload_
) {
2244 deferred_page_unloads_
.push_back(i
);
2246 pages_
[i
]->Unload();
2249 // If the last mouse down was on a page that's no longer visible, reset
2250 // that variable so that we don't send keyboard events to it (the focus
2251 // will be lost when the page is first closed anyways).
2252 if (static_cast<int>(i
) == last_page_mouse_down_
)
2253 last_page_mouse_down_
= -1;
2257 // Any pending highlighting of form fields will be invalid since these are in
2258 // screen coordinates.
2259 form_highlights_
.clear();
2261 if (visible_pages_
.size() == 0)
2262 first_visible_page_
= -1;
2264 first_visible_page_
= visible_pages_
.front();
2266 int most_visible_page
= first_visible_page_
;
2267 // Check if the next page is more visible than the first one.
2268 if (most_visible_page
!= -1 &&
2269 pages_
.size() > 0 &&
2270 most_visible_page
< static_cast<int>(pages_
.size()) - 1) {
2272 visible_rect
.Intersect(GetPageScreenRect(most_visible_page
));
2274 visible_rect
.Intersect(GetPageScreenRect(most_visible_page
+ 1));
2275 if (rc_next
.height() > rc_first
.height())
2276 most_visible_page
++;
2279 SetCurrentPage(most_visible_page
);
2282 bool PDFiumEngine::IsPageVisible(int index
) const {
2283 for (size_t i
= 0; i
< visible_pages_
.size(); ++i
) {
2284 if (visible_pages_
[i
] == index
)
2291 bool PDFiumEngine::CheckPageAvailable(int index
, std::vector
<int>* pending
) {
2292 if (!doc_
|| !form_
)
2295 if (static_cast<int>(pages_
.size()) > index
&& pages_
[index
]->available())
2298 if (!FPDFAvail_IsPageAvail(fpdf_availability_
, index
, &download_hints_
)) {
2300 for (j
= 0; j
< pending
->size(); ++j
) {
2301 if ((*pending
)[j
] == index
)
2305 if (j
== pending
->size())
2306 pending
->push_back(index
);
2310 if (static_cast<int>(pages_
.size()) > index
)
2311 pages_
[index
]->set_available(true);
2312 if (!default_page_size_
.GetArea())
2313 default_page_size_
= GetPageSize(index
);
2317 pp::Size
PDFiumEngine::GetPageSize(int index
) {
2319 double width_in_points
= 0;
2320 double height_in_points
= 0;
2321 int rv
= FPDF_GetPageSizeByIndex(
2322 doc_
, index
, &width_in_points
, &height_in_points
);
2325 int width_in_pixels
= static_cast<int>(
2326 width_in_points
* kPixelsPerInch
/ kPointsPerInch
);
2327 int height_in_pixels
= static_cast<int>(
2328 height_in_points
* kPixelsPerInch
/ kPointsPerInch
);
2329 if (current_rotation_
% 2 == 1)
2330 std::swap(width_in_pixels
, height_in_pixels
);
2331 size
= pp::Size(width_in_pixels
, height_in_pixels
);
2336 int PDFiumEngine::StartPaint(int page_index
, const pp::Rect
& dirty
) {
2337 // For the first time we hit paint, do nothing and just record the paint for
2338 // the next callback. This keeps the UI responsive in case the user is doing
2339 // a lot of scrolling.
2340 ProgressivePaint progressive
;
2341 progressive
.rect
= dirty
;
2342 progressive
.page_index
= page_index
;
2343 progressive
.bitmap
= NULL
;
2344 progressive
.painted_
= false;
2345 progressive_paints_
.push_back(progressive
);
2346 return progressive_paints_
.size() - 1;
2349 bool PDFiumEngine::ContinuePaint(int progressive_index
,
2350 pp::ImageData
* image_data
) {
2351 #if defined(OS_LINUX)
2352 g_last_instance_id
= client_
->GetPluginInstance()->pp_instance();
2356 int page_index
= progressive_paints_
[progressive_index
].page_index
;
2357 last_progressive_start_time_
= base::Time::Now();
2358 if (progressive_paints_
[progressive_index
].bitmap
) {
2359 rv
= FPDF_RenderPage_Continue(
2360 pages_
[page_index
]->GetPage(), static_cast<IFSDK_PAUSE
*>(this));
2362 pp::Rect dirty
= progressive_paints_
[progressive_index
].rect
;
2363 progressive_paints_
[progressive_index
].bitmap
= CreateBitmap(dirty
,
2365 int start_x
, start_y
, size_x
, size_y
;
2367 page_index
, dirty
, &start_x
, &start_y
, &size_x
, &size_y
);
2368 FPDFBitmap_FillRect(progressive_paints_
[progressive_index
].bitmap
, start_x
,
2369 start_y
, size_x
, size_y
, 0xFFFFFFFF);
2370 rv
= FPDF_RenderPageBitmap_Start(
2371 progressive_paints_
[progressive_index
].bitmap
,
2372 pages_
[page_index
]->GetPage(), start_x
, start_y
, size_x
, size_y
,
2374 GetRenderingFlags(), static_cast<IFSDK_PAUSE
*>(this));
2376 return rv
!= FPDF_RENDER_TOBECOUNTINUED
;
2379 void PDFiumEngine::FinishPaint(int progressive_index
,
2380 pp::ImageData
* image_data
) {
2381 int page_index
= progressive_paints_
[progressive_index
].page_index
;
2382 pp::Rect dirty_in_screen
= progressive_paints_
[progressive_index
].rect
;
2383 FPDF_BITMAP bitmap
= progressive_paints_
[progressive_index
].bitmap
;
2384 int start_x
, start_y
, size_x
, size_y
;
2386 page_index
, dirty_in_screen
, &start_x
, &start_y
, &size_x
, &size_y
);
2390 form_
, bitmap
, pages_
[page_index
]->GetPage(), start_x
, start_y
, size_x
,
2391 size_y
, current_rotation_
, GetRenderingFlags());
2393 FillPageSides(progressive_index
);
2395 // Paint the page shadows.
2396 PaintPageShadow(progressive_index
, image_data
);
2398 DrawSelections(progressive_index
, image_data
);
2400 FPDF_RenderPage_Close(pages_
[page_index
]->GetPage());
2401 FPDFBitmap_Destroy(bitmap
);
2402 progressive_paints_
.erase(progressive_paints_
.begin() + progressive_index
);
2404 client_
->DocumentPaintOccurred();
2407 void PDFiumEngine::CancelPaints() {
2408 for (size_t i
= 0; i
< progressive_paints_
.size(); ++i
) {
2409 FPDF_RenderPage_Close(pages_
[progressive_paints_
[i
].page_index
]->GetPage());
2410 FPDFBitmap_Destroy(progressive_paints_
[i
].bitmap
);
2412 progressive_paints_
.clear();
2415 void PDFiumEngine::FillPageSides(int progressive_index
) {
2416 int page_index
= progressive_paints_
[progressive_index
].page_index
;
2417 pp::Rect dirty_in_screen
= progressive_paints_
[progressive_index
].rect
;
2418 FPDF_BITMAP bitmap
= progressive_paints_
[progressive_index
].bitmap
;
2420 pp::Rect page_rect
= pages_
[page_index
]->rect();
2421 if (page_rect
.x() > 0) {
2423 page_rect
.y() - kPageShadowTop
,
2424 page_rect
.x() - kPageShadowLeft
,
2425 page_rect
.height() + kPageShadowTop
+
2426 kPageShadowBottom
+ kPageSeparatorThickness
);
2427 left
= GetScreenRect(left
).Intersect(dirty_in_screen
);
2429 FPDFBitmap_FillRect(bitmap
, left
.x() - dirty_in_screen
.x(),
2430 left
.y() - dirty_in_screen
.y(), left
.width(),
2431 left
.height(), kBackgroundColor
);
2434 if (page_rect
.right() < document_size_
.width()) {
2435 pp::Rect
right(page_rect
.right() + kPageShadowRight
,
2436 page_rect
.y() - kPageShadowTop
,
2437 document_size_
.width() - page_rect
.right() -
2439 page_rect
.height() + kPageShadowTop
+
2440 kPageShadowBottom
+ kPageSeparatorThickness
);
2441 right
= GetScreenRect(right
).Intersect(dirty_in_screen
);
2443 FPDFBitmap_FillRect(bitmap
, right
.x() - dirty_in_screen
.x(),
2444 right
.y() - dirty_in_screen
.y(), right
.width(),
2445 right
.height(), kBackgroundColor
);
2449 pp::Rect
bottom(page_rect
.x() - kPageShadowLeft
,
2450 page_rect
.bottom() + kPageShadowBottom
,
2451 page_rect
.width() + kPageShadowLeft
+ kPageShadowRight
,
2452 kPageSeparatorThickness
);
2453 bottom
= GetScreenRect(bottom
).Intersect(dirty_in_screen
);
2455 FPDFBitmap_FillRect(bitmap
, bottom
.x() - dirty_in_screen
.x(),
2456 bottom
.y() - dirty_in_screen
.y(), bottom
.width(),
2457 bottom
.height(), kBackgroundColor
);
2460 void PDFiumEngine::PaintPageShadow(int progressive_index
,
2461 pp::ImageData
* image_data
) {
2462 int page_index
= progressive_paints_
[progressive_index
].page_index
;
2463 pp::Rect dirty_in_screen
= progressive_paints_
[progressive_index
].rect
;
2464 pp::Rect page_rect
= pages_
[page_index
]->rect();
2465 pp::Rect
shadow_rect(page_rect
);
2466 shadow_rect
.Inset(-kPageShadowLeft
, -kPageShadowTop
,
2467 -kPageShadowRight
, -kPageShadowBottom
);
2469 // Due to the rounding errors of the GetScreenRect it is possible to get
2470 // different size shadows on the left and right sides even they are defined
2471 // the same. To fix this issue let's calculate shadow rect and then shrink
2472 // it by the size of the shadows.
2473 shadow_rect
= GetScreenRect(shadow_rect
);
2474 page_rect
= shadow_rect
;
2476 page_rect
.Inset(static_cast<int>(ceil(kPageShadowLeft
* current_zoom_
)),
2477 static_cast<int>(ceil(kPageShadowTop
* current_zoom_
)),
2478 static_cast<int>(ceil(kPageShadowRight
* current_zoom_
)),
2479 static_cast<int>(ceil(kPageShadowBottom
* current_zoom_
)));
2481 DrawPageShadow(page_rect
, shadow_rect
, dirty_in_screen
, image_data
);
2484 void PDFiumEngine::DrawSelections(int progressive_index
,
2485 pp::ImageData
* image_data
) {
2486 int page_index
= progressive_paints_
[progressive_index
].page_index
;
2487 pp::Rect dirty_in_screen
= progressive_paints_
[progressive_index
].rect
;
2489 void* region
= NULL
;
2491 GetRegion(dirty_in_screen
.point(), image_data
, ®ion
, &stride
);
2493 std::vector
<pp::Rect
> highlighted_rects
;
2494 pp::Rect visible_rect
= GetVisibleRect();
2495 for (size_t k
= 0; k
< selection_
.size(); ++k
) {
2496 if (selection_
[k
].page_index() != page_index
)
2498 std::vector
<pp::Rect
> rects
= selection_
[k
].GetScreenRects(
2499 visible_rect
.point(), current_zoom_
, current_rotation_
);
2500 for (size_t j
= 0; j
< rects
.size(); ++j
) {
2501 pp::Rect visible_selection
= rects
[j
].Intersect(dirty_in_screen
);
2502 if (visible_selection
.IsEmpty())
2505 visible_selection
.Offset(
2506 -dirty_in_screen
.point().x(), -dirty_in_screen
.point().y());
2507 Highlight(region
, stride
, visible_selection
, &highlighted_rects
);
2511 for (size_t k
= 0; k
< form_highlights_
.size(); ++k
) {
2512 pp::Rect visible_selection
= form_highlights_
[k
].Intersect(dirty_in_screen
);
2513 if (visible_selection
.IsEmpty())
2516 visible_selection
.Offset(
2517 -dirty_in_screen
.point().x(), -dirty_in_screen
.point().y());
2518 Highlight(region
, stride
, visible_selection
, &highlighted_rects
);
2520 form_highlights_
.clear();
2523 void PDFiumEngine::PaintUnavailablePage(int page_index
,
2524 const pp::Rect
& dirty
,
2525 pp::ImageData
* image_data
) {
2526 int start_x
, start_y
, size_x
, size_y
;
2527 GetPDFiumRect(page_index
, dirty
, &start_x
, &start_y
, &size_x
, &size_y
);
2528 FPDF_BITMAP bitmap
= CreateBitmap(dirty
, image_data
);
2529 FPDFBitmap_FillRect(bitmap
, start_x
, start_y
, size_x
, size_y
,
2532 pp::Rect
loading_text_in_screen(
2533 pages_
[page_index
]->rect().width() / 2,
2534 pages_
[page_index
]->rect().y() + kLoadingTextVerticalOffset
, 0, 0);
2535 loading_text_in_screen
= GetScreenRect(loading_text_in_screen
);
2536 FPDFBitmap_Destroy(bitmap
);
2539 int PDFiumEngine::GetProgressiveIndex(int page_index
) const {
2540 for (size_t i
= 0; i
< progressive_paints_
.size(); ++i
) {
2541 if (progressive_paints_
[i
].page_index
== page_index
)
2547 FPDF_BITMAP
PDFiumEngine::CreateBitmap(const pp::Rect
& rect
,
2548 pp::ImageData
* image_data
) const {
2551 GetRegion(rect
.point(), image_data
, ®ion
, &stride
);
2554 return FPDFBitmap_CreateEx(
2555 rect
.width(), rect
.height(), FPDFBitmap_BGRx
, region
, stride
);
2558 void PDFiumEngine::GetPDFiumRect(
2559 int page_index
, const pp::Rect
& rect
, int* start_x
, int* start_y
,
2560 int* size_x
, int* size_y
) const {
2561 pp::Rect page_rect
= GetScreenRect(pages_
[page_index
]->rect());
2562 page_rect
.Offset(-rect
.x(), -rect
.y());
2564 *start_x
= page_rect
.x();
2565 *start_y
= page_rect
.y();
2566 *size_x
= page_rect
.width();
2567 *size_y
= page_rect
.height();
2570 int PDFiumEngine::GetRenderingFlags() const {
2571 int flags
= FPDF_LCD_TEXT
| FPDF_NO_CATCH
;
2572 if (render_grayscale_
)
2573 flags
|= FPDF_GRAYSCALE
;
2574 if (client_
->IsPrintPreview())
2575 flags
|= FPDF_PRINTING
;
2579 pp::Rect
PDFiumEngine::GetVisibleRect() const {
2581 rv
.set_x(static_cast<int>(position_
.x() / current_zoom_
));
2582 rv
.set_y(static_cast<int>(position_
.y() / current_zoom_
));
2583 rv
.set_width(static_cast<int>(ceil(plugin_size_
.width() / current_zoom_
)));
2584 rv
.set_height(static_cast<int>(ceil(plugin_size_
.height() / current_zoom_
)));
2588 pp::Rect
PDFiumEngine::GetPageScreenRect(int page_index
) const {
2589 // Since we use this rect for creating the PDFium bitmap, also include other
2590 // areas around the page that we might need to update such as the page
2591 // separator and the sides if the page is narrower than the document.
2592 return GetScreenRect(pp::Rect(
2594 pages_
[page_index
]->rect().y() - kPageShadowTop
,
2595 document_size_
.width(),
2596 pages_
[page_index
]->rect().height() + kPageShadowTop
+
2597 kPageShadowBottom
+ kPageSeparatorThickness
));
2600 pp::Rect
PDFiumEngine::GetScreenRect(const pp::Rect
& rect
) const {
2603 static_cast<int>(ceil(rect
.right() * current_zoom_
- position_
.x()));
2605 static_cast<int>(ceil(rect
.bottom() * current_zoom_
- position_
.y()));
2607 rv
.set_x(static_cast<int>(rect
.x() * current_zoom_
- position_
.x()));
2608 rv
.set_y(static_cast<int>(rect
.y() * current_zoom_
- position_
.y()));
2609 rv
.set_width(right
- rv
.x());
2610 rv
.set_height(bottom
- rv
.y());
2614 void PDFiumEngine::Highlight(void* buffer
,
2616 const pp::Rect
& rect
,
2617 std::vector
<pp::Rect
>* highlighted_rects
) {
2621 pp::Rect new_rect
= rect
;
2622 for (size_t i
= 0; i
< highlighted_rects
->size(); ++i
)
2623 new_rect
= new_rect
.Subtract((*highlighted_rects
)[i
]);
2625 highlighted_rects
->push_back(new_rect
);
2626 int l
= new_rect
.x();
2627 int t
= new_rect
.y();
2628 int w
= new_rect
.width();
2629 int h
= new_rect
.height();
2631 for (int y
= t
; y
< t
+ h
; ++y
) {
2632 for (int x
= l
; x
< l
+ w
; ++x
) {
2633 uint8
* pixel
= static_cast<uint8
*>(buffer
) + y
* stride
+ x
* 4;
2634 // This is our highlight color.
2635 pixel
[0] = static_cast<uint8
>(
2636 pixel
[0] * (kHighlightColorB
/ 255.0));
2637 pixel
[1] = static_cast<uint8
>(
2638 pixel
[1] * (kHighlightColorG
/ 255.0));
2639 pixel
[2] = static_cast<uint8
>(
2640 pixel
[2] * (kHighlightColorR
/ 255.0));
2645 PDFiumEngine::SelectionChangeInvalidator::SelectionChangeInvalidator(
2646 PDFiumEngine
* engine
) : engine_(engine
) {
2647 previous_origin_
= engine_
->GetVisibleRect().point();
2648 GetVisibleSelectionsScreenRects(&old_selections_
);
2651 PDFiumEngine::SelectionChangeInvalidator::~SelectionChangeInvalidator() {
2652 // Offset the old selections if the document scrolled since we recorded them.
2653 pp::Point offset
= previous_origin_
- engine_
->GetVisibleRect().point();
2654 for (size_t i
= 0; i
< old_selections_
.size(); ++i
)
2655 old_selections_
[i
].Offset(offset
);
2657 std::vector
<pp::Rect
> new_selections
;
2658 GetVisibleSelectionsScreenRects(&new_selections
);
2659 for (size_t i
= 0; i
< new_selections
.size(); ++i
) {
2660 for (size_t j
= 0; j
< old_selections_
.size(); ++j
) {
2661 if (new_selections
[i
] == old_selections_
[j
]) {
2662 // Rectangle was selected before and after, so no need to invalidate it.
2663 // Mark the rectangles by setting them to empty.
2664 new_selections
[i
] = old_selections_
[j
] = pp::Rect();
2669 for (size_t i
= 0; i
< old_selections_
.size(); ++i
) {
2670 if (!old_selections_
[i
].IsEmpty())
2671 engine_
->client_
->Invalidate(old_selections_
[i
]);
2673 for (size_t i
= 0; i
< new_selections
.size(); ++i
) {
2674 if (!new_selections
[i
].IsEmpty())
2675 engine_
->client_
->Invalidate(new_selections
[i
]);
2677 engine_
->OnSelectionChanged();
2681 PDFiumEngine::SelectionChangeInvalidator::GetVisibleSelectionsScreenRects(
2682 std::vector
<pp::Rect
>* rects
) {
2683 pp::Rect visible_rect
= engine_
->GetVisibleRect();
2684 for (size_t i
= 0; i
< engine_
->selection_
.size(); ++i
) {
2685 int page_index
= engine_
->selection_
[i
].page_index();
2686 if (!engine_
->IsPageVisible(page_index
))
2687 continue; // This selection is on a page that's not currently visible.
2689 std::vector
<pp::Rect
> selection_rects
=
2690 engine_
->selection_
[i
].GetScreenRects(
2691 visible_rect
.point(),
2692 engine_
->current_zoom_
,
2693 engine_
->current_rotation_
);
2694 rects
->insert(rects
->end(), selection_rects
.begin(), selection_rects
.end());
2698 void PDFiumEngine::DeviceToPage(int page_index
,
2703 *page_x
= *page_y
= 0;
2704 int temp_x
= static_cast<int>((device_x
+ position_
.x())/ current_zoom_
-
2705 pages_
[page_index
]->rect().x());
2706 int temp_y
= static_cast<int>((device_y
+ position_
.y())/ current_zoom_
-
2707 pages_
[page_index
]->rect().y());
2709 pages_
[page_index
]->GetPage(), 0, 0,
2710 pages_
[page_index
]->rect().width(), pages_
[page_index
]->rect().height(),
2711 current_rotation_
, temp_x
, temp_y
, page_x
, page_y
);
2714 int PDFiumEngine::GetVisiblePageIndex(FPDF_PAGE page
) {
2715 for (size_t i
= 0; i
< visible_pages_
.size(); ++i
) {
2716 if (pages_
[visible_pages_
[i
]]->GetPage() == page
)
2717 return visible_pages_
[i
];
2722 void PDFiumEngine::SetCurrentPage(int index
) {
2723 if (index
== most_visible_page_
|| !form_
)
2725 if (most_visible_page_
!= -1 && called_do_document_action_
) {
2726 FPDF_PAGE old_page
= pages_
[most_visible_page_
]->GetPage();
2727 FORM_DoPageAAction(old_page
, form_
, FPDFPAGE_AACTION_CLOSE
);
2729 most_visible_page_
= index
;
2730 #if defined(OS_LINUX)
2731 g_last_instance_id
= client_
->GetPluginInstance()->pp_instance();
2733 if (most_visible_page_
!= -1 && called_do_document_action_
) {
2734 FPDF_PAGE new_page
= pages_
[most_visible_page_
]->GetPage();
2735 FORM_DoPageAAction(new_page
, form_
, FPDFPAGE_AACTION_OPEN
);
2739 void PDFiumEngine::TransformPDFPageForPrinting(
2741 const PP_PrintSettings_Dev
& print_settings
) {
2742 // Get the source page width and height in points.
2743 const double src_page_width
= FPDF_GetPageWidth(page
);
2744 const double src_page_height
= FPDF_GetPageHeight(page
);
2746 const int src_page_rotation
= FPDFPage_GetRotation(page
);
2747 const bool fit_to_page
= print_settings
.print_scaling_option
==
2748 PP_PRINTSCALINGOPTION_FIT_TO_PRINTABLE_AREA
;
2750 pp::Size
page_size(print_settings
.paper_size
);
2751 pp::Rect
content_rect(print_settings
.printable_area
);
2752 const bool rotated
= (src_page_rotation
% 2 == 1);
2753 SetPageSizeAndContentRect(rotated
,
2754 src_page_width
> src_page_height
,
2758 // Compute the screen page width and height in points.
2759 const int actual_page_width
=
2760 rotated
? page_size
.height() : page_size
.width();
2761 const int actual_page_height
=
2762 rotated
? page_size
.width() : page_size
.height();
2764 const double scale_factor
= CalculateScaleFactor(fit_to_page
, content_rect
,
2766 src_page_height
, rotated
);
2768 // Calculate positions for the clip box.
2769 ClipBox source_clip_box
;
2770 CalculateClipBoxBoundary(page
, scale_factor
, rotated
, &source_clip_box
);
2772 // Calculate the translation offset values.
2773 double offset_x
= 0;
2774 double offset_y
= 0;
2776 CalculateScaledClipBoxOffset(content_rect
, source_clip_box
, &offset_x
,
2779 CalculateNonScaledClipBoxOffset(content_rect
, src_page_rotation
,
2780 actual_page_width
, actual_page_height
,
2781 source_clip_box
, &offset_x
, &offset_y
);
2784 // Reset the media box and crop box. When the page has crop box and media box,
2785 // the plugin will display the crop box contents and not the entire media box.
2786 // If the pages have different crop box values, the plugin will display a
2787 // document of multiple page sizes. To give better user experience, we
2788 // decided to have same crop box and media box values. Hence, the user will
2789 // see a list of uniform pages.
2790 FPDFPage_SetMediaBox(page
, 0, 0, page_size
.width(), page_size
.height());
2791 FPDFPage_SetCropBox(page
, 0, 0, page_size
.width(), page_size
.height());
2793 // Transformation is not required, return. Do this check only after updating
2794 // the media box and crop box. For more detailed information, please refer to
2795 // the comment block right before FPDF_SetMediaBox and FPDF_GetMediaBox calls.
2796 if (scale_factor
== 1.0 && offset_x
== 0 && offset_y
== 0)
2800 // All the positions have been calculated, now manipulate the PDF.
2801 FS_MATRIX matrix
= {static_cast<float>(scale_factor
),
2804 static_cast<float>(scale_factor
),
2805 static_cast<float>(offset_x
),
2806 static_cast<float>(offset_y
)};
2807 FS_RECTF cliprect
= {static_cast<float>(source_clip_box
.left
+offset_x
),
2808 static_cast<float>(source_clip_box
.top
+offset_y
),
2809 static_cast<float>(source_clip_box
.right
+offset_x
),
2810 static_cast<float>(source_clip_box
.bottom
+offset_y
)};
2811 FPDFPage_TransFormWithClip(page
, &matrix
, &cliprect
);
2812 FPDFPage_TransformAnnots(page
, scale_factor
, 0, 0, scale_factor
,
2813 offset_x
, offset_y
);
2816 void PDFiumEngine::DrawPageShadow(const pp::Rect
& page_rc
,
2817 const pp::Rect
& shadow_rc
,
2818 const pp::Rect
& clip_rc
,
2819 pp::ImageData
* image_data
) {
2820 pp::Rect
page_rect(page_rc
);
2821 page_rect
.Offset(page_offset_
);
2823 pp::Rect
shadow_rect(shadow_rc
);
2824 shadow_rect
.Offset(page_offset_
);
2826 pp::Rect
clip_rect(clip_rc
);
2827 clip_rect
.Offset(page_offset_
);
2829 // Page drop shadow parameters.
2830 const double factor
= 0.5;
2831 uint32 depth
= std::max(
2832 std::max(page_rect
.x() - shadow_rect
.x(),
2833 page_rect
.y() - shadow_rect
.y()),
2834 std::max(shadow_rect
.right() - page_rect
.right(),
2835 shadow_rect
.bottom() - page_rect
.bottom()));
2836 depth
= static_cast<uint32
>(depth
* 1.5) + 1;
2838 // We need to check depth only to verify our copy of shadow matrix is correct.
2839 if (!page_shadow_
.get() || page_shadow_
->depth() != depth
)
2840 page_shadow_
.reset(new ShadowMatrix(depth
, factor
, kBackgroundColor
));
2842 DCHECK(!image_data
->is_null());
2843 DrawShadow(image_data
, shadow_rect
, page_rect
, clip_rect
, *page_shadow_
);
2846 void PDFiumEngine::GetRegion(const pp::Point
& location
,
2847 pp::ImageData
* image_data
,
2849 int* stride
) const {
2850 if (image_data
->is_null()) {
2851 DCHECK(plugin_size_
.IsEmpty());
2856 char* buffer
= static_cast<char*>(image_data
->data());
2857 *stride
= image_data
->stride();
2859 pp::Point offset_location
= location
+ page_offset_
;
2860 // TODO: update this when we support BIDI and scrollbars can be on the left.
2862 !pp::Rect(page_offset_
, plugin_size_
).Contains(offset_location
)) {
2867 buffer
+= location
.y() * (*stride
);
2868 buffer
+= (location
.x() + page_offset_
.x()) * 4;
2872 void PDFiumEngine::OnSelectionChanged() {
2873 if (HasPermission(PDFEngine::PERMISSION_COPY
))
2874 pp::PDF::SetSelectedText(GetPluginInstance(), GetSelectedText().c_str());
2877 void PDFiumEngine::Form_Invalidate(FPDF_FORMFILLINFO
* param
,
2883 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
2884 int page_index
= engine
->GetVisiblePageIndex(page
);
2885 if (page_index
== -1) {
2886 // This can sometime happen when the page is closed because it went off
2887 // screen, and PDFium invalidates the control as it's being deleted.
2891 pp::Rect rect
= engine
->pages_
[page_index
]->PageToScreen(
2892 engine
->GetVisibleRect().point(), engine
->current_zoom_
, left
, top
, right
,
2893 bottom
, engine
->current_rotation_
);
2894 engine
->client_
->Invalidate(rect
);
2897 void PDFiumEngine::Form_OutputSelectedRect(FPDF_FORMFILLINFO
* param
,
2903 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
2904 int page_index
= engine
->GetVisiblePageIndex(page
);
2905 if (page_index
== -1) {
2909 pp::Rect rect
= engine
->pages_
[page_index
]->PageToScreen(
2910 engine
->GetVisibleRect().point(), engine
->current_zoom_
, left
, top
, right
,
2911 bottom
, engine
->current_rotation_
);
2912 engine
->form_highlights_
.push_back(rect
);
2915 void PDFiumEngine::Form_SetCursor(FPDF_FORMFILLINFO
* param
, int cursor_type
) {
2916 // We don't need this since it's not enough to change the cursor in all
2917 // scenarios. Instead, we check which form field we're under in OnMouseMove.
2920 int PDFiumEngine::Form_SetTimer(FPDF_FORMFILLINFO
* param
,
2922 TimerCallback timer_func
) {
2923 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
2924 engine
->timers_
[++engine
->next_timer_id_
] =
2925 std::pair
<int, TimerCallback
>(elapse
, timer_func
);
2926 engine
->client_
->ScheduleCallback(engine
->next_timer_id_
, elapse
);
2927 return engine
->next_timer_id_
;
2930 void PDFiumEngine::Form_KillTimer(FPDF_FORMFILLINFO
* param
, int timer_id
) {
2931 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
2932 engine
->timers_
.erase(timer_id
);
2935 FPDF_SYSTEMTIME
PDFiumEngine::Form_GetLocalTime(FPDF_FORMFILLINFO
* param
) {
2936 base::Time time
= base::Time::Now();
2937 base::Time::Exploded exploded
;
2938 time
.LocalExplode(&exploded
);
2941 rv
.wYear
= exploded
.year
;
2942 rv
.wMonth
= exploded
.month
;
2943 rv
.wDayOfWeek
= exploded
.day_of_week
;
2944 rv
.wDay
= exploded
.day_of_month
;
2945 rv
.wHour
= exploded
.hour
;
2946 rv
.wMinute
= exploded
.minute
;
2947 rv
.wSecond
= exploded
.second
;
2948 rv
.wMilliseconds
= exploded
.millisecond
;
2952 void PDFiumEngine::Form_OnChange(FPDF_FORMFILLINFO
* param
) {
2953 // Don't care about.
2956 FPDF_PAGE
PDFiumEngine::Form_GetPage(FPDF_FORMFILLINFO
* param
,
2957 FPDF_DOCUMENT document
,
2959 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
2960 if (page_index
< 0 || page_index
>= static_cast<int>(engine
->pages_
.size()))
2962 return engine
->pages_
[page_index
]->GetPage();
2965 FPDF_PAGE
PDFiumEngine::Form_GetCurrentPage(FPDF_FORMFILLINFO
* param
,
2966 FPDF_DOCUMENT document
) {
2967 // TODO(jam): find out what this is used for.
2968 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
2969 int index
= engine
->last_page_mouse_down_
;
2971 index
= engine
->GetMostVisiblePage();
2978 return engine
->pages_
[index
]->GetPage();
2981 int PDFiumEngine::Form_GetRotation(FPDF_FORMFILLINFO
* param
, FPDF_PAGE page
) {
2985 void PDFiumEngine::Form_ExecuteNamedAction(FPDF_FORMFILLINFO
* param
,
2986 FPDF_BYTESTRING named_action
) {
2987 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
2988 std::string
action(named_action
);
2989 if (action
== "Print") {
2990 engine
->client_
->Print();
2994 int index
= engine
->last_page_mouse_down_
;
2995 /* Don't try to calculate the most visible page if we don't have a left click
2996 before this event (this code originally copied Form_GetCurrentPage which of
2997 course needs to do that and which doesn't have recursion). This can end up
2998 causing infinite recursion. See http://crbug.com/240413 for more
2999 information. Either way, it's not necessary for the spec'd list of named
3002 index = engine->GetMostVisiblePage();
3007 // This is the only list of named actions per the spec (see 12.6.4.11). Adobe
3008 // Reader supports more, like FitWidth, but since they're not part of the spec
3009 // and we haven't got bugs about them, no need to now.
3010 if (action
== "NextPage") {
3011 engine
->client_
->ScrollToPage(index
+ 1);
3012 } else if (action
== "PrevPage") {
3013 engine
->client_
->ScrollToPage(index
- 1);
3014 } else if (action
== "FirstPage") {
3015 engine
->client_
->ScrollToPage(0);
3016 } else if (action
== "LastPage") {
3017 engine
->client_
->ScrollToPage(engine
->pages_
.size() - 1);
3021 void PDFiumEngine::Form_SetTextFieldFocus(FPDF_FORMFILLINFO
* param
,
3022 FPDF_WIDESTRING value
,
3023 FPDF_DWORD valueLen
,
3024 FPDF_BOOL is_focus
) {
3025 // Do nothing for now.
3026 // TODO(gene): use this signal to trigger OSK.
3029 void PDFiumEngine::Form_DoURIAction(FPDF_FORMFILLINFO
* param
,
3030 FPDF_BYTESTRING uri
) {
3031 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3032 engine
->client_
->NavigateTo(std::string(uri
), false);
3035 void PDFiumEngine::Form_DoGoToAction(FPDF_FORMFILLINFO
* param
,
3038 float* position_array
,
3039 int size_of_array
) {
3040 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3041 engine
->client_
->ScrollToPage(page_index
);
3044 int PDFiumEngine::Form_Alert(IPDF_JSPLATFORM
* param
,
3045 FPDF_WIDESTRING message
,
3046 FPDF_WIDESTRING title
,
3049 // See fpdfformfill.h for these values.
3052 ALERT_TYPE_OK_CANCEL
,
3054 ALERT_TYPE_YES_NO_CANCEL
3058 ALERT_RESULT_OK
= 1,
3059 ALERT_RESULT_CANCEL
,
3064 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3065 std::string message_str
=
3066 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(message
));
3067 if (type
== ALERT_TYPE_OK
) {
3068 engine
->client_
->Alert(message_str
);
3069 return ALERT_RESULT_OK
;
3072 bool rv
= engine
->client_
->Confirm(message_str
);
3073 if (type
== ALERT_TYPE_OK_CANCEL
)
3074 return rv
? ALERT_RESULT_OK
: ALERT_RESULT_CANCEL
;
3075 return rv
? ALERT_RESULT_YES
: ALERT_RESULT_NO
;
3078 void PDFiumEngine::Form_Beep(IPDF_JSPLATFORM
* param
, int type
) {
3079 // Beeps are annoying, and not possible using javascript, so ignore for now.
3082 int PDFiumEngine::Form_Response(IPDF_JSPLATFORM
* param
,
3083 FPDF_WIDESTRING question
,
3084 FPDF_WIDESTRING title
,
3085 FPDF_WIDESTRING default_response
,
3086 FPDF_WIDESTRING label
,
3090 std::string question_str
= base::UTF16ToUTF8(
3091 reinterpret_cast<const base::char16
*>(question
));
3092 std::string default_str
= base::UTF16ToUTF8(
3093 reinterpret_cast<const base::char16
*>(default_response
));
3095 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3096 std::string rv
= engine
->client_
->Prompt(question_str
, default_str
);
3097 base::string16 rv_16
= base::UTF8ToUTF16(rv
);
3098 int rv_bytes
= rv_16
.size() * sizeof(base::char16
);
3100 int bytes_to_copy
= rv_bytes
< length
? rv_bytes
: length
;
3101 memcpy(response
, rv_16
.c_str(), bytes_to_copy
);
3106 int PDFiumEngine::Form_GetFilePath(IPDF_JSPLATFORM
* param
,
3109 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3110 std::string rv
= engine
->client_
->GetURL();
3111 if (file_path
&& rv
.size() <= static_cast<size_t>(length
))
3112 memcpy(file_path
, rv
.c_str(), rv
.size());
3116 void PDFiumEngine::Form_Mail(IPDF_JSPLATFORM
* param
,
3121 FPDF_WIDESTRING subject
,
3123 FPDF_WIDESTRING bcc
,
3124 FPDF_WIDESTRING message
) {
3125 DCHECK(length
== 0); // Don't handle attachments; no way with mailto.
3126 std::string to_str
=
3127 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(to
));
3128 std::string cc_str
=
3129 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(cc
));
3130 std::string bcc_str
=
3131 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(bcc
));
3132 std::string subject_str
=
3133 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(subject
));
3134 std::string message_str
=
3135 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(message
));
3137 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3138 engine
->client_
->Email(to_str
, cc_str
, bcc_str
, subject_str
, message_str
);
3141 void PDFiumEngine::Form_Print(IPDF_JSPLATFORM
* param
,
3146 FPDF_BOOL shrink_to_fit
,
3147 FPDF_BOOL print_as_image
,
3149 FPDF_BOOL annotations
) {
3150 // No way to pass the extra information to the print dialog using JavaScript.
3151 // Just opening it is fine for now.
3152 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3153 engine
->client_
->Print();
3156 void PDFiumEngine::Form_SubmitForm(IPDF_JSPLATFORM
* param
,
3159 FPDF_WIDESTRING url
) {
3160 std::string url_str
=
3161 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(url
));
3162 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3163 engine
->client_
->SubmitForm(url_str
, form_data
, length
);
3166 void PDFiumEngine::Form_GotoPage(IPDF_JSPLATFORM
* param
,
3168 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3169 engine
->client_
->ScrollToPage(page_number
);
3172 int PDFiumEngine::Form_Browse(IPDF_JSPLATFORM
* param
,
3175 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3176 std::string path
= engine
->client_
->ShowFileSelectionDialog();
3177 if (path
.size() + 1 <= static_cast<size_t>(length
))
3178 memcpy(file_path
, &path
[0], path
.size() + 1);
3179 return path
.size() + 1;
3182 FPDF_BOOL
PDFiumEngine::Pause_NeedToPauseNow(IFSDK_PAUSE
* param
) {
3183 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3184 return (base::Time::Now() - engine
->last_progressive_start_time_
).
3185 InMilliseconds() > engine
->progressive_paint_timeout_
;
3188 ScopedUnsupportedFeature::ScopedUnsupportedFeature(PDFiumEngine
* engine
)
3189 : engine_(engine
), old_engine_(g_engine_for_unsupported
) {
3190 g_engine_for_unsupported
= engine_
;
3193 ScopedUnsupportedFeature::~ScopedUnsupportedFeature() {
3194 g_engine_for_unsupported
= old_engine_
;
3197 PDFEngineExports
* PDFEngineExports::Create() {
3198 return new PDFiumEngineExports
;
3203 int CalculatePosition(FPDF_PAGE page
,
3204 const PDFiumEngineExports::RenderingSettings
& settings
,
3206 int page_width
= static_cast<int>(
3207 FPDF_GetPageWidth(page
) * settings
.dpi_x
/ kPointsPerInch
);
3208 int page_height
= static_cast<int>(
3209 FPDF_GetPageHeight(page
) * settings
.dpi_y
/ kPointsPerInch
);
3211 // Start by assuming that we will draw exactly to the bounds rect
3213 *dest
= settings
.bounds
;
3215 int rotate
= 0; // normal orientation.
3217 // Auto-rotate landscape pages to print correctly.
3218 if (settings
.autorotate
&&
3219 (dest
->width() > dest
->height()) != (page_width
> page_height
)) {
3220 rotate
= 3; // 90 degrees counter-clockwise.
3221 std::swap(page_width
, page_height
);
3224 // See if we need to scale the output
3225 bool scale_to_bounds
= false;
3226 if (settings
.fit_to_bounds
&&
3227 ((page_width
> dest
->width()) || (page_height
> dest
->height()))) {
3228 scale_to_bounds
= true;
3229 } else if (settings
.stretch_to_bounds
&&
3230 ((page_width
< dest
->width()) || (page_height
< dest
->height()))) {
3231 scale_to_bounds
= true;
3234 if (scale_to_bounds
) {
3235 // If we need to maintain aspect ratio, calculate the actual width and
3237 if (settings
.keep_aspect_ratio
) {
3238 double scale_factor_x
= page_width
;
3239 scale_factor_x
/= dest
->width();
3240 double scale_factor_y
= page_height
;
3241 scale_factor_y
/= dest
->height();
3242 if (scale_factor_x
> scale_factor_y
) {
3243 dest
->set_height(page_height
/ scale_factor_x
);
3245 dest
->set_width(page_width
/ scale_factor_y
);
3249 // We are not scaling to bounds. Draw in the actual page size. If the
3250 // actual page size is larger than the bounds, the output will be
3252 dest
->set_width(page_width
);
3253 dest
->set_height(page_height
);
3256 if (settings
.center_in_bounds
) {
3257 pp::Point
offset((settings
.bounds
.width() - dest
->width()) / 2,
3258 (settings
.bounds
.height() - dest
->height()) / 2);
3259 dest
->Offset(offset
);
3267 bool PDFiumEngineExports::RenderPDFPageToDC(const void* pdf_buffer
,
3270 const RenderingSettings
& settings
,
3272 FPDF_DOCUMENT doc
= FPDF_LoadMemDocument(pdf_buffer
, buffer_size
, NULL
);
3275 FPDF_PAGE page
= FPDF_LoadPage(doc
, page_number
);
3277 FPDF_CloseDocument(doc
);
3280 RenderingSettings new_settings
= settings
;
3281 // calculate the page size
3282 if (new_settings
.dpi_x
== -1)
3283 new_settings
.dpi_x
= GetDeviceCaps(dc
, LOGPIXELSX
);
3284 if (new_settings
.dpi_y
== -1)
3285 new_settings
.dpi_y
= GetDeviceCaps(dc
, LOGPIXELSY
);
3288 int rotate
= CalculatePosition(page
, new_settings
, &dest
);
3290 int save_state
= SaveDC(dc
);
3291 // The caller wanted all drawing to happen within the bounds specified.
3292 // Based on scale calculations, our destination rect might be larger
3293 // than the bounds. Set the clip rect to the bounds.
3294 IntersectClipRect(dc
, settings
.bounds
.x(), settings
.bounds
.y(),
3295 settings
.bounds
.x() + settings
.bounds
.width(),
3296 settings
.bounds
.y() + settings
.bounds
.height());
3298 // A temporary hack. PDFs generated by Cairo (used by Chrome OS to generate
3299 // a PDF output from a webpage) result in very large metafiles and the
3300 // rendering using FPDF_RenderPage is incorrect. In this case, render as a
3301 // bitmap. Note that this code does not kick in for PDFs printed from Chrome
3302 // because in that case we create a temp PDF first before printing and this
3303 // temp PDF does not have a creator string that starts with "cairo".
3304 base::string16 creator
;
3305 size_t buffer_bytes
= FPDF_GetMetaText(doc
, "Creator", NULL
, 0);
3306 if (buffer_bytes
> 1) {
3307 FPDF_GetMetaText(doc
, "Creator", WriteInto(&creator
, buffer_bytes
),
3310 bool use_bitmap
= false;
3311 if (StartsWith(creator
, L
"cairo", false))
3314 // Another temporary hack. Some PDFs seems to render very slowly if
3315 // FPDF_RenderPage is directly used on a printer DC. I suspect it is
3316 // because of the code to talk Postscript directly to the printer if
3317 // the printer supports this. Need to discuss this with PDFium. For now,
3318 // render to a bitmap and then blit the bitmap to the DC if we have been
3319 // supplied a printer DC.
3320 int device_type
= GetDeviceCaps(dc
, TECHNOLOGY
);
3322 (device_type
== DT_RASPRINTER
) || (device_type
== DT_PLOTTER
)) {
3323 FPDF_BITMAP bitmap
= FPDFBitmap_Create(dest
.width(), dest
.height(),
3326 FPDFBitmap_FillRect(bitmap
, 0, 0, dest
.width(), dest
.height(), 0xFFFFFFFF);
3327 FPDF_RenderPageBitmap(
3328 bitmap
, page
, 0, 0, dest
.width(), dest
.height(), rotate
,
3329 FPDF_ANNOT
| FPDF_PRINTING
| FPDF_NO_CATCH
);
3330 int stride
= FPDFBitmap_GetStride(bitmap
);
3332 memset(&bmi
, 0, sizeof(bmi
));
3333 bmi
.bmiHeader
.biSize
= sizeof(BITMAPINFOHEADER
);
3334 bmi
.bmiHeader
.biWidth
= dest
.width();
3335 bmi
.bmiHeader
.biHeight
= -dest
.height(); // top-down image
3336 bmi
.bmiHeader
.biPlanes
= 1;
3337 bmi
.bmiHeader
.biBitCount
= 32;
3338 bmi
.bmiHeader
.biCompression
= BI_RGB
;
3339 bmi
.bmiHeader
.biSizeImage
= stride
* dest
.height();
3340 StretchDIBits(dc
, dest
.x(), dest
.y(), dest
.width(), dest
.height(),
3341 0, 0, dest
.width(), dest
.height(),
3342 FPDFBitmap_GetBuffer(bitmap
), &bmi
, DIB_RGB_COLORS
, SRCCOPY
);
3343 FPDFBitmap_Destroy(bitmap
);
3345 FPDF_RenderPage(dc
, page
, dest
.x(), dest
.y(), dest
.width(), dest
.height(),
3346 rotate
, FPDF_ANNOT
| FPDF_PRINTING
| FPDF_NO_CATCH
);
3348 RestoreDC(dc
, save_state
);
3349 FPDF_ClosePage(page
);
3350 FPDF_CloseDocument(doc
);
3355 bool PDFiumEngineExports::RenderPDFPageToBitmap(
3356 const void* pdf_buffer
,
3357 int pdf_buffer_size
,
3359 const RenderingSettings
& settings
,
3360 void* bitmap_buffer
) {
3361 FPDF_DOCUMENT doc
= FPDF_LoadMemDocument(pdf_buffer
, pdf_buffer_size
, NULL
);
3364 FPDF_PAGE page
= FPDF_LoadPage(doc
, page_number
);
3366 FPDF_CloseDocument(doc
);
3371 int rotate
= CalculatePosition(page
, settings
, &dest
);
3373 FPDF_BITMAP bitmap
=
3374 FPDFBitmap_CreateEx(settings
.bounds
.width(), settings
.bounds
.height(),
3375 FPDFBitmap_BGRA
, bitmap_buffer
,
3376 settings
.bounds
.width() * 4);
3378 FPDFBitmap_FillRect(bitmap
, 0, 0, settings
.bounds
.width(),
3379 settings
.bounds
.height(), 0xFFFFFFFF);
3380 // Shift top-left corner of bounds to (0, 0) if it's not there.
3381 dest
.set_point(dest
.point() - settings
.bounds
.point());
3382 FPDF_RenderPageBitmap(
3383 bitmap
, page
, dest
.x(), dest
.y(), dest
.width(), dest
.height(), rotate
,
3384 FPDF_ANNOT
| FPDF_PRINTING
| FPDF_NO_CATCH
);
3385 FPDFBitmap_Destroy(bitmap
);
3386 FPDF_ClosePage(page
);
3387 FPDF_CloseDocument(doc
);
3391 bool PDFiumEngineExports::GetPDFDocInfo(const void* pdf_buffer
,
3394 double* max_page_width
) {
3395 FPDF_DOCUMENT doc
= FPDF_LoadMemDocument(pdf_buffer
, buffer_size
, NULL
);
3398 int page_count_local
= FPDF_GetPageCount(doc
);
3400 *page_count
= page_count_local
;
3402 if (max_page_width
) {
3403 *max_page_width
= 0;
3404 for (int page_number
= 0; page_number
< page_count_local
; page_number
++) {
3405 double page_width
= 0;
3406 double page_height
= 0;
3407 FPDF_GetPageSizeByIndex(doc
, page_number
, &page_width
, &page_height
);
3408 if (page_width
> *max_page_width
) {
3409 *max_page_width
= page_width
;
3413 FPDF_CloseDocument(doc
);
3417 bool PDFiumEngineExports::GetPDFPageSizeByIndex(
3418 const void* pdf_buffer
,
3419 int pdf_buffer_size
,
3423 FPDF_DOCUMENT doc
= FPDF_LoadMemDocument(pdf_buffer
, pdf_buffer_size
, NULL
);
3426 bool success
= FPDF_GetPageSizeByIndex(doc
, page_number
, width
, height
) != 0;
3427 FPDF_CloseDocument(doc
);
3431 } // namespace chrome_pdf