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 (IsWhitespace(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 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 fpdf_availability_(NULL
),
597 last_page_mouse_down_(-1),
598 first_visible_page_(-1),
599 most_visible_page_(-1),
600 called_do_document_action_(false),
601 render_grayscale_(false),
602 progressive_paint_timeout_(0),
603 getting_password_(false) {
604 find_factory_
.Initialize(this);
605 password_factory_
.Initialize(this);
607 file_access_
.m_FileLen
= 0;
608 file_access_
.m_GetBlock
= &GetBlock
;
609 file_access_
.m_Param
= &doc_loader_
;
611 file_availability_
.version
= 1;
612 file_availability_
.IsDataAvail
= &IsDataAvail
;
613 file_availability_
.loader
= &doc_loader_
;
615 download_hints_
.version
= 1;
616 download_hints_
.AddSegment
= &AddSegment
;
617 download_hints_
.loader
= &doc_loader_
;
619 // Initialize FPDF_FORMFILLINFO member variables. Deriving from this struct
620 // allows the static callbacks to be able to cast the FPDF_FORMFILLINFO in
621 // callbacks to ourself instead of maintaining a map of them to
623 FPDF_FORMFILLINFO::version
= 1;
624 FPDF_FORMFILLINFO::m_pJsPlatform
= this;
625 FPDF_FORMFILLINFO::Release
= NULL
;
626 FPDF_FORMFILLINFO::FFI_Invalidate
= Form_Invalidate
;
627 FPDF_FORMFILLINFO::FFI_OutputSelectedRect
= Form_OutputSelectedRect
;
628 FPDF_FORMFILLINFO::FFI_SetCursor
= Form_SetCursor
;
629 FPDF_FORMFILLINFO::FFI_SetTimer
= Form_SetTimer
;
630 FPDF_FORMFILLINFO::FFI_KillTimer
= Form_KillTimer
;
631 FPDF_FORMFILLINFO::FFI_GetLocalTime
= Form_GetLocalTime
;
632 FPDF_FORMFILLINFO::FFI_OnChange
= Form_OnChange
;
633 FPDF_FORMFILLINFO::FFI_GetPage
= Form_GetPage
;
634 FPDF_FORMFILLINFO::FFI_GetCurrentPage
= Form_GetCurrentPage
;
635 FPDF_FORMFILLINFO::FFI_GetRotation
= Form_GetRotation
;
636 FPDF_FORMFILLINFO::FFI_ExecuteNamedAction
= Form_ExecuteNamedAction
;
637 FPDF_FORMFILLINFO::FFI_SetTextFieldFocus
= Form_SetTextFieldFocus
;
638 FPDF_FORMFILLINFO::FFI_DoURIAction
= Form_DoURIAction
;
639 FPDF_FORMFILLINFO::FFI_DoGoToAction
= Form_DoGoToAction
;
641 FPDF_FORMFILLINFO::version
= 2;
642 FPDF_FORMFILLINFO::FFI_EmailTo
= Form_EmailTo
;
643 FPDF_FORMFILLINFO::FFI_DisplayCaret
= Form_DisplayCaret
;
644 FPDF_FORMFILLINFO::FFI_SetCurrentPage
= Form_SetCurrentPage
;
645 FPDF_FORMFILLINFO::FFI_GetCurrentPageIndex
= Form_GetCurrentPageIndex
;
646 FPDF_FORMFILLINFO::FFI_GetPageViewRect
= Form_GetPageViewRect
;
647 FPDF_FORMFILLINFO::FFI_GetPlatform
= Form_GetPlatform
;
648 FPDF_FORMFILLINFO::FFI_PopupMenu
= Form_PopupMenu
;
649 FPDF_FORMFILLINFO::FFI_PostRequestURL
= Form_PostRequestURL
;
650 FPDF_FORMFILLINFO::FFI_PutRequestURL
= Form_PutRequestURL
;
651 FPDF_FORMFILLINFO::FFI_UploadTo
= Form_UploadTo
;
652 FPDF_FORMFILLINFO::FFI_DownloadFromURL
= Form_DownloadFromURL
;
653 FPDF_FORMFILLINFO::FFI_OpenFile
= Form_OpenFile
;
654 FPDF_FORMFILLINFO::FFI_GotoURL
= Form_GotoURL
;
655 FPDF_FORMFILLINFO::FFI_GetLanguage
= Form_GetLanguage
;
656 #endif // PDF_USE_XFA
657 IPDF_JSPLATFORM::version
= 1;
658 IPDF_JSPLATFORM::app_alert
= Form_Alert
;
659 IPDF_JSPLATFORM::app_beep
= Form_Beep
;
660 IPDF_JSPLATFORM::app_response
= Form_Response
;
661 IPDF_JSPLATFORM::Doc_getFilePath
= Form_GetFilePath
;
662 IPDF_JSPLATFORM::Doc_mail
= Form_Mail
;
663 IPDF_JSPLATFORM::Doc_print
= Form_Print
;
664 IPDF_JSPLATFORM::Doc_submitForm
= Form_SubmitForm
;
665 IPDF_JSPLATFORM::Doc_gotoPage
= Form_GotoPage
;
666 IPDF_JSPLATFORM::Field_browse
= Form_Browse
;
668 IFSDK_PAUSE::version
= 1;
669 IFSDK_PAUSE::user
= NULL
;
670 IFSDK_PAUSE::NeedToPauseNow
= Pause_NeedToPauseNow
;
673 PDFiumEngine::~PDFiumEngine() {
674 for (size_t i
= 0; i
< pages_
.size(); ++i
)
678 FORM_DoDocumentAAction(form_
, FPDFDOC_AACTION_WC
);
679 FPDF_CloseDocument(doc_
);
680 FPDFDOC_ExitFormFillEnvironment(form_
);
682 FPDFAvail_Destroy(fpdf_availability_
);
684 STLDeleteElements(&pages_
);
689 // This is just for testing, needs to be removed later
691 #define XFA_TESTFILE(filename) "E:/"#filename
693 #define XFA_TESTFILE(filename) "/home/"#filename
697 FPDF_FILEHANDLER file_handler
;
701 void Sample_Release(FPDF_LPVOID client_data
) {
704 FPDF_FILE
* file_wrapper
= (FPDF_FILE
*)client_data
;
705 fclose(file_wrapper
->file
);
709 FPDF_DWORD
Sample_GetSize(FPDF_LPVOID client_data
) {
712 FPDF_FILE
* file_wrapper
= (FPDF_FILE
*)client_data
;
713 long cur_pos
= ftell(file_wrapper
->file
);
716 if (fseek(file_wrapper
->file
, 0, SEEK_END
))
718 long size
= ftell(file_wrapper
->file
);
719 fseek(file_wrapper
->file
, cur_pos
, SEEK_SET
);
720 return (FPDF_DWORD
)size
;
723 FPDF_RESULT
Sample_ReadBlock(FPDF_LPVOID client_data
,
729 FPDF_FILE
* file_wrapper
= (FPDF_FILE
*)client_data
;
730 if (fseek(file_wrapper
->file
, (long)offset
, SEEK_SET
))
732 size_t read_size
= fread(buffer
, 1, size
, file_wrapper
->file
);
733 return read_size
== size
? 0 : -1;
736 FPDF_RESULT
Sample_WriteBlock(FPDF_LPVOID client_data
,
742 FPDF_FILE
* file_wrapper
= (FPDF_FILE
*)client_data
;
743 if (fseek(file_wrapper
->file
, (long)offset
, SEEK_SET
))
746 size_t write_size
= fwrite(buffer
, 1, size
, file_wrapper
->file
);
747 return write_size
== size
? 0 : -1;
750 FPDF_RESULT
Sample_Flush(FPDF_LPVOID client_data
) {
754 fflush(((FPDF_FILE
*)client_data
)->file
);
758 FPDF_RESULT
Sample_Truncate(FPDF_LPVOID client_data
, FPDF_DWORD size
) {
762 void PDFiumEngine::Form_EmailTo(FPDF_FORMFILLINFO
* param
,
763 FPDF_FILEHANDLER
* file_handler
,
765 FPDF_WIDESTRING subject
,
768 FPDF_WIDESTRING message
) {
770 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(to
));
771 std::string subject_str
=
772 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(subject
));
774 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(cc
));
775 std::string bcc_str
=
776 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(bcc
));
777 std::string message_str
=
778 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(message
));
780 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
781 engine
->client_
->Email(to_str
, cc_str
, bcc_str
, subject_str
, message_str
);
784 void PDFiumEngine::Form_DisplayCaret(FPDF_FORMFILLINFO
* param
,
791 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
792 engine
->client_
->UpdateCursor(PP_CURSORTYPE_IBEAM
);
793 std::vector
<pp::Rect
> tickmarks
;
794 pp::Rect
rect(left
, top
, right
, bottom
);
795 tickmarks
.push_back(rect
);
796 engine
->client_
->UpdateTickMarks(tickmarks
);
799 void PDFiumEngine::Form_SetCurrentPage(FPDF_FORMFILLINFO
* param
,
800 FPDF_DOCUMENT document
,
802 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
803 pp::Rect page_view_rect
= engine
->GetPageContentsRect(page
);
804 engine
->ScrolledToYPosition(page_view_rect
.height());
805 pp::Point
pos(1, page_view_rect
.height());
806 engine
->SetScrollPosition(pos
);
809 int PDFiumEngine::Form_GetCurrentPageIndex(FPDF_FORMFILLINFO
* param
,
810 FPDF_DOCUMENT document
) {
811 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
812 return engine
->GetMostVisiblePage();
815 void PDFiumEngine::Form_GetPageViewRect(FPDF_FORMFILLINFO
* param
,
821 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
822 int page_index
= engine
->GetMostVisiblePage();
823 pp::Rect page_view_rect
= engine
->GetPageContentsRect(page_index
);
825 *left
= page_view_rect
.x();
826 *right
= page_view_rect
.right();
827 *top
= page_view_rect
.y();
828 *bottom
= page_view_rect
.bottom();
831 int PDFiumEngine::Form_GetPlatform(FPDF_FORMFILLINFO
* param
,
834 int platform_flag
= -1;
838 #elif defined(__linux__)
844 std::string javascript
= "alert(\"Platform:"
845 + base::DoubleToString(platform_flag
)
848 return platform_flag
;
851 FPDF_BOOL
PDFiumEngine::Form_PopupMenu(FPDF_FORMFILLINFO
* param
,
860 FPDF_BOOL
PDFiumEngine::Form_PostRequestURL(FPDF_FORMFILLINFO
* param
,
862 FPDF_WIDESTRING data
,
863 FPDF_WIDESTRING content_type
,
864 FPDF_WIDESTRING encode
,
865 FPDF_WIDESTRING header
,
866 FPDF_BSTR
* response
) {
867 std::string url_str
=
868 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(url
));
869 std::string data_str
=
870 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(data
));
871 std::string content_type_str
=
872 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(content_type
));
873 std::string encode_str
=
874 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(encode
));
875 std::string header_str
=
876 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(header
));
878 std::string javascript
= "alert(\"Post:"
879 + url_str
+ "," + data_str
+ "," + content_type_str
+ ","
880 + encode_str
+ "," + header_str
885 FPDF_BOOL
PDFiumEngine::Form_PutRequestURL(FPDF_FORMFILLINFO
* param
,
887 FPDF_WIDESTRING data
,
888 FPDF_WIDESTRING encode
) {
889 std::string url_str
=
890 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(url
));
891 std::string data_str
=
892 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(data
));
893 std::string encode_str
=
894 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(encode
));
896 std::string javascript
= "alert(\"Put:"
897 + url_str
+ "," + data_str
+ "," + encode_str
903 void PDFiumEngine::Form_UploadTo(FPDF_FORMFILLINFO
* param
,
904 FPDF_FILEHANDLER
* file_handle
,
906 FPDF_WIDESTRING to
) {
908 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(to
));
909 // TODO: needs the full implementation of form uploading
912 FPDF_LPFILEHANDLER
PDFiumEngine::Form_DownloadFromURL(FPDF_FORMFILLINFO
* param
,
913 FPDF_WIDESTRING url
) {
914 std::string url_str
=
915 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(url
));
917 // Now should get data from url.
918 // For testing purpose, use data read from file
919 // TODO: needs the full implementation here
920 FILE* file
= fopen(XFA_TESTFILE("downloadtest.tem"), "w");
922 FPDF_FILE
* file_wrapper
= new FPDF_FILE
;
923 file_wrapper
->file
= file
;
924 file_wrapper
->file_handler
.clientData
= file_wrapper
;
925 file_wrapper
->file_handler
.Flush
= Sample_Flush
;
926 file_wrapper
->file_handler
.GetSize
= Sample_GetSize
;
927 file_wrapper
->file_handler
.ReadBlock
= Sample_ReadBlock
;
928 file_wrapper
->file_handler
.Release
= Sample_Release
;
929 file_wrapper
->file_handler
.Truncate
= Sample_Truncate
;
930 file_wrapper
->file_handler
.WriteBlock
= Sample_WriteBlock
;
932 return &file_wrapper
->file_handler
;
935 FPDF_FILEHANDLER
* PDFiumEngine::Form_OpenFile(FPDF_FORMFILLINFO
* param
,
939 std::string url_str
= "NULL";
942 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(url
));
944 // TODO: need to implement open file from the url
945 // Use a file path for the ease of testing
946 FILE* file
= fopen(XFA_TESTFILE("tem.txt"), mode
);
947 FPDF_FILE
* file_wrapper
= new FPDF_FILE
;
948 file_wrapper
->file
= file
;
949 file_wrapper
->file_handler
.clientData
= file_wrapper
;
950 file_wrapper
->file_handler
.Flush
= Sample_Flush
;
951 file_wrapper
->file_handler
.GetSize
= Sample_GetSize
;
952 file_wrapper
->file_handler
.ReadBlock
= Sample_ReadBlock
;
953 file_wrapper
->file_handler
.Release
= Sample_Release
;
954 file_wrapper
->file_handler
.Truncate
= Sample_Truncate
;
955 file_wrapper
->file_handler
.WriteBlock
= Sample_WriteBlock
;
956 return &file_wrapper
->file_handler
;
959 void PDFiumEngine::Form_GotoURL(FPDF_FORMFILLINFO
* param
,
960 FPDF_DOCUMENT document
,
961 FPDF_WIDESTRING url
) {
962 std::string url_str
=
963 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(url
));
964 // TODO: needs to implement GOTO URL action
967 int PDFiumEngine::Form_GetLanguage(FPDF_FORMFILLINFO
* param
,
973 #endif // PDF_USE_XFA
975 int PDFiumEngine::GetBlock(void* param
, unsigned long position
,
976 unsigned char* buffer
, unsigned long size
) {
977 DocumentLoader
* loader
= static_cast<DocumentLoader
*>(param
);
978 return loader
->GetBlock(position
, size
, buffer
);
981 FPDF_BOOL
PDFiumEngine::IsDataAvail(FX_FILEAVAIL
* param
,
982 size_t offset
, size_t size
) {
983 PDFiumEngine::FileAvail
* file_avail
=
984 static_cast<PDFiumEngine::FileAvail
*>(param
);
985 return file_avail
->loader
->IsDataAvailable(offset
, size
);
988 void PDFiumEngine::AddSegment(FX_DOWNLOADHINTS
* param
,
989 size_t offset
, size_t size
) {
990 PDFiumEngine::DownloadHints
* download_hints
=
991 static_cast<PDFiumEngine::DownloadHints
*>(param
);
992 return download_hints
->loader
->RequestData(offset
, size
);
995 bool PDFiumEngine::New(const char* url
,
996 const char* headers
) {
1005 void PDFiumEngine::PageOffsetUpdated(const pp::Point
& page_offset
) {
1006 page_offset_
= page_offset
;
1009 void PDFiumEngine::PluginSizeUpdated(const pp::Size
& size
) {
1012 plugin_size_
= size
;
1013 CalculateVisiblePages();
1016 void PDFiumEngine::ScrolledToXPosition(int position
) {
1019 int old_x
= position_
.x();
1020 position_
.set_x(position
);
1021 CalculateVisiblePages();
1022 client_
->Scroll(pp::Point(old_x
- position
, 0));
1025 void PDFiumEngine::ScrolledToYPosition(int position
) {
1028 int old_y
= position_
.y();
1029 position_
.set_y(position
);
1030 CalculateVisiblePages();
1031 client_
->Scroll(pp::Point(0, old_y
- position
));
1034 void PDFiumEngine::PrePaint() {
1035 for (size_t i
= 0; i
< progressive_paints_
.size(); ++i
)
1036 progressive_paints_
[i
].painted_
= false;
1039 void PDFiumEngine::Paint(const pp::Rect
& rect
,
1040 pp::ImageData
* image_data
,
1041 std::vector
<pp::Rect
>* ready
,
1042 std::vector
<pp::Rect
>* pending
) {
1047 pp::Rect leftover
= rect
;
1048 for (size_t i
= 0; i
< visible_pages_
.size(); ++i
) {
1049 int index
= visible_pages_
[i
];
1050 pp::Rect page_rect
= pages_
[index
]->rect();
1051 // Convert the current page's rectangle to screen rectangle. We do this
1052 // instead of the reverse (converting the dirty rectangle from screen to
1053 // page coordinates) because then we'd have to convert back to screen
1054 // coordinates, and the rounding errors sometime leave pixels dirty or even
1055 // move the text up or down a pixel when zoomed.
1056 pp::Rect page_rect_in_screen
= GetPageScreenRect(index
);
1057 pp::Rect dirty_in_screen
= page_rect_in_screen
.Intersect(leftover
);
1058 if (dirty_in_screen
.IsEmpty())
1061 leftover
= leftover
.Subtract(dirty_in_screen
);
1063 if (pages_
[index
]->available()) {
1064 int progressive
= GetProgressiveIndex(index
);
1065 if (progressive
!= -1) {
1066 DCHECK_GE(progressive
, 0);
1067 DCHECK_LT(static_cast<size_t>(progressive
), progressive_paints_
.size());
1068 if (progressive_paints_
[progressive
].rect
!= dirty_in_screen
) {
1069 // The PDFium code can only handle one progressive paint at a time, so
1070 // queue this up. Previously we used to merge the rects when this
1071 // happened, but it made scrolling up on complex PDFs very slow since
1072 // there would be a damaged rect at the top (from scroll) and at the
1073 // bottom (from toolbar).
1074 pending
->push_back(dirty_in_screen
);
1079 if (progressive
== -1) {
1080 progressive
= StartPaint(index
, dirty_in_screen
);
1081 progressive_paint_timeout_
= kMaxInitialProgressivePaintTimeMs
;
1083 progressive_paint_timeout_
= kMaxProgressivePaintTimeMs
;
1086 progressive_paints_
[progressive
].painted_
= true;
1087 if (ContinuePaint(progressive
, image_data
)) {
1088 FinishPaint(progressive
, image_data
);
1089 ready
->push_back(dirty_in_screen
);
1091 pending
->push_back(dirty_in_screen
);
1094 PaintUnavailablePage(index
, dirty_in_screen
, image_data
);
1095 ready
->push_back(dirty_in_screen
);
1100 void PDFiumEngine::PostPaint() {
1101 for (size_t i
= 0; i
< progressive_paints_
.size(); ++i
) {
1102 if (progressive_paints_
[i
].painted_
)
1105 // This rectangle must have been merged with another one, that's why we
1106 // weren't asked to paint it. Remove it or otherwise we'll never finish
1108 FPDF_RenderPage_Close(
1109 pages_
[progressive_paints_
[i
].page_index
]->GetPage());
1110 FPDFBitmap_Destroy(progressive_paints_
[i
].bitmap
);
1111 progressive_paints_
.erase(progressive_paints_
.begin() + i
);
1116 bool PDFiumEngine::HandleDocumentLoad(const pp::URLLoader
& loader
) {
1117 password_tries_remaining_
= kMaxPasswordTries
;
1118 return doc_loader_
.Init(loader
, url_
, headers_
);
1121 pp::Instance
* PDFiumEngine::GetPluginInstance() {
1122 return client_
->GetPluginInstance();
1125 pp::URLLoader
PDFiumEngine::CreateURLLoader() {
1126 return client_
->CreateURLLoader();
1129 void PDFiumEngine::AppendPage(PDFEngine
* engine
, int index
) {
1130 // Unload and delete the blank page before appending.
1131 pages_
[index
]->Unload();
1132 pages_
[index
]->set_calculated_links(false);
1133 pp::Size curr_page_size
= GetPageSize(index
);
1134 FPDFPage_Delete(doc_
, index
);
1135 FPDF_ImportPages(doc_
,
1136 static_cast<PDFiumEngine
*>(engine
)->doc(),
1139 pp::Size new_page_size
= GetPageSize(index
);
1140 if (curr_page_size
!= new_page_size
)
1142 client_
->Invalidate(GetPageScreenRect(index
));
1145 pp::Point
PDFiumEngine::GetScrollPosition() {
1149 void PDFiumEngine::SetScrollPosition(const pp::Point
& position
) {
1150 position_
= position
;
1153 bool PDFiumEngine::IsProgressiveLoad() {
1154 return doc_loader_
.is_partial_document();
1157 void PDFiumEngine::OnPartialDocumentLoaded() {
1158 file_access_
.m_FileLen
= doc_loader_
.document_size();
1159 fpdf_availability_
= FPDFAvail_Create(&file_availability_
, &file_access_
);
1160 DCHECK(fpdf_availability_
);
1162 // Currently engine does not deal efficiently with some non-linearized files.
1163 // See http://code.google.com/p/chromium/issues/detail?id=59400
1164 // To improve user experience we download entire file for non-linearized PDF.
1165 if (!FPDFAvail_IsLinearized(fpdf_availability_
)) {
1166 doc_loader_
.RequestData(0, doc_loader_
.document_size());
1173 void PDFiumEngine::OnPendingRequestComplete() {
1174 if (!doc_
|| !form_
) {
1179 // LoadDocument() will result in |pending_pages_| being reset so there's no
1180 // need to run the code below in that case.
1181 bool update_pages
= false;
1182 std::vector
<int> still_pending
;
1183 for (size_t i
= 0; i
< pending_pages_
.size(); ++i
) {
1184 if (CheckPageAvailable(pending_pages_
[i
], &still_pending
)) {
1185 update_pages
= true;
1186 if (IsPageVisible(pending_pages_
[i
]))
1187 client_
->Invalidate(GetPageScreenRect(pending_pages_
[i
]));
1190 pending_pages_
.swap(still_pending
);
1195 void PDFiumEngine::OnNewDataAvailable() {
1196 client_
->DocumentLoadProgress(doc_loader_
.GetAvailableData(),
1197 doc_loader_
.document_size());
1200 void PDFiumEngine::OnDocumentComplete() {
1201 if (!doc_
|| !form_
) {
1202 file_access_
.m_FileLen
= doc_loader_
.document_size();
1207 bool need_update
= false;
1208 for (size_t i
= 0; i
< pages_
.size(); ++i
) {
1209 if (pages_
[i
]->available())
1212 pages_
[i
]->set_available(true);
1213 // We still need to call IsPageAvail() even if the whole document is
1214 // already downloaded.
1215 FPDFAvail_IsPageAvail(fpdf_availability_
, i
, &download_hints_
);
1217 if (IsPageVisible(i
))
1218 client_
->Invalidate(GetPageScreenRect(i
));
1223 FinishLoadingDocument();
1226 void PDFiumEngine::FinishLoadingDocument() {
1227 DCHECK(doc_loader_
.IsDocumentComplete() && doc_
);
1228 if (called_do_document_action_
)
1230 called_do_document_action_
= true;
1232 // These can only be called now, as the JS might end up needing a page.
1233 FORM_DoDocumentJSAction(form_
);
1234 FORM_DoDocumentOpenAction(form_
);
1235 if (most_visible_page_
!= -1) {
1236 FPDF_PAGE new_page
= pages_
[most_visible_page_
]->GetPage();
1237 FORM_DoPageAAction(new_page
, form_
, FPDFPAGE_AACTION_OPEN
);
1240 if (doc_
) // This can only happen if loading |doc_| fails.
1241 client_
->DocumentLoadComplete(pages_
.size());
1244 void PDFiumEngine::UnsupportedFeature(int type
) {
1245 std::string feature
;
1248 case FPDF_UNSP_DOC_XFAFORM
:
1252 case FPDF_UNSP_DOC_PORTABLECOLLECTION
:
1253 feature
= "Portfolios_Packages";
1255 case FPDF_UNSP_DOC_ATTACHMENT
:
1256 case FPDF_UNSP_ANNOT_ATTACHMENT
:
1257 feature
= "Attachment";
1259 case FPDF_UNSP_DOC_SECURITY
:
1260 feature
= "Rights_Management";
1262 case FPDF_UNSP_DOC_SHAREDREVIEW
:
1263 feature
= "Shared_Review";
1265 case FPDF_UNSP_DOC_SHAREDFORM_ACROBAT
:
1266 case FPDF_UNSP_DOC_SHAREDFORM_FILESYSTEM
:
1267 case FPDF_UNSP_DOC_SHAREDFORM_EMAIL
:
1268 feature
= "Shared_Form";
1270 case FPDF_UNSP_ANNOT_3DANNOT
:
1273 case FPDF_UNSP_ANNOT_MOVIE
:
1276 case FPDF_UNSP_ANNOT_SOUND
:
1279 case FPDF_UNSP_ANNOT_SCREEN_MEDIA
:
1280 case FPDF_UNSP_ANNOT_SCREEN_RICHMEDIA
:
1283 case FPDF_UNSP_ANNOT_SIG
:
1284 feature
= "Digital_Signature";
1287 client_
->DocumentHasUnsupportedFeature(feature
);
1290 void PDFiumEngine::ContinueFind(int32_t result
) {
1291 StartFind(current_find_text_
.c_str(), !!result
);
1294 bool PDFiumEngine::HandleEvent(const pp::InputEvent
& event
) {
1295 DCHECK(!defer_page_unload_
);
1296 defer_page_unload_
= true;
1298 switch (event
.GetType()) {
1299 case PP_INPUTEVENT_TYPE_MOUSEDOWN
:
1300 rv
= OnMouseDown(pp::MouseInputEvent(event
));
1302 case PP_INPUTEVENT_TYPE_MOUSEUP
:
1303 rv
= OnMouseUp(pp::MouseInputEvent(event
));
1305 case PP_INPUTEVENT_TYPE_MOUSEMOVE
:
1306 rv
= OnMouseMove(pp::MouseInputEvent(event
));
1308 case PP_INPUTEVENT_TYPE_KEYDOWN
:
1309 rv
= OnKeyDown(pp::KeyboardInputEvent(event
));
1311 case PP_INPUTEVENT_TYPE_KEYUP
:
1312 rv
= OnKeyUp(pp::KeyboardInputEvent(event
));
1314 case PP_INPUTEVENT_TYPE_CHAR
:
1315 rv
= OnChar(pp::KeyboardInputEvent(event
));
1321 DCHECK(defer_page_unload_
);
1322 defer_page_unload_
= false;
1323 for (size_t i
= 0; i
< deferred_page_unloads_
.size(); ++i
)
1324 pages_
[deferred_page_unloads_
[i
]]->Unload();
1325 deferred_page_unloads_
.clear();
1329 uint32_t PDFiumEngine::QuerySupportedPrintOutputFormats() {
1330 if (!HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
))
1332 return PP_PRINTOUTPUTFORMAT_PDF
;
1335 void PDFiumEngine::PrintBegin() {
1336 FORM_DoDocumentAAction(form_
, FPDFDOC_AACTION_WP
);
1339 pp::Resource
PDFiumEngine::PrintPages(
1340 const PP_PrintPageNumberRange_Dev
* page_ranges
, uint32_t page_range_count
,
1341 const PP_PrintSettings_Dev
& print_settings
) {
1342 if (HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY
))
1343 return PrintPagesAsPDF(page_ranges
, page_range_count
, print_settings
);
1344 else if (HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
))
1345 return PrintPagesAsRasterPDF(page_ranges
, page_range_count
, print_settings
);
1346 return pp::Resource();
1349 FPDF_DOCUMENT
PDFiumEngine::CreateSinglePageRasterPdf(
1350 double source_page_width
,
1351 double source_page_height
,
1352 const PP_PrintSettings_Dev
& print_settings
,
1353 PDFiumPage
* page_to_print
) {
1354 FPDF_DOCUMENT temp_doc
= FPDF_CreateNewDocument();
1358 const pp::Size
& bitmap_size(page_to_print
->rect().size());
1360 FPDF_PAGE temp_page
=
1361 FPDFPage_New(temp_doc
, 0, source_page_width
, source_page_height
);
1363 pp::ImageData image
= pp::ImageData(client_
->GetPluginInstance(),
1364 PP_IMAGEDATAFORMAT_BGRA_PREMUL
,
1368 FPDF_BITMAP bitmap
= FPDFBitmap_CreateEx(bitmap_size
.width(),
1369 bitmap_size
.height(),
1375 FPDFBitmap_FillRect(
1376 bitmap
, 0, 0, bitmap_size
.width(), bitmap_size
.height(), 0xFFFFFFFF);
1378 pp::Rect page_rect
= page_to_print
->rect();
1379 FPDF_RenderPageBitmap(bitmap
,
1380 page_to_print
->GetPrintPage(),
1385 print_settings
.orientation
,
1386 FPDF_ANNOT
| FPDF_PRINTING
| FPDF_NO_CATCH
);
1388 double ratio_x
= ConvertUnitDouble(bitmap_size
.width(),
1391 double ratio_y
= ConvertUnitDouble(bitmap_size
.height(),
1395 // Add the bitmap to an image object and add the image object to the output
1397 FPDF_PAGEOBJECT temp_img
= FPDFPageObj_NewImgeObj(temp_doc
);
1398 FPDFImageObj_SetBitmap(&temp_page
, 1, temp_img
, bitmap
);
1399 FPDFImageObj_SetMatrix(temp_img
, ratio_x
, 0, 0, ratio_y
, 0, 0);
1400 FPDFPage_InsertObject(temp_page
, temp_img
);
1401 FPDFPage_GenerateContent(temp_page
);
1402 FPDF_ClosePage(temp_page
);
1404 page_to_print
->ClosePrintPage();
1405 FPDFBitmap_Destroy(bitmap
);
1410 pp::Buffer_Dev
PDFiumEngine::PrintPagesAsRasterPDF(
1411 const PP_PrintPageNumberRange_Dev
* page_ranges
, uint32_t page_range_count
,
1412 const PP_PrintSettings_Dev
& print_settings
) {
1413 if (!page_range_count
)
1414 return pp::Buffer_Dev();
1416 // If document is not downloaded yet, disable printing.
1417 if (doc_
&& !doc_loader_
.IsDocumentComplete())
1418 return pp::Buffer_Dev();
1420 FPDF_DOCUMENT output_doc
= FPDF_CreateNewDocument();
1422 return pp::Buffer_Dev();
1424 SaveSelectedFormForPrint();
1426 std::vector
<PDFiumPage
> pages_to_print
;
1427 // width and height of source PDF pages.
1428 std::vector
<std::pair
<double, double> > source_page_sizes
;
1429 // Collect pages to print and sizes of source pages.
1430 std::vector
<uint32_t> page_numbers
=
1431 GetPageNumbersFromPrintPageNumberRange(page_ranges
, page_range_count
);
1432 for (size_t i
= 0; i
< page_numbers
.size(); ++i
) {
1433 uint32_t page_number
= page_numbers
[i
];
1434 FPDF_PAGE pdf_page
= FPDF_LoadPage(doc_
, page_number
);
1435 double source_page_width
= FPDF_GetPageWidth(pdf_page
);
1436 double source_page_height
= FPDF_GetPageHeight(pdf_page
);
1437 source_page_sizes
.push_back(std::make_pair(source_page_width
,
1438 source_page_height
));
1440 int width_in_pixels
= ConvertUnit(source_page_width
,
1442 print_settings
.dpi
);
1443 int height_in_pixels
= ConvertUnit(source_page_height
,
1445 print_settings
.dpi
);
1447 pp::Rect
rect(width_in_pixels
, height_in_pixels
);
1448 pages_to_print
.push_back(PDFiumPage(this, page_number
, rect
, true));
1449 FPDF_ClosePage(pdf_page
);
1452 #if defined(OS_LINUX)
1453 g_last_instance_id
= client_
->GetPluginInstance()->pp_instance();
1457 for (; i
< pages_to_print
.size(); ++i
) {
1458 double source_page_width
= source_page_sizes
[i
].first
;
1459 double source_page_height
= source_page_sizes
[i
].second
;
1461 // Use temp_doc to compress image by saving PDF to buffer.
1462 FPDF_DOCUMENT temp_doc
= CreateSinglePageRasterPdf(source_page_width
,
1465 &pages_to_print
[i
]);
1470 pp::Buffer_Dev buffer
= GetFlattenedPrintData(temp_doc
);
1471 FPDF_CloseDocument(temp_doc
);
1473 PDFiumMemBufferFileRead
file_read(buffer
.data(), buffer
.size());
1474 temp_doc
= FPDF_LoadCustomDocument(&file_read
, NULL
);
1476 FPDF_BOOL imported
= FPDF_ImportPages(output_doc
, temp_doc
, "1", i
);
1477 FPDF_CloseDocument(temp_doc
);
1482 pp::Buffer_Dev buffer
;
1483 if (i
== pages_to_print
.size()) {
1484 FPDF_CopyViewerPreferences(output_doc
, doc_
);
1485 FitContentsToPrintableAreaIfRequired(output_doc
, print_settings
);
1486 // Now flatten all the output pages.
1487 buffer
= GetFlattenedPrintData(output_doc
);
1489 FPDF_CloseDocument(output_doc
);
1493 pp::Buffer_Dev
PDFiumEngine::GetFlattenedPrintData(const FPDF_DOCUMENT
& doc
) {
1494 int page_count
= FPDF_GetPageCount(doc
);
1495 bool flatten_succeeded
= true;
1496 for (int i
= 0; i
< page_count
; ++i
) {
1497 FPDF_PAGE page
= FPDF_LoadPage(doc
, i
);
1500 int flatten_ret
= FPDFPage_Flatten(page
, FLAT_PRINT
);
1501 FPDF_ClosePage(page
);
1502 if (flatten_ret
== FLATTEN_FAIL
) {
1503 flatten_succeeded
= false;
1507 flatten_succeeded
= false;
1511 if (!flatten_succeeded
) {
1512 FPDF_CloseDocument(doc
);
1513 return pp::Buffer_Dev();
1516 pp::Buffer_Dev buffer
;
1517 PDFiumMemBufferFileWrite output_file_write
;
1518 if (FPDF_SaveAsCopy(doc
, &output_file_write
, 0)) {
1519 buffer
= pp::Buffer_Dev(
1520 client_
->GetPluginInstance(), output_file_write
.size());
1521 if (!buffer
.is_null()) {
1522 memcpy(buffer
.data(), output_file_write
.buffer().c_str(),
1523 output_file_write
.size());
1529 pp::Buffer_Dev
PDFiumEngine::PrintPagesAsPDF(
1530 const PP_PrintPageNumberRange_Dev
* page_ranges
, uint32_t page_range_count
,
1531 const PP_PrintSettings_Dev
& print_settings
) {
1532 if (!page_range_count
)
1533 return pp::Buffer_Dev();
1536 FPDF_DOCUMENT output_doc
= FPDF_CreateNewDocument();
1538 return pp::Buffer_Dev();
1540 SaveSelectedFormForPrint();
1542 std::string page_number_str
;
1543 for (uint32_t index
= 0; index
< page_range_count
; ++index
) {
1544 if (!page_number_str
.empty())
1545 page_number_str
.append(",");
1546 page_number_str
.append(
1547 base::IntToString(page_ranges
[index
].first_page_number
+ 1));
1548 if (page_ranges
[index
].first_page_number
!=
1549 page_ranges
[index
].last_page_number
) {
1550 page_number_str
.append("-");
1551 page_number_str
.append(
1552 base::IntToString(page_ranges
[index
].last_page_number
+ 1));
1556 std::vector
<uint32_t> page_numbers
=
1557 GetPageNumbersFromPrintPageNumberRange(page_ranges
, page_range_count
);
1558 for (size_t i
= 0; i
< page_numbers
.size(); ++i
) {
1559 uint32_t page_number
= page_numbers
[i
];
1560 pages_
[page_number
]->GetPage();
1561 if (!IsPageVisible(page_numbers
[i
]))
1562 pages_
[page_number
]->Unload();
1565 FPDF_CopyViewerPreferences(output_doc
, doc_
);
1566 if (!FPDF_ImportPages(output_doc
, doc_
, page_number_str
.c_str(), 0)) {
1567 FPDF_CloseDocument(output_doc
);
1568 return pp::Buffer_Dev();
1571 FitContentsToPrintableAreaIfRequired(output_doc
, print_settings
);
1573 // Now flatten all the output pages.
1574 pp::Buffer_Dev buffer
= GetFlattenedPrintData(output_doc
);
1575 FPDF_CloseDocument(output_doc
);
1579 void PDFiumEngine::FitContentsToPrintableAreaIfRequired(
1580 const FPDF_DOCUMENT
& doc
, const PP_PrintSettings_Dev
& print_settings
) {
1581 // Check to see if we need to fit pdf contents to printer paper size.
1582 if (print_settings
.print_scaling_option
!=
1583 PP_PRINTSCALINGOPTION_SOURCE_SIZE
) {
1584 int num_pages
= FPDF_GetPageCount(doc
);
1585 // In-place transformation is more efficient than creating a new
1586 // transformed document from the source document. Therefore, transform
1587 // every page to fit the contents in the selected printer paper.
1588 for (int i
= 0; i
< num_pages
; ++i
) {
1589 FPDF_PAGE page
= FPDF_LoadPage(doc
, i
);
1590 TransformPDFPageForPrinting(page
, print_settings
);
1591 FPDF_ClosePage(page
);
1596 void PDFiumEngine::SaveSelectedFormForPrint() {
1597 FORM_ForceToKillFocus(form_
);
1598 client_
->FormTextFieldFocusChange(false);
1601 void PDFiumEngine::PrintEnd() {
1602 FORM_DoDocumentAAction(form_
, FPDFDOC_AACTION_DP
);
1605 PDFiumPage::Area
PDFiumEngine::GetCharIndex(const pp::MouseInputEvent
& event
,
1609 PDFiumPage::LinkTarget
* target
) {
1610 // First figure out which page this is in.
1611 pp::Point mouse_point
= event
.GetPosition();
1612 return GetCharIndex(mouse_point
, page_index
, char_index
, form_type
, target
);
1615 PDFiumPage::Area
PDFiumEngine::GetCharIndex(const pp::Point
& point
,
1619 PDFiumPage::LinkTarget
* target
) {
1621 pp::Point
point_in_page(
1622 static_cast<int>((point
.x() + position_
.x()) / current_zoom_
),
1623 static_cast<int>((point
.y() + position_
.y()) / current_zoom_
));
1624 for (size_t i
= 0; i
< visible_pages_
.size(); ++i
) {
1625 if (pages_
[visible_pages_
[i
]]->rect().Contains(point_in_page
)) {
1626 page
= visible_pages_
[i
];
1631 return PDFiumPage::NONSELECTABLE_AREA
;
1633 // If the page hasn't finished rendering, calling into the page sometimes
1635 for (size_t i
= 0; i
< progressive_paints_
.size(); ++i
) {
1636 if (progressive_paints_
[i
].page_index
== page
)
1637 return PDFiumPage::NONSELECTABLE_AREA
;
1641 return pages_
[page
]->GetCharIndex(
1642 point_in_page
, current_rotation_
, char_index
, form_type
, target
);
1645 bool PDFiumEngine::OnMouseDown(const pp::MouseInputEvent
& event
) {
1646 if (event
.GetButton() == PP_INPUTEVENT_MOUSEBUTTON_RIGHT
) {
1647 if (!selection_
.size())
1649 std::vector
<pp::Rect
> selection_rect_vector
;
1650 GetAllScreenRectsUnion(&selection_
, GetVisibleRect().point(),
1651 &selection_rect_vector
);
1652 pp::Point point
= event
.GetPosition();
1653 for (size_t i
= 0; i
< selection_rect_vector
.size(); ++i
) {
1654 if (selection_rect_vector
[i
].Contains(point
.x(), point
.y()))
1657 SelectionChangeInvalidator
selection_invalidator(this);
1661 if (event
.GetButton() != PP_INPUTEVENT_MOUSEBUTTON_LEFT
)
1664 SelectionChangeInvalidator
selection_invalidator(this);
1667 int page_index
= -1;
1668 int char_index
= -1;
1669 int form_type
= FPDF_FORMFIELD_UNKNOWN
;
1670 PDFiumPage::LinkTarget target
;
1671 PDFiumPage::Area area
=
1672 GetCharIndex(event
, &page_index
, &char_index
, &form_type
, &target
);
1673 mouse_down_state_
.Set(area
, target
);
1675 // Decide whether to open link or not based on user action in mouse up and
1676 // mouse move events.
1677 if (area
== PDFiumPage::WEBLINK_AREA
)
1680 if (area
== PDFiumPage::DOCLINK_AREA
) {
1681 client_
->ScrollToPage(target
.page
);
1682 client_
->FormTextFieldFocusChange(false);
1686 if (page_index
!= -1) {
1687 last_page_mouse_down_
= page_index
;
1688 double page_x
, page_y
;
1689 pp::Point point
= event
.GetPosition();
1690 DeviceToPage(page_index
, point
.x(), point
.y(), &page_x
, &page_y
);
1692 FORM_OnLButtonDown(form_
, pages_
[page_index
]->GetPage(), 0, page_x
, page_y
);
1693 if (form_type
> FPDF_FORMFIELD_UNKNOWN
) { // returns -1 sometimes...
1694 mouse_down_state_
.Set(PDFiumPage::NONSELECTABLE_AREA
, target
);
1695 bool is_valid_control
= (form_type
== FPDF_FORMFIELD_TEXTFIELD
||
1696 form_type
== FPDF_FORMFIELD_COMBOBOX
);
1698 is_valid_control
|= (form_type
== FPDF_FORMFIELD_XFA
);
1700 client_
->FormTextFieldFocusChange(is_valid_control
);
1701 return true; // Return now before we get into the selection code.
1705 client_
->FormTextFieldFocusChange(false);
1707 if (area
!= PDFiumPage::TEXT_AREA
)
1708 return true; // Return true so WebKit doesn't do its own highlighting.
1710 if (event
.GetClickCount() == 1) {
1711 OnSingleClick(page_index
, char_index
);
1712 } else if (event
.GetClickCount() == 2 ||
1713 event
.GetClickCount() == 3) {
1714 OnMultipleClick(event
.GetClickCount(), page_index
, char_index
);
1720 void PDFiumEngine::OnSingleClick(int page_index
, int char_index
) {
1722 selection_
.push_back(PDFiumRange(pages_
[page_index
], char_index
, 0));
1725 void PDFiumEngine::OnMultipleClick(int click_count
,
1728 // It would be more efficient if the SDK could support finding a space, but
1730 int start_index
= char_index
;
1732 base::char16 cur
= pages_
[page_index
]->GetCharAtIndex(start_index
);
1733 // For double click, we want to select one word so we look for whitespace
1734 // boundaries. For triple click, we want the whole line.
1735 if (cur
== '\n' || (click_count
== 2 && (cur
== ' ' || cur
== '\t')))
1737 } while (--start_index
>= 0);
1741 int end_index
= char_index
;
1742 int total
= pages_
[page_index
]->GetCharCount();
1743 while (end_index
++ <= total
) {
1744 base::char16 cur
= pages_
[page_index
]->GetCharAtIndex(end_index
);
1745 if (cur
== '\n' || (click_count
== 2 && (cur
== ' ' || cur
== '\t')))
1749 selection_
.push_back(PDFiumRange(
1750 pages_
[page_index
], start_index
, end_index
- start_index
));
1753 bool PDFiumEngine::OnMouseUp(const pp::MouseInputEvent
& event
) {
1754 if (event
.GetButton() != PP_INPUTEVENT_MOUSEBUTTON_LEFT
)
1757 int page_index
= -1;
1758 int char_index
= -1;
1759 int form_type
= FPDF_FORMFIELD_UNKNOWN
;
1760 PDFiumPage::LinkTarget target
;
1761 PDFiumPage::Area area
=
1762 GetCharIndex(event
, &page_index
, &char_index
, &form_type
, &target
);
1764 // Open link on mouse up for same link for which mouse down happened earlier.
1765 if (mouse_down_state_
.Matches(area
, target
)) {
1766 if (area
== PDFiumPage::WEBLINK_AREA
) {
1767 bool open_in_new_tab
= !!(event
.GetModifiers() & kDefaultKeyModifier
);
1768 client_
->NavigateTo(target
.url
, open_in_new_tab
);
1769 client_
->FormTextFieldFocusChange(false);
1774 if (page_index
!= -1) {
1775 double page_x
, page_y
;
1776 pp::Point point
= event
.GetPosition();
1777 DeviceToPage(page_index
, point
.x(), point
.y(), &page_x
, &page_y
);
1779 form_
, pages_
[page_index
]->GetPage(), 0, page_x
, page_y
);
1785 SetSelecting(false);
1789 bool PDFiumEngine::OnMouseMove(const pp::MouseInputEvent
& event
) {
1790 int page_index
= -1;
1791 int char_index
= -1;
1792 int form_type
= FPDF_FORMFIELD_UNKNOWN
;
1793 PDFiumPage::LinkTarget target
;
1794 PDFiumPage::Area area
=
1795 GetCharIndex(event
, &page_index
, &char_index
, &form_type
, &target
);
1797 // Clear |mouse_down_state_| if mouse moves away from where the mouse down
1799 if (!mouse_down_state_
.Matches(area
, target
))
1800 mouse_down_state_
.Reset();
1803 PP_CursorType_Dev cursor
;
1805 case PDFiumPage::TEXT_AREA
:
1806 cursor
= PP_CURSORTYPE_IBEAM
;
1808 case PDFiumPage::WEBLINK_AREA
:
1809 case PDFiumPage::DOCLINK_AREA
:
1810 cursor
= PP_CURSORTYPE_HAND
;
1812 case PDFiumPage::NONSELECTABLE_AREA
:
1814 switch (form_type
) {
1815 case FPDF_FORMFIELD_PUSHBUTTON
:
1816 case FPDF_FORMFIELD_CHECKBOX
:
1817 case FPDF_FORMFIELD_RADIOBUTTON
:
1818 case FPDF_FORMFIELD_COMBOBOX
:
1819 case FPDF_FORMFIELD_LISTBOX
:
1820 cursor
= PP_CURSORTYPE_HAND
;
1822 case FPDF_FORMFIELD_TEXTFIELD
:
1823 cursor
= PP_CURSORTYPE_IBEAM
;
1826 cursor
= PP_CURSORTYPE_POINTER
;
1832 if (page_index
!= -1) {
1833 double page_x
, page_y
;
1834 pp::Point point
= event
.GetPosition();
1835 DeviceToPage(page_index
, point
.x(), point
.y(), &page_x
, &page_y
);
1836 FORM_OnMouseMove(form_
, pages_
[page_index
]->GetPage(), 0, page_x
, page_y
);
1839 client_
->UpdateCursor(cursor
);
1840 pp::Point point
= event
.GetPosition();
1841 std::string url
= GetLinkAtPosition(event
.GetPosition());
1842 if (url
!= link_under_cursor_
) {
1843 link_under_cursor_
= url
;
1844 pp::PDF::SetLinkUnderCursor(GetPluginInstance(), url
.c_str());
1846 // No need to swallow the event, since this might interfere with the
1847 // scrollbars if the user is dragging them.
1851 // We're selecting but right now we're not over text, so don't change the
1852 // current selection.
1853 if (area
!= PDFiumPage::TEXT_AREA
&& area
!= PDFiumPage::WEBLINK_AREA
&&
1854 area
!= PDFiumPage::DOCLINK_AREA
) {
1858 SelectionChangeInvalidator
selection_invalidator(this);
1860 // Check if the user has descreased their selection area and we need to remove
1861 // pages from selection_.
1862 for (size_t i
= 0; i
< selection_
.size(); ++i
) {
1863 if (selection_
[i
].page_index() == page_index
) {
1864 // There should be no other pages after this.
1865 selection_
.erase(selection_
.begin() + i
+ 1, selection_
.end());
1870 if (selection_
.size() == 0)
1873 int last
= selection_
.size() - 1;
1874 if (selection_
[last
].page_index() == page_index
) {
1875 // Selecting within a page.
1877 if (char_index
>= selection_
[last
].char_index()) {
1878 // Selecting forward.
1879 count
= char_index
- selection_
[last
].char_index() + 1;
1881 count
= char_index
- selection_
[last
].char_index() - 1;
1883 selection_
[last
].SetCharCount(count
);
1884 } else if (selection_
[last
].page_index() < page_index
) {
1885 // Selecting into the next page.
1887 // First make sure that there are no gaps in selection, i.e. if mousedown on
1888 // page one but we only get mousemove over page three, we want page two.
1889 for (int i
= selection_
[last
].page_index() + 1; i
< page_index
; ++i
) {
1890 selection_
.push_back(PDFiumRange(pages_
[i
], 0,
1891 pages_
[i
]->GetCharCount()));
1894 int count
= pages_
[selection_
[last
].page_index()]->GetCharCount();
1895 selection_
[last
].SetCharCount(count
- selection_
[last
].char_index());
1896 selection_
.push_back(PDFiumRange(pages_
[page_index
], 0, char_index
));
1898 // Selecting into the previous page.
1899 // The selection's char_index is 0-based, so the character count is one
1900 // more than the index. The character count needs to be negative to
1901 // indicate a backwards selection.
1902 selection_
[last
].SetCharCount(-(selection_
[last
].char_index() + 1));
1904 // First make sure that there are no gaps in selection, i.e. if mousedown on
1905 // page three but we only get mousemove over page one, we want page two.
1906 for (int i
= selection_
[last
].page_index() - 1; i
> page_index
; --i
) {
1907 selection_
.push_back(PDFiumRange(pages_
[i
], 0,
1908 pages_
[i
]->GetCharCount()));
1911 int count
= pages_
[page_index
]->GetCharCount();
1912 selection_
.push_back(
1913 PDFiumRange(pages_
[page_index
], count
, count
- char_index
));
1919 bool PDFiumEngine::OnKeyDown(const pp::KeyboardInputEvent
& event
) {
1920 if (last_page_mouse_down_
== -1)
1923 bool rv
= !!FORM_OnKeyDown(
1924 form_
, pages_
[last_page_mouse_down_
]->GetPage(),
1925 event
.GetKeyCode(), event
.GetModifiers());
1927 if (event
.GetKeyCode() == ui::VKEY_BACK
||
1928 event
.GetKeyCode() == ui::VKEY_ESCAPE
) {
1929 // Chrome doesn't send char events for backspace or escape keys, see
1930 // PlatformKeyboardEventBuilder::isCharacterKey() and
1931 // http://chrome-corpsvn.mtv.corp.google.com/viewvc?view=rev&root=chrome&revision=31805
1932 // for more information. So just fake one since PDFium uses it.
1934 str
.push_back(event
.GetKeyCode());
1935 pp::KeyboardInputEvent
synthesized(pp::KeyboardInputEvent(
1936 client_
->GetPluginInstance(),
1937 PP_INPUTEVENT_TYPE_CHAR
,
1938 event
.GetTimeStamp(),
1939 event
.GetModifiers(),
1942 OnChar(synthesized
);
1948 bool PDFiumEngine::OnKeyUp(const pp::KeyboardInputEvent
& event
) {
1949 if (last_page_mouse_down_
== -1)
1952 return !!FORM_OnKeyUp(
1953 form_
, pages_
[last_page_mouse_down_
]->GetPage(),
1954 event
.GetKeyCode(), event
.GetModifiers());
1957 bool PDFiumEngine::OnChar(const pp::KeyboardInputEvent
& event
) {
1958 if (last_page_mouse_down_
== -1)
1961 base::string16 str
= base::UTF8ToUTF16(event
.GetCharacterText().AsString());
1962 return !!FORM_OnChar(
1963 form_
, pages_
[last_page_mouse_down_
]->GetPage(),
1965 event
.GetModifiers());
1968 void PDFiumEngine::StartFind(const char* text
, bool case_sensitive
) {
1969 // We can get a call to StartFind before we have any page information (i.e.
1970 // before the first call to LoadDocument has happened). Handle this case.
1974 bool first_search
= false;
1975 int character_to_start_searching_from
= 0;
1976 if (current_find_text_
!= text
) { // First time we search for this text.
1977 first_search
= true;
1978 std::vector
<PDFiumRange
> old_selection
= selection_
;
1980 current_find_text_
= text
;
1982 if (old_selection
.empty()) {
1983 // Start searching from the beginning of the document.
1984 next_page_to_search_
= 0;
1985 last_page_to_search_
= pages_
.size() - 1;
1986 last_character_index_to_search_
= -1;
1988 // There's a current selection, so start from it.
1989 next_page_to_search_
= old_selection
[0].page_index();
1990 last_character_index_to_search_
= old_selection
[0].char_index();
1991 character_to_start_searching_from
= old_selection
[0].char_index();
1992 last_page_to_search_
= next_page_to_search_
;
1996 int current_page
= next_page_to_search_
;
1998 if (pages_
[current_page
]->available()) {
1999 base::string16 str
= base::UTF8ToUTF16(text
);
2000 // Don't use PDFium to search for now, since it doesn't support unicode
2001 // text. Leave the code for now to avoid bit-rot, in case it's fixed later.
2004 str
, case_sensitive
, first_search
, character_to_start_searching_from
,
2008 str
, case_sensitive
, first_search
, character_to_start_searching_from
,
2012 if (!IsPageVisible(current_page
))
2013 pages_
[current_page
]->Unload();
2016 if (next_page_to_search_
!= last_page_to_search_
||
2017 (first_search
&& last_character_index_to_search_
!= -1)) {
2018 ++next_page_to_search_
;
2021 if (next_page_to_search_
== static_cast<int>(pages_
.size()))
2022 next_page_to_search_
= 0;
2023 // If there's only one page in the document and we start searching midway,
2024 // then we'll want to search the page one more time.
2025 bool end_of_search
=
2026 next_page_to_search_
== last_page_to_search_
&&
2027 // Only one page but didn't start midway.
2028 ((pages_
.size() == 1 && last_character_index_to_search_
== -1) ||
2029 // Started midway, but only 1 page and we already looped around.
2030 (pages_
.size() == 1 && !first_search
) ||
2031 // Started midway, and we've just looped around.
2032 (pages_
.size() > 1 && current_page
== next_page_to_search_
));
2034 if (end_of_search
) {
2035 // Send the final notification.
2036 client_
->NotifyNumberOfFindResultsChanged(find_results_
.size(), true);
2038 // When searching is complete, resume finding at a particular index.
2039 // Assuming the user has not clicked the find button in the meanwhile.
2040 if (resume_find_index_
.valid() && !current_find_index_
.valid()) {
2041 size_t resume_index
= resume_find_index_
.GetIndex();
2042 if (resume_index
>= find_results_
.size()) {
2043 // This might happen if the PDF has some dynamically generated text?
2046 current_find_index_
.SetIndex(resume_index
);
2047 client_
->NotifySelectedFindResultChanged(resume_index
);
2049 resume_find_index_
.Invalidate();
2051 pp::CompletionCallback callback
=
2052 find_factory_
.NewCallback(&PDFiumEngine::ContinueFind
);
2053 pp::Module::Get()->core()->CallOnMainThread(
2054 0, callback
, case_sensitive
? 1 : 0);
2058 void PDFiumEngine::SearchUsingPDFium(const base::string16
& term
,
2059 bool case_sensitive
,
2061 int character_to_start_searching_from
,
2063 // Find all the matches in the current page.
2064 unsigned long flags
= case_sensitive
? FPDF_MATCHCASE
: 0;
2065 FPDF_SCHHANDLE find
= FPDFText_FindStart(
2066 pages_
[current_page
]->GetTextPage(),
2067 reinterpret_cast<const unsigned short*>(term
.c_str()),
2068 flags
, character_to_start_searching_from
);
2070 // Note: since we search one page at a time, we don't find matches across
2071 // page boundaries. We could do this manually ourself, but it seems low
2072 // priority since Reader itself doesn't do it.
2073 while (FPDFText_FindNext(find
)) {
2074 PDFiumRange
result(pages_
[current_page
],
2075 FPDFText_GetSchResultIndex(find
),
2076 FPDFText_GetSchCount(find
));
2078 if (!first_search
&&
2079 last_character_index_to_search_
!= -1 &&
2080 result
.page_index() == last_page_to_search_
&&
2081 result
.char_index() >= last_character_index_to_search_
) {
2085 AddFindResult(result
);
2088 FPDFText_FindClose(find
);
2091 void PDFiumEngine::SearchUsingICU(const base::string16
& term
,
2092 bool case_sensitive
,
2094 int character_to_start_searching_from
,
2096 base::string16 page_text
;
2097 int text_length
= pages_
[current_page
]->GetCharCount();
2098 if (character_to_start_searching_from
) {
2099 text_length
-= character_to_start_searching_from
;
2100 } else if (!first_search
&&
2101 last_character_index_to_search_
!= -1 &&
2102 current_page
== last_page_to_search_
) {
2103 text_length
= last_character_index_to_search_
;
2105 if (text_length
<= 0)
2108 PDFiumAPIStringBufferAdapter
<base::string16
> api_string_adapter(&page_text
,
2111 unsigned short* data
=
2112 reinterpret_cast<unsigned short*>(api_string_adapter
.GetData());
2113 int written
= FPDFText_GetText(pages_
[current_page
]->GetTextPage(),
2114 character_to_start_searching_from
,
2117 api_string_adapter
.Close(written
);
2119 std::vector
<PDFEngine::Client::SearchStringResult
> results
;
2120 client_
->SearchString(
2121 page_text
.c_str(), term
.c_str(), case_sensitive
, &results
);
2122 for (size_t i
= 0; i
< results
.size(); ++i
) {
2123 // Need to map the indexes from the page text, which may have generated
2124 // characters like space etc, to character indices from the page.
2125 int temp_start
= results
[i
].start_index
+ character_to_start_searching_from
;
2126 int start
= FPDFText_GetCharIndexFromTextIndex(
2127 pages_
[current_page
]->GetTextPage(), temp_start
);
2128 int end
= FPDFText_GetCharIndexFromTextIndex(
2129 pages_
[current_page
]->GetTextPage(),
2130 temp_start
+ results
[i
].length
);
2131 AddFindResult(PDFiumRange(pages_
[current_page
], start
, end
- start
));
2135 void PDFiumEngine::AddFindResult(const PDFiumRange
& result
) {
2136 // Figure out where to insert the new location, since we could have
2137 // started searching midway and now we wrapped.
2138 size_t result_index
;
2139 int page_index
= result
.page_index();
2140 int char_index
= result
.char_index();
2141 for (result_index
= 0; result_index
< find_results_
.size(); ++result_index
) {
2142 if (find_results_
[result_index
].page_index() > page_index
||
2143 (find_results_
[result_index
].page_index() == page_index
&&
2144 find_results_
[result_index
].char_index() > char_index
)) {
2148 find_results_
.insert(find_results_
.begin() + result_index
, result
);
2151 if (current_find_index_
.valid()) {
2152 if (result_index
<= current_find_index_
.GetIndex()) {
2153 // Update the current match index
2154 size_t find_index
= current_find_index_
.IncrementIndex();
2155 DCHECK_LT(find_index
, find_results_
.size());
2156 client_
->NotifySelectedFindResultChanged(current_find_index_
.GetIndex());
2158 } else if (!resume_find_index_
.valid()) {
2159 // Both indices are invalid. Select the first match.
2160 SelectFindResult(true);
2162 client_
->NotifyNumberOfFindResultsChanged(find_results_
.size(), false);
2165 bool PDFiumEngine::SelectFindResult(bool forward
) {
2166 if (find_results_
.empty()) {
2171 SelectionChangeInvalidator
selection_invalidator(this);
2173 // Move back/forward through the search locations we previously found.
2175 const size_t last_index
= find_results_
.size() - 1;
2176 if (current_find_index_
.valid()) {
2177 size_t current_index
= current_find_index_
.GetIndex();
2179 new_index
= (current_index
>= last_index
) ? 0 : current_index
+ 1;
2181 new_index
= (current_find_index_
.GetIndex() == 0) ?
2182 last_index
: current_index
- 1;
2185 new_index
= forward
? 0 : last_index
;
2187 current_find_index_
.SetIndex(new_index
);
2189 // Update the selection before telling the client to scroll, since it could
2192 selection_
.push_back(find_results_
[current_find_index_
.GetIndex()]);
2194 // If the result is not in view, scroll to it.
2195 pp::Rect bounding_rect
;
2196 pp::Rect visible_rect
= GetVisibleRect();
2197 // Use zoom of 1.0 since visible_rect is without zoom.
2198 std::vector
<pp::Rect
> rects
;
2199 rects
= find_results_
[current_find_index_
.GetIndex()].GetScreenRects(
2200 pp::Point(), 1.0, current_rotation_
);
2201 for (size_t i
= 0; i
< rects
.size(); ++i
)
2202 bounding_rect
= bounding_rect
.Union(rects
[i
]);
2203 if (!visible_rect
.Contains(bounding_rect
)) {
2204 pp::Point center
= bounding_rect
.CenterPoint();
2205 // Make the page centered.
2206 int new_y
= static_cast<int>(center
.y() * current_zoom_
) -
2207 static_cast<int>(visible_rect
.height() * current_zoom_
/ 2);
2210 client_
->ScrollToY(new_y
);
2212 // Only move horizontally if it's not visible.
2213 if (center
.x() < visible_rect
.x() || center
.x() > visible_rect
.right()) {
2214 int new_x
= static_cast<int>(center
.x() * current_zoom_
) -
2215 static_cast<int>(visible_rect
.width() * current_zoom_
/ 2);
2218 client_
->ScrollToX(new_x
);
2222 client_
->NotifySelectedFindResultChanged(current_find_index_
.GetIndex());
2226 void PDFiumEngine::StopFind() {
2227 SelectionChangeInvalidator
selection_invalidator(this);
2231 find_results_
.clear();
2232 next_page_to_search_
= -1;
2233 last_page_to_search_
= -1;
2234 last_character_index_to_search_
= -1;
2235 current_find_index_
.Invalidate();
2236 current_find_text_
.clear();
2238 find_factory_
.CancelAll();
2241 void PDFiumEngine::GetAllScreenRectsUnion(std::vector
<PDFiumRange
>* rect_range
,
2242 const pp::Point
& offset_point
,
2243 std::vector
<pp::Rect
>* rect_vector
) {
2244 for (std::vector
<PDFiumRange
>::iterator it
= rect_range
->begin();
2245 it
!= rect_range
->end(); ++it
) {
2247 std::vector
<pp::Rect
> rects
=
2248 it
->GetScreenRects(offset_point
, current_zoom_
, current_rotation_
);
2249 for (size_t j
= 0; j
< rects
.size(); ++j
)
2250 rect
= rect
.Union(rects
[j
]);
2251 rect_vector
->push_back(rect
);
2255 void PDFiumEngine::UpdateTickMarks() {
2256 std::vector
<pp::Rect
> tickmarks
;
2257 GetAllScreenRectsUnion(&find_results_
, pp::Point(0, 0), &tickmarks
);
2258 client_
->UpdateTickMarks(tickmarks
);
2261 void PDFiumEngine::ZoomUpdated(double new_zoom_level
) {
2264 current_zoom_
= new_zoom_level
;
2266 CalculateVisiblePages();
2270 void PDFiumEngine::RotateClockwise() {
2271 current_rotation_
= (current_rotation_
+ 1) % 4;
2275 void PDFiumEngine::RotateCounterclockwise() {
2276 current_rotation_
= (current_rotation_
- 1) % 4;
2280 void PDFiumEngine::InvalidateAllPages() {
2284 client_
->Invalidate(pp::Rect(plugin_size_
));
2287 std::string
PDFiumEngine::GetSelectedText() {
2288 if (!HasPermission(PDFEngine::PERMISSION_COPY
))
2289 return std::string();
2291 base::string16 result
;
2292 base::string16 new_line_char
= base::UTF8ToUTF16("\n");
2293 for (size_t i
= 0; i
< selection_
.size(); ++i
) {
2295 selection_
[i
- 1].page_index() > selection_
[i
].page_index()) {
2296 result
= selection_
[i
].GetText() + new_line_char
+ result
;
2299 result
.append(new_line_char
);
2300 result
.append(selection_
[i
].GetText());
2304 FormatStringWithHyphens(&result
);
2305 FormatStringForOS(&result
);
2306 return base::UTF16ToUTF8(result
);
2309 std::string
PDFiumEngine::GetLinkAtPosition(const pp::Point
& point
) {
2312 int page_index
= -1;
2313 int form_type
= FPDF_FORMFIELD_UNKNOWN
;
2314 PDFiumPage::LinkTarget target
;
2315 PDFiumPage::Area area
=
2316 GetCharIndex(point
, &page_index
, &temp
, &form_type
, &target
);
2317 if (area
== PDFiumPage::WEBLINK_AREA
)
2322 bool PDFiumEngine::IsSelecting() {
2326 bool PDFiumEngine::HasPermission(DocumentPermission permission
) const {
2327 switch (permission
) {
2328 case PERMISSION_COPY
:
2329 return (permissions_
& kPDFPermissionCopyMask
) != 0;
2330 case PERMISSION_COPY_ACCESSIBLE
:
2331 return (permissions_
& kPDFPermissionCopyAccessibleMask
) != 0;
2332 case PERMISSION_PRINT_LOW_QUALITY
:
2333 return (permissions_
& kPDFPermissionPrintLowQualityMask
) != 0;
2334 case PERMISSION_PRINT_HIGH_QUALITY
:
2335 return (permissions_
& kPDFPermissionPrintLowQualityMask
) != 0 &&
2336 (permissions_
& kPDFPermissionPrintHighQualityMask
) != 0;
2342 void PDFiumEngine::SelectAll() {
2343 SelectionChangeInvalidator
selection_invalidator(this);
2346 for (size_t i
= 0; i
< pages_
.size(); ++i
)
2347 if (pages_
[i
]->available()) {
2348 selection_
.push_back(PDFiumRange(pages_
[i
], 0,
2349 pages_
[i
]->GetCharCount()));
2353 int PDFiumEngine::GetNumberOfPages() {
2354 return pages_
.size();
2357 pp::VarArray
PDFiumEngine::GetBookmarks() {
2358 pp::VarDictionary dict
= TraverseBookmarks(doc_
, NULL
);
2359 // The root bookmark contains no useful information.
2360 return pp::VarArray(dict
.Get(pp::Var("children")));
2363 int PDFiumEngine::GetNamedDestinationPage(const std::string
& destination
) {
2364 // Look for the destination.
2365 FPDF_DEST dest
= FPDF_GetNamedDestByName(doc_
, destination
.c_str());
2367 // Look for a bookmark with the same name.
2368 base::string16 destination_wide
= base::UTF8ToUTF16(destination
);
2369 FPDF_WIDESTRING destination_pdf_wide
=
2370 reinterpret_cast<FPDF_WIDESTRING
>(destination_wide
.c_str());
2371 FPDF_BOOKMARK bookmark
= FPDFBookmark_Find(doc_
, destination_pdf_wide
);
2374 dest
= FPDFBookmark_GetDest(doc_
, bookmark
);
2376 return dest
? FPDFDest_GetPageIndex(doc_
, dest
) : -1;
2379 int PDFiumEngine::GetFirstVisiblePage() {
2380 CalculateVisiblePages();
2381 return first_visible_page_
;
2384 int PDFiumEngine::GetMostVisiblePage() {
2385 CalculateVisiblePages();
2386 return most_visible_page_
;
2389 pp::Rect
PDFiumEngine::GetPageRect(int index
) {
2390 pp::Rect
rc(pages_
[index
]->rect());
2391 rc
.Inset(-kPageShadowLeft
, -kPageShadowTop
,
2392 -kPageShadowRight
, -kPageShadowBottom
);
2396 pp::Rect
PDFiumEngine::GetPageContentsRect(int index
) {
2397 return GetScreenRect(pages_
[index
]->rect());
2400 void PDFiumEngine::PaintThumbnail(pp::ImageData
* image_data
, int index
) {
2401 FPDF_BITMAP bitmap
= FPDFBitmap_CreateEx(
2402 image_data
->size().width(), image_data
->size().height(),
2403 FPDFBitmap_BGRx
, image_data
->data(), image_data
->stride());
2405 if (pages_
[index
]->available()) {
2406 FPDFBitmap_FillRect(bitmap
, 0, 0, image_data
->size().width(),
2407 image_data
->size().height(), 0xFFFFFFFF);
2409 FPDF_RenderPageBitmap(
2410 bitmap
, pages_
[index
]->GetPage(), 0, 0, image_data
->size().width(),
2411 image_data
->size().height(), 0, GetRenderingFlags());
2413 FPDFBitmap_FillRect(bitmap
, 0, 0, image_data
->size().width(),
2414 image_data
->size().height(), kPendingPageColor
);
2417 FPDFBitmap_Destroy(bitmap
);
2420 void PDFiumEngine::SetGrayscale(bool grayscale
) {
2421 render_grayscale_
= grayscale
;
2424 void PDFiumEngine::OnCallback(int id
) {
2425 if (!timers_
.count(id
))
2428 timers_
[id
].second(id
);
2429 if (timers_
.count(id
)) // The callback might delete the timer.
2430 client_
->ScheduleCallback(id
, timers_
[id
].first
);
2433 std::string
PDFiumEngine::GetPageAsJSON(int index
) {
2434 if (!(HasPermission(PERMISSION_COPY
) ||
2435 HasPermission(PERMISSION_COPY_ACCESSIBLE
))) {
2439 if (index
< 0 || static_cast<size_t>(index
) > pages_
.size() - 1)
2442 scoped_ptr
<base::Value
> node(
2443 pages_
[index
]->GetAccessibleContentAsValue(current_rotation_
));
2444 std::string page_json
;
2445 base::JSONWriter::Write(*node
, &page_json
);
2449 bool PDFiumEngine::GetPrintScaling() {
2450 return !!FPDF_VIEWERREF_GetPrintScaling(doc_
);
2453 int PDFiumEngine::GetCopiesToPrint() {
2454 return FPDF_VIEWERREF_GetNumCopies(doc_
);
2457 int PDFiumEngine::GetDuplexType() {
2458 return static_cast<int>(FPDF_VIEWERREF_GetDuplex(doc_
));
2461 bool PDFiumEngine::GetPageSizeAndUniformity(pp::Size
* size
) {
2465 pp::Size page_size
= GetPageSize(0);
2466 for (size_t i
= 1; i
< pages_
.size(); ++i
) {
2467 if (page_size
!= GetPageSize(i
))
2471 // Convert |page_size| back to points.
2473 ConvertUnit(page_size
.width(), kPixelsPerInch
, kPointsPerInch
));
2475 ConvertUnit(page_size
.height(), kPixelsPerInch
, kPointsPerInch
));
2479 void PDFiumEngine::AppendBlankPages(int num_pages
) {
2480 DCHECK_NE(num_pages
, 0);
2486 pending_pages_
.clear();
2488 // Delete all pages except the first one.
2489 while (pages_
.size() > 1) {
2490 delete pages_
.back();
2492 FPDFPage_Delete(doc_
, pages_
.size());
2495 // Calculate document size and all page sizes.
2496 std::vector
<pp::Rect
> page_rects
;
2497 pp::Size page_size
= GetPageSize(0);
2498 page_size
.Enlarge(kPageShadowLeft
+ kPageShadowRight
,
2499 kPageShadowTop
+ kPageShadowBottom
);
2500 pp::Size old_document_size
= document_size_
;
2501 document_size_
= pp::Size(page_size
.width(), 0);
2502 for (int i
= 0; i
< num_pages
; ++i
) {
2504 // Add space for horizontal separator.
2505 document_size_
.Enlarge(0, kPageSeparatorThickness
);
2508 pp::Rect
rect(pp::Point(0, document_size_
.height()), page_size
);
2509 page_rects
.push_back(rect
);
2511 document_size_
.Enlarge(0, page_size
.height());
2514 // Create blank pages.
2515 for (int i
= 1; i
< num_pages
; ++i
) {
2516 pp::Rect
page_rect(page_rects
[i
]);
2517 page_rect
.Inset(kPageShadowLeft
, kPageShadowTop
,
2518 kPageShadowRight
, kPageShadowBottom
);
2519 double width_in_points
= ConvertUnitDouble(page_rect
.width(),
2522 double height_in_points
= ConvertUnitDouble(page_rect
.height(),
2525 FPDFPage_New(doc_
, i
, width_in_points
, height_in_points
);
2526 pages_
.push_back(new PDFiumPage(this, i
, page_rect
, true));
2529 CalculateVisiblePages();
2530 if (document_size_
!= old_document_size
)
2531 client_
->DocumentSizeUpdated(document_size_
);
2534 void PDFiumEngine::LoadDocument() {
2535 // Check if the document is ready for loading. If it isn't just bail for now,
2536 // we will call LoadDocument() again later.
2537 if (!doc_
&& !doc_loader_
.IsDocumentComplete() &&
2538 !FPDFAvail_IsDocAvail(fpdf_availability_
, &download_hints_
)) {
2542 // If we're in the middle of getting a password, just return. We will retry
2543 // loading the document after we get the password anyway.
2544 if (getting_password_
)
2547 ScopedUnsupportedFeature
scoped_unsupported_feature(this);
2548 bool needs_password
= false;
2549 if (TryLoadingDoc(false, std::string(), &needs_password
)) {
2550 ContinueLoadingDocument(false, std::string());
2554 GetPasswordAndLoad();
2556 client_
->DocumentLoadFailed();
2559 bool PDFiumEngine::TryLoadingDoc(bool with_password
,
2560 const std::string
& password
,
2561 bool* needs_password
) {
2562 *needs_password
= false;
2566 const char* password_cstr
= NULL
;
2567 if (with_password
) {
2568 password_cstr
= password
.c_str();
2569 password_tries_remaining_
--;
2571 if (doc_loader_
.IsDocumentComplete())
2572 doc_
= FPDF_LoadCustomDocument(&file_access_
, password_cstr
);
2574 doc_
= FPDFAvail_GetDocument(fpdf_availability_
, password_cstr
);
2576 if (!doc_
&& FPDF_GetLastError() == FPDF_ERR_PASSWORD
)
2577 *needs_password
= true;
2579 return doc_
!= NULL
;
2582 void PDFiumEngine::GetPasswordAndLoad() {
2583 getting_password_
= true;
2584 DCHECK(!doc_
&& FPDF_GetLastError() == FPDF_ERR_PASSWORD
);
2585 client_
->GetDocumentPassword(password_factory_
.NewCallbackWithOutput(
2586 &PDFiumEngine::OnGetPasswordComplete
));
2589 void PDFiumEngine::OnGetPasswordComplete(int32_t result
,
2590 const pp::Var
& password
) {
2591 getting_password_
= false;
2593 bool password_given
= false;
2594 std::string password_text
;
2595 if (result
== PP_OK
&& password
.is_string()) {
2596 password_text
= password
.AsString();
2597 if (!password_text
.empty())
2598 password_given
= true;
2600 ContinueLoadingDocument(password_given
, password_text
);
2603 void PDFiumEngine::ContinueLoadingDocument(
2605 const std::string
& password
) {
2606 ScopedUnsupportedFeature
scoped_unsupported_feature(this);
2608 bool needs_password
= false;
2609 bool loaded
= TryLoadingDoc(has_password
, password
, &needs_password
);
2610 bool password_incorrect
= !loaded
&& has_password
&& needs_password
;
2611 if (password_incorrect
&& password_tries_remaining_
> 0) {
2612 GetPasswordAndLoad();
2617 client_
->DocumentLoadFailed();
2621 if (FPDFDoc_GetPageMode(doc_
) == PAGEMODE_USEOUTLINES
)
2622 client_
->DocumentHasUnsupportedFeature("Bookmarks");
2624 permissions_
= FPDF_GetDocPermissions(doc_
);
2627 // Only returns 0 when data isn't available. If form data is downloaded, or
2628 // if this isn't a form, returns positive values.
2629 if (!doc_loader_
.IsDocumentComplete() &&
2630 !FPDFAvail_IsFormAvail(fpdf_availability_
, &download_hints_
)) {
2634 form_
= FPDFDOC_InitFormFillEnvironment(
2635 doc_
, static_cast<FPDF_FORMFILLINFO
*>(this));
2640 FPDF_SetFormFieldHighlightColor(form_
, 0, kFormHighlightColor
);
2641 FPDF_SetFormFieldHighlightAlpha(form_
, kFormHighlightAlpha
);
2644 if (!doc_loader_
.IsDocumentComplete()) {
2645 // Check if the first page is available. In a linearized PDF, that is not
2646 // always page 0. Doing this gives us the default page size, since when the
2647 // document is available, the first page is available as well.
2648 CheckPageAvailable(FPDFAvail_GetFirstPageNum(doc_
), &pending_pages_
);
2651 LoadPageInfo(false);
2653 if (doc_loader_
.IsDocumentComplete())
2654 FinishLoadingDocument();
2657 void PDFiumEngine::LoadPageInfo(bool reload
) {
2658 pending_pages_
.clear();
2659 pp::Size old_document_size
= document_size_
;
2660 document_size_
= pp::Size();
2661 std::vector
<pp::Rect
> page_rects
;
2662 int page_count
= FPDF_GetPageCount(doc_
);
2663 bool doc_complete
= doc_loader_
.IsDocumentComplete();
2664 for (int i
= 0; i
< page_count
; ++i
) {
2666 // Add space for horizontal separator.
2667 document_size_
.Enlarge(0, kPageSeparatorThickness
);
2670 // Get page availability. If reload==false, and document is not loaded yet
2671 // (we are using async loading) - mark all pages as unavailable.
2672 // If reload==true (we have document constructed already), get page
2673 // availability flag from already existing PDFiumPage class.
2674 bool page_available
= reload
? pages_
[i
]->available() : doc_complete
;
2676 pp::Size size
= page_available
? GetPageSize(i
) : default_page_size_
;
2677 size
.Enlarge(kPageShadowLeft
+ kPageShadowRight
,
2678 kPageShadowTop
+ kPageShadowBottom
);
2679 pp::Rect
rect(pp::Point(0, document_size_
.height()), size
);
2680 page_rects
.push_back(rect
);
2682 if (size
.width() > document_size_
.width())
2683 document_size_
.set_width(size
.width());
2685 document_size_
.Enlarge(0, size
.height());
2688 for (int i
= 0; i
< page_count
; ++i
) {
2689 // Center pages relative to the entire document.
2690 page_rects
[i
].set_x((document_size_
.width() - page_rects
[i
].width()) / 2);
2691 pp::Rect
page_rect(page_rects
[i
]);
2692 page_rect
.Inset(kPageShadowLeft
, kPageShadowTop
,
2693 kPageShadowRight
, kPageShadowBottom
);
2695 pages_
[i
]->set_rect(page_rect
);
2697 pages_
.push_back(new PDFiumPage(this, i
, page_rect
, doc_complete
));
2701 CalculateVisiblePages();
2702 if (document_size_
!= old_document_size
)
2703 client_
->DocumentSizeUpdated(document_size_
);
2706 void PDFiumEngine::CalculateVisiblePages() {
2707 // Clear pending requests queue, since it may contain requests to the pages
2708 // that are already invisible (after scrolling for example).
2709 pending_pages_
.clear();
2710 doc_loader_
.ClearPendingRequests();
2712 visible_pages_
.clear();
2713 pp::Rect
visible_rect(plugin_size_
);
2714 for (size_t i
= 0; i
< pages_
.size(); ++i
) {
2715 // Check an entire PageScreenRect, since we might need to repaint side
2716 // borders and shadows even if the page itself is not visible.
2717 // For example, when user use pdf with different page sizes and zoomed in
2718 // outside page area.
2719 if (visible_rect
.Intersects(GetPageScreenRect(i
))) {
2720 visible_pages_
.push_back(i
);
2721 CheckPageAvailable(i
, &pending_pages_
);
2723 // Need to unload pages when we're not using them, since some PDFs use a
2724 // lot of memory. See http://crbug.com/48791
2725 if (defer_page_unload_
) {
2726 deferred_page_unloads_
.push_back(i
);
2728 pages_
[i
]->Unload();
2731 // If the last mouse down was on a page that's no longer visible, reset
2732 // that variable so that we don't send keyboard events to it (the focus
2733 // will be lost when the page is first closed anyways).
2734 if (static_cast<int>(i
) == last_page_mouse_down_
)
2735 last_page_mouse_down_
= -1;
2739 // Any pending highlighting of form fields will be invalid since these are in
2740 // screen coordinates.
2741 form_highlights_
.clear();
2743 if (visible_pages_
.size() == 0)
2744 first_visible_page_
= -1;
2746 first_visible_page_
= visible_pages_
.front();
2748 int most_visible_page
= first_visible_page_
;
2749 // Check if the next page is more visible than the first one.
2750 if (most_visible_page
!= -1 &&
2751 pages_
.size() > 0 &&
2752 most_visible_page
< static_cast<int>(pages_
.size()) - 1) {
2754 visible_rect
.Intersect(GetPageScreenRect(most_visible_page
));
2756 visible_rect
.Intersect(GetPageScreenRect(most_visible_page
+ 1));
2757 if (rc_next
.height() > rc_first
.height())
2758 most_visible_page
++;
2761 SetCurrentPage(most_visible_page
);
2764 bool PDFiumEngine::IsPageVisible(int index
) const {
2765 for (size_t i
= 0; i
< visible_pages_
.size(); ++i
) {
2766 if (visible_pages_
[i
] == index
)
2773 bool PDFiumEngine::CheckPageAvailable(int index
, std::vector
<int>* pending
) {
2774 if (!doc_
|| !form_
)
2777 if (static_cast<int>(pages_
.size()) > index
&& pages_
[index
]->available())
2780 if (!FPDFAvail_IsPageAvail(fpdf_availability_
, index
, &download_hints_
)) {
2782 for (j
= 0; j
< pending
->size(); ++j
) {
2783 if ((*pending
)[j
] == index
)
2787 if (j
== pending
->size())
2788 pending
->push_back(index
);
2792 if (static_cast<int>(pages_
.size()) > index
)
2793 pages_
[index
]->set_available(true);
2794 if (!default_page_size_
.GetArea())
2795 default_page_size_
= GetPageSize(index
);
2799 pp::Size
PDFiumEngine::GetPageSize(int index
) {
2801 double width_in_points
= 0;
2802 double height_in_points
= 0;
2803 int rv
= FPDF_GetPageSizeByIndex(
2804 doc_
, index
, &width_in_points
, &height_in_points
);
2807 int width_in_pixels
= static_cast<int>(
2808 ConvertUnitDouble(width_in_points
, kPointsPerInch
, kPixelsPerInch
));
2809 int height_in_pixels
= static_cast<int>(
2810 ConvertUnitDouble(height_in_points
, kPointsPerInch
, kPixelsPerInch
));
2811 if (current_rotation_
% 2 == 1)
2812 std::swap(width_in_pixels
, height_in_pixels
);
2813 size
= pp::Size(width_in_pixels
, height_in_pixels
);
2818 int PDFiumEngine::StartPaint(int page_index
, const pp::Rect
& dirty
) {
2819 // For the first time we hit paint, do nothing and just record the paint for
2820 // the next callback. This keeps the UI responsive in case the user is doing
2821 // a lot of scrolling.
2822 ProgressivePaint progressive
;
2823 progressive
.rect
= dirty
;
2824 progressive
.page_index
= page_index
;
2825 progressive
.bitmap
= NULL
;
2826 progressive
.painted_
= false;
2827 progressive_paints_
.push_back(progressive
);
2828 return progressive_paints_
.size() - 1;
2831 bool PDFiumEngine::ContinuePaint(int progressive_index
,
2832 pp::ImageData
* image_data
) {
2833 DCHECK_GE(progressive_index
, 0);
2834 DCHECK_LT(static_cast<size_t>(progressive_index
), progressive_paints_
.size());
2837 #if defined(OS_LINUX)
2838 g_last_instance_id
= client_
->GetPluginInstance()->pp_instance();
2842 FPDF_BITMAP bitmap
= progressive_paints_
[progressive_index
].bitmap
;
2843 int page_index
= progressive_paints_
[progressive_index
].page_index
;
2844 DCHECK_GE(page_index
, 0);
2845 DCHECK_LT(static_cast<size_t>(page_index
), pages_
.size());
2846 FPDF_PAGE page
= pages_
[page_index
]->GetPage();
2848 last_progressive_start_time_
= base::Time::Now();
2850 rv
= FPDF_RenderPage_Continue(page
, static_cast<IFSDK_PAUSE
*>(this));
2852 pp::Rect dirty
= progressive_paints_
[progressive_index
].rect
;
2853 bitmap
= CreateBitmap(dirty
, image_data
);
2854 int start_x
, start_y
, size_x
, size_y
;
2855 GetPDFiumRect(page_index
, dirty
, &start_x
, &start_y
, &size_x
, &size_y
);
2856 FPDFBitmap_FillRect(bitmap
, start_x
, start_y
, size_x
, size_y
, 0xFFFFFFFF);
2857 rv
= FPDF_RenderPageBitmap_Start(
2858 bitmap
, page
, start_x
, start_y
, size_x
, size_y
,
2860 GetRenderingFlags(), static_cast<IFSDK_PAUSE
*>(this));
2861 progressive_paints_
[progressive_index
].bitmap
= bitmap
;
2863 return rv
!= FPDF_RENDER_TOBECOUNTINUED
;
2866 void PDFiumEngine::FinishPaint(int progressive_index
,
2867 pp::ImageData
* image_data
) {
2868 DCHECK_GE(progressive_index
, 0);
2869 DCHECK_LT(static_cast<size_t>(progressive_index
), progressive_paints_
.size());
2872 int page_index
= progressive_paints_
[progressive_index
].page_index
;
2873 pp::Rect dirty_in_screen
= progressive_paints_
[progressive_index
].rect
;
2874 FPDF_BITMAP bitmap
= progressive_paints_
[progressive_index
].bitmap
;
2875 int start_x
, start_y
, size_x
, size_y
;
2877 page_index
, dirty_in_screen
, &start_x
, &start_y
, &size_x
, &size_y
);
2881 form_
, bitmap
, pages_
[page_index
]->GetPage(), start_x
, start_y
, size_x
,
2882 size_y
, current_rotation_
, GetRenderingFlags());
2884 FillPageSides(progressive_index
);
2886 // Paint the page shadows.
2887 PaintPageShadow(progressive_index
, image_data
);
2889 DrawSelections(progressive_index
, image_data
);
2891 FPDF_RenderPage_Close(pages_
[page_index
]->GetPage());
2892 FPDFBitmap_Destroy(bitmap
);
2893 progressive_paints_
.erase(progressive_paints_
.begin() + progressive_index
);
2895 client_
->DocumentPaintOccurred();
2898 void PDFiumEngine::CancelPaints() {
2899 for (size_t i
= 0; i
< progressive_paints_
.size(); ++i
) {
2900 FPDF_RenderPage_Close(pages_
[progressive_paints_
[i
].page_index
]->GetPage());
2901 FPDFBitmap_Destroy(progressive_paints_
[i
].bitmap
);
2903 progressive_paints_
.clear();
2906 void PDFiumEngine::FillPageSides(int progressive_index
) {
2907 DCHECK_GE(progressive_index
, 0);
2908 DCHECK_LT(static_cast<size_t>(progressive_index
), progressive_paints_
.size());
2910 int page_index
= progressive_paints_
[progressive_index
].page_index
;
2911 pp::Rect dirty_in_screen
= progressive_paints_
[progressive_index
].rect
;
2912 FPDF_BITMAP bitmap
= progressive_paints_
[progressive_index
].bitmap
;
2914 pp::Rect page_rect
= pages_
[page_index
]->rect();
2915 if (page_rect
.x() > 0) {
2917 page_rect
.y() - kPageShadowTop
,
2918 page_rect
.x() - kPageShadowLeft
,
2919 page_rect
.height() + kPageShadowTop
+
2920 kPageShadowBottom
+ kPageSeparatorThickness
);
2921 left
= GetScreenRect(left
).Intersect(dirty_in_screen
);
2923 FPDFBitmap_FillRect(bitmap
, left
.x() - dirty_in_screen
.x(),
2924 left
.y() - dirty_in_screen
.y(), left
.width(),
2925 left
.height(), client_
->GetBackgroundColor());
2928 if (page_rect
.right() < document_size_
.width()) {
2929 pp::Rect
right(page_rect
.right() + kPageShadowRight
,
2930 page_rect
.y() - kPageShadowTop
,
2931 document_size_
.width() - page_rect
.right() -
2933 page_rect
.height() + kPageShadowTop
+
2934 kPageShadowBottom
+ kPageSeparatorThickness
);
2935 right
= GetScreenRect(right
).Intersect(dirty_in_screen
);
2937 FPDFBitmap_FillRect(bitmap
, right
.x() - dirty_in_screen
.x(),
2938 right
.y() - dirty_in_screen
.y(), right
.width(),
2939 right
.height(), client_
->GetBackgroundColor());
2943 pp::Rect
bottom(page_rect
.x() - kPageShadowLeft
,
2944 page_rect
.bottom() + kPageShadowBottom
,
2945 page_rect
.width() + kPageShadowLeft
+ kPageShadowRight
,
2946 kPageSeparatorThickness
);
2947 bottom
= GetScreenRect(bottom
).Intersect(dirty_in_screen
);
2949 FPDFBitmap_FillRect(bitmap
, bottom
.x() - dirty_in_screen
.x(),
2950 bottom
.y() - dirty_in_screen
.y(), bottom
.width(),
2951 bottom
.height(), client_
->GetBackgroundColor());
2954 void PDFiumEngine::PaintPageShadow(int progressive_index
,
2955 pp::ImageData
* image_data
) {
2956 DCHECK_GE(progressive_index
, 0);
2957 DCHECK_LT(static_cast<size_t>(progressive_index
), progressive_paints_
.size());
2960 int page_index
= progressive_paints_
[progressive_index
].page_index
;
2961 pp::Rect dirty_in_screen
= progressive_paints_
[progressive_index
].rect
;
2962 pp::Rect page_rect
= pages_
[page_index
]->rect();
2963 pp::Rect
shadow_rect(page_rect
);
2964 shadow_rect
.Inset(-kPageShadowLeft
, -kPageShadowTop
,
2965 -kPageShadowRight
, -kPageShadowBottom
);
2967 // Due to the rounding errors of the GetScreenRect it is possible to get
2968 // different size shadows on the left and right sides even they are defined
2969 // the same. To fix this issue let's calculate shadow rect and then shrink
2970 // it by the size of the shadows.
2971 shadow_rect
= GetScreenRect(shadow_rect
);
2972 page_rect
= shadow_rect
;
2974 page_rect
.Inset(static_cast<int>(ceil(kPageShadowLeft
* current_zoom_
)),
2975 static_cast<int>(ceil(kPageShadowTop
* current_zoom_
)),
2976 static_cast<int>(ceil(kPageShadowRight
* current_zoom_
)),
2977 static_cast<int>(ceil(kPageShadowBottom
* current_zoom_
)));
2979 DrawPageShadow(page_rect
, shadow_rect
, dirty_in_screen
, image_data
);
2982 void PDFiumEngine::DrawSelections(int progressive_index
,
2983 pp::ImageData
* image_data
) {
2984 DCHECK_GE(progressive_index
, 0);
2985 DCHECK_LT(static_cast<size_t>(progressive_index
), progressive_paints_
.size());
2988 int page_index
= progressive_paints_
[progressive_index
].page_index
;
2989 pp::Rect dirty_in_screen
= progressive_paints_
[progressive_index
].rect
;
2991 void* region
= NULL
;
2993 GetRegion(dirty_in_screen
.point(), image_data
, ®ion
, &stride
);
2995 std::vector
<pp::Rect
> highlighted_rects
;
2996 pp::Rect visible_rect
= GetVisibleRect();
2997 for (size_t k
= 0; k
< selection_
.size(); ++k
) {
2998 if (selection_
[k
].page_index() != page_index
)
3000 std::vector
<pp::Rect
> rects
= selection_
[k
].GetScreenRects(
3001 visible_rect
.point(), current_zoom_
, current_rotation_
);
3002 for (size_t j
= 0; j
< rects
.size(); ++j
) {
3003 pp::Rect visible_selection
= rects
[j
].Intersect(dirty_in_screen
);
3004 if (visible_selection
.IsEmpty())
3007 visible_selection
.Offset(
3008 -dirty_in_screen
.point().x(), -dirty_in_screen
.point().y());
3009 Highlight(region
, stride
, visible_selection
, &highlighted_rects
);
3013 for (size_t k
= 0; k
< form_highlights_
.size(); ++k
) {
3014 pp::Rect visible_selection
= form_highlights_
[k
].Intersect(dirty_in_screen
);
3015 if (visible_selection
.IsEmpty())
3018 visible_selection
.Offset(
3019 -dirty_in_screen
.point().x(), -dirty_in_screen
.point().y());
3020 Highlight(region
, stride
, visible_selection
, &highlighted_rects
);
3022 form_highlights_
.clear();
3025 void PDFiumEngine::PaintUnavailablePage(int page_index
,
3026 const pp::Rect
& dirty
,
3027 pp::ImageData
* image_data
) {
3028 int start_x
, start_y
, size_x
, size_y
;
3029 GetPDFiumRect(page_index
, dirty
, &start_x
, &start_y
, &size_x
, &size_y
);
3030 FPDF_BITMAP bitmap
= CreateBitmap(dirty
, image_data
);
3031 FPDFBitmap_FillRect(bitmap
, start_x
, start_y
, size_x
, size_y
,
3034 pp::Rect
loading_text_in_screen(
3035 pages_
[page_index
]->rect().width() / 2,
3036 pages_
[page_index
]->rect().y() + kLoadingTextVerticalOffset
, 0, 0);
3037 loading_text_in_screen
= GetScreenRect(loading_text_in_screen
);
3038 FPDFBitmap_Destroy(bitmap
);
3041 int PDFiumEngine::GetProgressiveIndex(int page_index
) const {
3042 for (size_t i
= 0; i
< progressive_paints_
.size(); ++i
) {
3043 if (progressive_paints_
[i
].page_index
== page_index
)
3049 FPDF_BITMAP
PDFiumEngine::CreateBitmap(const pp::Rect
& rect
,
3050 pp::ImageData
* image_data
) const {
3053 GetRegion(rect
.point(), image_data
, ®ion
, &stride
);
3056 return FPDFBitmap_CreateEx(
3057 rect
.width(), rect
.height(), FPDFBitmap_BGRx
, region
, stride
);
3060 void PDFiumEngine::GetPDFiumRect(
3061 int page_index
, const pp::Rect
& rect
, int* start_x
, int* start_y
,
3062 int* size_x
, int* size_y
) const {
3063 pp::Rect page_rect
= GetScreenRect(pages_
[page_index
]->rect());
3064 page_rect
.Offset(-rect
.x(), -rect
.y());
3066 *start_x
= page_rect
.x();
3067 *start_y
= page_rect
.y();
3068 *size_x
= page_rect
.width();
3069 *size_y
= page_rect
.height();
3072 int PDFiumEngine::GetRenderingFlags() const {
3073 int flags
= FPDF_LCD_TEXT
| FPDF_NO_CATCH
;
3074 if (render_grayscale_
)
3075 flags
|= FPDF_GRAYSCALE
;
3076 if (client_
->IsPrintPreview())
3077 flags
|= FPDF_PRINTING
;
3081 pp::Rect
PDFiumEngine::GetVisibleRect() const {
3083 rv
.set_x(static_cast<int>(position_
.x() / current_zoom_
));
3084 rv
.set_y(static_cast<int>(position_
.y() / current_zoom_
));
3085 rv
.set_width(static_cast<int>(ceil(plugin_size_
.width() / current_zoom_
)));
3086 rv
.set_height(static_cast<int>(ceil(plugin_size_
.height() / current_zoom_
)));
3090 pp::Rect
PDFiumEngine::GetPageScreenRect(int page_index
) const {
3091 // Since we use this rect for creating the PDFium bitmap, also include other
3092 // areas around the page that we might need to update such as the page
3093 // separator and the sides if the page is narrower than the document.
3094 return GetScreenRect(pp::Rect(
3096 pages_
[page_index
]->rect().y() - kPageShadowTop
,
3097 document_size_
.width(),
3098 pages_
[page_index
]->rect().height() + kPageShadowTop
+
3099 kPageShadowBottom
+ kPageSeparatorThickness
));
3102 pp::Rect
PDFiumEngine::GetScreenRect(const pp::Rect
& rect
) const {
3105 static_cast<int>(ceil(rect
.right() * current_zoom_
- position_
.x()));
3107 static_cast<int>(ceil(rect
.bottom() * current_zoom_
- position_
.y()));
3109 rv
.set_x(static_cast<int>(rect
.x() * current_zoom_
- position_
.x()));
3110 rv
.set_y(static_cast<int>(rect
.y() * current_zoom_
- position_
.y()));
3111 rv
.set_width(right
- rv
.x());
3112 rv
.set_height(bottom
- rv
.y());
3116 void PDFiumEngine::Highlight(void* buffer
,
3118 const pp::Rect
& rect
,
3119 std::vector
<pp::Rect
>* highlighted_rects
) {
3123 pp::Rect new_rect
= rect
;
3124 for (size_t i
= 0; i
< highlighted_rects
->size(); ++i
)
3125 new_rect
= new_rect
.Subtract((*highlighted_rects
)[i
]);
3127 highlighted_rects
->push_back(new_rect
);
3128 int l
= new_rect
.x();
3129 int t
= new_rect
.y();
3130 int w
= new_rect
.width();
3131 int h
= new_rect
.height();
3133 for (int y
= t
; y
< t
+ h
; ++y
) {
3134 for (int x
= l
; x
< l
+ w
; ++x
) {
3135 uint8
* pixel
= static_cast<uint8
*>(buffer
) + y
* stride
+ x
* 4;
3136 // This is our highlight color.
3137 pixel
[0] = static_cast<uint8
>(
3138 pixel
[0] * (kHighlightColorB
/ 255.0));
3139 pixel
[1] = static_cast<uint8
>(
3140 pixel
[1] * (kHighlightColorG
/ 255.0));
3141 pixel
[2] = static_cast<uint8
>(
3142 pixel
[2] * (kHighlightColorR
/ 255.0));
3147 PDFiumEngine::SelectionChangeInvalidator::SelectionChangeInvalidator(
3148 PDFiumEngine
* engine
) : engine_(engine
) {
3149 previous_origin_
= engine_
->GetVisibleRect().point();
3150 GetVisibleSelectionsScreenRects(&old_selections_
);
3153 PDFiumEngine::SelectionChangeInvalidator::~SelectionChangeInvalidator() {
3154 // Offset the old selections if the document scrolled since we recorded them.
3155 pp::Point offset
= previous_origin_
- engine_
->GetVisibleRect().point();
3156 for (size_t i
= 0; i
< old_selections_
.size(); ++i
)
3157 old_selections_
[i
].Offset(offset
);
3159 std::vector
<pp::Rect
> new_selections
;
3160 GetVisibleSelectionsScreenRects(&new_selections
);
3161 for (size_t i
= 0; i
< new_selections
.size(); ++i
) {
3162 for (size_t j
= 0; j
< old_selections_
.size(); ++j
) {
3163 if (!old_selections_
[j
].IsEmpty() &&
3164 new_selections
[i
] == old_selections_
[j
]) {
3165 // Rectangle was selected before and after, so no need to invalidate it.
3166 // Mark the rectangles by setting them to empty.
3167 new_selections
[i
] = old_selections_
[j
] = pp::Rect();
3173 for (size_t i
= 0; i
< old_selections_
.size(); ++i
) {
3174 if (!old_selections_
[i
].IsEmpty())
3175 engine_
->client_
->Invalidate(old_selections_
[i
]);
3177 for (size_t i
= 0; i
< new_selections
.size(); ++i
) {
3178 if (!new_selections
[i
].IsEmpty())
3179 engine_
->client_
->Invalidate(new_selections
[i
]);
3181 engine_
->OnSelectionChanged();
3185 PDFiumEngine::SelectionChangeInvalidator::GetVisibleSelectionsScreenRects(
3186 std::vector
<pp::Rect
>* rects
) {
3187 pp::Rect visible_rect
= engine_
->GetVisibleRect();
3188 for (size_t i
= 0; i
< engine_
->selection_
.size(); ++i
) {
3189 int page_index
= engine_
->selection_
[i
].page_index();
3190 if (!engine_
->IsPageVisible(page_index
))
3191 continue; // This selection is on a page that's not currently visible.
3193 std::vector
<pp::Rect
> selection_rects
=
3194 engine_
->selection_
[i
].GetScreenRects(
3195 visible_rect
.point(),
3196 engine_
->current_zoom_
,
3197 engine_
->current_rotation_
);
3198 rects
->insert(rects
->end(), selection_rects
.begin(), selection_rects
.end());
3202 PDFiumEngine::MouseDownState::MouseDownState(
3203 const PDFiumPage::Area
& area
,
3204 const PDFiumPage::LinkTarget
& target
)
3205 : area_(area
), target_(target
) {
3208 PDFiumEngine::MouseDownState::~MouseDownState() {
3211 void PDFiumEngine::MouseDownState::Set(const PDFiumPage::Area
& area
,
3212 const PDFiumPage::LinkTarget
& target
) {
3217 void PDFiumEngine::MouseDownState::Reset() {
3218 area_
= PDFiumPage::NONSELECTABLE_AREA
;
3219 target_
= PDFiumPage::LinkTarget();
3222 bool PDFiumEngine::MouseDownState::Matches(
3223 const PDFiumPage::Area
& area
,
3224 const PDFiumPage::LinkTarget
& target
) const {
3225 if (area_
== area
) {
3226 if (area
== PDFiumPage::WEBLINK_AREA
)
3227 return target_
.url
== target
.url
;
3228 if (area
== PDFiumPage::DOCLINK_AREA
)
3229 return target_
.page
== target
.page
;
3235 PDFiumEngine::FindTextIndex::FindTextIndex()
3236 : valid_(false), index_(0) {
3239 PDFiumEngine::FindTextIndex::~FindTextIndex() {
3242 void PDFiumEngine::FindTextIndex::Invalidate() {
3246 size_t PDFiumEngine::FindTextIndex::GetIndex() const {
3251 void PDFiumEngine::FindTextIndex::SetIndex(size_t index
) {
3256 size_t PDFiumEngine::FindTextIndex::IncrementIndex() {
3261 void PDFiumEngine::DeviceToPage(int page_index
,
3266 *page_x
= *page_y
= 0;
3267 int temp_x
= static_cast<int>((device_x
+ position_
.x())/ current_zoom_
-
3268 pages_
[page_index
]->rect().x());
3269 int temp_y
= static_cast<int>((device_y
+ position_
.y())/ current_zoom_
-
3270 pages_
[page_index
]->rect().y());
3272 pages_
[page_index
]->GetPage(), 0, 0,
3273 pages_
[page_index
]->rect().width(), pages_
[page_index
]->rect().height(),
3274 current_rotation_
, temp_x
, temp_y
, page_x
, page_y
);
3277 int PDFiumEngine::GetVisiblePageIndex(FPDF_PAGE page
) {
3278 for (size_t i
= 0; i
< visible_pages_
.size(); ++i
) {
3279 if (pages_
[visible_pages_
[i
]]->GetPage() == page
)
3280 return visible_pages_
[i
];
3285 void PDFiumEngine::SetCurrentPage(int index
) {
3286 if (index
== most_visible_page_
|| !form_
)
3288 if (most_visible_page_
!= -1 && called_do_document_action_
) {
3289 FPDF_PAGE old_page
= pages_
[most_visible_page_
]->GetPage();
3290 FORM_DoPageAAction(old_page
, form_
, FPDFPAGE_AACTION_CLOSE
);
3292 most_visible_page_
= index
;
3293 #if defined(OS_LINUX)
3294 g_last_instance_id
= client_
->GetPluginInstance()->pp_instance();
3296 if (most_visible_page_
!= -1 && called_do_document_action_
) {
3297 FPDF_PAGE new_page
= pages_
[most_visible_page_
]->GetPage();
3298 FORM_DoPageAAction(new_page
, form_
, FPDFPAGE_AACTION_OPEN
);
3302 void PDFiumEngine::TransformPDFPageForPrinting(
3304 const PP_PrintSettings_Dev
& print_settings
) {
3305 // Get the source page width and height in points.
3306 const double src_page_width
= FPDF_GetPageWidth(page
);
3307 const double src_page_height
= FPDF_GetPageHeight(page
);
3309 const int src_page_rotation
= FPDFPage_GetRotation(page
);
3310 const bool fit_to_page
= print_settings
.print_scaling_option
==
3311 PP_PRINTSCALINGOPTION_FIT_TO_PRINTABLE_AREA
;
3313 pp::Size
page_size(print_settings
.paper_size
);
3314 pp::Rect
content_rect(print_settings
.printable_area
);
3315 const bool rotated
= (src_page_rotation
% 2 == 1);
3316 SetPageSizeAndContentRect(rotated
,
3317 src_page_width
> src_page_height
,
3321 // Compute the screen page width and height in points.
3322 const int actual_page_width
=
3323 rotated
? page_size
.height() : page_size
.width();
3324 const int actual_page_height
=
3325 rotated
? page_size
.width() : page_size
.height();
3327 const double scale_factor
= CalculateScaleFactor(fit_to_page
, content_rect
,
3329 src_page_height
, rotated
);
3331 // Calculate positions for the clip box.
3332 ClipBox source_clip_box
;
3333 CalculateClipBoxBoundary(page
, scale_factor
, rotated
, &source_clip_box
);
3335 // Calculate the translation offset values.
3336 double offset_x
= 0;
3337 double offset_y
= 0;
3339 CalculateScaledClipBoxOffset(content_rect
, source_clip_box
, &offset_x
,
3342 CalculateNonScaledClipBoxOffset(content_rect
, src_page_rotation
,
3343 actual_page_width
, actual_page_height
,
3344 source_clip_box
, &offset_x
, &offset_y
);
3347 // Reset the media box and crop box. When the page has crop box and media box,
3348 // the plugin will display the crop box contents and not the entire media box.
3349 // If the pages have different crop box values, the plugin will display a
3350 // document of multiple page sizes. To give better user experience, we
3351 // decided to have same crop box and media box values. Hence, the user will
3352 // see a list of uniform pages.
3353 FPDFPage_SetMediaBox(page
, 0, 0, page_size
.width(), page_size
.height());
3354 FPDFPage_SetCropBox(page
, 0, 0, page_size
.width(), page_size
.height());
3356 // Transformation is not required, return. Do this check only after updating
3357 // the media box and crop box. For more detailed information, please refer to
3358 // the comment block right before FPDF_SetMediaBox and FPDF_GetMediaBox calls.
3359 if (scale_factor
== 1.0 && offset_x
== 0 && offset_y
== 0)
3363 // All the positions have been calculated, now manipulate the PDF.
3364 FS_MATRIX matrix
= {static_cast<float>(scale_factor
),
3367 static_cast<float>(scale_factor
),
3368 static_cast<float>(offset_x
),
3369 static_cast<float>(offset_y
)};
3370 FS_RECTF cliprect
= {static_cast<float>(source_clip_box
.left
+offset_x
),
3371 static_cast<float>(source_clip_box
.top
+offset_y
),
3372 static_cast<float>(source_clip_box
.right
+offset_x
),
3373 static_cast<float>(source_clip_box
.bottom
+offset_y
)};
3374 FPDFPage_TransFormWithClip(page
, &matrix
, &cliprect
);
3375 FPDFPage_TransformAnnots(page
, scale_factor
, 0, 0, scale_factor
,
3376 offset_x
, offset_y
);
3379 void PDFiumEngine::DrawPageShadow(const pp::Rect
& page_rc
,
3380 const pp::Rect
& shadow_rc
,
3381 const pp::Rect
& clip_rc
,
3382 pp::ImageData
* image_data
) {
3383 pp::Rect
page_rect(page_rc
);
3384 page_rect
.Offset(page_offset_
);
3386 pp::Rect
shadow_rect(shadow_rc
);
3387 shadow_rect
.Offset(page_offset_
);
3389 pp::Rect
clip_rect(clip_rc
);
3390 clip_rect
.Offset(page_offset_
);
3392 // Page drop shadow parameters.
3393 const double factor
= 0.5;
3394 uint32 depth
= std::max(
3395 std::max(page_rect
.x() - shadow_rect
.x(),
3396 page_rect
.y() - shadow_rect
.y()),
3397 std::max(shadow_rect
.right() - page_rect
.right(),
3398 shadow_rect
.bottom() - page_rect
.bottom()));
3399 depth
= static_cast<uint32
>(depth
* 1.5) + 1;
3401 // We need to check depth only to verify our copy of shadow matrix is correct.
3402 if (!page_shadow_
.get() || page_shadow_
->depth() != depth
)
3403 page_shadow_
.reset(new ShadowMatrix(depth
, factor
,
3404 client_
->GetBackgroundColor()));
3406 DCHECK(!image_data
->is_null());
3407 DrawShadow(image_data
, shadow_rect
, page_rect
, clip_rect
, *page_shadow_
);
3410 void PDFiumEngine::GetRegion(const pp::Point
& location
,
3411 pp::ImageData
* image_data
,
3413 int* stride
) const {
3414 if (image_data
->is_null()) {
3415 DCHECK(plugin_size_
.IsEmpty());
3420 char* buffer
= static_cast<char*>(image_data
->data());
3421 *stride
= image_data
->stride();
3423 pp::Point offset_location
= location
+ page_offset_
;
3424 // TODO: update this when we support BIDI and scrollbars can be on the left.
3426 !pp::Rect(page_offset_
, plugin_size_
).Contains(offset_location
)) {
3431 buffer
+= location
.y() * (*stride
);
3432 buffer
+= (location
.x() + page_offset_
.x()) * 4;
3436 void PDFiumEngine::OnSelectionChanged() {
3437 pp::PDF::SetSelectedText(GetPluginInstance(), GetSelectedText().c_str());
3440 void PDFiumEngine::RotateInternal() {
3441 // Store the current find index so that we can resume finding at that
3442 // particular index after we have recomputed the find results.
3443 std::string current_find_text
= current_find_text_
;
3444 if (current_find_index_
.valid())
3445 resume_find_index_
.SetIndex(current_find_index_
.GetIndex());
3447 resume_find_index_
.Invalidate();
3449 InvalidateAllPages();
3451 if (!current_find_text
.empty()) {
3453 client_
->NotifyNumberOfFindResultsChanged(0, false);
3454 StartFind(current_find_text
.c_str(), false);
3458 void PDFiumEngine::SetSelecting(bool selecting
) {
3459 bool was_selecting
= selecting_
;
3460 selecting_
= selecting
;
3461 if (selecting_
!= was_selecting
)
3462 client_
->IsSelectingChanged(selecting
);
3465 void PDFiumEngine::Form_Invalidate(FPDF_FORMFILLINFO
* param
,
3471 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3472 int page_index
= engine
->GetVisiblePageIndex(page
);
3473 if (page_index
== -1) {
3474 // This can sometime happen when the page is closed because it went off
3475 // screen, and PDFium invalidates the control as it's being deleted.
3479 pp::Rect rect
= engine
->pages_
[page_index
]->PageToScreen(
3480 engine
->GetVisibleRect().point(), engine
->current_zoom_
, left
, top
, right
,
3481 bottom
, engine
->current_rotation_
);
3482 engine
->client_
->Invalidate(rect
);
3485 void PDFiumEngine::Form_OutputSelectedRect(FPDF_FORMFILLINFO
* param
,
3491 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3492 int page_index
= engine
->GetVisiblePageIndex(page
);
3493 if (page_index
== -1) {
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
->form_highlights_
.push_back(rect
);
3503 void PDFiumEngine::Form_SetCursor(FPDF_FORMFILLINFO
* param
, int cursor_type
) {
3504 // We don't need this since it's not enough to change the cursor in all
3505 // scenarios. Instead, we check which form field we're under in OnMouseMove.
3508 int PDFiumEngine::Form_SetTimer(FPDF_FORMFILLINFO
* param
,
3510 TimerCallback timer_func
) {
3511 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3512 engine
->timers_
[++engine
->next_timer_id_
] =
3513 std::pair
<int, TimerCallback
>(elapse
, timer_func
);
3514 engine
->client_
->ScheduleCallback(engine
->next_timer_id_
, elapse
);
3515 return engine
->next_timer_id_
;
3518 void PDFiumEngine::Form_KillTimer(FPDF_FORMFILLINFO
* param
, int timer_id
) {
3519 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3520 engine
->timers_
.erase(timer_id
);
3523 FPDF_SYSTEMTIME
PDFiumEngine::Form_GetLocalTime(FPDF_FORMFILLINFO
* param
) {
3524 base::Time time
= base::Time::Now();
3525 base::Time::Exploded exploded
;
3526 time
.LocalExplode(&exploded
);
3529 rv
.wYear
= exploded
.year
;
3530 rv
.wMonth
= exploded
.month
;
3531 rv
.wDayOfWeek
= exploded
.day_of_week
;
3532 rv
.wDay
= exploded
.day_of_month
;
3533 rv
.wHour
= exploded
.hour
;
3534 rv
.wMinute
= exploded
.minute
;
3535 rv
.wSecond
= exploded
.second
;
3536 rv
.wMilliseconds
= exploded
.millisecond
;
3540 void PDFiumEngine::Form_OnChange(FPDF_FORMFILLINFO
* param
) {
3541 // Don't care about.
3544 FPDF_PAGE
PDFiumEngine::Form_GetPage(FPDF_FORMFILLINFO
* param
,
3545 FPDF_DOCUMENT document
,
3547 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3548 if (page_index
< 0 || page_index
>= static_cast<int>(engine
->pages_
.size()))
3550 return engine
->pages_
[page_index
]->GetPage();
3553 FPDF_PAGE
PDFiumEngine::Form_GetCurrentPage(FPDF_FORMFILLINFO
* param
,
3554 FPDF_DOCUMENT document
) {
3555 // TODO(jam): find out what this is used for.
3556 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3557 int index
= engine
->last_page_mouse_down_
;
3559 index
= engine
->GetMostVisiblePage();
3566 return engine
->pages_
[index
]->GetPage();
3569 int PDFiumEngine::Form_GetRotation(FPDF_FORMFILLINFO
* param
, FPDF_PAGE page
) {
3573 void PDFiumEngine::Form_ExecuteNamedAction(FPDF_FORMFILLINFO
* param
,
3574 FPDF_BYTESTRING named_action
) {
3575 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3576 std::string
action(named_action
);
3577 if (action
== "Print") {
3578 engine
->client_
->Print();
3582 int index
= engine
->last_page_mouse_down_
;
3583 /* Don't try to calculate the most visible page if we don't have a left click
3584 before this event (this code originally copied Form_GetCurrentPage which of
3585 course needs to do that and which doesn't have recursion). This can end up
3586 causing infinite recursion. See http://crbug.com/240413 for more
3587 information. Either way, it's not necessary for the spec'd list of named
3590 index = engine->GetMostVisiblePage();
3595 // This is the only list of named actions per the spec (see 12.6.4.11). Adobe
3596 // Reader supports more, like FitWidth, but since they're not part of the spec
3597 // and we haven't got bugs about them, no need to now.
3598 if (action
== "NextPage") {
3599 engine
->client_
->ScrollToPage(index
+ 1);
3600 } else if (action
== "PrevPage") {
3601 engine
->client_
->ScrollToPage(index
- 1);
3602 } else if (action
== "FirstPage") {
3603 engine
->client_
->ScrollToPage(0);
3604 } else if (action
== "LastPage") {
3605 engine
->client_
->ScrollToPage(engine
->pages_
.size() - 1);
3609 void PDFiumEngine::Form_SetTextFieldFocus(FPDF_FORMFILLINFO
* param
,
3610 FPDF_WIDESTRING value
,
3611 FPDF_DWORD valueLen
,
3612 FPDF_BOOL is_focus
) {
3613 // Do nothing for now.
3614 // TODO(gene): use this signal to trigger OSK.
3617 void PDFiumEngine::Form_DoURIAction(FPDF_FORMFILLINFO
* param
,
3618 FPDF_BYTESTRING uri
) {
3619 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3620 engine
->client_
->NavigateTo(std::string(uri
), false);
3623 void PDFiumEngine::Form_DoGoToAction(FPDF_FORMFILLINFO
* param
,
3626 float* position_array
,
3627 int size_of_array
) {
3628 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3629 engine
->client_
->ScrollToPage(page_index
);
3632 int PDFiumEngine::Form_Alert(IPDF_JSPLATFORM
* param
,
3633 FPDF_WIDESTRING message
,
3634 FPDF_WIDESTRING title
,
3637 // See fpdfformfill.h for these values.
3640 ALERT_TYPE_OK_CANCEL
,
3642 ALERT_TYPE_YES_NO_CANCEL
3646 ALERT_RESULT_OK
= 1,
3647 ALERT_RESULT_CANCEL
,
3652 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3653 std::string message_str
=
3654 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(message
));
3655 if (type
== ALERT_TYPE_OK
) {
3656 engine
->client_
->Alert(message_str
);
3657 return ALERT_RESULT_OK
;
3660 bool rv
= engine
->client_
->Confirm(message_str
);
3661 if (type
== ALERT_TYPE_OK_CANCEL
)
3662 return rv
? ALERT_RESULT_OK
: ALERT_RESULT_CANCEL
;
3663 return rv
? ALERT_RESULT_YES
: ALERT_RESULT_NO
;
3666 void PDFiumEngine::Form_Beep(IPDF_JSPLATFORM
* param
, int type
) {
3667 // Beeps are annoying, and not possible using javascript, so ignore for now.
3670 int PDFiumEngine::Form_Response(IPDF_JSPLATFORM
* param
,
3671 FPDF_WIDESTRING question
,
3672 FPDF_WIDESTRING title
,
3673 FPDF_WIDESTRING default_response
,
3674 FPDF_WIDESTRING label
,
3678 std::string question_str
= base::UTF16ToUTF8(
3679 reinterpret_cast<const base::char16
*>(question
));
3680 std::string default_str
= base::UTF16ToUTF8(
3681 reinterpret_cast<const base::char16
*>(default_response
));
3683 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3684 std::string rv
= engine
->client_
->Prompt(question_str
, default_str
);
3685 base::string16 rv_16
= base::UTF8ToUTF16(rv
);
3686 int rv_bytes
= rv_16
.size() * sizeof(base::char16
);
3688 int bytes_to_copy
= rv_bytes
< length
? rv_bytes
: length
;
3689 memcpy(response
, rv_16
.c_str(), bytes_to_copy
);
3694 int PDFiumEngine::Form_GetFilePath(IPDF_JSPLATFORM
* param
,
3697 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3698 std::string rv
= engine
->client_
->GetURL();
3699 if (file_path
&& rv
.size() <= static_cast<size_t>(length
))
3700 memcpy(file_path
, rv
.c_str(), rv
.size());
3704 void PDFiumEngine::Form_Mail(IPDF_JSPLATFORM
* param
,
3709 FPDF_WIDESTRING subject
,
3711 FPDF_WIDESTRING bcc
,
3712 FPDF_WIDESTRING message
) {
3713 // Note: |mail_data| and |length| are ignored. We don't handle attachments;
3714 // there is no way with mailto.
3715 std::string to_str
=
3716 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(to
));
3717 std::string cc_str
=
3718 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(cc
));
3719 std::string bcc_str
=
3720 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(bcc
));
3721 std::string subject_str
=
3722 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(subject
));
3723 std::string message_str
=
3724 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(message
));
3726 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3727 engine
->client_
->Email(to_str
, cc_str
, bcc_str
, subject_str
, message_str
);
3730 void PDFiumEngine::Form_Print(IPDF_JSPLATFORM
* param
,
3735 FPDF_BOOL shrink_to_fit
,
3736 FPDF_BOOL print_as_image
,
3738 FPDF_BOOL annotations
) {
3739 // No way to pass the extra information to the print dialog using JavaScript.
3740 // Just opening it is fine for now.
3741 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3742 engine
->client_
->Print();
3745 void PDFiumEngine::Form_SubmitForm(IPDF_JSPLATFORM
* param
,
3748 FPDF_WIDESTRING url
) {
3749 std::string url_str
=
3750 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(url
));
3751 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3752 engine
->client_
->SubmitForm(url_str
, form_data
, length
);
3755 void PDFiumEngine::Form_GotoPage(IPDF_JSPLATFORM
* param
,
3757 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3758 engine
->client_
->ScrollToPage(page_number
);
3761 int PDFiumEngine::Form_Browse(IPDF_JSPLATFORM
* param
,
3764 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3765 std::string path
= engine
->client_
->ShowFileSelectionDialog();
3766 if (path
.size() + 1 <= static_cast<size_t>(length
))
3767 memcpy(file_path
, &path
[0], path
.size() + 1);
3768 return path
.size() + 1;
3771 FPDF_BOOL
PDFiumEngine::Pause_NeedToPauseNow(IFSDK_PAUSE
* param
) {
3772 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3773 return (base::Time::Now() - engine
->last_progressive_start_time_
).
3774 InMilliseconds() > engine
->progressive_paint_timeout_
;
3777 ScopedUnsupportedFeature::ScopedUnsupportedFeature(PDFiumEngine
* engine
)
3778 : engine_(engine
), old_engine_(g_engine_for_unsupported
) {
3779 g_engine_for_unsupported
= engine_
;
3782 ScopedUnsupportedFeature::~ScopedUnsupportedFeature() {
3783 g_engine_for_unsupported
= old_engine_
;
3786 PDFEngineExports
* PDFEngineExports::Create() {
3787 return new PDFiumEngineExports
;
3792 int CalculatePosition(FPDF_PAGE page
,
3793 const PDFiumEngineExports::RenderingSettings
& settings
,
3795 int page_width
= static_cast<int>(ConvertUnitDouble(FPDF_GetPageWidth(page
),
3798 int page_height
= static_cast<int>(ConvertUnitDouble(FPDF_GetPageHeight(page
),
3802 // Start by assuming that we will draw exactly to the bounds rect
3804 *dest
= settings
.bounds
;
3806 int rotate
= 0; // normal orientation.
3808 // Auto-rotate landscape pages to print correctly.
3809 if (settings
.autorotate
&&
3810 (dest
->width() > dest
->height()) != (page_width
> page_height
)) {
3811 rotate
= 3; // 90 degrees counter-clockwise.
3812 std::swap(page_width
, page_height
);
3815 // See if we need to scale the output
3816 bool scale_to_bounds
= false;
3817 if (settings
.fit_to_bounds
&&
3818 ((page_width
> dest
->width()) || (page_height
> dest
->height()))) {
3819 scale_to_bounds
= true;
3820 } else if (settings
.stretch_to_bounds
&&
3821 ((page_width
< dest
->width()) || (page_height
< dest
->height()))) {
3822 scale_to_bounds
= true;
3825 if (scale_to_bounds
) {
3826 // If we need to maintain aspect ratio, calculate the actual width and
3828 if (settings
.keep_aspect_ratio
) {
3829 double scale_factor_x
= page_width
;
3830 scale_factor_x
/= dest
->width();
3831 double scale_factor_y
= page_height
;
3832 scale_factor_y
/= dest
->height();
3833 if (scale_factor_x
> scale_factor_y
) {
3834 dest
->set_height(page_height
/ scale_factor_x
);
3836 dest
->set_width(page_width
/ scale_factor_y
);
3840 // We are not scaling to bounds. Draw in the actual page size. If the
3841 // actual page size is larger than the bounds, the output will be
3843 dest
->set_width(page_width
);
3844 dest
->set_height(page_height
);
3847 if (settings
.center_in_bounds
) {
3848 pp::Point
offset((settings
.bounds
.width() - dest
->width()) / 2,
3849 (settings
.bounds
.height() - dest
->height()) / 2);
3850 dest
->Offset(offset
);
3858 bool PDFiumEngineExports::RenderPDFPageToDC(const void* pdf_buffer
,
3861 const RenderingSettings
& settings
,
3863 FPDF_DOCUMENT doc
= FPDF_LoadMemDocument(pdf_buffer
, buffer_size
, NULL
);
3866 FPDF_PAGE page
= FPDF_LoadPage(doc
, page_number
);
3868 FPDF_CloseDocument(doc
);
3871 RenderingSettings new_settings
= settings
;
3872 // calculate the page size
3873 if (new_settings
.dpi_x
== -1)
3874 new_settings
.dpi_x
= GetDeviceCaps(dc
, LOGPIXELSX
);
3875 if (new_settings
.dpi_y
== -1)
3876 new_settings
.dpi_y
= GetDeviceCaps(dc
, LOGPIXELSY
);
3879 int rotate
= CalculatePosition(page
, new_settings
, &dest
);
3881 int save_state
= SaveDC(dc
);
3882 // The caller wanted all drawing to happen within the bounds specified.
3883 // Based on scale calculations, our destination rect might be larger
3884 // than the bounds. Set the clip rect to the bounds.
3885 IntersectClipRect(dc
, settings
.bounds
.x(), settings
.bounds
.y(),
3886 settings
.bounds
.x() + settings
.bounds
.width(),
3887 settings
.bounds
.y() + settings
.bounds
.height());
3889 // A temporary hack. PDFs generated by Cairo (used by Chrome OS to generate
3890 // a PDF output from a webpage) result in very large metafiles and the
3891 // rendering using FPDF_RenderPage is incorrect. In this case, render as a
3892 // bitmap. Note that this code does not kick in for PDFs printed from Chrome
3893 // because in that case we create a temp PDF first before printing and this
3894 // temp PDF does not have a creator string that starts with "cairo".
3895 base::string16 creator
;
3896 size_t buffer_bytes
= FPDF_GetMetaText(doc
, "Creator", NULL
, 0);
3897 if (buffer_bytes
> 1) {
3899 doc
, "Creator", WriteInto(&creator
, buffer_bytes
+ 1), buffer_bytes
);
3901 bool use_bitmap
= false;
3902 if (StartsWith(creator
, L
"cairo", false))
3905 // Another temporary hack. Some PDFs seems to render very slowly if
3906 // FPDF_RenderPage is directly used on a printer DC. I suspect it is
3907 // because of the code to talk Postscript directly to the printer if
3908 // the printer supports this. Need to discuss this with PDFium. For now,
3909 // render to a bitmap and then blit the bitmap to the DC if we have been
3910 // supplied a printer DC.
3911 int device_type
= GetDeviceCaps(dc
, TECHNOLOGY
);
3913 (device_type
== DT_RASPRINTER
) || (device_type
== DT_PLOTTER
)) {
3914 FPDF_BITMAP bitmap
= FPDFBitmap_Create(dest
.width(), dest
.height(),
3917 FPDFBitmap_FillRect(bitmap
, 0, 0, dest
.width(), dest
.height(), 0xFFFFFFFF);
3918 FPDF_RenderPageBitmap(
3919 bitmap
, page
, 0, 0, dest
.width(), dest
.height(), rotate
,
3920 FPDF_ANNOT
| FPDF_PRINTING
| FPDF_NO_CATCH
);
3921 int stride
= FPDFBitmap_GetStride(bitmap
);
3923 memset(&bmi
, 0, sizeof(bmi
));
3924 bmi
.bmiHeader
.biSize
= sizeof(BITMAPINFOHEADER
);
3925 bmi
.bmiHeader
.biWidth
= dest
.width();
3926 bmi
.bmiHeader
.biHeight
= -dest
.height(); // top-down image
3927 bmi
.bmiHeader
.biPlanes
= 1;
3928 bmi
.bmiHeader
.biBitCount
= 32;
3929 bmi
.bmiHeader
.biCompression
= BI_RGB
;
3930 bmi
.bmiHeader
.biSizeImage
= stride
* dest
.height();
3931 StretchDIBits(dc
, dest
.x(), dest
.y(), dest
.width(), dest
.height(),
3932 0, 0, dest
.width(), dest
.height(),
3933 FPDFBitmap_GetBuffer(bitmap
), &bmi
, DIB_RGB_COLORS
, SRCCOPY
);
3934 FPDFBitmap_Destroy(bitmap
);
3936 FPDF_RenderPage(dc
, page
, dest
.x(), dest
.y(), dest
.width(), dest
.height(),
3937 rotate
, FPDF_ANNOT
| FPDF_PRINTING
| FPDF_NO_CATCH
);
3939 RestoreDC(dc
, save_state
);
3940 FPDF_ClosePage(page
);
3941 FPDF_CloseDocument(doc
);
3946 bool PDFiumEngineExports::RenderPDFPageToBitmap(
3947 const void* pdf_buffer
,
3948 int pdf_buffer_size
,
3950 const RenderingSettings
& settings
,
3951 void* bitmap_buffer
) {
3952 FPDF_DOCUMENT doc
= FPDF_LoadMemDocument(pdf_buffer
, pdf_buffer_size
, NULL
);
3955 FPDF_PAGE page
= FPDF_LoadPage(doc
, page_number
);
3957 FPDF_CloseDocument(doc
);
3962 int rotate
= CalculatePosition(page
, settings
, &dest
);
3964 FPDF_BITMAP bitmap
=
3965 FPDFBitmap_CreateEx(settings
.bounds
.width(), settings
.bounds
.height(),
3966 FPDFBitmap_BGRA
, bitmap_buffer
,
3967 settings
.bounds
.width() * 4);
3969 FPDFBitmap_FillRect(bitmap
, 0, 0, settings
.bounds
.width(),
3970 settings
.bounds
.height(), 0xFFFFFFFF);
3971 // Shift top-left corner of bounds to (0, 0) if it's not there.
3972 dest
.set_point(dest
.point() - settings
.bounds
.point());
3973 FPDF_RenderPageBitmap(
3974 bitmap
, page
, dest
.x(), dest
.y(), dest
.width(), dest
.height(), rotate
,
3975 FPDF_ANNOT
| FPDF_PRINTING
| FPDF_NO_CATCH
);
3976 FPDFBitmap_Destroy(bitmap
);
3977 FPDF_ClosePage(page
);
3978 FPDF_CloseDocument(doc
);
3982 bool PDFiumEngineExports::GetPDFDocInfo(const void* pdf_buffer
,
3985 double* max_page_width
) {
3986 FPDF_DOCUMENT doc
= FPDF_LoadMemDocument(pdf_buffer
, buffer_size
, NULL
);
3989 int page_count_local
= FPDF_GetPageCount(doc
);
3991 *page_count
= page_count_local
;
3993 if (max_page_width
) {
3994 *max_page_width
= 0;
3995 for (int page_number
= 0; page_number
< page_count_local
; page_number
++) {
3996 double page_width
= 0;
3997 double page_height
= 0;
3998 FPDF_GetPageSizeByIndex(doc
, page_number
, &page_width
, &page_height
);
3999 if (page_width
> *max_page_width
) {
4000 *max_page_width
= page_width
;
4004 FPDF_CloseDocument(doc
);
4008 bool PDFiumEngineExports::GetPDFPageSizeByIndex(
4009 const void* pdf_buffer
,
4010 int pdf_buffer_size
,
4014 FPDF_DOCUMENT doc
= FPDF_LoadMemDocument(pdf_buffer
, pdf_buffer_size
, NULL
);
4017 bool success
= FPDF_GetPageSizeByIndex(doc
, page_number
, width
, height
) != 0;
4018 FPDF_CloseDocument(doc
);
4022 } // namespace chrome_pdf