1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "pdf/pdfium/pdfium_engine.h"
9 #include "base/json/json_writer.h"
10 #include "base/logging.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/stl_util.h"
13 #include "base/strings/string_number_conversions.h"
14 #include "base/strings/string_piece.h"
15 #include "base/strings/string_util.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "base/values.h"
18 #include "pdf/draw_utils.h"
19 #include "pdf/pdfium/pdfium_mem_buffer_file_read.h"
20 #include "pdf/pdfium/pdfium_mem_buffer_file_write.h"
21 #include "ppapi/c/pp_errors.h"
22 #include "ppapi/c/pp_input_event.h"
23 #include "ppapi/c/ppb_core.h"
24 #include "ppapi/c/private/ppb_pdf.h"
25 #include "ppapi/cpp/dev/memory_dev.h"
26 #include "ppapi/cpp/input_event.h"
27 #include "ppapi/cpp/instance.h"
28 #include "ppapi/cpp/module.h"
29 #include "ppapi/cpp/private/pdf.h"
30 #include "ppapi/cpp/trusted/browser_font_trusted.h"
31 #include "ppapi/cpp/url_response_info.h"
32 #include "ppapi/cpp/var.h"
33 #include "third_party/pdfium/fpdfsdk/include/fpdf_ext.h"
34 #include "third_party/pdfium/fpdfsdk/include/fpdf_flatten.h"
35 #include "third_party/pdfium/fpdfsdk/include/fpdf_searchex.h"
36 #include "third_party/pdfium/fpdfsdk/include/fpdf_sysfontinfo.h"
37 #include "third_party/pdfium/fpdfsdk/include/fpdf_transformpage.h"
38 #include "third_party/pdfium/fpdfsdk/include/fpdfedit.h"
39 #include "third_party/pdfium/fpdfsdk/include/fpdfoom.h"
40 #include "third_party/pdfium/fpdfsdk/include/fpdfppo.h"
41 #include "third_party/pdfium/fpdfsdk/include/fpdfsave.h"
42 #include "third_party/pdfium/fpdfsdk/include/pdfwindow/PDFWindow.h"
43 #include "third_party/pdfium/fpdfsdk/include/pdfwindow/PWL_FontMap.h"
44 #include "ui/events/keycodes/keyboard_codes.h"
46 namespace chrome_pdf
{
48 #define kPageShadowTop 3
49 #define kPageShadowBottom 7
50 #define kPageShadowLeft 5
51 #define kPageShadowRight 5
53 #define kPageSeparatorThickness 4
54 #define kHighlightColorR 153
55 #define kHighlightColorG 193
56 #define kHighlightColorB 218
58 #define kPendingPageColorR 238
59 #define kPendingPageColorG 238
60 #define kPendingPageColorB 238
61 #define kPendingPageColorA 255
63 #define kFormHighlightColor 0xFFE4DD
64 #define kFormHighlightAlpha 100
66 #define kMaxPasswordTries 3
69 // http://www.adobe.com/devnet/acrobat/pdfs/pdf_reference_1-7.pdf
70 #define kPDFPermissionPrintLowQualityMask 1 << 2
71 #define kPDFPermissionPrintHighQualityMask 1 << 11
72 #define kPDFPermissionCopyMask 1 << 4
73 #define kPDFPermissionCopyAccessibleMask 1 << 9
75 #define kLoadingTextVerticalOffset 50
77 // The maximum amount of time we'll spend doing a paint before we give back
78 // control of the thread.
79 #define kMaxProgressivePaintTimeMs 50
81 // The maximum amount of time we'll spend doing the first paint. This is less
82 // than the above to keep things smooth if the user is scrolling quickly. We
83 // try painting a little because with accelerated compositing, we get flushes
84 // only every 16 ms. If we were to wait until the next flush to paint the rest
85 // of the pdf, we would never get to draw the pdf and would only draw the
86 // scrollbars. This value is picked to give enough time for gpu related code to
87 // do its thing and still fit within the timelimit for 60Hz. For the
88 // non-composited case, this doesn't make things worse since we're still
89 // painting the scrollbars > 60 Hz.
90 #define kMaxInitialProgressivePaintTimeMs 10
92 // Copied from printing/units.cc because we don't want to depend on printing
93 // since it brings in libpng which causes duplicate symbols with PDFium.
94 const int kPointsPerInch
= 72;
95 const int kPixelsPerInch
= 96;
104 int ConvertUnit(int value
, int old_unit
, int new_unit
) {
105 // With integer arithmetic, to divide a value with correct rounding, you need
106 // to add half of the divisor value to the dividend value. You need to do the
107 // reverse with negative number.
109 return ((value
* new_unit
) + (old_unit
/ 2)) / old_unit
;
111 return ((value
* new_unit
) - (old_unit
/ 2)) / old_unit
;
115 std::vector
<uint32_t> GetPageNumbersFromPrintPageNumberRange(
116 const PP_PrintPageNumberRange_Dev
* page_ranges
,
117 uint32_t page_range_count
) {
118 std::vector
<uint32_t> page_numbers
;
119 for (uint32_t index
= 0; index
< page_range_count
; ++index
) {
120 for (uint32_t page_number
= page_ranges
[index
].first_page_number
;
121 page_number
<= page_ranges
[index
].last_page_number
; ++page_number
) {
122 page_numbers
.push_back(page_number
);
128 #if defined(OS_LINUX)
130 PP_Instance g_last_instance_id
;
132 struct PDFFontSubstitution
{
133 const char* pdf_name
;
139 // This list is for CPWL_FontMap::GetDefaultFontByCharset().
140 // We pretend to have these font natively and let the browser (or underlying
141 // fontconfig) to pick the proper font on the system.
142 void EnumFonts(struct _FPDF_SYSFONTINFO
* sysfontinfo
, void* mapper
) {
143 FPDF_AddInstalledFont(mapper
, "Arial", FXFONT_DEFAULT_CHARSET
);
146 while (CPWL_FontMap::defaultTTFMap
[i
].charset
!= -1) {
147 FPDF_AddInstalledFont(mapper
,
148 CPWL_FontMap::defaultTTFMap
[i
].fontname
,
149 CPWL_FontMap::defaultTTFMap
[i
].charset
);
154 const PDFFontSubstitution PDFFontSubstitutions
[] = {
155 {"Courier", "Courier New", false, false},
156 {"Courier-Bold", "Courier New", true, false},
157 {"Courier-BoldOblique", "Courier New", true, true},
158 {"Courier-Oblique", "Courier New", false, true},
159 {"Helvetica", "Arial", false, false},
160 {"Helvetica-Bold", "Arial", true, false},
161 {"Helvetica-BoldOblique", "Arial", true, true},
162 {"Helvetica-Oblique", "Arial", false, true},
163 {"Times-Roman", "Times New Roman", false, false},
164 {"Times-Bold", "Times New Roman", true, false},
165 {"Times-BoldItalic", "Times New Roman", true, true},
166 {"Times-Italic", "Times New Roman", false, true},
168 // MS P?(Mincho|Gothic) are the most notable fonts in Japanese PDF files
169 // without embedding the glyphs. Sometimes the font names are encoded
170 // in Japanese Windows's locale (CP932/Shift_JIS) without space.
171 // Most Linux systems don't have the exact font, but for outsourcing
172 // fontconfig to find substitutable font in the system, we pass ASCII
174 {"MS-PGothic", "MS PGothic", false, false},
175 {"MS-Gothic", "MS Gothic", false, false},
176 {"MS-PMincho", "MS PMincho", false, false},
177 {"MS-Mincho", "MS Mincho", false, false},
178 // MS PGothic in Shift_JIS encoding.
179 {"\x82\x6C\x82\x72\x82\x6F\x83\x53\x83\x56\x83\x62\x83\x4E",
180 "MS PGothic", false, false},
181 // MS Gothic in Shift_JIS encoding.
182 {"\x82\x6C\x82\x72\x83\x53\x83\x56\x83\x62\x83\x4E",
183 "MS Gothic", false, false},
184 // MS PMincho in Shift_JIS encoding.
185 {"\x82\x6C\x82\x72\x82\x6F\x96\xBE\x92\xA9",
186 "MS PMincho", false, false},
187 // MS Mincho in Shift_JIS encoding.
188 {"\x82\x6C\x82\x72\x96\xBE\x92\xA9",
189 "MS Mincho", false, false},
192 void* MapFont(struct _FPDF_SYSFONTINFO
*, int weight
, int italic
,
193 int charset
, int pitch_family
, const char* face
, int* exact
) {
194 pp::BrowserFontDescription description
;
196 // Pretend the system does not have the Symbol font to force a fallback to
197 // the built in Symbol font in CFX_FontMapper::FindSubstFont().
198 if (strcmp(face
, "Symbol") == 0)
201 if (pitch_family
& FXFONT_FF_FIXEDPITCH
) {
202 description
.set_family(PP_BROWSERFONT_TRUSTED_FAMILY_MONOSPACE
);
203 } else if (pitch_family
& FXFONT_FF_ROMAN
) {
204 description
.set_family(PP_BROWSERFONT_TRUSTED_FAMILY_SERIF
);
207 // Map from the standard PDF fonts to TrueType font names.
209 for (i
= 0; i
< arraysize(PDFFontSubstitutions
); ++i
) {
210 if (strcmp(face
, PDFFontSubstitutions
[i
].pdf_name
) == 0) {
211 description
.set_face(PDFFontSubstitutions
[i
].face
);
212 if (PDFFontSubstitutions
[i
].bold
)
213 description
.set_weight(PP_BROWSERFONT_TRUSTED_WEIGHT_BOLD
);
214 if (PDFFontSubstitutions
[i
].italic
)
215 description
.set_italic(true);
220 if (i
== arraysize(PDFFontSubstitutions
)) {
221 // TODO(kochi): Pass the face in UTF-8. If face is not encoded in UTF-8,
222 // convert to UTF-8 before passing.
223 description
.set_face(face
);
226 if (!pp::PDF::IsAvailable()) {
231 PP_Resource font_resource
= pp::PDF::GetFontFileWithFallback(
232 pp::InstanceHandle(g_last_instance_id
),
233 &description
.pp_font_description(),
234 static_cast<PP_PrivateFontCharset
>(charset
));
235 long res_id
= font_resource
;
236 return reinterpret_cast<void*>(res_id
);
239 unsigned long GetFontData(struct _FPDF_SYSFONTINFO
*, void* font_id
,
240 unsigned int table
, unsigned char* buffer
,
241 unsigned long buf_size
) {
242 if (!pp::PDF::IsAvailable()) {
247 uint32_t size
= buf_size
;
248 long res_id
= reinterpret_cast<long>(font_id
);
249 if (!pp::PDF::GetFontTableForPrivateFontFile(res_id
, table
, buffer
, &size
))
254 void DeleteFont(struct _FPDF_SYSFONTINFO
*, void* font_id
) {
255 long res_id
= reinterpret_cast<long>(font_id
);
256 pp::Module::Get()->core()->ReleaseResource(res_id
);
259 FPDF_SYSFONTINFO g_font_info
= {
270 #endif // defined(OS_LINUX)
272 void OOM_Handler(_OOM_INFO
*) {
273 // Kill the process. This is important for security, since the code doesn't
274 // NULL-check many memory allocations. If a malloc fails, returns NULL, and
275 // the buffer is then used, it provides a handy mapping of memory starting at
276 // address 0 for an attacker to utilize.
280 OOM_INFO g_oom_info
= {
285 PDFiumEngine
* g_engine_for_unsupported
;
287 void Unsupported_Handler(UNSUPPORT_INFO
*, int type
) {
288 if (!g_engine_for_unsupported
) {
293 g_engine_for_unsupported
->UnsupportedFeature(type
);
296 UNSUPPORT_INFO g_unsuppored_info
= {
301 // Set the destination page size and content area in points based on source
302 // page rotation and orientation.
304 // |rotated| True if source page is rotated 90 degree or 270 degree.
305 // |is_src_page_landscape| is true if the source page orientation is landscape.
306 // |page_size| has the actual destination page size in points.
307 // |content_rect| has the actual destination page printable area values in
309 void SetPageSizeAndContentRect(bool rotated
,
310 bool is_src_page_landscape
,
312 pp::Rect
* content_rect
) {
313 bool is_dst_page_landscape
= page_size
->width() > page_size
->height();
314 bool page_orientation_mismatched
= is_src_page_landscape
!=
315 is_dst_page_landscape
;
316 bool rotate_dst_page
= rotated
^ page_orientation_mismatched
;
317 if (rotate_dst_page
) {
318 page_size
->SetSize(page_size
->height(), page_size
->width());
319 content_rect
->SetRect(content_rect
->y(), content_rect
->x(),
320 content_rect
->height(), content_rect
->width());
324 // Calculate the scale factor between |content_rect| and a page of size
325 // |src_width| x |src_height|.
327 // |scale_to_fit| is true, if we need to calculate the scale factor.
328 // |content_rect| specifies the printable area of the destination page, with
329 // origin at left-bottom. Values are in points.
330 // |src_width| specifies the source page width in points.
331 // |src_height| specifies the source page height in points.
332 // |rotated| True if source page is rotated 90 degree or 270 degree.
333 double CalculateScaleFactor(bool scale_to_fit
,
334 const pp::Rect
& content_rect
,
335 double src_width
, double src_height
, bool rotated
) {
336 if (!scale_to_fit
|| src_width
== 0 || src_height
== 0)
339 double actual_source_page_width
= rotated
? src_height
: src_width
;
340 double actual_source_page_height
= rotated
? src_width
: src_height
;
341 double ratio_x
= static_cast<double>(content_rect
.width()) /
342 actual_source_page_width
;
343 double ratio_y
= static_cast<double>(content_rect
.height()) /
344 actual_source_page_height
;
345 return std::min(ratio_x
, ratio_y
);
348 // Compute source clip box boundaries based on the crop box / media box of
349 // source page and scale factor.
351 // |page| Handle to the source page. Returned by FPDF_LoadPage function.
352 // |scale_factor| specifies the scale factor that should be applied to source
353 // clip box boundaries.
354 // |rotated| True if source page is rotated 90 degree or 270 degree.
355 // |clip_box| out param to hold the computed source clip box values.
356 void CalculateClipBoxBoundary(FPDF_PAGE page
, double scale_factor
, bool rotated
,
358 if (!FPDFPage_GetCropBox(page
, &clip_box
->left
, &clip_box
->bottom
,
359 &clip_box
->right
, &clip_box
->top
)) {
360 if (!FPDFPage_GetMediaBox(page
, &clip_box
->left
, &clip_box
->bottom
,
361 &clip_box
->right
, &clip_box
->top
)) {
362 // Make the default size to be letter size (8.5" X 11"). We are just
363 // following the PDFium way of handling these corner cases. PDFium always
364 // consider US-Letter as the default page size.
365 float paper_width
= 612;
366 float paper_height
= 792;
368 clip_box
->bottom
= 0;
369 clip_box
->right
= rotated
? paper_height
: paper_width
;
370 clip_box
->top
= rotated
? paper_width
: paper_height
;
373 clip_box
->left
*= scale_factor
;
374 clip_box
->right
*= scale_factor
;
375 clip_box
->bottom
*= scale_factor
;
376 clip_box
->top
*= scale_factor
;
379 // Calculate the clip box translation offset for a page that does need to be
380 // scaled. All parameters are in points.
382 // |content_rect| specifies the printable area of the destination page, with
383 // origin at left-bottom.
384 // |source_clip_box| specifies the source clip box positions, relative to
385 // origin at left-bottom.
386 // |offset_x| and |offset_y| will contain the final translation offsets for the
387 // source clip box, relative to origin at left-bottom.
388 void CalculateScaledClipBoxOffset(const pp::Rect
& content_rect
,
389 const ClipBox
& source_clip_box
,
390 double* offset_x
, double* offset_y
) {
391 const float clip_box_width
= source_clip_box
.right
- source_clip_box
.left
;
392 const float clip_box_height
= source_clip_box
.top
- source_clip_box
.bottom
;
394 // Center the intended clip region to real clip region.
395 *offset_x
= (content_rect
.width() - clip_box_width
) / 2 + content_rect
.x() -
396 source_clip_box
.left
;
397 *offset_y
= (content_rect
.height() - clip_box_height
) / 2 + content_rect
.y() -
398 source_clip_box
.bottom
;
401 // Calculate the clip box offset for a page that does not need to be scaled.
402 // All parameters are in points.
404 // |content_rect| specifies the printable area of the destination page, with
405 // origin at left-bottom.
406 // |rotation| specifies the source page rotation values which are N / 90
408 // |page_width| specifies the screen destination page width.
409 // |page_height| specifies the screen destination page height.
410 // |source_clip_box| specifies the source clip box positions, relative to origin
412 // |offset_x| and |offset_y| will contain the final translation offsets for the
413 // source clip box, relative to origin at left-bottom.
414 void CalculateNonScaledClipBoxOffset(const pp::Rect
& content_rect
, int rotation
,
415 int page_width
, int page_height
,
416 const ClipBox
& source_clip_box
,
417 double* offset_x
, double* offset_y
) {
418 // Align the intended clip region to left-top corner of real clip region.
421 *offset_x
= -1 * source_clip_box
.left
;
422 *offset_y
= page_height
- source_clip_box
.top
;
426 *offset_y
= -1 * source_clip_box
.bottom
;
429 *offset_x
= page_width
- source_clip_box
.right
;
433 *offset_x
= page_height
- source_clip_box
.right
;
434 *offset_y
= page_width
- source_clip_box
.top
;
442 // Do an in-place transformation of objects on |page|. Translate all objects on
443 // |page| in |source_clip_box| by (|offset_x|, |offset_y|) and scale them by
446 // |page| Handle to the page. Returned by FPDF_LoadPage function.
447 // |source_clip_box| specifies the source clip box positions, relative to
448 // origin at left-bottom.
449 // |scale_factor| specifies the scale factor that should be applied to page
451 // |offset_x| and |offset_y| specifies the translation offsets for the page
452 // objects, relative to origin at left-bottom.
454 void TransformPageObjects(FPDF_PAGE page
, const ClipBox
& source_clip_box
,
455 const double scale_factor
, double offset_x
,
457 const int obj_count
= FPDFPage_CountObject(page
);
459 // Create a new clip path.
460 FPDF_CLIPPATH clip_path
= FPDF_CreateClipPath(
461 source_clip_box
.left
+ offset_x
, source_clip_box
.bottom
+ offset_y
,
462 source_clip_box
.right
+ offset_x
, source_clip_box
.top
+ offset_y
);
464 for (int obj_idx
= 0; obj_idx
< obj_count
; ++obj_idx
) {
465 FPDF_PAGEOBJECT page_obj
= FPDFPage_GetObject(page
, obj_idx
);
466 FPDFPageObj_Transform(page_obj
, scale_factor
, 0, 0, scale_factor
,
468 FPDFPageObj_TransformClipPath(page_obj
, scale_factor
, 0, 0, scale_factor
,
471 FPDFPage_TransformAnnots(page
, scale_factor
, 0, 0, scale_factor
,
473 FPDFPage_GenerateContent(page
);
475 // Add a extra clip path to the new pdf page here.
476 FPDFPage_InsertClipPath(page
, clip_path
);
478 // Destroy the clip path.
479 FPDF_DestroyClipPath(clip_path
);
482 bool InitializeSDK(void* data
) {
483 FPDF_InitLibrary(data
);
485 #if defined(OS_LINUX)
486 // Font loading doesn't work in the renderer sandbox in Linux.
487 FPDF_SetSystemFontInfo(&g_font_info
);
490 FSDK_SetOOMHandler(&g_oom_info
);
491 FSDK_SetUnSpObjProcessHandler(&g_unsuppored_info
);
497 FPDF_DestroyLibrary();
500 PDFEngine
* PDFEngine::Create(PDFEngine::Client
* client
) {
501 return new PDFiumEngine(client
);
504 PDFiumEngine::PDFiumEngine(PDFEngine::Client
* client
)
507 current_rotation_(0),
509 password_tries_remaining_(0),
512 defer_page_unload_(false),
514 next_page_to_search_(-1),
515 last_page_to_search_(-1),
516 last_character_index_to_search_(-1),
517 current_find_index_(-1),
519 fpdf_availability_(NULL
),
521 last_page_mouse_down_(-1),
522 first_visible_page_(-1),
523 most_visible_page_(-1),
524 called_do_document_action_(false),
525 render_grayscale_(false),
526 progressive_paint_timeout_(0),
527 getting_password_(false) {
528 find_factory_
.Initialize(this);
529 password_factory_
.Initialize(this);
531 file_access_
.m_FileLen
= 0;
532 file_access_
.m_GetBlock
= &GetBlock
;
533 file_access_
.m_Param
= &doc_loader_
;
535 file_availability_
.version
= 1;
536 file_availability_
.IsDataAvail
= &IsDataAvail
;
537 file_availability_
.loader
= &doc_loader_
;
539 download_hints_
.version
= 1;
540 download_hints_
.AddSegment
= &AddSegment
;
541 download_hints_
.loader
= &doc_loader_
;
543 // Initialize FPDF_FORMFILLINFO member variables. Deriving from this struct
544 // allows the static callbacks to be able to cast the FPDF_FORMFILLINFO in
545 // callbacks to ourself instead of maintaining a map of them to
547 FPDF_FORMFILLINFO::version
= 1;
548 FPDF_FORMFILLINFO::m_pJsPlatform
= this;
549 FPDF_FORMFILLINFO::Release
= NULL
;
550 FPDF_FORMFILLINFO::FFI_Invalidate
= Form_Invalidate
;
551 FPDF_FORMFILLINFO::FFI_OutputSelectedRect
= Form_OutputSelectedRect
;
552 FPDF_FORMFILLINFO::FFI_SetCursor
= Form_SetCursor
;
553 FPDF_FORMFILLINFO::FFI_SetTimer
= Form_SetTimer
;
554 FPDF_FORMFILLINFO::FFI_KillTimer
= Form_KillTimer
;
555 FPDF_FORMFILLINFO::FFI_GetLocalTime
= Form_GetLocalTime
;
556 FPDF_FORMFILLINFO::FFI_OnChange
= Form_OnChange
;
557 FPDF_FORMFILLINFO::FFI_GetPage
= Form_GetPage
;
558 FPDF_FORMFILLINFO::FFI_GetCurrentPage
= Form_GetCurrentPage
;
559 FPDF_FORMFILLINFO::FFI_GetRotation
= Form_GetRotation
;
560 FPDF_FORMFILLINFO::FFI_ExecuteNamedAction
= Form_ExecuteNamedAction
;
561 FPDF_FORMFILLINFO::FFI_SetTextFieldFocus
= Form_SetTextFieldFocus
;
562 FPDF_FORMFILLINFO::FFI_DoURIAction
= Form_DoURIAction
;
563 FPDF_FORMFILLINFO::FFI_DoGoToAction
= Form_DoGoToAction
;
565 IPDF_JSPLATFORM::version
= 1;
566 IPDF_JSPLATFORM::app_alert
= Form_Alert
;
567 IPDF_JSPLATFORM::app_beep
= Form_Beep
;
568 IPDF_JSPLATFORM::app_response
= Form_Response
;
569 IPDF_JSPLATFORM::Doc_getFilePath
= Form_GetFilePath
;
570 IPDF_JSPLATFORM::Doc_mail
= Form_Mail
;
571 IPDF_JSPLATFORM::Doc_print
= Form_Print
;
572 IPDF_JSPLATFORM::Doc_submitForm
= Form_SubmitForm
;
573 IPDF_JSPLATFORM::Doc_gotoPage
= Form_GotoPage
;
574 IPDF_JSPLATFORM::Field_browse
= Form_Browse
;
576 IFSDK_PAUSE::version
= 1;
577 IFSDK_PAUSE::user
= NULL
;
578 IFSDK_PAUSE::NeedToPauseNow
= Pause_NeedToPauseNow
;
581 PDFiumEngine::~PDFiumEngine() {
582 STLDeleteElements(&pages_
);
585 FORM_DoDocumentAAction(form_
, FPDFDOC_AACTION_WC
);
586 FPDFDOC_ExitFormFillEnviroument(form_
);
588 FPDF_CloseDocument(doc_
);
591 if (fpdf_availability_
)
592 FPDFAvail_Destroy(fpdf_availability_
);
595 int PDFiumEngine::GetBlock(void* param
, unsigned long position
,
596 unsigned char* buffer
, unsigned long size
) {
597 DocumentLoader
* loader
= static_cast<DocumentLoader
*>(param
);
598 return loader
->GetBlock(position
, size
, buffer
);
601 bool PDFiumEngine::IsDataAvail(FX_FILEAVAIL
* param
,
602 size_t offset
, size_t size
) {
603 PDFiumEngine::FileAvail
* file_avail
=
604 static_cast<PDFiumEngine::FileAvail
*>(param
);
605 return file_avail
->loader
->IsDataAvailable(offset
, size
);
608 void PDFiumEngine::AddSegment(FX_DOWNLOADHINTS
* param
,
609 size_t offset
, size_t size
) {
610 PDFiumEngine::DownloadHints
* download_hints
=
611 static_cast<PDFiumEngine::DownloadHints
*>(param
);
612 return download_hints
->loader
->RequestData(offset
, size
);
615 bool PDFiumEngine::New(const char* url
) {
617 headers_
= std::string();
621 bool PDFiumEngine::New(const char* url
,
622 const char* headers
) {
625 headers_
= std::string();
631 void PDFiumEngine::PageOffsetUpdated(const pp::Point
& page_offset
) {
632 page_offset_
= page_offset
;
635 void PDFiumEngine::PluginSizeUpdated(const pp::Size
& size
) {
639 CalculateVisiblePages();
642 void PDFiumEngine::ScrolledToXPosition(int position
) {
645 int old_x
= position_
.x();
646 position_
.set_x(position
);
647 CalculateVisiblePages();
648 client_
->Scroll(pp::Point(old_x
- position
, 0));
651 void PDFiumEngine::ScrolledToYPosition(int position
) {
654 int old_y
= position_
.y();
655 position_
.set_y(position
);
656 CalculateVisiblePages();
657 client_
->Scroll(pp::Point(0, old_y
- position
));
660 void PDFiumEngine::PrePaint() {
661 for (size_t i
= 0; i
< progressive_paints_
.size(); ++i
)
662 progressive_paints_
[i
].painted_
= false;
665 void PDFiumEngine::Paint(const pp::Rect
& rect
,
666 pp::ImageData
* image_data
,
667 std::vector
<pp::Rect
>* ready
,
668 std::vector
<pp::Rect
>* pending
) {
669 pp::Rect leftover
= rect
;
670 for (size_t i
= 0; i
< visible_pages_
.size(); ++i
) {
671 int index
= visible_pages_
[i
];
672 pp::Rect page_rect
= pages_
[index
]->rect();
673 // Convert the current page's rectangle to screen rectangle. We do this
674 // instead of the reverse (converting the dirty rectangle from screen to
675 // page coordinates) because then we'd have to convert back to screen
676 // coordinates, and the rounding errors sometime leave pixels dirty or even
677 // move the text up or down a pixel when zoomed.
678 pp::Rect page_rect_in_screen
= GetPageScreenRect(index
);
679 pp::Rect dirty_in_screen
= page_rect_in_screen
.Intersect(leftover
);
680 if (dirty_in_screen
.IsEmpty())
683 leftover
= leftover
.Subtract(dirty_in_screen
);
685 if (pages_
[index
]->available()) {
686 int progressive
= GetProgressiveIndex(index
);
687 if (progressive
!= -1 &&
688 progressive_paints_
[progressive
].rect
!= dirty_in_screen
) {
689 // The PDFium code can only handle one progressive paint at a time, so
690 // queue this up. Previously we used to merge the rects when this
691 // happened, but it made scrolling up on complex PDFs very slow since
692 // there would be a damaged rect at the top (from scroll) and at the
693 // bottom (from toolbar).
694 pending
->push_back(dirty_in_screen
);
698 if (progressive
== -1) {
699 progressive
= StartPaint(index
, dirty_in_screen
);
700 progressive_paint_timeout_
= kMaxInitialProgressivePaintTimeMs
;
702 progressive_paint_timeout_
= kMaxProgressivePaintTimeMs
;
705 progressive_paints_
[progressive
].painted_
= true;
706 if (ContinuePaint(progressive
, image_data
)) {
707 FinishPaint(progressive
, image_data
);
708 ready
->push_back(dirty_in_screen
);
710 pending
->push_back(dirty_in_screen
);
713 PaintUnavailablePage(index
, dirty_in_screen
, image_data
);
714 ready
->push_back(dirty_in_screen
);
719 void PDFiumEngine::PostPaint() {
720 for (size_t i
= 0; i
< progressive_paints_
.size(); ++i
) {
721 if (progressive_paints_
[i
].painted_
)
724 // This rectangle must have been merged with another one, that's why we
725 // weren't asked to paint it. Remove it or otherwise we'll never finish
727 FPDF_RenderPage_Close(
728 pages_
[progressive_paints_
[i
].page_index
]->GetPage());
729 FPDFBitmap_Destroy(progressive_paints_
[i
].bitmap
);
730 progressive_paints_
.erase(progressive_paints_
.begin() + i
);
735 bool PDFiumEngine::HandleDocumentLoad(const pp::URLLoader
& loader
) {
736 password_tries_remaining_
= kMaxPasswordTries
;
737 return doc_loader_
.Init(loader
, url_
, headers_
);
740 pp::Instance
* PDFiumEngine::GetPluginInstance() {
741 return client_
->GetPluginInstance();
744 pp::URLLoader
PDFiumEngine::CreateURLLoader() {
745 return client_
->CreateURLLoader();
748 void PDFiumEngine::AppendPage(PDFEngine
* engine
, int index
) {
749 // Unload and delete the blank page before appending.
750 pages_
[index
]->Unload();
751 pages_
[index
]->set_calculated_links(false);
752 pp::Size curr_page_size
= GetPageSize(index
);
753 FPDFPage_Delete(doc_
, index
);
754 FPDF_ImportPages(doc_
,
755 static_cast<PDFiumEngine
*>(engine
)->doc(),
758 pp::Size new_page_size
= GetPageSize(index
);
759 if (curr_page_size
!= new_page_size
)
761 client_
->Invalidate(GetPageScreenRect(index
));
764 pp::Point
PDFiumEngine::GetScrollPosition() {
768 void PDFiumEngine::SetScrollPosition(const pp::Point
& position
) {
769 position_
= position
;
772 bool PDFiumEngine::IsProgressiveLoad() {
773 return doc_loader_
.is_partial_document();
776 void PDFiumEngine::OnPartialDocumentLoaded() {
777 file_access_
.m_FileLen
= doc_loader_
.document_size();
778 fpdf_availability_
= FPDFAvail_Create(&file_availability_
, &file_access_
);
779 DCHECK(fpdf_availability_
);
781 // Currently engine does not deal efficiently with some non-linearized files.
782 // See http://code.google.com/p/chromium/issues/detail?id=59400
783 // To improve user experience we download entire file for non-linearized PDF.
784 if (!FPDFAvail_IsLinearized(fpdf_availability_
)) {
785 doc_loader_
.RequestData(0, doc_loader_
.document_size());
792 void PDFiumEngine::OnPendingRequestComplete() {
793 if (!doc_
|| !form_
) {
798 // LoadDocument() will result in |pending_pages_| being reset so there's no
799 // need to run the code below in that case.
800 bool update_pages
= false;
801 std::vector
<int> still_pending
;
802 for (size_t i
= 0; i
< pending_pages_
.size(); ++i
) {
803 if (CheckPageAvailable(pending_pages_
[i
], &still_pending
)) {
805 if (IsPageVisible(pending_pages_
[i
]))
806 client_
->Invalidate(GetPageScreenRect(pending_pages_
[i
]));
809 pending_pages_
.swap(still_pending
);
814 void PDFiumEngine::OnNewDataAvailable() {
815 client_
->DocumentLoadProgress(doc_loader_
.GetAvailableData(),
816 doc_loader_
.document_size());
819 void PDFiumEngine::OnDocumentComplete() {
820 if (!doc_
|| !form_
) {
821 file_access_
.m_FileLen
= doc_loader_
.document_size();
826 bool need_update
= false;
827 for (size_t i
= 0; i
< pages_
.size(); ++i
) {
828 if (pages_
[i
]->available())
831 pages_
[i
]->set_available(true);
832 // We still need to call IsPageAvail() even if the whole document is
833 // already downloaded.
834 FPDFAvail_IsPageAvail(fpdf_availability_
, i
, &download_hints_
);
836 if (IsPageVisible(i
))
837 client_
->Invalidate(GetPageScreenRect(i
));
842 FinishLoadingDocument();
845 void PDFiumEngine::FinishLoadingDocument() {
846 DCHECK(doc_loader_
.IsDocumentComplete() && doc_
);
847 if (called_do_document_action_
)
849 called_do_document_action_
= true;
851 // These can only be called now, as the JS might end up needing a page.
852 FORM_DoDocumentJSAction(form_
);
853 FORM_DoDocumentOpenAction(form_
);
854 if (most_visible_page_
!= -1) {
855 FPDF_PAGE new_page
= pages_
[most_visible_page_
]->GetPage();
856 FORM_DoPageAAction(new_page
, form_
, FPDFPAGE_AACTION_OPEN
);
859 if (doc_
) // This can only happen if loading |doc_| fails.
860 client_
->DocumentLoadComplete(pages_
.size());
863 void PDFiumEngine::UnsupportedFeature(int type
) {
866 case FPDF_UNSP_DOC_XFAFORM
:
869 case FPDF_UNSP_DOC_PORTABLECOLLECTION
:
870 feature
= "Portfolios_Packages";
872 case FPDF_UNSP_DOC_ATTACHMENT
:
873 case FPDF_UNSP_ANNOT_ATTACHMENT
:
874 feature
= "Attachment";
876 case FPDF_UNSP_DOC_SECURITY
:
877 feature
= "Rights_Management";
879 case FPDF_UNSP_DOC_SHAREDREVIEW
:
880 feature
= "Shared_Review";
882 case FPDF_UNSP_DOC_SHAREDFORM_ACROBAT
:
883 case FPDF_UNSP_DOC_SHAREDFORM_FILESYSTEM
:
884 case FPDF_UNSP_DOC_SHAREDFORM_EMAIL
:
885 feature
= "Shared_Form";
887 case FPDF_UNSP_ANNOT_3DANNOT
:
890 case FPDF_UNSP_ANNOT_MOVIE
:
893 case FPDF_UNSP_ANNOT_SOUND
:
896 case FPDF_UNSP_ANNOT_SCREEN_MEDIA
:
897 case FPDF_UNSP_ANNOT_SCREEN_RICHMEDIA
:
900 case FPDF_UNSP_ANNOT_SIG
:
901 feature
= "Digital_Signature";
904 client_
->DocumentHasUnsupportedFeature(feature
);
907 void PDFiumEngine::ContinueFind(int32_t result
) {
908 StartFind(current_find_text_
.c_str(), !!result
);
911 bool PDFiumEngine::HandleEvent(const pp::InputEvent
& event
) {
912 DCHECK(!defer_page_unload_
);
913 defer_page_unload_
= true;
915 switch (event
.GetType()) {
916 case PP_INPUTEVENT_TYPE_MOUSEDOWN
:
917 rv
= OnMouseDown(pp::MouseInputEvent(event
));
919 case PP_INPUTEVENT_TYPE_MOUSEUP
:
920 rv
= OnMouseUp(pp::MouseInputEvent(event
));
922 case PP_INPUTEVENT_TYPE_MOUSEMOVE
:
923 rv
= OnMouseMove(pp::MouseInputEvent(event
));
925 case PP_INPUTEVENT_TYPE_KEYDOWN
:
926 rv
= OnKeyDown(pp::KeyboardInputEvent(event
));
928 case PP_INPUTEVENT_TYPE_KEYUP
:
929 rv
= OnKeyUp(pp::KeyboardInputEvent(event
));
931 case PP_INPUTEVENT_TYPE_CHAR
:
932 rv
= OnChar(pp::KeyboardInputEvent(event
));
938 DCHECK(defer_page_unload_
);
939 defer_page_unload_
= false;
940 for (size_t i
= 0; i
< deferred_page_unloads_
.size(); ++i
)
941 pages_
[deferred_page_unloads_
[i
]]->Unload();
942 deferred_page_unloads_
.clear();
946 uint32_t PDFiumEngine::QuerySupportedPrintOutputFormats() {
947 if (!HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
))
949 return PP_PRINTOUTPUTFORMAT_PDF
;
952 void PDFiumEngine::PrintBegin() {
953 FORM_DoDocumentAAction(form_
, FPDFDOC_AACTION_WP
);
956 pp::Resource
PDFiumEngine::PrintPages(
957 const PP_PrintPageNumberRange_Dev
* page_ranges
, uint32_t page_range_count
,
958 const PP_PrintSettings_Dev
& print_settings
) {
959 if (HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY
))
960 return PrintPagesAsPDF(page_ranges
, page_range_count
, print_settings
);
961 else if (HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
))
962 return PrintPagesAsRasterPDF(page_ranges
, page_range_count
, print_settings
);
963 return pp::Resource();
966 pp::Buffer_Dev
PDFiumEngine::PrintPagesAsRasterPDF(
967 const PP_PrintPageNumberRange_Dev
* page_ranges
, uint32_t page_range_count
,
968 const PP_PrintSettings_Dev
& print_settings
) {
969 if (!page_range_count
)
970 return pp::Buffer_Dev();
972 // If document is not downloaded yet, disable printing.
973 if (doc_
&& !doc_loader_
.IsDocumentComplete())
974 return pp::Buffer_Dev();
976 FPDF_DOCUMENT output_doc
= FPDF_CreateNewDocument();
978 return pp::Buffer_Dev();
980 SaveSelectedFormForPrint();
982 std::vector
<PDFiumPage
> pages_to_print
;
983 // width and height of source PDF pages.
984 std::vector
<std::pair
<double, double> > source_page_sizes
;
985 // Collect pages to print and sizes of source pages.
986 std::vector
<uint32_t> page_numbers
=
987 GetPageNumbersFromPrintPageNumberRange(page_ranges
, page_range_count
);
988 for (size_t i
= 0; i
< page_numbers
.size(); ++i
) {
989 uint32_t page_number
= page_numbers
[i
];
990 FPDF_PAGE pdf_page
= FPDF_LoadPage(doc_
, page_number
);
991 double source_page_width
= FPDF_GetPageWidth(pdf_page
);
992 double source_page_height
= FPDF_GetPageHeight(pdf_page
);
993 source_page_sizes
.push_back(std::make_pair(source_page_width
,
994 source_page_height
));
996 int width_in_pixels
= ConvertUnit(source_page_width
,
997 static_cast<int>(kPointsPerInch
),
999 int height_in_pixels
= ConvertUnit(source_page_height
,
1000 static_cast<int>(kPointsPerInch
),
1001 print_settings
.dpi
);
1003 pp::Rect
rect(width_in_pixels
, height_in_pixels
);
1004 pages_to_print
.push_back(PDFiumPage(this, page_number
, rect
, true));
1005 FPDF_ClosePage(pdf_page
);
1008 #if defined(OS_LINUX)
1009 g_last_instance_id
= client_
->GetPluginInstance()->pp_instance();
1013 for (; i
< pages_to_print
.size(); ++i
) {
1014 double source_page_width
= source_page_sizes
[i
].first
;
1015 double source_page_height
= source_page_sizes
[i
].second
;
1016 const pp::Size
& bitmap_size(pages_to_print
[i
].rect().size());
1018 // Use temp_doc to compress image by saving PDF to buffer.
1019 FPDF_DOCUMENT temp_doc
= FPDF_CreateNewDocument();
1023 FPDF_PAGE output_page
= FPDFPage_New(temp_doc
, 0, source_page_width
,
1024 source_page_height
);
1026 pp::ImageData image
= pp::ImageData(client_
->GetPluginInstance(),
1027 PP_IMAGEDATAFORMAT_BGRA_PREMUL
,
1031 FPDF_BITMAP bitmap
= FPDFBitmap_CreateEx(bitmap_size
.width(),
1032 bitmap_size
.height(),
1038 FPDFBitmap_FillRect(bitmap
, 0, 0, bitmap_size
.width(),
1039 bitmap_size
.height(), 255, 255, 255, 255);
1041 pp::Rect page_rect
= pages_to_print
[i
].rect();
1042 FPDF_RenderPageBitmap(bitmap
, pages_to_print
[i
].GetPrintPage(),
1043 page_rect
.x(), page_rect
.y(),
1044 page_rect
.width(), page_rect
.height(),
1045 print_settings
.orientation
,
1046 FPDF_ANNOT
| FPDF_PRINTING
| FPDF_NO_CATCH
);
1048 double ratio_x
= (static_cast<double>(bitmap_size
.width()) *
1049 kPointsPerInch
) / print_settings
.dpi
;
1050 double ratio_y
= (static_cast<double>(bitmap_size
.height()) *
1051 kPointsPerInch
) / print_settings
.dpi
;
1053 // Add the bitmap to an image object and add the image object to the output
1055 FPDF_PAGEOBJECT img_obj
= FPDFPageObj_NewImgeObj(output_doc
);
1056 FPDFImageObj_SetBitmap(&output_page
, 1, img_obj
, bitmap
);
1057 FPDFImageObj_SetMatrix(img_obj
, ratio_x
, 0, 0, ratio_y
, 0, 0);
1058 FPDFPage_InsertObject(output_page
, img_obj
);
1059 FPDFPage_GenerateContent(output_page
);
1060 FPDF_ClosePage(output_page
);
1062 pages_to_print
[i
].ClosePrintPage();
1063 FPDFBitmap_Destroy(bitmap
);
1065 pp::Buffer_Dev buffer
= GetFlattenedPrintData(temp_doc
);
1066 FPDF_CloseDocument(temp_doc
);
1068 PDFiumMemBufferFileRead
file_read(buffer
.data(), buffer
.size());
1069 temp_doc
= FPDF_LoadCustomDocument(&file_read
, NULL
);
1073 FPDF_BOOL imported
= FPDF_ImportPages(output_doc
, temp_doc
, "1", i
);
1074 FPDF_CloseDocument(temp_doc
);
1079 pp::Buffer_Dev buffer
;
1080 if (i
== pages_to_print
.size()) {
1081 FPDF_CopyViewerPreferences(output_doc
, doc_
);
1082 FitContentsToPrintableAreaIfRequired(output_doc
, print_settings
);
1083 // Now flatten all the output pages.
1084 buffer
= GetFlattenedPrintData(output_doc
);
1086 FPDF_CloseDocument(output_doc
);
1090 pp::Buffer_Dev
PDFiumEngine::GetFlattenedPrintData(const FPDF_DOCUMENT
& doc
) {
1091 int page_count
= FPDF_GetPageCount(doc
);
1092 bool flatten_succeeded
= true;
1093 for (int i
= 0; i
< page_count
; ++i
) {
1094 FPDF_PAGE page
= FPDF_LoadPage(doc
, i
);
1097 int flatten_ret
= FPDFPage_Flatten(page
, FLAT_PRINT
);
1098 FPDF_ClosePage(page
);
1099 if (flatten_ret
== FLATTEN_FAIL
) {
1100 flatten_succeeded
= false;
1104 flatten_succeeded
= false;
1108 if (!flatten_succeeded
) {
1109 FPDF_CloseDocument(doc
);
1110 return pp::Buffer_Dev();
1113 pp::Buffer_Dev buffer
;
1114 PDFiumMemBufferFileWrite output_file_write
;
1115 if (FPDF_SaveAsCopy(doc
, &output_file_write
, 0)) {
1116 buffer
= pp::Buffer_Dev(
1117 client_
->GetPluginInstance(), output_file_write
.size());
1118 if (!buffer
.is_null()) {
1119 memcpy(buffer
.data(), output_file_write
.buffer().c_str(),
1120 output_file_write
.size());
1126 pp::Buffer_Dev
PDFiumEngine::PrintPagesAsPDF(
1127 const PP_PrintPageNumberRange_Dev
* page_ranges
, uint32_t page_range_count
,
1128 const PP_PrintSettings_Dev
& print_settings
) {
1129 if (!page_range_count
)
1130 return pp::Buffer_Dev();
1133 FPDF_DOCUMENT output_doc
= FPDF_CreateNewDocument();
1135 return pp::Buffer_Dev();
1137 SaveSelectedFormForPrint();
1139 std::string page_number_str
;
1140 for (uint32_t index
= 0; index
< page_range_count
; ++index
) {
1141 if (!page_number_str
.empty())
1142 page_number_str
.append(",");
1143 page_number_str
.append(
1144 base::IntToString(page_ranges
[index
].first_page_number
+ 1));
1145 if (page_ranges
[index
].first_page_number
!=
1146 page_ranges
[index
].last_page_number
) {
1147 page_number_str
.append("-");
1148 page_number_str
.append(
1149 base::IntToString(page_ranges
[index
].last_page_number
+ 1));
1153 std::vector
<uint32_t> page_numbers
=
1154 GetPageNumbersFromPrintPageNumberRange(page_ranges
, page_range_count
);
1155 for (size_t i
= 0; i
< page_numbers
.size(); ++i
) {
1156 uint32_t page_number
= page_numbers
[i
];
1157 pages_
[page_number
]->GetPage();
1158 if (!IsPageVisible(page_numbers
[i
]))
1159 pages_
[page_number
]->Unload();
1162 FPDF_CopyViewerPreferences(output_doc
, doc_
);
1163 if (!FPDF_ImportPages(output_doc
, doc_
, page_number_str
.c_str(), 0)) {
1164 FPDF_CloseDocument(output_doc
);
1165 return pp::Buffer_Dev();
1168 FitContentsToPrintableAreaIfRequired(output_doc
, print_settings
);
1170 // Now flatten all the output pages.
1171 pp::Buffer_Dev buffer
= GetFlattenedPrintData(output_doc
);
1172 FPDF_CloseDocument(output_doc
);
1176 void PDFiumEngine::FitContentsToPrintableAreaIfRequired(
1177 const FPDF_DOCUMENT
& doc
, const PP_PrintSettings_Dev
& print_settings
) {
1178 // Check to see if we need to fit pdf contents to printer paper size.
1179 if (print_settings
.print_scaling_option
!=
1180 PP_PRINTSCALINGOPTION_SOURCE_SIZE
) {
1181 int num_pages
= FPDF_GetPageCount(doc
);
1182 // In-place transformation is more efficient than creating a new
1183 // transformed document from the source document. Therefore, transform
1184 // every page to fit the contents in the selected printer paper.
1185 for (int i
= 0; i
< num_pages
; ++i
) {
1186 FPDF_PAGE page
= FPDF_LoadPage(doc
, i
);
1187 TransformPDFPageForPrinting(page
, print_settings
);
1188 FPDF_ClosePage(page
);
1193 void PDFiumEngine::SaveSelectedFormForPrint() {
1194 FORM_ForceToKillFocus(form_
);
1195 client_
->FormTextFieldFocusChange(false);
1198 void PDFiumEngine::PrintEnd() {
1199 FORM_DoDocumentAAction(form_
, FPDFDOC_AACTION_DP
);
1202 PDFiumPage::Area
PDFiumEngine::GetCharIndex(
1203 const pp::MouseInputEvent
& event
, int* page_index
,
1204 int* char_index
, PDFiumPage::LinkTarget
* target
) {
1205 // First figure out which page this is in.
1206 pp::Point mouse_point
= event
.GetPosition();
1208 static_cast<int>((mouse_point
.x() + position_
.x()) / current_zoom_
),
1209 static_cast<int>((mouse_point
.y() + position_
.y()) / current_zoom_
));
1210 return GetCharIndex(point
, page_index
, char_index
, target
);
1213 PDFiumPage::Area
PDFiumEngine::GetCharIndex(
1214 const pp::Point
& point
,
1217 PDFiumPage::LinkTarget
* target
) {
1219 for (size_t i
= 0; i
< visible_pages_
.size(); ++i
) {
1220 if (pages_
[visible_pages_
[i
]]->rect().Contains(point
)) {
1221 page
= visible_pages_
[i
];
1226 return PDFiumPage::NONSELECTABLE_AREA
;
1228 // If the page hasn't finished rendering, calling into the page sometimes
1230 for (size_t i
= 0; i
< progressive_paints_
.size(); ++i
) {
1231 if (progressive_paints_
[i
].page_index
== page
)
1232 return PDFiumPage::NONSELECTABLE_AREA
;
1236 return pages_
[page
]->GetCharIndex(point
, current_rotation_
, char_index
,
1240 bool PDFiumEngine::OnMouseDown(const pp::MouseInputEvent
& event
) {
1241 if (event
.GetButton() != PP_INPUTEVENT_MOUSEBUTTON_LEFT
)
1244 SelectionChangeInvalidator
selection_invalidator(this);
1247 int page_index
= -1;
1248 int char_index
= -1;
1249 PDFiumPage::LinkTarget target
;
1250 PDFiumPage::Area area
= GetCharIndex(event
, &page_index
,
1251 &char_index
, &target
);
1252 if (area
== PDFiumPage::WEBLINK_AREA
) {
1253 bool open_in_new_tab
= !!(event
.GetModifiers() & kDefaultKeyModifier
);
1254 client_
->NavigateTo(target
.url
, open_in_new_tab
);
1255 client_
->FormTextFieldFocusChange(false);
1259 if (area
== PDFiumPage::DOCLINK_AREA
) {
1260 client_
->ScrollToPage(target
.page
);
1261 client_
->FormTextFieldFocusChange(false);
1265 if (page_index
!= -1) {
1266 last_page_mouse_down_
= page_index
;
1267 double page_x
, page_y
;
1268 pp::Point point
= event
.GetPosition();
1269 DeviceToPage(page_index
, point
.x(), point
.y(), &page_x
, &page_y
);
1271 FORM_OnLButtonDown(form_
, pages_
[page_index
]->GetPage(), 0, page_x
, page_y
);
1272 int control
= FPDPage_HasFormFieldAtPoint(
1273 form_
, pages_
[page_index
]->GetPage(), page_x
, page_y
);
1274 if (control
> FPDF_FORMFIELD_UNKNOWN
) { // returns -1 sometimes...
1275 client_
->FormTextFieldFocusChange(control
== FPDF_FORMFIELD_TEXTFIELD
||
1276 control
== FPDF_FORMFIELD_COMBOBOX
);
1277 return true; // Return now before we get into the selection code.
1281 client_
->FormTextFieldFocusChange(false);
1283 if (area
!= PDFiumPage::TEXT_AREA
)
1284 return true; // Return true so WebKit doesn't do its own highlighting.
1286 if (event
.GetClickCount() == 1) {
1287 OnSingleClick(page_index
, char_index
);
1288 } else if (event
.GetClickCount() == 2 ||
1289 event
.GetClickCount() == 3) {
1290 OnMultipleClick(event
.GetClickCount(), page_index
, char_index
);
1296 void PDFiumEngine::OnSingleClick(int page_index
, int char_index
) {
1298 selection_
.push_back(PDFiumRange(pages_
[page_index
], char_index
, 0));
1301 void PDFiumEngine::OnMultipleClick(int click_count
,
1304 // It would be more efficient if the SDK could support finding a space, but
1306 int start_index
= char_index
;
1308 base::char16 cur
= pages_
[page_index
]->GetCharAtIndex(start_index
);
1309 // For double click, we want to select one word so we look for whitespace
1310 // boundaries. For triple click, we want the whole line.
1311 if (cur
== '\n' || (click_count
== 2 && (cur
== ' ' || cur
== '\t')))
1313 } while (--start_index
>= 0);
1317 int end_index
= char_index
;
1318 int total
= pages_
[page_index
]->GetCharCount();
1319 while (end_index
++ <= total
) {
1320 base::char16 cur
= pages_
[page_index
]->GetCharAtIndex(end_index
);
1321 if (cur
== '\n' || (click_count
== 2 && (cur
== ' ' || cur
== '\t')))
1325 selection_
.push_back(PDFiumRange(
1326 pages_
[page_index
], start_index
, end_index
- start_index
));
1329 bool PDFiumEngine::OnMouseUp(const pp::MouseInputEvent
& event
) {
1330 if (event
.GetButton() != PP_INPUTEVENT_MOUSEBUTTON_LEFT
)
1333 int page_index
= -1;
1334 int char_index
= -1;
1335 GetCharIndex(event
, &page_index
, &char_index
, NULL
);
1336 if (page_index
!= -1) {
1337 double page_x
, page_y
;
1338 pp::Point point
= event
.GetPosition();
1339 DeviceToPage(page_index
, point
.x(), point
.y(), &page_x
, &page_y
);
1341 form_
, pages_
[page_index
]->GetPage(), 0, page_x
, page_y
);
1351 bool PDFiumEngine::OnMouseMove(const pp::MouseInputEvent
& event
) {
1352 int page_index
= -1;
1353 int char_index
= -1;
1354 PDFiumPage::Area area
= GetCharIndex(event
, &page_index
, &char_index
, NULL
);
1356 PP_CursorType_Dev cursor
;
1358 case PDFiumPage::TEXT_AREA
:
1359 cursor
= PP_CURSORTYPE_IBEAM
;
1361 case PDFiumPage::WEBLINK_AREA
:
1362 case PDFiumPage::DOCLINK_AREA
:
1363 cursor
= PP_CURSORTYPE_HAND
;
1365 case PDFiumPage::NONSELECTABLE_AREA
:
1367 cursor
= PP_CURSORTYPE_POINTER
;
1371 if (page_index
!= -1) {
1372 double page_x
, page_y
;
1373 pp::Point point
= event
.GetPosition();
1374 DeviceToPage(page_index
, point
.x(), point
.y(), &page_x
, &page_y
);
1376 FORM_OnMouseMove(form_
, pages_
[page_index
]->GetPage(), 0, page_x
, page_y
);
1377 int control
= FPDPage_HasFormFieldAtPoint(
1378 form_
, pages_
[page_index
]->GetPage(), page_x
, page_y
);
1380 case FPDF_FORMFIELD_PUSHBUTTON
:
1381 case FPDF_FORMFIELD_CHECKBOX
:
1382 case FPDF_FORMFIELD_RADIOBUTTON
:
1383 case FPDF_FORMFIELD_COMBOBOX
:
1384 case FPDF_FORMFIELD_LISTBOX
:
1385 cursor
= PP_CURSORTYPE_HAND
;
1387 case FPDF_FORMFIELD_TEXTFIELD
:
1388 cursor
= PP_CURSORTYPE_IBEAM
;
1395 client_
->UpdateCursor(cursor
);
1396 pp::Point point
= event
.GetPosition();
1397 std::string url
= GetLinkAtPosition(event
.GetPosition());
1398 if (url
!= link_under_cursor_
) {
1399 link_under_cursor_
= url
;
1400 pp::PDF::SetLinkUnderCursor(GetPluginInstance(), url
.c_str());
1402 // No need to swallow the event, since this might interfere with the
1403 // scrollbars if the user is dragging them.
1407 // We're selecting but right now we're not over text, so don't change the
1408 // current selection.
1409 if (area
!= PDFiumPage::TEXT_AREA
&& area
!= PDFiumPage::WEBLINK_AREA
&&
1410 area
!= PDFiumPage::DOCLINK_AREA
) {
1414 SelectionChangeInvalidator
selection_invalidator(this);
1416 // Check if the user has descreased their selection area and we need to remove
1417 // pages from selection_.
1418 for (size_t i
= 0; i
< selection_
.size(); ++i
) {
1419 if (selection_
[i
].page_index() == page_index
) {
1420 // There should be no other pages after this.
1421 selection_
.erase(selection_
.begin() + i
+ 1, selection_
.end());
1426 if (selection_
.size() == 0)
1429 int last
= selection_
.size() - 1;
1430 if (selection_
[last
].page_index() == page_index
) {
1431 // Selecting within a page.
1433 if (char_index
>= selection_
[last
].char_index()) {
1434 // Selecting forward.
1435 count
= char_index
- selection_
[last
].char_index() + 1;
1437 count
= char_index
- selection_
[last
].char_index() - 1;
1439 selection_
[last
].SetCharCount(count
);
1440 } else if (selection_
[last
].page_index() < page_index
) {
1441 // Selecting into the next page.
1443 // First make sure that there are no gaps in selection, i.e. if mousedown on
1444 // page one but we only get mousemove over page three, we want page two.
1445 for (int i
= selection_
[last
].page_index() + 1; i
< page_index
; ++i
) {
1446 selection_
.push_back(PDFiumRange(pages_
[i
], 0,
1447 pages_
[i
]->GetCharCount()));
1450 int count
= pages_
[selection_
[last
].page_index()]->GetCharCount();
1451 selection_
[last
].SetCharCount(count
- selection_
[last
].char_index());
1452 selection_
.push_back(PDFiumRange(pages_
[page_index
], 0, char_index
));
1454 // Selecting into the previous page.
1455 selection_
[last
].SetCharCount(-selection_
[last
].char_index());
1457 // First make sure that there are no gaps in selection, i.e. if mousedown on
1458 // page three but we only get mousemove over page one, we want page two.
1459 for (int i
= selection_
[last
].page_index() - 1; i
> page_index
; --i
) {
1460 selection_
.push_back(PDFiumRange(pages_
[i
], 0,
1461 pages_
[i
]->GetCharCount()));
1464 int count
= pages_
[page_index
]->GetCharCount();
1465 selection_
.push_back(
1466 PDFiumRange(pages_
[page_index
], count
, count
- char_index
));
1472 bool PDFiumEngine::OnKeyDown(const pp::KeyboardInputEvent
& event
) {
1473 if (last_page_mouse_down_
== -1)
1476 bool rv
= !!FORM_OnKeyDown(
1477 form_
, pages_
[last_page_mouse_down_
]->GetPage(),
1478 event
.GetKeyCode(), event
.GetModifiers());
1480 if (event
.GetKeyCode() == ui::VKEY_BACK
||
1481 event
.GetKeyCode() == ui::VKEY_ESCAPE
) {
1482 // Chrome doesn't send char events for backspace or escape keys, see
1483 // PlatformKeyboardEventBuilder::isCharacterKey() and
1484 // http://chrome-corpsvn.mtv.corp.google.com/viewvc?view=rev&root=chrome&revision=31805
1485 // for more information. So just fake one since PDFium uses it.
1487 str
.push_back(event
.GetKeyCode());
1488 pp::KeyboardInputEvent
synthesized(pp::KeyboardInputEvent(
1489 client_
->GetPluginInstance(),
1490 PP_INPUTEVENT_TYPE_CHAR
,
1491 event
.GetTimeStamp(),
1492 event
.GetModifiers(),
1495 OnChar(synthesized
);
1501 bool PDFiumEngine::OnKeyUp(const pp::KeyboardInputEvent
& event
) {
1502 if (last_page_mouse_down_
== -1)
1505 return !!FORM_OnKeyUp(
1506 form_
, pages_
[last_page_mouse_down_
]->GetPage(),
1507 event
.GetKeyCode(), event
.GetModifiers());
1510 bool PDFiumEngine::OnChar(const pp::KeyboardInputEvent
& event
) {
1511 if (last_page_mouse_down_
== -1)
1514 base::string16 str
= base::UTF8ToUTF16(event
.GetCharacterText().AsString());
1515 return !!FORM_OnChar(
1516 form_
, pages_
[last_page_mouse_down_
]->GetPage(),
1518 event
.GetModifiers());
1521 void PDFiumEngine::StartFind(const char* text
, bool case_sensitive
) {
1522 // We can get a call to StartFind before we have any page information (i.e.
1523 // before the first call to LoadDocument has happened). Handle this case.
1527 bool first_search
= false;
1528 int character_to_start_searching_from
= 0;
1529 if (current_find_text_
!= text
) { // First time we search for this text.
1530 first_search
= true;
1531 std::vector
<PDFiumRange
> old_selection
= selection_
;
1533 current_find_text_
= text
;
1535 if (old_selection
.empty()) {
1536 // Start searching from the beginning of the document.
1537 next_page_to_search_
= 0;
1538 last_page_to_search_
= pages_
.size() - 1;
1539 last_character_index_to_search_
= -1;
1541 // There's a current selection, so start from it.
1542 next_page_to_search_
= old_selection
[0].page_index();
1543 last_character_index_to_search_
= old_selection
[0].char_index();
1544 character_to_start_searching_from
= old_selection
[0].char_index();
1545 last_page_to_search_
= next_page_to_search_
;
1549 int current_page
= next_page_to_search_
;
1551 if (pages_
[current_page
]->available()) {
1552 base::string16 str
= base::UTF8ToUTF16(text
);
1553 // Don't use PDFium to search for now, since it doesn't support unicode text.
1554 // Leave the code for now to avoid bit-rot, in case it's fixed later.
1557 str
, case_sensitive
, first_search
, character_to_start_searching_from
,
1561 str
, case_sensitive
, first_search
, character_to_start_searching_from
,
1565 if (!IsPageVisible(current_page
))
1566 pages_
[current_page
]->Unload();
1569 if (next_page_to_search_
!= last_page_to_search_
||
1570 (first_search
&& last_character_index_to_search_
!= -1)) {
1571 ++next_page_to_search_
;
1574 if (next_page_to_search_
== static_cast<int>(pages_
.size()))
1575 next_page_to_search_
= 0;
1576 // If there's only one page in the document and we start searching midway,
1577 // then we'll want to search the page one more time.
1578 bool end_of_search
=
1579 next_page_to_search_
== last_page_to_search_
&&
1580 // Only one page but didn't start midway.
1581 ((pages_
.size() == 1 && last_character_index_to_search_
== -1) ||
1582 // Started midway, but only 1 page and we already looped around.
1583 (pages_
.size() == 1 && !first_search
) ||
1584 // Started midway, and we've just looped around.
1585 (pages_
.size() > 1 && current_page
== next_page_to_search_
));
1587 if (end_of_search
) {
1588 // Send the final notification.
1589 client_
->NotifyNumberOfFindResultsChanged(find_results_
.size(), true);
1591 pp::CompletionCallback callback
=
1592 find_factory_
.NewCallback(&PDFiumEngine::ContinueFind
);
1593 pp::Module::Get()->core()->CallOnMainThread(
1594 0, callback
, case_sensitive
? 1 : 0);
1598 void PDFiumEngine::SearchUsingPDFium(const base::string16
& term
,
1599 bool case_sensitive
,
1601 int character_to_start_searching_from
,
1603 // Find all the matches in the current page.
1604 unsigned long flags
= case_sensitive
? FPDF_MATCHCASE
: 0;
1605 FPDF_SCHHANDLE find
= FPDFText_FindStart(
1606 pages_
[current_page
]->GetTextPage(),
1607 reinterpret_cast<const unsigned short*>(term
.c_str()),
1608 flags
, character_to_start_searching_from
);
1610 // Note: since we search one page at a time, we don't find matches across
1611 // page boundaries. We could do this manually ourself, but it seems low
1612 // priority since Reader itself doesn't do it.
1613 while (FPDFText_FindNext(find
)) {
1614 PDFiumRange
result(pages_
[current_page
],
1615 FPDFText_GetSchResultIndex(find
),
1616 FPDFText_GetSchCount(find
));
1618 if (!first_search
&&
1619 last_character_index_to_search_
!= -1 &&
1620 result
.page_index() == last_page_to_search_
&&
1621 result
.char_index() >= last_character_index_to_search_
) {
1625 AddFindResult(result
);
1628 FPDFText_FindClose(find
);
1631 void PDFiumEngine::SearchUsingICU(const base::string16
& term
,
1632 bool case_sensitive
,
1634 int character_to_start_searching_from
,
1636 base::string16 page_text
;
1637 int text_length
= pages_
[current_page
]->GetCharCount();
1638 if (character_to_start_searching_from
) {
1639 text_length
-= character_to_start_searching_from
;
1640 } else if (!first_search
&&
1641 last_character_index_to_search_
!= -1 &&
1642 current_page
== last_page_to_search_
) {
1643 text_length
= last_character_index_to_search_
;
1645 if (text_length
<= 0)
1647 unsigned short* data
=
1648 reinterpret_cast<unsigned short*>(WriteInto(&page_text
, text_length
+ 1));
1649 FPDFText_GetText(pages_
[current_page
]->GetTextPage(),
1650 character_to_start_searching_from
,
1653 std::vector
<PDFEngine::Client::SearchStringResult
> results
;
1654 client_
->SearchString(
1655 page_text
.c_str(), term
.c_str(), case_sensitive
, &results
);
1656 for (size_t i
= 0; i
< results
.size(); ++i
) {
1657 // Need to map the indexes from the page text, which may have generated
1658 // characters like space etc, to character indices from the page.
1659 int temp_start
= results
[i
].start_index
+ character_to_start_searching_from
;
1660 int start
= FPDFText_GetCharIndexFromTextIndex(
1661 pages_
[current_page
]->GetTextPage(), temp_start
);
1662 int end
= FPDFText_GetCharIndexFromTextIndex(
1663 pages_
[current_page
]->GetTextPage(),
1664 temp_start
+ results
[i
].length
);
1665 AddFindResult(PDFiumRange(pages_
[current_page
], start
, end
- start
));
1669 void PDFiumEngine::AddFindResult(const PDFiumRange
& result
) {
1670 // Figure out where to insert the new location, since we could have
1671 // started searching midway and now we wrapped.
1673 int page_index
= result
.page_index();
1674 int char_index
= result
.char_index();
1675 for (i
= 0; i
< find_results_
.size(); ++i
) {
1676 if (find_results_
[i
].page_index() > page_index
||
1677 (find_results_
[i
].page_index() == page_index
&&
1678 find_results_
[i
].char_index() > char_index
)) {
1682 find_results_
.insert(find_results_
.begin() + i
, result
);
1685 if (current_find_index_
== -1) {
1686 // Select the first match.
1687 SelectFindResult(true);
1688 } else if (static_cast<int>(i
) <= current_find_index_
) {
1689 // Update the current match index
1690 current_find_index_
++;
1691 client_
->NotifySelectedFindResultChanged(current_find_index_
);
1693 client_
->NotifyNumberOfFindResultsChanged(find_results_
.size(), false);
1696 bool PDFiumEngine::SelectFindResult(bool forward
) {
1697 if (find_results_
.empty()) {
1702 SelectionChangeInvalidator
selection_invalidator(this);
1704 // Move back/forward through the search locations we previously found.
1706 if (++current_find_index_
== static_cast<int>(find_results_
.size()))
1707 current_find_index_
= 0;
1709 if (--current_find_index_
< 0) {
1710 current_find_index_
= find_results_
.size() - 1;
1714 // Update the selection before telling the client to scroll, since it could
1717 selection_
.push_back(find_results_
[current_find_index_
]);
1719 // If the result is not in view, scroll to it.
1721 pp::Rect bounding_rect
;
1722 pp::Rect visible_rect
= GetVisibleRect();
1723 // Use zoom of 1.0 since visible_rect is without zoom.
1724 std::vector
<pp::Rect
> rects
= find_results_
[current_find_index_
].
1725 GetScreenRects(pp::Point(), 1.0, current_rotation_
);
1726 for (i
= 0; i
< rects
.size(); ++i
)
1727 bounding_rect
= bounding_rect
.Union(rects
[i
]);
1728 if (!visible_rect
.Contains(bounding_rect
)) {
1729 pp::Point center
= bounding_rect
.CenterPoint();
1730 // Make the page centered.
1731 int new_y
= static_cast<int>(center
.y() * current_zoom_
) -
1732 static_cast<int>(visible_rect
.height() * current_zoom_
/ 2);
1735 client_
->ScrollToY(new_y
);
1737 // Only move horizontally if it's not visible.
1738 if (center
.x() < visible_rect
.x() || center
.x() > visible_rect
.right()) {
1739 int new_x
= static_cast<int>(center
.x() * current_zoom_
) -
1740 static_cast<int>(visible_rect
.width() * current_zoom_
/ 2);
1743 client_
->ScrollToX(new_x
);
1747 client_
->NotifySelectedFindResultChanged(current_find_index_
);
1752 void PDFiumEngine::StopFind() {
1753 SelectionChangeInvalidator
selection_invalidator(this);
1757 find_results_
.clear();
1758 next_page_to_search_
= -1;
1759 last_page_to_search_
= -1;
1760 last_character_index_to_search_
= -1;
1761 current_find_index_
= -1;
1762 current_find_text_
.clear();
1764 find_factory_
.CancelAll();
1767 void PDFiumEngine::UpdateTickMarks() {
1768 std::vector
<pp::Rect
> tickmarks
;
1769 for (size_t i
= 0; i
< find_results_
.size(); ++i
) {
1771 // Always use an origin of 0,0 since scroll positions don't affect tickmark.
1772 std::vector
<pp::Rect
> rects
= find_results_
[i
].GetScreenRects(
1773 pp::Point(0, 0), current_zoom_
, current_rotation_
);
1774 for (size_t j
= 0; j
< rects
.size(); ++j
)
1775 rect
= rect
.Union(rects
[j
]);
1776 tickmarks
.push_back(rect
);
1779 client_
->UpdateTickMarks(tickmarks
);
1782 void PDFiumEngine::ZoomUpdated(double new_zoom_level
) {
1785 current_zoom_
= new_zoom_level
;
1787 CalculateVisiblePages();
1791 void PDFiumEngine::RotateClockwise() {
1792 current_rotation_
= (current_rotation_
+ 1) % 4;
1793 InvalidateAllPages();
1796 void PDFiumEngine::RotateCounterclockwise() {
1797 current_rotation_
= (current_rotation_
- 1) % 4;
1798 InvalidateAllPages();
1801 void PDFiumEngine::InvalidateAllPages() {
1803 find_results_
.clear();
1808 client_
->Invalidate(pp::Rect(plugin_size_
));
1811 std::string
PDFiumEngine::GetSelectedText() {
1812 base::string16 result
;
1813 for (size_t i
= 0; i
< selection_
.size(); ++i
) {
1815 selection_
[i
- 1].page_index() > selection_
[i
].page_index()) {
1816 result
= selection_
[i
].GetText() + result
;
1818 result
.append(selection_
[i
].GetText());
1822 return base::UTF16ToUTF8(result
);
1825 std::string
PDFiumEngine::GetLinkAtPosition(const pp::Point
& point
) {
1827 PDFiumPage::LinkTarget target
;
1828 PDFiumPage::Area area
= GetCharIndex(point
, &temp
, &temp
, &target
);
1829 if (area
== PDFiumPage::WEBLINK_AREA
)
1831 return std::string();
1834 bool PDFiumEngine::IsSelecting() {
1838 bool PDFiumEngine::HasPermission(DocumentPermission permission
) const {
1839 switch (permission
) {
1840 case PERMISSION_COPY
:
1841 return (permissions_
& kPDFPermissionCopyMask
) != 0;
1842 case PERMISSION_COPY_ACCESSIBLE
:
1843 return (permissions_
& kPDFPermissionCopyAccessibleMask
) != 0;
1844 case PERMISSION_PRINT_LOW_QUALITY
:
1845 return (permissions_
& kPDFPermissionPrintLowQualityMask
) != 0;
1846 case PERMISSION_PRINT_HIGH_QUALITY
:
1847 return (permissions_
& kPDFPermissionPrintLowQualityMask
) != 0 &&
1848 (permissions_
& kPDFPermissionPrintHighQualityMask
) != 0;
1854 void PDFiumEngine::SelectAll() {
1855 SelectionChangeInvalidator
selection_invalidator(this);
1858 for (size_t i
= 0; i
< pages_
.size(); ++i
)
1859 if (pages_
[i
]->available()) {
1860 selection_
.push_back(PDFiumRange(pages_
[i
], 0,
1861 pages_
[i
]->GetCharCount()));
1865 int PDFiumEngine::GetNumberOfPages() {
1866 return pages_
.size();
1869 int PDFiumEngine::GetNamedDestinationPage(const std::string
& destination
) {
1870 // Look for the destination.
1871 FPDF_DEST dest
= FPDF_GetNamedDestByName(doc_
, destination
.c_str());
1873 // Look for a bookmark with the same name.
1874 base::string16 destination_wide
= base::UTF8ToUTF16(destination
);
1875 FPDF_WIDESTRING destination_pdf_wide
=
1876 reinterpret_cast<FPDF_WIDESTRING
>(destination_wide
.c_str());
1877 FPDF_BOOKMARK bookmark
= FPDFBookmark_Find(doc_
, destination_pdf_wide
);
1880 dest
= FPDFBookmark_GetDest(doc_
, bookmark
);
1882 return dest
? FPDFDest_GetPageIndex(doc_
, dest
) : -1;
1885 int PDFiumEngine::GetFirstVisiblePage() {
1886 CalculateVisiblePages();
1887 return first_visible_page_
;
1890 int PDFiumEngine::GetMostVisiblePage() {
1891 CalculateVisiblePages();
1892 return most_visible_page_
;
1895 pp::Rect
PDFiumEngine::GetPageRect(int index
) {
1896 pp::Rect
rc(pages_
[index
]->rect());
1897 rc
.Inset(-kPageShadowLeft
, -kPageShadowTop
,
1898 -kPageShadowRight
, -kPageShadowBottom
);
1902 pp::Rect
PDFiumEngine::GetPageContentsRect(int index
) {
1903 return GetScreenRect(pages_
[index
]->rect());
1906 void PDFiumEngine::PaintThumbnail(pp::ImageData
* image_data
, int index
) {
1907 FPDF_BITMAP bitmap
= FPDFBitmap_CreateEx(
1908 image_data
->size().width(), image_data
->size().height(),
1909 FPDFBitmap_BGRx
, image_data
->data(), image_data
->stride());
1911 if (pages_
[index
]->available()) {
1912 FPDFBitmap_FillRect(
1913 bitmap
, 0, 0, image_data
->size().width(), image_data
->size().height(),
1914 255, 255, 255, 255);
1916 FPDF_RenderPageBitmap(
1917 bitmap
, pages_
[index
]->GetPage(), 0, 0, image_data
->size().width(),
1918 image_data
->size().height(), 0, GetRenderingFlags());
1920 FPDFBitmap_FillRect(
1921 bitmap
, 0, 0, image_data
->size().width(), image_data
->size().height(),
1922 kPendingPageColorR
, kPendingPageColorG
, kPendingPageColorB
,
1923 kPendingPageColorA
);
1926 FPDFBitmap_Destroy(bitmap
);
1929 void PDFiumEngine::SetGrayscale(bool grayscale
) {
1930 render_grayscale_
= grayscale
;
1933 void PDFiumEngine::OnCallback(int id
) {
1934 if (!timers_
.count(id
))
1937 timers_
[id
].second(id
);
1938 if (timers_
.count(id
)) // The callback might delete the timer.
1939 client_
->ScheduleCallback(id
, timers_
[id
].first
);
1942 std::string
PDFiumEngine::GetPageAsJSON(int index
) {
1943 if (!(HasPermission(PERMISSION_COPY
) ||
1944 HasPermission(PERMISSION_COPY_ACCESSIBLE
))) {
1948 if (index
< 0 || static_cast<size_t>(index
) > pages_
.size() - 1)
1951 scoped_ptr
<base::Value
> node(
1952 pages_
[index
]->GetAccessibleContentAsValue(current_rotation_
));
1953 std::string page_json
;
1954 base::JSONWriter::Write(node
.get(), &page_json
);
1958 bool PDFiumEngine::GetPrintScaling() {
1959 return !!FPDF_VIEWERREF_GetPrintScaling(doc_
);
1962 void PDFiumEngine::AppendBlankPages(int num_pages
) {
1963 DCHECK(num_pages
!= 0);
1969 pending_pages_
.clear();
1971 // Delete all pages except the first one.
1972 while (pages_
.size() > 1) {
1973 delete pages_
.back();
1975 FPDFPage_Delete(doc_
, pages_
.size());
1978 // Calculate document size and all page sizes.
1979 std::vector
<pp::Rect
> page_rects
;
1980 pp::Size page_size
= GetPageSize(0);
1981 page_size
.Enlarge(kPageShadowLeft
+ kPageShadowRight
,
1982 kPageShadowTop
+ kPageShadowBottom
);
1983 pp::Size old_document_size
= document_size_
;
1984 document_size_
= pp::Size(page_size
.width(), 0);
1985 for (int i
= 0; i
< num_pages
; ++i
) {
1987 // Add space for horizontal separator.
1988 document_size_
.Enlarge(0, kPageSeparatorThickness
);
1991 pp::Rect
rect(pp::Point(0, document_size_
.height()), page_size
);
1992 page_rects
.push_back(rect
);
1994 document_size_
.Enlarge(0, page_size
.height());
1997 // Create blank pages.
1998 for (int i
= 1; i
< num_pages
; ++i
) {
1999 pp::Rect
page_rect(page_rects
[i
]);
2000 page_rect
.Inset(kPageShadowLeft
, kPageShadowTop
,
2001 kPageShadowRight
, kPageShadowBottom
);
2002 double width_in_points
=
2003 page_rect
.width() * kPointsPerInch
/ kPixelsPerInch
;
2004 double height_in_points
=
2005 page_rect
.height() * kPointsPerInch
/ kPixelsPerInch
;
2006 FPDFPage_New(doc_
, i
, width_in_points
, height_in_points
);
2007 pages_
.push_back(new PDFiumPage(this, i
, page_rect
, true));
2010 CalculateVisiblePages();
2011 if (document_size_
!= old_document_size
)
2012 client_
->DocumentSizeUpdated(document_size_
);
2015 void PDFiumEngine::LoadDocument() {
2016 // Check if the document is ready for loading. If it isn't just bail for now,
2017 // we will call LoadDocument() again later.
2018 if (!doc_
&& !doc_loader_
.IsDocumentComplete() &&
2019 !FPDFAvail_IsDocAvail(fpdf_availability_
, &download_hints_
)) {
2023 // If we're in the middle of getting a password, just return. We will retry
2024 // loading the document after we get the password anyway.
2025 if (getting_password_
)
2028 ScopedUnsupportedFeature
scoped_unsupported_feature(this);
2029 bool needs_password
= false;
2030 if (TryLoadingDoc(false, std::string(), &needs_password
)) {
2031 ContinueLoadingDocument(false, std::string());
2035 GetPasswordAndLoad();
2037 client_
->DocumentLoadFailed();
2040 bool PDFiumEngine::TryLoadingDoc(bool with_password
,
2041 const std::string
& password
,
2042 bool* needs_password
) {
2043 *needs_password
= false;
2047 const char* password_cstr
= NULL
;
2048 if (with_password
) {
2049 password_cstr
= password
.c_str();
2050 password_tries_remaining_
--;
2052 if (doc_loader_
.IsDocumentComplete())
2053 doc_
= FPDF_LoadCustomDocument(&file_access_
, password_cstr
);
2055 doc_
= FPDFAvail_GetDocument(fpdf_availability_
, password_cstr
);
2057 if (!doc_
&& FPDF_GetLastError() == FPDF_ERR_PASSWORD
)
2058 *needs_password
= true;
2060 return doc_
!= NULL
;
2063 void PDFiumEngine::GetPasswordAndLoad() {
2064 getting_password_
= true;
2065 DCHECK(!doc_
&& FPDF_GetLastError() == FPDF_ERR_PASSWORD
);
2066 client_
->GetDocumentPassword(password_factory_
.NewCallbackWithOutput(
2067 &PDFiumEngine::OnGetPasswordComplete
));
2070 void PDFiumEngine::OnGetPasswordComplete(int32_t result
,
2071 const pp::Var
& password
) {
2072 getting_password_
= false;
2074 bool password_given
= false;
2075 std::string password_text
;
2076 if (result
== PP_OK
&& password
.is_string()) {
2077 password_text
= password
.AsString();
2078 if (!password_text
.empty())
2079 password_given
= true;
2081 ContinueLoadingDocument(password_given
, password_text
);
2084 void PDFiumEngine::ContinueLoadingDocument(
2086 const std::string
& password
) {
2087 ScopedUnsupportedFeature
scoped_unsupported_feature(this);
2089 bool needs_password
= false;
2090 bool loaded
= TryLoadingDoc(has_password
, password
, &needs_password
);
2091 bool password_incorrect
= !loaded
&& has_password
&& needs_password
;
2092 if (password_incorrect
&& password_tries_remaining_
> 0) {
2093 GetPasswordAndLoad();
2098 client_
->DocumentLoadFailed();
2102 if (FPDFDoc_GetPageMode(doc_
) == PAGEMODE_USEOUTLINES
)
2103 client_
->DocumentHasUnsupportedFeature("Bookmarks");
2105 permissions_
= FPDF_GetDocPermissions(doc_
);
2108 // Only returns 0 when data isn't available. If form data is downloaded, or
2109 // if this isn't a form, returns positive values.
2110 if (!doc_loader_
.IsDocumentComplete() &&
2111 !FPDFAvail_IsFormAvail(fpdf_availability_
, &download_hints_
)) {
2115 form_
= FPDFDOC_InitFormFillEnviroument(
2116 doc_
, static_cast<FPDF_FORMFILLINFO
*>(this));
2117 FPDF_SetFormFieldHighlightColor(form_
, 0, kFormHighlightColor
);
2118 FPDF_SetFormFieldHighlightAlpha(form_
, kFormHighlightAlpha
);
2121 if (!doc_loader_
.IsDocumentComplete()) {
2122 // Check if the first page is available. In a linearized PDF, that is not
2123 // always page 0. Doing this gives us the default page size, since when the
2124 // document is available, the first page is available as well.
2125 CheckPageAvailable(FPDFAvail_GetFirstPageNum(doc_
), &pending_pages_
);
2128 LoadPageInfo(false);
2130 if (doc_loader_
.IsDocumentComplete())
2131 FinishLoadingDocument();
2134 void PDFiumEngine::LoadPageInfo(bool reload
) {
2135 pending_pages_
.clear();
2136 pp::Size old_document_size
= document_size_
;
2137 document_size_
= pp::Size();
2138 std::vector
<pp::Rect
> page_rects
;
2139 int page_count
= FPDF_GetPageCount(doc_
);
2140 bool doc_complete
= doc_loader_
.IsDocumentComplete();
2141 for (int i
= 0; i
< page_count
; ++i
) {
2143 // Add space for horizontal separator.
2144 document_size_
.Enlarge(0, kPageSeparatorThickness
);
2147 // Get page availability. If reload==false, and document is not loaded yet
2148 // (we are using async loading) - mark all pages as unavailable.
2149 // If reload==true (we have document constructed already), get page
2150 // availability flag from already existing PDFiumPage class.
2151 bool page_available
= reload
? pages_
[i
]->available() : doc_complete
;
2153 pp::Size size
= page_available
? GetPageSize(i
) : default_page_size_
;
2154 size
.Enlarge(kPageShadowLeft
+ kPageShadowRight
,
2155 kPageShadowTop
+ kPageShadowBottom
);
2156 pp::Rect
rect(pp::Point(0, document_size_
.height()), size
);
2157 page_rects
.push_back(rect
);
2159 if (size
.width() > document_size_
.width())
2160 document_size_
.set_width(size
.width());
2162 document_size_
.Enlarge(0, size
.height());
2165 for (int i
= 0; i
< page_count
; ++i
) {
2166 // Center pages relative to the entire document.
2167 page_rects
[i
].set_x((document_size_
.width() - page_rects
[i
].width()) / 2);
2168 pp::Rect
page_rect(page_rects
[i
]);
2169 page_rect
.Inset(kPageShadowLeft
, kPageShadowTop
,
2170 kPageShadowRight
, kPageShadowBottom
);
2172 pages_
[i
]->set_rect(page_rect
);
2174 pages_
.push_back(new PDFiumPage(this, i
, page_rect
, doc_complete
));
2178 CalculateVisiblePages();
2179 if (document_size_
!= old_document_size
)
2180 client_
->DocumentSizeUpdated(document_size_
);
2183 void PDFiumEngine::CalculateVisiblePages() {
2184 // Clear pending requests queue, since it may contain requests to the pages
2185 // that are already invisible (after scrolling for example).
2186 pending_pages_
.clear();
2187 doc_loader_
.ClearPendingRequests();
2189 visible_pages_
.clear();
2190 pp::Rect
visible_rect(plugin_size_
);
2191 for (size_t i
= 0; i
< pages_
.size(); ++i
) {
2192 // Check an entire PageScreenRect, since we might need to repaint side
2193 // borders and shadows even if the page itself is not visible.
2194 // For example, when user use pdf with different page sizes and zoomed in
2195 // outside page area.
2196 if (visible_rect
.Intersects(GetPageScreenRect(i
))) {
2197 visible_pages_
.push_back(i
);
2198 CheckPageAvailable(i
, &pending_pages_
);
2200 // Need to unload pages when we're not using them, since some PDFs use a
2201 // lot of memory. See http://crbug.com/48791
2202 if (defer_page_unload_
) {
2203 deferred_page_unloads_
.push_back(i
);
2205 pages_
[i
]->Unload();
2208 // If the last mouse down was on a page that's no longer visible, reset
2209 // that variable so that we don't send keyboard events to it (the focus
2210 // will be lost when the page is first closed anyways).
2211 if (static_cast<int>(i
) == last_page_mouse_down_
)
2212 last_page_mouse_down_
= -1;
2216 // Any pending highlighting of form fields will be invalid since these are in
2217 // screen coordinates.
2218 form_highlights_
.clear();
2220 if (visible_pages_
.size() == 0)
2221 first_visible_page_
= -1;
2223 first_visible_page_
= visible_pages_
.front();
2225 int most_visible_page
= first_visible_page_
;
2226 // Check if the next page is more visible than the first one.
2227 if (most_visible_page
!= -1 &&
2228 pages_
.size() > 0 &&
2229 most_visible_page
< static_cast<int>(pages_
.size()) - 1) {
2231 visible_rect
.Intersect(GetPageScreenRect(most_visible_page
));
2233 visible_rect
.Intersect(GetPageScreenRect(most_visible_page
+ 1));
2234 if (rc_next
.height() > rc_first
.height())
2235 most_visible_page
++;
2238 SetCurrentPage(most_visible_page
);
2241 bool PDFiumEngine::IsPageVisible(int index
) const {
2242 for (size_t i
= 0; i
< visible_pages_
.size(); ++i
) {
2243 if (visible_pages_
[i
] == index
)
2250 bool PDFiumEngine::CheckPageAvailable(int index
, std::vector
<int>* pending
) {
2251 if (!doc_
|| !form_
)
2254 if (static_cast<int>(pages_
.size()) > index
&& pages_
[index
]->available())
2257 if (!FPDFAvail_IsPageAvail(fpdf_availability_
, index
, &download_hints_
)) {
2259 for (j
= 0; j
< pending
->size(); ++j
) {
2260 if ((*pending
)[j
] == index
)
2264 if (j
== pending
->size())
2265 pending
->push_back(index
);
2269 if (static_cast<int>(pages_
.size()) > index
)
2270 pages_
[index
]->set_available(true);
2271 if (!default_page_size_
.GetArea())
2272 default_page_size_
= GetPageSize(index
);
2276 pp::Size
PDFiumEngine::GetPageSize(int index
) {
2278 double width_in_points
= 0;
2279 double height_in_points
= 0;
2280 int rv
= FPDF_GetPageSizeByIndex(
2281 doc_
, index
, &width_in_points
, &height_in_points
);
2284 int width_in_pixels
= static_cast<int>(
2285 width_in_points
* kPixelsPerInch
/ kPointsPerInch
);
2286 int height_in_pixels
= static_cast<int>(
2287 height_in_points
* kPixelsPerInch
/ kPointsPerInch
);
2288 if (current_rotation_
% 2 == 1)
2289 std::swap(width_in_pixels
, height_in_pixels
);
2290 size
= pp::Size(width_in_pixels
, height_in_pixels
);
2295 int PDFiumEngine::StartPaint(int page_index
, const pp::Rect
& dirty
) {
2296 // For the first time we hit paint, do nothing and just record the paint for
2297 // the next callback. This keeps the UI responsive in case the user is doing
2298 // a lot of scrolling.
2299 ProgressivePaint progressive
;
2300 progressive
.rect
= dirty
;
2301 progressive
.page_index
= page_index
;
2302 progressive
.bitmap
= NULL
;
2303 progressive
.painted_
= false;
2304 progressive_paints_
.push_back(progressive
);
2305 return progressive_paints_
.size() - 1;
2308 bool PDFiumEngine::ContinuePaint(int progressive_index
,
2309 pp::ImageData
* image_data
) {
2310 #if defined(OS_LINUX)
2311 g_last_instance_id
= client_
->GetPluginInstance()->pp_instance();
2315 int page_index
= progressive_paints_
[progressive_index
].page_index
;
2316 last_progressive_start_time_
= base::Time::Now();
2317 if (progressive_paints_
[progressive_index
].bitmap
) {
2318 rv
= FPDF_RenderPage_Continue(
2319 pages_
[page_index
]->GetPage(), static_cast<IFSDK_PAUSE
*>(this));
2321 pp::Rect dirty
= progressive_paints_
[progressive_index
].rect
;
2322 progressive_paints_
[progressive_index
].bitmap
= CreateBitmap(dirty
,
2324 int start_x
, start_y
, size_x
, size_y
;
2326 page_index
, dirty
, &start_x
, &start_y
, &size_x
, &size_y
);
2327 FPDFBitmap_FillRect(
2328 progressive_paints_
[progressive_index
].bitmap
, start_x
, start_y
, size_x
,
2329 size_y
, 255, 255, 255, 255);
2330 rv
= FPDF_RenderPageBitmap_Start(
2331 progressive_paints_
[progressive_index
].bitmap
,
2332 pages_
[page_index
]->GetPage(), start_x
, start_y
, size_x
, size_y
,
2334 GetRenderingFlags(), static_cast<IFSDK_PAUSE
*>(this));
2336 return rv
!= FPDF_RENDER_TOBECOUNTINUED
;
2339 void PDFiumEngine::FinishPaint(int progressive_index
,
2340 pp::ImageData
* image_data
) {
2341 int page_index
= progressive_paints_
[progressive_index
].page_index
;
2342 pp::Rect dirty_in_screen
= progressive_paints_
[progressive_index
].rect
;
2343 FPDF_BITMAP bitmap
= progressive_paints_
[progressive_index
].bitmap
;
2344 int start_x
, start_y
, size_x
, size_y
;
2346 page_index
, dirty_in_screen
, &start_x
, &start_y
, &size_x
, &size_y
);
2350 form_
, bitmap
, pages_
[page_index
]->GetPage(), start_x
, start_y
, size_x
,
2351 size_y
, current_rotation_
, GetRenderingFlags());
2353 FillPageSides(progressive_index
);
2355 // Paint the page shadows.
2356 PaintPageShadow(progressive_index
, image_data
);
2358 DrawSelections(progressive_index
, image_data
);
2360 FPDF_RenderPage_Close(pages_
[page_index
]->GetPage());
2361 FPDFBitmap_Destroy(bitmap
);
2362 progressive_paints_
.erase(progressive_paints_
.begin() + progressive_index
);
2364 client_
->DocumentPaintOccurred();
2367 void PDFiumEngine::CancelPaints() {
2368 for (size_t i
= 0; i
< progressive_paints_
.size(); ++i
) {
2369 FPDF_RenderPage_Close(pages_
[progressive_paints_
[i
].page_index
]->GetPage());
2370 FPDFBitmap_Destroy(progressive_paints_
[i
].bitmap
);
2372 progressive_paints_
.clear();
2375 void PDFiumEngine::FillPageSides(int progressive_index
) {
2376 int page_index
= progressive_paints_
[progressive_index
].page_index
;
2377 pp::Rect dirty_in_screen
= progressive_paints_
[progressive_index
].rect
;
2378 FPDF_BITMAP bitmap
= progressive_paints_
[progressive_index
].bitmap
;
2380 pp::Rect page_rect
= pages_
[page_index
]->rect();
2381 if (page_rect
.x() > 0) {
2383 page_rect
.y() - kPageShadowTop
,
2384 page_rect
.x() - kPageShadowLeft
,
2385 page_rect
.height() + kPageShadowTop
+
2386 kPageShadowBottom
+ kPageSeparatorThickness
);
2387 left
= GetScreenRect(left
).Intersect(dirty_in_screen
);
2389 FPDFBitmap_FillRect(
2390 bitmap
, left
.x() - dirty_in_screen
.x(),
2391 left
.y() - dirty_in_screen
.y(), left
.width(), left
.height(),
2392 kBackgroundColorR
, kBackgroundColorG
, kBackgroundColorB
,
2396 if (page_rect
.right() < document_size_
.width()) {
2397 pp::Rect
right(page_rect
.right() + kPageShadowRight
,
2398 page_rect
.y() - kPageShadowTop
,
2399 document_size_
.width() - page_rect
.right() -
2401 page_rect
.height() + kPageShadowTop
+
2402 kPageShadowBottom
+ kPageSeparatorThickness
);
2403 right
= GetScreenRect(right
).Intersect(dirty_in_screen
);
2405 FPDFBitmap_FillRect(
2406 bitmap
, right
.x() - dirty_in_screen
.x(),
2407 right
.y() - dirty_in_screen
.y(), right
.width(), right
.height(),
2408 kBackgroundColorR
, kBackgroundColorG
, kBackgroundColorB
,
2413 pp::Rect
bottom(page_rect
.x() - kPageShadowLeft
,
2414 page_rect
.bottom() + kPageShadowBottom
,
2415 page_rect
.width() + kPageShadowLeft
+ kPageShadowRight
,
2416 kPageSeparatorThickness
);
2417 bottom
= GetScreenRect(bottom
).Intersect(dirty_in_screen
);
2419 FPDFBitmap_FillRect(
2420 bitmap
, bottom
.x() - dirty_in_screen
.x(),
2421 bottom
.y() - dirty_in_screen
.y(), bottom
.width(), bottom
.height(),
2422 kBackgroundColorR
, kBackgroundColorG
, kBackgroundColorB
,
2426 void PDFiumEngine::PaintPageShadow(int progressive_index
,
2427 pp::ImageData
* image_data
) {
2428 int page_index
= progressive_paints_
[progressive_index
].page_index
;
2429 pp::Rect dirty_in_screen
= progressive_paints_
[progressive_index
].rect
;
2430 pp::Rect page_rect
= pages_
[page_index
]->rect();
2431 pp::Rect
shadow_rect(page_rect
);
2432 shadow_rect
.Inset(-kPageShadowLeft
, -kPageShadowTop
,
2433 -kPageShadowRight
, -kPageShadowBottom
);
2435 // Due to the rounding errors of the GetScreenRect it is possible to get
2436 // different size shadows on the left and right sides even they are defined
2437 // the same. To fix this issue let's calculate shadow rect and then shrink
2438 // it by the size of the shadows.
2439 shadow_rect
= GetScreenRect(shadow_rect
);
2440 page_rect
= shadow_rect
;
2442 page_rect
.Inset(static_cast<int>(ceil(kPageShadowLeft
* current_zoom_
)),
2443 static_cast<int>(ceil(kPageShadowTop
* current_zoom_
)),
2444 static_cast<int>(ceil(kPageShadowRight
* current_zoom_
)),
2445 static_cast<int>(ceil(kPageShadowBottom
* current_zoom_
)));
2447 DrawPageShadow(page_rect
, shadow_rect
, dirty_in_screen
, image_data
);
2450 void PDFiumEngine::DrawSelections(int progressive_index
,
2451 pp::ImageData
* image_data
) {
2452 int page_index
= progressive_paints_
[progressive_index
].page_index
;
2453 pp::Rect dirty_in_screen
= progressive_paints_
[progressive_index
].rect
;
2455 void* region
= NULL
;
2457 GetRegion(dirty_in_screen
.point(), image_data
, ®ion
, &stride
);
2459 std::vector
<pp::Rect
> highlighted_rects
;
2460 pp::Rect visible_rect
= GetVisibleRect();
2461 for (size_t k
= 0; k
< selection_
.size(); ++k
) {
2462 if (selection_
[k
].page_index() != page_index
)
2464 std::vector
<pp::Rect
> rects
= selection_
[k
].GetScreenRects(
2465 visible_rect
.point(), current_zoom_
, current_rotation_
);
2466 for (size_t j
= 0; j
< rects
.size(); ++j
) {
2467 pp::Rect visible_selection
= rects
[j
].Intersect(dirty_in_screen
);
2468 if (visible_selection
.IsEmpty())
2471 visible_selection
.Offset(
2472 -dirty_in_screen
.point().x(), -dirty_in_screen
.point().y());
2473 Highlight(region
, stride
, visible_selection
, &highlighted_rects
);
2477 for (size_t k
= 0; k
< form_highlights_
.size(); ++k
) {
2478 pp::Rect visible_selection
= form_highlights_
[k
].Intersect(dirty_in_screen
);
2479 if (visible_selection
.IsEmpty())
2482 visible_selection
.Offset(
2483 -dirty_in_screen
.point().x(), -dirty_in_screen
.point().y());
2484 Highlight(region
, stride
, visible_selection
, &highlighted_rects
);
2486 form_highlights_
.clear();
2489 void PDFiumEngine::PaintUnavailablePage(int page_index
,
2490 const pp::Rect
& dirty
,
2491 pp::ImageData
* image_data
) {
2492 int start_x
, start_y
, size_x
, size_y
;
2493 GetPDFiumRect(page_index
, dirty
, &start_x
, &start_y
, &size_x
, &size_y
);
2494 FPDF_BITMAP bitmap
= CreateBitmap(dirty
, image_data
);
2495 FPDFBitmap_FillRect(bitmap
, start_x
, start_y
, size_x
, size_y
,
2496 kPendingPageColorR
, kPendingPageColorG
, kPendingPageColorB
,
2497 kPendingPageColorA
);
2499 pp::Rect
loading_text_in_screen(
2500 pages_
[page_index
]->rect().width() / 2,
2501 pages_
[page_index
]->rect().y() + kLoadingTextVerticalOffset
, 0, 0);
2502 loading_text_in_screen
= GetScreenRect(loading_text_in_screen
);
2503 FPDFBitmap_Destroy(bitmap
);
2506 int PDFiumEngine::GetProgressiveIndex(int page_index
) const {
2507 for (size_t i
= 0; i
< progressive_paints_
.size(); ++i
) {
2508 if (progressive_paints_
[i
].page_index
== page_index
)
2514 FPDF_BITMAP
PDFiumEngine::CreateBitmap(const pp::Rect
& rect
,
2515 pp::ImageData
* image_data
) const {
2518 GetRegion(rect
.point(), image_data
, ®ion
, &stride
);
2521 return FPDFBitmap_CreateEx(
2522 rect
.width(), rect
.height(), FPDFBitmap_BGRx
, region
, stride
);
2525 void PDFiumEngine::GetPDFiumRect(
2526 int page_index
, const pp::Rect
& rect
, int* start_x
, int* start_y
,
2527 int* size_x
, int* size_y
) const {
2528 pp::Rect page_rect
= GetScreenRect(pages_
[page_index
]->rect());
2529 page_rect
.Offset(-rect
.x(), -rect
.y());
2531 *start_x
= page_rect
.x();
2532 *start_y
= page_rect
.y();
2533 *size_x
= page_rect
.width();
2534 *size_y
= page_rect
.height();
2537 int PDFiumEngine::GetRenderingFlags() const {
2538 int flags
= FPDF_LCD_TEXT
| FPDF_NO_CATCH
;
2539 if (render_grayscale_
)
2540 flags
|= FPDF_GRAYSCALE
;
2541 if (client_
->IsPrintPreview())
2542 flags
|= FPDF_PRINTING
;
2546 pp::Rect
PDFiumEngine::GetVisibleRect() const {
2548 rv
.set_x(static_cast<int>(position_
.x() / current_zoom_
));
2549 rv
.set_y(static_cast<int>(position_
.y() / current_zoom_
));
2550 rv
.set_width(static_cast<int>(ceil(plugin_size_
.width() / current_zoom_
)));
2551 rv
.set_height(static_cast<int>(ceil(plugin_size_
.height() / current_zoom_
)));
2555 pp::Rect
PDFiumEngine::GetPageScreenRect(int page_index
) const {
2556 // Since we use this rect for creating the PDFium bitmap, also include other
2557 // areas around the page that we might need to update such as the page
2558 // separator and the sides if the page is narrower than the document.
2559 return GetScreenRect(pp::Rect(
2561 pages_
[page_index
]->rect().y() - kPageShadowTop
,
2562 document_size_
.width(),
2563 pages_
[page_index
]->rect().height() + kPageShadowTop
+
2564 kPageShadowBottom
+ kPageSeparatorThickness
));
2567 pp::Rect
PDFiumEngine::GetScreenRect(const pp::Rect
& rect
) const {
2570 static_cast<int>(ceil(rect
.right() * current_zoom_
- position_
.x()));
2572 static_cast<int>(ceil(rect
.bottom() * current_zoom_
- position_
.y()));
2574 rv
.set_x(static_cast<int>(rect
.x() * current_zoom_
- position_
.x()));
2575 rv
.set_y(static_cast<int>(rect
.y() * current_zoom_
- position_
.y()));
2576 rv
.set_width(right
- rv
.x());
2577 rv
.set_height(bottom
- rv
.y());
2581 void PDFiumEngine::Highlight(void* buffer
,
2583 const pp::Rect
& rect
,
2584 std::vector
<pp::Rect
>* highlighted_rects
) {
2588 pp::Rect new_rect
= rect
;
2589 for (size_t i
= 0; i
< highlighted_rects
->size(); ++i
)
2590 new_rect
= new_rect
.Subtract((*highlighted_rects
)[i
]);
2592 highlighted_rects
->push_back(new_rect
);
2593 int l
= new_rect
.x();
2594 int t
= new_rect
.y();
2595 int w
= new_rect
.width();
2596 int h
= new_rect
.height();
2598 for (int y
= t
; y
< t
+ h
; ++y
) {
2599 for (int x
= l
; x
< l
+ w
; ++x
) {
2600 uint8
* pixel
= static_cast<uint8
*>(buffer
) + y
* stride
+ x
* 4;
2601 // This is our highlight color.
2602 pixel
[0] = static_cast<uint8
>(
2603 pixel
[0] * (kHighlightColorB
/ 255.0));
2604 pixel
[1] = static_cast<uint8
>(
2605 pixel
[1] * (kHighlightColorG
/ 255.0));
2606 pixel
[2] = static_cast<uint8
>(
2607 pixel
[2] * (kHighlightColorR
/ 255.0));
2612 PDFiumEngine::SelectionChangeInvalidator::SelectionChangeInvalidator(
2613 PDFiumEngine
* engine
) : engine_(engine
) {
2614 previous_origin_
= engine_
->GetVisibleRect().point();
2615 GetVisibleSelectionsScreenRects(&old_selections_
);
2618 PDFiumEngine::SelectionChangeInvalidator::~SelectionChangeInvalidator() {
2619 // Offset the old selections if the document scrolled since we recorded them.
2620 pp::Point offset
= previous_origin_
- engine_
->GetVisibleRect().point();
2621 for (size_t i
= 0; i
< old_selections_
.size(); ++i
)
2622 old_selections_
[i
].Offset(offset
);
2624 std::vector
<pp::Rect
> new_selections
;
2625 GetVisibleSelectionsScreenRects(&new_selections
);
2626 for (size_t i
= 0; i
< new_selections
.size(); ++i
) {
2627 for (size_t j
= 0; j
< old_selections_
.size(); ++j
) {
2628 if (new_selections
[i
] == old_selections_
[j
]) {
2629 // Rectangle was selected before and after, so no need to invalidate it.
2630 // Mark the rectangles by setting them to empty.
2631 new_selections
[i
] = old_selections_
[j
] = pp::Rect();
2636 for (size_t i
= 0; i
< old_selections_
.size(); ++i
) {
2637 if (!old_selections_
[i
].IsEmpty())
2638 engine_
->client_
->Invalidate(old_selections_
[i
]);
2640 for (size_t i
= 0; i
< new_selections
.size(); ++i
) {
2641 if (!new_selections
[i
].IsEmpty())
2642 engine_
->client_
->Invalidate(new_selections
[i
]);
2644 engine_
->OnSelectionChanged();
2648 PDFiumEngine::SelectionChangeInvalidator::GetVisibleSelectionsScreenRects(
2649 std::vector
<pp::Rect
>* rects
) {
2650 pp::Rect visible_rect
= engine_
->GetVisibleRect();
2651 for (size_t i
= 0; i
< engine_
->selection_
.size(); ++i
) {
2652 int page_index
= engine_
->selection_
[i
].page_index();
2653 if (!engine_
->IsPageVisible(page_index
))
2654 continue; // This selection is on a page that's not currently visible.
2656 std::vector
<pp::Rect
> selection_rects
=
2657 engine_
->selection_
[i
].GetScreenRects(
2658 visible_rect
.point(),
2659 engine_
->current_zoom_
,
2660 engine_
->current_rotation_
);
2661 rects
->insert(rects
->end(), selection_rects
.begin(), selection_rects
.end());
2665 void PDFiumEngine::DeviceToPage(int page_index
,
2670 *page_x
= *page_y
= 0;
2671 int temp_x
= static_cast<int>((device_x
+ position_
.x())/ current_zoom_
-
2672 pages_
[page_index
]->rect().x());
2673 int temp_y
= static_cast<int>((device_y
+ position_
.y())/ current_zoom_
-
2674 pages_
[page_index
]->rect().y());
2676 pages_
[page_index
]->GetPage(), 0, 0,
2677 pages_
[page_index
]->rect().width(), pages_
[page_index
]->rect().height(),
2678 current_rotation_
, temp_x
, temp_y
, page_x
, page_y
);
2681 int PDFiumEngine::GetVisiblePageIndex(FPDF_PAGE page
) {
2682 for (size_t i
= 0; i
< visible_pages_
.size(); ++i
) {
2683 if (pages_
[visible_pages_
[i
]]->GetPage() == page
)
2684 return visible_pages_
[i
];
2689 void PDFiumEngine::SetCurrentPage(int index
) {
2690 if (index
== most_visible_page_
|| !form_
)
2692 if (most_visible_page_
!= -1 && called_do_document_action_
) {
2693 FPDF_PAGE old_page
= pages_
[most_visible_page_
]->GetPage();
2694 FORM_DoPageAAction(old_page
, form_
, FPDFPAGE_AACTION_CLOSE
);
2696 most_visible_page_
= index
;
2697 #if defined(OS_LINUX)
2698 g_last_instance_id
= client_
->GetPluginInstance()->pp_instance();
2700 if (most_visible_page_
!= -1 && called_do_document_action_
) {
2701 FPDF_PAGE new_page
= pages_
[most_visible_page_
]->GetPage();
2702 FORM_DoPageAAction(new_page
, form_
, FPDFPAGE_AACTION_OPEN
);
2706 void PDFiumEngine::TransformPDFPageForPrinting(
2708 const PP_PrintSettings_Dev
& print_settings
) {
2709 // Get the source page width and height in points.
2710 const double src_page_width
= FPDF_GetPageWidth(page
);
2711 const double src_page_height
= FPDF_GetPageHeight(page
);
2713 const int src_page_rotation
= FPDFPage_GetRotation(page
);
2714 const bool fit_to_page
= print_settings
.print_scaling_option
==
2715 PP_PRINTSCALINGOPTION_FIT_TO_PRINTABLE_AREA
;
2717 pp::Size
page_size(print_settings
.paper_size
);
2718 pp::Rect
content_rect(print_settings
.printable_area
);
2719 const bool rotated
= (src_page_rotation
% 2 == 1);
2720 SetPageSizeAndContentRect(rotated
,
2721 src_page_width
> src_page_height
,
2725 // Compute the screen page width and height in points.
2726 const int actual_page_width
=
2727 rotated
? page_size
.height() : page_size
.width();
2728 const int actual_page_height
=
2729 rotated
? page_size
.width() : page_size
.height();
2731 const double scale_factor
= CalculateScaleFactor(fit_to_page
, content_rect
,
2733 src_page_height
, rotated
);
2735 // Calculate positions for the clip box.
2736 ClipBox source_clip_box
;
2737 CalculateClipBoxBoundary(page
, scale_factor
, rotated
, &source_clip_box
);
2739 // Calculate the translation offset values.
2740 double offset_x
= 0;
2741 double offset_y
= 0;
2743 CalculateScaledClipBoxOffset(content_rect
, source_clip_box
, &offset_x
,
2746 CalculateNonScaledClipBoxOffset(content_rect
, src_page_rotation
,
2747 actual_page_width
, actual_page_height
,
2748 source_clip_box
, &offset_x
, &offset_y
);
2751 // Reset the media box and crop box. When the page has crop box and media box,
2752 // the plugin will display the crop box contents and not the entire media box.
2753 // If the pages have different crop box values, the plugin will display a
2754 // document of multiple page sizes. To give better user experience, we
2755 // decided to have same crop box and media box values. Hence, the user will
2756 // see a list of uniform pages.
2757 FPDFPage_SetMediaBox(page
, 0, 0, page_size
.width(), page_size
.height());
2758 FPDFPage_SetCropBox(page
, 0, 0, page_size
.width(), page_size
.height());
2760 // Transformation is not required, return. Do this check only after updating
2761 // the media box and crop box. For more detailed information, please refer to
2762 // the comment block right before FPDF_SetMediaBox and FPDF_GetMediaBox calls.
2763 if (scale_factor
== 1.0 && offset_x
== 0 && offset_y
== 0)
2767 // All the positions have been calculated, now manipulate the PDF.
2768 FS_MATRIX matrix
= {static_cast<float>(scale_factor
),
2771 static_cast<float>(scale_factor
),
2772 static_cast<float>(offset_x
),
2773 static_cast<float>(offset_y
)};
2774 FS_RECTF cliprect
= {static_cast<float>(source_clip_box
.left
+offset_x
),
2775 static_cast<float>(source_clip_box
.top
+offset_y
),
2776 static_cast<float>(source_clip_box
.right
+offset_x
),
2777 static_cast<float>(source_clip_box
.bottom
+offset_y
)};
2778 FPDFPage_TransFormWithClip(page
, &matrix
, &cliprect
);
2779 FPDFPage_TransformAnnots(page
, scale_factor
, 0, 0, scale_factor
,
2780 offset_x
, offset_y
);
2783 void PDFiumEngine::DrawPageShadow(const pp::Rect
& page_rc
,
2784 const pp::Rect
& shadow_rc
,
2785 const pp::Rect
& clip_rc
,
2786 pp::ImageData
* image_data
) {
2787 pp::Rect
page_rect(page_rc
);
2788 page_rect
.Offset(page_offset_
);
2790 pp::Rect
shadow_rect(shadow_rc
);
2791 shadow_rect
.Offset(page_offset_
);
2793 pp::Rect
clip_rect(clip_rc
);
2794 clip_rect
.Offset(page_offset_
);
2796 // Page drop shadow parameters.
2797 const double factor
= 0.5;
2798 const uint32 background
= (kBackgroundColorA
<< 24) |
2799 (kBackgroundColorR
<< 16) |
2800 (kBackgroundColorG
<< 8) |
2802 uint32 depth
= std::max(
2803 std::max(page_rect
.x() - shadow_rect
.x(),
2804 page_rect
.y() - shadow_rect
.y()),
2805 std::max(shadow_rect
.right() - page_rect
.right(),
2806 shadow_rect
.bottom() - page_rect
.bottom()));
2807 depth
= static_cast<uint32
>(depth
* 1.5) + 1;
2809 // We need to check depth only to verify our copy of shadow matrix is correct.
2810 if (!page_shadow_
.get() || page_shadow_
->depth() != depth
)
2811 page_shadow_
.reset(new ShadowMatrix(depth
, factor
, background
));
2813 DCHECK(!image_data
->is_null());
2814 DrawShadow(image_data
, shadow_rect
, page_rect
, clip_rect
, *page_shadow_
);
2817 void PDFiumEngine::GetRegion(const pp::Point
& location
,
2818 pp::ImageData
* image_data
,
2820 int* stride
) const {
2821 if (image_data
->is_null()) {
2822 DCHECK(plugin_size_
.IsEmpty());
2827 char* buffer
= static_cast<char*>(image_data
->data());
2828 *stride
= image_data
->stride();
2830 pp::Point offset_location
= location
+ page_offset_
;
2831 // TODO: update this when we support BIDI and scrollbars can be on the left.
2833 !pp::Rect(page_offset_
, plugin_size_
).Contains(offset_location
)) {
2838 buffer
+= location
.y() * (*stride
);
2839 buffer
+= (location
.x() + page_offset_
.x()) * 4;
2843 void PDFiumEngine::OnSelectionChanged() {
2844 if (HasPermission(PDFEngine::PERMISSION_COPY
))
2845 pp::PDF::SetSelectedText(GetPluginInstance(), GetSelectedText().c_str());
2848 void PDFiumEngine::Form_Invalidate(FPDF_FORMFILLINFO
* param
,
2854 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
2855 int page_index
= engine
->GetVisiblePageIndex(page
);
2856 if (page_index
== -1) {
2857 // This can sometime happen when the page is closed because it went off
2858 // screen, and PDFium invalidates the control as it's being deleted.
2862 pp::Rect rect
= engine
->pages_
[page_index
]->PageToScreen(
2863 engine
->GetVisibleRect().point(), engine
->current_zoom_
, left
, top
, right
,
2864 bottom
, engine
->current_rotation_
);
2865 engine
->client_
->Invalidate(rect
);
2868 void PDFiumEngine::Form_OutputSelectedRect(FPDF_FORMFILLINFO
* param
,
2874 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
2875 int page_index
= engine
->GetVisiblePageIndex(page
);
2876 if (page_index
== -1) {
2880 pp::Rect rect
= engine
->pages_
[page_index
]->PageToScreen(
2881 engine
->GetVisibleRect().point(), engine
->current_zoom_
, left
, top
, right
,
2882 bottom
, engine
->current_rotation_
);
2883 engine
->form_highlights_
.push_back(rect
);
2886 void PDFiumEngine::Form_SetCursor(FPDF_FORMFILLINFO
* param
, int cursor_type
) {
2887 // We don't need this since it's not enough to change the cursor in all
2888 // scenarios. Instead, we check which form field we're under in OnMouseMove.
2891 int PDFiumEngine::Form_SetTimer(FPDF_FORMFILLINFO
* param
,
2893 TimerCallback timer_func
) {
2894 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
2895 engine
->timers_
[++engine
->next_timer_id_
] =
2896 std::pair
<int, TimerCallback
>(elapse
, timer_func
);
2897 engine
->client_
->ScheduleCallback(engine
->next_timer_id_
, elapse
);
2898 return engine
->next_timer_id_
;
2901 void PDFiumEngine::Form_KillTimer(FPDF_FORMFILLINFO
* param
, int timer_id
) {
2902 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
2903 engine
->timers_
.erase(timer_id
);
2906 FPDF_SYSTEMTIME
PDFiumEngine::Form_GetLocalTime(FPDF_FORMFILLINFO
* param
) {
2907 base::Time time
= base::Time::Now();
2908 base::Time::Exploded exploded
;
2909 time
.LocalExplode(&exploded
);
2912 rv
.wYear
= exploded
.year
;
2913 rv
.wMonth
= exploded
.month
;
2914 rv
.wDayOfWeek
= exploded
.day_of_week
;
2915 rv
.wDay
= exploded
.day_of_month
;
2916 rv
.wHour
= exploded
.hour
;
2917 rv
.wMinute
= exploded
.minute
;
2918 rv
.wSecond
= exploded
.second
;
2919 rv
.wMilliseconds
= exploded
.millisecond
;
2923 void PDFiumEngine::Form_OnChange(FPDF_FORMFILLINFO
* param
) {
2924 // Don't care about.
2927 FPDF_PAGE
PDFiumEngine::Form_GetPage(FPDF_FORMFILLINFO
* param
,
2928 FPDF_DOCUMENT document
,
2930 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
2931 if (page_index
< 0 || page_index
>= static_cast<int>(engine
->pages_
.size()))
2933 return engine
->pages_
[page_index
]->GetPage();
2936 FPDF_PAGE
PDFiumEngine::Form_GetCurrentPage(FPDF_FORMFILLINFO
* param
,
2937 FPDF_DOCUMENT document
) {
2938 // TODO(jam): find out what this is used for.
2939 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
2940 int index
= engine
->last_page_mouse_down_
;
2942 index
= engine
->GetMostVisiblePage();
2949 return engine
->pages_
[index
]->GetPage();
2952 int PDFiumEngine::Form_GetRotation(FPDF_FORMFILLINFO
* param
, FPDF_PAGE page
) {
2956 void PDFiumEngine::Form_ExecuteNamedAction(FPDF_FORMFILLINFO
* param
,
2957 FPDF_BYTESTRING named_action
) {
2958 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
2959 std::string
action(named_action
);
2960 if (action
== "Print") {
2961 engine
->client_
->Print();
2965 int index
= engine
->last_page_mouse_down_
;
2966 /* Don't try to calculate the most visible page if we don't have a left click
2967 before this event (this code originally copied Form_GetCurrentPage which of
2968 course needs to do that and which doesn't have recursion). This can end up
2969 causing infinite recursion. See http://crbug.com/240413 for more
2970 information. Either way, it's not necessary for the spec'd list of named
2973 index = engine->GetMostVisiblePage();
2978 // This is the only list of named actions per the spec (see 12.6.4.11). Adobe
2979 // Reader supports more, like FitWidth, but since they're not part of the spec
2980 // and we haven't got bugs about them, no need to now.
2981 if (action
== "NextPage") {
2982 engine
->client_
->ScrollToPage(index
+ 1);
2983 } else if (action
== "PrevPage") {
2984 engine
->client_
->ScrollToPage(index
- 1);
2985 } else if (action
== "FirstPage") {
2986 engine
->client_
->ScrollToPage(0);
2987 } else if (action
== "LastPage") {
2988 engine
->client_
->ScrollToPage(engine
->pages_
.size() - 1);
2992 void PDFiumEngine::Form_SetTextFieldFocus(FPDF_FORMFILLINFO
* param
,
2993 FPDF_WIDESTRING value
,
2994 FPDF_DWORD valueLen
,
2995 FPDF_BOOL is_focus
) {
2996 // Do nothing for now.
2997 // TODO(gene): use this signal to trigger OSK.
3000 void PDFiumEngine::Form_DoURIAction(FPDF_FORMFILLINFO
* param
,
3001 FPDF_BYTESTRING uri
) {
3002 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3003 engine
->client_
->NavigateTo(std::string(uri
), false);
3006 void PDFiumEngine::Form_DoGoToAction(FPDF_FORMFILLINFO
* param
,
3009 float* position_array
,
3010 int size_of_array
) {
3011 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3012 engine
->client_
->ScrollToPage(page_index
);
3015 int PDFiumEngine::Form_Alert(IPDF_JSPLATFORM
* param
,
3016 FPDF_WIDESTRING message
,
3017 FPDF_WIDESTRING title
,
3020 // See fpdfformfill.h for these values.
3023 ALERT_TYPE_OK_CANCEL
,
3025 ALERT_TYPE_YES_NO_CANCEL
3029 ALERT_RESULT_OK
= 1,
3030 ALERT_RESULT_CANCEL
,
3035 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3036 std::string message_str
=
3037 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(message
));
3038 if (type
== ALERT_TYPE_OK
) {
3039 engine
->client_
->Alert(message_str
);
3040 return ALERT_RESULT_OK
;
3043 bool rv
= engine
->client_
->Confirm(message_str
);
3044 if (type
== ALERT_TYPE_OK_CANCEL
)
3045 return rv
? ALERT_RESULT_OK
: ALERT_RESULT_CANCEL
;
3046 return rv
? ALERT_RESULT_YES
: ALERT_RESULT_NO
;
3049 void PDFiumEngine::Form_Beep(IPDF_JSPLATFORM
* param
, int type
) {
3050 // Beeps are annoying, and not possible using javascript, so ignore for now.
3053 int PDFiumEngine::Form_Response(IPDF_JSPLATFORM
* param
,
3054 FPDF_WIDESTRING question
,
3055 FPDF_WIDESTRING title
,
3056 FPDF_WIDESTRING default_response
,
3057 FPDF_WIDESTRING label
,
3061 std::string question_str
= base::UTF16ToUTF8(
3062 reinterpret_cast<const base::char16
*>(question
));
3063 std::string default_str
= base::UTF16ToUTF8(
3064 reinterpret_cast<const base::char16
*>(default_response
));
3066 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3067 std::string rv
= engine
->client_
->Prompt(question_str
, default_str
);
3068 base::string16 rv_16
= base::UTF8ToUTF16(rv
);
3069 int rv_bytes
= rv_16
.size() * sizeof(base::char16
);
3070 if (response
&& rv_bytes
<= length
)
3071 memcpy(response
, rv_16
.c_str(), rv_bytes
);
3075 int PDFiumEngine::Form_GetFilePath(IPDF_JSPLATFORM
* param
,
3078 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3079 std::string rv
= engine
->client_
->GetURL();
3080 if (file_path
&& rv
.size() <= static_cast<size_t>(length
))
3081 memcpy(file_path
, rv
.c_str(), rv
.size());
3085 void PDFiumEngine::Form_Mail(IPDF_JSPLATFORM
* param
,
3090 FPDF_WIDESTRING subject
,
3092 FPDF_WIDESTRING bcc
,
3093 FPDF_WIDESTRING message
) {
3094 DCHECK(length
== 0); // Don't handle attachments; no way with mailto.
3095 std::string to_str
=
3096 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(to
));
3097 std::string cc_str
=
3098 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(cc
));
3099 std::string bcc_str
=
3100 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(bcc
));
3101 std::string subject_str
=
3102 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(subject
));
3103 std::string message_str
=
3104 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(message
));
3106 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3107 engine
->client_
->Email(to_str
, cc_str
, bcc_str
, subject_str
, message_str
);
3110 void PDFiumEngine::Form_Print(IPDF_JSPLATFORM
* param
,
3115 FPDF_BOOL shrink_to_fit
,
3116 FPDF_BOOL print_as_image
,
3118 FPDF_BOOL annotations
) {
3119 // No way to pass the extra information to the print dialog using JavaScript.
3120 // Just opening it is fine for now.
3121 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3122 engine
->client_
->Print();
3125 void PDFiumEngine::Form_SubmitForm(IPDF_JSPLATFORM
* param
,
3128 FPDF_WIDESTRING url
) {
3129 std::string url_str
=
3130 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(url
));
3131 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3132 engine
->client_
->SubmitForm(url_str
, form_data
, length
);
3135 void PDFiumEngine::Form_GotoPage(IPDF_JSPLATFORM
* param
,
3137 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3138 engine
->client_
->ScrollToPage(page_number
);
3141 int PDFiumEngine::Form_Browse(IPDF_JSPLATFORM
* param
,
3144 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3145 std::string path
= engine
->client_
->ShowFileSelectionDialog();
3146 if (path
.size() + 1 <= static_cast<size_t>(length
))
3147 memcpy(file_path
, &path
[0], path
.size() + 1);
3148 return path
.size() + 1;
3151 FPDF_BOOL
PDFiumEngine::Pause_NeedToPauseNow(IFSDK_PAUSE
* param
) {
3152 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3153 return (base::Time::Now() - engine
->last_progressive_start_time_
).
3154 InMilliseconds() > engine
->progressive_paint_timeout_
;
3157 ScopedUnsupportedFeature::ScopedUnsupportedFeature(PDFiumEngine
* engine
)
3158 : engine_(engine
), old_engine_(g_engine_for_unsupported
) {
3159 g_engine_for_unsupported
= engine_
;
3162 ScopedUnsupportedFeature::~ScopedUnsupportedFeature() {
3163 g_engine_for_unsupported
= old_engine_
;
3166 PDFEngineExports
* PDFEngineExports::Create() {
3167 return new PDFiumEngineExports
;
3172 int CalculatePosition(FPDF_PAGE page
,
3173 const PDFiumEngineExports::RenderingSettings
& settings
,
3175 int page_width
= static_cast<int>(
3176 FPDF_GetPageWidth(page
) * settings
.dpi_x
/ kPointsPerInch
);
3177 int page_height
= static_cast<int>(
3178 FPDF_GetPageHeight(page
) * settings
.dpi_y
/ kPointsPerInch
);
3180 // Start by assuming that we will draw exactly to the bounds rect
3182 *dest
= settings
.bounds
;
3184 int rotate
= 0; // normal orientation.
3186 // Auto-rotate landscape pages to print correctly.
3187 if (settings
.autorotate
&&
3188 (dest
->width() > dest
->height()) != (page_width
> page_height
)) {
3189 rotate
= 1; // 90 degrees clockwise.
3190 std::swap(page_width
, page_height
);
3193 // See if we need to scale the output
3194 bool scale_to_bounds
= false;
3195 if (settings
.fit_to_bounds
&&
3196 ((page_width
> dest
->width()) || (page_height
> dest
->height()))) {
3197 scale_to_bounds
= true;
3198 } else if (settings
.stretch_to_bounds
&&
3199 ((page_width
< dest
->width()) || (page_height
< dest
->height()))) {
3200 scale_to_bounds
= true;
3203 if (scale_to_bounds
) {
3204 // If we need to maintain aspect ratio, calculate the actual width and
3206 if (settings
.keep_aspect_ratio
) {
3207 double scale_factor_x
= page_width
;
3208 scale_factor_x
/= dest
->width();
3209 double scale_factor_y
= page_height
;
3210 scale_factor_y
/= dest
->height();
3211 if (scale_factor_x
> scale_factor_y
) {
3212 dest
->set_height(page_height
/ scale_factor_x
);
3214 dest
->set_width(page_width
/ scale_factor_y
);
3218 // We are not scaling to bounds. Draw in the actual page size. If the
3219 // actual page size is larger than the bounds, the output will be
3221 dest
->set_width(page_width
);
3222 dest
->set_height(page_height
);
3225 if (settings
.center_in_bounds
) {
3226 pp::Point
offset((settings
.bounds
.width() - dest
->width()) / 2,
3227 (settings
.bounds
.height() - dest
->height()) / 2);
3228 dest
->Offset(offset
);
3236 bool PDFiumEngineExports::RenderPDFPageToDC(const void* pdf_buffer
,
3239 const RenderingSettings
& settings
,
3241 FPDF_DOCUMENT doc
= FPDF_LoadMemDocument(pdf_buffer
, buffer_size
, NULL
);
3244 FPDF_PAGE page
= FPDF_LoadPage(doc
, page_number
);
3246 FPDF_CloseDocument(doc
);
3249 RenderingSettings new_settings
= settings
;
3250 // calculate the page size
3251 if (new_settings
.dpi_x
== -1)
3252 new_settings
.dpi_x
= GetDeviceCaps(dc
, LOGPIXELSX
);
3253 if (new_settings
.dpi_y
== -1)
3254 new_settings
.dpi_y
= GetDeviceCaps(dc
, LOGPIXELSY
);
3257 int rotate
= CalculatePosition(page
, new_settings
, &dest
);
3259 int save_state
= SaveDC(dc
);
3260 // The caller wanted all drawing to happen within the bounds specified.
3261 // Based on scale calculations, our destination rect might be larger
3262 // than the bounds. Set the clip rect to the bounds.
3263 IntersectClipRect(dc
, settings
.bounds
.x(), settings
.bounds
.y(),
3264 settings
.bounds
.x() + settings
.bounds
.width(),
3265 settings
.bounds
.y() + settings
.bounds
.height());
3267 // A temporary hack. PDFs generated by Cairo (used by Chrome OS to generate
3268 // a PDF output from a webpage) result in very large metafiles and the
3269 // rendering using FPDF_RenderPage is incorrect. In this case, render as a
3270 // bitmap. Note that this code does not kick in for PDFs printed from Chrome
3271 // because in that case we create a temp PDF first before printing and this
3272 // temp PDF does not have a creator string that starts with "cairo".
3273 base::string16 creator
;
3274 size_t buffer_bytes
= FPDF_GetMetaText(doc
, "Creator", NULL
, 0);
3275 if (buffer_bytes
> 1) {
3276 FPDF_GetMetaText(doc
, "Creator", WriteInto(&creator
, buffer_bytes
),
3279 bool use_bitmap
= false;
3280 if (StartsWith(creator
, L
"cairo", false))
3283 // Another temporary hack. Some PDFs seems to render very slowly if
3284 // FPDF_RenderPage is directly used on a printer DC. I suspect it is
3285 // because of the code to talk Postscript directly to the printer if
3286 // the printer supports this. Need to discuss this with PDFium. For now,
3287 // render to a bitmap and then blit the bitmap to the DC if we have been
3288 // supplied a printer DC.
3289 int device_type
= GetDeviceCaps(dc
, TECHNOLOGY
);
3291 (device_type
== DT_RASPRINTER
) || (device_type
== DT_PLOTTER
)) {
3292 FPDF_BITMAP bitmap
= FPDFBitmap_Create(dest
.width(), dest
.height(),
3295 FPDFBitmap_FillRect(bitmap
, 0, 0, dest
.width(), dest
.height(), 255, 255,
3297 FPDF_RenderPageBitmap(
3298 bitmap
, page
, 0, 0, dest
.width(), dest
.height(), rotate
,
3299 FPDF_ANNOT
| FPDF_PRINTING
| FPDF_NO_CATCH
);
3300 int stride
= FPDFBitmap_GetStride(bitmap
);
3302 memset(&bmi
, 0, sizeof(bmi
));
3303 bmi
.bmiHeader
.biSize
= sizeof(BITMAPINFOHEADER
);
3304 bmi
.bmiHeader
.biWidth
= dest
.width();
3305 bmi
.bmiHeader
.biHeight
= -dest
.height(); // top-down image
3306 bmi
.bmiHeader
.biPlanes
= 1;
3307 bmi
.bmiHeader
.biBitCount
= 32;
3308 bmi
.bmiHeader
.biCompression
= BI_RGB
;
3309 bmi
.bmiHeader
.biSizeImage
= stride
* dest
.height();
3310 StretchDIBits(dc
, dest
.x(), dest
.y(), dest
.width(), dest
.height(),
3311 0, 0, dest
.width(), dest
.height(),
3312 FPDFBitmap_GetBuffer(bitmap
), &bmi
, DIB_RGB_COLORS
, SRCCOPY
);
3313 FPDFBitmap_Destroy(bitmap
);
3315 FPDF_RenderPage(dc
, page
, dest
.x(), dest
.y(), dest
.width(), dest
.height(),
3316 rotate
, FPDF_ANNOT
| FPDF_PRINTING
| FPDF_NO_CATCH
);
3318 RestoreDC(dc
, save_state
);
3319 FPDF_ClosePage(page
);
3320 FPDF_CloseDocument(doc
);
3325 bool PDFiumEngineExports::RenderPDFPageToBitmap(
3326 const void* pdf_buffer
,
3327 int pdf_buffer_size
,
3329 const RenderingSettings
& settings
,
3330 void* bitmap_buffer
) {
3331 FPDF_DOCUMENT doc
= FPDF_LoadMemDocument(pdf_buffer
, pdf_buffer_size
, NULL
);
3334 FPDF_PAGE page
= FPDF_LoadPage(doc
, page_number
);
3336 FPDF_CloseDocument(doc
);
3341 int rotate
= CalculatePosition(page
, settings
, &dest
);
3343 FPDF_BITMAP bitmap
=
3344 FPDFBitmap_CreateEx(settings
.bounds
.width(), settings
.bounds
.height(),
3345 FPDFBitmap_BGRA
, bitmap_buffer
,
3346 settings
.bounds
.width() * 4);
3348 FPDFBitmap_FillRect(bitmap
, 0, 0, settings
.bounds
.width(),
3349 settings
.bounds
.height(), 255, 255, 255, 255);
3350 // Shift top-left corner of bounds to (0, 0) if it's not there.
3351 dest
.set_point(dest
.point() - settings
.bounds
.point());
3352 FPDF_RenderPageBitmap(
3353 bitmap
, page
, dest
.x(), dest
.y(), dest
.width(), dest
.height(), rotate
,
3354 FPDF_ANNOT
| FPDF_PRINTING
| FPDF_NO_CATCH
);
3355 FPDFBitmap_Destroy(bitmap
);
3356 FPDF_ClosePage(page
);
3357 FPDF_CloseDocument(doc
);
3361 bool PDFiumEngineExports::GetPDFDocInfo(const void* pdf_buffer
,
3364 double* max_page_width
) {
3365 FPDF_DOCUMENT doc
= FPDF_LoadMemDocument(pdf_buffer
, buffer_size
, NULL
);
3368 int page_count_local
= FPDF_GetPageCount(doc
);
3370 *page_count
= page_count_local
;
3372 if (max_page_width
) {
3373 *max_page_width
= 0;
3374 for (int page_number
= 0; page_number
< page_count_local
; page_number
++) {
3375 double page_width
= 0;
3376 double page_height
= 0;
3377 FPDF_GetPageSizeByIndex(doc
, page_number
, &page_width
, &page_height
);
3378 if (page_width
> *max_page_width
) {
3379 *max_page_width
= page_width
;
3383 FPDF_CloseDocument(doc
);
3387 } // namespace chrome_pdf