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 "gin/public/gin_embedders.h"
22 #include "pdf/draw_utils.h"
23 #include "pdf/pdfium/pdfium_api_string_buffer_adapter.h"
24 #include "pdf/pdfium/pdfium_mem_buffer_file_read.h"
25 #include "pdf/pdfium/pdfium_mem_buffer_file_write.h"
26 #include "ppapi/c/pp_errors.h"
27 #include "ppapi/c/pp_input_event.h"
28 #include "ppapi/c/ppb_core.h"
29 #include "ppapi/c/private/ppb_pdf.h"
30 #include "ppapi/cpp/dev/memory_dev.h"
31 #include "ppapi/cpp/input_event.h"
32 #include "ppapi/cpp/instance.h"
33 #include "ppapi/cpp/module.h"
34 #include "ppapi/cpp/private/pdf.h"
35 #include "ppapi/cpp/trusted/browser_font_trusted.h"
36 #include "ppapi/cpp/url_response_info.h"
37 #include "ppapi/cpp/var.h"
38 #include "ppapi/cpp/var_dictionary.h"
39 #include "printing/units.h"
40 #include "third_party/pdfium/public/fpdf_edit.h"
41 #include "third_party/pdfium/public/fpdf_ext.h"
42 #include "third_party/pdfium/public/fpdf_flatten.h"
43 #include "third_party/pdfium/public/fpdf_ppo.h"
44 #include "third_party/pdfium/public/fpdf_save.h"
45 #include "third_party/pdfium/public/fpdf_searchex.h"
46 #include "third_party/pdfium/public/fpdf_sysfontinfo.h"
47 #include "third_party/pdfium/public/fpdf_transformpage.h"
48 #include "ui/events/keycodes/keyboard_codes.h"
49 #include "v8/include/v8.h"
51 using printing::ConvertUnit
;
52 using printing::ConvertUnitDouble
;
53 using printing::kPointsPerInch
;
54 using printing::kPixelsPerInch
;
56 namespace chrome_pdf
{
60 #define kPageShadowTop 3
61 #define kPageShadowBottom 7
62 #define kPageShadowLeft 5
63 #define kPageShadowRight 5
65 #define kPageSeparatorThickness 4
66 #define kHighlightColorR 153
67 #define kHighlightColorG 193
68 #define kHighlightColorB 218
70 const uint32 kPendingPageColor
= 0xFFEEEEEE;
72 #define kFormHighlightColor 0xFFE4DD
73 #define kFormHighlightAlpha 100
75 #define kMaxPasswordTries 3
78 // http://www.adobe.com/devnet/acrobat/pdfs/pdf_reference_1-7.pdf
79 #define kPDFPermissionPrintLowQualityMask 1 << 2
80 #define kPDFPermissionPrintHighQualityMask 1 << 11
81 #define kPDFPermissionCopyMask 1 << 4
82 #define kPDFPermissionCopyAccessibleMask 1 << 9
84 #define kLoadingTextVerticalOffset 50
86 // The maximum amount of time we'll spend doing a paint before we give back
87 // control of the thread.
88 #define kMaxProgressivePaintTimeMs 50
90 // The maximum amount of time we'll spend doing the first paint. This is less
91 // than the above to keep things smooth if the user is scrolling quickly. We
92 // try painting a little because with accelerated compositing, we get flushes
93 // only every 16 ms. If we were to wait until the next flush to paint the rest
94 // of the pdf, we would never get to draw the pdf and would only draw the
95 // scrollbars. This value is picked to give enough time for gpu related code to
96 // do its thing and still fit within the timelimit for 60Hz. For the
97 // non-composited case, this doesn't make things worse since we're still
98 // painting the scrollbars > 60 Hz.
99 #define kMaxInitialProgressivePaintTimeMs 10
108 std::vector
<uint32_t> GetPageNumbersFromPrintPageNumberRange(
109 const PP_PrintPageNumberRange_Dev
* page_ranges
,
110 uint32_t page_range_count
) {
111 std::vector
<uint32_t> page_numbers
;
112 for (uint32_t index
= 0; index
< page_range_count
; ++index
) {
113 for (uint32_t page_number
= page_ranges
[index
].first_page_number
;
114 page_number
<= page_ranges
[index
].last_page_number
; ++page_number
) {
115 page_numbers
.push_back(page_number
);
121 #if defined(OS_LINUX)
123 PP_Instance g_last_instance_id
;
125 struct PDFFontSubstitution
{
126 const char* pdf_name
;
132 PP_BrowserFont_Trusted_Weight
WeightToBrowserFontTrustedWeight(int weight
) {
133 static_assert(PP_BROWSERFONT_TRUSTED_WEIGHT_100
== 0,
134 "PP_BrowserFont_Trusted_Weight min");
135 static_assert(PP_BROWSERFONT_TRUSTED_WEIGHT_900
== 8,
136 "PP_BrowserFont_Trusted_Weight max");
137 const int kMinimumWeight
= 100;
138 const int kMaximumWeight
= 900;
139 int normalized_weight
=
140 std::min(std::max(weight
, kMinimumWeight
), kMaximumWeight
);
141 normalized_weight
= (normalized_weight
/ 100) - 1;
142 return static_cast<PP_BrowserFont_Trusted_Weight
>(normalized_weight
);
145 // This list is for CPWL_FontMap::GetDefaultFontByCharset().
146 // We pretend to have these font natively and let the browser (or underlying
147 // fontconfig) to pick the proper font on the system.
148 void EnumFonts(struct _FPDF_SYSFONTINFO
* sysfontinfo
, void* mapper
) {
149 FPDF_AddInstalledFont(mapper
, "Arial", FXFONT_DEFAULT_CHARSET
);
151 const FPDF_CharsetFontMap
* font_map
= FPDF_GetDefaultTTFMap();
152 for (; font_map
->charset
!= -1; ++font_map
) {
153 FPDF_AddInstalledFont(mapper
, font_map
->fontname
, font_map
->charset
);
157 const PDFFontSubstitution PDFFontSubstitutions
[] = {
158 {"Courier", "Courier New", false, false},
159 {"Courier-Bold", "Courier New", true, false},
160 {"Courier-BoldOblique", "Courier New", true, true},
161 {"Courier-Oblique", "Courier New", false, true},
162 {"Helvetica", "Arial", false, false},
163 {"Helvetica-Bold", "Arial", true, false},
164 {"Helvetica-BoldOblique", "Arial", true, true},
165 {"Helvetica-Oblique", "Arial", false, true},
166 {"Times-Roman", "Times New Roman", false, false},
167 {"Times-Bold", "Times New Roman", true, false},
168 {"Times-BoldItalic", "Times New Roman", true, true},
169 {"Times-Italic", "Times New Roman", false, true},
171 // MS P?(Mincho|Gothic) are the most notable fonts in Japanese PDF files
172 // without embedding the glyphs. Sometimes the font names are encoded
173 // in Japanese Windows's locale (CP932/Shift_JIS) without space.
174 // Most Linux systems don't have the exact font, but for outsourcing
175 // fontconfig to find substitutable font in the system, we pass ASCII
177 {"MS-PGothic", "MS PGothic", false, false},
178 {"MS-Gothic", "MS Gothic", false, false},
179 {"MS-PMincho", "MS PMincho", false, false},
180 {"MS-Mincho", "MS Mincho", false, false},
181 // MS PGothic in Shift_JIS encoding.
182 {"\x82\x6C\x82\x72\x82\x6F\x83\x53\x83\x56\x83\x62\x83\x4E",
183 "MS PGothic", false, false},
184 // MS Gothic in Shift_JIS encoding.
185 {"\x82\x6C\x82\x72\x83\x53\x83\x56\x83\x62\x83\x4E",
186 "MS Gothic", false, false},
187 // MS PMincho in Shift_JIS encoding.
188 {"\x82\x6C\x82\x72\x82\x6F\x96\xBE\x92\xA9",
189 "MS PMincho", false, false},
190 // MS Mincho in Shift_JIS encoding.
191 {"\x82\x6C\x82\x72\x96\xBE\x92\xA9",
192 "MS Mincho", false, false},
195 void* MapFont(struct _FPDF_SYSFONTINFO
*, int weight
, int italic
,
196 int charset
, int pitch_family
, const char* face
, int* exact
) {
197 // Do not attempt to map fonts if pepper is not initialized (for privet local
199 // TODO(noamsml): Real font substitution (http://crbug.com/391978)
200 if (!pp::Module::Get())
203 pp::BrowserFontDescription description
;
205 // Pretend the system does not have the Symbol font to force a fallback to
206 // the built in Symbol font in CFX_FontMapper::FindSubstFont().
207 if (strcmp(face
, "Symbol") == 0)
210 if (pitch_family
& FXFONT_FF_FIXEDPITCH
) {
211 description
.set_family(PP_BROWSERFONT_TRUSTED_FAMILY_MONOSPACE
);
212 } else if (pitch_family
& FXFONT_FF_ROMAN
) {
213 description
.set_family(PP_BROWSERFONT_TRUSTED_FAMILY_SERIF
);
216 // Map from the standard PDF fonts to TrueType font names.
218 for (i
= 0; i
< arraysize(PDFFontSubstitutions
); ++i
) {
219 if (strcmp(face
, PDFFontSubstitutions
[i
].pdf_name
) == 0) {
220 description
.set_face(PDFFontSubstitutions
[i
].face
);
221 if (PDFFontSubstitutions
[i
].bold
)
222 description
.set_weight(PP_BROWSERFONT_TRUSTED_WEIGHT_BOLD
);
223 if (PDFFontSubstitutions
[i
].italic
)
224 description
.set_italic(true);
229 if (i
== arraysize(PDFFontSubstitutions
)) {
230 // Convert to UTF-8 before calling set_face().
231 std::string face_utf8
;
232 if (base::IsStringUTF8(face
)) {
235 std::string encoding
;
236 if (base::DetectEncoding(face
, &encoding
)) {
237 // ConvertToUtf8AndNormalize() clears |face_utf8| on failure.
238 base::ConvertToUtf8AndNormalize(face
, encoding
, &face_utf8
);
242 if (face_utf8
.empty())
245 description
.set_face(face_utf8
);
246 description
.set_weight(WeightToBrowserFontTrustedWeight(weight
));
247 description
.set_italic(italic
> 0);
250 if (!pp::PDF::IsAvailable()) {
255 PP_Resource font_resource
= pp::PDF::GetFontFileWithFallback(
256 pp::InstanceHandle(g_last_instance_id
),
257 &description
.pp_font_description(),
258 static_cast<PP_PrivateFontCharset
>(charset
));
259 long res_id
= font_resource
;
260 return reinterpret_cast<void*>(res_id
);
263 unsigned long GetFontData(struct _FPDF_SYSFONTINFO
*, void* font_id
,
264 unsigned int table
, unsigned char* buffer
,
265 unsigned long buf_size
) {
266 if (!pp::PDF::IsAvailable()) {
271 uint32_t size
= buf_size
;
272 long res_id
= reinterpret_cast<long>(font_id
);
273 if (!pp::PDF::GetFontTableForPrivateFontFile(res_id
, table
, buffer
, &size
))
278 void DeleteFont(struct _FPDF_SYSFONTINFO
*, void* font_id
) {
279 long res_id
= reinterpret_cast<long>(font_id
);
280 pp::Module::Get()->core()->ReleaseResource(res_id
);
283 FPDF_SYSFONTINFO g_font_info
= {
294 #endif // defined(OS_LINUX)
296 PDFiumEngine
* g_engine_for_unsupported
;
298 void Unsupported_Handler(UNSUPPORT_INFO
*, int type
) {
299 if (!g_engine_for_unsupported
) {
304 g_engine_for_unsupported
->UnsupportedFeature(type
);
307 UNSUPPORT_INFO g_unsuppored_info
= {
312 // Set the destination page size and content area in points based on source
313 // page rotation and orientation.
315 // |rotated| True if source page is rotated 90 degree or 270 degree.
316 // |is_src_page_landscape| is true if the source page orientation is landscape.
317 // |page_size| has the actual destination page size in points.
318 // |content_rect| has the actual destination page printable area values in
320 void SetPageSizeAndContentRect(bool rotated
,
321 bool is_src_page_landscape
,
323 pp::Rect
* content_rect
) {
324 bool is_dst_page_landscape
= page_size
->width() > page_size
->height();
325 bool page_orientation_mismatched
= is_src_page_landscape
!=
326 is_dst_page_landscape
;
327 bool rotate_dst_page
= rotated
^ page_orientation_mismatched
;
328 if (rotate_dst_page
) {
329 page_size
->SetSize(page_size
->height(), page_size
->width());
330 content_rect
->SetRect(content_rect
->y(), content_rect
->x(),
331 content_rect
->height(), content_rect
->width());
335 // Calculate the scale factor between |content_rect| and a page of size
336 // |src_width| x |src_height|.
338 // |scale_to_fit| is true, if we need to calculate the scale factor.
339 // |content_rect| specifies the printable area of the destination page, with
340 // origin at left-bottom. Values are in points.
341 // |src_width| specifies the source page width in points.
342 // |src_height| specifies the source page height in points.
343 // |rotated| True if source page is rotated 90 degree or 270 degree.
344 double CalculateScaleFactor(bool scale_to_fit
,
345 const pp::Rect
& content_rect
,
346 double src_width
, double src_height
, bool rotated
) {
347 if (!scale_to_fit
|| src_width
== 0 || src_height
== 0)
350 double actual_source_page_width
= rotated
? src_height
: src_width
;
351 double actual_source_page_height
= rotated
? src_width
: src_height
;
352 double ratio_x
= static_cast<double>(content_rect
.width()) /
353 actual_source_page_width
;
354 double ratio_y
= static_cast<double>(content_rect
.height()) /
355 actual_source_page_height
;
356 return std::min(ratio_x
, ratio_y
);
359 // Compute source clip box boundaries based on the crop box / media box of
360 // source page and scale factor.
362 // |page| Handle to the source page. Returned by FPDF_LoadPage function.
363 // |scale_factor| specifies the scale factor that should be applied to source
364 // clip box boundaries.
365 // |rotated| True if source page is rotated 90 degree or 270 degree.
366 // |clip_box| out param to hold the computed source clip box values.
367 void CalculateClipBoxBoundary(FPDF_PAGE page
, double scale_factor
, bool rotated
,
369 if (!FPDFPage_GetCropBox(page
, &clip_box
->left
, &clip_box
->bottom
,
370 &clip_box
->right
, &clip_box
->top
)) {
371 if (!FPDFPage_GetMediaBox(page
, &clip_box
->left
, &clip_box
->bottom
,
372 &clip_box
->right
, &clip_box
->top
)) {
373 // Make the default size to be letter size (8.5" X 11"). We are just
374 // following the PDFium way of handling these corner cases. PDFium always
375 // consider US-Letter as the default page size.
376 float paper_width
= 612;
377 float paper_height
= 792;
379 clip_box
->bottom
= 0;
380 clip_box
->right
= rotated
? paper_height
: paper_width
;
381 clip_box
->top
= rotated
? paper_width
: paper_height
;
384 clip_box
->left
*= scale_factor
;
385 clip_box
->right
*= scale_factor
;
386 clip_box
->bottom
*= scale_factor
;
387 clip_box
->top
*= scale_factor
;
390 // Calculate the clip box translation offset for a page that does need to be
391 // scaled. All parameters are in points.
393 // |content_rect| specifies the printable area of the destination page, with
394 // origin at left-bottom.
395 // |source_clip_box| specifies the source clip box positions, relative to
396 // origin at left-bottom.
397 // |offset_x| and |offset_y| will contain the final translation offsets for the
398 // source clip box, relative to origin at left-bottom.
399 void CalculateScaledClipBoxOffset(const pp::Rect
& content_rect
,
400 const ClipBox
& source_clip_box
,
401 double* offset_x
, double* offset_y
) {
402 const float clip_box_width
= source_clip_box
.right
- source_clip_box
.left
;
403 const float clip_box_height
= source_clip_box
.top
- source_clip_box
.bottom
;
405 // Center the intended clip region to real clip region.
406 *offset_x
= (content_rect
.width() - clip_box_width
) / 2 + content_rect
.x() -
407 source_clip_box
.left
;
408 *offset_y
= (content_rect
.height() - clip_box_height
) / 2 + content_rect
.y() -
409 source_clip_box
.bottom
;
412 // Calculate the clip box offset for a page that does not need to be scaled.
413 // All parameters are in points.
415 // |content_rect| specifies the printable area of the destination page, with
416 // origin at left-bottom.
417 // |rotation| specifies the source page rotation values which are N / 90
419 // |page_width| specifies the screen destination page width.
420 // |page_height| specifies the screen destination page height.
421 // |source_clip_box| specifies the source clip box positions, relative to origin
423 // |offset_x| and |offset_y| will contain the final translation offsets for the
424 // source clip box, relative to origin at left-bottom.
425 void CalculateNonScaledClipBoxOffset(const pp::Rect
& content_rect
, int rotation
,
426 int page_width
, int page_height
,
427 const ClipBox
& source_clip_box
,
428 double* offset_x
, double* offset_y
) {
429 // Align the intended clip region to left-top corner of real clip region.
432 *offset_x
= -1 * source_clip_box
.left
;
433 *offset_y
= page_height
- source_clip_box
.top
;
437 *offset_y
= -1 * source_clip_box
.bottom
;
440 *offset_x
= page_width
- source_clip_box
.right
;
444 *offset_x
= page_height
- source_clip_box
.right
;
445 *offset_y
= page_width
- source_clip_box
.top
;
453 // This formats a string with special 0xfffe end-of-line hyphens the same way
454 // as Adobe Reader. When a hyphen is encountered, the next non-CR/LF whitespace
455 // becomes CR+LF and the hyphen is erased. If there is no whitespace between
456 // two hyphens, the latter hyphen is erased and ignored.
457 void FormatStringWithHyphens(base::string16
* text
) {
458 // First pass marks all the hyphen positions.
459 struct HyphenPosition
{
460 HyphenPosition() : position(0), next_whitespace_position(0) {}
462 size_t next_whitespace_position
; // 0 for none
464 std::vector
<HyphenPosition
> hyphen_positions
;
465 HyphenPosition current_hyphen_position
;
466 bool current_hyphen_position_is_valid
= false;
467 const base::char16 kPdfiumHyphenEOL
= 0xfffe;
469 for (size_t i
= 0; i
< text
->size(); ++i
) {
470 const base::char16
& current_char
= (*text
)[i
];
471 if (current_char
== kPdfiumHyphenEOL
) {
472 if (current_hyphen_position_is_valid
)
473 hyphen_positions
.push_back(current_hyphen_position
);
474 current_hyphen_position
= HyphenPosition();
475 current_hyphen_position
.position
= i
;
476 current_hyphen_position_is_valid
= true;
477 } else if (base::IsUnicodeWhitespace(current_char
)) {
478 if (current_hyphen_position_is_valid
) {
479 if (current_char
!= L
'\r' && current_char
!= L
'\n')
480 current_hyphen_position
.next_whitespace_position
= i
;
481 hyphen_positions
.push_back(current_hyphen_position
);
482 current_hyphen_position_is_valid
= false;
486 if (current_hyphen_position_is_valid
)
487 hyphen_positions
.push_back(current_hyphen_position
);
489 // With all the hyphen positions, do the search and replace.
490 while (!hyphen_positions
.empty()) {
491 static const base::char16 kCr
[] = {L
'\r', L
'\0'};
492 const HyphenPosition
& position
= hyphen_positions
.back();
493 if (position
.next_whitespace_position
!= 0) {
494 (*text
)[position
.next_whitespace_position
] = L
'\n';
495 text
->insert(position
.next_whitespace_position
, kCr
);
497 text
->erase(position
.position
, 1);
498 hyphen_positions
.pop_back();
501 // Adobe Reader also get rid of trailing spaces right before a CRLF.
502 static const base::char16 kSpaceCrCn
[] = {L
' ', L
'\r', L
'\n', L
'\0'};
503 static const base::char16 kCrCn
[] = {L
'\r', L
'\n', L
'\0'};
504 base::ReplaceSubstringsAfterOffset(text
, 0, kSpaceCrCn
, kCrCn
);
507 // Replace CR/LF with just LF on POSIX.
508 void FormatStringForOS(base::string16
* text
) {
509 #if defined(OS_POSIX)
510 static const base::char16 kCr
[] = {L
'\r', L
'\0'};
511 static const base::char16 kBlank
[] = {L
'\0'};
512 base::ReplaceChars(*text
, kCr
, kBlank
, text
);
513 #elif defined(OS_WIN)
520 // Returns a VarDictionary (representing a bookmark), which in turn contains
521 // child VarDictionaries (representing the child bookmarks).
522 // If NULL is passed in as the bookmark then we traverse from the "root".
523 // Note that the "root" bookmark contains no useful information.
524 pp::VarDictionary
TraverseBookmarks(FPDF_DOCUMENT doc
, FPDF_BOOKMARK bookmark
) {
525 pp::VarDictionary dict
;
526 base::string16 title
;
527 unsigned long buffer_size
= FPDFBookmark_GetTitle(bookmark
, NULL
, 0);
528 size_t title_length
= base::checked_cast
<size_t>(buffer_size
) /
529 sizeof(base::string16::value_type
);
530 if (title_length
> 0) {
531 PDFiumAPIStringBufferAdapter
<base::string16
> api_string_adapter(
532 &title
, title_length
, true);
533 void* data
= api_string_adapter
.GetData();
534 FPDFBookmark_GetTitle(bookmark
, data
, buffer_size
);
535 api_string_adapter
.Close(title_length
);
537 dict
.Set(pp::Var("title"), pp::Var(base::UTF16ToUTF8(title
)));
539 FPDF_DEST dest
= FPDFBookmark_GetDest(doc
, bookmark
);
540 // Some bookmarks don't have a page to select.
542 int page_index
= FPDFDest_GetPageIndex(doc
, dest
);
543 dict
.Set(pp::Var("page"), pp::Var(page_index
));
546 pp::VarArray children
;
548 for (FPDF_BOOKMARK child_bookmark
= FPDFBookmark_GetFirstChild(doc
, bookmark
);
549 child_bookmark
!= NULL
;
550 child_bookmark
= FPDFBookmark_GetNextSibling(doc
, child_bookmark
)) {
551 children
.Set(child_index
, TraverseBookmarks(doc
, child_bookmark
));
554 dict
.Set(pp::Var("children"), children
);
560 bool InitializeSDK() {
563 #if defined(OS_LINUX)
564 // Font loading doesn't work in the renderer sandbox in Linux.
565 FPDF_SetSystemFontInfo(&g_font_info
);
568 FSDK_SetUnSpObjProcessHandler(&g_unsuppored_info
);
574 FPDF_DestroyLibrary();
577 PDFEngine
* PDFEngine::Create(PDFEngine::Client
* client
) {
578 return new PDFiumEngine(client
);
581 PDFiumEngine::PDFiumEngine(PDFEngine::Client
* client
)
584 current_rotation_(0),
586 password_tries_remaining_(0),
589 defer_page_unload_(false),
591 mouse_down_state_(PDFiumPage::NONSELECTABLE_AREA
,
592 PDFiumPage::LinkTarget()),
593 next_page_to_search_(-1),
594 last_page_to_search_(-1),
595 last_character_index_to_search_(-1),
597 permissions_handler_revision_(-1),
598 fpdf_availability_(NULL
),
600 last_page_mouse_down_(-1),
601 first_visible_page_(-1),
602 most_visible_page_(-1),
603 called_do_document_action_(false),
604 render_grayscale_(false),
605 progressive_paint_timeout_(0),
606 getting_password_(false) {
607 find_factory_
.Initialize(this);
608 password_factory_
.Initialize(this);
610 file_access_
.m_FileLen
= 0;
611 file_access_
.m_GetBlock
= &GetBlock
;
612 file_access_
.m_Param
= &doc_loader_
;
614 file_availability_
.version
= 1;
615 file_availability_
.IsDataAvail
= &IsDataAvail
;
616 file_availability_
.loader
= &doc_loader_
;
618 download_hints_
.version
= 1;
619 download_hints_
.AddSegment
= &AddSegment
;
620 download_hints_
.loader
= &doc_loader_
;
622 // Initialize FPDF_FORMFILLINFO member variables. Deriving from this struct
623 // allows the static callbacks to be able to cast the FPDF_FORMFILLINFO in
624 // callbacks to ourself instead of maintaining a map of them to
626 FPDF_FORMFILLINFO::version
= 1;
627 FPDF_FORMFILLINFO::m_pJsPlatform
= this;
628 FPDF_FORMFILLINFO::Release
= NULL
;
629 FPDF_FORMFILLINFO::FFI_Invalidate
= Form_Invalidate
;
630 FPDF_FORMFILLINFO::FFI_OutputSelectedRect
= Form_OutputSelectedRect
;
631 FPDF_FORMFILLINFO::FFI_SetCursor
= Form_SetCursor
;
632 FPDF_FORMFILLINFO::FFI_SetTimer
= Form_SetTimer
;
633 FPDF_FORMFILLINFO::FFI_KillTimer
= Form_KillTimer
;
634 FPDF_FORMFILLINFO::FFI_GetLocalTime
= Form_GetLocalTime
;
635 FPDF_FORMFILLINFO::FFI_OnChange
= Form_OnChange
;
636 FPDF_FORMFILLINFO::FFI_GetPage
= Form_GetPage
;
637 FPDF_FORMFILLINFO::FFI_GetCurrentPage
= Form_GetCurrentPage
;
638 FPDF_FORMFILLINFO::FFI_GetRotation
= Form_GetRotation
;
639 FPDF_FORMFILLINFO::FFI_ExecuteNamedAction
= Form_ExecuteNamedAction
;
640 FPDF_FORMFILLINFO::FFI_SetTextFieldFocus
= Form_SetTextFieldFocus
;
641 FPDF_FORMFILLINFO::FFI_DoURIAction
= Form_DoURIAction
;
642 FPDF_FORMFILLINFO::FFI_DoGoToAction
= Form_DoGoToAction
;
644 FPDF_FORMFILLINFO::version
= 2;
645 FPDF_FORMFILLINFO::FFI_EmailTo
= Form_EmailTo
;
646 FPDF_FORMFILLINFO::FFI_DisplayCaret
= Form_DisplayCaret
;
647 FPDF_FORMFILLINFO::FFI_SetCurrentPage
= Form_SetCurrentPage
;
648 FPDF_FORMFILLINFO::FFI_GetCurrentPageIndex
= Form_GetCurrentPageIndex
;
649 FPDF_FORMFILLINFO::FFI_GetPageViewRect
= Form_GetPageViewRect
;
650 FPDF_FORMFILLINFO::FFI_GetPlatform
= Form_GetPlatform
;
651 FPDF_FORMFILLINFO::FFI_PopupMenu
= Form_PopupMenu
;
652 FPDF_FORMFILLINFO::FFI_PostRequestURL
= Form_PostRequestURL
;
653 FPDF_FORMFILLINFO::FFI_PutRequestURL
= Form_PutRequestURL
;
654 FPDF_FORMFILLINFO::FFI_UploadTo
= Form_UploadTo
;
655 FPDF_FORMFILLINFO::FFI_DownloadFromURL
= Form_DownloadFromURL
;
656 FPDF_FORMFILLINFO::FFI_OpenFile
= Form_OpenFile
;
657 FPDF_FORMFILLINFO::FFI_GotoURL
= Form_GotoURL
;
658 FPDF_FORMFILLINFO::FFI_GetLanguage
= Form_GetLanguage
;
659 #endif // PDF_USE_XFA
660 IPDF_JSPLATFORM::version
= 2;
661 IPDF_JSPLATFORM::app_alert
= Form_Alert
;
662 IPDF_JSPLATFORM::app_beep
= Form_Beep
;
663 IPDF_JSPLATFORM::app_response
= Form_Response
;
664 IPDF_JSPLATFORM::Doc_getFilePath
= Form_GetFilePath
;
665 IPDF_JSPLATFORM::Doc_mail
= Form_Mail
;
666 IPDF_JSPLATFORM::Doc_print
= Form_Print
;
667 IPDF_JSPLATFORM::Doc_submitForm
= Form_SubmitForm
;
668 IPDF_JSPLATFORM::Doc_gotoPage
= Form_GotoPage
;
669 IPDF_JSPLATFORM::Field_browse
= Form_Browse
;
670 IPDF_JSPLATFORM::m_isolate
= v8::Isolate::GetCurrent();
671 IPDF_JSPLATFORM::m_v8EmbedderSlot
= gin::kEmbedderPDFium
;
673 IFSDK_PAUSE::version
= 1;
674 IFSDK_PAUSE::user
= NULL
;
675 IFSDK_PAUSE::NeedToPauseNow
= Pause_NeedToPauseNow
;
678 PDFiumEngine::~PDFiumEngine() {
679 for (size_t i
= 0; i
< pages_
.size(); ++i
)
683 FORM_DoDocumentAAction(form_
, FPDFDOC_AACTION_WC
);
686 // XFA may require |form_| to outlive |doc_|, so shut down in that order.
687 FPDF_CloseDocument(doc_
);
688 FPDFDOC_ExitFormFillEnvironment(form_
);
690 // Normally |doc_| should outlive |form_|.
691 FPDFDOC_ExitFormFillEnvironment(form_
);
692 FPDF_CloseDocument(doc_
);
695 FPDFAvail_Destroy(fpdf_availability_
);
697 STLDeleteElements(&pages_
);
702 // This is just for testing, needs to be removed later
704 #define XFA_TESTFILE(filename) "E:/"#filename
706 #define XFA_TESTFILE(filename) "/home/"#filename
710 FPDF_FILEHANDLER file_handler
;
714 void Sample_Release(FPDF_LPVOID client_data
) {
717 FPDF_FILE
* file_wrapper
= (FPDF_FILE
*)client_data
;
718 fclose(file_wrapper
->file
);
722 FPDF_DWORD
Sample_GetSize(FPDF_LPVOID client_data
) {
725 FPDF_FILE
* file_wrapper
= (FPDF_FILE
*)client_data
;
726 long cur_pos
= ftell(file_wrapper
->file
);
729 if (fseek(file_wrapper
->file
, 0, SEEK_END
))
731 long size
= ftell(file_wrapper
->file
);
732 fseek(file_wrapper
->file
, cur_pos
, SEEK_SET
);
733 return (FPDF_DWORD
)size
;
736 FPDF_RESULT
Sample_ReadBlock(FPDF_LPVOID client_data
,
742 FPDF_FILE
* file_wrapper
= (FPDF_FILE
*)client_data
;
743 if (fseek(file_wrapper
->file
, (long)offset
, SEEK_SET
))
745 size_t read_size
= fread(buffer
, 1, size
, file_wrapper
->file
);
746 return read_size
== size
? 0 : -1;
749 FPDF_RESULT
Sample_WriteBlock(FPDF_LPVOID client_data
,
755 FPDF_FILE
* file_wrapper
= (FPDF_FILE
*)client_data
;
756 if (fseek(file_wrapper
->file
, (long)offset
, SEEK_SET
))
759 size_t write_size
= fwrite(buffer
, 1, size
, file_wrapper
->file
);
760 return write_size
== size
? 0 : -1;
763 FPDF_RESULT
Sample_Flush(FPDF_LPVOID client_data
) {
767 fflush(((FPDF_FILE
*)client_data
)->file
);
771 FPDF_RESULT
Sample_Truncate(FPDF_LPVOID client_data
, FPDF_DWORD size
) {
775 void PDFiumEngine::Form_EmailTo(FPDF_FORMFILLINFO
* param
,
776 FPDF_FILEHANDLER
* file_handler
,
778 FPDF_WIDESTRING subject
,
781 FPDF_WIDESTRING message
) {
783 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(to
));
784 std::string subject_str
=
785 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(subject
));
787 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(cc
));
788 std::string bcc_str
=
789 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(bcc
));
790 std::string message_str
=
791 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(message
));
793 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
794 engine
->client_
->Email(to_str
, cc_str
, bcc_str
, subject_str
, message_str
);
797 void PDFiumEngine::Form_DisplayCaret(FPDF_FORMFILLINFO
* param
,
804 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
805 engine
->client_
->UpdateCursor(PP_CURSORTYPE_IBEAM
);
806 std::vector
<pp::Rect
> tickmarks
;
807 pp::Rect
rect(left
, top
, right
, bottom
);
808 tickmarks
.push_back(rect
);
809 engine
->client_
->UpdateTickMarks(tickmarks
);
812 void PDFiumEngine::Form_SetCurrentPage(FPDF_FORMFILLINFO
* param
,
813 FPDF_DOCUMENT document
,
815 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
816 pp::Rect page_view_rect
= engine
->GetPageContentsRect(page
);
817 engine
->ScrolledToYPosition(page_view_rect
.height());
818 pp::Point
pos(1, page_view_rect
.height());
819 engine
->SetScrollPosition(pos
);
822 int PDFiumEngine::Form_GetCurrentPageIndex(FPDF_FORMFILLINFO
* param
,
823 FPDF_DOCUMENT document
) {
824 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
825 return engine
->GetMostVisiblePage();
828 void PDFiumEngine::Form_GetPageViewRect(FPDF_FORMFILLINFO
* param
,
834 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
835 int page_index
= engine
->GetMostVisiblePage();
836 pp::Rect page_view_rect
= engine
->GetPageContentsRect(page_index
);
838 *left
= page_view_rect
.x();
839 *right
= page_view_rect
.right();
840 *top
= page_view_rect
.y();
841 *bottom
= page_view_rect
.bottom();
844 int PDFiumEngine::Form_GetPlatform(FPDF_FORMFILLINFO
* param
,
847 int platform_flag
= -1;
851 #elif defined(__linux__)
857 std::string javascript
= "alert(\"Platform:"
858 + base::DoubleToString(platform_flag
)
861 return platform_flag
;
864 FPDF_BOOL
PDFiumEngine::Form_PopupMenu(FPDF_FORMFILLINFO
* param
,
873 FPDF_BOOL
PDFiumEngine::Form_PostRequestURL(FPDF_FORMFILLINFO
* param
,
875 FPDF_WIDESTRING data
,
876 FPDF_WIDESTRING content_type
,
877 FPDF_WIDESTRING encode
,
878 FPDF_WIDESTRING header
,
879 FPDF_BSTR
* response
) {
880 std::string url_str
=
881 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(url
));
882 std::string data_str
=
883 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(data
));
884 std::string content_type_str
=
885 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(content_type
));
886 std::string encode_str
=
887 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(encode
));
888 std::string header_str
=
889 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(header
));
891 std::string javascript
= "alert(\"Post:"
892 + url_str
+ "," + data_str
+ "," + content_type_str
+ ","
893 + encode_str
+ "," + header_str
898 FPDF_BOOL
PDFiumEngine::Form_PutRequestURL(FPDF_FORMFILLINFO
* param
,
900 FPDF_WIDESTRING data
,
901 FPDF_WIDESTRING encode
) {
902 std::string url_str
=
903 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(url
));
904 std::string data_str
=
905 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(data
));
906 std::string encode_str
=
907 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(encode
));
909 std::string javascript
= "alert(\"Put:"
910 + url_str
+ "," + data_str
+ "," + encode_str
916 void PDFiumEngine::Form_UploadTo(FPDF_FORMFILLINFO
* param
,
917 FPDF_FILEHANDLER
* file_handle
,
919 FPDF_WIDESTRING to
) {
921 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(to
));
922 // TODO: needs the full implementation of form uploading
925 FPDF_LPFILEHANDLER
PDFiumEngine::Form_DownloadFromURL(FPDF_FORMFILLINFO
* param
,
926 FPDF_WIDESTRING url
) {
927 std::string url_str
=
928 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(url
));
930 // Now should get data from url.
931 // For testing purpose, use data read from file
932 // TODO: needs the full implementation here
933 FILE* file
= fopen(XFA_TESTFILE("downloadtest.tem"), "w");
935 FPDF_FILE
* file_wrapper
= new FPDF_FILE
;
936 file_wrapper
->file
= file
;
937 file_wrapper
->file_handler
.clientData
= file_wrapper
;
938 file_wrapper
->file_handler
.Flush
= Sample_Flush
;
939 file_wrapper
->file_handler
.GetSize
= Sample_GetSize
;
940 file_wrapper
->file_handler
.ReadBlock
= Sample_ReadBlock
;
941 file_wrapper
->file_handler
.Release
= Sample_Release
;
942 file_wrapper
->file_handler
.Truncate
= Sample_Truncate
;
943 file_wrapper
->file_handler
.WriteBlock
= Sample_WriteBlock
;
945 return &file_wrapper
->file_handler
;
948 FPDF_FILEHANDLER
* PDFiumEngine::Form_OpenFile(FPDF_FORMFILLINFO
* param
,
952 std::string url_str
= "NULL";
955 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(url
));
957 // TODO: need to implement open file from the url
958 // Use a file path for the ease of testing
959 FILE* file
= fopen(XFA_TESTFILE("tem.txt"), mode
);
960 FPDF_FILE
* file_wrapper
= new FPDF_FILE
;
961 file_wrapper
->file
= file
;
962 file_wrapper
->file_handler
.clientData
= file_wrapper
;
963 file_wrapper
->file_handler
.Flush
= Sample_Flush
;
964 file_wrapper
->file_handler
.GetSize
= Sample_GetSize
;
965 file_wrapper
->file_handler
.ReadBlock
= Sample_ReadBlock
;
966 file_wrapper
->file_handler
.Release
= Sample_Release
;
967 file_wrapper
->file_handler
.Truncate
= Sample_Truncate
;
968 file_wrapper
->file_handler
.WriteBlock
= Sample_WriteBlock
;
969 return &file_wrapper
->file_handler
;
972 void PDFiumEngine::Form_GotoURL(FPDF_FORMFILLINFO
* param
,
973 FPDF_DOCUMENT document
,
974 FPDF_WIDESTRING url
) {
975 std::string url_str
=
976 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(url
));
977 // TODO: needs to implement GOTO URL action
980 int PDFiumEngine::Form_GetLanguage(FPDF_FORMFILLINFO
* param
,
986 #endif // PDF_USE_XFA
988 int PDFiumEngine::GetBlock(void* param
, unsigned long position
,
989 unsigned char* buffer
, unsigned long size
) {
990 DocumentLoader
* loader
= static_cast<DocumentLoader
*>(param
);
991 return loader
->GetBlock(position
, size
, buffer
);
994 FPDF_BOOL
PDFiumEngine::IsDataAvail(FX_FILEAVAIL
* param
,
995 size_t offset
, size_t size
) {
996 PDFiumEngine::FileAvail
* file_avail
=
997 static_cast<PDFiumEngine::FileAvail
*>(param
);
998 return file_avail
->loader
->IsDataAvailable(offset
, size
);
1001 void PDFiumEngine::AddSegment(FX_DOWNLOADHINTS
* param
,
1002 size_t offset
, size_t size
) {
1003 PDFiumEngine::DownloadHints
* download_hints
=
1004 static_cast<PDFiumEngine::DownloadHints
*>(param
);
1005 return download_hints
->loader
->RequestData(offset
, size
);
1008 bool PDFiumEngine::New(const char* url
,
1009 const char* headers
) {
1018 void PDFiumEngine::PageOffsetUpdated(const pp::Point
& page_offset
) {
1019 page_offset_
= page_offset
;
1022 void PDFiumEngine::PluginSizeUpdated(const pp::Size
& size
) {
1025 plugin_size_
= size
;
1026 CalculateVisiblePages();
1029 void PDFiumEngine::ScrolledToXPosition(int position
) {
1032 int old_x
= position_
.x();
1033 position_
.set_x(position
);
1034 CalculateVisiblePages();
1035 client_
->Scroll(pp::Point(old_x
- position
, 0));
1038 void PDFiumEngine::ScrolledToYPosition(int position
) {
1041 int old_y
= position_
.y();
1042 position_
.set_y(position
);
1043 CalculateVisiblePages();
1044 client_
->Scroll(pp::Point(0, old_y
- position
));
1047 void PDFiumEngine::PrePaint() {
1048 for (size_t i
= 0; i
< progressive_paints_
.size(); ++i
)
1049 progressive_paints_
[i
].painted_
= false;
1052 void PDFiumEngine::Paint(const pp::Rect
& rect
,
1053 pp::ImageData
* image_data
,
1054 std::vector
<pp::Rect
>* ready
,
1055 std::vector
<pp::Rect
>* pending
) {
1060 pp::Rect leftover
= rect
;
1061 for (size_t i
= 0; i
< visible_pages_
.size(); ++i
) {
1062 int index
= visible_pages_
[i
];
1063 pp::Rect page_rect
= pages_
[index
]->rect();
1064 // Convert the current page's rectangle to screen rectangle. We do this
1065 // instead of the reverse (converting the dirty rectangle from screen to
1066 // page coordinates) because then we'd have to convert back to screen
1067 // coordinates, and the rounding errors sometime leave pixels dirty or even
1068 // move the text up or down a pixel when zoomed.
1069 pp::Rect page_rect_in_screen
= GetPageScreenRect(index
);
1070 pp::Rect dirty_in_screen
= page_rect_in_screen
.Intersect(leftover
);
1071 if (dirty_in_screen
.IsEmpty())
1074 // Compute the leftover dirty region. The first page may have blank space
1075 // above it, in which case we also need to subtract that space from the
1078 pp::Rect blank_space_in_screen
= dirty_in_screen
;
1079 blank_space_in_screen
.set_y(0);
1080 blank_space_in_screen
.set_height(dirty_in_screen
.y());
1081 leftover
= leftover
.Subtract(blank_space_in_screen
);
1083 leftover
= leftover
.Subtract(dirty_in_screen
);
1085 if (pages_
[index
]->available()) {
1086 int progressive
= GetProgressiveIndex(index
);
1087 if (progressive
!= -1) {
1088 DCHECK_GE(progressive
, 0);
1089 DCHECK_LT(static_cast<size_t>(progressive
), progressive_paints_
.size());
1090 if (progressive_paints_
[progressive
].rect
!= dirty_in_screen
) {
1091 // The PDFium code can only handle one progressive paint at a time, so
1092 // queue this up. Previously we used to merge the rects when this
1093 // happened, but it made scrolling up on complex PDFs very slow since
1094 // there would be a damaged rect at the top (from scroll) and at the
1095 // bottom (from toolbar).
1096 pending
->push_back(dirty_in_screen
);
1101 if (progressive
== -1) {
1102 progressive
= StartPaint(index
, dirty_in_screen
);
1103 progressive_paint_timeout_
= kMaxInitialProgressivePaintTimeMs
;
1105 progressive_paint_timeout_
= kMaxProgressivePaintTimeMs
;
1108 progressive_paints_
[progressive
].painted_
= true;
1109 if (ContinuePaint(progressive
, image_data
)) {
1110 FinishPaint(progressive
, image_data
);
1111 ready
->push_back(dirty_in_screen
);
1113 pending
->push_back(dirty_in_screen
);
1116 PaintUnavailablePage(index
, dirty_in_screen
, image_data
);
1117 ready
->push_back(dirty_in_screen
);
1122 void PDFiumEngine::PostPaint() {
1123 for (size_t i
= 0; i
< progressive_paints_
.size(); ++i
) {
1124 if (progressive_paints_
[i
].painted_
)
1127 // This rectangle must have been merged with another one, that's why we
1128 // weren't asked to paint it. Remove it or otherwise we'll never finish
1130 FPDF_RenderPage_Close(
1131 pages_
[progressive_paints_
[i
].page_index
]->GetPage());
1132 FPDFBitmap_Destroy(progressive_paints_
[i
].bitmap
);
1133 progressive_paints_
.erase(progressive_paints_
.begin() + i
);
1138 bool PDFiumEngine::HandleDocumentLoad(const pp::URLLoader
& loader
) {
1139 password_tries_remaining_
= kMaxPasswordTries
;
1140 return doc_loader_
.Init(loader
, url_
, headers_
);
1143 pp::Instance
* PDFiumEngine::GetPluginInstance() {
1144 return client_
->GetPluginInstance();
1147 pp::URLLoader
PDFiumEngine::CreateURLLoader() {
1148 return client_
->CreateURLLoader();
1151 void PDFiumEngine::AppendPage(PDFEngine
* engine
, int index
) {
1152 // Unload and delete the blank page before appending.
1153 pages_
[index
]->Unload();
1154 pages_
[index
]->set_calculated_links(false);
1155 pp::Size curr_page_size
= GetPageSize(index
);
1156 FPDFPage_Delete(doc_
, index
);
1157 FPDF_ImportPages(doc_
,
1158 static_cast<PDFiumEngine
*>(engine
)->doc(),
1161 pp::Size new_page_size
= GetPageSize(index
);
1162 if (curr_page_size
!= new_page_size
)
1164 client_
->Invalidate(GetPageScreenRect(index
));
1167 pp::Point
PDFiumEngine::GetScrollPosition() {
1171 void PDFiumEngine::SetScrollPosition(const pp::Point
& position
) {
1172 position_
= position
;
1175 bool PDFiumEngine::IsProgressiveLoad() {
1176 return doc_loader_
.is_partial_document();
1179 void PDFiumEngine::OnPartialDocumentLoaded() {
1180 file_access_
.m_FileLen
= doc_loader_
.document_size();
1181 fpdf_availability_
= FPDFAvail_Create(&file_availability_
, &file_access_
);
1182 DCHECK(fpdf_availability_
);
1184 // Currently engine does not deal efficiently with some non-linearized files.
1185 // See http://code.google.com/p/chromium/issues/detail?id=59400
1186 // To improve user experience we download entire file for non-linearized PDF.
1187 if (!FPDFAvail_IsLinearized(fpdf_availability_
)) {
1188 doc_loader_
.RequestData(0, doc_loader_
.document_size());
1195 void PDFiumEngine::OnPendingRequestComplete() {
1196 if (!doc_
|| !form_
) {
1201 // LoadDocument() will result in |pending_pages_| being reset so there's no
1202 // need to run the code below in that case.
1203 bool update_pages
= false;
1204 std::vector
<int> still_pending
;
1205 for (size_t i
= 0; i
< pending_pages_
.size(); ++i
) {
1206 if (CheckPageAvailable(pending_pages_
[i
], &still_pending
)) {
1207 update_pages
= true;
1208 if (IsPageVisible(pending_pages_
[i
]))
1209 client_
->Invalidate(GetPageScreenRect(pending_pages_
[i
]));
1212 pending_pages_
.swap(still_pending
);
1217 void PDFiumEngine::OnNewDataAvailable() {
1218 client_
->DocumentLoadProgress(doc_loader_
.GetAvailableData(),
1219 doc_loader_
.document_size());
1222 void PDFiumEngine::OnDocumentComplete() {
1223 if (!doc_
|| !form_
) {
1224 file_access_
.m_FileLen
= doc_loader_
.document_size();
1229 bool need_update
= false;
1230 for (size_t i
= 0; i
< pages_
.size(); ++i
) {
1231 if (pages_
[i
]->available())
1234 pages_
[i
]->set_available(true);
1235 // We still need to call IsPageAvail() even if the whole document is
1236 // already downloaded.
1237 FPDFAvail_IsPageAvail(fpdf_availability_
, i
, &download_hints_
);
1239 if (IsPageVisible(i
))
1240 client_
->Invalidate(GetPageScreenRect(i
));
1245 FinishLoadingDocument();
1248 void PDFiumEngine::FinishLoadingDocument() {
1249 DCHECK(doc_loader_
.IsDocumentComplete() && doc_
);
1250 if (called_do_document_action_
)
1252 called_do_document_action_
= true;
1254 // These can only be called now, as the JS might end up needing a page.
1255 FORM_DoDocumentJSAction(form_
);
1256 FORM_DoDocumentOpenAction(form_
);
1257 if (most_visible_page_
!= -1) {
1258 FPDF_PAGE new_page
= pages_
[most_visible_page_
]->GetPage();
1259 FORM_DoPageAAction(new_page
, form_
, FPDFPAGE_AACTION_OPEN
);
1262 if (doc_
) // This can only happen if loading |doc_| fails.
1263 client_
->DocumentLoadComplete(pages_
.size());
1266 void PDFiumEngine::UnsupportedFeature(int type
) {
1267 std::string feature
;
1270 case FPDF_UNSP_DOC_XFAFORM
:
1274 case FPDF_UNSP_DOC_PORTABLECOLLECTION
:
1275 feature
= "Portfolios_Packages";
1277 case FPDF_UNSP_DOC_ATTACHMENT
:
1278 case FPDF_UNSP_ANNOT_ATTACHMENT
:
1279 feature
= "Attachment";
1281 case FPDF_UNSP_DOC_SECURITY
:
1282 feature
= "Rights_Management";
1284 case FPDF_UNSP_DOC_SHAREDREVIEW
:
1285 feature
= "Shared_Review";
1287 case FPDF_UNSP_DOC_SHAREDFORM_ACROBAT
:
1288 case FPDF_UNSP_DOC_SHAREDFORM_FILESYSTEM
:
1289 case FPDF_UNSP_DOC_SHAREDFORM_EMAIL
:
1290 feature
= "Shared_Form";
1292 case FPDF_UNSP_ANNOT_3DANNOT
:
1295 case FPDF_UNSP_ANNOT_MOVIE
:
1298 case FPDF_UNSP_ANNOT_SOUND
:
1301 case FPDF_UNSP_ANNOT_SCREEN_MEDIA
:
1302 case FPDF_UNSP_ANNOT_SCREEN_RICHMEDIA
:
1305 case FPDF_UNSP_ANNOT_SIG
:
1306 feature
= "Digital_Signature";
1309 client_
->DocumentHasUnsupportedFeature(feature
);
1312 void PDFiumEngine::ContinueFind(int32_t result
) {
1313 StartFind(current_find_text_
.c_str(), !!result
);
1316 bool PDFiumEngine::HandleEvent(const pp::InputEvent
& event
) {
1317 DCHECK(!defer_page_unload_
);
1318 defer_page_unload_
= true;
1320 switch (event
.GetType()) {
1321 case PP_INPUTEVENT_TYPE_MOUSEDOWN
:
1322 rv
= OnMouseDown(pp::MouseInputEvent(event
));
1324 case PP_INPUTEVENT_TYPE_MOUSEUP
:
1325 rv
= OnMouseUp(pp::MouseInputEvent(event
));
1327 case PP_INPUTEVENT_TYPE_MOUSEMOVE
:
1328 rv
= OnMouseMove(pp::MouseInputEvent(event
));
1330 case PP_INPUTEVENT_TYPE_KEYDOWN
:
1331 rv
= OnKeyDown(pp::KeyboardInputEvent(event
));
1333 case PP_INPUTEVENT_TYPE_KEYUP
:
1334 rv
= OnKeyUp(pp::KeyboardInputEvent(event
));
1336 case PP_INPUTEVENT_TYPE_CHAR
:
1337 rv
= OnChar(pp::KeyboardInputEvent(event
));
1343 DCHECK(defer_page_unload_
);
1344 defer_page_unload_
= false;
1345 for (size_t i
= 0; i
< deferred_page_unloads_
.size(); ++i
)
1346 pages_
[deferred_page_unloads_
[i
]]->Unload();
1347 deferred_page_unloads_
.clear();
1351 uint32_t PDFiumEngine::QuerySupportedPrintOutputFormats() {
1352 if (!HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
))
1354 return PP_PRINTOUTPUTFORMAT_PDF
;
1357 void PDFiumEngine::PrintBegin() {
1358 FORM_DoDocumentAAction(form_
, FPDFDOC_AACTION_WP
);
1361 pp::Resource
PDFiumEngine::PrintPages(
1362 const PP_PrintPageNumberRange_Dev
* page_ranges
, uint32_t page_range_count
,
1363 const PP_PrintSettings_Dev
& print_settings
) {
1364 if (HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY
))
1365 return PrintPagesAsPDF(page_ranges
, page_range_count
, print_settings
);
1366 else if (HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
))
1367 return PrintPagesAsRasterPDF(page_ranges
, page_range_count
, print_settings
);
1368 return pp::Resource();
1371 FPDF_DOCUMENT
PDFiumEngine::CreateSinglePageRasterPdf(
1372 double source_page_width
,
1373 double source_page_height
,
1374 const PP_PrintSettings_Dev
& print_settings
,
1375 PDFiumPage
* page_to_print
) {
1376 FPDF_DOCUMENT temp_doc
= FPDF_CreateNewDocument();
1380 const pp::Size
& bitmap_size(page_to_print
->rect().size());
1382 FPDF_PAGE temp_page
=
1383 FPDFPage_New(temp_doc
, 0, source_page_width
, source_page_height
);
1385 pp::ImageData image
= pp::ImageData(client_
->GetPluginInstance(),
1386 PP_IMAGEDATAFORMAT_BGRA_PREMUL
,
1390 FPDF_BITMAP bitmap
= FPDFBitmap_CreateEx(bitmap_size
.width(),
1391 bitmap_size
.height(),
1397 FPDFBitmap_FillRect(
1398 bitmap
, 0, 0, bitmap_size
.width(), bitmap_size
.height(), 0xFFFFFFFF);
1400 pp::Rect page_rect
= page_to_print
->rect();
1401 FPDF_RenderPageBitmap(bitmap
,
1402 page_to_print
->GetPrintPage(),
1407 print_settings
.orientation
,
1408 FPDF_ANNOT
| FPDF_PRINTING
| FPDF_NO_CATCH
);
1410 double ratio_x
= ConvertUnitDouble(bitmap_size
.width(),
1413 double ratio_y
= ConvertUnitDouble(bitmap_size
.height(),
1417 // Add the bitmap to an image object and add the image object to the output
1419 FPDF_PAGEOBJECT temp_img
= FPDFPageObj_NewImgeObj(temp_doc
);
1420 FPDFImageObj_SetBitmap(&temp_page
, 1, temp_img
, bitmap
);
1421 FPDFImageObj_SetMatrix(temp_img
, ratio_x
, 0, 0, ratio_y
, 0, 0);
1422 FPDFPage_InsertObject(temp_page
, temp_img
);
1423 FPDFPage_GenerateContent(temp_page
);
1424 FPDF_ClosePage(temp_page
);
1426 page_to_print
->ClosePrintPage();
1427 FPDFBitmap_Destroy(bitmap
);
1432 pp::Buffer_Dev
PDFiumEngine::PrintPagesAsRasterPDF(
1433 const PP_PrintPageNumberRange_Dev
* page_ranges
, uint32_t page_range_count
,
1434 const PP_PrintSettings_Dev
& print_settings
) {
1435 if (!page_range_count
)
1436 return pp::Buffer_Dev();
1438 // If document is not downloaded yet, disable printing.
1439 if (doc_
&& !doc_loader_
.IsDocumentComplete())
1440 return pp::Buffer_Dev();
1442 FPDF_DOCUMENT output_doc
= FPDF_CreateNewDocument();
1444 return pp::Buffer_Dev();
1446 SaveSelectedFormForPrint();
1448 std::vector
<PDFiumPage
> pages_to_print
;
1449 // width and height of source PDF pages.
1450 std::vector
<std::pair
<double, double> > source_page_sizes
;
1451 // Collect pages to print and sizes of source pages.
1452 std::vector
<uint32_t> page_numbers
=
1453 GetPageNumbersFromPrintPageNumberRange(page_ranges
, page_range_count
);
1454 for (size_t i
= 0; i
< page_numbers
.size(); ++i
) {
1455 uint32_t page_number
= page_numbers
[i
];
1456 FPDF_PAGE pdf_page
= FPDF_LoadPage(doc_
, page_number
);
1457 double source_page_width
= FPDF_GetPageWidth(pdf_page
);
1458 double source_page_height
= FPDF_GetPageHeight(pdf_page
);
1459 source_page_sizes
.push_back(std::make_pair(source_page_width
,
1460 source_page_height
));
1462 int width_in_pixels
= ConvertUnit(source_page_width
,
1464 print_settings
.dpi
);
1465 int height_in_pixels
= ConvertUnit(source_page_height
,
1467 print_settings
.dpi
);
1469 pp::Rect
rect(width_in_pixels
, height_in_pixels
);
1470 pages_to_print
.push_back(PDFiumPage(this, page_number
, rect
, true));
1471 FPDF_ClosePage(pdf_page
);
1474 #if defined(OS_LINUX)
1475 g_last_instance_id
= client_
->GetPluginInstance()->pp_instance();
1479 for (; i
< pages_to_print
.size(); ++i
) {
1480 double source_page_width
= source_page_sizes
[i
].first
;
1481 double source_page_height
= source_page_sizes
[i
].second
;
1483 // Use temp_doc to compress image by saving PDF to buffer.
1484 FPDF_DOCUMENT temp_doc
= CreateSinglePageRasterPdf(source_page_width
,
1487 &pages_to_print
[i
]);
1492 pp::Buffer_Dev buffer
= GetFlattenedPrintData(temp_doc
);
1493 FPDF_CloseDocument(temp_doc
);
1495 PDFiumMemBufferFileRead
file_read(buffer
.data(), buffer
.size());
1496 temp_doc
= FPDF_LoadCustomDocument(&file_read
, NULL
);
1498 FPDF_BOOL imported
= FPDF_ImportPages(output_doc
, temp_doc
, "1", i
);
1499 FPDF_CloseDocument(temp_doc
);
1504 pp::Buffer_Dev buffer
;
1505 if (i
== pages_to_print
.size()) {
1506 FPDF_CopyViewerPreferences(output_doc
, doc_
);
1507 FitContentsToPrintableAreaIfRequired(output_doc
, print_settings
);
1508 // Now flatten all the output pages.
1509 buffer
= GetFlattenedPrintData(output_doc
);
1511 FPDF_CloseDocument(output_doc
);
1515 pp::Buffer_Dev
PDFiumEngine::GetFlattenedPrintData(const FPDF_DOCUMENT
& doc
) {
1516 int page_count
= FPDF_GetPageCount(doc
);
1517 bool flatten_succeeded
= true;
1518 for (int i
= 0; i
< page_count
; ++i
) {
1519 FPDF_PAGE page
= FPDF_LoadPage(doc
, i
);
1522 int flatten_ret
= FPDFPage_Flatten(page
, FLAT_PRINT
);
1523 FPDF_ClosePage(page
);
1524 if (flatten_ret
== FLATTEN_FAIL
) {
1525 flatten_succeeded
= false;
1529 flatten_succeeded
= false;
1533 if (!flatten_succeeded
) {
1534 FPDF_CloseDocument(doc
);
1535 return pp::Buffer_Dev();
1538 pp::Buffer_Dev buffer
;
1539 PDFiumMemBufferFileWrite output_file_write
;
1540 if (FPDF_SaveAsCopy(doc
, &output_file_write
, 0)) {
1541 buffer
= pp::Buffer_Dev(
1542 client_
->GetPluginInstance(), output_file_write
.size());
1543 if (!buffer
.is_null()) {
1544 memcpy(buffer
.data(), output_file_write
.buffer().c_str(),
1545 output_file_write
.size());
1551 pp::Buffer_Dev
PDFiumEngine::PrintPagesAsPDF(
1552 const PP_PrintPageNumberRange_Dev
* page_ranges
, uint32_t page_range_count
,
1553 const PP_PrintSettings_Dev
& print_settings
) {
1554 if (!page_range_count
)
1555 return pp::Buffer_Dev();
1558 FPDF_DOCUMENT output_doc
= FPDF_CreateNewDocument();
1560 return pp::Buffer_Dev();
1562 SaveSelectedFormForPrint();
1564 std::string page_number_str
;
1565 for (uint32_t index
= 0; index
< page_range_count
; ++index
) {
1566 if (!page_number_str
.empty())
1567 page_number_str
.append(",");
1568 page_number_str
.append(
1569 base::IntToString(page_ranges
[index
].first_page_number
+ 1));
1570 if (page_ranges
[index
].first_page_number
!=
1571 page_ranges
[index
].last_page_number
) {
1572 page_number_str
.append("-");
1573 page_number_str
.append(
1574 base::IntToString(page_ranges
[index
].last_page_number
+ 1));
1578 std::vector
<uint32_t> page_numbers
=
1579 GetPageNumbersFromPrintPageNumberRange(page_ranges
, page_range_count
);
1580 for (size_t i
= 0; i
< page_numbers
.size(); ++i
) {
1581 uint32_t page_number
= page_numbers
[i
];
1582 pages_
[page_number
]->GetPage();
1583 if (!IsPageVisible(page_numbers
[i
]))
1584 pages_
[page_number
]->Unload();
1587 FPDF_CopyViewerPreferences(output_doc
, doc_
);
1588 if (!FPDF_ImportPages(output_doc
, doc_
, page_number_str
.c_str(), 0)) {
1589 FPDF_CloseDocument(output_doc
);
1590 return pp::Buffer_Dev();
1593 FitContentsToPrintableAreaIfRequired(output_doc
, print_settings
);
1595 // Now flatten all the output pages.
1596 pp::Buffer_Dev buffer
= GetFlattenedPrintData(output_doc
);
1597 FPDF_CloseDocument(output_doc
);
1601 void PDFiumEngine::FitContentsToPrintableAreaIfRequired(
1602 const FPDF_DOCUMENT
& doc
, const PP_PrintSettings_Dev
& print_settings
) {
1603 // Check to see if we need to fit pdf contents to printer paper size.
1604 if (print_settings
.print_scaling_option
!=
1605 PP_PRINTSCALINGOPTION_SOURCE_SIZE
) {
1606 int num_pages
= FPDF_GetPageCount(doc
);
1607 // In-place transformation is more efficient than creating a new
1608 // transformed document from the source document. Therefore, transform
1609 // every page to fit the contents in the selected printer paper.
1610 for (int i
= 0; i
< num_pages
; ++i
) {
1611 FPDF_PAGE page
= FPDF_LoadPage(doc
, i
);
1612 TransformPDFPageForPrinting(page
, print_settings
);
1613 FPDF_ClosePage(page
);
1618 void PDFiumEngine::SaveSelectedFormForPrint() {
1619 FORM_ForceToKillFocus(form_
);
1620 client_
->FormTextFieldFocusChange(false);
1623 void PDFiumEngine::PrintEnd() {
1624 FORM_DoDocumentAAction(form_
, FPDFDOC_AACTION_DP
);
1627 PDFiumPage::Area
PDFiumEngine::GetCharIndex(const pp::MouseInputEvent
& event
,
1631 PDFiumPage::LinkTarget
* target
) {
1632 // First figure out which page this is in.
1633 pp::Point mouse_point
= event
.GetPosition();
1634 return GetCharIndex(mouse_point
, page_index
, char_index
, form_type
, target
);
1637 PDFiumPage::Area
PDFiumEngine::GetCharIndex(const pp::Point
& point
,
1641 PDFiumPage::LinkTarget
* target
) {
1643 pp::Point
point_in_page(
1644 static_cast<int>((point
.x() + position_
.x()) / current_zoom_
),
1645 static_cast<int>((point
.y() + position_
.y()) / current_zoom_
));
1646 for (size_t i
= 0; i
< visible_pages_
.size(); ++i
) {
1647 if (pages_
[visible_pages_
[i
]]->rect().Contains(point_in_page
)) {
1648 page
= visible_pages_
[i
];
1653 return PDFiumPage::NONSELECTABLE_AREA
;
1655 // If the page hasn't finished rendering, calling into the page sometimes
1657 for (size_t i
= 0; i
< progressive_paints_
.size(); ++i
) {
1658 if (progressive_paints_
[i
].page_index
== page
)
1659 return PDFiumPage::NONSELECTABLE_AREA
;
1663 return pages_
[page
]->GetCharIndex(
1664 point_in_page
, current_rotation_
, char_index
, form_type
, target
);
1667 bool PDFiumEngine::OnMouseDown(const pp::MouseInputEvent
& event
) {
1668 if (event
.GetButton() == PP_INPUTEVENT_MOUSEBUTTON_RIGHT
) {
1669 if (!selection_
.size())
1671 std::vector
<pp::Rect
> selection_rect_vector
;
1672 GetAllScreenRectsUnion(&selection_
, GetVisibleRect().point(),
1673 &selection_rect_vector
);
1674 pp::Point point
= event
.GetPosition();
1675 for (size_t i
= 0; i
< selection_rect_vector
.size(); ++i
) {
1676 if (selection_rect_vector
[i
].Contains(point
.x(), point
.y()))
1679 SelectionChangeInvalidator
selection_invalidator(this);
1683 if (event
.GetButton() != PP_INPUTEVENT_MOUSEBUTTON_LEFT
)
1686 SelectionChangeInvalidator
selection_invalidator(this);
1689 int page_index
= -1;
1690 int char_index
= -1;
1691 int form_type
= FPDF_FORMFIELD_UNKNOWN
;
1692 PDFiumPage::LinkTarget target
;
1693 PDFiumPage::Area area
=
1694 GetCharIndex(event
, &page_index
, &char_index
, &form_type
, &target
);
1695 mouse_down_state_
.Set(area
, target
);
1697 // Decide whether to open link or not based on user action in mouse up and
1698 // mouse move events.
1699 if (area
== PDFiumPage::WEBLINK_AREA
)
1702 if (area
== PDFiumPage::DOCLINK_AREA
) {
1703 client_
->ScrollToPage(target
.page
);
1704 client_
->FormTextFieldFocusChange(false);
1708 if (page_index
!= -1) {
1709 last_page_mouse_down_
= page_index
;
1710 double page_x
, page_y
;
1711 pp::Point point
= event
.GetPosition();
1712 DeviceToPage(page_index
, point
.x(), point
.y(), &page_x
, &page_y
);
1714 FORM_OnLButtonDown(form_
, pages_
[page_index
]->GetPage(), 0, page_x
, page_y
);
1715 if (form_type
> FPDF_FORMFIELD_UNKNOWN
) { // returns -1 sometimes...
1716 mouse_down_state_
.Set(PDFiumPage::NONSELECTABLE_AREA
, target
);
1717 bool is_valid_control
= (form_type
== FPDF_FORMFIELD_TEXTFIELD
||
1718 form_type
== FPDF_FORMFIELD_COMBOBOX
);
1720 is_valid_control
|= (form_type
== FPDF_FORMFIELD_XFA
);
1722 client_
->FormTextFieldFocusChange(is_valid_control
);
1723 return true; // Return now before we get into the selection code.
1727 client_
->FormTextFieldFocusChange(false);
1729 if (area
!= PDFiumPage::TEXT_AREA
)
1730 return true; // Return true so WebKit doesn't do its own highlighting.
1732 if (event
.GetClickCount() == 1) {
1733 OnSingleClick(page_index
, char_index
);
1734 } else if (event
.GetClickCount() == 2 ||
1735 event
.GetClickCount() == 3) {
1736 OnMultipleClick(event
.GetClickCount(), page_index
, char_index
);
1742 void PDFiumEngine::OnSingleClick(int page_index
, int char_index
) {
1744 selection_
.push_back(PDFiumRange(pages_
[page_index
], char_index
, 0));
1747 void PDFiumEngine::OnMultipleClick(int click_count
,
1750 // It would be more efficient if the SDK could support finding a space, but
1752 int start_index
= char_index
;
1754 base::char16 cur
= pages_
[page_index
]->GetCharAtIndex(start_index
);
1755 // For double click, we want to select one word so we look for whitespace
1756 // boundaries. For triple click, we want the whole line.
1757 if (cur
== '\n' || (click_count
== 2 && (cur
== ' ' || cur
== '\t')))
1759 } while (--start_index
>= 0);
1763 int end_index
= char_index
;
1764 int total
= pages_
[page_index
]->GetCharCount();
1765 while (end_index
++ <= total
) {
1766 base::char16 cur
= pages_
[page_index
]->GetCharAtIndex(end_index
);
1767 if (cur
== '\n' || (click_count
== 2 && (cur
== ' ' || cur
== '\t')))
1771 selection_
.push_back(PDFiumRange(
1772 pages_
[page_index
], start_index
, end_index
- start_index
));
1775 bool PDFiumEngine::OnMouseUp(const pp::MouseInputEvent
& event
) {
1776 if (event
.GetButton() != PP_INPUTEVENT_MOUSEBUTTON_LEFT
)
1779 int page_index
= -1;
1780 int char_index
= -1;
1781 int form_type
= FPDF_FORMFIELD_UNKNOWN
;
1782 PDFiumPage::LinkTarget target
;
1783 PDFiumPage::Area area
=
1784 GetCharIndex(event
, &page_index
, &char_index
, &form_type
, &target
);
1786 // Open link on mouse up for same link for which mouse down happened earlier.
1787 if (mouse_down_state_
.Matches(area
, target
)) {
1788 if (area
== PDFiumPage::WEBLINK_AREA
) {
1789 bool open_in_new_tab
= !!(event
.GetModifiers() & kDefaultKeyModifier
);
1790 client_
->NavigateTo(target
.url
, open_in_new_tab
);
1791 client_
->FormTextFieldFocusChange(false);
1796 if (page_index
!= -1) {
1797 double page_x
, page_y
;
1798 pp::Point point
= event
.GetPosition();
1799 DeviceToPage(page_index
, point
.x(), point
.y(), &page_x
, &page_y
);
1801 form_
, pages_
[page_index
]->GetPage(), 0, page_x
, page_y
);
1807 SetSelecting(false);
1811 bool PDFiumEngine::OnMouseMove(const pp::MouseInputEvent
& event
) {
1812 int page_index
= -1;
1813 int char_index
= -1;
1814 int form_type
= FPDF_FORMFIELD_UNKNOWN
;
1815 PDFiumPage::LinkTarget target
;
1816 PDFiumPage::Area area
=
1817 GetCharIndex(event
, &page_index
, &char_index
, &form_type
, &target
);
1819 // Clear |mouse_down_state_| if mouse moves away from where the mouse down
1821 if (!mouse_down_state_
.Matches(area
, target
))
1822 mouse_down_state_
.Reset();
1825 PP_CursorType_Dev cursor
;
1827 case PDFiumPage::TEXT_AREA
:
1828 cursor
= PP_CURSORTYPE_IBEAM
;
1830 case PDFiumPage::WEBLINK_AREA
:
1831 case PDFiumPage::DOCLINK_AREA
:
1832 cursor
= PP_CURSORTYPE_HAND
;
1834 case PDFiumPage::NONSELECTABLE_AREA
:
1836 switch (form_type
) {
1837 case FPDF_FORMFIELD_PUSHBUTTON
:
1838 case FPDF_FORMFIELD_CHECKBOX
:
1839 case FPDF_FORMFIELD_RADIOBUTTON
:
1840 case FPDF_FORMFIELD_COMBOBOX
:
1841 case FPDF_FORMFIELD_LISTBOX
:
1842 cursor
= PP_CURSORTYPE_HAND
;
1844 case FPDF_FORMFIELD_TEXTFIELD
:
1845 cursor
= PP_CURSORTYPE_IBEAM
;
1848 cursor
= PP_CURSORTYPE_POINTER
;
1854 if (page_index
!= -1) {
1855 double page_x
, page_y
;
1856 pp::Point point
= event
.GetPosition();
1857 DeviceToPage(page_index
, point
.x(), point
.y(), &page_x
, &page_y
);
1858 FORM_OnMouseMove(form_
, pages_
[page_index
]->GetPage(), 0, page_x
, page_y
);
1861 client_
->UpdateCursor(cursor
);
1862 pp::Point point
= event
.GetPosition();
1863 std::string url
= GetLinkAtPosition(event
.GetPosition());
1864 if (url
!= link_under_cursor_
) {
1865 link_under_cursor_
= url
;
1866 pp::PDF::SetLinkUnderCursor(GetPluginInstance(), url
.c_str());
1868 // No need to swallow the event, since this might interfere with the
1869 // scrollbars if the user is dragging them.
1873 // We're selecting but right now we're not over text, so don't change the
1874 // current selection.
1875 if (area
!= PDFiumPage::TEXT_AREA
&& area
!= PDFiumPage::WEBLINK_AREA
&&
1876 area
!= PDFiumPage::DOCLINK_AREA
) {
1880 SelectionChangeInvalidator
selection_invalidator(this);
1882 // Check if the user has descreased their selection area and we need to remove
1883 // pages from selection_.
1884 for (size_t i
= 0; i
< selection_
.size(); ++i
) {
1885 if (selection_
[i
].page_index() == page_index
) {
1886 // There should be no other pages after this.
1887 selection_
.erase(selection_
.begin() + i
+ 1, selection_
.end());
1892 if (selection_
.size() == 0)
1895 int last
= selection_
.size() - 1;
1896 if (selection_
[last
].page_index() == page_index
) {
1897 // Selecting within a page.
1899 if (char_index
>= selection_
[last
].char_index()) {
1900 // Selecting forward.
1901 count
= char_index
- selection_
[last
].char_index() + 1;
1903 count
= char_index
- selection_
[last
].char_index() - 1;
1905 selection_
[last
].SetCharCount(count
);
1906 } else if (selection_
[last
].page_index() < page_index
) {
1907 // Selecting into the next page.
1909 // First make sure that there are no gaps in selection, i.e. if mousedown on
1910 // page one but we only get mousemove over page three, we want page two.
1911 for (int i
= selection_
[last
].page_index() + 1; i
< page_index
; ++i
) {
1912 selection_
.push_back(PDFiumRange(pages_
[i
], 0,
1913 pages_
[i
]->GetCharCount()));
1916 int count
= pages_
[selection_
[last
].page_index()]->GetCharCount();
1917 selection_
[last
].SetCharCount(count
- selection_
[last
].char_index());
1918 selection_
.push_back(PDFiumRange(pages_
[page_index
], 0, char_index
));
1920 // Selecting into the previous page.
1921 // The selection's char_index is 0-based, so the character count is one
1922 // more than the index. The character count needs to be negative to
1923 // indicate a backwards selection.
1924 selection_
[last
].SetCharCount(-(selection_
[last
].char_index() + 1));
1926 // First make sure that there are no gaps in selection, i.e. if mousedown on
1927 // page three but we only get mousemove over page one, we want page two.
1928 for (int i
= selection_
[last
].page_index() - 1; i
> page_index
; --i
) {
1929 selection_
.push_back(PDFiumRange(pages_
[i
], 0,
1930 pages_
[i
]->GetCharCount()));
1933 int count
= pages_
[page_index
]->GetCharCount();
1934 selection_
.push_back(
1935 PDFiumRange(pages_
[page_index
], count
, count
- char_index
));
1941 bool PDFiumEngine::OnKeyDown(const pp::KeyboardInputEvent
& event
) {
1942 if (last_page_mouse_down_
== -1)
1945 bool rv
= !!FORM_OnKeyDown(
1946 form_
, pages_
[last_page_mouse_down_
]->GetPage(),
1947 event
.GetKeyCode(), event
.GetModifiers());
1949 if (event
.GetKeyCode() == ui::VKEY_BACK
||
1950 event
.GetKeyCode() == ui::VKEY_ESCAPE
) {
1951 // Chrome doesn't send char events for backspace or escape keys, see
1952 // PlatformKeyboardEventBuilder::isCharacterKey() and
1953 // http://chrome-corpsvn.mtv.corp.google.com/viewvc?view=rev&root=chrome&revision=31805
1954 // for more information. So just fake one since PDFium uses it.
1956 str
.push_back(event
.GetKeyCode());
1957 pp::KeyboardInputEvent
synthesized(pp::KeyboardInputEvent(
1958 client_
->GetPluginInstance(),
1959 PP_INPUTEVENT_TYPE_CHAR
,
1960 event
.GetTimeStamp(),
1961 event
.GetModifiers(),
1964 OnChar(synthesized
);
1970 bool PDFiumEngine::OnKeyUp(const pp::KeyboardInputEvent
& event
) {
1971 if (last_page_mouse_down_
== -1)
1974 return !!FORM_OnKeyUp(
1975 form_
, pages_
[last_page_mouse_down_
]->GetPage(),
1976 event
.GetKeyCode(), event
.GetModifiers());
1979 bool PDFiumEngine::OnChar(const pp::KeyboardInputEvent
& event
) {
1980 if (last_page_mouse_down_
== -1)
1983 base::string16 str
= base::UTF8ToUTF16(event
.GetCharacterText().AsString());
1984 return !!FORM_OnChar(
1985 form_
, pages_
[last_page_mouse_down_
]->GetPage(),
1987 event
.GetModifiers());
1990 void PDFiumEngine::StartFind(const char* text
, bool case_sensitive
) {
1991 // We can get a call to StartFind before we have any page information (i.e.
1992 // before the first call to LoadDocument has happened). Handle this case.
1996 bool first_search
= false;
1997 int character_to_start_searching_from
= 0;
1998 if (current_find_text_
!= text
) { // First time we search for this text.
1999 first_search
= true;
2000 std::vector
<PDFiumRange
> old_selection
= selection_
;
2002 current_find_text_
= text
;
2004 if (old_selection
.empty()) {
2005 // Start searching from the beginning of the document.
2006 next_page_to_search_
= 0;
2007 last_page_to_search_
= pages_
.size() - 1;
2008 last_character_index_to_search_
= -1;
2010 // There's a current selection, so start from it.
2011 next_page_to_search_
= old_selection
[0].page_index();
2012 last_character_index_to_search_
= old_selection
[0].char_index();
2013 character_to_start_searching_from
= old_selection
[0].char_index();
2014 last_page_to_search_
= next_page_to_search_
;
2018 int current_page
= next_page_to_search_
;
2020 if (pages_
[current_page
]->available()) {
2021 base::string16 str
= base::UTF8ToUTF16(text
);
2022 // Don't use PDFium to search for now, since it doesn't support unicode
2023 // text. Leave the code for now to avoid bit-rot, in case it's fixed later.
2026 str
, case_sensitive
, first_search
, character_to_start_searching_from
,
2030 str
, case_sensitive
, first_search
, character_to_start_searching_from
,
2034 if (!IsPageVisible(current_page
))
2035 pages_
[current_page
]->Unload();
2038 if (next_page_to_search_
!= last_page_to_search_
||
2039 (first_search
&& last_character_index_to_search_
!= -1)) {
2040 ++next_page_to_search_
;
2043 if (next_page_to_search_
== static_cast<int>(pages_
.size()))
2044 next_page_to_search_
= 0;
2045 // If there's only one page in the document and we start searching midway,
2046 // then we'll want to search the page one more time.
2047 bool end_of_search
=
2048 next_page_to_search_
== last_page_to_search_
&&
2049 // Only one page but didn't start midway.
2050 ((pages_
.size() == 1 && last_character_index_to_search_
== -1) ||
2051 // Started midway, but only 1 page and we already looped around.
2052 (pages_
.size() == 1 && !first_search
) ||
2053 // Started midway, and we've just looped around.
2054 (pages_
.size() > 1 && current_page
== next_page_to_search_
));
2056 if (end_of_search
) {
2057 // Send the final notification.
2058 client_
->NotifyNumberOfFindResultsChanged(find_results_
.size(), true);
2060 // When searching is complete, resume finding at a particular index.
2061 // Assuming the user has not clicked the find button in the meanwhile.
2062 if (resume_find_index_
.valid() && !current_find_index_
.valid()) {
2063 size_t resume_index
= resume_find_index_
.GetIndex();
2064 if (resume_index
>= find_results_
.size()) {
2065 // This might happen if the PDF has some dynamically generated text?
2068 current_find_index_
.SetIndex(resume_index
);
2069 client_
->NotifySelectedFindResultChanged(resume_index
);
2071 resume_find_index_
.Invalidate();
2073 pp::CompletionCallback callback
=
2074 find_factory_
.NewCallback(&PDFiumEngine::ContinueFind
);
2075 pp::Module::Get()->core()->CallOnMainThread(
2076 0, callback
, case_sensitive
? 1 : 0);
2080 void PDFiumEngine::SearchUsingPDFium(const base::string16
& term
,
2081 bool case_sensitive
,
2083 int character_to_start_searching_from
,
2085 // Find all the matches in the current page.
2086 unsigned long flags
= case_sensitive
? FPDF_MATCHCASE
: 0;
2087 FPDF_SCHHANDLE find
= FPDFText_FindStart(
2088 pages_
[current_page
]->GetTextPage(),
2089 reinterpret_cast<const unsigned short*>(term
.c_str()),
2090 flags
, character_to_start_searching_from
);
2092 // Note: since we search one page at a time, we don't find matches across
2093 // page boundaries. We could do this manually ourself, but it seems low
2094 // priority since Reader itself doesn't do it.
2095 while (FPDFText_FindNext(find
)) {
2096 PDFiumRange
result(pages_
[current_page
],
2097 FPDFText_GetSchResultIndex(find
),
2098 FPDFText_GetSchCount(find
));
2100 if (!first_search
&&
2101 last_character_index_to_search_
!= -1 &&
2102 result
.page_index() == last_page_to_search_
&&
2103 result
.char_index() >= last_character_index_to_search_
) {
2107 AddFindResult(result
);
2110 FPDFText_FindClose(find
);
2113 void PDFiumEngine::SearchUsingICU(const base::string16
& term
,
2114 bool case_sensitive
,
2116 int character_to_start_searching_from
,
2118 base::string16 page_text
;
2119 int text_length
= pages_
[current_page
]->GetCharCount();
2120 if (character_to_start_searching_from
) {
2121 text_length
-= character_to_start_searching_from
;
2122 } else if (!first_search
&&
2123 last_character_index_to_search_
!= -1 &&
2124 current_page
== last_page_to_search_
) {
2125 text_length
= last_character_index_to_search_
;
2127 if (text_length
<= 0)
2130 PDFiumAPIStringBufferAdapter
<base::string16
> api_string_adapter(&page_text
,
2133 unsigned short* data
=
2134 reinterpret_cast<unsigned short*>(api_string_adapter
.GetData());
2135 int written
= FPDFText_GetText(pages_
[current_page
]->GetTextPage(),
2136 character_to_start_searching_from
,
2139 api_string_adapter
.Close(written
);
2141 std::vector
<PDFEngine::Client::SearchStringResult
> results
;
2142 client_
->SearchString(
2143 page_text
.c_str(), term
.c_str(), case_sensitive
, &results
);
2144 for (size_t i
= 0; i
< results
.size(); ++i
) {
2145 // Need to map the indexes from the page text, which may have generated
2146 // characters like space etc, to character indices from the page.
2147 int temp_start
= results
[i
].start_index
+ character_to_start_searching_from
;
2148 int start
= FPDFText_GetCharIndexFromTextIndex(
2149 pages_
[current_page
]->GetTextPage(), temp_start
);
2150 int end
= FPDFText_GetCharIndexFromTextIndex(
2151 pages_
[current_page
]->GetTextPage(),
2152 temp_start
+ results
[i
].length
);
2153 AddFindResult(PDFiumRange(pages_
[current_page
], start
, end
- start
));
2157 void PDFiumEngine::AddFindResult(const PDFiumRange
& result
) {
2158 // Figure out where to insert the new location, since we could have
2159 // started searching midway and now we wrapped.
2160 size_t result_index
;
2161 int page_index
= result
.page_index();
2162 int char_index
= result
.char_index();
2163 for (result_index
= 0; result_index
< find_results_
.size(); ++result_index
) {
2164 if (find_results_
[result_index
].page_index() > page_index
||
2165 (find_results_
[result_index
].page_index() == page_index
&&
2166 find_results_
[result_index
].char_index() > char_index
)) {
2170 find_results_
.insert(find_results_
.begin() + result_index
, result
);
2173 if (current_find_index_
.valid()) {
2174 if (result_index
<= current_find_index_
.GetIndex()) {
2175 // Update the current match index
2176 size_t find_index
= current_find_index_
.IncrementIndex();
2177 DCHECK_LT(find_index
, find_results_
.size());
2178 client_
->NotifySelectedFindResultChanged(current_find_index_
.GetIndex());
2180 } else if (!resume_find_index_
.valid()) {
2181 // Both indices are invalid. Select the first match.
2182 SelectFindResult(true);
2184 client_
->NotifyNumberOfFindResultsChanged(find_results_
.size(), false);
2187 bool PDFiumEngine::SelectFindResult(bool forward
) {
2188 if (find_results_
.empty()) {
2193 SelectionChangeInvalidator
selection_invalidator(this);
2195 // Move back/forward through the search locations we previously found.
2197 const size_t last_index
= find_results_
.size() - 1;
2198 if (current_find_index_
.valid()) {
2199 size_t current_index
= current_find_index_
.GetIndex();
2201 new_index
= (current_index
>= last_index
) ? 0 : current_index
+ 1;
2203 new_index
= (current_find_index_
.GetIndex() == 0) ?
2204 last_index
: current_index
- 1;
2207 new_index
= forward
? 0 : last_index
;
2209 current_find_index_
.SetIndex(new_index
);
2211 // Update the selection before telling the client to scroll, since it could
2214 selection_
.push_back(find_results_
[current_find_index_
.GetIndex()]);
2216 // If the result is not in view, scroll to it.
2217 pp::Rect bounding_rect
;
2218 pp::Rect visible_rect
= GetVisibleRect();
2219 // Use zoom of 1.0 since visible_rect is without zoom.
2220 std::vector
<pp::Rect
> rects
;
2221 rects
= find_results_
[current_find_index_
.GetIndex()].GetScreenRects(
2222 pp::Point(), 1.0, current_rotation_
);
2223 for (size_t i
= 0; i
< rects
.size(); ++i
)
2224 bounding_rect
= bounding_rect
.Union(rects
[i
]);
2225 if (!visible_rect
.Contains(bounding_rect
)) {
2226 pp::Point center
= bounding_rect
.CenterPoint();
2227 // Make the page centered.
2228 int new_y
= static_cast<int>(center
.y() * current_zoom_
) -
2229 static_cast<int>(visible_rect
.height() * current_zoom_
/ 2);
2232 client_
->ScrollToY(new_y
);
2234 // Only move horizontally if it's not visible.
2235 if (center
.x() < visible_rect
.x() || center
.x() > visible_rect
.right()) {
2236 int new_x
= static_cast<int>(center
.x() * current_zoom_
) -
2237 static_cast<int>(visible_rect
.width() * current_zoom_
/ 2);
2240 client_
->ScrollToX(new_x
);
2244 client_
->NotifySelectedFindResultChanged(current_find_index_
.GetIndex());
2248 void PDFiumEngine::StopFind() {
2249 SelectionChangeInvalidator
selection_invalidator(this);
2253 find_results_
.clear();
2254 next_page_to_search_
= -1;
2255 last_page_to_search_
= -1;
2256 last_character_index_to_search_
= -1;
2257 current_find_index_
.Invalidate();
2258 current_find_text_
.clear();
2260 find_factory_
.CancelAll();
2263 void PDFiumEngine::GetAllScreenRectsUnion(std::vector
<PDFiumRange
>* rect_range
,
2264 const pp::Point
& offset_point
,
2265 std::vector
<pp::Rect
>* rect_vector
) {
2266 for (std::vector
<PDFiumRange
>::iterator it
= rect_range
->begin();
2267 it
!= rect_range
->end(); ++it
) {
2269 std::vector
<pp::Rect
> rects
=
2270 it
->GetScreenRects(offset_point
, current_zoom_
, current_rotation_
);
2271 for (size_t j
= 0; j
< rects
.size(); ++j
)
2272 rect
= rect
.Union(rects
[j
]);
2273 rect_vector
->push_back(rect
);
2277 void PDFiumEngine::UpdateTickMarks() {
2278 std::vector
<pp::Rect
> tickmarks
;
2279 GetAllScreenRectsUnion(&find_results_
, pp::Point(0, 0), &tickmarks
);
2280 client_
->UpdateTickMarks(tickmarks
);
2283 void PDFiumEngine::ZoomUpdated(double new_zoom_level
) {
2286 current_zoom_
= new_zoom_level
;
2288 CalculateVisiblePages();
2292 void PDFiumEngine::RotateClockwise() {
2293 current_rotation_
= (current_rotation_
+ 1) % 4;
2297 void PDFiumEngine::RotateCounterclockwise() {
2298 current_rotation_
= (current_rotation_
- 1) % 4;
2302 void PDFiumEngine::InvalidateAllPages() {
2306 client_
->Invalidate(pp::Rect(plugin_size_
));
2309 std::string
PDFiumEngine::GetSelectedText() {
2310 if (!HasPermission(PDFEngine::PERMISSION_COPY
))
2311 return std::string();
2313 base::string16 result
;
2314 base::string16 new_line_char
= base::UTF8ToUTF16("\n");
2315 for (size_t i
= 0; i
< selection_
.size(); ++i
) {
2317 selection_
[i
- 1].page_index() > selection_
[i
].page_index()) {
2318 result
= selection_
[i
].GetText() + new_line_char
+ result
;
2321 result
.append(new_line_char
);
2322 result
.append(selection_
[i
].GetText());
2326 FormatStringWithHyphens(&result
);
2327 FormatStringForOS(&result
);
2328 return base::UTF16ToUTF8(result
);
2331 std::string
PDFiumEngine::GetLinkAtPosition(const pp::Point
& point
) {
2334 int page_index
= -1;
2335 int form_type
= FPDF_FORMFIELD_UNKNOWN
;
2336 PDFiumPage::LinkTarget target
;
2337 PDFiumPage::Area area
=
2338 GetCharIndex(point
, &page_index
, &temp
, &form_type
, &target
);
2339 if (area
== PDFiumPage::WEBLINK_AREA
)
2344 bool PDFiumEngine::IsSelecting() {
2348 bool PDFiumEngine::HasPermission(DocumentPermission permission
) const {
2349 // PDF 1.7 spec, section 3.5.2 says: "If the revision number is 2 or greater,
2350 // the operations to which user access can be controlled are as follows: ..."
2352 // Thus for revision numbers less than 2, permissions are ignored and this
2353 // always returns true.
2354 if (permissions_handler_revision_
< 2)
2357 // Handle high quality printing permission separately for security handler
2358 // revision 3+. See table 3.20 in the PDF 1.7 spec.
2359 if (permission
== PERMISSION_PRINT_HIGH_QUALITY
&&
2360 permissions_handler_revision_
>= 3) {
2361 return (permissions_
& kPDFPermissionPrintLowQualityMask
) != 0 &&
2362 (permissions_
& kPDFPermissionPrintHighQualityMask
) != 0;
2365 switch (permission
) {
2366 case PERMISSION_COPY
:
2367 return (permissions_
& kPDFPermissionCopyMask
) != 0;
2368 case PERMISSION_COPY_ACCESSIBLE
:
2369 return (permissions_
& kPDFPermissionCopyAccessibleMask
) != 0;
2370 case PERMISSION_PRINT_LOW_QUALITY
:
2371 case PERMISSION_PRINT_HIGH_QUALITY
:
2372 // With security handler revision 2 rules, check the same bit for high
2373 // and low quality. See table 3.20 in the PDF 1.7 spec.
2374 return (permissions_
& kPDFPermissionPrintLowQualityMask
) != 0;
2380 void PDFiumEngine::SelectAll() {
2381 SelectionChangeInvalidator
selection_invalidator(this);
2384 for (size_t i
= 0; i
< pages_
.size(); ++i
)
2385 if (pages_
[i
]->available()) {
2386 selection_
.push_back(PDFiumRange(pages_
[i
], 0,
2387 pages_
[i
]->GetCharCount()));
2391 int PDFiumEngine::GetNumberOfPages() {
2392 return pages_
.size();
2395 pp::VarArray
PDFiumEngine::GetBookmarks() {
2396 pp::VarDictionary dict
= TraverseBookmarks(doc_
, NULL
);
2397 // The root bookmark contains no useful information.
2398 return pp::VarArray(dict
.Get(pp::Var("children")));
2401 int PDFiumEngine::GetNamedDestinationPage(const std::string
& destination
) {
2402 // Look for the destination.
2403 FPDF_DEST dest
= FPDF_GetNamedDestByName(doc_
, destination
.c_str());
2405 // Look for a bookmark with the same name.
2406 base::string16 destination_wide
= base::UTF8ToUTF16(destination
);
2407 FPDF_WIDESTRING destination_pdf_wide
=
2408 reinterpret_cast<FPDF_WIDESTRING
>(destination_wide
.c_str());
2409 FPDF_BOOKMARK bookmark
= FPDFBookmark_Find(doc_
, destination_pdf_wide
);
2412 dest
= FPDFBookmark_GetDest(doc_
, bookmark
);
2414 return dest
? FPDFDest_GetPageIndex(doc_
, dest
) : -1;
2417 int PDFiumEngine::GetFirstVisiblePage() {
2418 CalculateVisiblePages();
2419 return first_visible_page_
;
2422 int PDFiumEngine::GetMostVisiblePage() {
2423 CalculateVisiblePages();
2424 return most_visible_page_
;
2427 pp::Rect
PDFiumEngine::GetPageRect(int index
) {
2428 pp::Rect
rc(pages_
[index
]->rect());
2429 rc
.Inset(-kPageShadowLeft
, -kPageShadowTop
,
2430 -kPageShadowRight
, -kPageShadowBottom
);
2434 pp::Rect
PDFiumEngine::GetPageContentsRect(int index
) {
2435 return GetScreenRect(pages_
[index
]->rect());
2438 void PDFiumEngine::PaintThumbnail(pp::ImageData
* image_data
, int index
) {
2439 FPDF_BITMAP bitmap
= FPDFBitmap_CreateEx(
2440 image_data
->size().width(), image_data
->size().height(),
2441 FPDFBitmap_BGRx
, image_data
->data(), image_data
->stride());
2443 if (pages_
[index
]->available()) {
2444 FPDFBitmap_FillRect(bitmap
, 0, 0, image_data
->size().width(),
2445 image_data
->size().height(), 0xFFFFFFFF);
2447 FPDF_RenderPageBitmap(
2448 bitmap
, pages_
[index
]->GetPage(), 0, 0, image_data
->size().width(),
2449 image_data
->size().height(), 0, GetRenderingFlags());
2451 FPDFBitmap_FillRect(bitmap
, 0, 0, image_data
->size().width(),
2452 image_data
->size().height(), kPendingPageColor
);
2455 FPDFBitmap_Destroy(bitmap
);
2458 void PDFiumEngine::SetGrayscale(bool grayscale
) {
2459 render_grayscale_
= grayscale
;
2462 void PDFiumEngine::OnCallback(int id
) {
2463 if (!timers_
.count(id
))
2466 timers_
[id
].second(id
);
2467 if (timers_
.count(id
)) // The callback might delete the timer.
2468 client_
->ScheduleCallback(id
, timers_
[id
].first
);
2471 std::string
PDFiumEngine::GetPageAsJSON(int index
) {
2472 if (!(HasPermission(PERMISSION_COPY
) ||
2473 HasPermission(PERMISSION_COPY_ACCESSIBLE
))) {
2477 if (index
< 0 || static_cast<size_t>(index
) > pages_
.size() - 1)
2480 scoped_ptr
<base::Value
> node(
2481 pages_
[index
]->GetAccessibleContentAsValue(current_rotation_
));
2482 std::string page_json
;
2483 base::JSONWriter::Write(*node
, &page_json
);
2487 bool PDFiumEngine::GetPrintScaling() {
2488 return !!FPDF_VIEWERREF_GetPrintScaling(doc_
);
2491 int PDFiumEngine::GetCopiesToPrint() {
2492 return FPDF_VIEWERREF_GetNumCopies(doc_
);
2495 int PDFiumEngine::GetDuplexType() {
2496 return static_cast<int>(FPDF_VIEWERREF_GetDuplex(doc_
));
2499 bool PDFiumEngine::GetPageSizeAndUniformity(pp::Size
* size
) {
2503 pp::Size page_size
= GetPageSize(0);
2504 for (size_t i
= 1; i
< pages_
.size(); ++i
) {
2505 if (page_size
!= GetPageSize(i
))
2509 // Convert |page_size| back to points.
2511 ConvertUnit(page_size
.width(), kPixelsPerInch
, kPointsPerInch
));
2513 ConvertUnit(page_size
.height(), kPixelsPerInch
, kPointsPerInch
));
2517 void PDFiumEngine::AppendBlankPages(int num_pages
) {
2518 DCHECK_NE(num_pages
, 0);
2524 pending_pages_
.clear();
2526 // Delete all pages except the first one.
2527 while (pages_
.size() > 1) {
2528 delete pages_
.back();
2530 FPDFPage_Delete(doc_
, pages_
.size());
2533 // Calculate document size and all page sizes.
2534 std::vector
<pp::Rect
> page_rects
;
2535 pp::Size page_size
= GetPageSize(0);
2536 page_size
.Enlarge(kPageShadowLeft
+ kPageShadowRight
,
2537 kPageShadowTop
+ kPageShadowBottom
);
2538 pp::Size old_document_size
= document_size_
;
2539 document_size_
= pp::Size(page_size
.width(), 0);
2540 for (int i
= 0; i
< num_pages
; ++i
) {
2542 // Add space for horizontal separator.
2543 document_size_
.Enlarge(0, kPageSeparatorThickness
);
2546 pp::Rect
rect(pp::Point(0, document_size_
.height()), page_size
);
2547 page_rects
.push_back(rect
);
2549 document_size_
.Enlarge(0, page_size
.height());
2552 // Create blank pages.
2553 for (int i
= 1; i
< num_pages
; ++i
) {
2554 pp::Rect
page_rect(page_rects
[i
]);
2555 page_rect
.Inset(kPageShadowLeft
, kPageShadowTop
,
2556 kPageShadowRight
, kPageShadowBottom
);
2557 double width_in_points
= ConvertUnitDouble(page_rect
.width(),
2560 double height_in_points
= ConvertUnitDouble(page_rect
.height(),
2563 FPDFPage_New(doc_
, i
, width_in_points
, height_in_points
);
2564 pages_
.push_back(new PDFiumPage(this, i
, page_rect
, true));
2567 CalculateVisiblePages();
2568 if (document_size_
!= old_document_size
)
2569 client_
->DocumentSizeUpdated(document_size_
);
2572 void PDFiumEngine::LoadDocument() {
2573 // Check if the document is ready for loading. If it isn't just bail for now,
2574 // we will call LoadDocument() again later.
2575 if (!doc_
&& !doc_loader_
.IsDocumentComplete() &&
2576 !FPDFAvail_IsDocAvail(fpdf_availability_
, &download_hints_
)) {
2580 // If we're in the middle of getting a password, just return. We will retry
2581 // loading the document after we get the password anyway.
2582 if (getting_password_
)
2585 ScopedUnsupportedFeature
scoped_unsupported_feature(this);
2586 bool needs_password
= false;
2587 if (TryLoadingDoc(false, std::string(), &needs_password
)) {
2588 ContinueLoadingDocument(false, std::string());
2592 GetPasswordAndLoad();
2594 client_
->DocumentLoadFailed();
2597 bool PDFiumEngine::TryLoadingDoc(bool with_password
,
2598 const std::string
& password
,
2599 bool* needs_password
) {
2600 *needs_password
= false;
2604 const char* password_cstr
= NULL
;
2605 if (with_password
) {
2606 password_cstr
= password
.c_str();
2607 password_tries_remaining_
--;
2609 if (doc_loader_
.IsDocumentComplete())
2610 doc_
= FPDF_LoadCustomDocument(&file_access_
, password_cstr
);
2612 doc_
= FPDFAvail_GetDocument(fpdf_availability_
, password_cstr
);
2614 if (!doc_
&& FPDF_GetLastError() == FPDF_ERR_PASSWORD
)
2615 *needs_password
= true;
2617 return doc_
!= NULL
;
2620 void PDFiumEngine::GetPasswordAndLoad() {
2621 getting_password_
= true;
2622 DCHECK(!doc_
&& FPDF_GetLastError() == FPDF_ERR_PASSWORD
);
2623 client_
->GetDocumentPassword(password_factory_
.NewCallbackWithOutput(
2624 &PDFiumEngine::OnGetPasswordComplete
));
2627 void PDFiumEngine::OnGetPasswordComplete(int32_t result
,
2628 const pp::Var
& password
) {
2629 getting_password_
= false;
2631 bool password_given
= false;
2632 std::string password_text
;
2633 if (result
== PP_OK
&& password
.is_string()) {
2634 password_text
= password
.AsString();
2635 if (!password_text
.empty())
2636 password_given
= true;
2638 ContinueLoadingDocument(password_given
, password_text
);
2641 void PDFiumEngine::ContinueLoadingDocument(
2643 const std::string
& password
) {
2644 ScopedUnsupportedFeature
scoped_unsupported_feature(this);
2646 bool needs_password
= false;
2647 bool loaded
= TryLoadingDoc(has_password
, password
, &needs_password
);
2648 bool password_incorrect
= !loaded
&& has_password
&& needs_password
;
2649 if (password_incorrect
&& password_tries_remaining_
> 0) {
2650 GetPasswordAndLoad();
2655 client_
->DocumentLoadFailed();
2659 if (FPDFDoc_GetPageMode(doc_
) == PAGEMODE_USEOUTLINES
)
2660 client_
->DocumentHasUnsupportedFeature("Bookmarks");
2662 permissions_
= FPDF_GetDocPermissions(doc_
);
2663 permissions_handler_revision_
= FPDF_GetSecurityHandlerRevision(doc_
);
2666 // Only returns 0 when data isn't available. If form data is downloaded, or
2667 // if this isn't a form, returns positive values.
2668 if (!doc_loader_
.IsDocumentComplete() &&
2669 !FPDFAvail_IsFormAvail(fpdf_availability_
, &download_hints_
)) {
2673 form_
= FPDFDOC_InitFormFillEnvironment(
2674 doc_
, static_cast<FPDF_FORMFILLINFO
*>(this));
2679 FPDF_SetFormFieldHighlightColor(form_
, 0, kFormHighlightColor
);
2680 FPDF_SetFormFieldHighlightAlpha(form_
, kFormHighlightAlpha
);
2683 if (!doc_loader_
.IsDocumentComplete()) {
2684 // Check if the first page is available. In a linearized PDF, that is not
2685 // always page 0. Doing this gives us the default page size, since when the
2686 // document is available, the first page is available as well.
2687 CheckPageAvailable(FPDFAvail_GetFirstPageNum(doc_
), &pending_pages_
);
2690 LoadPageInfo(false);
2692 if (doc_loader_
.IsDocumentComplete())
2693 FinishLoadingDocument();
2696 void PDFiumEngine::LoadPageInfo(bool reload
) {
2697 pending_pages_
.clear();
2698 pp::Size old_document_size
= document_size_
;
2699 document_size_
= pp::Size();
2700 std::vector
<pp::Rect
> page_rects
;
2701 int page_count
= FPDF_GetPageCount(doc_
);
2702 bool doc_complete
= doc_loader_
.IsDocumentComplete();
2703 for (int i
= 0; i
< page_count
; ++i
) {
2705 // Add space for horizontal separator.
2706 document_size_
.Enlarge(0, kPageSeparatorThickness
);
2709 // Get page availability. If reload==false, and document is not loaded yet
2710 // (we are using async loading) - mark all pages as unavailable.
2711 // If reload==true (we have document constructed already), get page
2712 // availability flag from already existing PDFiumPage class.
2713 bool page_available
= reload
? pages_
[i
]->available() : doc_complete
;
2715 pp::Size size
= page_available
? GetPageSize(i
) : default_page_size_
;
2716 size
.Enlarge(kPageShadowLeft
+ kPageShadowRight
,
2717 kPageShadowTop
+ kPageShadowBottom
);
2718 pp::Rect
rect(pp::Point(0, document_size_
.height()), size
);
2719 page_rects
.push_back(rect
);
2721 if (size
.width() > document_size_
.width())
2722 document_size_
.set_width(size
.width());
2724 document_size_
.Enlarge(0, size
.height());
2727 for (int i
= 0; i
< page_count
; ++i
) {
2728 // Center pages relative to the entire document.
2729 page_rects
[i
].set_x((document_size_
.width() - page_rects
[i
].width()) / 2);
2730 pp::Rect
page_rect(page_rects
[i
]);
2731 page_rect
.Inset(kPageShadowLeft
, kPageShadowTop
,
2732 kPageShadowRight
, kPageShadowBottom
);
2734 pages_
[i
]->set_rect(page_rect
);
2736 pages_
.push_back(new PDFiumPage(this, i
, page_rect
, doc_complete
));
2740 CalculateVisiblePages();
2741 if (document_size_
!= old_document_size
)
2742 client_
->DocumentSizeUpdated(document_size_
);
2745 void PDFiumEngine::CalculateVisiblePages() {
2746 // Clear pending requests queue, since it may contain requests to the pages
2747 // that are already invisible (after scrolling for example).
2748 pending_pages_
.clear();
2749 doc_loader_
.ClearPendingRequests();
2751 visible_pages_
.clear();
2752 pp::Rect
visible_rect(plugin_size_
);
2753 for (size_t i
= 0; i
< pages_
.size(); ++i
) {
2754 // Check an entire PageScreenRect, since we might need to repaint side
2755 // borders and shadows even if the page itself is not visible.
2756 // For example, when user use pdf with different page sizes and zoomed in
2757 // outside page area.
2758 if (visible_rect
.Intersects(GetPageScreenRect(i
))) {
2759 visible_pages_
.push_back(i
);
2760 CheckPageAvailable(i
, &pending_pages_
);
2762 // Need to unload pages when we're not using them, since some PDFs use a
2763 // lot of memory. See http://crbug.com/48791
2764 if (defer_page_unload_
) {
2765 deferred_page_unloads_
.push_back(i
);
2767 pages_
[i
]->Unload();
2770 // If the last mouse down was on a page that's no longer visible, reset
2771 // that variable so that we don't send keyboard events to it (the focus
2772 // will be lost when the page is first closed anyways).
2773 if (static_cast<int>(i
) == last_page_mouse_down_
)
2774 last_page_mouse_down_
= -1;
2778 // Any pending highlighting of form fields will be invalid since these are in
2779 // screen coordinates.
2780 form_highlights_
.clear();
2782 if (visible_pages_
.size() == 0)
2783 first_visible_page_
= -1;
2785 first_visible_page_
= visible_pages_
.front();
2787 int most_visible_page
= first_visible_page_
;
2788 // Check if the next page is more visible than the first one.
2789 if (most_visible_page
!= -1 &&
2790 pages_
.size() > 0 &&
2791 most_visible_page
< static_cast<int>(pages_
.size()) - 1) {
2793 visible_rect
.Intersect(GetPageScreenRect(most_visible_page
));
2795 visible_rect
.Intersect(GetPageScreenRect(most_visible_page
+ 1));
2796 if (rc_next
.height() > rc_first
.height())
2797 most_visible_page
++;
2800 SetCurrentPage(most_visible_page
);
2803 bool PDFiumEngine::IsPageVisible(int index
) const {
2804 for (size_t i
= 0; i
< visible_pages_
.size(); ++i
) {
2805 if (visible_pages_
[i
] == index
)
2812 bool PDFiumEngine::CheckPageAvailable(int index
, std::vector
<int>* pending
) {
2813 if (!doc_
|| !form_
)
2816 if (static_cast<int>(pages_
.size()) > index
&& pages_
[index
]->available())
2819 if (!FPDFAvail_IsPageAvail(fpdf_availability_
, index
, &download_hints_
)) {
2821 for (j
= 0; j
< pending
->size(); ++j
) {
2822 if ((*pending
)[j
] == index
)
2826 if (j
== pending
->size())
2827 pending
->push_back(index
);
2831 if (static_cast<int>(pages_
.size()) > index
)
2832 pages_
[index
]->set_available(true);
2833 if (!default_page_size_
.GetArea())
2834 default_page_size_
= GetPageSize(index
);
2838 pp::Size
PDFiumEngine::GetPageSize(int index
) {
2840 double width_in_points
= 0;
2841 double height_in_points
= 0;
2842 int rv
= FPDF_GetPageSizeByIndex(
2843 doc_
, index
, &width_in_points
, &height_in_points
);
2846 int width_in_pixels
= static_cast<int>(
2847 ConvertUnitDouble(width_in_points
, kPointsPerInch
, kPixelsPerInch
));
2848 int height_in_pixels
= static_cast<int>(
2849 ConvertUnitDouble(height_in_points
, kPointsPerInch
, kPixelsPerInch
));
2850 if (current_rotation_
% 2 == 1)
2851 std::swap(width_in_pixels
, height_in_pixels
);
2852 size
= pp::Size(width_in_pixels
, height_in_pixels
);
2857 int PDFiumEngine::StartPaint(int page_index
, const pp::Rect
& dirty
) {
2858 // For the first time we hit paint, do nothing and just record the paint for
2859 // the next callback. This keeps the UI responsive in case the user is doing
2860 // a lot of scrolling.
2861 ProgressivePaint progressive
;
2862 progressive
.rect
= dirty
;
2863 progressive
.page_index
= page_index
;
2864 progressive
.bitmap
= NULL
;
2865 progressive
.painted_
= false;
2866 progressive_paints_
.push_back(progressive
);
2867 return progressive_paints_
.size() - 1;
2870 bool PDFiumEngine::ContinuePaint(int progressive_index
,
2871 pp::ImageData
* image_data
) {
2872 DCHECK_GE(progressive_index
, 0);
2873 DCHECK_LT(static_cast<size_t>(progressive_index
), progressive_paints_
.size());
2876 #if defined(OS_LINUX)
2877 g_last_instance_id
= client_
->GetPluginInstance()->pp_instance();
2881 FPDF_BITMAP bitmap
= progressive_paints_
[progressive_index
].bitmap
;
2882 int page_index
= progressive_paints_
[progressive_index
].page_index
;
2883 DCHECK_GE(page_index
, 0);
2884 DCHECK_LT(static_cast<size_t>(page_index
), pages_
.size());
2885 FPDF_PAGE page
= pages_
[page_index
]->GetPage();
2887 last_progressive_start_time_
= base::Time::Now();
2889 rv
= FPDF_RenderPage_Continue(page
, static_cast<IFSDK_PAUSE
*>(this));
2891 pp::Rect dirty
= progressive_paints_
[progressive_index
].rect
;
2892 bitmap
= CreateBitmap(dirty
, image_data
);
2893 int start_x
, start_y
, size_x
, size_y
;
2894 GetPDFiumRect(page_index
, dirty
, &start_x
, &start_y
, &size_x
, &size_y
);
2895 FPDFBitmap_FillRect(bitmap
, start_x
, start_y
, size_x
, size_y
, 0xFFFFFFFF);
2896 rv
= FPDF_RenderPageBitmap_Start(
2897 bitmap
, page
, start_x
, start_y
, size_x
, size_y
,
2899 GetRenderingFlags(), static_cast<IFSDK_PAUSE
*>(this));
2900 progressive_paints_
[progressive_index
].bitmap
= bitmap
;
2902 return rv
!= FPDF_RENDER_TOBECOUNTINUED
;
2905 void PDFiumEngine::FinishPaint(int progressive_index
,
2906 pp::ImageData
* image_data
) {
2907 DCHECK_GE(progressive_index
, 0);
2908 DCHECK_LT(static_cast<size_t>(progressive_index
), progressive_paints_
.size());
2911 int page_index
= progressive_paints_
[progressive_index
].page_index
;
2912 pp::Rect dirty_in_screen
= progressive_paints_
[progressive_index
].rect
;
2913 FPDF_BITMAP bitmap
= progressive_paints_
[progressive_index
].bitmap
;
2914 int start_x
, start_y
, size_x
, size_y
;
2916 page_index
, dirty_in_screen
, &start_x
, &start_y
, &size_x
, &size_y
);
2920 form_
, bitmap
, pages_
[page_index
]->GetPage(), start_x
, start_y
, size_x
,
2921 size_y
, current_rotation_
, GetRenderingFlags());
2923 FillPageSides(progressive_index
);
2925 // Paint the page shadows.
2926 PaintPageShadow(progressive_index
, image_data
);
2928 DrawSelections(progressive_index
, image_data
);
2930 FPDF_RenderPage_Close(pages_
[page_index
]->GetPage());
2931 FPDFBitmap_Destroy(bitmap
);
2932 progressive_paints_
.erase(progressive_paints_
.begin() + progressive_index
);
2934 client_
->DocumentPaintOccurred();
2937 void PDFiumEngine::CancelPaints() {
2938 for (size_t i
= 0; i
< progressive_paints_
.size(); ++i
) {
2939 FPDF_RenderPage_Close(pages_
[progressive_paints_
[i
].page_index
]->GetPage());
2940 FPDFBitmap_Destroy(progressive_paints_
[i
].bitmap
);
2942 progressive_paints_
.clear();
2945 void PDFiumEngine::FillPageSides(int progressive_index
) {
2946 DCHECK_GE(progressive_index
, 0);
2947 DCHECK_LT(static_cast<size_t>(progressive_index
), progressive_paints_
.size());
2949 int page_index
= progressive_paints_
[progressive_index
].page_index
;
2950 pp::Rect dirty_in_screen
= progressive_paints_
[progressive_index
].rect
;
2951 FPDF_BITMAP bitmap
= progressive_paints_
[progressive_index
].bitmap
;
2953 pp::Rect page_rect
= pages_
[page_index
]->rect();
2954 if (page_rect
.x() > 0) {
2956 page_rect
.y() - kPageShadowTop
,
2957 page_rect
.x() - kPageShadowLeft
,
2958 page_rect
.height() + kPageShadowTop
+
2959 kPageShadowBottom
+ kPageSeparatorThickness
);
2960 left
= GetScreenRect(left
).Intersect(dirty_in_screen
);
2962 FPDFBitmap_FillRect(bitmap
, left
.x() - dirty_in_screen
.x(),
2963 left
.y() - dirty_in_screen
.y(), left
.width(),
2964 left
.height(), client_
->GetBackgroundColor());
2967 if (page_rect
.right() < document_size_
.width()) {
2968 pp::Rect
right(page_rect
.right() + kPageShadowRight
,
2969 page_rect
.y() - kPageShadowTop
,
2970 document_size_
.width() - page_rect
.right() -
2972 page_rect
.height() + kPageShadowTop
+
2973 kPageShadowBottom
+ kPageSeparatorThickness
);
2974 right
= GetScreenRect(right
).Intersect(dirty_in_screen
);
2976 FPDFBitmap_FillRect(bitmap
, right
.x() - dirty_in_screen
.x(),
2977 right
.y() - dirty_in_screen
.y(), right
.width(),
2978 right
.height(), client_
->GetBackgroundColor());
2982 pp::Rect
bottom(page_rect
.x() - kPageShadowLeft
,
2983 page_rect
.bottom() + kPageShadowBottom
,
2984 page_rect
.width() + kPageShadowLeft
+ kPageShadowRight
,
2985 kPageSeparatorThickness
);
2986 bottom
= GetScreenRect(bottom
).Intersect(dirty_in_screen
);
2988 FPDFBitmap_FillRect(bitmap
, bottom
.x() - dirty_in_screen
.x(),
2989 bottom
.y() - dirty_in_screen
.y(), bottom
.width(),
2990 bottom
.height(), client_
->GetBackgroundColor());
2993 void PDFiumEngine::PaintPageShadow(int progressive_index
,
2994 pp::ImageData
* image_data
) {
2995 DCHECK_GE(progressive_index
, 0);
2996 DCHECK_LT(static_cast<size_t>(progressive_index
), progressive_paints_
.size());
2999 int page_index
= progressive_paints_
[progressive_index
].page_index
;
3000 pp::Rect dirty_in_screen
= progressive_paints_
[progressive_index
].rect
;
3001 pp::Rect page_rect
= pages_
[page_index
]->rect();
3002 pp::Rect
shadow_rect(page_rect
);
3003 shadow_rect
.Inset(-kPageShadowLeft
, -kPageShadowTop
,
3004 -kPageShadowRight
, -kPageShadowBottom
);
3006 // Due to the rounding errors of the GetScreenRect it is possible to get
3007 // different size shadows on the left and right sides even they are defined
3008 // the same. To fix this issue let's calculate shadow rect and then shrink
3009 // it by the size of the shadows.
3010 shadow_rect
= GetScreenRect(shadow_rect
);
3011 page_rect
= shadow_rect
;
3013 page_rect
.Inset(static_cast<int>(ceil(kPageShadowLeft
* current_zoom_
)),
3014 static_cast<int>(ceil(kPageShadowTop
* current_zoom_
)),
3015 static_cast<int>(ceil(kPageShadowRight
* current_zoom_
)),
3016 static_cast<int>(ceil(kPageShadowBottom
* current_zoom_
)));
3018 DrawPageShadow(page_rect
, shadow_rect
, dirty_in_screen
, image_data
);
3021 void PDFiumEngine::DrawSelections(int progressive_index
,
3022 pp::ImageData
* image_data
) {
3023 DCHECK_GE(progressive_index
, 0);
3024 DCHECK_LT(static_cast<size_t>(progressive_index
), progressive_paints_
.size());
3027 int page_index
= progressive_paints_
[progressive_index
].page_index
;
3028 pp::Rect dirty_in_screen
= progressive_paints_
[progressive_index
].rect
;
3030 void* region
= NULL
;
3032 GetRegion(dirty_in_screen
.point(), image_data
, ®ion
, &stride
);
3034 std::vector
<pp::Rect
> highlighted_rects
;
3035 pp::Rect visible_rect
= GetVisibleRect();
3036 for (size_t k
= 0; k
< selection_
.size(); ++k
) {
3037 if (selection_
[k
].page_index() != page_index
)
3039 std::vector
<pp::Rect
> rects
= selection_
[k
].GetScreenRects(
3040 visible_rect
.point(), current_zoom_
, current_rotation_
);
3041 for (size_t j
= 0; j
< rects
.size(); ++j
) {
3042 pp::Rect visible_selection
= rects
[j
].Intersect(dirty_in_screen
);
3043 if (visible_selection
.IsEmpty())
3046 visible_selection
.Offset(
3047 -dirty_in_screen
.point().x(), -dirty_in_screen
.point().y());
3048 Highlight(region
, stride
, visible_selection
, &highlighted_rects
);
3052 for (size_t k
= 0; k
< form_highlights_
.size(); ++k
) {
3053 pp::Rect visible_selection
= form_highlights_
[k
].Intersect(dirty_in_screen
);
3054 if (visible_selection
.IsEmpty())
3057 visible_selection
.Offset(
3058 -dirty_in_screen
.point().x(), -dirty_in_screen
.point().y());
3059 Highlight(region
, stride
, visible_selection
, &highlighted_rects
);
3061 form_highlights_
.clear();
3064 void PDFiumEngine::PaintUnavailablePage(int page_index
,
3065 const pp::Rect
& dirty
,
3066 pp::ImageData
* image_data
) {
3067 int start_x
, start_y
, size_x
, size_y
;
3068 GetPDFiumRect(page_index
, dirty
, &start_x
, &start_y
, &size_x
, &size_y
);
3069 FPDF_BITMAP bitmap
= CreateBitmap(dirty
, image_data
);
3070 FPDFBitmap_FillRect(bitmap
, start_x
, start_y
, size_x
, size_y
,
3073 pp::Rect
loading_text_in_screen(
3074 pages_
[page_index
]->rect().width() / 2,
3075 pages_
[page_index
]->rect().y() + kLoadingTextVerticalOffset
, 0, 0);
3076 loading_text_in_screen
= GetScreenRect(loading_text_in_screen
);
3077 FPDFBitmap_Destroy(bitmap
);
3080 int PDFiumEngine::GetProgressiveIndex(int page_index
) const {
3081 for (size_t i
= 0; i
< progressive_paints_
.size(); ++i
) {
3082 if (progressive_paints_
[i
].page_index
== page_index
)
3088 FPDF_BITMAP
PDFiumEngine::CreateBitmap(const pp::Rect
& rect
,
3089 pp::ImageData
* image_data
) const {
3092 GetRegion(rect
.point(), image_data
, ®ion
, &stride
);
3095 return FPDFBitmap_CreateEx(
3096 rect
.width(), rect
.height(), FPDFBitmap_BGRx
, region
, stride
);
3099 void PDFiumEngine::GetPDFiumRect(
3100 int page_index
, const pp::Rect
& rect
, int* start_x
, int* start_y
,
3101 int* size_x
, int* size_y
) const {
3102 pp::Rect page_rect
= GetScreenRect(pages_
[page_index
]->rect());
3103 page_rect
.Offset(-rect
.x(), -rect
.y());
3105 *start_x
= page_rect
.x();
3106 *start_y
= page_rect
.y();
3107 *size_x
= page_rect
.width();
3108 *size_y
= page_rect
.height();
3111 int PDFiumEngine::GetRenderingFlags() const {
3112 int flags
= FPDF_LCD_TEXT
| FPDF_NO_CATCH
;
3113 if (render_grayscale_
)
3114 flags
|= FPDF_GRAYSCALE
;
3115 if (client_
->IsPrintPreview())
3116 flags
|= FPDF_PRINTING
;
3120 pp::Rect
PDFiumEngine::GetVisibleRect() const {
3122 rv
.set_x(static_cast<int>(position_
.x() / current_zoom_
));
3123 rv
.set_y(static_cast<int>(position_
.y() / current_zoom_
));
3124 rv
.set_width(static_cast<int>(ceil(plugin_size_
.width() / current_zoom_
)));
3125 rv
.set_height(static_cast<int>(ceil(plugin_size_
.height() / current_zoom_
)));
3129 pp::Rect
PDFiumEngine::GetPageScreenRect(int page_index
) const {
3130 // Since we use this rect for creating the PDFium bitmap, also include other
3131 // areas around the page that we might need to update such as the page
3132 // separator and the sides if the page is narrower than the document.
3133 return GetScreenRect(pp::Rect(
3135 pages_
[page_index
]->rect().y() - kPageShadowTop
,
3136 document_size_
.width(),
3137 pages_
[page_index
]->rect().height() + kPageShadowTop
+
3138 kPageShadowBottom
+ kPageSeparatorThickness
));
3141 pp::Rect
PDFiumEngine::GetScreenRect(const pp::Rect
& rect
) const {
3144 static_cast<int>(ceil(rect
.right() * current_zoom_
- position_
.x()));
3146 static_cast<int>(ceil(rect
.bottom() * current_zoom_
- position_
.y()));
3148 rv
.set_x(static_cast<int>(rect
.x() * current_zoom_
- position_
.x()));
3149 rv
.set_y(static_cast<int>(rect
.y() * current_zoom_
- position_
.y()));
3150 rv
.set_width(right
- rv
.x());
3151 rv
.set_height(bottom
- rv
.y());
3155 void PDFiumEngine::Highlight(void* buffer
,
3157 const pp::Rect
& rect
,
3158 std::vector
<pp::Rect
>* highlighted_rects
) {
3162 pp::Rect new_rect
= rect
;
3163 for (size_t i
= 0; i
< highlighted_rects
->size(); ++i
)
3164 new_rect
= new_rect
.Subtract((*highlighted_rects
)[i
]);
3166 highlighted_rects
->push_back(new_rect
);
3167 int l
= new_rect
.x();
3168 int t
= new_rect
.y();
3169 int w
= new_rect
.width();
3170 int h
= new_rect
.height();
3172 for (int y
= t
; y
< t
+ h
; ++y
) {
3173 for (int x
= l
; x
< l
+ w
; ++x
) {
3174 uint8
* pixel
= static_cast<uint8
*>(buffer
) + y
* stride
+ x
* 4;
3175 // This is our highlight color.
3176 pixel
[0] = static_cast<uint8
>(
3177 pixel
[0] * (kHighlightColorB
/ 255.0));
3178 pixel
[1] = static_cast<uint8
>(
3179 pixel
[1] * (kHighlightColorG
/ 255.0));
3180 pixel
[2] = static_cast<uint8
>(
3181 pixel
[2] * (kHighlightColorR
/ 255.0));
3186 PDFiumEngine::SelectionChangeInvalidator::SelectionChangeInvalidator(
3187 PDFiumEngine
* engine
) : engine_(engine
) {
3188 previous_origin_
= engine_
->GetVisibleRect().point();
3189 GetVisibleSelectionsScreenRects(&old_selections_
);
3192 PDFiumEngine::SelectionChangeInvalidator::~SelectionChangeInvalidator() {
3193 // Offset the old selections if the document scrolled since we recorded them.
3194 pp::Point offset
= previous_origin_
- engine_
->GetVisibleRect().point();
3195 for (size_t i
= 0; i
< old_selections_
.size(); ++i
)
3196 old_selections_
[i
].Offset(offset
);
3198 std::vector
<pp::Rect
> new_selections
;
3199 GetVisibleSelectionsScreenRects(&new_selections
);
3200 for (size_t i
= 0; i
< new_selections
.size(); ++i
) {
3201 for (size_t j
= 0; j
< old_selections_
.size(); ++j
) {
3202 if (!old_selections_
[j
].IsEmpty() &&
3203 new_selections
[i
] == old_selections_
[j
]) {
3204 // Rectangle was selected before and after, so no need to invalidate it.
3205 // Mark the rectangles by setting them to empty.
3206 new_selections
[i
] = old_selections_
[j
] = pp::Rect();
3212 for (size_t i
= 0; i
< old_selections_
.size(); ++i
) {
3213 if (!old_selections_
[i
].IsEmpty())
3214 engine_
->client_
->Invalidate(old_selections_
[i
]);
3216 for (size_t i
= 0; i
< new_selections
.size(); ++i
) {
3217 if (!new_selections
[i
].IsEmpty())
3218 engine_
->client_
->Invalidate(new_selections
[i
]);
3220 engine_
->OnSelectionChanged();
3224 PDFiumEngine::SelectionChangeInvalidator::GetVisibleSelectionsScreenRects(
3225 std::vector
<pp::Rect
>* rects
) {
3226 pp::Rect visible_rect
= engine_
->GetVisibleRect();
3227 for (size_t i
= 0; i
< engine_
->selection_
.size(); ++i
) {
3228 int page_index
= engine_
->selection_
[i
].page_index();
3229 if (!engine_
->IsPageVisible(page_index
))
3230 continue; // This selection is on a page that's not currently visible.
3232 std::vector
<pp::Rect
> selection_rects
=
3233 engine_
->selection_
[i
].GetScreenRects(
3234 visible_rect
.point(),
3235 engine_
->current_zoom_
,
3236 engine_
->current_rotation_
);
3237 rects
->insert(rects
->end(), selection_rects
.begin(), selection_rects
.end());
3241 PDFiumEngine::MouseDownState::MouseDownState(
3242 const PDFiumPage::Area
& area
,
3243 const PDFiumPage::LinkTarget
& target
)
3244 : area_(area
), target_(target
) {
3247 PDFiumEngine::MouseDownState::~MouseDownState() {
3250 void PDFiumEngine::MouseDownState::Set(const PDFiumPage::Area
& area
,
3251 const PDFiumPage::LinkTarget
& target
) {
3256 void PDFiumEngine::MouseDownState::Reset() {
3257 area_
= PDFiumPage::NONSELECTABLE_AREA
;
3258 target_
= PDFiumPage::LinkTarget();
3261 bool PDFiumEngine::MouseDownState::Matches(
3262 const PDFiumPage::Area
& area
,
3263 const PDFiumPage::LinkTarget
& target
) const {
3264 if (area_
== area
) {
3265 if (area
== PDFiumPage::WEBLINK_AREA
)
3266 return target_
.url
== target
.url
;
3267 if (area
== PDFiumPage::DOCLINK_AREA
)
3268 return target_
.page
== target
.page
;
3274 PDFiumEngine::FindTextIndex::FindTextIndex()
3275 : valid_(false), index_(0) {
3278 PDFiumEngine::FindTextIndex::~FindTextIndex() {
3281 void PDFiumEngine::FindTextIndex::Invalidate() {
3285 size_t PDFiumEngine::FindTextIndex::GetIndex() const {
3290 void PDFiumEngine::FindTextIndex::SetIndex(size_t index
) {
3295 size_t PDFiumEngine::FindTextIndex::IncrementIndex() {
3300 void PDFiumEngine::DeviceToPage(int page_index
,
3305 *page_x
= *page_y
= 0;
3306 int temp_x
= static_cast<int>((device_x
+ position_
.x())/ current_zoom_
-
3307 pages_
[page_index
]->rect().x());
3308 int temp_y
= static_cast<int>((device_y
+ position_
.y())/ current_zoom_
-
3309 pages_
[page_index
]->rect().y());
3311 pages_
[page_index
]->GetPage(), 0, 0,
3312 pages_
[page_index
]->rect().width(), pages_
[page_index
]->rect().height(),
3313 current_rotation_
, temp_x
, temp_y
, page_x
, page_y
);
3316 int PDFiumEngine::GetVisiblePageIndex(FPDF_PAGE page
) {
3317 for (size_t i
= 0; i
< visible_pages_
.size(); ++i
) {
3318 if (pages_
[visible_pages_
[i
]]->GetPage() == page
)
3319 return visible_pages_
[i
];
3324 void PDFiumEngine::SetCurrentPage(int index
) {
3325 if (index
== most_visible_page_
|| !form_
)
3327 if (most_visible_page_
!= -1 && called_do_document_action_
) {
3328 FPDF_PAGE old_page
= pages_
[most_visible_page_
]->GetPage();
3329 FORM_DoPageAAction(old_page
, form_
, FPDFPAGE_AACTION_CLOSE
);
3331 most_visible_page_
= index
;
3332 #if defined(OS_LINUX)
3333 g_last_instance_id
= client_
->GetPluginInstance()->pp_instance();
3335 if (most_visible_page_
!= -1 && called_do_document_action_
) {
3336 FPDF_PAGE new_page
= pages_
[most_visible_page_
]->GetPage();
3337 FORM_DoPageAAction(new_page
, form_
, FPDFPAGE_AACTION_OPEN
);
3341 void PDFiumEngine::TransformPDFPageForPrinting(
3343 const PP_PrintSettings_Dev
& print_settings
) {
3344 // Get the source page width and height in points.
3345 const double src_page_width
= FPDF_GetPageWidth(page
);
3346 const double src_page_height
= FPDF_GetPageHeight(page
);
3348 const int src_page_rotation
= FPDFPage_GetRotation(page
);
3349 const bool fit_to_page
= print_settings
.print_scaling_option
==
3350 PP_PRINTSCALINGOPTION_FIT_TO_PRINTABLE_AREA
;
3352 pp::Size
page_size(print_settings
.paper_size
);
3353 pp::Rect
content_rect(print_settings
.printable_area
);
3354 const bool rotated
= (src_page_rotation
% 2 == 1);
3355 SetPageSizeAndContentRect(rotated
,
3356 src_page_width
> src_page_height
,
3360 // Compute the screen page width and height in points.
3361 const int actual_page_width
=
3362 rotated
? page_size
.height() : page_size
.width();
3363 const int actual_page_height
=
3364 rotated
? page_size
.width() : page_size
.height();
3366 const double scale_factor
= CalculateScaleFactor(fit_to_page
, content_rect
,
3368 src_page_height
, rotated
);
3370 // Calculate positions for the clip box.
3371 ClipBox source_clip_box
;
3372 CalculateClipBoxBoundary(page
, scale_factor
, rotated
, &source_clip_box
);
3374 // Calculate the translation offset values.
3375 double offset_x
= 0;
3376 double offset_y
= 0;
3378 CalculateScaledClipBoxOffset(content_rect
, source_clip_box
, &offset_x
,
3381 CalculateNonScaledClipBoxOffset(content_rect
, src_page_rotation
,
3382 actual_page_width
, actual_page_height
,
3383 source_clip_box
, &offset_x
, &offset_y
);
3386 // Reset the media box and crop box. When the page has crop box and media box,
3387 // the plugin will display the crop box contents and not the entire media box.
3388 // If the pages have different crop box values, the plugin will display a
3389 // document of multiple page sizes. To give better user experience, we
3390 // decided to have same crop box and media box values. Hence, the user will
3391 // see a list of uniform pages.
3392 FPDFPage_SetMediaBox(page
, 0, 0, page_size
.width(), page_size
.height());
3393 FPDFPage_SetCropBox(page
, 0, 0, page_size
.width(), page_size
.height());
3395 // Transformation is not required, return. Do this check only after updating
3396 // the media box and crop box. For more detailed information, please refer to
3397 // the comment block right before FPDF_SetMediaBox and FPDF_GetMediaBox calls.
3398 if (scale_factor
== 1.0 && offset_x
== 0 && offset_y
== 0)
3402 // All the positions have been calculated, now manipulate the PDF.
3403 FS_MATRIX matrix
= {static_cast<float>(scale_factor
),
3406 static_cast<float>(scale_factor
),
3407 static_cast<float>(offset_x
),
3408 static_cast<float>(offset_y
)};
3409 FS_RECTF cliprect
= {static_cast<float>(source_clip_box
.left
+offset_x
),
3410 static_cast<float>(source_clip_box
.top
+offset_y
),
3411 static_cast<float>(source_clip_box
.right
+offset_x
),
3412 static_cast<float>(source_clip_box
.bottom
+offset_y
)};
3413 FPDFPage_TransFormWithClip(page
, &matrix
, &cliprect
);
3414 FPDFPage_TransformAnnots(page
, scale_factor
, 0, 0, scale_factor
,
3415 offset_x
, offset_y
);
3418 void PDFiumEngine::DrawPageShadow(const pp::Rect
& page_rc
,
3419 const pp::Rect
& shadow_rc
,
3420 const pp::Rect
& clip_rc
,
3421 pp::ImageData
* image_data
) {
3422 pp::Rect
page_rect(page_rc
);
3423 page_rect
.Offset(page_offset_
);
3425 pp::Rect
shadow_rect(shadow_rc
);
3426 shadow_rect
.Offset(page_offset_
);
3428 pp::Rect
clip_rect(clip_rc
);
3429 clip_rect
.Offset(page_offset_
);
3431 // Page drop shadow parameters.
3432 const double factor
= 0.5;
3433 uint32 depth
= std::max(
3434 std::max(page_rect
.x() - shadow_rect
.x(),
3435 page_rect
.y() - shadow_rect
.y()),
3436 std::max(shadow_rect
.right() - page_rect
.right(),
3437 shadow_rect
.bottom() - page_rect
.bottom()));
3438 depth
= static_cast<uint32
>(depth
* 1.5) + 1;
3440 // We need to check depth only to verify our copy of shadow matrix is correct.
3441 if (!page_shadow_
.get() || page_shadow_
->depth() != depth
)
3442 page_shadow_
.reset(new ShadowMatrix(depth
, factor
,
3443 client_
->GetBackgroundColor()));
3445 DCHECK(!image_data
->is_null());
3446 DrawShadow(image_data
, shadow_rect
, page_rect
, clip_rect
, *page_shadow_
);
3449 void PDFiumEngine::GetRegion(const pp::Point
& location
,
3450 pp::ImageData
* image_data
,
3452 int* stride
) const {
3453 if (image_data
->is_null()) {
3454 DCHECK(plugin_size_
.IsEmpty());
3459 char* buffer
= static_cast<char*>(image_data
->data());
3460 *stride
= image_data
->stride();
3462 pp::Point offset_location
= location
+ page_offset_
;
3463 // TODO: update this when we support BIDI and scrollbars can be on the left.
3465 !pp::Rect(page_offset_
, plugin_size_
).Contains(offset_location
)) {
3470 buffer
+= location
.y() * (*stride
);
3471 buffer
+= (location
.x() + page_offset_
.x()) * 4;
3475 void PDFiumEngine::OnSelectionChanged() {
3476 pp::PDF::SetSelectedText(GetPluginInstance(), GetSelectedText().c_str());
3479 void PDFiumEngine::RotateInternal() {
3480 // Store the current find index so that we can resume finding at that
3481 // particular index after we have recomputed the find results.
3482 std::string current_find_text
= current_find_text_
;
3483 if (current_find_index_
.valid())
3484 resume_find_index_
.SetIndex(current_find_index_
.GetIndex());
3486 resume_find_index_
.Invalidate();
3488 InvalidateAllPages();
3490 if (!current_find_text
.empty()) {
3492 client_
->NotifyNumberOfFindResultsChanged(0, false);
3493 StartFind(current_find_text
.c_str(), false);
3497 void PDFiumEngine::SetSelecting(bool selecting
) {
3498 bool was_selecting
= selecting_
;
3499 selecting_
= selecting
;
3500 if (selecting_
!= was_selecting
)
3501 client_
->IsSelectingChanged(selecting
);
3504 void PDFiumEngine::Form_Invalidate(FPDF_FORMFILLINFO
* param
,
3510 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3511 int page_index
= engine
->GetVisiblePageIndex(page
);
3512 if (page_index
== -1) {
3513 // This can sometime happen when the page is closed because it went off
3514 // screen, and PDFium invalidates the control as it's being deleted.
3518 pp::Rect rect
= engine
->pages_
[page_index
]->PageToScreen(
3519 engine
->GetVisibleRect().point(), engine
->current_zoom_
, left
, top
, right
,
3520 bottom
, engine
->current_rotation_
);
3521 engine
->client_
->Invalidate(rect
);
3524 void PDFiumEngine::Form_OutputSelectedRect(FPDF_FORMFILLINFO
* param
,
3530 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3531 int page_index
= engine
->GetVisiblePageIndex(page
);
3532 if (page_index
== -1) {
3536 pp::Rect rect
= engine
->pages_
[page_index
]->PageToScreen(
3537 engine
->GetVisibleRect().point(), engine
->current_zoom_
, left
, top
, right
,
3538 bottom
, engine
->current_rotation_
);
3539 engine
->form_highlights_
.push_back(rect
);
3542 void PDFiumEngine::Form_SetCursor(FPDF_FORMFILLINFO
* param
, int cursor_type
) {
3543 // We don't need this since it's not enough to change the cursor in all
3544 // scenarios. Instead, we check which form field we're under in OnMouseMove.
3547 int PDFiumEngine::Form_SetTimer(FPDF_FORMFILLINFO
* param
,
3549 TimerCallback timer_func
) {
3550 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3551 engine
->timers_
[++engine
->next_timer_id_
] =
3552 std::pair
<int, TimerCallback
>(elapse
, timer_func
);
3553 engine
->client_
->ScheduleCallback(engine
->next_timer_id_
, elapse
);
3554 return engine
->next_timer_id_
;
3557 void PDFiumEngine::Form_KillTimer(FPDF_FORMFILLINFO
* param
, int timer_id
) {
3558 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3559 engine
->timers_
.erase(timer_id
);
3562 FPDF_SYSTEMTIME
PDFiumEngine::Form_GetLocalTime(FPDF_FORMFILLINFO
* param
) {
3563 base::Time time
= base::Time::Now();
3564 base::Time::Exploded exploded
;
3565 time
.LocalExplode(&exploded
);
3568 rv
.wYear
= exploded
.year
;
3569 rv
.wMonth
= exploded
.month
;
3570 rv
.wDayOfWeek
= exploded
.day_of_week
;
3571 rv
.wDay
= exploded
.day_of_month
;
3572 rv
.wHour
= exploded
.hour
;
3573 rv
.wMinute
= exploded
.minute
;
3574 rv
.wSecond
= exploded
.second
;
3575 rv
.wMilliseconds
= exploded
.millisecond
;
3579 void PDFiumEngine::Form_OnChange(FPDF_FORMFILLINFO
* param
) {
3580 // Don't care about.
3583 FPDF_PAGE
PDFiumEngine::Form_GetPage(FPDF_FORMFILLINFO
* param
,
3584 FPDF_DOCUMENT document
,
3586 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3587 if (page_index
< 0 || page_index
>= static_cast<int>(engine
->pages_
.size()))
3589 return engine
->pages_
[page_index
]->GetPage();
3592 FPDF_PAGE
PDFiumEngine::Form_GetCurrentPage(FPDF_FORMFILLINFO
* param
,
3593 FPDF_DOCUMENT document
) {
3594 // TODO(jam): find out what this is used for.
3595 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3596 int index
= engine
->last_page_mouse_down_
;
3598 index
= engine
->GetMostVisiblePage();
3605 return engine
->pages_
[index
]->GetPage();
3608 int PDFiumEngine::Form_GetRotation(FPDF_FORMFILLINFO
* param
, FPDF_PAGE page
) {
3612 void PDFiumEngine::Form_ExecuteNamedAction(FPDF_FORMFILLINFO
* param
,
3613 FPDF_BYTESTRING named_action
) {
3614 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3615 std::string
action(named_action
);
3616 if (action
== "Print") {
3617 engine
->client_
->Print();
3621 int index
= engine
->last_page_mouse_down_
;
3622 /* Don't try to calculate the most visible page if we don't have a left click
3623 before this event (this code originally copied Form_GetCurrentPage which of
3624 course needs to do that and which doesn't have recursion). This can end up
3625 causing infinite recursion. See http://crbug.com/240413 for more
3626 information. Either way, it's not necessary for the spec'd list of named
3629 index = engine->GetMostVisiblePage();
3634 // This is the only list of named actions per the spec (see 12.6.4.11). Adobe
3635 // Reader supports more, like FitWidth, but since they're not part of the spec
3636 // and we haven't got bugs about them, no need to now.
3637 if (action
== "NextPage") {
3638 engine
->client_
->ScrollToPage(index
+ 1);
3639 } else if (action
== "PrevPage") {
3640 engine
->client_
->ScrollToPage(index
- 1);
3641 } else if (action
== "FirstPage") {
3642 engine
->client_
->ScrollToPage(0);
3643 } else if (action
== "LastPage") {
3644 engine
->client_
->ScrollToPage(engine
->pages_
.size() - 1);
3648 void PDFiumEngine::Form_SetTextFieldFocus(FPDF_FORMFILLINFO
* param
,
3649 FPDF_WIDESTRING value
,
3650 FPDF_DWORD valueLen
,
3651 FPDF_BOOL is_focus
) {
3652 // Do nothing for now.
3653 // TODO(gene): use this signal to trigger OSK.
3656 void PDFiumEngine::Form_DoURIAction(FPDF_FORMFILLINFO
* param
,
3657 FPDF_BYTESTRING uri
) {
3658 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3659 engine
->client_
->NavigateTo(std::string(uri
), false);
3662 void PDFiumEngine::Form_DoGoToAction(FPDF_FORMFILLINFO
* param
,
3665 float* position_array
,
3666 int size_of_array
) {
3667 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3668 engine
->client_
->ScrollToPage(page_index
);
3671 int PDFiumEngine::Form_Alert(IPDF_JSPLATFORM
* param
,
3672 FPDF_WIDESTRING message
,
3673 FPDF_WIDESTRING title
,
3676 // See fpdfformfill.h for these values.
3679 ALERT_TYPE_OK_CANCEL
,
3681 ALERT_TYPE_YES_NO_CANCEL
3685 ALERT_RESULT_OK
= 1,
3686 ALERT_RESULT_CANCEL
,
3691 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3692 std::string message_str
=
3693 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(message
));
3694 if (type
== ALERT_TYPE_OK
) {
3695 engine
->client_
->Alert(message_str
);
3696 return ALERT_RESULT_OK
;
3699 bool rv
= engine
->client_
->Confirm(message_str
);
3700 if (type
== ALERT_TYPE_OK_CANCEL
)
3701 return rv
? ALERT_RESULT_OK
: ALERT_RESULT_CANCEL
;
3702 return rv
? ALERT_RESULT_YES
: ALERT_RESULT_NO
;
3705 void PDFiumEngine::Form_Beep(IPDF_JSPLATFORM
* param
, int type
) {
3706 // Beeps are annoying, and not possible using javascript, so ignore for now.
3709 int PDFiumEngine::Form_Response(IPDF_JSPLATFORM
* param
,
3710 FPDF_WIDESTRING question
,
3711 FPDF_WIDESTRING title
,
3712 FPDF_WIDESTRING default_response
,
3713 FPDF_WIDESTRING label
,
3717 std::string question_str
= base::UTF16ToUTF8(
3718 reinterpret_cast<const base::char16
*>(question
));
3719 std::string default_str
= base::UTF16ToUTF8(
3720 reinterpret_cast<const base::char16
*>(default_response
));
3722 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3723 std::string rv
= engine
->client_
->Prompt(question_str
, default_str
);
3724 base::string16 rv_16
= base::UTF8ToUTF16(rv
);
3725 int rv_bytes
= rv_16
.size() * sizeof(base::char16
);
3727 int bytes_to_copy
= rv_bytes
< length
? rv_bytes
: length
;
3728 memcpy(response
, rv_16
.c_str(), bytes_to_copy
);
3733 int PDFiumEngine::Form_GetFilePath(IPDF_JSPLATFORM
* param
,
3736 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3737 std::string rv
= engine
->client_
->GetURL();
3738 if (file_path
&& rv
.size() <= static_cast<size_t>(length
))
3739 memcpy(file_path
, rv
.c_str(), rv
.size());
3743 void PDFiumEngine::Form_Mail(IPDF_JSPLATFORM
* param
,
3748 FPDF_WIDESTRING subject
,
3750 FPDF_WIDESTRING bcc
,
3751 FPDF_WIDESTRING message
) {
3752 // Note: |mail_data| and |length| are ignored. We don't handle attachments;
3753 // there is no way with mailto.
3754 std::string to_str
=
3755 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(to
));
3756 std::string cc_str
=
3757 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(cc
));
3758 std::string bcc_str
=
3759 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(bcc
));
3760 std::string subject_str
=
3761 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(subject
));
3762 std::string message_str
=
3763 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(message
));
3765 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3766 engine
->client_
->Email(to_str
, cc_str
, bcc_str
, subject_str
, message_str
);
3769 void PDFiumEngine::Form_Print(IPDF_JSPLATFORM
* param
,
3774 FPDF_BOOL shrink_to_fit
,
3775 FPDF_BOOL print_as_image
,
3777 FPDF_BOOL annotations
) {
3778 // No way to pass the extra information to the print dialog using JavaScript.
3779 // Just opening it is fine for now.
3780 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3781 engine
->client_
->Print();
3784 void PDFiumEngine::Form_SubmitForm(IPDF_JSPLATFORM
* param
,
3787 FPDF_WIDESTRING url
) {
3788 std::string url_str
=
3789 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(url
));
3790 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3791 engine
->client_
->SubmitForm(url_str
, form_data
, length
);
3794 void PDFiumEngine::Form_GotoPage(IPDF_JSPLATFORM
* param
,
3796 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3797 engine
->client_
->ScrollToPage(page_number
);
3800 int PDFiumEngine::Form_Browse(IPDF_JSPLATFORM
* param
,
3803 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3804 std::string path
= engine
->client_
->ShowFileSelectionDialog();
3805 if (path
.size() + 1 <= static_cast<size_t>(length
))
3806 memcpy(file_path
, &path
[0], path
.size() + 1);
3807 return path
.size() + 1;
3810 FPDF_BOOL
PDFiumEngine::Pause_NeedToPauseNow(IFSDK_PAUSE
* param
) {
3811 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3812 return (base::Time::Now() - engine
->last_progressive_start_time_
).
3813 InMilliseconds() > engine
->progressive_paint_timeout_
;
3816 ScopedUnsupportedFeature::ScopedUnsupportedFeature(PDFiumEngine
* engine
)
3817 : engine_(engine
), old_engine_(g_engine_for_unsupported
) {
3818 g_engine_for_unsupported
= engine_
;
3821 ScopedUnsupportedFeature::~ScopedUnsupportedFeature() {
3822 g_engine_for_unsupported
= old_engine_
;
3825 PDFEngineExports
* PDFEngineExports::Create() {
3826 return new PDFiumEngineExports
;
3831 int CalculatePosition(FPDF_PAGE page
,
3832 const PDFiumEngineExports::RenderingSettings
& settings
,
3834 int page_width
= static_cast<int>(ConvertUnitDouble(FPDF_GetPageWidth(page
),
3837 int page_height
= static_cast<int>(ConvertUnitDouble(FPDF_GetPageHeight(page
),
3841 // Start by assuming that we will draw exactly to the bounds rect
3843 *dest
= settings
.bounds
;
3845 int rotate
= 0; // normal orientation.
3847 // Auto-rotate landscape pages to print correctly.
3848 if (settings
.autorotate
&&
3849 (dest
->width() > dest
->height()) != (page_width
> page_height
)) {
3850 rotate
= 3; // 90 degrees counter-clockwise.
3851 std::swap(page_width
, page_height
);
3854 // See if we need to scale the output
3855 bool scale_to_bounds
= false;
3856 if (settings
.fit_to_bounds
&&
3857 ((page_width
> dest
->width()) || (page_height
> dest
->height()))) {
3858 scale_to_bounds
= true;
3859 } else if (settings
.stretch_to_bounds
&&
3860 ((page_width
< dest
->width()) || (page_height
< dest
->height()))) {
3861 scale_to_bounds
= true;
3864 if (scale_to_bounds
) {
3865 // If we need to maintain aspect ratio, calculate the actual width and
3867 if (settings
.keep_aspect_ratio
) {
3868 double scale_factor_x
= page_width
;
3869 scale_factor_x
/= dest
->width();
3870 double scale_factor_y
= page_height
;
3871 scale_factor_y
/= dest
->height();
3872 if (scale_factor_x
> scale_factor_y
) {
3873 dest
->set_height(page_height
/ scale_factor_x
);
3875 dest
->set_width(page_width
/ scale_factor_y
);
3879 // We are not scaling to bounds. Draw in the actual page size. If the
3880 // actual page size is larger than the bounds, the output will be
3882 dest
->set_width(page_width
);
3883 dest
->set_height(page_height
);
3886 if (settings
.center_in_bounds
) {
3887 pp::Point
offset((settings
.bounds
.width() - dest
->width()) / 2,
3888 (settings
.bounds
.height() - dest
->height()) / 2);
3889 dest
->Offset(offset
);
3897 bool PDFiumEngineExports::RenderPDFPageToDC(const void* pdf_buffer
,
3900 const RenderingSettings
& settings
,
3902 FPDF_DOCUMENT doc
= FPDF_LoadMemDocument(pdf_buffer
, buffer_size
, NULL
);
3905 FPDF_PAGE page
= FPDF_LoadPage(doc
, page_number
);
3907 FPDF_CloseDocument(doc
);
3910 RenderingSettings new_settings
= settings
;
3911 // calculate the page size
3912 if (new_settings
.dpi_x
== -1)
3913 new_settings
.dpi_x
= GetDeviceCaps(dc
, LOGPIXELSX
);
3914 if (new_settings
.dpi_y
== -1)
3915 new_settings
.dpi_y
= GetDeviceCaps(dc
, LOGPIXELSY
);
3918 int rotate
= CalculatePosition(page
, new_settings
, &dest
);
3920 int save_state
= SaveDC(dc
);
3921 // The caller wanted all drawing to happen within the bounds specified.
3922 // Based on scale calculations, our destination rect might be larger
3923 // than the bounds. Set the clip rect to the bounds.
3924 IntersectClipRect(dc
, settings
.bounds
.x(), settings
.bounds
.y(),
3925 settings
.bounds
.x() + settings
.bounds
.width(),
3926 settings
.bounds
.y() + settings
.bounds
.height());
3928 // A temporary hack. PDFs generated by Cairo (used by Chrome OS to generate
3929 // a PDF output from a webpage) result in very large metafiles and the
3930 // rendering using FPDF_RenderPage is incorrect. In this case, render as a
3931 // bitmap. Note that this code does not kick in for PDFs printed from Chrome
3932 // because in that case we create a temp PDF first before printing and this
3933 // temp PDF does not have a creator string that starts with "cairo".
3934 base::string16 creator
;
3935 size_t buffer_bytes
= FPDF_GetMetaText(doc
, "Creator", NULL
, 0);
3936 if (buffer_bytes
> 1) {
3937 FPDF_GetMetaText(doc
, "Creator",
3938 base::WriteInto(&creator
, buffer_bytes
+ 1), buffer_bytes
);
3940 bool use_bitmap
= false;
3941 if (base::StartsWith(creator
, L
"cairo", base::CompareCase::INSENSITIVE_ASCII
))
3944 // Another temporary hack. Some PDFs seems to render very slowly if
3945 // FPDF_RenderPage is directly used on a printer DC. I suspect it is
3946 // because of the code to talk Postscript directly to the printer if
3947 // the printer supports this. Need to discuss this with PDFium. For now,
3948 // render to a bitmap and then blit the bitmap to the DC if we have been
3949 // supplied a printer DC.
3950 int device_type
= GetDeviceCaps(dc
, TECHNOLOGY
);
3952 (device_type
== DT_RASPRINTER
) || (device_type
== DT_PLOTTER
)) {
3953 FPDF_BITMAP bitmap
= FPDFBitmap_Create(dest
.width(), dest
.height(),
3956 FPDFBitmap_FillRect(bitmap
, 0, 0, dest
.width(), dest
.height(), 0xFFFFFFFF);
3957 FPDF_RenderPageBitmap(
3958 bitmap
, page
, 0, 0, dest
.width(), dest
.height(), rotate
,
3959 FPDF_ANNOT
| FPDF_PRINTING
| FPDF_NO_CATCH
);
3960 int stride
= FPDFBitmap_GetStride(bitmap
);
3962 memset(&bmi
, 0, sizeof(bmi
));
3963 bmi
.bmiHeader
.biSize
= sizeof(BITMAPINFOHEADER
);
3964 bmi
.bmiHeader
.biWidth
= dest
.width();
3965 bmi
.bmiHeader
.biHeight
= -dest
.height(); // top-down image
3966 bmi
.bmiHeader
.biPlanes
= 1;
3967 bmi
.bmiHeader
.biBitCount
= 32;
3968 bmi
.bmiHeader
.biCompression
= BI_RGB
;
3969 bmi
.bmiHeader
.biSizeImage
= stride
* dest
.height();
3970 StretchDIBits(dc
, dest
.x(), dest
.y(), dest
.width(), dest
.height(),
3971 0, 0, dest
.width(), dest
.height(),
3972 FPDFBitmap_GetBuffer(bitmap
), &bmi
, DIB_RGB_COLORS
, SRCCOPY
);
3973 FPDFBitmap_Destroy(bitmap
);
3975 FPDF_RenderPage(dc
, page
, dest
.x(), dest
.y(), dest
.width(), dest
.height(),
3976 rotate
, FPDF_ANNOT
| FPDF_PRINTING
| FPDF_NO_CATCH
);
3978 RestoreDC(dc
, save_state
);
3979 FPDF_ClosePage(page
);
3980 FPDF_CloseDocument(doc
);
3985 bool PDFiumEngineExports::RenderPDFPageToBitmap(
3986 const void* pdf_buffer
,
3987 int pdf_buffer_size
,
3989 const RenderingSettings
& settings
,
3990 void* bitmap_buffer
) {
3991 FPDF_DOCUMENT doc
= FPDF_LoadMemDocument(pdf_buffer
, pdf_buffer_size
, NULL
);
3994 FPDF_PAGE page
= FPDF_LoadPage(doc
, page_number
);
3996 FPDF_CloseDocument(doc
);
4001 int rotate
= CalculatePosition(page
, settings
, &dest
);
4003 FPDF_BITMAP bitmap
=
4004 FPDFBitmap_CreateEx(settings
.bounds
.width(), settings
.bounds
.height(),
4005 FPDFBitmap_BGRA
, bitmap_buffer
,
4006 settings
.bounds
.width() * 4);
4008 FPDFBitmap_FillRect(bitmap
, 0, 0, settings
.bounds
.width(),
4009 settings
.bounds
.height(), 0xFFFFFFFF);
4010 // Shift top-left corner of bounds to (0, 0) if it's not there.
4011 dest
.set_point(dest
.point() - settings
.bounds
.point());
4012 FPDF_RenderPageBitmap(
4013 bitmap
, page
, dest
.x(), dest
.y(), dest
.width(), dest
.height(), rotate
,
4014 FPDF_ANNOT
| FPDF_PRINTING
| FPDF_NO_CATCH
);
4015 FPDFBitmap_Destroy(bitmap
);
4016 FPDF_ClosePage(page
);
4017 FPDF_CloseDocument(doc
);
4021 bool PDFiumEngineExports::GetPDFDocInfo(const void* pdf_buffer
,
4024 double* max_page_width
) {
4025 FPDF_DOCUMENT doc
= FPDF_LoadMemDocument(pdf_buffer
, buffer_size
, NULL
);
4028 int page_count_local
= FPDF_GetPageCount(doc
);
4030 *page_count
= page_count_local
;
4032 if (max_page_width
) {
4033 *max_page_width
= 0;
4034 for (int page_number
= 0; page_number
< page_count_local
; page_number
++) {
4035 double page_width
= 0;
4036 double page_height
= 0;
4037 FPDF_GetPageSizeByIndex(doc
, page_number
, &page_width
, &page_height
);
4038 if (page_width
> *max_page_width
) {
4039 *max_page_width
= page_width
;
4043 FPDF_CloseDocument(doc
);
4047 bool PDFiumEngineExports::GetPDFPageSizeByIndex(
4048 const void* pdf_buffer
,
4049 int pdf_buffer_size
,
4053 FPDF_DOCUMENT doc
= FPDF_LoadMemDocument(pdf_buffer
, pdf_buffer_size
, NULL
);
4056 bool success
= FPDF_GetPageSizeByIndex(doc
, page_number
, width
, height
) != 0;
4057 FPDF_CloseDocument(doc
);
4061 } // namespace chrome_pdf