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/i18n/icu_encoding_detection.h"
10 #include "base/i18n/icu_string_conversions.h"
11 #include "base/json/json_writer.h"
12 #include "base/logging.h"
13 #include "base/memory/scoped_ptr.h"
14 #include "base/numerics/safe_conversions.h"
15 #include "base/stl_util.h"
16 #include "base/strings/string_number_conversions.h"
17 #include "base/strings/string_piece.h"
18 #include "base/strings/string_util.h"
19 #include "base/strings/utf_string_conversions.h"
20 #include "base/values.h"
21 #include "pdf/draw_utils.h"
22 #include "pdf/pdfium/pdfium_api_string_buffer_adapter.h"
23 #include "pdf/pdfium/pdfium_mem_buffer_file_read.h"
24 #include "pdf/pdfium/pdfium_mem_buffer_file_write.h"
25 #include "ppapi/c/pp_errors.h"
26 #include "ppapi/c/pp_input_event.h"
27 #include "ppapi/c/ppb_core.h"
28 #include "ppapi/c/private/ppb_pdf.h"
29 #include "ppapi/cpp/dev/memory_dev.h"
30 #include "ppapi/cpp/input_event.h"
31 #include "ppapi/cpp/instance.h"
32 #include "ppapi/cpp/module.h"
33 #include "ppapi/cpp/private/pdf.h"
34 #include "ppapi/cpp/trusted/browser_font_trusted.h"
35 #include "ppapi/cpp/url_response_info.h"
36 #include "ppapi/cpp/var.h"
37 #include "ppapi/cpp/var_dictionary.h"
38 #include "printing/units.h"
39 #include "third_party/pdfium/public/fpdf_edit.h"
40 #include "third_party/pdfium/public/fpdf_ext.h"
41 #include "third_party/pdfium/public/fpdf_flatten.h"
42 #include "third_party/pdfium/public/fpdf_ppo.h"
43 #include "third_party/pdfium/public/fpdf_save.h"
44 #include "third_party/pdfium/public/fpdf_searchex.h"
45 #include "third_party/pdfium/public/fpdf_sysfontinfo.h"
46 #include "third_party/pdfium/public/fpdf_transformpage.h"
47 #include "ui/events/keycodes/keyboard_codes.h"
49 using printing::ConvertUnit
;
50 using printing::ConvertUnitDouble
;
51 using printing::kPointsPerInch
;
52 using printing::kPixelsPerInch
;
54 namespace chrome_pdf
{
58 #define kPageShadowTop 3
59 #define kPageShadowBottom 7
60 #define kPageShadowLeft 5
61 #define kPageShadowRight 5
63 #define kPageSeparatorThickness 4
64 #define kHighlightColorR 153
65 #define kHighlightColorG 193
66 #define kHighlightColorB 218
68 const uint32 kPendingPageColor
= 0xFFEEEEEE;
70 #define kFormHighlightColor 0xFFE4DD
71 #define kFormHighlightAlpha 100
73 #define kMaxPasswordTries 3
76 // http://www.adobe.com/devnet/acrobat/pdfs/pdf_reference_1-7.pdf
77 #define kPDFPermissionPrintLowQualityMask 1 << 2
78 #define kPDFPermissionPrintHighQualityMask 1 << 11
79 #define kPDFPermissionCopyMask 1 << 4
80 #define kPDFPermissionCopyAccessibleMask 1 << 9
82 #define kLoadingTextVerticalOffset 50
84 // The maximum amount of time we'll spend doing a paint before we give back
85 // control of the thread.
86 #define kMaxProgressivePaintTimeMs 50
88 // The maximum amount of time we'll spend doing the first paint. This is less
89 // than the above to keep things smooth if the user is scrolling quickly. We
90 // try painting a little because with accelerated compositing, we get flushes
91 // only every 16 ms. If we were to wait until the next flush to paint the rest
92 // of the pdf, we would never get to draw the pdf and would only draw the
93 // scrollbars. This value is picked to give enough time for gpu related code to
94 // do its thing and still fit within the timelimit for 60Hz. For the
95 // non-composited case, this doesn't make things worse since we're still
96 // painting the scrollbars > 60 Hz.
97 #define kMaxInitialProgressivePaintTimeMs 10
106 std::vector
<uint32_t> GetPageNumbersFromPrintPageNumberRange(
107 const PP_PrintPageNumberRange_Dev
* page_ranges
,
108 uint32_t page_range_count
) {
109 std::vector
<uint32_t> page_numbers
;
110 for (uint32_t index
= 0; index
< page_range_count
; ++index
) {
111 for (uint32_t page_number
= page_ranges
[index
].first_page_number
;
112 page_number
<= page_ranges
[index
].last_page_number
; ++page_number
) {
113 page_numbers
.push_back(page_number
);
119 #if defined(OS_LINUX)
121 PP_Instance g_last_instance_id
;
123 struct PDFFontSubstitution
{
124 const char* pdf_name
;
130 PP_BrowserFont_Trusted_Weight
WeightToBrowserFontTrustedWeight(int weight
) {
131 static_assert(PP_BROWSERFONT_TRUSTED_WEIGHT_100
== 0,
132 "PP_BrowserFont_Trusted_Weight min");
133 static_assert(PP_BROWSERFONT_TRUSTED_WEIGHT_900
== 8,
134 "PP_BrowserFont_Trusted_Weight max");
135 const int kMinimumWeight
= 100;
136 const int kMaximumWeight
= 900;
137 int normalized_weight
=
138 std::min(std::max(weight
, kMinimumWeight
), kMaximumWeight
);
139 normalized_weight
= (normalized_weight
/ 100) - 1;
140 return static_cast<PP_BrowserFont_Trusted_Weight
>(normalized_weight
);
143 // This list is for CPWL_FontMap::GetDefaultFontByCharset().
144 // We pretend to have these font natively and let the browser (or underlying
145 // fontconfig) to pick the proper font on the system.
146 void EnumFonts(struct _FPDF_SYSFONTINFO
* sysfontinfo
, void* mapper
) {
147 FPDF_AddInstalledFont(mapper
, "Arial", FXFONT_DEFAULT_CHARSET
);
149 const FPDF_CharsetFontMap
* font_map
= FPDF_GetDefaultTTFMap();
150 for (; font_map
->charset
!= -1; ++font_map
) {
151 FPDF_AddInstalledFont(mapper
, font_map
->fontname
, font_map
->charset
);
155 const PDFFontSubstitution PDFFontSubstitutions
[] = {
156 {"Courier", "Courier New", false, false},
157 {"Courier-Bold", "Courier New", true, false},
158 {"Courier-BoldOblique", "Courier New", true, true},
159 {"Courier-Oblique", "Courier New", false, true},
160 {"Helvetica", "Arial", false, false},
161 {"Helvetica-Bold", "Arial", true, false},
162 {"Helvetica-BoldOblique", "Arial", true, true},
163 {"Helvetica-Oblique", "Arial", false, true},
164 {"Times-Roman", "Times New Roman", false, false},
165 {"Times-Bold", "Times New Roman", true, false},
166 {"Times-BoldItalic", "Times New Roman", true, true},
167 {"Times-Italic", "Times New Roman", false, true},
169 // MS P?(Mincho|Gothic) are the most notable fonts in Japanese PDF files
170 // without embedding the glyphs. Sometimes the font names are encoded
171 // in Japanese Windows's locale (CP932/Shift_JIS) without space.
172 // Most Linux systems don't have the exact font, but for outsourcing
173 // fontconfig to find substitutable font in the system, we pass ASCII
175 {"MS-PGothic", "MS PGothic", false, false},
176 {"MS-Gothic", "MS Gothic", false, false},
177 {"MS-PMincho", "MS PMincho", false, false},
178 {"MS-Mincho", "MS Mincho", false, false},
179 // MS PGothic in Shift_JIS encoding.
180 {"\x82\x6C\x82\x72\x82\x6F\x83\x53\x83\x56\x83\x62\x83\x4E",
181 "MS PGothic", false, false},
182 // MS Gothic in Shift_JIS encoding.
183 {"\x82\x6C\x82\x72\x83\x53\x83\x56\x83\x62\x83\x4E",
184 "MS Gothic", false, false},
185 // MS PMincho in Shift_JIS encoding.
186 {"\x82\x6C\x82\x72\x82\x6F\x96\xBE\x92\xA9",
187 "MS PMincho", false, false},
188 // MS Mincho in Shift_JIS encoding.
189 {"\x82\x6C\x82\x72\x96\xBE\x92\xA9",
190 "MS Mincho", false, false},
193 void* MapFont(struct _FPDF_SYSFONTINFO
*, int weight
, int italic
,
194 int charset
, int pitch_family
, const char* face
, int* exact
) {
195 // Do not attempt to map fonts if pepper is not initialized (for privet local
197 // TODO(noamsml): Real font substitution (http://crbug.com/391978)
198 if (!pp::Module::Get())
201 pp::BrowserFontDescription description
;
203 // Pretend the system does not have the Symbol font to force a fallback to
204 // the built in Symbol font in CFX_FontMapper::FindSubstFont().
205 if (strcmp(face
, "Symbol") == 0)
208 if (pitch_family
& FXFONT_FF_FIXEDPITCH
) {
209 description
.set_family(PP_BROWSERFONT_TRUSTED_FAMILY_MONOSPACE
);
210 } else if (pitch_family
& FXFONT_FF_ROMAN
) {
211 description
.set_family(PP_BROWSERFONT_TRUSTED_FAMILY_SERIF
);
214 // Map from the standard PDF fonts to TrueType font names.
216 for (i
= 0; i
< arraysize(PDFFontSubstitutions
); ++i
) {
217 if (strcmp(face
, PDFFontSubstitutions
[i
].pdf_name
) == 0) {
218 description
.set_face(PDFFontSubstitutions
[i
].face
);
219 if (PDFFontSubstitutions
[i
].bold
)
220 description
.set_weight(PP_BROWSERFONT_TRUSTED_WEIGHT_BOLD
);
221 if (PDFFontSubstitutions
[i
].italic
)
222 description
.set_italic(true);
227 if (i
== arraysize(PDFFontSubstitutions
)) {
228 // Convert to UTF-8 before calling set_face().
229 std::string face_utf8
;
230 if (base::IsStringUTF8(face
)) {
233 std::string encoding
;
234 if (base::DetectEncoding(face
, &encoding
)) {
235 // ConvertToUtf8AndNormalize() clears |face_utf8| on failure.
236 base::ConvertToUtf8AndNormalize(face
, encoding
, &face_utf8
);
240 if (face_utf8
.empty())
243 description
.set_face(face_utf8
);
244 description
.set_weight(WeightToBrowserFontTrustedWeight(weight
));
245 description
.set_italic(italic
> 0);
248 if (!pp::PDF::IsAvailable()) {
253 PP_Resource font_resource
= pp::PDF::GetFontFileWithFallback(
254 pp::InstanceHandle(g_last_instance_id
),
255 &description
.pp_font_description(),
256 static_cast<PP_PrivateFontCharset
>(charset
));
257 long res_id
= font_resource
;
258 return reinterpret_cast<void*>(res_id
);
261 unsigned long GetFontData(struct _FPDF_SYSFONTINFO
*, void* font_id
,
262 unsigned int table
, unsigned char* buffer
,
263 unsigned long buf_size
) {
264 if (!pp::PDF::IsAvailable()) {
269 uint32_t size
= buf_size
;
270 long res_id
= reinterpret_cast<long>(font_id
);
271 if (!pp::PDF::GetFontTableForPrivateFontFile(res_id
, table
, buffer
, &size
))
276 void DeleteFont(struct _FPDF_SYSFONTINFO
*, void* font_id
) {
277 long res_id
= reinterpret_cast<long>(font_id
);
278 pp::Module::Get()->core()->ReleaseResource(res_id
);
281 FPDF_SYSFONTINFO g_font_info
= {
292 #endif // defined(OS_LINUX)
294 PDFiumEngine
* g_engine_for_unsupported
;
296 void Unsupported_Handler(UNSUPPORT_INFO
*, int type
) {
297 if (!g_engine_for_unsupported
) {
302 g_engine_for_unsupported
->UnsupportedFeature(type
);
305 UNSUPPORT_INFO g_unsuppored_info
= {
310 // Set the destination page size and content area in points based on source
311 // page rotation and orientation.
313 // |rotated| True if source page is rotated 90 degree or 270 degree.
314 // |is_src_page_landscape| is true if the source page orientation is landscape.
315 // |page_size| has the actual destination page size in points.
316 // |content_rect| has the actual destination page printable area values in
318 void SetPageSizeAndContentRect(bool rotated
,
319 bool is_src_page_landscape
,
321 pp::Rect
* content_rect
) {
322 bool is_dst_page_landscape
= page_size
->width() > page_size
->height();
323 bool page_orientation_mismatched
= is_src_page_landscape
!=
324 is_dst_page_landscape
;
325 bool rotate_dst_page
= rotated
^ page_orientation_mismatched
;
326 if (rotate_dst_page
) {
327 page_size
->SetSize(page_size
->height(), page_size
->width());
328 content_rect
->SetRect(content_rect
->y(), content_rect
->x(),
329 content_rect
->height(), content_rect
->width());
333 // Calculate the scale factor between |content_rect| and a page of size
334 // |src_width| x |src_height|.
336 // |scale_to_fit| is true, if we need to calculate the scale factor.
337 // |content_rect| specifies the printable area of the destination page, with
338 // origin at left-bottom. Values are in points.
339 // |src_width| specifies the source page width in points.
340 // |src_height| specifies the source page height in points.
341 // |rotated| True if source page is rotated 90 degree or 270 degree.
342 double CalculateScaleFactor(bool scale_to_fit
,
343 const pp::Rect
& content_rect
,
344 double src_width
, double src_height
, bool rotated
) {
345 if (!scale_to_fit
|| src_width
== 0 || src_height
== 0)
348 double actual_source_page_width
= rotated
? src_height
: src_width
;
349 double actual_source_page_height
= rotated
? src_width
: src_height
;
350 double ratio_x
= static_cast<double>(content_rect
.width()) /
351 actual_source_page_width
;
352 double ratio_y
= static_cast<double>(content_rect
.height()) /
353 actual_source_page_height
;
354 return std::min(ratio_x
, ratio_y
);
357 // Compute source clip box boundaries based on the crop box / media box of
358 // source page and scale factor.
360 // |page| Handle to the source page. Returned by FPDF_LoadPage function.
361 // |scale_factor| specifies the scale factor that should be applied to source
362 // clip box boundaries.
363 // |rotated| True if source page is rotated 90 degree or 270 degree.
364 // |clip_box| out param to hold the computed source clip box values.
365 void CalculateClipBoxBoundary(FPDF_PAGE page
, double scale_factor
, bool rotated
,
367 if (!FPDFPage_GetCropBox(page
, &clip_box
->left
, &clip_box
->bottom
,
368 &clip_box
->right
, &clip_box
->top
)) {
369 if (!FPDFPage_GetMediaBox(page
, &clip_box
->left
, &clip_box
->bottom
,
370 &clip_box
->right
, &clip_box
->top
)) {
371 // Make the default size to be letter size (8.5" X 11"). We are just
372 // following the PDFium way of handling these corner cases. PDFium always
373 // consider US-Letter as the default page size.
374 float paper_width
= 612;
375 float paper_height
= 792;
377 clip_box
->bottom
= 0;
378 clip_box
->right
= rotated
? paper_height
: paper_width
;
379 clip_box
->top
= rotated
? paper_width
: paper_height
;
382 clip_box
->left
*= scale_factor
;
383 clip_box
->right
*= scale_factor
;
384 clip_box
->bottom
*= scale_factor
;
385 clip_box
->top
*= scale_factor
;
388 // Calculate the clip box translation offset for a page that does need to be
389 // scaled. All parameters are in points.
391 // |content_rect| specifies the printable area of the destination page, with
392 // origin at left-bottom.
393 // |source_clip_box| specifies the source clip box positions, relative to
394 // origin at left-bottom.
395 // |offset_x| and |offset_y| will contain the final translation offsets for the
396 // source clip box, relative to origin at left-bottom.
397 void CalculateScaledClipBoxOffset(const pp::Rect
& content_rect
,
398 const ClipBox
& source_clip_box
,
399 double* offset_x
, double* offset_y
) {
400 const float clip_box_width
= source_clip_box
.right
- source_clip_box
.left
;
401 const float clip_box_height
= source_clip_box
.top
- source_clip_box
.bottom
;
403 // Center the intended clip region to real clip region.
404 *offset_x
= (content_rect
.width() - clip_box_width
) / 2 + content_rect
.x() -
405 source_clip_box
.left
;
406 *offset_y
= (content_rect
.height() - clip_box_height
) / 2 + content_rect
.y() -
407 source_clip_box
.bottom
;
410 // Calculate the clip box offset for a page that does not need to be scaled.
411 // All parameters are in points.
413 // |content_rect| specifies the printable area of the destination page, with
414 // origin at left-bottom.
415 // |rotation| specifies the source page rotation values which are N / 90
417 // |page_width| specifies the screen destination page width.
418 // |page_height| specifies the screen destination page height.
419 // |source_clip_box| specifies the source clip box positions, relative to origin
421 // |offset_x| and |offset_y| will contain the final translation offsets for the
422 // source clip box, relative to origin at left-bottom.
423 void CalculateNonScaledClipBoxOffset(const pp::Rect
& content_rect
, int rotation
,
424 int page_width
, int page_height
,
425 const ClipBox
& source_clip_box
,
426 double* offset_x
, double* offset_y
) {
427 // Align the intended clip region to left-top corner of real clip region.
430 *offset_x
= -1 * source_clip_box
.left
;
431 *offset_y
= page_height
- source_clip_box
.top
;
435 *offset_y
= -1 * source_clip_box
.bottom
;
438 *offset_x
= page_width
- source_clip_box
.right
;
442 *offset_x
= page_height
- source_clip_box
.right
;
443 *offset_y
= page_width
- source_clip_box
.top
;
451 // This formats a string with special 0xfffe end-of-line hyphens the same way
452 // as Adobe Reader. When a hyphen is encountered, the next non-CR/LF whitespace
453 // becomes CR+LF and the hyphen is erased. If there is no whitespace between
454 // two hyphens, the latter hyphen is erased and ignored.
455 void FormatStringWithHyphens(base::string16
* text
) {
456 // First pass marks all the hyphen positions.
457 struct HyphenPosition
{
458 HyphenPosition() : position(0), next_whitespace_position(0) {}
460 size_t next_whitespace_position
; // 0 for none
462 std::vector
<HyphenPosition
> hyphen_positions
;
463 HyphenPosition current_hyphen_position
;
464 bool current_hyphen_position_is_valid
= false;
465 const base::char16 kPdfiumHyphenEOL
= 0xfffe;
467 for (size_t i
= 0; i
< text
->size(); ++i
) {
468 const base::char16
& current_char
= (*text
)[i
];
469 if (current_char
== kPdfiumHyphenEOL
) {
470 if (current_hyphen_position_is_valid
)
471 hyphen_positions
.push_back(current_hyphen_position
);
472 current_hyphen_position
= HyphenPosition();
473 current_hyphen_position
.position
= i
;
474 current_hyphen_position_is_valid
= true;
475 } else if (base::IsUnicodeWhitespace(current_char
)) {
476 if (current_hyphen_position_is_valid
) {
477 if (current_char
!= L
'\r' && current_char
!= L
'\n')
478 current_hyphen_position
.next_whitespace_position
= i
;
479 hyphen_positions
.push_back(current_hyphen_position
);
480 current_hyphen_position_is_valid
= false;
484 if (current_hyphen_position_is_valid
)
485 hyphen_positions
.push_back(current_hyphen_position
);
487 // With all the hyphen positions, do the search and replace.
488 while (!hyphen_positions
.empty()) {
489 static const base::char16 kCr
[] = {L
'\r', L
'\0'};
490 const HyphenPosition
& position
= hyphen_positions
.back();
491 if (position
.next_whitespace_position
!= 0) {
492 (*text
)[position
.next_whitespace_position
] = L
'\n';
493 text
->insert(position
.next_whitespace_position
, kCr
);
495 text
->erase(position
.position
, 1);
496 hyphen_positions
.pop_back();
499 // Adobe Reader also get rid of trailing spaces right before a CRLF.
500 static const base::char16 kSpaceCrCn
[] = {L
' ', L
'\r', L
'\n', L
'\0'};
501 static const base::char16 kCrCn
[] = {L
'\r', L
'\n', L
'\0'};
502 base::ReplaceSubstringsAfterOffset(text
, 0, kSpaceCrCn
, kCrCn
);
505 // Replace CR/LF with just LF on POSIX.
506 void FormatStringForOS(base::string16
* text
) {
507 #if defined(OS_POSIX)
508 static const base::char16 kCr
[] = {L
'\r', L
'\0'};
509 static const base::char16 kBlank
[] = {L
'\0'};
510 base::ReplaceChars(*text
, kCr
, kBlank
, text
);
511 #elif defined(OS_WIN)
518 // Returns a VarDictionary (representing a bookmark), which in turn contains
519 // child VarDictionaries (representing the child bookmarks).
520 // If NULL is passed in as the bookmark then we traverse from the "root".
521 // Note that the "root" bookmark contains no useful information.
522 pp::VarDictionary
TraverseBookmarks(FPDF_DOCUMENT doc
, FPDF_BOOKMARK bookmark
) {
523 pp::VarDictionary dict
;
524 base::string16 title
;
525 unsigned long buffer_size
= FPDFBookmark_GetTitle(bookmark
, NULL
, 0);
526 size_t title_length
= base::checked_cast
<size_t>(buffer_size
) /
527 sizeof(base::string16::value_type
);
528 if (title_length
> 0) {
529 PDFiumAPIStringBufferAdapter
<base::string16
> api_string_adapter(
530 &title
, title_length
, true);
531 void* data
= api_string_adapter
.GetData();
532 FPDFBookmark_GetTitle(bookmark
, data
, buffer_size
);
533 api_string_adapter
.Close(title_length
);
535 dict
.Set(pp::Var("title"), pp::Var(base::UTF16ToUTF8(title
)));
537 FPDF_DEST dest
= FPDFBookmark_GetDest(doc
, bookmark
);
538 // Some bookmarks don't have a page to select.
540 int page_index
= FPDFDest_GetPageIndex(doc
, dest
);
541 dict
.Set(pp::Var("page"), pp::Var(page_index
));
544 pp::VarArray children
;
546 for (FPDF_BOOKMARK child_bookmark
= FPDFBookmark_GetFirstChild(doc
, bookmark
);
547 child_bookmark
!= NULL
;
548 child_bookmark
= FPDFBookmark_GetNextSibling(doc
, child_bookmark
)) {
549 children
.Set(child_index
, TraverseBookmarks(doc
, child_bookmark
));
552 dict
.Set(pp::Var("children"), children
);
558 bool InitializeSDK() {
561 #if defined(OS_LINUX)
562 // Font loading doesn't work in the renderer sandbox in Linux.
563 FPDF_SetSystemFontInfo(&g_font_info
);
566 FSDK_SetUnSpObjProcessHandler(&g_unsuppored_info
);
572 FPDF_DestroyLibrary();
575 PDFEngine
* PDFEngine::Create(PDFEngine::Client
* client
) {
576 return new PDFiumEngine(client
);
579 PDFiumEngine::PDFiumEngine(PDFEngine::Client
* client
)
582 current_rotation_(0),
584 password_tries_remaining_(0),
587 defer_page_unload_(false),
589 mouse_down_state_(PDFiumPage::NONSELECTABLE_AREA
,
590 PDFiumPage::LinkTarget()),
591 next_page_to_search_(-1),
592 last_page_to_search_(-1),
593 last_character_index_to_search_(-1),
595 permissions_handler_revision_(-1),
596 fpdf_availability_(NULL
),
598 last_page_mouse_down_(-1),
599 first_visible_page_(-1),
600 most_visible_page_(-1),
601 called_do_document_action_(false),
602 render_grayscale_(false),
603 progressive_paint_timeout_(0),
604 getting_password_(false) {
605 find_factory_
.Initialize(this);
606 password_factory_
.Initialize(this);
608 file_access_
.m_FileLen
= 0;
609 file_access_
.m_GetBlock
= &GetBlock
;
610 file_access_
.m_Param
= &doc_loader_
;
612 file_availability_
.version
= 1;
613 file_availability_
.IsDataAvail
= &IsDataAvail
;
614 file_availability_
.loader
= &doc_loader_
;
616 download_hints_
.version
= 1;
617 download_hints_
.AddSegment
= &AddSegment
;
618 download_hints_
.loader
= &doc_loader_
;
620 // Initialize FPDF_FORMFILLINFO member variables. Deriving from this struct
621 // allows the static callbacks to be able to cast the FPDF_FORMFILLINFO in
622 // callbacks to ourself instead of maintaining a map of them to
624 FPDF_FORMFILLINFO::version
= 1;
625 FPDF_FORMFILLINFO::m_pJsPlatform
= this;
626 FPDF_FORMFILLINFO::Release
= NULL
;
627 FPDF_FORMFILLINFO::FFI_Invalidate
= Form_Invalidate
;
628 FPDF_FORMFILLINFO::FFI_OutputSelectedRect
= Form_OutputSelectedRect
;
629 FPDF_FORMFILLINFO::FFI_SetCursor
= Form_SetCursor
;
630 FPDF_FORMFILLINFO::FFI_SetTimer
= Form_SetTimer
;
631 FPDF_FORMFILLINFO::FFI_KillTimer
= Form_KillTimer
;
632 FPDF_FORMFILLINFO::FFI_GetLocalTime
= Form_GetLocalTime
;
633 FPDF_FORMFILLINFO::FFI_OnChange
= Form_OnChange
;
634 FPDF_FORMFILLINFO::FFI_GetPage
= Form_GetPage
;
635 FPDF_FORMFILLINFO::FFI_GetCurrentPage
= Form_GetCurrentPage
;
636 FPDF_FORMFILLINFO::FFI_GetRotation
= Form_GetRotation
;
637 FPDF_FORMFILLINFO::FFI_ExecuteNamedAction
= Form_ExecuteNamedAction
;
638 FPDF_FORMFILLINFO::FFI_SetTextFieldFocus
= Form_SetTextFieldFocus
;
639 FPDF_FORMFILLINFO::FFI_DoURIAction
= Form_DoURIAction
;
640 FPDF_FORMFILLINFO::FFI_DoGoToAction
= Form_DoGoToAction
;
642 FPDF_FORMFILLINFO::version
= 2;
643 FPDF_FORMFILLINFO::FFI_EmailTo
= Form_EmailTo
;
644 FPDF_FORMFILLINFO::FFI_DisplayCaret
= Form_DisplayCaret
;
645 FPDF_FORMFILLINFO::FFI_SetCurrentPage
= Form_SetCurrentPage
;
646 FPDF_FORMFILLINFO::FFI_GetCurrentPageIndex
= Form_GetCurrentPageIndex
;
647 FPDF_FORMFILLINFO::FFI_GetPageViewRect
= Form_GetPageViewRect
;
648 FPDF_FORMFILLINFO::FFI_GetPlatform
= Form_GetPlatform
;
649 FPDF_FORMFILLINFO::FFI_PopupMenu
= Form_PopupMenu
;
650 FPDF_FORMFILLINFO::FFI_PostRequestURL
= Form_PostRequestURL
;
651 FPDF_FORMFILLINFO::FFI_PutRequestURL
= Form_PutRequestURL
;
652 FPDF_FORMFILLINFO::FFI_UploadTo
= Form_UploadTo
;
653 FPDF_FORMFILLINFO::FFI_DownloadFromURL
= Form_DownloadFromURL
;
654 FPDF_FORMFILLINFO::FFI_OpenFile
= Form_OpenFile
;
655 FPDF_FORMFILLINFO::FFI_GotoURL
= Form_GotoURL
;
656 FPDF_FORMFILLINFO::FFI_GetLanguage
= Form_GetLanguage
;
657 #endif // PDF_USE_XFA
658 IPDF_JSPLATFORM::version
= 1;
659 IPDF_JSPLATFORM::app_alert
= Form_Alert
;
660 IPDF_JSPLATFORM::app_beep
= Form_Beep
;
661 IPDF_JSPLATFORM::app_response
= Form_Response
;
662 IPDF_JSPLATFORM::Doc_getFilePath
= Form_GetFilePath
;
663 IPDF_JSPLATFORM::Doc_mail
= Form_Mail
;
664 IPDF_JSPLATFORM::Doc_print
= Form_Print
;
665 IPDF_JSPLATFORM::Doc_submitForm
= Form_SubmitForm
;
666 IPDF_JSPLATFORM::Doc_gotoPage
= Form_GotoPage
;
667 IPDF_JSPLATFORM::Field_browse
= Form_Browse
;
669 IFSDK_PAUSE::version
= 1;
670 IFSDK_PAUSE::user
= NULL
;
671 IFSDK_PAUSE::NeedToPauseNow
= Pause_NeedToPauseNow
;
674 PDFiumEngine::~PDFiumEngine() {
675 for (size_t i
= 0; i
< pages_
.size(); ++i
)
679 FORM_DoDocumentAAction(form_
, FPDFDOC_AACTION_WC
);
680 FPDF_CloseDocument(doc_
);
681 FPDFDOC_ExitFormFillEnvironment(form_
);
683 FPDFAvail_Destroy(fpdf_availability_
);
685 STLDeleteElements(&pages_
);
690 // This is just for testing, needs to be removed later
692 #define XFA_TESTFILE(filename) "E:/"#filename
694 #define XFA_TESTFILE(filename) "/home/"#filename
698 FPDF_FILEHANDLER file_handler
;
702 void Sample_Release(FPDF_LPVOID client_data
) {
705 FPDF_FILE
* file_wrapper
= (FPDF_FILE
*)client_data
;
706 fclose(file_wrapper
->file
);
710 FPDF_DWORD
Sample_GetSize(FPDF_LPVOID client_data
) {
713 FPDF_FILE
* file_wrapper
= (FPDF_FILE
*)client_data
;
714 long cur_pos
= ftell(file_wrapper
->file
);
717 if (fseek(file_wrapper
->file
, 0, SEEK_END
))
719 long size
= ftell(file_wrapper
->file
);
720 fseek(file_wrapper
->file
, cur_pos
, SEEK_SET
);
721 return (FPDF_DWORD
)size
;
724 FPDF_RESULT
Sample_ReadBlock(FPDF_LPVOID client_data
,
730 FPDF_FILE
* file_wrapper
= (FPDF_FILE
*)client_data
;
731 if (fseek(file_wrapper
->file
, (long)offset
, SEEK_SET
))
733 size_t read_size
= fread(buffer
, 1, size
, file_wrapper
->file
);
734 return read_size
== size
? 0 : -1;
737 FPDF_RESULT
Sample_WriteBlock(FPDF_LPVOID client_data
,
743 FPDF_FILE
* file_wrapper
= (FPDF_FILE
*)client_data
;
744 if (fseek(file_wrapper
->file
, (long)offset
, SEEK_SET
))
747 size_t write_size
= fwrite(buffer
, 1, size
, file_wrapper
->file
);
748 return write_size
== size
? 0 : -1;
751 FPDF_RESULT
Sample_Flush(FPDF_LPVOID client_data
) {
755 fflush(((FPDF_FILE
*)client_data
)->file
);
759 FPDF_RESULT
Sample_Truncate(FPDF_LPVOID client_data
, FPDF_DWORD size
) {
763 void PDFiumEngine::Form_EmailTo(FPDF_FORMFILLINFO
* param
,
764 FPDF_FILEHANDLER
* file_handler
,
766 FPDF_WIDESTRING subject
,
769 FPDF_WIDESTRING message
) {
771 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(to
));
772 std::string subject_str
=
773 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(subject
));
775 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(cc
));
776 std::string bcc_str
=
777 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(bcc
));
778 std::string message_str
=
779 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(message
));
781 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
782 engine
->client_
->Email(to_str
, cc_str
, bcc_str
, subject_str
, message_str
);
785 void PDFiumEngine::Form_DisplayCaret(FPDF_FORMFILLINFO
* param
,
792 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
793 engine
->client_
->UpdateCursor(PP_CURSORTYPE_IBEAM
);
794 std::vector
<pp::Rect
> tickmarks
;
795 pp::Rect
rect(left
, top
, right
, bottom
);
796 tickmarks
.push_back(rect
);
797 engine
->client_
->UpdateTickMarks(tickmarks
);
800 void PDFiumEngine::Form_SetCurrentPage(FPDF_FORMFILLINFO
* param
,
801 FPDF_DOCUMENT document
,
803 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
804 pp::Rect page_view_rect
= engine
->GetPageContentsRect(page
);
805 engine
->ScrolledToYPosition(page_view_rect
.height());
806 pp::Point
pos(1, page_view_rect
.height());
807 engine
->SetScrollPosition(pos
);
810 int PDFiumEngine::Form_GetCurrentPageIndex(FPDF_FORMFILLINFO
* param
,
811 FPDF_DOCUMENT document
) {
812 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
813 return engine
->GetMostVisiblePage();
816 void PDFiumEngine::Form_GetPageViewRect(FPDF_FORMFILLINFO
* param
,
822 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
823 int page_index
= engine
->GetMostVisiblePage();
824 pp::Rect page_view_rect
= engine
->GetPageContentsRect(page_index
);
826 *left
= page_view_rect
.x();
827 *right
= page_view_rect
.right();
828 *top
= page_view_rect
.y();
829 *bottom
= page_view_rect
.bottom();
832 int PDFiumEngine::Form_GetPlatform(FPDF_FORMFILLINFO
* param
,
835 int platform_flag
= -1;
839 #elif defined(__linux__)
845 std::string javascript
= "alert(\"Platform:"
846 + base::DoubleToString(platform_flag
)
849 return platform_flag
;
852 FPDF_BOOL
PDFiumEngine::Form_PopupMenu(FPDF_FORMFILLINFO
* param
,
861 FPDF_BOOL
PDFiumEngine::Form_PostRequestURL(FPDF_FORMFILLINFO
* param
,
863 FPDF_WIDESTRING data
,
864 FPDF_WIDESTRING content_type
,
865 FPDF_WIDESTRING encode
,
866 FPDF_WIDESTRING header
,
867 FPDF_BSTR
* response
) {
868 std::string url_str
=
869 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(url
));
870 std::string data_str
=
871 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(data
));
872 std::string content_type_str
=
873 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(content_type
));
874 std::string encode_str
=
875 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(encode
));
876 std::string header_str
=
877 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(header
));
879 std::string javascript
= "alert(\"Post:"
880 + url_str
+ "," + data_str
+ "," + content_type_str
+ ","
881 + encode_str
+ "," + header_str
886 FPDF_BOOL
PDFiumEngine::Form_PutRequestURL(FPDF_FORMFILLINFO
* param
,
888 FPDF_WIDESTRING data
,
889 FPDF_WIDESTRING encode
) {
890 std::string url_str
=
891 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(url
));
892 std::string data_str
=
893 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(data
));
894 std::string encode_str
=
895 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(encode
));
897 std::string javascript
= "alert(\"Put:"
898 + url_str
+ "," + data_str
+ "," + encode_str
904 void PDFiumEngine::Form_UploadTo(FPDF_FORMFILLINFO
* param
,
905 FPDF_FILEHANDLER
* file_handle
,
907 FPDF_WIDESTRING to
) {
909 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(to
));
910 // TODO: needs the full implementation of form uploading
913 FPDF_LPFILEHANDLER
PDFiumEngine::Form_DownloadFromURL(FPDF_FORMFILLINFO
* param
,
914 FPDF_WIDESTRING url
) {
915 std::string url_str
=
916 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(url
));
918 // Now should get data from url.
919 // For testing purpose, use data read from file
920 // TODO: needs the full implementation here
921 FILE* file
= fopen(XFA_TESTFILE("downloadtest.tem"), "w");
923 FPDF_FILE
* file_wrapper
= new FPDF_FILE
;
924 file_wrapper
->file
= file
;
925 file_wrapper
->file_handler
.clientData
= file_wrapper
;
926 file_wrapper
->file_handler
.Flush
= Sample_Flush
;
927 file_wrapper
->file_handler
.GetSize
= Sample_GetSize
;
928 file_wrapper
->file_handler
.ReadBlock
= Sample_ReadBlock
;
929 file_wrapper
->file_handler
.Release
= Sample_Release
;
930 file_wrapper
->file_handler
.Truncate
= Sample_Truncate
;
931 file_wrapper
->file_handler
.WriteBlock
= Sample_WriteBlock
;
933 return &file_wrapper
->file_handler
;
936 FPDF_FILEHANDLER
* PDFiumEngine::Form_OpenFile(FPDF_FORMFILLINFO
* param
,
940 std::string url_str
= "NULL";
943 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(url
));
945 // TODO: need to implement open file from the url
946 // Use a file path for the ease of testing
947 FILE* file
= fopen(XFA_TESTFILE("tem.txt"), mode
);
948 FPDF_FILE
* file_wrapper
= new FPDF_FILE
;
949 file_wrapper
->file
= file
;
950 file_wrapper
->file_handler
.clientData
= file_wrapper
;
951 file_wrapper
->file_handler
.Flush
= Sample_Flush
;
952 file_wrapper
->file_handler
.GetSize
= Sample_GetSize
;
953 file_wrapper
->file_handler
.ReadBlock
= Sample_ReadBlock
;
954 file_wrapper
->file_handler
.Release
= Sample_Release
;
955 file_wrapper
->file_handler
.Truncate
= Sample_Truncate
;
956 file_wrapper
->file_handler
.WriteBlock
= Sample_WriteBlock
;
957 return &file_wrapper
->file_handler
;
960 void PDFiumEngine::Form_GotoURL(FPDF_FORMFILLINFO
* param
,
961 FPDF_DOCUMENT document
,
962 FPDF_WIDESTRING url
) {
963 std::string url_str
=
964 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(url
));
965 // TODO: needs to implement GOTO URL action
968 int PDFiumEngine::Form_GetLanguage(FPDF_FORMFILLINFO
* param
,
974 #endif // PDF_USE_XFA
976 int PDFiumEngine::GetBlock(void* param
, unsigned long position
,
977 unsigned char* buffer
, unsigned long size
) {
978 DocumentLoader
* loader
= static_cast<DocumentLoader
*>(param
);
979 return loader
->GetBlock(position
, size
, buffer
);
982 FPDF_BOOL
PDFiumEngine::IsDataAvail(FX_FILEAVAIL
* param
,
983 size_t offset
, size_t size
) {
984 PDFiumEngine::FileAvail
* file_avail
=
985 static_cast<PDFiumEngine::FileAvail
*>(param
);
986 return file_avail
->loader
->IsDataAvailable(offset
, size
);
989 void PDFiumEngine::AddSegment(FX_DOWNLOADHINTS
* param
,
990 size_t offset
, size_t size
) {
991 PDFiumEngine::DownloadHints
* download_hints
=
992 static_cast<PDFiumEngine::DownloadHints
*>(param
);
993 return download_hints
->loader
->RequestData(offset
, size
);
996 bool PDFiumEngine::New(const char* url
,
997 const char* headers
) {
1006 void PDFiumEngine::PageOffsetUpdated(const pp::Point
& page_offset
) {
1007 page_offset_
= page_offset
;
1010 void PDFiumEngine::PluginSizeUpdated(const pp::Size
& size
) {
1013 plugin_size_
= size
;
1014 CalculateVisiblePages();
1017 void PDFiumEngine::ScrolledToXPosition(int position
) {
1020 int old_x
= position_
.x();
1021 position_
.set_x(position
);
1022 CalculateVisiblePages();
1023 client_
->Scroll(pp::Point(old_x
- position
, 0));
1026 void PDFiumEngine::ScrolledToYPosition(int position
) {
1029 int old_y
= position_
.y();
1030 position_
.set_y(position
);
1031 CalculateVisiblePages();
1032 client_
->Scroll(pp::Point(0, old_y
- position
));
1035 void PDFiumEngine::PrePaint() {
1036 for (size_t i
= 0; i
< progressive_paints_
.size(); ++i
)
1037 progressive_paints_
[i
].painted_
= false;
1040 void PDFiumEngine::Paint(const pp::Rect
& rect
,
1041 pp::ImageData
* image_data
,
1042 std::vector
<pp::Rect
>* ready
,
1043 std::vector
<pp::Rect
>* pending
) {
1048 pp::Rect leftover
= rect
;
1049 for (size_t i
= 0; i
< visible_pages_
.size(); ++i
) {
1050 int index
= visible_pages_
[i
];
1051 pp::Rect page_rect
= pages_
[index
]->rect();
1052 // Convert the current page's rectangle to screen rectangle. We do this
1053 // instead of the reverse (converting the dirty rectangle from screen to
1054 // page coordinates) because then we'd have to convert back to screen
1055 // coordinates, and the rounding errors sometime leave pixels dirty or even
1056 // move the text up or down a pixel when zoomed.
1057 pp::Rect page_rect_in_screen
= GetPageScreenRect(index
);
1058 pp::Rect dirty_in_screen
= page_rect_in_screen
.Intersect(leftover
);
1059 if (dirty_in_screen
.IsEmpty())
1062 leftover
= leftover
.Subtract(dirty_in_screen
);
1064 if (pages_
[index
]->available()) {
1065 int progressive
= GetProgressiveIndex(index
);
1066 if (progressive
!= -1) {
1067 DCHECK_GE(progressive
, 0);
1068 DCHECK_LT(static_cast<size_t>(progressive
), progressive_paints_
.size());
1069 if (progressive_paints_
[progressive
].rect
!= dirty_in_screen
) {
1070 // The PDFium code can only handle one progressive paint at a time, so
1071 // queue this up. Previously we used to merge the rects when this
1072 // happened, but it made scrolling up on complex PDFs very slow since
1073 // there would be a damaged rect at the top (from scroll) and at the
1074 // bottom (from toolbar).
1075 pending
->push_back(dirty_in_screen
);
1080 if (progressive
== -1) {
1081 progressive
= StartPaint(index
, dirty_in_screen
);
1082 progressive_paint_timeout_
= kMaxInitialProgressivePaintTimeMs
;
1084 progressive_paint_timeout_
= kMaxProgressivePaintTimeMs
;
1087 progressive_paints_
[progressive
].painted_
= true;
1088 if (ContinuePaint(progressive
, image_data
)) {
1089 FinishPaint(progressive
, image_data
);
1090 ready
->push_back(dirty_in_screen
);
1092 pending
->push_back(dirty_in_screen
);
1095 PaintUnavailablePage(index
, dirty_in_screen
, image_data
);
1096 ready
->push_back(dirty_in_screen
);
1101 void PDFiumEngine::PostPaint() {
1102 for (size_t i
= 0; i
< progressive_paints_
.size(); ++i
) {
1103 if (progressive_paints_
[i
].painted_
)
1106 // This rectangle must have been merged with another one, that's why we
1107 // weren't asked to paint it. Remove it or otherwise we'll never finish
1109 FPDF_RenderPage_Close(
1110 pages_
[progressive_paints_
[i
].page_index
]->GetPage());
1111 FPDFBitmap_Destroy(progressive_paints_
[i
].bitmap
);
1112 progressive_paints_
.erase(progressive_paints_
.begin() + i
);
1117 bool PDFiumEngine::HandleDocumentLoad(const pp::URLLoader
& loader
) {
1118 password_tries_remaining_
= kMaxPasswordTries
;
1119 return doc_loader_
.Init(loader
, url_
, headers_
);
1122 pp::Instance
* PDFiumEngine::GetPluginInstance() {
1123 return client_
->GetPluginInstance();
1126 pp::URLLoader
PDFiumEngine::CreateURLLoader() {
1127 return client_
->CreateURLLoader();
1130 void PDFiumEngine::AppendPage(PDFEngine
* engine
, int index
) {
1131 // Unload and delete the blank page before appending.
1132 pages_
[index
]->Unload();
1133 pages_
[index
]->set_calculated_links(false);
1134 pp::Size curr_page_size
= GetPageSize(index
);
1135 FPDFPage_Delete(doc_
, index
);
1136 FPDF_ImportPages(doc_
,
1137 static_cast<PDFiumEngine
*>(engine
)->doc(),
1140 pp::Size new_page_size
= GetPageSize(index
);
1141 if (curr_page_size
!= new_page_size
)
1143 client_
->Invalidate(GetPageScreenRect(index
));
1146 pp::Point
PDFiumEngine::GetScrollPosition() {
1150 void PDFiumEngine::SetScrollPosition(const pp::Point
& position
) {
1151 position_
= position
;
1154 bool PDFiumEngine::IsProgressiveLoad() {
1155 return doc_loader_
.is_partial_document();
1158 void PDFiumEngine::OnPartialDocumentLoaded() {
1159 file_access_
.m_FileLen
= doc_loader_
.document_size();
1160 fpdf_availability_
= FPDFAvail_Create(&file_availability_
, &file_access_
);
1161 DCHECK(fpdf_availability_
);
1163 // Currently engine does not deal efficiently with some non-linearized files.
1164 // See http://code.google.com/p/chromium/issues/detail?id=59400
1165 // To improve user experience we download entire file for non-linearized PDF.
1166 if (!FPDFAvail_IsLinearized(fpdf_availability_
)) {
1167 doc_loader_
.RequestData(0, doc_loader_
.document_size());
1174 void PDFiumEngine::OnPendingRequestComplete() {
1175 if (!doc_
|| !form_
) {
1180 // LoadDocument() will result in |pending_pages_| being reset so there's no
1181 // need to run the code below in that case.
1182 bool update_pages
= false;
1183 std::vector
<int> still_pending
;
1184 for (size_t i
= 0; i
< pending_pages_
.size(); ++i
) {
1185 if (CheckPageAvailable(pending_pages_
[i
], &still_pending
)) {
1186 update_pages
= true;
1187 if (IsPageVisible(pending_pages_
[i
]))
1188 client_
->Invalidate(GetPageScreenRect(pending_pages_
[i
]));
1191 pending_pages_
.swap(still_pending
);
1196 void PDFiumEngine::OnNewDataAvailable() {
1197 client_
->DocumentLoadProgress(doc_loader_
.GetAvailableData(),
1198 doc_loader_
.document_size());
1201 void PDFiumEngine::OnDocumentComplete() {
1202 if (!doc_
|| !form_
) {
1203 file_access_
.m_FileLen
= doc_loader_
.document_size();
1208 bool need_update
= false;
1209 for (size_t i
= 0; i
< pages_
.size(); ++i
) {
1210 if (pages_
[i
]->available())
1213 pages_
[i
]->set_available(true);
1214 // We still need to call IsPageAvail() even if the whole document is
1215 // already downloaded.
1216 FPDFAvail_IsPageAvail(fpdf_availability_
, i
, &download_hints_
);
1218 if (IsPageVisible(i
))
1219 client_
->Invalidate(GetPageScreenRect(i
));
1224 FinishLoadingDocument();
1227 void PDFiumEngine::FinishLoadingDocument() {
1228 DCHECK(doc_loader_
.IsDocumentComplete() && doc_
);
1229 if (called_do_document_action_
)
1231 called_do_document_action_
= true;
1233 // These can only be called now, as the JS might end up needing a page.
1234 FORM_DoDocumentJSAction(form_
);
1235 FORM_DoDocumentOpenAction(form_
);
1236 if (most_visible_page_
!= -1) {
1237 FPDF_PAGE new_page
= pages_
[most_visible_page_
]->GetPage();
1238 FORM_DoPageAAction(new_page
, form_
, FPDFPAGE_AACTION_OPEN
);
1241 if (doc_
) // This can only happen if loading |doc_| fails.
1242 client_
->DocumentLoadComplete(pages_
.size());
1245 void PDFiumEngine::UnsupportedFeature(int type
) {
1246 std::string feature
;
1249 case FPDF_UNSP_DOC_XFAFORM
:
1253 case FPDF_UNSP_DOC_PORTABLECOLLECTION
:
1254 feature
= "Portfolios_Packages";
1256 case FPDF_UNSP_DOC_ATTACHMENT
:
1257 case FPDF_UNSP_ANNOT_ATTACHMENT
:
1258 feature
= "Attachment";
1260 case FPDF_UNSP_DOC_SECURITY
:
1261 feature
= "Rights_Management";
1263 case FPDF_UNSP_DOC_SHAREDREVIEW
:
1264 feature
= "Shared_Review";
1266 case FPDF_UNSP_DOC_SHAREDFORM_ACROBAT
:
1267 case FPDF_UNSP_DOC_SHAREDFORM_FILESYSTEM
:
1268 case FPDF_UNSP_DOC_SHAREDFORM_EMAIL
:
1269 feature
= "Shared_Form";
1271 case FPDF_UNSP_ANNOT_3DANNOT
:
1274 case FPDF_UNSP_ANNOT_MOVIE
:
1277 case FPDF_UNSP_ANNOT_SOUND
:
1280 case FPDF_UNSP_ANNOT_SCREEN_MEDIA
:
1281 case FPDF_UNSP_ANNOT_SCREEN_RICHMEDIA
:
1284 case FPDF_UNSP_ANNOT_SIG
:
1285 feature
= "Digital_Signature";
1288 client_
->DocumentHasUnsupportedFeature(feature
);
1291 void PDFiumEngine::ContinueFind(int32_t result
) {
1292 StartFind(current_find_text_
.c_str(), !!result
);
1295 bool PDFiumEngine::HandleEvent(const pp::InputEvent
& event
) {
1296 DCHECK(!defer_page_unload_
);
1297 defer_page_unload_
= true;
1299 switch (event
.GetType()) {
1300 case PP_INPUTEVENT_TYPE_MOUSEDOWN
:
1301 rv
= OnMouseDown(pp::MouseInputEvent(event
));
1303 case PP_INPUTEVENT_TYPE_MOUSEUP
:
1304 rv
= OnMouseUp(pp::MouseInputEvent(event
));
1306 case PP_INPUTEVENT_TYPE_MOUSEMOVE
:
1307 rv
= OnMouseMove(pp::MouseInputEvent(event
));
1309 case PP_INPUTEVENT_TYPE_KEYDOWN
:
1310 rv
= OnKeyDown(pp::KeyboardInputEvent(event
));
1312 case PP_INPUTEVENT_TYPE_KEYUP
:
1313 rv
= OnKeyUp(pp::KeyboardInputEvent(event
));
1315 case PP_INPUTEVENT_TYPE_CHAR
:
1316 rv
= OnChar(pp::KeyboardInputEvent(event
));
1322 DCHECK(defer_page_unload_
);
1323 defer_page_unload_
= false;
1324 for (size_t i
= 0; i
< deferred_page_unloads_
.size(); ++i
)
1325 pages_
[deferred_page_unloads_
[i
]]->Unload();
1326 deferred_page_unloads_
.clear();
1330 uint32_t PDFiumEngine::QuerySupportedPrintOutputFormats() {
1331 if (!HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
))
1333 return PP_PRINTOUTPUTFORMAT_PDF
;
1336 void PDFiumEngine::PrintBegin() {
1337 FORM_DoDocumentAAction(form_
, FPDFDOC_AACTION_WP
);
1340 pp::Resource
PDFiumEngine::PrintPages(
1341 const PP_PrintPageNumberRange_Dev
* page_ranges
, uint32_t page_range_count
,
1342 const PP_PrintSettings_Dev
& print_settings
) {
1343 if (HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY
))
1344 return PrintPagesAsPDF(page_ranges
, page_range_count
, print_settings
);
1345 else if (HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
))
1346 return PrintPagesAsRasterPDF(page_ranges
, page_range_count
, print_settings
);
1347 return pp::Resource();
1350 FPDF_DOCUMENT
PDFiumEngine::CreateSinglePageRasterPdf(
1351 double source_page_width
,
1352 double source_page_height
,
1353 const PP_PrintSettings_Dev
& print_settings
,
1354 PDFiumPage
* page_to_print
) {
1355 FPDF_DOCUMENT temp_doc
= FPDF_CreateNewDocument();
1359 const pp::Size
& bitmap_size(page_to_print
->rect().size());
1361 FPDF_PAGE temp_page
=
1362 FPDFPage_New(temp_doc
, 0, source_page_width
, source_page_height
);
1364 pp::ImageData image
= pp::ImageData(client_
->GetPluginInstance(),
1365 PP_IMAGEDATAFORMAT_BGRA_PREMUL
,
1369 FPDF_BITMAP bitmap
= FPDFBitmap_CreateEx(bitmap_size
.width(),
1370 bitmap_size
.height(),
1376 FPDFBitmap_FillRect(
1377 bitmap
, 0, 0, bitmap_size
.width(), bitmap_size
.height(), 0xFFFFFFFF);
1379 pp::Rect page_rect
= page_to_print
->rect();
1380 FPDF_RenderPageBitmap(bitmap
,
1381 page_to_print
->GetPrintPage(),
1386 print_settings
.orientation
,
1387 FPDF_ANNOT
| FPDF_PRINTING
| FPDF_NO_CATCH
);
1389 double ratio_x
= ConvertUnitDouble(bitmap_size
.width(),
1392 double ratio_y
= ConvertUnitDouble(bitmap_size
.height(),
1396 // Add the bitmap to an image object and add the image object to the output
1398 FPDF_PAGEOBJECT temp_img
= FPDFPageObj_NewImgeObj(temp_doc
);
1399 FPDFImageObj_SetBitmap(&temp_page
, 1, temp_img
, bitmap
);
1400 FPDFImageObj_SetMatrix(temp_img
, ratio_x
, 0, 0, ratio_y
, 0, 0);
1401 FPDFPage_InsertObject(temp_page
, temp_img
);
1402 FPDFPage_GenerateContent(temp_page
);
1403 FPDF_ClosePage(temp_page
);
1405 page_to_print
->ClosePrintPage();
1406 FPDFBitmap_Destroy(bitmap
);
1411 pp::Buffer_Dev
PDFiumEngine::PrintPagesAsRasterPDF(
1412 const PP_PrintPageNumberRange_Dev
* page_ranges
, uint32_t page_range_count
,
1413 const PP_PrintSettings_Dev
& print_settings
) {
1414 if (!page_range_count
)
1415 return pp::Buffer_Dev();
1417 // If document is not downloaded yet, disable printing.
1418 if (doc_
&& !doc_loader_
.IsDocumentComplete())
1419 return pp::Buffer_Dev();
1421 FPDF_DOCUMENT output_doc
= FPDF_CreateNewDocument();
1423 return pp::Buffer_Dev();
1425 SaveSelectedFormForPrint();
1427 std::vector
<PDFiumPage
> pages_to_print
;
1428 // width and height of source PDF pages.
1429 std::vector
<std::pair
<double, double> > source_page_sizes
;
1430 // Collect pages to print and sizes of source pages.
1431 std::vector
<uint32_t> page_numbers
=
1432 GetPageNumbersFromPrintPageNumberRange(page_ranges
, page_range_count
);
1433 for (size_t i
= 0; i
< page_numbers
.size(); ++i
) {
1434 uint32_t page_number
= page_numbers
[i
];
1435 FPDF_PAGE pdf_page
= FPDF_LoadPage(doc_
, page_number
);
1436 double source_page_width
= FPDF_GetPageWidth(pdf_page
);
1437 double source_page_height
= FPDF_GetPageHeight(pdf_page
);
1438 source_page_sizes
.push_back(std::make_pair(source_page_width
,
1439 source_page_height
));
1441 int width_in_pixels
= ConvertUnit(source_page_width
,
1443 print_settings
.dpi
);
1444 int height_in_pixels
= ConvertUnit(source_page_height
,
1446 print_settings
.dpi
);
1448 pp::Rect
rect(width_in_pixels
, height_in_pixels
);
1449 pages_to_print
.push_back(PDFiumPage(this, page_number
, rect
, true));
1450 FPDF_ClosePage(pdf_page
);
1453 #if defined(OS_LINUX)
1454 g_last_instance_id
= client_
->GetPluginInstance()->pp_instance();
1458 for (; i
< pages_to_print
.size(); ++i
) {
1459 double source_page_width
= source_page_sizes
[i
].first
;
1460 double source_page_height
= source_page_sizes
[i
].second
;
1462 // Use temp_doc to compress image by saving PDF to buffer.
1463 FPDF_DOCUMENT temp_doc
= CreateSinglePageRasterPdf(source_page_width
,
1466 &pages_to_print
[i
]);
1471 pp::Buffer_Dev buffer
= GetFlattenedPrintData(temp_doc
);
1472 FPDF_CloseDocument(temp_doc
);
1474 PDFiumMemBufferFileRead
file_read(buffer
.data(), buffer
.size());
1475 temp_doc
= FPDF_LoadCustomDocument(&file_read
, NULL
);
1477 FPDF_BOOL imported
= FPDF_ImportPages(output_doc
, temp_doc
, "1", i
);
1478 FPDF_CloseDocument(temp_doc
);
1483 pp::Buffer_Dev buffer
;
1484 if (i
== pages_to_print
.size()) {
1485 FPDF_CopyViewerPreferences(output_doc
, doc_
);
1486 FitContentsToPrintableAreaIfRequired(output_doc
, print_settings
);
1487 // Now flatten all the output pages.
1488 buffer
= GetFlattenedPrintData(output_doc
);
1490 FPDF_CloseDocument(output_doc
);
1494 pp::Buffer_Dev
PDFiumEngine::GetFlattenedPrintData(const FPDF_DOCUMENT
& doc
) {
1495 int page_count
= FPDF_GetPageCount(doc
);
1496 bool flatten_succeeded
= true;
1497 for (int i
= 0; i
< page_count
; ++i
) {
1498 FPDF_PAGE page
= FPDF_LoadPage(doc
, i
);
1501 int flatten_ret
= FPDFPage_Flatten(page
, FLAT_PRINT
);
1502 FPDF_ClosePage(page
);
1503 if (flatten_ret
== FLATTEN_FAIL
) {
1504 flatten_succeeded
= false;
1508 flatten_succeeded
= false;
1512 if (!flatten_succeeded
) {
1513 FPDF_CloseDocument(doc
);
1514 return pp::Buffer_Dev();
1517 pp::Buffer_Dev buffer
;
1518 PDFiumMemBufferFileWrite output_file_write
;
1519 if (FPDF_SaveAsCopy(doc
, &output_file_write
, 0)) {
1520 buffer
= pp::Buffer_Dev(
1521 client_
->GetPluginInstance(), output_file_write
.size());
1522 if (!buffer
.is_null()) {
1523 memcpy(buffer
.data(), output_file_write
.buffer().c_str(),
1524 output_file_write
.size());
1530 pp::Buffer_Dev
PDFiumEngine::PrintPagesAsPDF(
1531 const PP_PrintPageNumberRange_Dev
* page_ranges
, uint32_t page_range_count
,
1532 const PP_PrintSettings_Dev
& print_settings
) {
1533 if (!page_range_count
)
1534 return pp::Buffer_Dev();
1537 FPDF_DOCUMENT output_doc
= FPDF_CreateNewDocument();
1539 return pp::Buffer_Dev();
1541 SaveSelectedFormForPrint();
1543 std::string page_number_str
;
1544 for (uint32_t index
= 0; index
< page_range_count
; ++index
) {
1545 if (!page_number_str
.empty())
1546 page_number_str
.append(",");
1547 page_number_str
.append(
1548 base::IntToString(page_ranges
[index
].first_page_number
+ 1));
1549 if (page_ranges
[index
].first_page_number
!=
1550 page_ranges
[index
].last_page_number
) {
1551 page_number_str
.append("-");
1552 page_number_str
.append(
1553 base::IntToString(page_ranges
[index
].last_page_number
+ 1));
1557 std::vector
<uint32_t> page_numbers
=
1558 GetPageNumbersFromPrintPageNumberRange(page_ranges
, page_range_count
);
1559 for (size_t i
= 0; i
< page_numbers
.size(); ++i
) {
1560 uint32_t page_number
= page_numbers
[i
];
1561 pages_
[page_number
]->GetPage();
1562 if (!IsPageVisible(page_numbers
[i
]))
1563 pages_
[page_number
]->Unload();
1566 FPDF_CopyViewerPreferences(output_doc
, doc_
);
1567 if (!FPDF_ImportPages(output_doc
, doc_
, page_number_str
.c_str(), 0)) {
1568 FPDF_CloseDocument(output_doc
);
1569 return pp::Buffer_Dev();
1572 FitContentsToPrintableAreaIfRequired(output_doc
, print_settings
);
1574 // Now flatten all the output pages.
1575 pp::Buffer_Dev buffer
= GetFlattenedPrintData(output_doc
);
1576 FPDF_CloseDocument(output_doc
);
1580 void PDFiumEngine::FitContentsToPrintableAreaIfRequired(
1581 const FPDF_DOCUMENT
& doc
, const PP_PrintSettings_Dev
& print_settings
) {
1582 // Check to see if we need to fit pdf contents to printer paper size.
1583 if (print_settings
.print_scaling_option
!=
1584 PP_PRINTSCALINGOPTION_SOURCE_SIZE
) {
1585 int num_pages
= FPDF_GetPageCount(doc
);
1586 // In-place transformation is more efficient than creating a new
1587 // transformed document from the source document. Therefore, transform
1588 // every page to fit the contents in the selected printer paper.
1589 for (int i
= 0; i
< num_pages
; ++i
) {
1590 FPDF_PAGE page
= FPDF_LoadPage(doc
, i
);
1591 TransformPDFPageForPrinting(page
, print_settings
);
1592 FPDF_ClosePage(page
);
1597 void PDFiumEngine::SaveSelectedFormForPrint() {
1598 FORM_ForceToKillFocus(form_
);
1599 client_
->FormTextFieldFocusChange(false);
1602 void PDFiumEngine::PrintEnd() {
1603 FORM_DoDocumentAAction(form_
, FPDFDOC_AACTION_DP
);
1606 PDFiumPage::Area
PDFiumEngine::GetCharIndex(const pp::MouseInputEvent
& event
,
1610 PDFiumPage::LinkTarget
* target
) {
1611 // First figure out which page this is in.
1612 pp::Point mouse_point
= event
.GetPosition();
1613 return GetCharIndex(mouse_point
, page_index
, char_index
, form_type
, target
);
1616 PDFiumPage::Area
PDFiumEngine::GetCharIndex(const pp::Point
& point
,
1620 PDFiumPage::LinkTarget
* target
) {
1622 pp::Point
point_in_page(
1623 static_cast<int>((point
.x() + position_
.x()) / current_zoom_
),
1624 static_cast<int>((point
.y() + position_
.y()) / current_zoom_
));
1625 for (size_t i
= 0; i
< visible_pages_
.size(); ++i
) {
1626 if (pages_
[visible_pages_
[i
]]->rect().Contains(point_in_page
)) {
1627 page
= visible_pages_
[i
];
1632 return PDFiumPage::NONSELECTABLE_AREA
;
1634 // If the page hasn't finished rendering, calling into the page sometimes
1636 for (size_t i
= 0; i
< progressive_paints_
.size(); ++i
) {
1637 if (progressive_paints_
[i
].page_index
== page
)
1638 return PDFiumPage::NONSELECTABLE_AREA
;
1642 return pages_
[page
]->GetCharIndex(
1643 point_in_page
, current_rotation_
, char_index
, form_type
, target
);
1646 bool PDFiumEngine::OnMouseDown(const pp::MouseInputEvent
& event
) {
1647 if (event
.GetButton() == PP_INPUTEVENT_MOUSEBUTTON_RIGHT
) {
1648 if (!selection_
.size())
1650 std::vector
<pp::Rect
> selection_rect_vector
;
1651 GetAllScreenRectsUnion(&selection_
, GetVisibleRect().point(),
1652 &selection_rect_vector
);
1653 pp::Point point
= event
.GetPosition();
1654 for (size_t i
= 0; i
< selection_rect_vector
.size(); ++i
) {
1655 if (selection_rect_vector
[i
].Contains(point
.x(), point
.y()))
1658 SelectionChangeInvalidator
selection_invalidator(this);
1662 if (event
.GetButton() != PP_INPUTEVENT_MOUSEBUTTON_LEFT
)
1665 SelectionChangeInvalidator
selection_invalidator(this);
1668 int page_index
= -1;
1669 int char_index
= -1;
1670 int form_type
= FPDF_FORMFIELD_UNKNOWN
;
1671 PDFiumPage::LinkTarget target
;
1672 PDFiumPage::Area area
=
1673 GetCharIndex(event
, &page_index
, &char_index
, &form_type
, &target
);
1674 mouse_down_state_
.Set(area
, target
);
1676 // Decide whether to open link or not based on user action in mouse up and
1677 // mouse move events.
1678 if (area
== PDFiumPage::WEBLINK_AREA
)
1681 if (area
== PDFiumPage::DOCLINK_AREA
) {
1682 client_
->ScrollToPage(target
.page
);
1683 client_
->FormTextFieldFocusChange(false);
1687 if (page_index
!= -1) {
1688 last_page_mouse_down_
= page_index
;
1689 double page_x
, page_y
;
1690 pp::Point point
= event
.GetPosition();
1691 DeviceToPage(page_index
, point
.x(), point
.y(), &page_x
, &page_y
);
1693 FORM_OnLButtonDown(form_
, pages_
[page_index
]->GetPage(), 0, page_x
, page_y
);
1694 if (form_type
> FPDF_FORMFIELD_UNKNOWN
) { // returns -1 sometimes...
1695 mouse_down_state_
.Set(PDFiumPage::NONSELECTABLE_AREA
, target
);
1696 bool is_valid_control
= (form_type
== FPDF_FORMFIELD_TEXTFIELD
||
1697 form_type
== FPDF_FORMFIELD_COMBOBOX
);
1699 is_valid_control
|= (form_type
== FPDF_FORMFIELD_XFA
);
1701 client_
->FormTextFieldFocusChange(is_valid_control
);
1702 return true; // Return now before we get into the selection code.
1706 client_
->FormTextFieldFocusChange(false);
1708 if (area
!= PDFiumPage::TEXT_AREA
)
1709 return true; // Return true so WebKit doesn't do its own highlighting.
1711 if (event
.GetClickCount() == 1) {
1712 OnSingleClick(page_index
, char_index
);
1713 } else if (event
.GetClickCount() == 2 ||
1714 event
.GetClickCount() == 3) {
1715 OnMultipleClick(event
.GetClickCount(), page_index
, char_index
);
1721 void PDFiumEngine::OnSingleClick(int page_index
, int char_index
) {
1723 selection_
.push_back(PDFiumRange(pages_
[page_index
], char_index
, 0));
1726 void PDFiumEngine::OnMultipleClick(int click_count
,
1729 // It would be more efficient if the SDK could support finding a space, but
1731 int start_index
= char_index
;
1733 base::char16 cur
= pages_
[page_index
]->GetCharAtIndex(start_index
);
1734 // For double click, we want to select one word so we look for whitespace
1735 // boundaries. For triple click, we want the whole line.
1736 if (cur
== '\n' || (click_count
== 2 && (cur
== ' ' || cur
== '\t')))
1738 } while (--start_index
>= 0);
1742 int end_index
= char_index
;
1743 int total
= pages_
[page_index
]->GetCharCount();
1744 while (end_index
++ <= total
) {
1745 base::char16 cur
= pages_
[page_index
]->GetCharAtIndex(end_index
);
1746 if (cur
== '\n' || (click_count
== 2 && (cur
== ' ' || cur
== '\t')))
1750 selection_
.push_back(PDFiumRange(
1751 pages_
[page_index
], start_index
, end_index
- start_index
));
1754 bool PDFiumEngine::OnMouseUp(const pp::MouseInputEvent
& event
) {
1755 if (event
.GetButton() != PP_INPUTEVENT_MOUSEBUTTON_LEFT
)
1758 int page_index
= -1;
1759 int char_index
= -1;
1760 int form_type
= FPDF_FORMFIELD_UNKNOWN
;
1761 PDFiumPage::LinkTarget target
;
1762 PDFiumPage::Area area
=
1763 GetCharIndex(event
, &page_index
, &char_index
, &form_type
, &target
);
1765 // Open link on mouse up for same link for which mouse down happened earlier.
1766 if (mouse_down_state_
.Matches(area
, target
)) {
1767 if (area
== PDFiumPage::WEBLINK_AREA
) {
1768 bool open_in_new_tab
= !!(event
.GetModifiers() & kDefaultKeyModifier
);
1769 client_
->NavigateTo(target
.url
, open_in_new_tab
);
1770 client_
->FormTextFieldFocusChange(false);
1775 if (page_index
!= -1) {
1776 double page_x
, page_y
;
1777 pp::Point point
= event
.GetPosition();
1778 DeviceToPage(page_index
, point
.x(), point
.y(), &page_x
, &page_y
);
1780 form_
, pages_
[page_index
]->GetPage(), 0, page_x
, page_y
);
1786 SetSelecting(false);
1790 bool PDFiumEngine::OnMouseMove(const pp::MouseInputEvent
& event
) {
1791 int page_index
= -1;
1792 int char_index
= -1;
1793 int form_type
= FPDF_FORMFIELD_UNKNOWN
;
1794 PDFiumPage::LinkTarget target
;
1795 PDFiumPage::Area area
=
1796 GetCharIndex(event
, &page_index
, &char_index
, &form_type
, &target
);
1798 // Clear |mouse_down_state_| if mouse moves away from where the mouse down
1800 if (!mouse_down_state_
.Matches(area
, target
))
1801 mouse_down_state_
.Reset();
1804 PP_CursorType_Dev cursor
;
1806 case PDFiumPage::TEXT_AREA
:
1807 cursor
= PP_CURSORTYPE_IBEAM
;
1809 case PDFiumPage::WEBLINK_AREA
:
1810 case PDFiumPage::DOCLINK_AREA
:
1811 cursor
= PP_CURSORTYPE_HAND
;
1813 case PDFiumPage::NONSELECTABLE_AREA
:
1815 switch (form_type
) {
1816 case FPDF_FORMFIELD_PUSHBUTTON
:
1817 case FPDF_FORMFIELD_CHECKBOX
:
1818 case FPDF_FORMFIELD_RADIOBUTTON
:
1819 case FPDF_FORMFIELD_COMBOBOX
:
1820 case FPDF_FORMFIELD_LISTBOX
:
1821 cursor
= PP_CURSORTYPE_HAND
;
1823 case FPDF_FORMFIELD_TEXTFIELD
:
1824 cursor
= PP_CURSORTYPE_IBEAM
;
1827 cursor
= PP_CURSORTYPE_POINTER
;
1833 if (page_index
!= -1) {
1834 double page_x
, page_y
;
1835 pp::Point point
= event
.GetPosition();
1836 DeviceToPage(page_index
, point
.x(), point
.y(), &page_x
, &page_y
);
1837 FORM_OnMouseMove(form_
, pages_
[page_index
]->GetPage(), 0, page_x
, page_y
);
1840 client_
->UpdateCursor(cursor
);
1841 pp::Point point
= event
.GetPosition();
1842 std::string url
= GetLinkAtPosition(event
.GetPosition());
1843 if (url
!= link_under_cursor_
) {
1844 link_under_cursor_
= url
;
1845 pp::PDF::SetLinkUnderCursor(GetPluginInstance(), url
.c_str());
1847 // No need to swallow the event, since this might interfere with the
1848 // scrollbars if the user is dragging them.
1852 // We're selecting but right now we're not over text, so don't change the
1853 // current selection.
1854 if (area
!= PDFiumPage::TEXT_AREA
&& area
!= PDFiumPage::WEBLINK_AREA
&&
1855 area
!= PDFiumPage::DOCLINK_AREA
) {
1859 SelectionChangeInvalidator
selection_invalidator(this);
1861 // Check if the user has descreased their selection area and we need to remove
1862 // pages from selection_.
1863 for (size_t i
= 0; i
< selection_
.size(); ++i
) {
1864 if (selection_
[i
].page_index() == page_index
) {
1865 // There should be no other pages after this.
1866 selection_
.erase(selection_
.begin() + i
+ 1, selection_
.end());
1871 if (selection_
.size() == 0)
1874 int last
= selection_
.size() - 1;
1875 if (selection_
[last
].page_index() == page_index
) {
1876 // Selecting within a page.
1878 if (char_index
>= selection_
[last
].char_index()) {
1879 // Selecting forward.
1880 count
= char_index
- selection_
[last
].char_index() + 1;
1882 count
= char_index
- selection_
[last
].char_index() - 1;
1884 selection_
[last
].SetCharCount(count
);
1885 } else if (selection_
[last
].page_index() < page_index
) {
1886 // Selecting into the next page.
1888 // First make sure that there are no gaps in selection, i.e. if mousedown on
1889 // page one but we only get mousemove over page three, we want page two.
1890 for (int i
= selection_
[last
].page_index() + 1; i
< page_index
; ++i
) {
1891 selection_
.push_back(PDFiumRange(pages_
[i
], 0,
1892 pages_
[i
]->GetCharCount()));
1895 int count
= pages_
[selection_
[last
].page_index()]->GetCharCount();
1896 selection_
[last
].SetCharCount(count
- selection_
[last
].char_index());
1897 selection_
.push_back(PDFiumRange(pages_
[page_index
], 0, char_index
));
1899 // Selecting into the previous page.
1900 // The selection's char_index is 0-based, so the character count is one
1901 // more than the index. The character count needs to be negative to
1902 // indicate a backwards selection.
1903 selection_
[last
].SetCharCount(-(selection_
[last
].char_index() + 1));
1905 // First make sure that there are no gaps in selection, i.e. if mousedown on
1906 // page three but we only get mousemove over page one, we want page two.
1907 for (int i
= selection_
[last
].page_index() - 1; i
> page_index
; --i
) {
1908 selection_
.push_back(PDFiumRange(pages_
[i
], 0,
1909 pages_
[i
]->GetCharCount()));
1912 int count
= pages_
[page_index
]->GetCharCount();
1913 selection_
.push_back(
1914 PDFiumRange(pages_
[page_index
], count
, count
- char_index
));
1920 bool PDFiumEngine::OnKeyDown(const pp::KeyboardInputEvent
& event
) {
1921 if (last_page_mouse_down_
== -1)
1924 bool rv
= !!FORM_OnKeyDown(
1925 form_
, pages_
[last_page_mouse_down_
]->GetPage(),
1926 event
.GetKeyCode(), event
.GetModifiers());
1928 if (event
.GetKeyCode() == ui::VKEY_BACK
||
1929 event
.GetKeyCode() == ui::VKEY_ESCAPE
) {
1930 // Chrome doesn't send char events for backspace or escape keys, see
1931 // PlatformKeyboardEventBuilder::isCharacterKey() and
1932 // http://chrome-corpsvn.mtv.corp.google.com/viewvc?view=rev&root=chrome&revision=31805
1933 // for more information. So just fake one since PDFium uses it.
1935 str
.push_back(event
.GetKeyCode());
1936 pp::KeyboardInputEvent
synthesized(pp::KeyboardInputEvent(
1937 client_
->GetPluginInstance(),
1938 PP_INPUTEVENT_TYPE_CHAR
,
1939 event
.GetTimeStamp(),
1940 event
.GetModifiers(),
1943 OnChar(synthesized
);
1949 bool PDFiumEngine::OnKeyUp(const pp::KeyboardInputEvent
& event
) {
1950 if (last_page_mouse_down_
== -1)
1953 return !!FORM_OnKeyUp(
1954 form_
, pages_
[last_page_mouse_down_
]->GetPage(),
1955 event
.GetKeyCode(), event
.GetModifiers());
1958 bool PDFiumEngine::OnChar(const pp::KeyboardInputEvent
& event
) {
1959 if (last_page_mouse_down_
== -1)
1962 base::string16 str
= base::UTF8ToUTF16(event
.GetCharacterText().AsString());
1963 return !!FORM_OnChar(
1964 form_
, pages_
[last_page_mouse_down_
]->GetPage(),
1966 event
.GetModifiers());
1969 void PDFiumEngine::StartFind(const char* text
, bool case_sensitive
) {
1970 // We can get a call to StartFind before we have any page information (i.e.
1971 // before the first call to LoadDocument has happened). Handle this case.
1975 bool first_search
= false;
1976 int character_to_start_searching_from
= 0;
1977 if (current_find_text_
!= text
) { // First time we search for this text.
1978 first_search
= true;
1979 std::vector
<PDFiumRange
> old_selection
= selection_
;
1981 current_find_text_
= text
;
1983 if (old_selection
.empty()) {
1984 // Start searching from the beginning of the document.
1985 next_page_to_search_
= 0;
1986 last_page_to_search_
= pages_
.size() - 1;
1987 last_character_index_to_search_
= -1;
1989 // There's a current selection, so start from it.
1990 next_page_to_search_
= old_selection
[0].page_index();
1991 last_character_index_to_search_
= old_selection
[0].char_index();
1992 character_to_start_searching_from
= old_selection
[0].char_index();
1993 last_page_to_search_
= next_page_to_search_
;
1997 int current_page
= next_page_to_search_
;
1999 if (pages_
[current_page
]->available()) {
2000 base::string16 str
= base::UTF8ToUTF16(text
);
2001 // Don't use PDFium to search for now, since it doesn't support unicode
2002 // text. Leave the code for now to avoid bit-rot, in case it's fixed later.
2005 str
, case_sensitive
, first_search
, character_to_start_searching_from
,
2009 str
, case_sensitive
, first_search
, character_to_start_searching_from
,
2013 if (!IsPageVisible(current_page
))
2014 pages_
[current_page
]->Unload();
2017 if (next_page_to_search_
!= last_page_to_search_
||
2018 (first_search
&& last_character_index_to_search_
!= -1)) {
2019 ++next_page_to_search_
;
2022 if (next_page_to_search_
== static_cast<int>(pages_
.size()))
2023 next_page_to_search_
= 0;
2024 // If there's only one page in the document and we start searching midway,
2025 // then we'll want to search the page one more time.
2026 bool end_of_search
=
2027 next_page_to_search_
== last_page_to_search_
&&
2028 // Only one page but didn't start midway.
2029 ((pages_
.size() == 1 && last_character_index_to_search_
== -1) ||
2030 // Started midway, but only 1 page and we already looped around.
2031 (pages_
.size() == 1 && !first_search
) ||
2032 // Started midway, and we've just looped around.
2033 (pages_
.size() > 1 && current_page
== next_page_to_search_
));
2035 if (end_of_search
) {
2036 // Send the final notification.
2037 client_
->NotifyNumberOfFindResultsChanged(find_results_
.size(), true);
2039 // When searching is complete, resume finding at a particular index.
2040 // Assuming the user has not clicked the find button in the meanwhile.
2041 if (resume_find_index_
.valid() && !current_find_index_
.valid()) {
2042 size_t resume_index
= resume_find_index_
.GetIndex();
2043 if (resume_index
>= find_results_
.size()) {
2044 // This might happen if the PDF has some dynamically generated text?
2047 current_find_index_
.SetIndex(resume_index
);
2048 client_
->NotifySelectedFindResultChanged(resume_index
);
2050 resume_find_index_
.Invalidate();
2052 pp::CompletionCallback callback
=
2053 find_factory_
.NewCallback(&PDFiumEngine::ContinueFind
);
2054 pp::Module::Get()->core()->CallOnMainThread(
2055 0, callback
, case_sensitive
? 1 : 0);
2059 void PDFiumEngine::SearchUsingPDFium(const base::string16
& term
,
2060 bool case_sensitive
,
2062 int character_to_start_searching_from
,
2064 // Find all the matches in the current page.
2065 unsigned long flags
= case_sensitive
? FPDF_MATCHCASE
: 0;
2066 FPDF_SCHHANDLE find
= FPDFText_FindStart(
2067 pages_
[current_page
]->GetTextPage(),
2068 reinterpret_cast<const unsigned short*>(term
.c_str()),
2069 flags
, character_to_start_searching_from
);
2071 // Note: since we search one page at a time, we don't find matches across
2072 // page boundaries. We could do this manually ourself, but it seems low
2073 // priority since Reader itself doesn't do it.
2074 while (FPDFText_FindNext(find
)) {
2075 PDFiumRange
result(pages_
[current_page
],
2076 FPDFText_GetSchResultIndex(find
),
2077 FPDFText_GetSchCount(find
));
2079 if (!first_search
&&
2080 last_character_index_to_search_
!= -1 &&
2081 result
.page_index() == last_page_to_search_
&&
2082 result
.char_index() >= last_character_index_to_search_
) {
2086 AddFindResult(result
);
2089 FPDFText_FindClose(find
);
2092 void PDFiumEngine::SearchUsingICU(const base::string16
& term
,
2093 bool case_sensitive
,
2095 int character_to_start_searching_from
,
2097 base::string16 page_text
;
2098 int text_length
= pages_
[current_page
]->GetCharCount();
2099 if (character_to_start_searching_from
) {
2100 text_length
-= character_to_start_searching_from
;
2101 } else if (!first_search
&&
2102 last_character_index_to_search_
!= -1 &&
2103 current_page
== last_page_to_search_
) {
2104 text_length
= last_character_index_to_search_
;
2106 if (text_length
<= 0)
2109 PDFiumAPIStringBufferAdapter
<base::string16
> api_string_adapter(&page_text
,
2112 unsigned short* data
=
2113 reinterpret_cast<unsigned short*>(api_string_adapter
.GetData());
2114 int written
= FPDFText_GetText(pages_
[current_page
]->GetTextPage(),
2115 character_to_start_searching_from
,
2118 api_string_adapter
.Close(written
);
2120 std::vector
<PDFEngine::Client::SearchStringResult
> results
;
2121 client_
->SearchString(
2122 page_text
.c_str(), term
.c_str(), case_sensitive
, &results
);
2123 for (size_t i
= 0; i
< results
.size(); ++i
) {
2124 // Need to map the indexes from the page text, which may have generated
2125 // characters like space etc, to character indices from the page.
2126 int temp_start
= results
[i
].start_index
+ character_to_start_searching_from
;
2127 int start
= FPDFText_GetCharIndexFromTextIndex(
2128 pages_
[current_page
]->GetTextPage(), temp_start
);
2129 int end
= FPDFText_GetCharIndexFromTextIndex(
2130 pages_
[current_page
]->GetTextPage(),
2131 temp_start
+ results
[i
].length
);
2132 AddFindResult(PDFiumRange(pages_
[current_page
], start
, end
- start
));
2136 void PDFiumEngine::AddFindResult(const PDFiumRange
& result
) {
2137 // Figure out where to insert the new location, since we could have
2138 // started searching midway and now we wrapped.
2139 size_t result_index
;
2140 int page_index
= result
.page_index();
2141 int char_index
= result
.char_index();
2142 for (result_index
= 0; result_index
< find_results_
.size(); ++result_index
) {
2143 if (find_results_
[result_index
].page_index() > page_index
||
2144 (find_results_
[result_index
].page_index() == page_index
&&
2145 find_results_
[result_index
].char_index() > char_index
)) {
2149 find_results_
.insert(find_results_
.begin() + result_index
, result
);
2152 if (current_find_index_
.valid()) {
2153 if (result_index
<= current_find_index_
.GetIndex()) {
2154 // Update the current match index
2155 size_t find_index
= current_find_index_
.IncrementIndex();
2156 DCHECK_LT(find_index
, find_results_
.size());
2157 client_
->NotifySelectedFindResultChanged(current_find_index_
.GetIndex());
2159 } else if (!resume_find_index_
.valid()) {
2160 // Both indices are invalid. Select the first match.
2161 SelectFindResult(true);
2163 client_
->NotifyNumberOfFindResultsChanged(find_results_
.size(), false);
2166 bool PDFiumEngine::SelectFindResult(bool forward
) {
2167 if (find_results_
.empty()) {
2172 SelectionChangeInvalidator
selection_invalidator(this);
2174 // Move back/forward through the search locations we previously found.
2176 const size_t last_index
= find_results_
.size() - 1;
2177 if (current_find_index_
.valid()) {
2178 size_t current_index
= current_find_index_
.GetIndex();
2180 new_index
= (current_index
>= last_index
) ? 0 : current_index
+ 1;
2182 new_index
= (current_find_index_
.GetIndex() == 0) ?
2183 last_index
: current_index
- 1;
2186 new_index
= forward
? 0 : last_index
;
2188 current_find_index_
.SetIndex(new_index
);
2190 // Update the selection before telling the client to scroll, since it could
2193 selection_
.push_back(find_results_
[current_find_index_
.GetIndex()]);
2195 // If the result is not in view, scroll to it.
2196 pp::Rect bounding_rect
;
2197 pp::Rect visible_rect
= GetVisibleRect();
2198 // Use zoom of 1.0 since visible_rect is without zoom.
2199 std::vector
<pp::Rect
> rects
;
2200 rects
= find_results_
[current_find_index_
.GetIndex()].GetScreenRects(
2201 pp::Point(), 1.0, current_rotation_
);
2202 for (size_t i
= 0; i
< rects
.size(); ++i
)
2203 bounding_rect
= bounding_rect
.Union(rects
[i
]);
2204 if (!visible_rect
.Contains(bounding_rect
)) {
2205 pp::Point center
= bounding_rect
.CenterPoint();
2206 // Make the page centered.
2207 int new_y
= static_cast<int>(center
.y() * current_zoom_
) -
2208 static_cast<int>(visible_rect
.height() * current_zoom_
/ 2);
2211 client_
->ScrollToY(new_y
);
2213 // Only move horizontally if it's not visible.
2214 if (center
.x() < visible_rect
.x() || center
.x() > visible_rect
.right()) {
2215 int new_x
= static_cast<int>(center
.x() * current_zoom_
) -
2216 static_cast<int>(visible_rect
.width() * current_zoom_
/ 2);
2219 client_
->ScrollToX(new_x
);
2223 client_
->NotifySelectedFindResultChanged(current_find_index_
.GetIndex());
2227 void PDFiumEngine::StopFind() {
2228 SelectionChangeInvalidator
selection_invalidator(this);
2232 find_results_
.clear();
2233 next_page_to_search_
= -1;
2234 last_page_to_search_
= -1;
2235 last_character_index_to_search_
= -1;
2236 current_find_index_
.Invalidate();
2237 current_find_text_
.clear();
2239 find_factory_
.CancelAll();
2242 void PDFiumEngine::GetAllScreenRectsUnion(std::vector
<PDFiumRange
>* rect_range
,
2243 const pp::Point
& offset_point
,
2244 std::vector
<pp::Rect
>* rect_vector
) {
2245 for (std::vector
<PDFiumRange
>::iterator it
= rect_range
->begin();
2246 it
!= rect_range
->end(); ++it
) {
2248 std::vector
<pp::Rect
> rects
=
2249 it
->GetScreenRects(offset_point
, current_zoom_
, current_rotation_
);
2250 for (size_t j
= 0; j
< rects
.size(); ++j
)
2251 rect
= rect
.Union(rects
[j
]);
2252 rect_vector
->push_back(rect
);
2256 void PDFiumEngine::UpdateTickMarks() {
2257 std::vector
<pp::Rect
> tickmarks
;
2258 GetAllScreenRectsUnion(&find_results_
, pp::Point(0, 0), &tickmarks
);
2259 client_
->UpdateTickMarks(tickmarks
);
2262 void PDFiumEngine::ZoomUpdated(double new_zoom_level
) {
2265 current_zoom_
= new_zoom_level
;
2267 CalculateVisiblePages();
2271 void PDFiumEngine::RotateClockwise() {
2272 current_rotation_
= (current_rotation_
+ 1) % 4;
2276 void PDFiumEngine::RotateCounterclockwise() {
2277 current_rotation_
= (current_rotation_
- 1) % 4;
2281 void PDFiumEngine::InvalidateAllPages() {
2285 client_
->Invalidate(pp::Rect(plugin_size_
));
2288 std::string
PDFiumEngine::GetSelectedText() {
2289 if (!HasPermission(PDFEngine::PERMISSION_COPY
))
2290 return std::string();
2292 base::string16 result
;
2293 base::string16 new_line_char
= base::UTF8ToUTF16("\n");
2294 for (size_t i
= 0; i
< selection_
.size(); ++i
) {
2296 selection_
[i
- 1].page_index() > selection_
[i
].page_index()) {
2297 result
= selection_
[i
].GetText() + new_line_char
+ result
;
2300 result
.append(new_line_char
);
2301 result
.append(selection_
[i
].GetText());
2305 FormatStringWithHyphens(&result
);
2306 FormatStringForOS(&result
);
2307 return base::UTF16ToUTF8(result
);
2310 std::string
PDFiumEngine::GetLinkAtPosition(const pp::Point
& point
) {
2313 int page_index
= -1;
2314 int form_type
= FPDF_FORMFIELD_UNKNOWN
;
2315 PDFiumPage::LinkTarget target
;
2316 PDFiumPage::Area area
=
2317 GetCharIndex(point
, &page_index
, &temp
, &form_type
, &target
);
2318 if (area
== PDFiumPage::WEBLINK_AREA
)
2323 bool PDFiumEngine::IsSelecting() {
2327 bool PDFiumEngine::HasPermission(DocumentPermission permission
) const {
2328 // PDF 1.7 spec, section 3.5.2 says: "If the revision number is 2 or greater,
2329 // the operations to which user access can be controlled are as follows: ..."
2331 // Thus for revision numbers less than 2, permissions are ignored and this
2332 // always returns true.
2333 if (permissions_handler_revision_
< 2)
2336 // Handle high quality printing permission separately for security handler
2337 // revision 3+. See table 3.20 in the PDF 1.7 spec.
2338 if (permission
== PERMISSION_PRINT_HIGH_QUALITY
&&
2339 permissions_handler_revision_
>= 3) {
2340 return (permissions_
& kPDFPermissionPrintLowQualityMask
) != 0 &&
2341 (permissions_
& kPDFPermissionPrintHighQualityMask
) != 0;
2344 switch (permission
) {
2345 case PERMISSION_COPY
:
2346 return (permissions_
& kPDFPermissionCopyMask
) != 0;
2347 case PERMISSION_COPY_ACCESSIBLE
:
2348 return (permissions_
& kPDFPermissionCopyAccessibleMask
) != 0;
2349 case PERMISSION_PRINT_LOW_QUALITY
:
2350 case PERMISSION_PRINT_HIGH_QUALITY
:
2351 // With security handler revision 2 rules, check the same bit for high
2352 // and low quality. See table 3.20 in the PDF 1.7 spec.
2353 return (permissions_
& kPDFPermissionPrintLowQualityMask
) != 0;
2359 void PDFiumEngine::SelectAll() {
2360 SelectionChangeInvalidator
selection_invalidator(this);
2363 for (size_t i
= 0; i
< pages_
.size(); ++i
)
2364 if (pages_
[i
]->available()) {
2365 selection_
.push_back(PDFiumRange(pages_
[i
], 0,
2366 pages_
[i
]->GetCharCount()));
2370 int PDFiumEngine::GetNumberOfPages() {
2371 return pages_
.size();
2374 pp::VarArray
PDFiumEngine::GetBookmarks() {
2375 pp::VarDictionary dict
= TraverseBookmarks(doc_
, NULL
);
2376 // The root bookmark contains no useful information.
2377 return pp::VarArray(dict
.Get(pp::Var("children")));
2380 int PDFiumEngine::GetNamedDestinationPage(const std::string
& destination
) {
2381 // Look for the destination.
2382 FPDF_DEST dest
= FPDF_GetNamedDestByName(doc_
, destination
.c_str());
2384 // Look for a bookmark with the same name.
2385 base::string16 destination_wide
= base::UTF8ToUTF16(destination
);
2386 FPDF_WIDESTRING destination_pdf_wide
=
2387 reinterpret_cast<FPDF_WIDESTRING
>(destination_wide
.c_str());
2388 FPDF_BOOKMARK bookmark
= FPDFBookmark_Find(doc_
, destination_pdf_wide
);
2391 dest
= FPDFBookmark_GetDest(doc_
, bookmark
);
2393 return dest
? FPDFDest_GetPageIndex(doc_
, dest
) : -1;
2396 int PDFiumEngine::GetFirstVisiblePage() {
2397 CalculateVisiblePages();
2398 return first_visible_page_
;
2401 int PDFiumEngine::GetMostVisiblePage() {
2402 CalculateVisiblePages();
2403 return most_visible_page_
;
2406 pp::Rect
PDFiumEngine::GetPageRect(int index
) {
2407 pp::Rect
rc(pages_
[index
]->rect());
2408 rc
.Inset(-kPageShadowLeft
, -kPageShadowTop
,
2409 -kPageShadowRight
, -kPageShadowBottom
);
2413 pp::Rect
PDFiumEngine::GetPageContentsRect(int index
) {
2414 return GetScreenRect(pages_
[index
]->rect());
2417 void PDFiumEngine::PaintThumbnail(pp::ImageData
* image_data
, int index
) {
2418 FPDF_BITMAP bitmap
= FPDFBitmap_CreateEx(
2419 image_data
->size().width(), image_data
->size().height(),
2420 FPDFBitmap_BGRx
, image_data
->data(), image_data
->stride());
2422 if (pages_
[index
]->available()) {
2423 FPDFBitmap_FillRect(bitmap
, 0, 0, image_data
->size().width(),
2424 image_data
->size().height(), 0xFFFFFFFF);
2426 FPDF_RenderPageBitmap(
2427 bitmap
, pages_
[index
]->GetPage(), 0, 0, image_data
->size().width(),
2428 image_data
->size().height(), 0, GetRenderingFlags());
2430 FPDFBitmap_FillRect(bitmap
, 0, 0, image_data
->size().width(),
2431 image_data
->size().height(), kPendingPageColor
);
2434 FPDFBitmap_Destroy(bitmap
);
2437 void PDFiumEngine::SetGrayscale(bool grayscale
) {
2438 render_grayscale_
= grayscale
;
2441 void PDFiumEngine::OnCallback(int id
) {
2442 if (!timers_
.count(id
))
2445 timers_
[id
].second(id
);
2446 if (timers_
.count(id
)) // The callback might delete the timer.
2447 client_
->ScheduleCallback(id
, timers_
[id
].first
);
2450 std::string
PDFiumEngine::GetPageAsJSON(int index
) {
2451 if (!(HasPermission(PERMISSION_COPY
) ||
2452 HasPermission(PERMISSION_COPY_ACCESSIBLE
))) {
2456 if (index
< 0 || static_cast<size_t>(index
) > pages_
.size() - 1)
2459 scoped_ptr
<base::Value
> node(
2460 pages_
[index
]->GetAccessibleContentAsValue(current_rotation_
));
2461 std::string page_json
;
2462 base::JSONWriter::Write(*node
, &page_json
);
2466 bool PDFiumEngine::GetPrintScaling() {
2467 return !!FPDF_VIEWERREF_GetPrintScaling(doc_
);
2470 int PDFiumEngine::GetCopiesToPrint() {
2471 return FPDF_VIEWERREF_GetNumCopies(doc_
);
2474 int PDFiumEngine::GetDuplexType() {
2475 return static_cast<int>(FPDF_VIEWERREF_GetDuplex(doc_
));
2478 bool PDFiumEngine::GetPageSizeAndUniformity(pp::Size
* size
) {
2482 pp::Size page_size
= GetPageSize(0);
2483 for (size_t i
= 1; i
< pages_
.size(); ++i
) {
2484 if (page_size
!= GetPageSize(i
))
2488 // Convert |page_size| back to points.
2490 ConvertUnit(page_size
.width(), kPixelsPerInch
, kPointsPerInch
));
2492 ConvertUnit(page_size
.height(), kPixelsPerInch
, kPointsPerInch
));
2496 void PDFiumEngine::AppendBlankPages(int num_pages
) {
2497 DCHECK_NE(num_pages
, 0);
2503 pending_pages_
.clear();
2505 // Delete all pages except the first one.
2506 while (pages_
.size() > 1) {
2507 delete pages_
.back();
2509 FPDFPage_Delete(doc_
, pages_
.size());
2512 // Calculate document size and all page sizes.
2513 std::vector
<pp::Rect
> page_rects
;
2514 pp::Size page_size
= GetPageSize(0);
2515 page_size
.Enlarge(kPageShadowLeft
+ kPageShadowRight
,
2516 kPageShadowTop
+ kPageShadowBottom
);
2517 pp::Size old_document_size
= document_size_
;
2518 document_size_
= pp::Size(page_size
.width(), 0);
2519 for (int i
= 0; i
< num_pages
; ++i
) {
2521 // Add space for horizontal separator.
2522 document_size_
.Enlarge(0, kPageSeparatorThickness
);
2525 pp::Rect
rect(pp::Point(0, document_size_
.height()), page_size
);
2526 page_rects
.push_back(rect
);
2528 document_size_
.Enlarge(0, page_size
.height());
2531 // Create blank pages.
2532 for (int i
= 1; i
< num_pages
; ++i
) {
2533 pp::Rect
page_rect(page_rects
[i
]);
2534 page_rect
.Inset(kPageShadowLeft
, kPageShadowTop
,
2535 kPageShadowRight
, kPageShadowBottom
);
2536 double width_in_points
= ConvertUnitDouble(page_rect
.width(),
2539 double height_in_points
= ConvertUnitDouble(page_rect
.height(),
2542 FPDFPage_New(doc_
, i
, width_in_points
, height_in_points
);
2543 pages_
.push_back(new PDFiumPage(this, i
, page_rect
, true));
2546 CalculateVisiblePages();
2547 if (document_size_
!= old_document_size
)
2548 client_
->DocumentSizeUpdated(document_size_
);
2551 void PDFiumEngine::LoadDocument() {
2552 // Check if the document is ready for loading. If it isn't just bail for now,
2553 // we will call LoadDocument() again later.
2554 if (!doc_
&& !doc_loader_
.IsDocumentComplete() &&
2555 !FPDFAvail_IsDocAvail(fpdf_availability_
, &download_hints_
)) {
2559 // If we're in the middle of getting a password, just return. We will retry
2560 // loading the document after we get the password anyway.
2561 if (getting_password_
)
2564 ScopedUnsupportedFeature
scoped_unsupported_feature(this);
2565 bool needs_password
= false;
2566 if (TryLoadingDoc(false, std::string(), &needs_password
)) {
2567 ContinueLoadingDocument(false, std::string());
2571 GetPasswordAndLoad();
2573 client_
->DocumentLoadFailed();
2576 bool PDFiumEngine::TryLoadingDoc(bool with_password
,
2577 const std::string
& password
,
2578 bool* needs_password
) {
2579 *needs_password
= false;
2583 const char* password_cstr
= NULL
;
2584 if (with_password
) {
2585 password_cstr
= password
.c_str();
2586 password_tries_remaining_
--;
2588 if (doc_loader_
.IsDocumentComplete())
2589 doc_
= FPDF_LoadCustomDocument(&file_access_
, password_cstr
);
2591 doc_
= FPDFAvail_GetDocument(fpdf_availability_
, password_cstr
);
2593 if (!doc_
&& FPDF_GetLastError() == FPDF_ERR_PASSWORD
)
2594 *needs_password
= true;
2596 return doc_
!= NULL
;
2599 void PDFiumEngine::GetPasswordAndLoad() {
2600 getting_password_
= true;
2601 DCHECK(!doc_
&& FPDF_GetLastError() == FPDF_ERR_PASSWORD
);
2602 client_
->GetDocumentPassword(password_factory_
.NewCallbackWithOutput(
2603 &PDFiumEngine::OnGetPasswordComplete
));
2606 void PDFiumEngine::OnGetPasswordComplete(int32_t result
,
2607 const pp::Var
& password
) {
2608 getting_password_
= false;
2610 bool password_given
= false;
2611 std::string password_text
;
2612 if (result
== PP_OK
&& password
.is_string()) {
2613 password_text
= password
.AsString();
2614 if (!password_text
.empty())
2615 password_given
= true;
2617 ContinueLoadingDocument(password_given
, password_text
);
2620 void PDFiumEngine::ContinueLoadingDocument(
2622 const std::string
& password
) {
2623 ScopedUnsupportedFeature
scoped_unsupported_feature(this);
2625 bool needs_password
= false;
2626 bool loaded
= TryLoadingDoc(has_password
, password
, &needs_password
);
2627 bool password_incorrect
= !loaded
&& has_password
&& needs_password
;
2628 if (password_incorrect
&& password_tries_remaining_
> 0) {
2629 GetPasswordAndLoad();
2634 client_
->DocumentLoadFailed();
2638 if (FPDFDoc_GetPageMode(doc_
) == PAGEMODE_USEOUTLINES
)
2639 client_
->DocumentHasUnsupportedFeature("Bookmarks");
2641 permissions_
= FPDF_GetDocPermissions(doc_
);
2642 permissions_handler_revision_
= FPDF_GetSecurityHandlerRevision(doc_
);
2645 // Only returns 0 when data isn't available. If form data is downloaded, or
2646 // if this isn't a form, returns positive values.
2647 if (!doc_loader_
.IsDocumentComplete() &&
2648 !FPDFAvail_IsFormAvail(fpdf_availability_
, &download_hints_
)) {
2652 form_
= FPDFDOC_InitFormFillEnvironment(
2653 doc_
, static_cast<FPDF_FORMFILLINFO
*>(this));
2658 FPDF_SetFormFieldHighlightColor(form_
, 0, kFormHighlightColor
);
2659 FPDF_SetFormFieldHighlightAlpha(form_
, kFormHighlightAlpha
);
2662 if (!doc_loader_
.IsDocumentComplete()) {
2663 // Check if the first page is available. In a linearized PDF, that is not
2664 // always page 0. Doing this gives us the default page size, since when the
2665 // document is available, the first page is available as well.
2666 CheckPageAvailable(FPDFAvail_GetFirstPageNum(doc_
), &pending_pages_
);
2669 LoadPageInfo(false);
2671 if (doc_loader_
.IsDocumentComplete())
2672 FinishLoadingDocument();
2675 void PDFiumEngine::LoadPageInfo(bool reload
) {
2676 pending_pages_
.clear();
2677 pp::Size old_document_size
= document_size_
;
2678 document_size_
= pp::Size();
2679 std::vector
<pp::Rect
> page_rects
;
2680 int page_count
= FPDF_GetPageCount(doc_
);
2681 bool doc_complete
= doc_loader_
.IsDocumentComplete();
2682 for (int i
= 0; i
< page_count
; ++i
) {
2684 // Add space for horizontal separator.
2685 document_size_
.Enlarge(0, kPageSeparatorThickness
);
2688 // Get page availability. If reload==false, and document is not loaded yet
2689 // (we are using async loading) - mark all pages as unavailable.
2690 // If reload==true (we have document constructed already), get page
2691 // availability flag from already existing PDFiumPage class.
2692 bool page_available
= reload
? pages_
[i
]->available() : doc_complete
;
2694 pp::Size size
= page_available
? GetPageSize(i
) : default_page_size_
;
2695 size
.Enlarge(kPageShadowLeft
+ kPageShadowRight
,
2696 kPageShadowTop
+ kPageShadowBottom
);
2697 pp::Rect
rect(pp::Point(0, document_size_
.height()), size
);
2698 page_rects
.push_back(rect
);
2700 if (size
.width() > document_size_
.width())
2701 document_size_
.set_width(size
.width());
2703 document_size_
.Enlarge(0, size
.height());
2706 for (int i
= 0; i
< page_count
; ++i
) {
2707 // Center pages relative to the entire document.
2708 page_rects
[i
].set_x((document_size_
.width() - page_rects
[i
].width()) / 2);
2709 pp::Rect
page_rect(page_rects
[i
]);
2710 page_rect
.Inset(kPageShadowLeft
, kPageShadowTop
,
2711 kPageShadowRight
, kPageShadowBottom
);
2713 pages_
[i
]->set_rect(page_rect
);
2715 pages_
.push_back(new PDFiumPage(this, i
, page_rect
, doc_complete
));
2719 CalculateVisiblePages();
2720 if (document_size_
!= old_document_size
)
2721 client_
->DocumentSizeUpdated(document_size_
);
2724 void PDFiumEngine::CalculateVisiblePages() {
2725 // Clear pending requests queue, since it may contain requests to the pages
2726 // that are already invisible (after scrolling for example).
2727 pending_pages_
.clear();
2728 doc_loader_
.ClearPendingRequests();
2730 visible_pages_
.clear();
2731 pp::Rect
visible_rect(plugin_size_
);
2732 for (size_t i
= 0; i
< pages_
.size(); ++i
) {
2733 // Check an entire PageScreenRect, since we might need to repaint side
2734 // borders and shadows even if the page itself is not visible.
2735 // For example, when user use pdf with different page sizes and zoomed in
2736 // outside page area.
2737 if (visible_rect
.Intersects(GetPageScreenRect(i
))) {
2738 visible_pages_
.push_back(i
);
2739 CheckPageAvailable(i
, &pending_pages_
);
2741 // Need to unload pages when we're not using them, since some PDFs use a
2742 // lot of memory. See http://crbug.com/48791
2743 if (defer_page_unload_
) {
2744 deferred_page_unloads_
.push_back(i
);
2746 pages_
[i
]->Unload();
2749 // If the last mouse down was on a page that's no longer visible, reset
2750 // that variable so that we don't send keyboard events to it (the focus
2751 // will be lost when the page is first closed anyways).
2752 if (static_cast<int>(i
) == last_page_mouse_down_
)
2753 last_page_mouse_down_
= -1;
2757 // Any pending highlighting of form fields will be invalid since these are in
2758 // screen coordinates.
2759 form_highlights_
.clear();
2761 if (visible_pages_
.size() == 0)
2762 first_visible_page_
= -1;
2764 first_visible_page_
= visible_pages_
.front();
2766 int most_visible_page
= first_visible_page_
;
2767 // Check if the next page is more visible than the first one.
2768 if (most_visible_page
!= -1 &&
2769 pages_
.size() > 0 &&
2770 most_visible_page
< static_cast<int>(pages_
.size()) - 1) {
2772 visible_rect
.Intersect(GetPageScreenRect(most_visible_page
));
2774 visible_rect
.Intersect(GetPageScreenRect(most_visible_page
+ 1));
2775 if (rc_next
.height() > rc_first
.height())
2776 most_visible_page
++;
2779 SetCurrentPage(most_visible_page
);
2782 bool PDFiumEngine::IsPageVisible(int index
) const {
2783 for (size_t i
= 0; i
< visible_pages_
.size(); ++i
) {
2784 if (visible_pages_
[i
] == index
)
2791 bool PDFiumEngine::CheckPageAvailable(int index
, std::vector
<int>* pending
) {
2792 if (!doc_
|| !form_
)
2795 if (static_cast<int>(pages_
.size()) > index
&& pages_
[index
]->available())
2798 if (!FPDFAvail_IsPageAvail(fpdf_availability_
, index
, &download_hints_
)) {
2800 for (j
= 0; j
< pending
->size(); ++j
) {
2801 if ((*pending
)[j
] == index
)
2805 if (j
== pending
->size())
2806 pending
->push_back(index
);
2810 if (static_cast<int>(pages_
.size()) > index
)
2811 pages_
[index
]->set_available(true);
2812 if (!default_page_size_
.GetArea())
2813 default_page_size_
= GetPageSize(index
);
2817 pp::Size
PDFiumEngine::GetPageSize(int index
) {
2819 double width_in_points
= 0;
2820 double height_in_points
= 0;
2821 int rv
= FPDF_GetPageSizeByIndex(
2822 doc_
, index
, &width_in_points
, &height_in_points
);
2825 int width_in_pixels
= static_cast<int>(
2826 ConvertUnitDouble(width_in_points
, kPointsPerInch
, kPixelsPerInch
));
2827 int height_in_pixels
= static_cast<int>(
2828 ConvertUnitDouble(height_in_points
, kPointsPerInch
, kPixelsPerInch
));
2829 if (current_rotation_
% 2 == 1)
2830 std::swap(width_in_pixels
, height_in_pixels
);
2831 size
= pp::Size(width_in_pixels
, height_in_pixels
);
2836 int PDFiumEngine::StartPaint(int page_index
, const pp::Rect
& dirty
) {
2837 // For the first time we hit paint, do nothing and just record the paint for
2838 // the next callback. This keeps the UI responsive in case the user is doing
2839 // a lot of scrolling.
2840 ProgressivePaint progressive
;
2841 progressive
.rect
= dirty
;
2842 progressive
.page_index
= page_index
;
2843 progressive
.bitmap
= NULL
;
2844 progressive
.painted_
= false;
2845 progressive_paints_
.push_back(progressive
);
2846 return progressive_paints_
.size() - 1;
2849 bool PDFiumEngine::ContinuePaint(int progressive_index
,
2850 pp::ImageData
* image_data
) {
2851 DCHECK_GE(progressive_index
, 0);
2852 DCHECK_LT(static_cast<size_t>(progressive_index
), progressive_paints_
.size());
2855 #if defined(OS_LINUX)
2856 g_last_instance_id
= client_
->GetPluginInstance()->pp_instance();
2860 FPDF_BITMAP bitmap
= progressive_paints_
[progressive_index
].bitmap
;
2861 int page_index
= progressive_paints_
[progressive_index
].page_index
;
2862 DCHECK_GE(page_index
, 0);
2863 DCHECK_LT(static_cast<size_t>(page_index
), pages_
.size());
2864 FPDF_PAGE page
= pages_
[page_index
]->GetPage();
2866 last_progressive_start_time_
= base::Time::Now();
2868 rv
= FPDF_RenderPage_Continue(page
, static_cast<IFSDK_PAUSE
*>(this));
2870 pp::Rect dirty
= progressive_paints_
[progressive_index
].rect
;
2871 bitmap
= CreateBitmap(dirty
, image_data
);
2872 int start_x
, start_y
, size_x
, size_y
;
2873 GetPDFiumRect(page_index
, dirty
, &start_x
, &start_y
, &size_x
, &size_y
);
2874 FPDFBitmap_FillRect(bitmap
, start_x
, start_y
, size_x
, size_y
, 0xFFFFFFFF);
2875 rv
= FPDF_RenderPageBitmap_Start(
2876 bitmap
, page
, start_x
, start_y
, size_x
, size_y
,
2878 GetRenderingFlags(), static_cast<IFSDK_PAUSE
*>(this));
2879 progressive_paints_
[progressive_index
].bitmap
= bitmap
;
2881 return rv
!= FPDF_RENDER_TOBECOUNTINUED
;
2884 void PDFiumEngine::FinishPaint(int progressive_index
,
2885 pp::ImageData
* image_data
) {
2886 DCHECK_GE(progressive_index
, 0);
2887 DCHECK_LT(static_cast<size_t>(progressive_index
), progressive_paints_
.size());
2890 int page_index
= progressive_paints_
[progressive_index
].page_index
;
2891 pp::Rect dirty_in_screen
= progressive_paints_
[progressive_index
].rect
;
2892 FPDF_BITMAP bitmap
= progressive_paints_
[progressive_index
].bitmap
;
2893 int start_x
, start_y
, size_x
, size_y
;
2895 page_index
, dirty_in_screen
, &start_x
, &start_y
, &size_x
, &size_y
);
2899 form_
, bitmap
, pages_
[page_index
]->GetPage(), start_x
, start_y
, size_x
,
2900 size_y
, current_rotation_
, GetRenderingFlags());
2902 FillPageSides(progressive_index
);
2904 // Paint the page shadows.
2905 PaintPageShadow(progressive_index
, image_data
);
2907 DrawSelections(progressive_index
, image_data
);
2909 FPDF_RenderPage_Close(pages_
[page_index
]->GetPage());
2910 FPDFBitmap_Destroy(bitmap
);
2911 progressive_paints_
.erase(progressive_paints_
.begin() + progressive_index
);
2913 client_
->DocumentPaintOccurred();
2916 void PDFiumEngine::CancelPaints() {
2917 for (size_t i
= 0; i
< progressive_paints_
.size(); ++i
) {
2918 FPDF_RenderPage_Close(pages_
[progressive_paints_
[i
].page_index
]->GetPage());
2919 FPDFBitmap_Destroy(progressive_paints_
[i
].bitmap
);
2921 progressive_paints_
.clear();
2924 void PDFiumEngine::FillPageSides(int progressive_index
) {
2925 DCHECK_GE(progressive_index
, 0);
2926 DCHECK_LT(static_cast<size_t>(progressive_index
), progressive_paints_
.size());
2928 int page_index
= progressive_paints_
[progressive_index
].page_index
;
2929 pp::Rect dirty_in_screen
= progressive_paints_
[progressive_index
].rect
;
2930 FPDF_BITMAP bitmap
= progressive_paints_
[progressive_index
].bitmap
;
2932 pp::Rect page_rect
= pages_
[page_index
]->rect();
2933 if (page_rect
.x() > 0) {
2935 page_rect
.y() - kPageShadowTop
,
2936 page_rect
.x() - kPageShadowLeft
,
2937 page_rect
.height() + kPageShadowTop
+
2938 kPageShadowBottom
+ kPageSeparatorThickness
);
2939 left
= GetScreenRect(left
).Intersect(dirty_in_screen
);
2941 FPDFBitmap_FillRect(bitmap
, left
.x() - dirty_in_screen
.x(),
2942 left
.y() - dirty_in_screen
.y(), left
.width(),
2943 left
.height(), client_
->GetBackgroundColor());
2946 if (page_rect
.right() < document_size_
.width()) {
2947 pp::Rect
right(page_rect
.right() + kPageShadowRight
,
2948 page_rect
.y() - kPageShadowTop
,
2949 document_size_
.width() - page_rect
.right() -
2951 page_rect
.height() + kPageShadowTop
+
2952 kPageShadowBottom
+ kPageSeparatorThickness
);
2953 right
= GetScreenRect(right
).Intersect(dirty_in_screen
);
2955 FPDFBitmap_FillRect(bitmap
, right
.x() - dirty_in_screen
.x(),
2956 right
.y() - dirty_in_screen
.y(), right
.width(),
2957 right
.height(), client_
->GetBackgroundColor());
2961 pp::Rect
bottom(page_rect
.x() - kPageShadowLeft
,
2962 page_rect
.bottom() + kPageShadowBottom
,
2963 page_rect
.width() + kPageShadowLeft
+ kPageShadowRight
,
2964 kPageSeparatorThickness
);
2965 bottom
= GetScreenRect(bottom
).Intersect(dirty_in_screen
);
2967 FPDFBitmap_FillRect(bitmap
, bottom
.x() - dirty_in_screen
.x(),
2968 bottom
.y() - dirty_in_screen
.y(), bottom
.width(),
2969 bottom
.height(), client_
->GetBackgroundColor());
2972 void PDFiumEngine::PaintPageShadow(int progressive_index
,
2973 pp::ImageData
* image_data
) {
2974 DCHECK_GE(progressive_index
, 0);
2975 DCHECK_LT(static_cast<size_t>(progressive_index
), progressive_paints_
.size());
2978 int page_index
= progressive_paints_
[progressive_index
].page_index
;
2979 pp::Rect dirty_in_screen
= progressive_paints_
[progressive_index
].rect
;
2980 pp::Rect page_rect
= pages_
[page_index
]->rect();
2981 pp::Rect
shadow_rect(page_rect
);
2982 shadow_rect
.Inset(-kPageShadowLeft
, -kPageShadowTop
,
2983 -kPageShadowRight
, -kPageShadowBottom
);
2985 // Due to the rounding errors of the GetScreenRect it is possible to get
2986 // different size shadows on the left and right sides even they are defined
2987 // the same. To fix this issue let's calculate shadow rect and then shrink
2988 // it by the size of the shadows.
2989 shadow_rect
= GetScreenRect(shadow_rect
);
2990 page_rect
= shadow_rect
;
2992 page_rect
.Inset(static_cast<int>(ceil(kPageShadowLeft
* current_zoom_
)),
2993 static_cast<int>(ceil(kPageShadowTop
* current_zoom_
)),
2994 static_cast<int>(ceil(kPageShadowRight
* current_zoom_
)),
2995 static_cast<int>(ceil(kPageShadowBottom
* current_zoom_
)));
2997 DrawPageShadow(page_rect
, shadow_rect
, dirty_in_screen
, image_data
);
3000 void PDFiumEngine::DrawSelections(int progressive_index
,
3001 pp::ImageData
* image_data
) {
3002 DCHECK_GE(progressive_index
, 0);
3003 DCHECK_LT(static_cast<size_t>(progressive_index
), progressive_paints_
.size());
3006 int page_index
= progressive_paints_
[progressive_index
].page_index
;
3007 pp::Rect dirty_in_screen
= progressive_paints_
[progressive_index
].rect
;
3009 void* region
= NULL
;
3011 GetRegion(dirty_in_screen
.point(), image_data
, ®ion
, &stride
);
3013 std::vector
<pp::Rect
> highlighted_rects
;
3014 pp::Rect visible_rect
= GetVisibleRect();
3015 for (size_t k
= 0; k
< selection_
.size(); ++k
) {
3016 if (selection_
[k
].page_index() != page_index
)
3018 std::vector
<pp::Rect
> rects
= selection_
[k
].GetScreenRects(
3019 visible_rect
.point(), current_zoom_
, current_rotation_
);
3020 for (size_t j
= 0; j
< rects
.size(); ++j
) {
3021 pp::Rect visible_selection
= rects
[j
].Intersect(dirty_in_screen
);
3022 if (visible_selection
.IsEmpty())
3025 visible_selection
.Offset(
3026 -dirty_in_screen
.point().x(), -dirty_in_screen
.point().y());
3027 Highlight(region
, stride
, visible_selection
, &highlighted_rects
);
3031 for (size_t k
= 0; k
< form_highlights_
.size(); ++k
) {
3032 pp::Rect visible_selection
= form_highlights_
[k
].Intersect(dirty_in_screen
);
3033 if (visible_selection
.IsEmpty())
3036 visible_selection
.Offset(
3037 -dirty_in_screen
.point().x(), -dirty_in_screen
.point().y());
3038 Highlight(region
, stride
, visible_selection
, &highlighted_rects
);
3040 form_highlights_
.clear();
3043 void PDFiumEngine::PaintUnavailablePage(int page_index
,
3044 const pp::Rect
& dirty
,
3045 pp::ImageData
* image_data
) {
3046 int start_x
, start_y
, size_x
, size_y
;
3047 GetPDFiumRect(page_index
, dirty
, &start_x
, &start_y
, &size_x
, &size_y
);
3048 FPDF_BITMAP bitmap
= CreateBitmap(dirty
, image_data
);
3049 FPDFBitmap_FillRect(bitmap
, start_x
, start_y
, size_x
, size_y
,
3052 pp::Rect
loading_text_in_screen(
3053 pages_
[page_index
]->rect().width() / 2,
3054 pages_
[page_index
]->rect().y() + kLoadingTextVerticalOffset
, 0, 0);
3055 loading_text_in_screen
= GetScreenRect(loading_text_in_screen
);
3056 FPDFBitmap_Destroy(bitmap
);
3059 int PDFiumEngine::GetProgressiveIndex(int page_index
) const {
3060 for (size_t i
= 0; i
< progressive_paints_
.size(); ++i
) {
3061 if (progressive_paints_
[i
].page_index
== page_index
)
3067 FPDF_BITMAP
PDFiumEngine::CreateBitmap(const pp::Rect
& rect
,
3068 pp::ImageData
* image_data
) const {
3071 GetRegion(rect
.point(), image_data
, ®ion
, &stride
);
3074 return FPDFBitmap_CreateEx(
3075 rect
.width(), rect
.height(), FPDFBitmap_BGRx
, region
, stride
);
3078 void PDFiumEngine::GetPDFiumRect(
3079 int page_index
, const pp::Rect
& rect
, int* start_x
, int* start_y
,
3080 int* size_x
, int* size_y
) const {
3081 pp::Rect page_rect
= GetScreenRect(pages_
[page_index
]->rect());
3082 page_rect
.Offset(-rect
.x(), -rect
.y());
3084 *start_x
= page_rect
.x();
3085 *start_y
= page_rect
.y();
3086 *size_x
= page_rect
.width();
3087 *size_y
= page_rect
.height();
3090 int PDFiumEngine::GetRenderingFlags() const {
3091 int flags
= FPDF_LCD_TEXT
| FPDF_NO_CATCH
;
3092 if (render_grayscale_
)
3093 flags
|= FPDF_GRAYSCALE
;
3094 if (client_
->IsPrintPreview())
3095 flags
|= FPDF_PRINTING
;
3099 pp::Rect
PDFiumEngine::GetVisibleRect() const {
3101 rv
.set_x(static_cast<int>(position_
.x() / current_zoom_
));
3102 rv
.set_y(static_cast<int>(position_
.y() / current_zoom_
));
3103 rv
.set_width(static_cast<int>(ceil(plugin_size_
.width() / current_zoom_
)));
3104 rv
.set_height(static_cast<int>(ceil(plugin_size_
.height() / current_zoom_
)));
3108 pp::Rect
PDFiumEngine::GetPageScreenRect(int page_index
) const {
3109 // Since we use this rect for creating the PDFium bitmap, also include other
3110 // areas around the page that we might need to update such as the page
3111 // separator and the sides if the page is narrower than the document.
3112 return GetScreenRect(pp::Rect(
3114 pages_
[page_index
]->rect().y() - kPageShadowTop
,
3115 document_size_
.width(),
3116 pages_
[page_index
]->rect().height() + kPageShadowTop
+
3117 kPageShadowBottom
+ kPageSeparatorThickness
));
3120 pp::Rect
PDFiumEngine::GetScreenRect(const pp::Rect
& rect
) const {
3123 static_cast<int>(ceil(rect
.right() * current_zoom_
- position_
.x()));
3125 static_cast<int>(ceil(rect
.bottom() * current_zoom_
- position_
.y()));
3127 rv
.set_x(static_cast<int>(rect
.x() * current_zoom_
- position_
.x()));
3128 rv
.set_y(static_cast<int>(rect
.y() * current_zoom_
- position_
.y()));
3129 rv
.set_width(right
- rv
.x());
3130 rv
.set_height(bottom
- rv
.y());
3134 void PDFiumEngine::Highlight(void* buffer
,
3136 const pp::Rect
& rect
,
3137 std::vector
<pp::Rect
>* highlighted_rects
) {
3141 pp::Rect new_rect
= rect
;
3142 for (size_t i
= 0; i
< highlighted_rects
->size(); ++i
)
3143 new_rect
= new_rect
.Subtract((*highlighted_rects
)[i
]);
3145 highlighted_rects
->push_back(new_rect
);
3146 int l
= new_rect
.x();
3147 int t
= new_rect
.y();
3148 int w
= new_rect
.width();
3149 int h
= new_rect
.height();
3151 for (int y
= t
; y
< t
+ h
; ++y
) {
3152 for (int x
= l
; x
< l
+ w
; ++x
) {
3153 uint8
* pixel
= static_cast<uint8
*>(buffer
) + y
* stride
+ x
* 4;
3154 // This is our highlight color.
3155 pixel
[0] = static_cast<uint8
>(
3156 pixel
[0] * (kHighlightColorB
/ 255.0));
3157 pixel
[1] = static_cast<uint8
>(
3158 pixel
[1] * (kHighlightColorG
/ 255.0));
3159 pixel
[2] = static_cast<uint8
>(
3160 pixel
[2] * (kHighlightColorR
/ 255.0));
3165 PDFiumEngine::SelectionChangeInvalidator::SelectionChangeInvalidator(
3166 PDFiumEngine
* engine
) : engine_(engine
) {
3167 previous_origin_
= engine_
->GetVisibleRect().point();
3168 GetVisibleSelectionsScreenRects(&old_selections_
);
3171 PDFiumEngine::SelectionChangeInvalidator::~SelectionChangeInvalidator() {
3172 // Offset the old selections if the document scrolled since we recorded them.
3173 pp::Point offset
= previous_origin_
- engine_
->GetVisibleRect().point();
3174 for (size_t i
= 0; i
< old_selections_
.size(); ++i
)
3175 old_selections_
[i
].Offset(offset
);
3177 std::vector
<pp::Rect
> new_selections
;
3178 GetVisibleSelectionsScreenRects(&new_selections
);
3179 for (size_t i
= 0; i
< new_selections
.size(); ++i
) {
3180 for (size_t j
= 0; j
< old_selections_
.size(); ++j
) {
3181 if (!old_selections_
[j
].IsEmpty() &&
3182 new_selections
[i
] == old_selections_
[j
]) {
3183 // Rectangle was selected before and after, so no need to invalidate it.
3184 // Mark the rectangles by setting them to empty.
3185 new_selections
[i
] = old_selections_
[j
] = pp::Rect();
3191 for (size_t i
= 0; i
< old_selections_
.size(); ++i
) {
3192 if (!old_selections_
[i
].IsEmpty())
3193 engine_
->client_
->Invalidate(old_selections_
[i
]);
3195 for (size_t i
= 0; i
< new_selections
.size(); ++i
) {
3196 if (!new_selections
[i
].IsEmpty())
3197 engine_
->client_
->Invalidate(new_selections
[i
]);
3199 engine_
->OnSelectionChanged();
3203 PDFiumEngine::SelectionChangeInvalidator::GetVisibleSelectionsScreenRects(
3204 std::vector
<pp::Rect
>* rects
) {
3205 pp::Rect visible_rect
= engine_
->GetVisibleRect();
3206 for (size_t i
= 0; i
< engine_
->selection_
.size(); ++i
) {
3207 int page_index
= engine_
->selection_
[i
].page_index();
3208 if (!engine_
->IsPageVisible(page_index
))
3209 continue; // This selection is on a page that's not currently visible.
3211 std::vector
<pp::Rect
> selection_rects
=
3212 engine_
->selection_
[i
].GetScreenRects(
3213 visible_rect
.point(),
3214 engine_
->current_zoom_
,
3215 engine_
->current_rotation_
);
3216 rects
->insert(rects
->end(), selection_rects
.begin(), selection_rects
.end());
3220 PDFiumEngine::MouseDownState::MouseDownState(
3221 const PDFiumPage::Area
& area
,
3222 const PDFiumPage::LinkTarget
& target
)
3223 : area_(area
), target_(target
) {
3226 PDFiumEngine::MouseDownState::~MouseDownState() {
3229 void PDFiumEngine::MouseDownState::Set(const PDFiumPage::Area
& area
,
3230 const PDFiumPage::LinkTarget
& target
) {
3235 void PDFiumEngine::MouseDownState::Reset() {
3236 area_
= PDFiumPage::NONSELECTABLE_AREA
;
3237 target_
= PDFiumPage::LinkTarget();
3240 bool PDFiumEngine::MouseDownState::Matches(
3241 const PDFiumPage::Area
& area
,
3242 const PDFiumPage::LinkTarget
& target
) const {
3243 if (area_
== area
) {
3244 if (area
== PDFiumPage::WEBLINK_AREA
)
3245 return target_
.url
== target
.url
;
3246 if (area
== PDFiumPage::DOCLINK_AREA
)
3247 return target_
.page
== target
.page
;
3253 PDFiumEngine::FindTextIndex::FindTextIndex()
3254 : valid_(false), index_(0) {
3257 PDFiumEngine::FindTextIndex::~FindTextIndex() {
3260 void PDFiumEngine::FindTextIndex::Invalidate() {
3264 size_t PDFiumEngine::FindTextIndex::GetIndex() const {
3269 void PDFiumEngine::FindTextIndex::SetIndex(size_t index
) {
3274 size_t PDFiumEngine::FindTextIndex::IncrementIndex() {
3279 void PDFiumEngine::DeviceToPage(int page_index
,
3284 *page_x
= *page_y
= 0;
3285 int temp_x
= static_cast<int>((device_x
+ position_
.x())/ current_zoom_
-
3286 pages_
[page_index
]->rect().x());
3287 int temp_y
= static_cast<int>((device_y
+ position_
.y())/ current_zoom_
-
3288 pages_
[page_index
]->rect().y());
3290 pages_
[page_index
]->GetPage(), 0, 0,
3291 pages_
[page_index
]->rect().width(), pages_
[page_index
]->rect().height(),
3292 current_rotation_
, temp_x
, temp_y
, page_x
, page_y
);
3295 int PDFiumEngine::GetVisiblePageIndex(FPDF_PAGE page
) {
3296 for (size_t i
= 0; i
< visible_pages_
.size(); ++i
) {
3297 if (pages_
[visible_pages_
[i
]]->GetPage() == page
)
3298 return visible_pages_
[i
];
3303 void PDFiumEngine::SetCurrentPage(int index
) {
3304 if (index
== most_visible_page_
|| !form_
)
3306 if (most_visible_page_
!= -1 && called_do_document_action_
) {
3307 FPDF_PAGE old_page
= pages_
[most_visible_page_
]->GetPage();
3308 FORM_DoPageAAction(old_page
, form_
, FPDFPAGE_AACTION_CLOSE
);
3310 most_visible_page_
= index
;
3311 #if defined(OS_LINUX)
3312 g_last_instance_id
= client_
->GetPluginInstance()->pp_instance();
3314 if (most_visible_page_
!= -1 && called_do_document_action_
) {
3315 FPDF_PAGE new_page
= pages_
[most_visible_page_
]->GetPage();
3316 FORM_DoPageAAction(new_page
, form_
, FPDFPAGE_AACTION_OPEN
);
3320 void PDFiumEngine::TransformPDFPageForPrinting(
3322 const PP_PrintSettings_Dev
& print_settings
) {
3323 // Get the source page width and height in points.
3324 const double src_page_width
= FPDF_GetPageWidth(page
);
3325 const double src_page_height
= FPDF_GetPageHeight(page
);
3327 const int src_page_rotation
= FPDFPage_GetRotation(page
);
3328 const bool fit_to_page
= print_settings
.print_scaling_option
==
3329 PP_PRINTSCALINGOPTION_FIT_TO_PRINTABLE_AREA
;
3331 pp::Size
page_size(print_settings
.paper_size
);
3332 pp::Rect
content_rect(print_settings
.printable_area
);
3333 const bool rotated
= (src_page_rotation
% 2 == 1);
3334 SetPageSizeAndContentRect(rotated
,
3335 src_page_width
> src_page_height
,
3339 // Compute the screen page width and height in points.
3340 const int actual_page_width
=
3341 rotated
? page_size
.height() : page_size
.width();
3342 const int actual_page_height
=
3343 rotated
? page_size
.width() : page_size
.height();
3345 const double scale_factor
= CalculateScaleFactor(fit_to_page
, content_rect
,
3347 src_page_height
, rotated
);
3349 // Calculate positions for the clip box.
3350 ClipBox source_clip_box
;
3351 CalculateClipBoxBoundary(page
, scale_factor
, rotated
, &source_clip_box
);
3353 // Calculate the translation offset values.
3354 double offset_x
= 0;
3355 double offset_y
= 0;
3357 CalculateScaledClipBoxOffset(content_rect
, source_clip_box
, &offset_x
,
3360 CalculateNonScaledClipBoxOffset(content_rect
, src_page_rotation
,
3361 actual_page_width
, actual_page_height
,
3362 source_clip_box
, &offset_x
, &offset_y
);
3365 // Reset the media box and crop box. When the page has crop box and media box,
3366 // the plugin will display the crop box contents and not the entire media box.
3367 // If the pages have different crop box values, the plugin will display a
3368 // document of multiple page sizes. To give better user experience, we
3369 // decided to have same crop box and media box values. Hence, the user will
3370 // see a list of uniform pages.
3371 FPDFPage_SetMediaBox(page
, 0, 0, page_size
.width(), page_size
.height());
3372 FPDFPage_SetCropBox(page
, 0, 0, page_size
.width(), page_size
.height());
3374 // Transformation is not required, return. Do this check only after updating
3375 // the media box and crop box. For more detailed information, please refer to
3376 // the comment block right before FPDF_SetMediaBox and FPDF_GetMediaBox calls.
3377 if (scale_factor
== 1.0 && offset_x
== 0 && offset_y
== 0)
3381 // All the positions have been calculated, now manipulate the PDF.
3382 FS_MATRIX matrix
= {static_cast<float>(scale_factor
),
3385 static_cast<float>(scale_factor
),
3386 static_cast<float>(offset_x
),
3387 static_cast<float>(offset_y
)};
3388 FS_RECTF cliprect
= {static_cast<float>(source_clip_box
.left
+offset_x
),
3389 static_cast<float>(source_clip_box
.top
+offset_y
),
3390 static_cast<float>(source_clip_box
.right
+offset_x
),
3391 static_cast<float>(source_clip_box
.bottom
+offset_y
)};
3392 FPDFPage_TransFormWithClip(page
, &matrix
, &cliprect
);
3393 FPDFPage_TransformAnnots(page
, scale_factor
, 0, 0, scale_factor
,
3394 offset_x
, offset_y
);
3397 void PDFiumEngine::DrawPageShadow(const pp::Rect
& page_rc
,
3398 const pp::Rect
& shadow_rc
,
3399 const pp::Rect
& clip_rc
,
3400 pp::ImageData
* image_data
) {
3401 pp::Rect
page_rect(page_rc
);
3402 page_rect
.Offset(page_offset_
);
3404 pp::Rect
shadow_rect(shadow_rc
);
3405 shadow_rect
.Offset(page_offset_
);
3407 pp::Rect
clip_rect(clip_rc
);
3408 clip_rect
.Offset(page_offset_
);
3410 // Page drop shadow parameters.
3411 const double factor
= 0.5;
3412 uint32 depth
= std::max(
3413 std::max(page_rect
.x() - shadow_rect
.x(),
3414 page_rect
.y() - shadow_rect
.y()),
3415 std::max(shadow_rect
.right() - page_rect
.right(),
3416 shadow_rect
.bottom() - page_rect
.bottom()));
3417 depth
= static_cast<uint32
>(depth
* 1.5) + 1;
3419 // We need to check depth only to verify our copy of shadow matrix is correct.
3420 if (!page_shadow_
.get() || page_shadow_
->depth() != depth
)
3421 page_shadow_
.reset(new ShadowMatrix(depth
, factor
,
3422 client_
->GetBackgroundColor()));
3424 DCHECK(!image_data
->is_null());
3425 DrawShadow(image_data
, shadow_rect
, page_rect
, clip_rect
, *page_shadow_
);
3428 void PDFiumEngine::GetRegion(const pp::Point
& location
,
3429 pp::ImageData
* image_data
,
3431 int* stride
) const {
3432 if (image_data
->is_null()) {
3433 DCHECK(plugin_size_
.IsEmpty());
3438 char* buffer
= static_cast<char*>(image_data
->data());
3439 *stride
= image_data
->stride();
3441 pp::Point offset_location
= location
+ page_offset_
;
3442 // TODO: update this when we support BIDI and scrollbars can be on the left.
3444 !pp::Rect(page_offset_
, plugin_size_
).Contains(offset_location
)) {
3449 buffer
+= location
.y() * (*stride
);
3450 buffer
+= (location
.x() + page_offset_
.x()) * 4;
3454 void PDFiumEngine::OnSelectionChanged() {
3455 pp::PDF::SetSelectedText(GetPluginInstance(), GetSelectedText().c_str());
3458 void PDFiumEngine::RotateInternal() {
3459 // Store the current find index so that we can resume finding at that
3460 // particular index after we have recomputed the find results.
3461 std::string current_find_text
= current_find_text_
;
3462 if (current_find_index_
.valid())
3463 resume_find_index_
.SetIndex(current_find_index_
.GetIndex());
3465 resume_find_index_
.Invalidate();
3467 InvalidateAllPages();
3469 if (!current_find_text
.empty()) {
3471 client_
->NotifyNumberOfFindResultsChanged(0, false);
3472 StartFind(current_find_text
.c_str(), false);
3476 void PDFiumEngine::SetSelecting(bool selecting
) {
3477 bool was_selecting
= selecting_
;
3478 selecting_
= selecting
;
3479 if (selecting_
!= was_selecting
)
3480 client_
->IsSelectingChanged(selecting
);
3483 void PDFiumEngine::Form_Invalidate(FPDF_FORMFILLINFO
* param
,
3489 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3490 int page_index
= engine
->GetVisiblePageIndex(page
);
3491 if (page_index
== -1) {
3492 // This can sometime happen when the page is closed because it went off
3493 // screen, and PDFium invalidates the control as it's being deleted.
3497 pp::Rect rect
= engine
->pages_
[page_index
]->PageToScreen(
3498 engine
->GetVisibleRect().point(), engine
->current_zoom_
, left
, top
, right
,
3499 bottom
, engine
->current_rotation_
);
3500 engine
->client_
->Invalidate(rect
);
3503 void PDFiumEngine::Form_OutputSelectedRect(FPDF_FORMFILLINFO
* param
,
3509 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3510 int page_index
= engine
->GetVisiblePageIndex(page
);
3511 if (page_index
== -1) {
3515 pp::Rect rect
= engine
->pages_
[page_index
]->PageToScreen(
3516 engine
->GetVisibleRect().point(), engine
->current_zoom_
, left
, top
, right
,
3517 bottom
, engine
->current_rotation_
);
3518 engine
->form_highlights_
.push_back(rect
);
3521 void PDFiumEngine::Form_SetCursor(FPDF_FORMFILLINFO
* param
, int cursor_type
) {
3522 // We don't need this since it's not enough to change the cursor in all
3523 // scenarios. Instead, we check which form field we're under in OnMouseMove.
3526 int PDFiumEngine::Form_SetTimer(FPDF_FORMFILLINFO
* param
,
3528 TimerCallback timer_func
) {
3529 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3530 engine
->timers_
[++engine
->next_timer_id_
] =
3531 std::pair
<int, TimerCallback
>(elapse
, timer_func
);
3532 engine
->client_
->ScheduleCallback(engine
->next_timer_id_
, elapse
);
3533 return engine
->next_timer_id_
;
3536 void PDFiumEngine::Form_KillTimer(FPDF_FORMFILLINFO
* param
, int timer_id
) {
3537 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3538 engine
->timers_
.erase(timer_id
);
3541 FPDF_SYSTEMTIME
PDFiumEngine::Form_GetLocalTime(FPDF_FORMFILLINFO
* param
) {
3542 base::Time time
= base::Time::Now();
3543 base::Time::Exploded exploded
;
3544 time
.LocalExplode(&exploded
);
3547 rv
.wYear
= exploded
.year
;
3548 rv
.wMonth
= exploded
.month
;
3549 rv
.wDayOfWeek
= exploded
.day_of_week
;
3550 rv
.wDay
= exploded
.day_of_month
;
3551 rv
.wHour
= exploded
.hour
;
3552 rv
.wMinute
= exploded
.minute
;
3553 rv
.wSecond
= exploded
.second
;
3554 rv
.wMilliseconds
= exploded
.millisecond
;
3558 void PDFiumEngine::Form_OnChange(FPDF_FORMFILLINFO
* param
) {
3559 // Don't care about.
3562 FPDF_PAGE
PDFiumEngine::Form_GetPage(FPDF_FORMFILLINFO
* param
,
3563 FPDF_DOCUMENT document
,
3565 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3566 if (page_index
< 0 || page_index
>= static_cast<int>(engine
->pages_
.size()))
3568 return engine
->pages_
[page_index
]->GetPage();
3571 FPDF_PAGE
PDFiumEngine::Form_GetCurrentPage(FPDF_FORMFILLINFO
* param
,
3572 FPDF_DOCUMENT document
) {
3573 // TODO(jam): find out what this is used for.
3574 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3575 int index
= engine
->last_page_mouse_down_
;
3577 index
= engine
->GetMostVisiblePage();
3584 return engine
->pages_
[index
]->GetPage();
3587 int PDFiumEngine::Form_GetRotation(FPDF_FORMFILLINFO
* param
, FPDF_PAGE page
) {
3591 void PDFiumEngine::Form_ExecuteNamedAction(FPDF_FORMFILLINFO
* param
,
3592 FPDF_BYTESTRING named_action
) {
3593 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3594 std::string
action(named_action
);
3595 if (action
== "Print") {
3596 engine
->client_
->Print();
3600 int index
= engine
->last_page_mouse_down_
;
3601 /* Don't try to calculate the most visible page if we don't have a left click
3602 before this event (this code originally copied Form_GetCurrentPage which of
3603 course needs to do that and which doesn't have recursion). This can end up
3604 causing infinite recursion. See http://crbug.com/240413 for more
3605 information. Either way, it's not necessary for the spec'd list of named
3608 index = engine->GetMostVisiblePage();
3613 // This is the only list of named actions per the spec (see 12.6.4.11). Adobe
3614 // Reader supports more, like FitWidth, but since they're not part of the spec
3615 // and we haven't got bugs about them, no need to now.
3616 if (action
== "NextPage") {
3617 engine
->client_
->ScrollToPage(index
+ 1);
3618 } else if (action
== "PrevPage") {
3619 engine
->client_
->ScrollToPage(index
- 1);
3620 } else if (action
== "FirstPage") {
3621 engine
->client_
->ScrollToPage(0);
3622 } else if (action
== "LastPage") {
3623 engine
->client_
->ScrollToPage(engine
->pages_
.size() - 1);
3627 void PDFiumEngine::Form_SetTextFieldFocus(FPDF_FORMFILLINFO
* param
,
3628 FPDF_WIDESTRING value
,
3629 FPDF_DWORD valueLen
,
3630 FPDF_BOOL is_focus
) {
3631 // Do nothing for now.
3632 // TODO(gene): use this signal to trigger OSK.
3635 void PDFiumEngine::Form_DoURIAction(FPDF_FORMFILLINFO
* param
,
3636 FPDF_BYTESTRING uri
) {
3637 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3638 engine
->client_
->NavigateTo(std::string(uri
), false);
3641 void PDFiumEngine::Form_DoGoToAction(FPDF_FORMFILLINFO
* param
,
3644 float* position_array
,
3645 int size_of_array
) {
3646 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3647 engine
->client_
->ScrollToPage(page_index
);
3650 int PDFiumEngine::Form_Alert(IPDF_JSPLATFORM
* param
,
3651 FPDF_WIDESTRING message
,
3652 FPDF_WIDESTRING title
,
3655 // See fpdfformfill.h for these values.
3658 ALERT_TYPE_OK_CANCEL
,
3660 ALERT_TYPE_YES_NO_CANCEL
3664 ALERT_RESULT_OK
= 1,
3665 ALERT_RESULT_CANCEL
,
3670 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3671 std::string message_str
=
3672 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(message
));
3673 if (type
== ALERT_TYPE_OK
) {
3674 engine
->client_
->Alert(message_str
);
3675 return ALERT_RESULT_OK
;
3678 bool rv
= engine
->client_
->Confirm(message_str
);
3679 if (type
== ALERT_TYPE_OK_CANCEL
)
3680 return rv
? ALERT_RESULT_OK
: ALERT_RESULT_CANCEL
;
3681 return rv
? ALERT_RESULT_YES
: ALERT_RESULT_NO
;
3684 void PDFiumEngine::Form_Beep(IPDF_JSPLATFORM
* param
, int type
) {
3685 // Beeps are annoying, and not possible using javascript, so ignore for now.
3688 int PDFiumEngine::Form_Response(IPDF_JSPLATFORM
* param
,
3689 FPDF_WIDESTRING question
,
3690 FPDF_WIDESTRING title
,
3691 FPDF_WIDESTRING default_response
,
3692 FPDF_WIDESTRING label
,
3696 std::string question_str
= base::UTF16ToUTF8(
3697 reinterpret_cast<const base::char16
*>(question
));
3698 std::string default_str
= base::UTF16ToUTF8(
3699 reinterpret_cast<const base::char16
*>(default_response
));
3701 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3702 std::string rv
= engine
->client_
->Prompt(question_str
, default_str
);
3703 base::string16 rv_16
= base::UTF8ToUTF16(rv
);
3704 int rv_bytes
= rv_16
.size() * sizeof(base::char16
);
3706 int bytes_to_copy
= rv_bytes
< length
? rv_bytes
: length
;
3707 memcpy(response
, rv_16
.c_str(), bytes_to_copy
);
3712 int PDFiumEngine::Form_GetFilePath(IPDF_JSPLATFORM
* param
,
3715 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3716 std::string rv
= engine
->client_
->GetURL();
3717 if (file_path
&& rv
.size() <= static_cast<size_t>(length
))
3718 memcpy(file_path
, rv
.c_str(), rv
.size());
3722 void PDFiumEngine::Form_Mail(IPDF_JSPLATFORM
* param
,
3727 FPDF_WIDESTRING subject
,
3729 FPDF_WIDESTRING bcc
,
3730 FPDF_WIDESTRING message
) {
3731 // Note: |mail_data| and |length| are ignored. We don't handle attachments;
3732 // there is no way with mailto.
3733 std::string to_str
=
3734 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(to
));
3735 std::string cc_str
=
3736 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(cc
));
3737 std::string bcc_str
=
3738 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(bcc
));
3739 std::string subject_str
=
3740 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(subject
));
3741 std::string message_str
=
3742 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(message
));
3744 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3745 engine
->client_
->Email(to_str
, cc_str
, bcc_str
, subject_str
, message_str
);
3748 void PDFiumEngine::Form_Print(IPDF_JSPLATFORM
* param
,
3753 FPDF_BOOL shrink_to_fit
,
3754 FPDF_BOOL print_as_image
,
3756 FPDF_BOOL annotations
) {
3757 // No way to pass the extra information to the print dialog using JavaScript.
3758 // Just opening it is fine for now.
3759 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3760 engine
->client_
->Print();
3763 void PDFiumEngine::Form_SubmitForm(IPDF_JSPLATFORM
* param
,
3766 FPDF_WIDESTRING url
) {
3767 std::string url_str
=
3768 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(url
));
3769 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3770 engine
->client_
->SubmitForm(url_str
, form_data
, length
);
3773 void PDFiumEngine::Form_GotoPage(IPDF_JSPLATFORM
* param
,
3775 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3776 engine
->client_
->ScrollToPage(page_number
);
3779 int PDFiumEngine::Form_Browse(IPDF_JSPLATFORM
* param
,
3782 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3783 std::string path
= engine
->client_
->ShowFileSelectionDialog();
3784 if (path
.size() + 1 <= static_cast<size_t>(length
))
3785 memcpy(file_path
, &path
[0], path
.size() + 1);
3786 return path
.size() + 1;
3789 FPDF_BOOL
PDFiumEngine::Pause_NeedToPauseNow(IFSDK_PAUSE
* param
) {
3790 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3791 return (base::Time::Now() - engine
->last_progressive_start_time_
).
3792 InMilliseconds() > engine
->progressive_paint_timeout_
;
3795 ScopedUnsupportedFeature::ScopedUnsupportedFeature(PDFiumEngine
* engine
)
3796 : engine_(engine
), old_engine_(g_engine_for_unsupported
) {
3797 g_engine_for_unsupported
= engine_
;
3800 ScopedUnsupportedFeature::~ScopedUnsupportedFeature() {
3801 g_engine_for_unsupported
= old_engine_
;
3804 PDFEngineExports
* PDFEngineExports::Create() {
3805 return new PDFiumEngineExports
;
3810 int CalculatePosition(FPDF_PAGE page
,
3811 const PDFiumEngineExports::RenderingSettings
& settings
,
3813 int page_width
= static_cast<int>(ConvertUnitDouble(FPDF_GetPageWidth(page
),
3816 int page_height
= static_cast<int>(ConvertUnitDouble(FPDF_GetPageHeight(page
),
3820 // Start by assuming that we will draw exactly to the bounds rect
3822 *dest
= settings
.bounds
;
3824 int rotate
= 0; // normal orientation.
3826 // Auto-rotate landscape pages to print correctly.
3827 if (settings
.autorotate
&&
3828 (dest
->width() > dest
->height()) != (page_width
> page_height
)) {
3829 rotate
= 3; // 90 degrees counter-clockwise.
3830 std::swap(page_width
, page_height
);
3833 // See if we need to scale the output
3834 bool scale_to_bounds
= false;
3835 if (settings
.fit_to_bounds
&&
3836 ((page_width
> dest
->width()) || (page_height
> dest
->height()))) {
3837 scale_to_bounds
= true;
3838 } else if (settings
.stretch_to_bounds
&&
3839 ((page_width
< dest
->width()) || (page_height
< dest
->height()))) {
3840 scale_to_bounds
= true;
3843 if (scale_to_bounds
) {
3844 // If we need to maintain aspect ratio, calculate the actual width and
3846 if (settings
.keep_aspect_ratio
) {
3847 double scale_factor_x
= page_width
;
3848 scale_factor_x
/= dest
->width();
3849 double scale_factor_y
= page_height
;
3850 scale_factor_y
/= dest
->height();
3851 if (scale_factor_x
> scale_factor_y
) {
3852 dest
->set_height(page_height
/ scale_factor_x
);
3854 dest
->set_width(page_width
/ scale_factor_y
);
3858 // We are not scaling to bounds. Draw in the actual page size. If the
3859 // actual page size is larger than the bounds, the output will be
3861 dest
->set_width(page_width
);
3862 dest
->set_height(page_height
);
3865 if (settings
.center_in_bounds
) {
3866 pp::Point
offset((settings
.bounds
.width() - dest
->width()) / 2,
3867 (settings
.bounds
.height() - dest
->height()) / 2);
3868 dest
->Offset(offset
);
3876 bool PDFiumEngineExports::RenderPDFPageToDC(const void* pdf_buffer
,
3879 const RenderingSettings
& settings
,
3881 FPDF_DOCUMENT doc
= FPDF_LoadMemDocument(pdf_buffer
, buffer_size
, NULL
);
3884 FPDF_PAGE page
= FPDF_LoadPage(doc
, page_number
);
3886 FPDF_CloseDocument(doc
);
3889 RenderingSettings new_settings
= settings
;
3890 // calculate the page size
3891 if (new_settings
.dpi_x
== -1)
3892 new_settings
.dpi_x
= GetDeviceCaps(dc
, LOGPIXELSX
);
3893 if (new_settings
.dpi_y
== -1)
3894 new_settings
.dpi_y
= GetDeviceCaps(dc
, LOGPIXELSY
);
3897 int rotate
= CalculatePosition(page
, new_settings
, &dest
);
3899 int save_state
= SaveDC(dc
);
3900 // The caller wanted all drawing to happen within the bounds specified.
3901 // Based on scale calculations, our destination rect might be larger
3902 // than the bounds. Set the clip rect to the bounds.
3903 IntersectClipRect(dc
, settings
.bounds
.x(), settings
.bounds
.y(),
3904 settings
.bounds
.x() + settings
.bounds
.width(),
3905 settings
.bounds
.y() + settings
.bounds
.height());
3907 // A temporary hack. PDFs generated by Cairo (used by Chrome OS to generate
3908 // a PDF output from a webpage) result in very large metafiles and the
3909 // rendering using FPDF_RenderPage is incorrect. In this case, render as a
3910 // bitmap. Note that this code does not kick in for PDFs printed from Chrome
3911 // because in that case we create a temp PDF first before printing and this
3912 // temp PDF does not have a creator string that starts with "cairo".
3913 base::string16 creator
;
3914 size_t buffer_bytes
= FPDF_GetMetaText(doc
, "Creator", NULL
, 0);
3915 if (buffer_bytes
> 1) {
3916 FPDF_GetMetaText(doc
, "Creator",
3917 base::WriteInto(&creator
, buffer_bytes
+ 1), buffer_bytes
);
3919 bool use_bitmap
= false;
3920 if (base::StartsWith(creator
, L
"cairo", base::CompareCase::INSENSITIVE_ASCII
))
3923 // Another temporary hack. Some PDFs seems to render very slowly if
3924 // FPDF_RenderPage is directly used on a printer DC. I suspect it is
3925 // because of the code to talk Postscript directly to the printer if
3926 // the printer supports this. Need to discuss this with PDFium. For now,
3927 // render to a bitmap and then blit the bitmap to the DC if we have been
3928 // supplied a printer DC.
3929 int device_type
= GetDeviceCaps(dc
, TECHNOLOGY
);
3931 (device_type
== DT_RASPRINTER
) || (device_type
== DT_PLOTTER
)) {
3932 FPDF_BITMAP bitmap
= FPDFBitmap_Create(dest
.width(), dest
.height(),
3935 FPDFBitmap_FillRect(bitmap
, 0, 0, dest
.width(), dest
.height(), 0xFFFFFFFF);
3936 FPDF_RenderPageBitmap(
3937 bitmap
, page
, 0, 0, dest
.width(), dest
.height(), rotate
,
3938 FPDF_ANNOT
| FPDF_PRINTING
| FPDF_NO_CATCH
);
3939 int stride
= FPDFBitmap_GetStride(bitmap
);
3941 memset(&bmi
, 0, sizeof(bmi
));
3942 bmi
.bmiHeader
.biSize
= sizeof(BITMAPINFOHEADER
);
3943 bmi
.bmiHeader
.biWidth
= dest
.width();
3944 bmi
.bmiHeader
.biHeight
= -dest
.height(); // top-down image
3945 bmi
.bmiHeader
.biPlanes
= 1;
3946 bmi
.bmiHeader
.biBitCount
= 32;
3947 bmi
.bmiHeader
.biCompression
= BI_RGB
;
3948 bmi
.bmiHeader
.biSizeImage
= stride
* dest
.height();
3949 StretchDIBits(dc
, dest
.x(), dest
.y(), dest
.width(), dest
.height(),
3950 0, 0, dest
.width(), dest
.height(),
3951 FPDFBitmap_GetBuffer(bitmap
), &bmi
, DIB_RGB_COLORS
, SRCCOPY
);
3952 FPDFBitmap_Destroy(bitmap
);
3954 FPDF_RenderPage(dc
, page
, dest
.x(), dest
.y(), dest
.width(), dest
.height(),
3955 rotate
, FPDF_ANNOT
| FPDF_PRINTING
| FPDF_NO_CATCH
);
3957 RestoreDC(dc
, save_state
);
3958 FPDF_ClosePage(page
);
3959 FPDF_CloseDocument(doc
);
3964 bool PDFiumEngineExports::RenderPDFPageToBitmap(
3965 const void* pdf_buffer
,
3966 int pdf_buffer_size
,
3968 const RenderingSettings
& settings
,
3969 void* bitmap_buffer
) {
3970 FPDF_DOCUMENT doc
= FPDF_LoadMemDocument(pdf_buffer
, pdf_buffer_size
, NULL
);
3973 FPDF_PAGE page
= FPDF_LoadPage(doc
, page_number
);
3975 FPDF_CloseDocument(doc
);
3980 int rotate
= CalculatePosition(page
, settings
, &dest
);
3982 FPDF_BITMAP bitmap
=
3983 FPDFBitmap_CreateEx(settings
.bounds
.width(), settings
.bounds
.height(),
3984 FPDFBitmap_BGRA
, bitmap_buffer
,
3985 settings
.bounds
.width() * 4);
3987 FPDFBitmap_FillRect(bitmap
, 0, 0, settings
.bounds
.width(),
3988 settings
.bounds
.height(), 0xFFFFFFFF);
3989 // Shift top-left corner of bounds to (0, 0) if it's not there.
3990 dest
.set_point(dest
.point() - settings
.bounds
.point());
3991 FPDF_RenderPageBitmap(
3992 bitmap
, page
, dest
.x(), dest
.y(), dest
.width(), dest
.height(), rotate
,
3993 FPDF_ANNOT
| FPDF_PRINTING
| FPDF_NO_CATCH
);
3994 FPDFBitmap_Destroy(bitmap
);
3995 FPDF_ClosePage(page
);
3996 FPDF_CloseDocument(doc
);
4000 bool PDFiumEngineExports::GetPDFDocInfo(const void* pdf_buffer
,
4003 double* max_page_width
) {
4004 FPDF_DOCUMENT doc
= FPDF_LoadMemDocument(pdf_buffer
, buffer_size
, NULL
);
4007 int page_count_local
= FPDF_GetPageCount(doc
);
4009 *page_count
= page_count_local
;
4011 if (max_page_width
) {
4012 *max_page_width
= 0;
4013 for (int page_number
= 0; page_number
< page_count_local
; page_number
++) {
4014 double page_width
= 0;
4015 double page_height
= 0;
4016 FPDF_GetPageSizeByIndex(doc
, page_number
, &page_width
, &page_height
);
4017 if (page_width
> *max_page_width
) {
4018 *max_page_width
= page_width
;
4022 FPDF_CloseDocument(doc
);
4026 bool PDFiumEngineExports::GetPDFPageSizeByIndex(
4027 const void* pdf_buffer
,
4028 int pdf_buffer_size
,
4032 FPDF_DOCUMENT doc
= FPDF_LoadMemDocument(pdf_buffer
, pdf_buffer_size
, NULL
);
4035 bool success
= FPDF_GetPageSizeByIndex(doc
, page_number
, width
, height
) != 0;
4036 FPDF_CloseDocument(doc
);
4040 } // namespace chrome_pdf