1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "pdf/pdfium/pdfium_engine.h"
9 #include "base/json/json_writer.h"
10 #include "base/logging.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/stl_util.h"
13 #include "base/strings/string_number_conversions.h"
14 #include "base/strings/string_piece.h"
15 #include "base/strings/string_util.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "base/values.h"
18 #include "pdf/draw_utils.h"
19 #include "pdf/pdfium/pdfium_mem_buffer_file_read.h"
20 #include "pdf/pdfium/pdfium_mem_buffer_file_write.h"
21 #include "ppapi/c/pp_errors.h"
22 #include "ppapi/c/pp_input_event.h"
23 #include "ppapi/c/ppb_core.h"
24 #include "ppapi/c/private/ppb_pdf.h"
25 #include "ppapi/cpp/dev/memory_dev.h"
26 #include "ppapi/cpp/input_event.h"
27 #include "ppapi/cpp/instance.h"
28 #include "ppapi/cpp/module.h"
29 #include "ppapi/cpp/private/pdf.h"
30 #include "ppapi/cpp/trusted/browser_font_trusted.h"
31 #include "ppapi/cpp/url_response_info.h"
32 #include "ppapi/cpp/var.h"
33 #include "third_party/pdfium/fpdfsdk/include/fpdf_ext.h"
34 #include "third_party/pdfium/fpdfsdk/include/fpdf_flatten.h"
35 #include "third_party/pdfium/fpdfsdk/include/fpdf_searchex.h"
36 #include "third_party/pdfium/fpdfsdk/include/fpdf_sysfontinfo.h"
37 #include "third_party/pdfium/fpdfsdk/include/fpdf_transformpage.h"
38 #include "third_party/pdfium/fpdfsdk/include/fpdfedit.h"
39 #include "third_party/pdfium/fpdfsdk/include/fpdfoom.h"
40 #include "third_party/pdfium/fpdfsdk/include/fpdfppo.h"
41 #include "third_party/pdfium/fpdfsdk/include/fpdfsave.h"
42 #include "third_party/pdfium/fpdfsdk/include/pdfwindow/PDFWindow.h"
43 #include "third_party/pdfium/fpdfsdk/include/pdfwindow/PWL_FontMap.h"
44 #include "ui/events/keycodes/keyboard_codes.h"
46 namespace chrome_pdf
{
50 #define kPageShadowTop 3
51 #define kPageShadowBottom 7
52 #define kPageShadowLeft 5
53 #define kPageShadowRight 5
55 #define kPageSeparatorThickness 4
56 #define kHighlightColorR 153
57 #define kHighlightColorG 193
58 #define kHighlightColorB 218
60 const uint32 kPendingPageColor
= 0xFFEEEEEE;
62 #define kFormHighlightColor 0xFFE4DD
63 #define kFormHighlightAlpha 100
65 #define kMaxPasswordTries 3
68 // http://www.adobe.com/devnet/acrobat/pdfs/pdf_reference_1-7.pdf
69 #define kPDFPermissionPrintLowQualityMask 1 << 2
70 #define kPDFPermissionPrintHighQualityMask 1 << 11
71 #define kPDFPermissionCopyMask 1 << 4
72 #define kPDFPermissionCopyAccessibleMask 1 << 9
74 #define kLoadingTextVerticalOffset 50
76 // The maximum amount of time we'll spend doing a paint before we give back
77 // control of the thread.
78 #define kMaxProgressivePaintTimeMs 50
80 // The maximum amount of time we'll spend doing the first paint. This is less
81 // than the above to keep things smooth if the user is scrolling quickly. We
82 // try painting a little because with accelerated compositing, we get flushes
83 // only every 16 ms. If we were to wait until the next flush to paint the rest
84 // of the pdf, we would never get to draw the pdf and would only draw the
85 // scrollbars. This value is picked to give enough time for gpu related code to
86 // do its thing and still fit within the timelimit for 60Hz. For the
87 // non-composited case, this doesn't make things worse since we're still
88 // painting the scrollbars > 60 Hz.
89 #define kMaxInitialProgressivePaintTimeMs 10
91 // Copied from printing/units.cc because we don't want to depend on printing
92 // since it brings in libpng which causes duplicate symbols with PDFium.
93 const int kPointsPerInch
= 72;
94 const int kPixelsPerInch
= 96;
103 int ConvertUnit(int value
, int old_unit
, int new_unit
) {
104 // With integer arithmetic, to divide a value with correct rounding, you need
105 // to add half of the divisor value to the dividend value. You need to do the
106 // reverse with negative number.
108 return ((value
* new_unit
) + (old_unit
/ 2)) / old_unit
;
110 return ((value
* new_unit
) - (old_unit
/ 2)) / old_unit
;
114 std::vector
<uint32_t> GetPageNumbersFromPrintPageNumberRange(
115 const PP_PrintPageNumberRange_Dev
* page_ranges
,
116 uint32_t page_range_count
) {
117 std::vector
<uint32_t> page_numbers
;
118 for (uint32_t index
= 0; index
< page_range_count
; ++index
) {
119 for (uint32_t page_number
= page_ranges
[index
].first_page_number
;
120 page_number
<= page_ranges
[index
].last_page_number
; ++page_number
) {
121 page_numbers
.push_back(page_number
);
127 #if defined(OS_LINUX)
129 PP_Instance g_last_instance_id
;
131 struct PDFFontSubstitution
{
132 const char* pdf_name
;
138 PP_BrowserFont_Trusted_Weight
WeightToBrowserFontTrustedWeight(int weight
) {
139 COMPILE_ASSERT(PP_BROWSERFONT_TRUSTED_WEIGHT_100
== 0,
140 PP_BrowserFont_Trusted_Weight_Min
);
141 COMPILE_ASSERT(PP_BROWSERFONT_TRUSTED_WEIGHT_900
== 8,
142 PP_BrowserFont_Trusted_Weight_Max
);
143 const int kMinimumWeight
= 100;
144 const int kMaximumWeight
= 900;
145 int normalized_weight
=
146 std::min(std::max(weight
, kMinimumWeight
), kMaximumWeight
);
147 normalized_weight
= (normalized_weight
/ 100) - 1;
148 return static_cast<PP_BrowserFont_Trusted_Weight
>(normalized_weight
);
151 // This list is for CPWL_FontMap::GetDefaultFontByCharset().
152 // We pretend to have these font natively and let the browser (or underlying
153 // fontconfig) to pick the proper font on the system.
154 void EnumFonts(struct _FPDF_SYSFONTINFO
* sysfontinfo
, void* mapper
) {
155 FPDF_AddInstalledFont(mapper
, "Arial", FXFONT_DEFAULT_CHARSET
);
158 while (CPWL_FontMap::defaultTTFMap
[i
].charset
!= -1) {
159 FPDF_AddInstalledFont(mapper
,
160 CPWL_FontMap::defaultTTFMap
[i
].fontname
,
161 CPWL_FontMap::defaultTTFMap
[i
].charset
);
166 const PDFFontSubstitution PDFFontSubstitutions
[] = {
167 {"Courier", "Courier New", false, false},
168 {"Courier-Bold", "Courier New", true, false},
169 {"Courier-BoldOblique", "Courier New", true, true},
170 {"Courier-Oblique", "Courier New", false, true},
171 {"Helvetica", "Arial", false, false},
172 {"Helvetica-Bold", "Arial", true, false},
173 {"Helvetica-BoldOblique", "Arial", true, true},
174 {"Helvetica-Oblique", "Arial", false, true},
175 {"Times-Roman", "Times New Roman", false, false},
176 {"Times-Bold", "Times New Roman", true, false},
177 {"Times-BoldItalic", "Times New Roman", true, true},
178 {"Times-Italic", "Times New Roman", false, true},
180 // MS P?(Mincho|Gothic) are the most notable fonts in Japanese PDF files
181 // without embedding the glyphs. Sometimes the font names are encoded
182 // in Japanese Windows's locale (CP932/Shift_JIS) without space.
183 // Most Linux systems don't have the exact font, but for outsourcing
184 // fontconfig to find substitutable font in the system, we pass ASCII
186 {"MS-PGothic", "MS PGothic", false, false},
187 {"MS-Gothic", "MS Gothic", false, false},
188 {"MS-PMincho", "MS PMincho", false, false},
189 {"MS-Mincho", "MS Mincho", false, false},
190 // MS PGothic in Shift_JIS encoding.
191 {"\x82\x6C\x82\x72\x82\x6F\x83\x53\x83\x56\x83\x62\x83\x4E",
192 "MS PGothic", false, false},
193 // MS Gothic in Shift_JIS encoding.
194 {"\x82\x6C\x82\x72\x83\x53\x83\x56\x83\x62\x83\x4E",
195 "MS Gothic", false, false},
196 // MS PMincho in Shift_JIS encoding.
197 {"\x82\x6C\x82\x72\x82\x6F\x96\xBE\x92\xA9",
198 "MS PMincho", false, false},
199 // MS Mincho in Shift_JIS encoding.
200 {"\x82\x6C\x82\x72\x96\xBE\x92\xA9",
201 "MS Mincho", false, false},
204 void* MapFont(struct _FPDF_SYSFONTINFO
*, int weight
, int italic
,
205 int charset
, int pitch_family
, const char* face
, int* exact
) {
206 // Do not attempt to map fonts if pepper is not initialized (for privet local
208 // TODO(noamsml): Real font substitution (http://crbug.com/391978)
209 if (!pp::Module::Get())
212 pp::BrowserFontDescription description
;
214 // Pretend the system does not have the Symbol font to force a fallback to
215 // the built in Symbol font in CFX_FontMapper::FindSubstFont().
216 if (strcmp(face
, "Symbol") == 0)
219 if (pitch_family
& FXFONT_FF_FIXEDPITCH
) {
220 description
.set_family(PP_BROWSERFONT_TRUSTED_FAMILY_MONOSPACE
);
221 } else if (pitch_family
& FXFONT_FF_ROMAN
) {
222 description
.set_family(PP_BROWSERFONT_TRUSTED_FAMILY_SERIF
);
225 // Map from the standard PDF fonts to TrueType font names.
227 for (i
= 0; i
< arraysize(PDFFontSubstitutions
); ++i
) {
228 if (strcmp(face
, PDFFontSubstitutions
[i
].pdf_name
) == 0) {
229 description
.set_face(PDFFontSubstitutions
[i
].face
);
230 if (PDFFontSubstitutions
[i
].bold
)
231 description
.set_weight(PP_BROWSERFONT_TRUSTED_WEIGHT_BOLD
);
232 if (PDFFontSubstitutions
[i
].italic
)
233 description
.set_italic(true);
238 if (i
== arraysize(PDFFontSubstitutions
)) {
239 // TODO(kochi): Pass the face in UTF-8. If face is not encoded in UTF-8,
240 // convert to UTF-8 before passing.
241 description
.set_face(face
);
243 description
.set_weight(WeightToBrowserFontTrustedWeight(weight
));
244 description
.set_italic(italic
> 0);
247 if (!pp::PDF::IsAvailable()) {
252 PP_Resource font_resource
= pp::PDF::GetFontFileWithFallback(
253 pp::InstanceHandle(g_last_instance_id
),
254 &description
.pp_font_description(),
255 static_cast<PP_PrivateFontCharset
>(charset
));
256 long res_id
= font_resource
;
257 return reinterpret_cast<void*>(res_id
);
260 unsigned long GetFontData(struct _FPDF_SYSFONTINFO
*, void* font_id
,
261 unsigned int table
, unsigned char* buffer
,
262 unsigned long buf_size
) {
263 if (!pp::PDF::IsAvailable()) {
268 uint32_t size
= buf_size
;
269 long res_id
= reinterpret_cast<long>(font_id
);
270 if (!pp::PDF::GetFontTableForPrivateFontFile(res_id
, table
, buffer
, &size
))
275 void DeleteFont(struct _FPDF_SYSFONTINFO
*, void* font_id
) {
276 long res_id
= reinterpret_cast<long>(font_id
);
277 pp::Module::Get()->core()->ReleaseResource(res_id
);
280 FPDF_SYSFONTINFO g_font_info
= {
291 #endif // defined(OS_LINUX)
293 void OOM_Handler(_OOM_INFO
*) {
294 // Kill the process. This is important for security, since the code doesn't
295 // NULL-check many memory allocations. If a malloc fails, returns NULL, and
296 // the buffer is then used, it provides a handy mapping of memory starting at
297 // address 0 for an attacker to utilize.
301 OOM_INFO g_oom_info
= {
306 PDFiumEngine
* g_engine_for_unsupported
;
308 void Unsupported_Handler(UNSUPPORT_INFO
*, int type
) {
309 if (!g_engine_for_unsupported
) {
314 g_engine_for_unsupported
->UnsupportedFeature(type
);
317 UNSUPPORT_INFO g_unsuppored_info
= {
322 // Set the destination page size and content area in points based on source
323 // page rotation and orientation.
325 // |rotated| True if source page is rotated 90 degree or 270 degree.
326 // |is_src_page_landscape| is true if the source page orientation is landscape.
327 // |page_size| has the actual destination page size in points.
328 // |content_rect| has the actual destination page printable area values in
330 void SetPageSizeAndContentRect(bool rotated
,
331 bool is_src_page_landscape
,
333 pp::Rect
* content_rect
) {
334 bool is_dst_page_landscape
= page_size
->width() > page_size
->height();
335 bool page_orientation_mismatched
= is_src_page_landscape
!=
336 is_dst_page_landscape
;
337 bool rotate_dst_page
= rotated
^ page_orientation_mismatched
;
338 if (rotate_dst_page
) {
339 page_size
->SetSize(page_size
->height(), page_size
->width());
340 content_rect
->SetRect(content_rect
->y(), content_rect
->x(),
341 content_rect
->height(), content_rect
->width());
345 // Calculate the scale factor between |content_rect| and a page of size
346 // |src_width| x |src_height|.
348 // |scale_to_fit| is true, if we need to calculate the scale factor.
349 // |content_rect| specifies the printable area of the destination page, with
350 // origin at left-bottom. Values are in points.
351 // |src_width| specifies the source page width in points.
352 // |src_height| specifies the source page height in points.
353 // |rotated| True if source page is rotated 90 degree or 270 degree.
354 double CalculateScaleFactor(bool scale_to_fit
,
355 const pp::Rect
& content_rect
,
356 double src_width
, double src_height
, bool rotated
) {
357 if (!scale_to_fit
|| src_width
== 0 || src_height
== 0)
360 double actual_source_page_width
= rotated
? src_height
: src_width
;
361 double actual_source_page_height
= rotated
? src_width
: src_height
;
362 double ratio_x
= static_cast<double>(content_rect
.width()) /
363 actual_source_page_width
;
364 double ratio_y
= static_cast<double>(content_rect
.height()) /
365 actual_source_page_height
;
366 return std::min(ratio_x
, ratio_y
);
369 // Compute source clip box boundaries based on the crop box / media box of
370 // source page and scale factor.
372 // |page| Handle to the source page. Returned by FPDF_LoadPage function.
373 // |scale_factor| specifies the scale factor that should be applied to source
374 // clip box boundaries.
375 // |rotated| True if source page is rotated 90 degree or 270 degree.
376 // |clip_box| out param to hold the computed source clip box values.
377 void CalculateClipBoxBoundary(FPDF_PAGE page
, double scale_factor
, bool rotated
,
379 if (!FPDFPage_GetCropBox(page
, &clip_box
->left
, &clip_box
->bottom
,
380 &clip_box
->right
, &clip_box
->top
)) {
381 if (!FPDFPage_GetMediaBox(page
, &clip_box
->left
, &clip_box
->bottom
,
382 &clip_box
->right
, &clip_box
->top
)) {
383 // Make the default size to be letter size (8.5" X 11"). We are just
384 // following the PDFium way of handling these corner cases. PDFium always
385 // consider US-Letter as the default page size.
386 float paper_width
= 612;
387 float paper_height
= 792;
389 clip_box
->bottom
= 0;
390 clip_box
->right
= rotated
? paper_height
: paper_width
;
391 clip_box
->top
= rotated
? paper_width
: paper_height
;
394 clip_box
->left
*= scale_factor
;
395 clip_box
->right
*= scale_factor
;
396 clip_box
->bottom
*= scale_factor
;
397 clip_box
->top
*= scale_factor
;
400 // Calculate the clip box translation offset for a page that does need to be
401 // scaled. All parameters are in points.
403 // |content_rect| specifies the printable area of the destination page, with
404 // origin at left-bottom.
405 // |source_clip_box| specifies the source clip box positions, relative to
406 // origin at left-bottom.
407 // |offset_x| and |offset_y| will contain the final translation offsets for the
408 // source clip box, relative to origin at left-bottom.
409 void CalculateScaledClipBoxOffset(const pp::Rect
& content_rect
,
410 const ClipBox
& source_clip_box
,
411 double* offset_x
, double* offset_y
) {
412 const float clip_box_width
= source_clip_box
.right
- source_clip_box
.left
;
413 const float clip_box_height
= source_clip_box
.top
- source_clip_box
.bottom
;
415 // Center the intended clip region to real clip region.
416 *offset_x
= (content_rect
.width() - clip_box_width
) / 2 + content_rect
.x() -
417 source_clip_box
.left
;
418 *offset_y
= (content_rect
.height() - clip_box_height
) / 2 + content_rect
.y() -
419 source_clip_box
.bottom
;
422 // Calculate the clip box offset for a page that does not need to be scaled.
423 // All parameters are in points.
425 // |content_rect| specifies the printable area of the destination page, with
426 // origin at left-bottom.
427 // |rotation| specifies the source page rotation values which are N / 90
429 // |page_width| specifies the screen destination page width.
430 // |page_height| specifies the screen destination page height.
431 // |source_clip_box| specifies the source clip box positions, relative to origin
433 // |offset_x| and |offset_y| will contain the final translation offsets for the
434 // source clip box, relative to origin at left-bottom.
435 void CalculateNonScaledClipBoxOffset(const pp::Rect
& content_rect
, int rotation
,
436 int page_width
, int page_height
,
437 const ClipBox
& source_clip_box
,
438 double* offset_x
, double* offset_y
) {
439 // Align the intended clip region to left-top corner of real clip region.
442 *offset_x
= -1 * source_clip_box
.left
;
443 *offset_y
= page_height
- source_clip_box
.top
;
447 *offset_y
= -1 * source_clip_box
.bottom
;
450 *offset_x
= page_width
- source_clip_box
.right
;
454 *offset_x
= page_height
- source_clip_box
.right
;
455 *offset_y
= page_width
- source_clip_box
.top
;
463 // This formats a string with special 0xfffe end-of-line hyphens the same way
464 // as Adobe Reader. When a hyphen is encountered, the next non-CR/LF whitespace
465 // becomes CR+LF and the hyphen is erased. If there is no whitespace between
466 // two hyphens, the latter hyphen is erased and ignored.
467 void FormatStringWithHyphens(base::string16
* text
) {
468 // First pass marks all the hyphen positions.
469 struct HyphenPosition
{
470 HyphenPosition() : position(0), next_whitespace_position(0) {}
472 size_t next_whitespace_position
; // 0 for none
474 std::vector
<HyphenPosition
> hyphen_positions
;
475 HyphenPosition current_hyphen_position
;
476 bool current_hyphen_position_is_valid
= false;
477 const base::char16 kPdfiumHyphenEOL
= 0xfffe;
479 for (size_t i
= 0; i
< text
->size(); ++i
) {
480 const base::char16
& current_char
= (*text
)[i
];
481 if (current_char
== kPdfiumHyphenEOL
) {
482 if (current_hyphen_position_is_valid
)
483 hyphen_positions
.push_back(current_hyphen_position
);
484 current_hyphen_position
= HyphenPosition();
485 current_hyphen_position
.position
= i
;
486 current_hyphen_position_is_valid
= true;
487 } else if (IsWhitespace(current_char
)) {
488 if (current_hyphen_position_is_valid
) {
489 if (current_char
!= L
'\r' && current_char
!= L
'\n')
490 current_hyphen_position
.next_whitespace_position
= i
;
491 hyphen_positions
.push_back(current_hyphen_position
);
492 current_hyphen_position_is_valid
= false;
496 if (current_hyphen_position_is_valid
)
497 hyphen_positions
.push_back(current_hyphen_position
);
499 // With all the hyphen positions, do the search and replace.
500 while (!hyphen_positions
.empty()) {
501 static const base::char16 kCr
[] = {L
'\r', L
'\0'};
502 const HyphenPosition
& position
= hyphen_positions
.back();
503 if (position
.next_whitespace_position
!= 0) {
504 (*text
)[position
.next_whitespace_position
] = L
'\n';
505 text
->insert(position
.next_whitespace_position
, kCr
);
507 text
->erase(position
.position
, 1);
508 hyphen_positions
.pop_back();
511 // Adobe Reader also get rid of trailing spaces right before a CRLF.
512 static const base::char16 kSpaceCrCn
[] = {L
' ', L
'\r', L
'\n', L
'\0'};
513 static const base::char16 kCrCn
[] = {L
'\r', L
'\n', L
'\0'};
514 ReplaceSubstringsAfterOffset(text
, 0, kSpaceCrCn
, kCrCn
);
517 // Replace CR/LF with just LF on POSIX.
518 void FormatStringForOS(base::string16
* text
) {
519 #if defined(OS_POSIX)
520 static const base::char16 kCr
[] = {L
'\r', L
'\0'};
521 static const base::char16 kBlank
[] = {L
'\0'};
522 base::ReplaceChars(*text
, kCr
, kBlank
, text
);
523 #elif defined(OS_WIN)
532 bool InitializeSDK(void* data
) {
533 FPDF_InitLibrary(data
);
535 #if defined(OS_LINUX)
536 // Font loading doesn't work in the renderer sandbox in Linux.
537 FPDF_SetSystemFontInfo(&g_font_info
);
540 FSDK_SetOOMHandler(&g_oom_info
);
541 FSDK_SetUnSpObjProcessHandler(&g_unsuppored_info
);
547 FPDF_DestroyLibrary();
550 PDFEngine
* PDFEngine::Create(PDFEngine::Client
* client
) {
551 return new PDFiumEngine(client
);
554 PDFiumEngine::PDFiumEngine(PDFEngine::Client
* client
)
557 current_rotation_(0),
559 password_tries_remaining_(0),
562 defer_page_unload_(false),
564 mouse_down_state_(PDFiumPage::NONSELECTABLE_AREA
,
565 PDFiumPage::LinkTarget()),
566 next_page_to_search_(-1),
567 last_page_to_search_(-1),
568 last_character_index_to_search_(-1),
569 current_find_index_(-1),
570 resume_find_index_(-1),
572 fpdf_availability_(NULL
),
574 last_page_mouse_down_(-1),
575 first_visible_page_(-1),
576 most_visible_page_(-1),
577 called_do_document_action_(false),
578 render_grayscale_(false),
579 progressive_paint_timeout_(0),
580 getting_password_(false) {
581 find_factory_
.Initialize(this);
582 password_factory_
.Initialize(this);
584 file_access_
.m_FileLen
= 0;
585 file_access_
.m_GetBlock
= &GetBlock
;
586 file_access_
.m_Param
= &doc_loader_
;
588 file_availability_
.version
= 1;
589 file_availability_
.IsDataAvail
= &IsDataAvail
;
590 file_availability_
.loader
= &doc_loader_
;
592 download_hints_
.version
= 1;
593 download_hints_
.AddSegment
= &AddSegment
;
594 download_hints_
.loader
= &doc_loader_
;
596 // Initialize FPDF_FORMFILLINFO member variables. Deriving from this struct
597 // allows the static callbacks to be able to cast the FPDF_FORMFILLINFO in
598 // callbacks to ourself instead of maintaining a map of them to
600 FPDF_FORMFILLINFO::version
= 1;
601 FPDF_FORMFILLINFO::m_pJsPlatform
= this;
602 FPDF_FORMFILLINFO::Release
= NULL
;
603 FPDF_FORMFILLINFO::FFI_Invalidate
= Form_Invalidate
;
604 FPDF_FORMFILLINFO::FFI_OutputSelectedRect
= Form_OutputSelectedRect
;
605 FPDF_FORMFILLINFO::FFI_SetCursor
= Form_SetCursor
;
606 FPDF_FORMFILLINFO::FFI_SetTimer
= Form_SetTimer
;
607 FPDF_FORMFILLINFO::FFI_KillTimer
= Form_KillTimer
;
608 FPDF_FORMFILLINFO::FFI_GetLocalTime
= Form_GetLocalTime
;
609 FPDF_FORMFILLINFO::FFI_OnChange
= Form_OnChange
;
610 FPDF_FORMFILLINFO::FFI_GetPage
= Form_GetPage
;
611 FPDF_FORMFILLINFO::FFI_GetCurrentPage
= Form_GetCurrentPage
;
612 FPDF_FORMFILLINFO::FFI_GetRotation
= Form_GetRotation
;
613 FPDF_FORMFILLINFO::FFI_ExecuteNamedAction
= Form_ExecuteNamedAction
;
614 FPDF_FORMFILLINFO::FFI_SetTextFieldFocus
= Form_SetTextFieldFocus
;
615 FPDF_FORMFILLINFO::FFI_DoURIAction
= Form_DoURIAction
;
616 FPDF_FORMFILLINFO::FFI_DoGoToAction
= Form_DoGoToAction
;
618 IPDF_JSPLATFORM::version
= 1;
619 IPDF_JSPLATFORM::app_alert
= Form_Alert
;
620 IPDF_JSPLATFORM::app_beep
= Form_Beep
;
621 IPDF_JSPLATFORM::app_response
= Form_Response
;
622 IPDF_JSPLATFORM::Doc_getFilePath
= Form_GetFilePath
;
623 IPDF_JSPLATFORM::Doc_mail
= Form_Mail
;
624 IPDF_JSPLATFORM::Doc_print
= Form_Print
;
625 IPDF_JSPLATFORM::Doc_submitForm
= Form_SubmitForm
;
626 IPDF_JSPLATFORM::Doc_gotoPage
= Form_GotoPage
;
627 IPDF_JSPLATFORM::Field_browse
= Form_Browse
;
629 IFSDK_PAUSE::version
= 1;
630 IFSDK_PAUSE::user
= NULL
;
631 IFSDK_PAUSE::NeedToPauseNow
= Pause_NeedToPauseNow
;
634 PDFiumEngine::~PDFiumEngine() {
635 for (size_t i
= 0; i
< pages_
.size(); ++i
)
640 FORM_DoDocumentAAction(form_
, FPDFDOC_AACTION_WC
);
641 FPDFDOC_ExitFormFillEnviroument(form_
);
643 FPDF_CloseDocument(doc_
);
646 if (fpdf_availability_
)
647 FPDFAvail_Destroy(fpdf_availability_
);
649 STLDeleteElements(&pages_
);
652 int PDFiumEngine::GetBlock(void* param
, unsigned long position
,
653 unsigned char* buffer
, unsigned long size
) {
654 DocumentLoader
* loader
= static_cast<DocumentLoader
*>(param
);
655 return loader
->GetBlock(position
, size
, buffer
);
658 bool PDFiumEngine::IsDataAvail(FX_FILEAVAIL
* param
,
659 size_t offset
, size_t size
) {
660 PDFiumEngine::FileAvail
* file_avail
=
661 static_cast<PDFiumEngine::FileAvail
*>(param
);
662 return file_avail
->loader
->IsDataAvailable(offset
, size
);
665 void PDFiumEngine::AddSegment(FX_DOWNLOADHINTS
* param
,
666 size_t offset
, size_t size
) {
667 PDFiumEngine::DownloadHints
* download_hints
=
668 static_cast<PDFiumEngine::DownloadHints
*>(param
);
669 return download_hints
->loader
->RequestData(offset
, size
);
672 bool PDFiumEngine::New(const char* url
) {
674 headers_
= std::string();
678 bool PDFiumEngine::New(const char* url
,
679 const char* headers
) {
682 headers_
= std::string();
688 void PDFiumEngine::PageOffsetUpdated(const pp::Point
& page_offset
) {
689 page_offset_
= page_offset
;
692 void PDFiumEngine::PluginSizeUpdated(const pp::Size
& size
) {
696 CalculateVisiblePages();
699 void PDFiumEngine::ScrolledToXPosition(int position
) {
702 int old_x
= position_
.x();
703 position_
.set_x(position
);
704 CalculateVisiblePages();
705 client_
->Scroll(pp::Point(old_x
- position
, 0));
708 void PDFiumEngine::ScrolledToYPosition(int position
) {
711 int old_y
= position_
.y();
712 position_
.set_y(position
);
713 CalculateVisiblePages();
714 client_
->Scroll(pp::Point(0, old_y
- position
));
717 void PDFiumEngine::PrePaint() {
718 for (size_t i
= 0; i
< progressive_paints_
.size(); ++i
)
719 progressive_paints_
[i
].painted_
= false;
722 void PDFiumEngine::Paint(const pp::Rect
& rect
,
723 pp::ImageData
* image_data
,
724 std::vector
<pp::Rect
>* ready
,
725 std::vector
<pp::Rect
>* pending
) {
726 pp::Rect leftover
= rect
;
727 for (size_t i
= 0; i
< visible_pages_
.size(); ++i
) {
728 int index
= visible_pages_
[i
];
729 pp::Rect page_rect
= pages_
[index
]->rect();
730 // Convert the current page's rectangle to screen rectangle. We do this
731 // instead of the reverse (converting the dirty rectangle from screen to
732 // page coordinates) because then we'd have to convert back to screen
733 // coordinates, and the rounding errors sometime leave pixels dirty or even
734 // move the text up or down a pixel when zoomed.
735 pp::Rect page_rect_in_screen
= GetPageScreenRect(index
);
736 pp::Rect dirty_in_screen
= page_rect_in_screen
.Intersect(leftover
);
737 if (dirty_in_screen
.IsEmpty())
740 leftover
= leftover
.Subtract(dirty_in_screen
);
742 if (pages_
[index
]->available()) {
743 int progressive
= GetProgressiveIndex(index
);
744 if (progressive
!= -1 &&
745 progressive_paints_
[progressive
].rect
!= dirty_in_screen
) {
746 // The PDFium code can only handle one progressive paint at a time, so
747 // queue this up. Previously we used to merge the rects when this
748 // happened, but it made scrolling up on complex PDFs very slow since
749 // there would be a damaged rect at the top (from scroll) and at the
750 // bottom (from toolbar).
751 pending
->push_back(dirty_in_screen
);
755 if (progressive
== -1) {
756 progressive
= StartPaint(index
, dirty_in_screen
);
757 progressive_paint_timeout_
= kMaxInitialProgressivePaintTimeMs
;
759 progressive_paint_timeout_
= kMaxProgressivePaintTimeMs
;
762 progressive_paints_
[progressive
].painted_
= true;
763 if (ContinuePaint(progressive
, image_data
)) {
764 FinishPaint(progressive
, image_data
);
765 ready
->push_back(dirty_in_screen
);
767 pending
->push_back(dirty_in_screen
);
770 PaintUnavailablePage(index
, dirty_in_screen
, image_data
);
771 ready
->push_back(dirty_in_screen
);
776 void PDFiumEngine::PostPaint() {
777 for (size_t i
= 0; i
< progressive_paints_
.size(); ++i
) {
778 if (progressive_paints_
[i
].painted_
)
781 // This rectangle must have been merged with another one, that's why we
782 // weren't asked to paint it. Remove it or otherwise we'll never finish
784 FPDF_RenderPage_Close(
785 pages_
[progressive_paints_
[i
].page_index
]->GetPage());
786 FPDFBitmap_Destroy(progressive_paints_
[i
].bitmap
);
787 progressive_paints_
.erase(progressive_paints_
.begin() + i
);
792 bool PDFiumEngine::HandleDocumentLoad(const pp::URLLoader
& loader
) {
793 password_tries_remaining_
= kMaxPasswordTries
;
794 return doc_loader_
.Init(loader
, url_
, headers_
);
797 pp::Instance
* PDFiumEngine::GetPluginInstance() {
798 return client_
->GetPluginInstance();
801 pp::URLLoader
PDFiumEngine::CreateURLLoader() {
802 return client_
->CreateURLLoader();
805 void PDFiumEngine::AppendPage(PDFEngine
* engine
, int index
) {
806 // Unload and delete the blank page before appending.
807 pages_
[index
]->Unload();
808 pages_
[index
]->set_calculated_links(false);
809 pp::Size curr_page_size
= GetPageSize(index
);
810 FPDFPage_Delete(doc_
, index
);
811 FPDF_ImportPages(doc_
,
812 static_cast<PDFiumEngine
*>(engine
)->doc(),
815 pp::Size new_page_size
= GetPageSize(index
);
816 if (curr_page_size
!= new_page_size
)
818 client_
->Invalidate(GetPageScreenRect(index
));
821 pp::Point
PDFiumEngine::GetScrollPosition() {
825 void PDFiumEngine::SetScrollPosition(const pp::Point
& position
) {
826 position_
= position
;
829 bool PDFiumEngine::IsProgressiveLoad() {
830 return doc_loader_
.is_partial_document();
833 void PDFiumEngine::OnPartialDocumentLoaded() {
834 file_access_
.m_FileLen
= doc_loader_
.document_size();
835 fpdf_availability_
= FPDFAvail_Create(&file_availability_
, &file_access_
);
836 DCHECK(fpdf_availability_
);
838 // Currently engine does not deal efficiently with some non-linearized files.
839 // See http://code.google.com/p/chromium/issues/detail?id=59400
840 // To improve user experience we download entire file for non-linearized PDF.
841 if (!FPDFAvail_IsLinearized(fpdf_availability_
)) {
842 doc_loader_
.RequestData(0, doc_loader_
.document_size());
849 void PDFiumEngine::OnPendingRequestComplete() {
850 if (!doc_
|| !form_
) {
855 // LoadDocument() will result in |pending_pages_| being reset so there's no
856 // need to run the code below in that case.
857 bool update_pages
= false;
858 std::vector
<int> still_pending
;
859 for (size_t i
= 0; i
< pending_pages_
.size(); ++i
) {
860 if (CheckPageAvailable(pending_pages_
[i
], &still_pending
)) {
862 if (IsPageVisible(pending_pages_
[i
]))
863 client_
->Invalidate(GetPageScreenRect(pending_pages_
[i
]));
866 pending_pages_
.swap(still_pending
);
871 void PDFiumEngine::OnNewDataAvailable() {
872 client_
->DocumentLoadProgress(doc_loader_
.GetAvailableData(),
873 doc_loader_
.document_size());
876 void PDFiumEngine::OnDocumentComplete() {
877 if (!doc_
|| !form_
) {
878 file_access_
.m_FileLen
= doc_loader_
.document_size();
883 bool need_update
= false;
884 for (size_t i
= 0; i
< pages_
.size(); ++i
) {
885 if (pages_
[i
]->available())
888 pages_
[i
]->set_available(true);
889 // We still need to call IsPageAvail() even if the whole document is
890 // already downloaded.
891 FPDFAvail_IsPageAvail(fpdf_availability_
, i
, &download_hints_
);
893 if (IsPageVisible(i
))
894 client_
->Invalidate(GetPageScreenRect(i
));
899 FinishLoadingDocument();
902 void PDFiumEngine::FinishLoadingDocument() {
903 DCHECK(doc_loader_
.IsDocumentComplete() && doc_
);
904 if (called_do_document_action_
)
906 called_do_document_action_
= true;
908 // These can only be called now, as the JS might end up needing a page.
909 FORM_DoDocumentJSAction(form_
);
910 FORM_DoDocumentOpenAction(form_
);
911 if (most_visible_page_
!= -1) {
912 FPDF_PAGE new_page
= pages_
[most_visible_page_
]->GetPage();
913 FORM_DoPageAAction(new_page
, form_
, FPDFPAGE_AACTION_OPEN
);
916 if (doc_
) // This can only happen if loading |doc_| fails.
917 client_
->DocumentLoadComplete(pages_
.size());
920 void PDFiumEngine::UnsupportedFeature(int type
) {
923 case FPDF_UNSP_DOC_XFAFORM
:
926 case FPDF_UNSP_DOC_PORTABLECOLLECTION
:
927 feature
= "Portfolios_Packages";
929 case FPDF_UNSP_DOC_ATTACHMENT
:
930 case FPDF_UNSP_ANNOT_ATTACHMENT
:
931 feature
= "Attachment";
933 case FPDF_UNSP_DOC_SECURITY
:
934 feature
= "Rights_Management";
936 case FPDF_UNSP_DOC_SHAREDREVIEW
:
937 feature
= "Shared_Review";
939 case FPDF_UNSP_DOC_SHAREDFORM_ACROBAT
:
940 case FPDF_UNSP_DOC_SHAREDFORM_FILESYSTEM
:
941 case FPDF_UNSP_DOC_SHAREDFORM_EMAIL
:
942 feature
= "Shared_Form";
944 case FPDF_UNSP_ANNOT_3DANNOT
:
947 case FPDF_UNSP_ANNOT_MOVIE
:
950 case FPDF_UNSP_ANNOT_SOUND
:
953 case FPDF_UNSP_ANNOT_SCREEN_MEDIA
:
954 case FPDF_UNSP_ANNOT_SCREEN_RICHMEDIA
:
957 case FPDF_UNSP_ANNOT_SIG
:
958 feature
= "Digital_Signature";
961 client_
->DocumentHasUnsupportedFeature(feature
);
964 void PDFiumEngine::ContinueFind(int32_t result
) {
965 StartFind(current_find_text_
.c_str(), !!result
);
968 bool PDFiumEngine::HandleEvent(const pp::InputEvent
& event
) {
969 DCHECK(!defer_page_unload_
);
970 defer_page_unload_
= true;
972 switch (event
.GetType()) {
973 case PP_INPUTEVENT_TYPE_MOUSEDOWN
:
974 rv
= OnMouseDown(pp::MouseInputEvent(event
));
976 case PP_INPUTEVENT_TYPE_MOUSEUP
:
977 rv
= OnMouseUp(pp::MouseInputEvent(event
));
979 case PP_INPUTEVENT_TYPE_MOUSEMOVE
:
980 rv
= OnMouseMove(pp::MouseInputEvent(event
));
982 case PP_INPUTEVENT_TYPE_KEYDOWN
:
983 rv
= OnKeyDown(pp::KeyboardInputEvent(event
));
985 case PP_INPUTEVENT_TYPE_KEYUP
:
986 rv
= OnKeyUp(pp::KeyboardInputEvent(event
));
988 case PP_INPUTEVENT_TYPE_CHAR
:
989 rv
= OnChar(pp::KeyboardInputEvent(event
));
995 DCHECK(defer_page_unload_
);
996 defer_page_unload_
= false;
997 for (size_t i
= 0; i
< deferred_page_unloads_
.size(); ++i
)
998 pages_
[deferred_page_unloads_
[i
]]->Unload();
999 deferred_page_unloads_
.clear();
1003 uint32_t PDFiumEngine::QuerySupportedPrintOutputFormats() {
1004 if (!HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
))
1006 return PP_PRINTOUTPUTFORMAT_PDF
;
1009 void PDFiumEngine::PrintBegin() {
1010 FORM_DoDocumentAAction(form_
, FPDFDOC_AACTION_WP
);
1013 pp::Resource
PDFiumEngine::PrintPages(
1014 const PP_PrintPageNumberRange_Dev
* page_ranges
, uint32_t page_range_count
,
1015 const PP_PrintSettings_Dev
& print_settings
) {
1016 if (HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY
))
1017 return PrintPagesAsPDF(page_ranges
, page_range_count
, print_settings
);
1018 else if (HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
))
1019 return PrintPagesAsRasterPDF(page_ranges
, page_range_count
, print_settings
);
1020 return pp::Resource();
1023 FPDF_DOCUMENT
PDFiumEngine::CreateSinglePageRasterPdf(
1024 double source_page_width
,
1025 double source_page_height
,
1026 const PP_PrintSettings_Dev
& print_settings
,
1027 PDFiumPage
* page_to_print
) {
1028 FPDF_DOCUMENT temp_doc
= FPDF_CreateNewDocument();
1032 const pp::Size
& bitmap_size(page_to_print
->rect().size());
1034 FPDF_PAGE temp_page
=
1035 FPDFPage_New(temp_doc
, 0, source_page_width
, source_page_height
);
1037 pp::ImageData image
= pp::ImageData(client_
->GetPluginInstance(),
1038 PP_IMAGEDATAFORMAT_BGRA_PREMUL
,
1042 FPDF_BITMAP bitmap
= FPDFBitmap_CreateEx(bitmap_size
.width(),
1043 bitmap_size
.height(),
1049 FPDFBitmap_FillRect(
1050 bitmap
, 0, 0, bitmap_size
.width(), bitmap_size
.height(), 0xFFFFFFFF);
1052 pp::Rect page_rect
= page_to_print
->rect();
1053 FPDF_RenderPageBitmap(bitmap
,
1054 page_to_print
->GetPrintPage(),
1059 print_settings
.orientation
,
1060 FPDF_ANNOT
| FPDF_PRINTING
| FPDF_NO_CATCH
);
1062 double ratio_x
= (static_cast<double>(bitmap_size
.width()) * kPointsPerInch
) /
1065 (static_cast<double>(bitmap_size
.height()) * kPointsPerInch
) /
1068 // Add the bitmap to an image object and add the image object to the output
1070 FPDF_PAGEOBJECT temp_img
= FPDFPageObj_NewImgeObj(temp_doc
);
1071 FPDFImageObj_SetBitmap(&temp_page
, 1, temp_img
, bitmap
);
1072 FPDFImageObj_SetMatrix(temp_img
, ratio_x
, 0, 0, ratio_y
, 0, 0);
1073 FPDFPage_InsertObject(temp_page
, temp_img
);
1074 FPDFPage_GenerateContent(temp_page
);
1075 FPDF_ClosePage(temp_page
);
1077 page_to_print
->ClosePrintPage();
1078 FPDFBitmap_Destroy(bitmap
);
1083 pp::Buffer_Dev
PDFiumEngine::PrintPagesAsRasterPDF(
1084 const PP_PrintPageNumberRange_Dev
* page_ranges
, uint32_t page_range_count
,
1085 const PP_PrintSettings_Dev
& print_settings
) {
1086 if (!page_range_count
)
1087 return pp::Buffer_Dev();
1089 // If document is not downloaded yet, disable printing.
1090 if (doc_
&& !doc_loader_
.IsDocumentComplete())
1091 return pp::Buffer_Dev();
1093 FPDF_DOCUMENT output_doc
= FPDF_CreateNewDocument();
1095 return pp::Buffer_Dev();
1097 SaveSelectedFormForPrint();
1099 std::vector
<PDFiumPage
> pages_to_print
;
1100 // width and height of source PDF pages.
1101 std::vector
<std::pair
<double, double> > source_page_sizes
;
1102 // Collect pages to print and sizes of source pages.
1103 std::vector
<uint32_t> page_numbers
=
1104 GetPageNumbersFromPrintPageNumberRange(page_ranges
, page_range_count
);
1105 for (size_t i
= 0; i
< page_numbers
.size(); ++i
) {
1106 uint32_t page_number
= page_numbers
[i
];
1107 FPDF_PAGE pdf_page
= FPDF_LoadPage(doc_
, page_number
);
1108 double source_page_width
= FPDF_GetPageWidth(pdf_page
);
1109 double source_page_height
= FPDF_GetPageHeight(pdf_page
);
1110 source_page_sizes
.push_back(std::make_pair(source_page_width
,
1111 source_page_height
));
1113 int width_in_pixels
= ConvertUnit(source_page_width
,
1114 static_cast<int>(kPointsPerInch
),
1115 print_settings
.dpi
);
1116 int height_in_pixels
= ConvertUnit(source_page_height
,
1117 static_cast<int>(kPointsPerInch
),
1118 print_settings
.dpi
);
1120 pp::Rect
rect(width_in_pixels
, height_in_pixels
);
1121 pages_to_print
.push_back(PDFiumPage(this, page_number
, rect
, true));
1122 FPDF_ClosePage(pdf_page
);
1125 #if defined(OS_LINUX)
1126 g_last_instance_id
= client_
->GetPluginInstance()->pp_instance();
1130 for (; i
< pages_to_print
.size(); ++i
) {
1131 double source_page_width
= source_page_sizes
[i
].first
;
1132 double source_page_height
= source_page_sizes
[i
].second
;
1134 // Use temp_doc to compress image by saving PDF to buffer.
1135 FPDF_DOCUMENT temp_doc
= CreateSinglePageRasterPdf(source_page_width
,
1138 &pages_to_print
[i
]);
1143 pp::Buffer_Dev buffer
= GetFlattenedPrintData(temp_doc
);
1144 FPDF_CloseDocument(temp_doc
);
1146 PDFiumMemBufferFileRead
file_read(buffer
.data(), buffer
.size());
1147 temp_doc
= FPDF_LoadCustomDocument(&file_read
, NULL
);
1149 FPDF_BOOL imported
= FPDF_ImportPages(output_doc
, temp_doc
, "1", i
);
1150 FPDF_CloseDocument(temp_doc
);
1155 pp::Buffer_Dev buffer
;
1156 if (i
== pages_to_print
.size()) {
1157 FPDF_CopyViewerPreferences(output_doc
, doc_
);
1158 FitContentsToPrintableAreaIfRequired(output_doc
, print_settings
);
1159 // Now flatten all the output pages.
1160 buffer
= GetFlattenedPrintData(output_doc
);
1162 FPDF_CloseDocument(output_doc
);
1166 pp::Buffer_Dev
PDFiumEngine::GetFlattenedPrintData(const FPDF_DOCUMENT
& doc
) {
1167 int page_count
= FPDF_GetPageCount(doc
);
1168 bool flatten_succeeded
= true;
1169 for (int i
= 0; i
< page_count
; ++i
) {
1170 FPDF_PAGE page
= FPDF_LoadPage(doc
, i
);
1173 int flatten_ret
= FPDFPage_Flatten(page
, FLAT_PRINT
);
1174 FPDF_ClosePage(page
);
1175 if (flatten_ret
== FLATTEN_FAIL
) {
1176 flatten_succeeded
= false;
1180 flatten_succeeded
= false;
1184 if (!flatten_succeeded
) {
1185 FPDF_CloseDocument(doc
);
1186 return pp::Buffer_Dev();
1189 pp::Buffer_Dev buffer
;
1190 PDFiumMemBufferFileWrite output_file_write
;
1191 if (FPDF_SaveAsCopy(doc
, &output_file_write
, 0)) {
1192 buffer
= pp::Buffer_Dev(
1193 client_
->GetPluginInstance(), output_file_write
.size());
1194 if (!buffer
.is_null()) {
1195 memcpy(buffer
.data(), output_file_write
.buffer().c_str(),
1196 output_file_write
.size());
1202 pp::Buffer_Dev
PDFiumEngine::PrintPagesAsPDF(
1203 const PP_PrintPageNumberRange_Dev
* page_ranges
, uint32_t page_range_count
,
1204 const PP_PrintSettings_Dev
& print_settings
) {
1205 if (!page_range_count
)
1206 return pp::Buffer_Dev();
1209 FPDF_DOCUMENT output_doc
= FPDF_CreateNewDocument();
1211 return pp::Buffer_Dev();
1213 SaveSelectedFormForPrint();
1215 std::string page_number_str
;
1216 for (uint32_t index
= 0; index
< page_range_count
; ++index
) {
1217 if (!page_number_str
.empty())
1218 page_number_str
.append(",");
1219 page_number_str
.append(
1220 base::IntToString(page_ranges
[index
].first_page_number
+ 1));
1221 if (page_ranges
[index
].first_page_number
!=
1222 page_ranges
[index
].last_page_number
) {
1223 page_number_str
.append("-");
1224 page_number_str
.append(
1225 base::IntToString(page_ranges
[index
].last_page_number
+ 1));
1229 std::vector
<uint32_t> page_numbers
=
1230 GetPageNumbersFromPrintPageNumberRange(page_ranges
, page_range_count
);
1231 for (size_t i
= 0; i
< page_numbers
.size(); ++i
) {
1232 uint32_t page_number
= page_numbers
[i
];
1233 pages_
[page_number
]->GetPage();
1234 if (!IsPageVisible(page_numbers
[i
]))
1235 pages_
[page_number
]->Unload();
1238 FPDF_CopyViewerPreferences(output_doc
, doc_
);
1239 if (!FPDF_ImportPages(output_doc
, doc_
, page_number_str
.c_str(), 0)) {
1240 FPDF_CloseDocument(output_doc
);
1241 return pp::Buffer_Dev();
1244 FitContentsToPrintableAreaIfRequired(output_doc
, print_settings
);
1246 // Now flatten all the output pages.
1247 pp::Buffer_Dev buffer
= GetFlattenedPrintData(output_doc
);
1248 FPDF_CloseDocument(output_doc
);
1252 void PDFiumEngine::FitContentsToPrintableAreaIfRequired(
1253 const FPDF_DOCUMENT
& doc
, const PP_PrintSettings_Dev
& print_settings
) {
1254 // Check to see if we need to fit pdf contents to printer paper size.
1255 if (print_settings
.print_scaling_option
!=
1256 PP_PRINTSCALINGOPTION_SOURCE_SIZE
) {
1257 int num_pages
= FPDF_GetPageCount(doc
);
1258 // In-place transformation is more efficient than creating a new
1259 // transformed document from the source document. Therefore, transform
1260 // every page to fit the contents in the selected printer paper.
1261 for (int i
= 0; i
< num_pages
; ++i
) {
1262 FPDF_PAGE page
= FPDF_LoadPage(doc
, i
);
1263 TransformPDFPageForPrinting(page
, print_settings
);
1264 FPDF_ClosePage(page
);
1269 void PDFiumEngine::SaveSelectedFormForPrint() {
1270 FORM_ForceToKillFocus(form_
);
1271 client_
->FormTextFieldFocusChange(false);
1274 void PDFiumEngine::PrintEnd() {
1275 FORM_DoDocumentAAction(form_
, FPDFDOC_AACTION_DP
);
1278 PDFiumPage::Area
PDFiumEngine::GetCharIndex(
1279 const pp::MouseInputEvent
& event
, int* page_index
,
1280 int* char_index
, PDFiumPage::LinkTarget
* target
) {
1281 // First figure out which page this is in.
1282 pp::Point mouse_point
= event
.GetPosition();
1284 static_cast<int>((mouse_point
.x() + position_
.x()) / current_zoom_
),
1285 static_cast<int>((mouse_point
.y() + position_
.y()) / current_zoom_
));
1286 return GetCharIndex(point
, page_index
, char_index
, target
);
1289 PDFiumPage::Area
PDFiumEngine::GetCharIndex(
1290 const pp::Point
& point
,
1293 PDFiumPage::LinkTarget
* target
) {
1295 for (size_t i
= 0; i
< visible_pages_
.size(); ++i
) {
1296 if (pages_
[visible_pages_
[i
]]->rect().Contains(point
)) {
1297 page
= visible_pages_
[i
];
1302 return PDFiumPage::NONSELECTABLE_AREA
;
1304 // If the page hasn't finished rendering, calling into the page sometimes
1306 for (size_t i
= 0; i
< progressive_paints_
.size(); ++i
) {
1307 if (progressive_paints_
[i
].page_index
== page
)
1308 return PDFiumPage::NONSELECTABLE_AREA
;
1312 return pages_
[page
]->GetCharIndex(point
, current_rotation_
, char_index
,
1316 bool PDFiumEngine::OnMouseDown(const pp::MouseInputEvent
& event
) {
1317 if (event
.GetButton() != PP_INPUTEVENT_MOUSEBUTTON_LEFT
)
1320 SelectionChangeInvalidator
selection_invalidator(this);
1323 int page_index
= -1;
1324 int char_index
= -1;
1325 PDFiumPage::LinkTarget target
;
1326 PDFiumPage::Area area
= GetCharIndex(event
, &page_index
,
1327 &char_index
, &target
);
1328 mouse_down_state_
.Set(area
, target
);
1330 // Decide whether to open link or not based on user action in mouse up and
1331 // mouse move events.
1332 if (area
== PDFiumPage::WEBLINK_AREA
)
1335 if (area
== PDFiumPage::DOCLINK_AREA
) {
1336 client_
->ScrollToPage(target
.page
);
1337 client_
->FormTextFieldFocusChange(false);
1341 if (page_index
!= -1) {
1342 last_page_mouse_down_
= page_index
;
1343 double page_x
, page_y
;
1344 pp::Point point
= event
.GetPosition();
1345 DeviceToPage(page_index
, point
.x(), point
.y(), &page_x
, &page_y
);
1347 FORM_OnLButtonDown(form_
, pages_
[page_index
]->GetPage(), 0, page_x
, page_y
);
1348 int control
= FPDPage_HasFormFieldAtPoint(
1349 form_
, pages_
[page_index
]->GetPage(), page_x
, page_y
);
1350 if (control
> FPDF_FORMFIELD_UNKNOWN
) { // returns -1 sometimes...
1351 client_
->FormTextFieldFocusChange(control
== FPDF_FORMFIELD_TEXTFIELD
||
1352 control
== FPDF_FORMFIELD_COMBOBOX
);
1353 return true; // Return now before we get into the selection code.
1357 client_
->FormTextFieldFocusChange(false);
1359 if (area
!= PDFiumPage::TEXT_AREA
)
1360 return true; // Return true so WebKit doesn't do its own highlighting.
1362 if (event
.GetClickCount() == 1) {
1363 OnSingleClick(page_index
, char_index
);
1364 } else if (event
.GetClickCount() == 2 ||
1365 event
.GetClickCount() == 3) {
1366 OnMultipleClick(event
.GetClickCount(), page_index
, char_index
);
1372 void PDFiumEngine::OnSingleClick(int page_index
, int char_index
) {
1374 selection_
.push_back(PDFiumRange(pages_
[page_index
], char_index
, 0));
1377 void PDFiumEngine::OnMultipleClick(int click_count
,
1380 // It would be more efficient if the SDK could support finding a space, but
1382 int start_index
= char_index
;
1384 base::char16 cur
= pages_
[page_index
]->GetCharAtIndex(start_index
);
1385 // For double click, we want to select one word so we look for whitespace
1386 // boundaries. For triple click, we want the whole line.
1387 if (cur
== '\n' || (click_count
== 2 && (cur
== ' ' || cur
== '\t')))
1389 } while (--start_index
>= 0);
1393 int end_index
= char_index
;
1394 int total
= pages_
[page_index
]->GetCharCount();
1395 while (end_index
++ <= total
) {
1396 base::char16 cur
= pages_
[page_index
]->GetCharAtIndex(end_index
);
1397 if (cur
== '\n' || (click_count
== 2 && (cur
== ' ' || cur
== '\t')))
1401 selection_
.push_back(PDFiumRange(
1402 pages_
[page_index
], start_index
, end_index
- start_index
));
1405 bool PDFiumEngine::OnMouseUp(const pp::MouseInputEvent
& event
) {
1406 if (event
.GetButton() != PP_INPUTEVENT_MOUSEBUTTON_LEFT
)
1409 int page_index
= -1;
1410 int char_index
= -1;
1411 PDFiumPage::LinkTarget target
;
1412 PDFiumPage::Area area
=
1413 GetCharIndex(event
, &page_index
, &char_index
, &target
);
1415 // Open link on mouse up for same link for which mouse down happened earlier.
1416 if (mouse_down_state_
.Matches(area
, target
)) {
1417 if (area
== PDFiumPage::WEBLINK_AREA
) {
1418 bool open_in_new_tab
= !!(event
.GetModifiers() & kDefaultKeyModifier
);
1419 client_
->NavigateTo(target
.url
, open_in_new_tab
);
1420 client_
->FormTextFieldFocusChange(false);
1425 if (page_index
!= -1) {
1426 double page_x
, page_y
;
1427 pp::Point point
= event
.GetPosition();
1428 DeviceToPage(page_index
, point
.x(), point
.y(), &page_x
, &page_y
);
1430 form_
, pages_
[page_index
]->GetPage(), 0, page_x
, page_y
);
1440 bool PDFiumEngine::OnMouseMove(const pp::MouseInputEvent
& event
) {
1441 int page_index
= -1;
1442 int char_index
= -1;
1443 PDFiumPage::LinkTarget target
;
1444 PDFiumPage::Area area
=
1445 GetCharIndex(event
, &page_index
, &char_index
, &target
);
1447 // Clear |mouse_down_state_| if mouse moves away from where the mouse down
1449 if (!mouse_down_state_
.Matches(area
, target
))
1450 mouse_down_state_
.Reset();
1453 PP_CursorType_Dev cursor
;
1455 case PDFiumPage::TEXT_AREA
:
1456 cursor
= PP_CURSORTYPE_IBEAM
;
1458 case PDFiumPage::WEBLINK_AREA
:
1459 case PDFiumPage::DOCLINK_AREA
:
1460 cursor
= PP_CURSORTYPE_HAND
;
1462 case PDFiumPage::NONSELECTABLE_AREA
:
1464 cursor
= PP_CURSORTYPE_POINTER
;
1468 if (page_index
!= -1) {
1469 double page_x
, page_y
;
1470 pp::Point point
= event
.GetPosition();
1471 DeviceToPage(page_index
, point
.x(), point
.y(), &page_x
, &page_y
);
1473 FORM_OnMouseMove(form_
, pages_
[page_index
]->GetPage(), 0, page_x
, page_y
);
1474 int control
= FPDPage_HasFormFieldAtPoint(
1475 form_
, pages_
[page_index
]->GetPage(), page_x
, page_y
);
1477 case FPDF_FORMFIELD_PUSHBUTTON
:
1478 case FPDF_FORMFIELD_CHECKBOX
:
1479 case FPDF_FORMFIELD_RADIOBUTTON
:
1480 case FPDF_FORMFIELD_COMBOBOX
:
1481 case FPDF_FORMFIELD_LISTBOX
:
1482 cursor
= PP_CURSORTYPE_HAND
;
1484 case FPDF_FORMFIELD_TEXTFIELD
:
1485 cursor
= PP_CURSORTYPE_IBEAM
;
1492 client_
->UpdateCursor(cursor
);
1493 pp::Point point
= event
.GetPosition();
1494 std::string url
= GetLinkAtPosition(event
.GetPosition());
1495 if (url
!= link_under_cursor_
) {
1496 link_under_cursor_
= url
;
1497 pp::PDF::SetLinkUnderCursor(GetPluginInstance(), url
.c_str());
1499 // No need to swallow the event, since this might interfere with the
1500 // scrollbars if the user is dragging them.
1504 // We're selecting but right now we're not over text, so don't change the
1505 // current selection.
1506 if (area
!= PDFiumPage::TEXT_AREA
&& area
!= PDFiumPage::WEBLINK_AREA
&&
1507 area
!= PDFiumPage::DOCLINK_AREA
) {
1511 SelectionChangeInvalidator
selection_invalidator(this);
1513 // Check if the user has descreased their selection area and we need to remove
1514 // pages from selection_.
1515 for (size_t i
= 0; i
< selection_
.size(); ++i
) {
1516 if (selection_
[i
].page_index() == page_index
) {
1517 // There should be no other pages after this.
1518 selection_
.erase(selection_
.begin() + i
+ 1, selection_
.end());
1523 if (selection_
.size() == 0)
1526 int last
= selection_
.size() - 1;
1527 if (selection_
[last
].page_index() == page_index
) {
1528 // Selecting within a page.
1530 if (char_index
>= selection_
[last
].char_index()) {
1531 // Selecting forward.
1532 count
= char_index
- selection_
[last
].char_index() + 1;
1534 count
= char_index
- selection_
[last
].char_index() - 1;
1536 selection_
[last
].SetCharCount(count
);
1537 } else if (selection_
[last
].page_index() < page_index
) {
1538 // Selecting into the next page.
1540 // First make sure that there are no gaps in selection, i.e. if mousedown on
1541 // page one but we only get mousemove over page three, we want page two.
1542 for (int i
= selection_
[last
].page_index() + 1; i
< page_index
; ++i
) {
1543 selection_
.push_back(PDFiumRange(pages_
[i
], 0,
1544 pages_
[i
]->GetCharCount()));
1547 int count
= pages_
[selection_
[last
].page_index()]->GetCharCount();
1548 selection_
[last
].SetCharCount(count
- selection_
[last
].char_index());
1549 selection_
.push_back(PDFiumRange(pages_
[page_index
], 0, char_index
));
1551 // Selecting into the previous page.
1552 selection_
[last
].SetCharCount(-selection_
[last
].char_index());
1554 // First make sure that there are no gaps in selection, i.e. if mousedown on
1555 // page three but we only get mousemove over page one, we want page two.
1556 for (int i
= selection_
[last
].page_index() - 1; i
> page_index
; --i
) {
1557 selection_
.push_back(PDFiumRange(pages_
[i
], 0,
1558 pages_
[i
]->GetCharCount()));
1561 int count
= pages_
[page_index
]->GetCharCount();
1562 selection_
.push_back(
1563 PDFiumRange(pages_
[page_index
], count
, count
- char_index
));
1569 bool PDFiumEngine::OnKeyDown(const pp::KeyboardInputEvent
& event
) {
1570 if (last_page_mouse_down_
== -1)
1573 bool rv
= !!FORM_OnKeyDown(
1574 form_
, pages_
[last_page_mouse_down_
]->GetPage(),
1575 event
.GetKeyCode(), event
.GetModifiers());
1577 if (event
.GetKeyCode() == ui::VKEY_BACK
||
1578 event
.GetKeyCode() == ui::VKEY_ESCAPE
) {
1579 // Chrome doesn't send char events for backspace or escape keys, see
1580 // PlatformKeyboardEventBuilder::isCharacterKey() and
1581 // http://chrome-corpsvn.mtv.corp.google.com/viewvc?view=rev&root=chrome&revision=31805
1582 // for more information. So just fake one since PDFium uses it.
1584 str
.push_back(event
.GetKeyCode());
1585 pp::KeyboardInputEvent
synthesized(pp::KeyboardInputEvent(
1586 client_
->GetPluginInstance(),
1587 PP_INPUTEVENT_TYPE_CHAR
,
1588 event
.GetTimeStamp(),
1589 event
.GetModifiers(),
1592 OnChar(synthesized
);
1598 bool PDFiumEngine::OnKeyUp(const pp::KeyboardInputEvent
& event
) {
1599 if (last_page_mouse_down_
== -1)
1602 return !!FORM_OnKeyUp(
1603 form_
, pages_
[last_page_mouse_down_
]->GetPage(),
1604 event
.GetKeyCode(), event
.GetModifiers());
1607 bool PDFiumEngine::OnChar(const pp::KeyboardInputEvent
& event
) {
1608 if (last_page_mouse_down_
== -1)
1611 base::string16 str
= base::UTF8ToUTF16(event
.GetCharacterText().AsString());
1612 return !!FORM_OnChar(
1613 form_
, pages_
[last_page_mouse_down_
]->GetPage(),
1615 event
.GetModifiers());
1618 void PDFiumEngine::StartFind(const char* text
, bool case_sensitive
) {
1619 // We can get a call to StartFind before we have any page information (i.e.
1620 // before the first call to LoadDocument has happened). Handle this case.
1624 bool first_search
= false;
1625 int character_to_start_searching_from
= 0;
1626 if (current_find_text_
!= text
) { // First time we search for this text.
1627 first_search
= true;
1628 std::vector
<PDFiumRange
> old_selection
= selection_
;
1630 current_find_text_
= text
;
1632 if (old_selection
.empty()) {
1633 // Start searching from the beginning of the document.
1634 next_page_to_search_
= 0;
1635 last_page_to_search_
= pages_
.size() - 1;
1636 last_character_index_to_search_
= -1;
1638 // There's a current selection, so start from it.
1639 next_page_to_search_
= old_selection
[0].page_index();
1640 last_character_index_to_search_
= old_selection
[0].char_index();
1641 character_to_start_searching_from
= old_selection
[0].char_index();
1642 last_page_to_search_
= next_page_to_search_
;
1646 int current_page
= next_page_to_search_
;
1648 if (pages_
[current_page
]->available()) {
1649 base::string16 str
= base::UTF8ToUTF16(text
);
1650 // Don't use PDFium to search for now, since it doesn't support unicode text.
1651 // Leave the code for now to avoid bit-rot, in case it's fixed later.
1654 str
, case_sensitive
, first_search
, character_to_start_searching_from
,
1658 str
, case_sensitive
, first_search
, character_to_start_searching_from
,
1662 if (!IsPageVisible(current_page
))
1663 pages_
[current_page
]->Unload();
1666 if (next_page_to_search_
!= last_page_to_search_
||
1667 (first_search
&& last_character_index_to_search_
!= -1)) {
1668 ++next_page_to_search_
;
1671 if (next_page_to_search_
== static_cast<int>(pages_
.size()))
1672 next_page_to_search_
= 0;
1673 // If there's only one page in the document and we start searching midway,
1674 // then we'll want to search the page one more time.
1675 bool end_of_search
=
1676 next_page_to_search_
== last_page_to_search_
&&
1677 // Only one page but didn't start midway.
1678 ((pages_
.size() == 1 && last_character_index_to_search_
== -1) ||
1679 // Started midway, but only 1 page and we already looped around.
1680 (pages_
.size() == 1 && !first_search
) ||
1681 // Started midway, and we've just looped around.
1682 (pages_
.size() > 1 && current_page
== next_page_to_search_
));
1684 if (end_of_search
) {
1685 // Send the final notification.
1686 client_
->NotifyNumberOfFindResultsChanged(find_results_
.size(), true);
1688 // When searching is complete, resume finding at a particular index.
1689 if (resume_find_index_
!= -1) {
1690 current_find_index_
= resume_find_index_
;
1691 resume_find_index_
= -1;
1694 pp::CompletionCallback callback
=
1695 find_factory_
.NewCallback(&PDFiumEngine::ContinueFind
);
1696 pp::Module::Get()->core()->CallOnMainThread(
1697 0, callback
, case_sensitive
? 1 : 0);
1701 void PDFiumEngine::SearchUsingPDFium(const base::string16
& term
,
1702 bool case_sensitive
,
1704 int character_to_start_searching_from
,
1706 // Find all the matches in the current page.
1707 unsigned long flags
= case_sensitive
? FPDF_MATCHCASE
: 0;
1708 FPDF_SCHHANDLE find
= FPDFText_FindStart(
1709 pages_
[current_page
]->GetTextPage(),
1710 reinterpret_cast<const unsigned short*>(term
.c_str()),
1711 flags
, character_to_start_searching_from
);
1713 // Note: since we search one page at a time, we don't find matches across
1714 // page boundaries. We could do this manually ourself, but it seems low
1715 // priority since Reader itself doesn't do it.
1716 while (FPDFText_FindNext(find
)) {
1717 PDFiumRange
result(pages_
[current_page
],
1718 FPDFText_GetSchResultIndex(find
),
1719 FPDFText_GetSchCount(find
));
1721 if (!first_search
&&
1722 last_character_index_to_search_
!= -1 &&
1723 result
.page_index() == last_page_to_search_
&&
1724 result
.char_index() >= last_character_index_to_search_
) {
1728 AddFindResult(result
);
1731 FPDFText_FindClose(find
);
1734 void PDFiumEngine::SearchUsingICU(const base::string16
& term
,
1735 bool case_sensitive
,
1737 int character_to_start_searching_from
,
1739 base::string16 page_text
;
1740 int text_length
= pages_
[current_page
]->GetCharCount();
1741 if (character_to_start_searching_from
) {
1742 text_length
-= character_to_start_searching_from
;
1743 } else if (!first_search
&&
1744 last_character_index_to_search_
!= -1 &&
1745 current_page
== last_page_to_search_
) {
1746 text_length
= last_character_index_to_search_
;
1748 if (text_length
<= 0)
1750 unsigned short* data
=
1751 reinterpret_cast<unsigned short*>(WriteInto(&page_text
, text_length
+ 1));
1752 FPDFText_GetText(pages_
[current_page
]->GetTextPage(),
1753 character_to_start_searching_from
,
1756 std::vector
<PDFEngine::Client::SearchStringResult
> results
;
1757 client_
->SearchString(
1758 page_text
.c_str(), term
.c_str(), case_sensitive
, &results
);
1759 for (size_t i
= 0; i
< results
.size(); ++i
) {
1760 // Need to map the indexes from the page text, which may have generated
1761 // characters like space etc, to character indices from the page.
1762 int temp_start
= results
[i
].start_index
+ character_to_start_searching_from
;
1763 int start
= FPDFText_GetCharIndexFromTextIndex(
1764 pages_
[current_page
]->GetTextPage(), temp_start
);
1765 int end
= FPDFText_GetCharIndexFromTextIndex(
1766 pages_
[current_page
]->GetTextPage(),
1767 temp_start
+ results
[i
].length
);
1768 AddFindResult(PDFiumRange(pages_
[current_page
], start
, end
- start
));
1772 void PDFiumEngine::AddFindResult(const PDFiumRange
& result
) {
1773 // Figure out where to insert the new location, since we could have
1774 // started searching midway and now we wrapped.
1776 int page_index
= result
.page_index();
1777 int char_index
= result
.char_index();
1778 for (i
= 0; i
< find_results_
.size(); ++i
) {
1779 if (find_results_
[i
].page_index() > page_index
||
1780 (find_results_
[i
].page_index() == page_index
&&
1781 find_results_
[i
].char_index() > char_index
)) {
1785 find_results_
.insert(find_results_
.begin() + i
, result
);
1788 if (current_find_index_
== -1 && resume_find_index_
== -1) {
1789 // Select the first match.
1790 SelectFindResult(true);
1791 } else if (static_cast<int>(i
) <= current_find_index_
) {
1792 // Update the current match index
1793 current_find_index_
++;
1794 client_
->NotifySelectedFindResultChanged(current_find_index_
);
1796 client_
->NotifyNumberOfFindResultsChanged(find_results_
.size(), false);
1799 bool PDFiumEngine::SelectFindResult(bool forward
) {
1800 if (find_results_
.empty()) {
1805 SelectionChangeInvalidator
selection_invalidator(this);
1807 // Move back/forward through the search locations we previously found.
1809 if (++current_find_index_
== static_cast<int>(find_results_
.size()))
1810 current_find_index_
= 0;
1812 if (--current_find_index_
< 0) {
1813 current_find_index_
= find_results_
.size() - 1;
1817 // Update the selection before telling the client to scroll, since it could
1820 selection_
.push_back(find_results_
[current_find_index_
]);
1822 // If the result is not in view, scroll to it.
1824 pp::Rect bounding_rect
;
1825 pp::Rect visible_rect
= GetVisibleRect();
1826 // Use zoom of 1.0 since visible_rect is without zoom.
1827 std::vector
<pp::Rect
> rects
= find_results_
[current_find_index_
].
1828 GetScreenRects(pp::Point(), 1.0, current_rotation_
);
1829 for (i
= 0; i
< rects
.size(); ++i
)
1830 bounding_rect
= bounding_rect
.Union(rects
[i
]);
1831 if (!visible_rect
.Contains(bounding_rect
)) {
1832 pp::Point center
= bounding_rect
.CenterPoint();
1833 // Make the page centered.
1834 int new_y
= static_cast<int>(center
.y() * current_zoom_
) -
1835 static_cast<int>(visible_rect
.height() * current_zoom_
/ 2);
1838 client_
->ScrollToY(new_y
);
1840 // Only move horizontally if it's not visible.
1841 if (center
.x() < visible_rect
.x() || center
.x() > visible_rect
.right()) {
1842 int new_x
= static_cast<int>(center
.x() * current_zoom_
) -
1843 static_cast<int>(visible_rect
.width() * current_zoom_
/ 2);
1846 client_
->ScrollToX(new_x
);
1850 client_
->NotifySelectedFindResultChanged(current_find_index_
);
1855 void PDFiumEngine::StopFind() {
1856 SelectionChangeInvalidator
selection_invalidator(this);
1860 find_results_
.clear();
1861 next_page_to_search_
= -1;
1862 last_page_to_search_
= -1;
1863 last_character_index_to_search_
= -1;
1864 current_find_index_
= -1;
1865 current_find_text_
.clear();
1867 find_factory_
.CancelAll();
1870 void PDFiumEngine::UpdateTickMarks() {
1871 std::vector
<pp::Rect
> tickmarks
;
1872 for (size_t i
= 0; i
< find_results_
.size(); ++i
) {
1874 // Always use an origin of 0,0 since scroll positions don't affect tickmark.
1875 std::vector
<pp::Rect
> rects
= find_results_
[i
].GetScreenRects(
1876 pp::Point(0, 0), current_zoom_
, current_rotation_
);
1877 for (size_t j
= 0; j
< rects
.size(); ++j
)
1878 rect
= rect
.Union(rects
[j
]);
1879 tickmarks
.push_back(rect
);
1882 client_
->UpdateTickMarks(tickmarks
);
1885 void PDFiumEngine::ZoomUpdated(double new_zoom_level
) {
1888 current_zoom_
= new_zoom_level
;
1890 CalculateVisiblePages();
1894 void PDFiumEngine::RotateClockwise() {
1895 current_rotation_
= (current_rotation_
+ 1) % 4;
1897 // Store the current find index so that we can resume finding at that
1898 // particular index after we have recomputed the find results.
1899 std::string current_find_text
= current_find_text_
;
1900 resume_find_index_
= current_find_index_
;
1902 InvalidateAllPages();
1904 if (!current_find_text
.empty())
1905 StartFind(current_find_text
.c_str(), false);
1908 void PDFiumEngine::RotateCounterclockwise() {
1909 current_rotation_
= (current_rotation_
- 1) % 4;
1911 // Store the current find index so that we can resume finding at that
1912 // particular index after we have recomputed the find results.
1913 std::string current_find_text
= current_find_text_
;
1914 resume_find_index_
= current_find_index_
;
1916 InvalidateAllPages();
1918 if (!current_find_text
.empty())
1919 StartFind(current_find_text
.c_str(), false);
1922 void PDFiumEngine::InvalidateAllPages() {
1926 client_
->Invalidate(pp::Rect(plugin_size_
));
1929 std::string
PDFiumEngine::GetSelectedText() {
1930 base::string16 result
;
1931 for (size_t i
= 0; i
< selection_
.size(); ++i
) {
1933 selection_
[i
- 1].page_index() > selection_
[i
].page_index()) {
1934 result
= selection_
[i
].GetText() + result
;
1936 result
.append(selection_
[i
].GetText());
1940 FormatStringWithHyphens(&result
);
1941 FormatStringForOS(&result
);
1942 return base::UTF16ToUTF8(result
);
1945 std::string
PDFiumEngine::GetLinkAtPosition(const pp::Point
& point
) {
1947 PDFiumPage::LinkTarget target
;
1948 pp::Point
point_in_page(
1949 static_cast<int>((point
.x() + position_
.x()) / current_zoom_
),
1950 static_cast<int>((point
.y() + position_
.y()) / current_zoom_
));
1951 PDFiumPage::Area area
= GetCharIndex(point_in_page
, &temp
, &temp
, &target
);
1952 if (area
== PDFiumPage::WEBLINK_AREA
)
1954 return std::string();
1957 bool PDFiumEngine::IsSelecting() {
1961 bool PDFiumEngine::HasPermission(DocumentPermission permission
) const {
1962 switch (permission
) {
1963 case PERMISSION_COPY
:
1964 return (permissions_
& kPDFPermissionCopyMask
) != 0;
1965 case PERMISSION_COPY_ACCESSIBLE
:
1966 return (permissions_
& kPDFPermissionCopyAccessibleMask
) != 0;
1967 case PERMISSION_PRINT_LOW_QUALITY
:
1968 return (permissions_
& kPDFPermissionPrintLowQualityMask
) != 0;
1969 case PERMISSION_PRINT_HIGH_QUALITY
:
1970 return (permissions_
& kPDFPermissionPrintLowQualityMask
) != 0 &&
1971 (permissions_
& kPDFPermissionPrintHighQualityMask
) != 0;
1977 void PDFiumEngine::SelectAll() {
1978 SelectionChangeInvalidator
selection_invalidator(this);
1981 for (size_t i
= 0; i
< pages_
.size(); ++i
)
1982 if (pages_
[i
]->available()) {
1983 selection_
.push_back(PDFiumRange(pages_
[i
], 0,
1984 pages_
[i
]->GetCharCount()));
1988 int PDFiumEngine::GetNumberOfPages() {
1989 return pages_
.size();
1992 int PDFiumEngine::GetNamedDestinationPage(const std::string
& destination
) {
1993 // Look for the destination.
1994 FPDF_DEST dest
= FPDF_GetNamedDestByName(doc_
, destination
.c_str());
1996 // Look for a bookmark with the same name.
1997 base::string16 destination_wide
= base::UTF8ToUTF16(destination
);
1998 FPDF_WIDESTRING destination_pdf_wide
=
1999 reinterpret_cast<FPDF_WIDESTRING
>(destination_wide
.c_str());
2000 FPDF_BOOKMARK bookmark
= FPDFBookmark_Find(doc_
, destination_pdf_wide
);
2003 dest
= FPDFBookmark_GetDest(doc_
, bookmark
);
2005 return dest
? FPDFDest_GetPageIndex(doc_
, dest
) : -1;
2008 int PDFiumEngine::GetFirstVisiblePage() {
2009 CalculateVisiblePages();
2010 return first_visible_page_
;
2013 int PDFiumEngine::GetMostVisiblePage() {
2014 CalculateVisiblePages();
2015 return most_visible_page_
;
2018 pp::Rect
PDFiumEngine::GetPageRect(int index
) {
2019 pp::Rect
rc(pages_
[index
]->rect());
2020 rc
.Inset(-kPageShadowLeft
, -kPageShadowTop
,
2021 -kPageShadowRight
, -kPageShadowBottom
);
2025 pp::Rect
PDFiumEngine::GetPageContentsRect(int index
) {
2026 return GetScreenRect(pages_
[index
]->rect());
2029 void PDFiumEngine::PaintThumbnail(pp::ImageData
* image_data
, int index
) {
2030 FPDF_BITMAP bitmap
= FPDFBitmap_CreateEx(
2031 image_data
->size().width(), image_data
->size().height(),
2032 FPDFBitmap_BGRx
, image_data
->data(), image_data
->stride());
2034 if (pages_
[index
]->available()) {
2035 FPDFBitmap_FillRect(bitmap
, 0, 0, image_data
->size().width(),
2036 image_data
->size().height(), 0xFFFFFFFF);
2038 FPDF_RenderPageBitmap(
2039 bitmap
, pages_
[index
]->GetPage(), 0, 0, image_data
->size().width(),
2040 image_data
->size().height(), 0, GetRenderingFlags());
2042 FPDFBitmap_FillRect(bitmap
, 0, 0, image_data
->size().width(),
2043 image_data
->size().height(), kPendingPageColor
);
2046 FPDFBitmap_Destroy(bitmap
);
2049 void PDFiumEngine::SetGrayscale(bool grayscale
) {
2050 render_grayscale_
= grayscale
;
2053 void PDFiumEngine::OnCallback(int id
) {
2054 if (!timers_
.count(id
))
2057 timers_
[id
].second(id
);
2058 if (timers_
.count(id
)) // The callback might delete the timer.
2059 client_
->ScheduleCallback(id
, timers_
[id
].first
);
2062 std::string
PDFiumEngine::GetPageAsJSON(int index
) {
2063 if (!(HasPermission(PERMISSION_COPY
) ||
2064 HasPermission(PERMISSION_COPY_ACCESSIBLE
))) {
2068 if (index
< 0 || static_cast<size_t>(index
) > pages_
.size() - 1)
2071 scoped_ptr
<base::Value
> node(
2072 pages_
[index
]->GetAccessibleContentAsValue(current_rotation_
));
2073 std::string page_json
;
2074 base::JSONWriter::Write(node
.get(), &page_json
);
2078 bool PDFiumEngine::GetPrintScaling() {
2079 return !!FPDF_VIEWERREF_GetPrintScaling(doc_
);
2082 void PDFiumEngine::AppendBlankPages(int num_pages
) {
2083 DCHECK(num_pages
!= 0);
2089 pending_pages_
.clear();
2091 // Delete all pages except the first one.
2092 while (pages_
.size() > 1) {
2093 delete pages_
.back();
2095 FPDFPage_Delete(doc_
, pages_
.size());
2098 // Calculate document size and all page sizes.
2099 std::vector
<pp::Rect
> page_rects
;
2100 pp::Size page_size
= GetPageSize(0);
2101 page_size
.Enlarge(kPageShadowLeft
+ kPageShadowRight
,
2102 kPageShadowTop
+ kPageShadowBottom
);
2103 pp::Size old_document_size
= document_size_
;
2104 document_size_
= pp::Size(page_size
.width(), 0);
2105 for (int i
= 0; i
< num_pages
; ++i
) {
2107 // Add space for horizontal separator.
2108 document_size_
.Enlarge(0, kPageSeparatorThickness
);
2111 pp::Rect
rect(pp::Point(0, document_size_
.height()), page_size
);
2112 page_rects
.push_back(rect
);
2114 document_size_
.Enlarge(0, page_size
.height());
2117 // Create blank pages.
2118 for (int i
= 1; i
< num_pages
; ++i
) {
2119 pp::Rect
page_rect(page_rects
[i
]);
2120 page_rect
.Inset(kPageShadowLeft
, kPageShadowTop
,
2121 kPageShadowRight
, kPageShadowBottom
);
2122 double width_in_points
=
2123 page_rect
.width() * kPointsPerInch
/ kPixelsPerInch
;
2124 double height_in_points
=
2125 page_rect
.height() * kPointsPerInch
/ kPixelsPerInch
;
2126 FPDFPage_New(doc_
, i
, width_in_points
, height_in_points
);
2127 pages_
.push_back(new PDFiumPage(this, i
, page_rect
, true));
2130 CalculateVisiblePages();
2131 if (document_size_
!= old_document_size
)
2132 client_
->DocumentSizeUpdated(document_size_
);
2135 void PDFiumEngine::LoadDocument() {
2136 // Check if the document is ready for loading. If it isn't just bail for now,
2137 // we will call LoadDocument() again later.
2138 if (!doc_
&& !doc_loader_
.IsDocumentComplete() &&
2139 !FPDFAvail_IsDocAvail(fpdf_availability_
, &download_hints_
)) {
2143 // If we're in the middle of getting a password, just return. We will retry
2144 // loading the document after we get the password anyway.
2145 if (getting_password_
)
2148 ScopedUnsupportedFeature
scoped_unsupported_feature(this);
2149 bool needs_password
= false;
2150 if (TryLoadingDoc(false, std::string(), &needs_password
)) {
2151 ContinueLoadingDocument(false, std::string());
2155 GetPasswordAndLoad();
2157 client_
->DocumentLoadFailed();
2160 bool PDFiumEngine::TryLoadingDoc(bool with_password
,
2161 const std::string
& password
,
2162 bool* needs_password
) {
2163 *needs_password
= false;
2167 const char* password_cstr
= NULL
;
2168 if (with_password
) {
2169 password_cstr
= password
.c_str();
2170 password_tries_remaining_
--;
2172 if (doc_loader_
.IsDocumentComplete())
2173 doc_
= FPDF_LoadCustomDocument(&file_access_
, password_cstr
);
2175 doc_
= FPDFAvail_GetDocument(fpdf_availability_
, password_cstr
);
2177 if (!doc_
&& FPDF_GetLastError() == FPDF_ERR_PASSWORD
)
2178 *needs_password
= true;
2180 return doc_
!= NULL
;
2183 void PDFiumEngine::GetPasswordAndLoad() {
2184 getting_password_
= true;
2185 DCHECK(!doc_
&& FPDF_GetLastError() == FPDF_ERR_PASSWORD
);
2186 client_
->GetDocumentPassword(password_factory_
.NewCallbackWithOutput(
2187 &PDFiumEngine::OnGetPasswordComplete
));
2190 void PDFiumEngine::OnGetPasswordComplete(int32_t result
,
2191 const pp::Var
& password
) {
2192 getting_password_
= false;
2194 bool password_given
= false;
2195 std::string password_text
;
2196 if (result
== PP_OK
&& password
.is_string()) {
2197 password_text
= password
.AsString();
2198 if (!password_text
.empty())
2199 password_given
= true;
2201 ContinueLoadingDocument(password_given
, password_text
);
2204 void PDFiumEngine::ContinueLoadingDocument(
2206 const std::string
& password
) {
2207 ScopedUnsupportedFeature
scoped_unsupported_feature(this);
2209 bool needs_password
= false;
2210 bool loaded
= TryLoadingDoc(has_password
, password
, &needs_password
);
2211 bool password_incorrect
= !loaded
&& has_password
&& needs_password
;
2212 if (password_incorrect
&& password_tries_remaining_
> 0) {
2213 GetPasswordAndLoad();
2218 client_
->DocumentLoadFailed();
2222 if (FPDFDoc_GetPageMode(doc_
) == PAGEMODE_USEOUTLINES
)
2223 client_
->DocumentHasUnsupportedFeature("Bookmarks");
2225 permissions_
= FPDF_GetDocPermissions(doc_
);
2228 // Only returns 0 when data isn't available. If form data is downloaded, or
2229 // if this isn't a form, returns positive values.
2230 if (!doc_loader_
.IsDocumentComplete() &&
2231 !FPDFAvail_IsFormAvail(fpdf_availability_
, &download_hints_
)) {
2235 form_
= FPDFDOC_InitFormFillEnviroument(
2236 doc_
, static_cast<FPDF_FORMFILLINFO
*>(this));
2237 FPDF_SetFormFieldHighlightColor(form_
, 0, kFormHighlightColor
);
2238 FPDF_SetFormFieldHighlightAlpha(form_
, kFormHighlightAlpha
);
2241 if (!doc_loader_
.IsDocumentComplete()) {
2242 // Check if the first page is available. In a linearized PDF, that is not
2243 // always page 0. Doing this gives us the default page size, since when the
2244 // document is available, the first page is available as well.
2245 CheckPageAvailable(FPDFAvail_GetFirstPageNum(doc_
), &pending_pages_
);
2248 LoadPageInfo(false);
2250 if (doc_loader_
.IsDocumentComplete())
2251 FinishLoadingDocument();
2254 void PDFiumEngine::LoadPageInfo(bool reload
) {
2255 pending_pages_
.clear();
2256 pp::Size old_document_size
= document_size_
;
2257 document_size_
= pp::Size();
2258 std::vector
<pp::Rect
> page_rects
;
2259 int page_count
= FPDF_GetPageCount(doc_
);
2260 bool doc_complete
= doc_loader_
.IsDocumentComplete();
2261 for (int i
= 0; i
< page_count
; ++i
) {
2263 // Add space for horizontal separator.
2264 document_size_
.Enlarge(0, kPageSeparatorThickness
);
2267 // Get page availability. If reload==false, and document is not loaded yet
2268 // (we are using async loading) - mark all pages as unavailable.
2269 // If reload==true (we have document constructed already), get page
2270 // availability flag from already existing PDFiumPage class.
2271 bool page_available
= reload
? pages_
[i
]->available() : doc_complete
;
2273 pp::Size size
= page_available
? GetPageSize(i
) : default_page_size_
;
2274 size
.Enlarge(kPageShadowLeft
+ kPageShadowRight
,
2275 kPageShadowTop
+ kPageShadowBottom
);
2276 pp::Rect
rect(pp::Point(0, document_size_
.height()), size
);
2277 page_rects
.push_back(rect
);
2279 if (size
.width() > document_size_
.width())
2280 document_size_
.set_width(size
.width());
2282 document_size_
.Enlarge(0, size
.height());
2285 for (int i
= 0; i
< page_count
; ++i
) {
2286 // Center pages relative to the entire document.
2287 page_rects
[i
].set_x((document_size_
.width() - page_rects
[i
].width()) / 2);
2288 pp::Rect
page_rect(page_rects
[i
]);
2289 page_rect
.Inset(kPageShadowLeft
, kPageShadowTop
,
2290 kPageShadowRight
, kPageShadowBottom
);
2292 pages_
[i
]->set_rect(page_rect
);
2294 pages_
.push_back(new PDFiumPage(this, i
, page_rect
, doc_complete
));
2298 CalculateVisiblePages();
2299 if (document_size_
!= old_document_size
)
2300 client_
->DocumentSizeUpdated(document_size_
);
2303 void PDFiumEngine::CalculateVisiblePages() {
2304 // Clear pending requests queue, since it may contain requests to the pages
2305 // that are already invisible (after scrolling for example).
2306 pending_pages_
.clear();
2307 doc_loader_
.ClearPendingRequests();
2309 visible_pages_
.clear();
2310 pp::Rect
visible_rect(plugin_size_
);
2311 for (size_t i
= 0; i
< pages_
.size(); ++i
) {
2312 // Check an entire PageScreenRect, since we might need to repaint side
2313 // borders and shadows even if the page itself is not visible.
2314 // For example, when user use pdf with different page sizes and zoomed in
2315 // outside page area.
2316 if (visible_rect
.Intersects(GetPageScreenRect(i
))) {
2317 visible_pages_
.push_back(i
);
2318 CheckPageAvailable(i
, &pending_pages_
);
2320 // Need to unload pages when we're not using them, since some PDFs use a
2321 // lot of memory. See http://crbug.com/48791
2322 if (defer_page_unload_
) {
2323 deferred_page_unloads_
.push_back(i
);
2325 pages_
[i
]->Unload();
2328 // If the last mouse down was on a page that's no longer visible, reset
2329 // that variable so that we don't send keyboard events to it (the focus
2330 // will be lost when the page is first closed anyways).
2331 if (static_cast<int>(i
) == last_page_mouse_down_
)
2332 last_page_mouse_down_
= -1;
2336 // Any pending highlighting of form fields will be invalid since these are in
2337 // screen coordinates.
2338 form_highlights_
.clear();
2340 if (visible_pages_
.size() == 0)
2341 first_visible_page_
= -1;
2343 first_visible_page_
= visible_pages_
.front();
2345 int most_visible_page
= first_visible_page_
;
2346 // Check if the next page is more visible than the first one.
2347 if (most_visible_page
!= -1 &&
2348 pages_
.size() > 0 &&
2349 most_visible_page
< static_cast<int>(pages_
.size()) - 1) {
2351 visible_rect
.Intersect(GetPageScreenRect(most_visible_page
));
2353 visible_rect
.Intersect(GetPageScreenRect(most_visible_page
+ 1));
2354 if (rc_next
.height() > rc_first
.height())
2355 most_visible_page
++;
2358 SetCurrentPage(most_visible_page
);
2361 bool PDFiumEngine::IsPageVisible(int index
) const {
2362 for (size_t i
= 0; i
< visible_pages_
.size(); ++i
) {
2363 if (visible_pages_
[i
] == index
)
2370 bool PDFiumEngine::CheckPageAvailable(int index
, std::vector
<int>* pending
) {
2371 if (!doc_
|| !form_
)
2374 if (static_cast<int>(pages_
.size()) > index
&& pages_
[index
]->available())
2377 if (!FPDFAvail_IsPageAvail(fpdf_availability_
, index
, &download_hints_
)) {
2379 for (j
= 0; j
< pending
->size(); ++j
) {
2380 if ((*pending
)[j
] == index
)
2384 if (j
== pending
->size())
2385 pending
->push_back(index
);
2389 if (static_cast<int>(pages_
.size()) > index
)
2390 pages_
[index
]->set_available(true);
2391 if (!default_page_size_
.GetArea())
2392 default_page_size_
= GetPageSize(index
);
2396 pp::Size
PDFiumEngine::GetPageSize(int index
) {
2398 double width_in_points
= 0;
2399 double height_in_points
= 0;
2400 int rv
= FPDF_GetPageSizeByIndex(
2401 doc_
, index
, &width_in_points
, &height_in_points
);
2404 int width_in_pixels
= static_cast<int>(
2405 width_in_points
* kPixelsPerInch
/ kPointsPerInch
);
2406 int height_in_pixels
= static_cast<int>(
2407 height_in_points
* kPixelsPerInch
/ kPointsPerInch
);
2408 if (current_rotation_
% 2 == 1)
2409 std::swap(width_in_pixels
, height_in_pixels
);
2410 size
= pp::Size(width_in_pixels
, height_in_pixels
);
2415 int PDFiumEngine::StartPaint(int page_index
, const pp::Rect
& dirty
) {
2416 // For the first time we hit paint, do nothing and just record the paint for
2417 // the next callback. This keeps the UI responsive in case the user is doing
2418 // a lot of scrolling.
2419 ProgressivePaint progressive
;
2420 progressive
.rect
= dirty
;
2421 progressive
.page_index
= page_index
;
2422 progressive
.bitmap
= NULL
;
2423 progressive
.painted_
= false;
2424 progressive_paints_
.push_back(progressive
);
2425 return progressive_paints_
.size() - 1;
2428 bool PDFiumEngine::ContinuePaint(int progressive_index
,
2429 pp::ImageData
* image_data
) {
2430 #if defined(OS_LINUX)
2431 g_last_instance_id
= client_
->GetPluginInstance()->pp_instance();
2435 int page_index
= progressive_paints_
[progressive_index
].page_index
;
2436 last_progressive_start_time_
= base::Time::Now();
2437 if (progressive_paints_
[progressive_index
].bitmap
) {
2438 rv
= FPDF_RenderPage_Continue(
2439 pages_
[page_index
]->GetPage(), static_cast<IFSDK_PAUSE
*>(this));
2441 pp::Rect dirty
= progressive_paints_
[progressive_index
].rect
;
2442 progressive_paints_
[progressive_index
].bitmap
= CreateBitmap(dirty
,
2444 int start_x
, start_y
, size_x
, size_y
;
2446 page_index
, dirty
, &start_x
, &start_y
, &size_x
, &size_y
);
2447 FPDFBitmap_FillRect(progressive_paints_
[progressive_index
].bitmap
, start_x
,
2448 start_y
, size_x
, size_y
, 0xFFFFFFFF);
2449 rv
= FPDF_RenderPageBitmap_Start(
2450 progressive_paints_
[progressive_index
].bitmap
,
2451 pages_
[page_index
]->GetPage(), start_x
, start_y
, size_x
, size_y
,
2453 GetRenderingFlags(), static_cast<IFSDK_PAUSE
*>(this));
2455 return rv
!= FPDF_RENDER_TOBECOUNTINUED
;
2458 void PDFiumEngine::FinishPaint(int progressive_index
,
2459 pp::ImageData
* image_data
) {
2460 int page_index
= progressive_paints_
[progressive_index
].page_index
;
2461 pp::Rect dirty_in_screen
= progressive_paints_
[progressive_index
].rect
;
2462 FPDF_BITMAP bitmap
= progressive_paints_
[progressive_index
].bitmap
;
2463 int start_x
, start_y
, size_x
, size_y
;
2465 page_index
, dirty_in_screen
, &start_x
, &start_y
, &size_x
, &size_y
);
2469 form_
, bitmap
, pages_
[page_index
]->GetPage(), start_x
, start_y
, size_x
,
2470 size_y
, current_rotation_
, GetRenderingFlags());
2472 FillPageSides(progressive_index
);
2474 // Paint the page shadows.
2475 PaintPageShadow(progressive_index
, image_data
);
2477 DrawSelections(progressive_index
, image_data
);
2479 FPDF_RenderPage_Close(pages_
[page_index
]->GetPage());
2480 FPDFBitmap_Destroy(bitmap
);
2481 progressive_paints_
.erase(progressive_paints_
.begin() + progressive_index
);
2483 client_
->DocumentPaintOccurred();
2486 void PDFiumEngine::CancelPaints() {
2487 for (size_t i
= 0; i
< progressive_paints_
.size(); ++i
) {
2488 FPDF_RenderPage_Close(pages_
[progressive_paints_
[i
].page_index
]->GetPage());
2489 FPDFBitmap_Destroy(progressive_paints_
[i
].bitmap
);
2491 progressive_paints_
.clear();
2494 void PDFiumEngine::FillPageSides(int progressive_index
) {
2495 int page_index
= progressive_paints_
[progressive_index
].page_index
;
2496 pp::Rect dirty_in_screen
= progressive_paints_
[progressive_index
].rect
;
2497 FPDF_BITMAP bitmap
= progressive_paints_
[progressive_index
].bitmap
;
2499 pp::Rect page_rect
= pages_
[page_index
]->rect();
2500 if (page_rect
.x() > 0) {
2502 page_rect
.y() - kPageShadowTop
,
2503 page_rect
.x() - kPageShadowLeft
,
2504 page_rect
.height() + kPageShadowTop
+
2505 kPageShadowBottom
+ kPageSeparatorThickness
);
2506 left
= GetScreenRect(left
).Intersect(dirty_in_screen
);
2508 FPDFBitmap_FillRect(bitmap
, left
.x() - dirty_in_screen
.x(),
2509 left
.y() - dirty_in_screen
.y(), left
.width(),
2510 left
.height(), kBackgroundColor
);
2513 if (page_rect
.right() < document_size_
.width()) {
2514 pp::Rect
right(page_rect
.right() + kPageShadowRight
,
2515 page_rect
.y() - kPageShadowTop
,
2516 document_size_
.width() - page_rect
.right() -
2518 page_rect
.height() + kPageShadowTop
+
2519 kPageShadowBottom
+ kPageSeparatorThickness
);
2520 right
= GetScreenRect(right
).Intersect(dirty_in_screen
);
2522 FPDFBitmap_FillRect(bitmap
, right
.x() - dirty_in_screen
.x(),
2523 right
.y() - dirty_in_screen
.y(), right
.width(),
2524 right
.height(), kBackgroundColor
);
2528 pp::Rect
bottom(page_rect
.x() - kPageShadowLeft
,
2529 page_rect
.bottom() + kPageShadowBottom
,
2530 page_rect
.width() + kPageShadowLeft
+ kPageShadowRight
,
2531 kPageSeparatorThickness
);
2532 bottom
= GetScreenRect(bottom
).Intersect(dirty_in_screen
);
2534 FPDFBitmap_FillRect(bitmap
, bottom
.x() - dirty_in_screen
.x(),
2535 bottom
.y() - dirty_in_screen
.y(), bottom
.width(),
2536 bottom
.height(), kBackgroundColor
);
2539 void PDFiumEngine::PaintPageShadow(int progressive_index
,
2540 pp::ImageData
* image_data
) {
2541 int page_index
= progressive_paints_
[progressive_index
].page_index
;
2542 pp::Rect dirty_in_screen
= progressive_paints_
[progressive_index
].rect
;
2543 pp::Rect page_rect
= pages_
[page_index
]->rect();
2544 pp::Rect
shadow_rect(page_rect
);
2545 shadow_rect
.Inset(-kPageShadowLeft
, -kPageShadowTop
,
2546 -kPageShadowRight
, -kPageShadowBottom
);
2548 // Due to the rounding errors of the GetScreenRect it is possible to get
2549 // different size shadows on the left and right sides even they are defined
2550 // the same. To fix this issue let's calculate shadow rect and then shrink
2551 // it by the size of the shadows.
2552 shadow_rect
= GetScreenRect(shadow_rect
);
2553 page_rect
= shadow_rect
;
2555 page_rect
.Inset(static_cast<int>(ceil(kPageShadowLeft
* current_zoom_
)),
2556 static_cast<int>(ceil(kPageShadowTop
* current_zoom_
)),
2557 static_cast<int>(ceil(kPageShadowRight
* current_zoom_
)),
2558 static_cast<int>(ceil(kPageShadowBottom
* current_zoom_
)));
2560 DrawPageShadow(page_rect
, shadow_rect
, dirty_in_screen
, image_data
);
2563 void PDFiumEngine::DrawSelections(int progressive_index
,
2564 pp::ImageData
* image_data
) {
2565 int page_index
= progressive_paints_
[progressive_index
].page_index
;
2566 pp::Rect dirty_in_screen
= progressive_paints_
[progressive_index
].rect
;
2568 void* region
= NULL
;
2570 GetRegion(dirty_in_screen
.point(), image_data
, ®ion
, &stride
);
2572 std::vector
<pp::Rect
> highlighted_rects
;
2573 pp::Rect visible_rect
= GetVisibleRect();
2574 for (size_t k
= 0; k
< selection_
.size(); ++k
) {
2575 if (selection_
[k
].page_index() != page_index
)
2577 std::vector
<pp::Rect
> rects
= selection_
[k
].GetScreenRects(
2578 visible_rect
.point(), current_zoom_
, current_rotation_
);
2579 for (size_t j
= 0; j
< rects
.size(); ++j
) {
2580 pp::Rect visible_selection
= rects
[j
].Intersect(dirty_in_screen
);
2581 if (visible_selection
.IsEmpty())
2584 visible_selection
.Offset(
2585 -dirty_in_screen
.point().x(), -dirty_in_screen
.point().y());
2586 Highlight(region
, stride
, visible_selection
, &highlighted_rects
);
2590 for (size_t k
= 0; k
< form_highlights_
.size(); ++k
) {
2591 pp::Rect visible_selection
= form_highlights_
[k
].Intersect(dirty_in_screen
);
2592 if (visible_selection
.IsEmpty())
2595 visible_selection
.Offset(
2596 -dirty_in_screen
.point().x(), -dirty_in_screen
.point().y());
2597 Highlight(region
, stride
, visible_selection
, &highlighted_rects
);
2599 form_highlights_
.clear();
2602 void PDFiumEngine::PaintUnavailablePage(int page_index
,
2603 const pp::Rect
& dirty
,
2604 pp::ImageData
* image_data
) {
2605 int start_x
, start_y
, size_x
, size_y
;
2606 GetPDFiumRect(page_index
, dirty
, &start_x
, &start_y
, &size_x
, &size_y
);
2607 FPDF_BITMAP bitmap
= CreateBitmap(dirty
, image_data
);
2608 FPDFBitmap_FillRect(bitmap
, start_x
, start_y
, size_x
, size_y
,
2611 pp::Rect
loading_text_in_screen(
2612 pages_
[page_index
]->rect().width() / 2,
2613 pages_
[page_index
]->rect().y() + kLoadingTextVerticalOffset
, 0, 0);
2614 loading_text_in_screen
= GetScreenRect(loading_text_in_screen
);
2615 FPDFBitmap_Destroy(bitmap
);
2618 int PDFiumEngine::GetProgressiveIndex(int page_index
) const {
2619 for (size_t i
= 0; i
< progressive_paints_
.size(); ++i
) {
2620 if (progressive_paints_
[i
].page_index
== page_index
)
2626 FPDF_BITMAP
PDFiumEngine::CreateBitmap(const pp::Rect
& rect
,
2627 pp::ImageData
* image_data
) const {
2630 GetRegion(rect
.point(), image_data
, ®ion
, &stride
);
2633 return FPDFBitmap_CreateEx(
2634 rect
.width(), rect
.height(), FPDFBitmap_BGRx
, region
, stride
);
2637 void PDFiumEngine::GetPDFiumRect(
2638 int page_index
, const pp::Rect
& rect
, int* start_x
, int* start_y
,
2639 int* size_x
, int* size_y
) const {
2640 pp::Rect page_rect
= GetScreenRect(pages_
[page_index
]->rect());
2641 page_rect
.Offset(-rect
.x(), -rect
.y());
2643 *start_x
= page_rect
.x();
2644 *start_y
= page_rect
.y();
2645 *size_x
= page_rect
.width();
2646 *size_y
= page_rect
.height();
2649 int PDFiumEngine::GetRenderingFlags() const {
2650 int flags
= FPDF_LCD_TEXT
| FPDF_NO_CATCH
;
2651 if (render_grayscale_
)
2652 flags
|= FPDF_GRAYSCALE
;
2653 if (client_
->IsPrintPreview())
2654 flags
|= FPDF_PRINTING
;
2658 pp::Rect
PDFiumEngine::GetVisibleRect() const {
2660 rv
.set_x(static_cast<int>(position_
.x() / current_zoom_
));
2661 rv
.set_y(static_cast<int>(position_
.y() / current_zoom_
));
2662 rv
.set_width(static_cast<int>(ceil(plugin_size_
.width() / current_zoom_
)));
2663 rv
.set_height(static_cast<int>(ceil(plugin_size_
.height() / current_zoom_
)));
2667 pp::Rect
PDFiumEngine::GetPageScreenRect(int page_index
) const {
2668 // Since we use this rect for creating the PDFium bitmap, also include other
2669 // areas around the page that we might need to update such as the page
2670 // separator and the sides if the page is narrower than the document.
2671 return GetScreenRect(pp::Rect(
2673 pages_
[page_index
]->rect().y() - kPageShadowTop
,
2674 document_size_
.width(),
2675 pages_
[page_index
]->rect().height() + kPageShadowTop
+
2676 kPageShadowBottom
+ kPageSeparatorThickness
));
2679 pp::Rect
PDFiumEngine::GetScreenRect(const pp::Rect
& rect
) const {
2682 static_cast<int>(ceil(rect
.right() * current_zoom_
- position_
.x()));
2684 static_cast<int>(ceil(rect
.bottom() * current_zoom_
- position_
.y()));
2686 rv
.set_x(static_cast<int>(rect
.x() * current_zoom_
- position_
.x()));
2687 rv
.set_y(static_cast<int>(rect
.y() * current_zoom_
- position_
.y()));
2688 rv
.set_width(right
- rv
.x());
2689 rv
.set_height(bottom
- rv
.y());
2693 void PDFiumEngine::Highlight(void* buffer
,
2695 const pp::Rect
& rect
,
2696 std::vector
<pp::Rect
>* highlighted_rects
) {
2700 pp::Rect new_rect
= rect
;
2701 for (size_t i
= 0; i
< highlighted_rects
->size(); ++i
)
2702 new_rect
= new_rect
.Subtract((*highlighted_rects
)[i
]);
2704 highlighted_rects
->push_back(new_rect
);
2705 int l
= new_rect
.x();
2706 int t
= new_rect
.y();
2707 int w
= new_rect
.width();
2708 int h
= new_rect
.height();
2710 for (int y
= t
; y
< t
+ h
; ++y
) {
2711 for (int x
= l
; x
< l
+ w
; ++x
) {
2712 uint8
* pixel
= static_cast<uint8
*>(buffer
) + y
* stride
+ x
* 4;
2713 // This is our highlight color.
2714 pixel
[0] = static_cast<uint8
>(
2715 pixel
[0] * (kHighlightColorB
/ 255.0));
2716 pixel
[1] = static_cast<uint8
>(
2717 pixel
[1] * (kHighlightColorG
/ 255.0));
2718 pixel
[2] = static_cast<uint8
>(
2719 pixel
[2] * (kHighlightColorR
/ 255.0));
2724 PDFiumEngine::SelectionChangeInvalidator::SelectionChangeInvalidator(
2725 PDFiumEngine
* engine
) : engine_(engine
) {
2726 previous_origin_
= engine_
->GetVisibleRect().point();
2727 GetVisibleSelectionsScreenRects(&old_selections_
);
2730 PDFiumEngine::SelectionChangeInvalidator::~SelectionChangeInvalidator() {
2731 // Offset the old selections if the document scrolled since we recorded them.
2732 pp::Point offset
= previous_origin_
- engine_
->GetVisibleRect().point();
2733 for (size_t i
= 0; i
< old_selections_
.size(); ++i
)
2734 old_selections_
[i
].Offset(offset
);
2736 std::vector
<pp::Rect
> new_selections
;
2737 GetVisibleSelectionsScreenRects(&new_selections
);
2738 for (size_t i
= 0; i
< new_selections
.size(); ++i
) {
2739 for (size_t j
= 0; j
< old_selections_
.size(); ++j
) {
2740 if (!old_selections_
[j
].IsEmpty() &&
2741 new_selections
[i
] == old_selections_
[j
]) {
2742 // Rectangle was selected before and after, so no need to invalidate it.
2743 // Mark the rectangles by setting them to empty.
2744 new_selections
[i
] = old_selections_
[j
] = pp::Rect();
2750 for (size_t i
= 0; i
< old_selections_
.size(); ++i
) {
2751 if (!old_selections_
[i
].IsEmpty())
2752 engine_
->client_
->Invalidate(old_selections_
[i
]);
2754 for (size_t i
= 0; i
< new_selections
.size(); ++i
) {
2755 if (!new_selections
[i
].IsEmpty())
2756 engine_
->client_
->Invalidate(new_selections
[i
]);
2758 engine_
->OnSelectionChanged();
2762 PDFiumEngine::SelectionChangeInvalidator::GetVisibleSelectionsScreenRects(
2763 std::vector
<pp::Rect
>* rects
) {
2764 pp::Rect visible_rect
= engine_
->GetVisibleRect();
2765 for (size_t i
= 0; i
< engine_
->selection_
.size(); ++i
) {
2766 int page_index
= engine_
->selection_
[i
].page_index();
2767 if (!engine_
->IsPageVisible(page_index
))
2768 continue; // This selection is on a page that's not currently visible.
2770 std::vector
<pp::Rect
> selection_rects
=
2771 engine_
->selection_
[i
].GetScreenRects(
2772 visible_rect
.point(),
2773 engine_
->current_zoom_
,
2774 engine_
->current_rotation_
);
2775 rects
->insert(rects
->end(), selection_rects
.begin(), selection_rects
.end());
2779 PDFiumEngine::MouseDownState::MouseDownState(
2780 const PDFiumPage::Area
& area
,
2781 const PDFiumPage::LinkTarget
& target
)
2782 : area_(area
), target_(target
) {
2785 PDFiumEngine::MouseDownState::~MouseDownState() {
2788 void PDFiumEngine::MouseDownState::Set(const PDFiumPage::Area
& area
,
2789 const PDFiumPage::LinkTarget
& target
) {
2794 void PDFiumEngine::MouseDownState::Reset() {
2795 area_
= PDFiumPage::NONSELECTABLE_AREA
;
2796 target_
= PDFiumPage::LinkTarget();
2799 bool PDFiumEngine::MouseDownState::Matches(
2800 const PDFiumPage::Area
& area
,
2801 const PDFiumPage::LinkTarget
& target
) const {
2802 if (area_
== area
) {
2803 if (area
== PDFiumPage::WEBLINK_AREA
)
2804 return target_
.url
== target
.url
;
2805 if (area
== PDFiumPage::DOCLINK_AREA
)
2806 return target_
.page
== target
.page
;
2812 void PDFiumEngine::DeviceToPage(int page_index
,
2817 *page_x
= *page_y
= 0;
2818 int temp_x
= static_cast<int>((device_x
+ position_
.x())/ current_zoom_
-
2819 pages_
[page_index
]->rect().x());
2820 int temp_y
= static_cast<int>((device_y
+ position_
.y())/ current_zoom_
-
2821 pages_
[page_index
]->rect().y());
2823 pages_
[page_index
]->GetPage(), 0, 0,
2824 pages_
[page_index
]->rect().width(), pages_
[page_index
]->rect().height(),
2825 current_rotation_
, temp_x
, temp_y
, page_x
, page_y
);
2828 int PDFiumEngine::GetVisiblePageIndex(FPDF_PAGE page
) {
2829 for (size_t i
= 0; i
< visible_pages_
.size(); ++i
) {
2830 if (pages_
[visible_pages_
[i
]]->GetPage() == page
)
2831 return visible_pages_
[i
];
2836 void PDFiumEngine::SetCurrentPage(int index
) {
2837 if (index
== most_visible_page_
|| !form_
)
2839 if (most_visible_page_
!= -1 && called_do_document_action_
) {
2840 FPDF_PAGE old_page
= pages_
[most_visible_page_
]->GetPage();
2841 FORM_DoPageAAction(old_page
, form_
, FPDFPAGE_AACTION_CLOSE
);
2843 most_visible_page_
= index
;
2844 #if defined(OS_LINUX)
2845 g_last_instance_id
= client_
->GetPluginInstance()->pp_instance();
2847 if (most_visible_page_
!= -1 && called_do_document_action_
) {
2848 FPDF_PAGE new_page
= pages_
[most_visible_page_
]->GetPage();
2849 FORM_DoPageAAction(new_page
, form_
, FPDFPAGE_AACTION_OPEN
);
2853 void PDFiumEngine::TransformPDFPageForPrinting(
2855 const PP_PrintSettings_Dev
& print_settings
) {
2856 // Get the source page width and height in points.
2857 const double src_page_width
= FPDF_GetPageWidth(page
);
2858 const double src_page_height
= FPDF_GetPageHeight(page
);
2860 const int src_page_rotation
= FPDFPage_GetRotation(page
);
2861 const bool fit_to_page
= print_settings
.print_scaling_option
==
2862 PP_PRINTSCALINGOPTION_FIT_TO_PRINTABLE_AREA
;
2864 pp::Size
page_size(print_settings
.paper_size
);
2865 pp::Rect
content_rect(print_settings
.printable_area
);
2866 const bool rotated
= (src_page_rotation
% 2 == 1);
2867 SetPageSizeAndContentRect(rotated
,
2868 src_page_width
> src_page_height
,
2872 // Compute the screen page width and height in points.
2873 const int actual_page_width
=
2874 rotated
? page_size
.height() : page_size
.width();
2875 const int actual_page_height
=
2876 rotated
? page_size
.width() : page_size
.height();
2878 const double scale_factor
= CalculateScaleFactor(fit_to_page
, content_rect
,
2880 src_page_height
, rotated
);
2882 // Calculate positions for the clip box.
2883 ClipBox source_clip_box
;
2884 CalculateClipBoxBoundary(page
, scale_factor
, rotated
, &source_clip_box
);
2886 // Calculate the translation offset values.
2887 double offset_x
= 0;
2888 double offset_y
= 0;
2890 CalculateScaledClipBoxOffset(content_rect
, source_clip_box
, &offset_x
,
2893 CalculateNonScaledClipBoxOffset(content_rect
, src_page_rotation
,
2894 actual_page_width
, actual_page_height
,
2895 source_clip_box
, &offset_x
, &offset_y
);
2898 // Reset the media box and crop box. When the page has crop box and media box,
2899 // the plugin will display the crop box contents and not the entire media box.
2900 // If the pages have different crop box values, the plugin will display a
2901 // document of multiple page sizes. To give better user experience, we
2902 // decided to have same crop box and media box values. Hence, the user will
2903 // see a list of uniform pages.
2904 FPDFPage_SetMediaBox(page
, 0, 0, page_size
.width(), page_size
.height());
2905 FPDFPage_SetCropBox(page
, 0, 0, page_size
.width(), page_size
.height());
2907 // Transformation is not required, return. Do this check only after updating
2908 // the media box and crop box. For more detailed information, please refer to
2909 // the comment block right before FPDF_SetMediaBox and FPDF_GetMediaBox calls.
2910 if (scale_factor
== 1.0 && offset_x
== 0 && offset_y
== 0)
2914 // All the positions have been calculated, now manipulate the PDF.
2915 FS_MATRIX matrix
= {static_cast<float>(scale_factor
),
2918 static_cast<float>(scale_factor
),
2919 static_cast<float>(offset_x
),
2920 static_cast<float>(offset_y
)};
2921 FS_RECTF cliprect
= {static_cast<float>(source_clip_box
.left
+offset_x
),
2922 static_cast<float>(source_clip_box
.top
+offset_y
),
2923 static_cast<float>(source_clip_box
.right
+offset_x
),
2924 static_cast<float>(source_clip_box
.bottom
+offset_y
)};
2925 FPDFPage_TransFormWithClip(page
, &matrix
, &cliprect
);
2926 FPDFPage_TransformAnnots(page
, scale_factor
, 0, 0, scale_factor
,
2927 offset_x
, offset_y
);
2930 void PDFiumEngine::DrawPageShadow(const pp::Rect
& page_rc
,
2931 const pp::Rect
& shadow_rc
,
2932 const pp::Rect
& clip_rc
,
2933 pp::ImageData
* image_data
) {
2934 pp::Rect
page_rect(page_rc
);
2935 page_rect
.Offset(page_offset_
);
2937 pp::Rect
shadow_rect(shadow_rc
);
2938 shadow_rect
.Offset(page_offset_
);
2940 pp::Rect
clip_rect(clip_rc
);
2941 clip_rect
.Offset(page_offset_
);
2943 // Page drop shadow parameters.
2944 const double factor
= 0.5;
2945 uint32 depth
= std::max(
2946 std::max(page_rect
.x() - shadow_rect
.x(),
2947 page_rect
.y() - shadow_rect
.y()),
2948 std::max(shadow_rect
.right() - page_rect
.right(),
2949 shadow_rect
.bottom() - page_rect
.bottom()));
2950 depth
= static_cast<uint32
>(depth
* 1.5) + 1;
2952 // We need to check depth only to verify our copy of shadow matrix is correct.
2953 if (!page_shadow_
.get() || page_shadow_
->depth() != depth
)
2954 page_shadow_
.reset(new ShadowMatrix(depth
, factor
, kBackgroundColor
));
2956 DCHECK(!image_data
->is_null());
2957 DrawShadow(image_data
, shadow_rect
, page_rect
, clip_rect
, *page_shadow_
);
2960 void PDFiumEngine::GetRegion(const pp::Point
& location
,
2961 pp::ImageData
* image_data
,
2963 int* stride
) const {
2964 if (image_data
->is_null()) {
2965 DCHECK(plugin_size_
.IsEmpty());
2970 char* buffer
= static_cast<char*>(image_data
->data());
2971 *stride
= image_data
->stride();
2973 pp::Point offset_location
= location
+ page_offset_
;
2974 // TODO: update this when we support BIDI and scrollbars can be on the left.
2976 !pp::Rect(page_offset_
, plugin_size_
).Contains(offset_location
)) {
2981 buffer
+= location
.y() * (*stride
);
2982 buffer
+= (location
.x() + page_offset_
.x()) * 4;
2986 void PDFiumEngine::OnSelectionChanged() {
2987 if (HasPermission(PDFEngine::PERMISSION_COPY
))
2988 pp::PDF::SetSelectedText(GetPluginInstance(), GetSelectedText().c_str());
2991 void PDFiumEngine::Form_Invalidate(FPDF_FORMFILLINFO
* param
,
2997 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
2998 int page_index
= engine
->GetVisiblePageIndex(page
);
2999 if (page_index
== -1) {
3000 // This can sometime happen when the page is closed because it went off
3001 // screen, and PDFium invalidates the control as it's being deleted.
3005 pp::Rect rect
= engine
->pages_
[page_index
]->PageToScreen(
3006 engine
->GetVisibleRect().point(), engine
->current_zoom_
, left
, top
, right
,
3007 bottom
, engine
->current_rotation_
);
3008 engine
->client_
->Invalidate(rect
);
3011 void PDFiumEngine::Form_OutputSelectedRect(FPDF_FORMFILLINFO
* param
,
3017 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3018 int page_index
= engine
->GetVisiblePageIndex(page
);
3019 if (page_index
== -1) {
3023 pp::Rect rect
= engine
->pages_
[page_index
]->PageToScreen(
3024 engine
->GetVisibleRect().point(), engine
->current_zoom_
, left
, top
, right
,
3025 bottom
, engine
->current_rotation_
);
3026 engine
->form_highlights_
.push_back(rect
);
3029 void PDFiumEngine::Form_SetCursor(FPDF_FORMFILLINFO
* param
, int cursor_type
) {
3030 // We don't need this since it's not enough to change the cursor in all
3031 // scenarios. Instead, we check which form field we're under in OnMouseMove.
3034 int PDFiumEngine::Form_SetTimer(FPDF_FORMFILLINFO
* param
,
3036 TimerCallback timer_func
) {
3037 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3038 engine
->timers_
[++engine
->next_timer_id_
] =
3039 std::pair
<int, TimerCallback
>(elapse
, timer_func
);
3040 engine
->client_
->ScheduleCallback(engine
->next_timer_id_
, elapse
);
3041 return engine
->next_timer_id_
;
3044 void PDFiumEngine::Form_KillTimer(FPDF_FORMFILLINFO
* param
, int timer_id
) {
3045 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3046 engine
->timers_
.erase(timer_id
);
3049 FPDF_SYSTEMTIME
PDFiumEngine::Form_GetLocalTime(FPDF_FORMFILLINFO
* param
) {
3050 base::Time time
= base::Time::Now();
3051 base::Time::Exploded exploded
;
3052 time
.LocalExplode(&exploded
);
3055 rv
.wYear
= exploded
.year
;
3056 rv
.wMonth
= exploded
.month
;
3057 rv
.wDayOfWeek
= exploded
.day_of_week
;
3058 rv
.wDay
= exploded
.day_of_month
;
3059 rv
.wHour
= exploded
.hour
;
3060 rv
.wMinute
= exploded
.minute
;
3061 rv
.wSecond
= exploded
.second
;
3062 rv
.wMilliseconds
= exploded
.millisecond
;
3066 void PDFiumEngine::Form_OnChange(FPDF_FORMFILLINFO
* param
) {
3067 // Don't care about.
3070 FPDF_PAGE
PDFiumEngine::Form_GetPage(FPDF_FORMFILLINFO
* param
,
3071 FPDF_DOCUMENT document
,
3073 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3074 if (page_index
< 0 || page_index
>= static_cast<int>(engine
->pages_
.size()))
3076 return engine
->pages_
[page_index
]->GetPage();
3079 FPDF_PAGE
PDFiumEngine::Form_GetCurrentPage(FPDF_FORMFILLINFO
* param
,
3080 FPDF_DOCUMENT document
) {
3081 // TODO(jam): find out what this is used for.
3082 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3083 int index
= engine
->last_page_mouse_down_
;
3085 index
= engine
->GetMostVisiblePage();
3092 return engine
->pages_
[index
]->GetPage();
3095 int PDFiumEngine::Form_GetRotation(FPDF_FORMFILLINFO
* param
, FPDF_PAGE page
) {
3099 void PDFiumEngine::Form_ExecuteNamedAction(FPDF_FORMFILLINFO
* param
,
3100 FPDF_BYTESTRING named_action
) {
3101 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3102 std::string
action(named_action
);
3103 if (action
== "Print") {
3104 engine
->client_
->Print();
3108 int index
= engine
->last_page_mouse_down_
;
3109 /* Don't try to calculate the most visible page if we don't have a left click
3110 before this event (this code originally copied Form_GetCurrentPage which of
3111 course needs to do that and which doesn't have recursion). This can end up
3112 causing infinite recursion. See http://crbug.com/240413 for more
3113 information. Either way, it's not necessary for the spec'd list of named
3116 index = engine->GetMostVisiblePage();
3121 // This is the only list of named actions per the spec (see 12.6.4.11). Adobe
3122 // Reader supports more, like FitWidth, but since they're not part of the spec
3123 // and we haven't got bugs about them, no need to now.
3124 if (action
== "NextPage") {
3125 engine
->client_
->ScrollToPage(index
+ 1);
3126 } else if (action
== "PrevPage") {
3127 engine
->client_
->ScrollToPage(index
- 1);
3128 } else if (action
== "FirstPage") {
3129 engine
->client_
->ScrollToPage(0);
3130 } else if (action
== "LastPage") {
3131 engine
->client_
->ScrollToPage(engine
->pages_
.size() - 1);
3135 void PDFiumEngine::Form_SetTextFieldFocus(FPDF_FORMFILLINFO
* param
,
3136 FPDF_WIDESTRING value
,
3137 FPDF_DWORD valueLen
,
3138 FPDF_BOOL is_focus
) {
3139 // Do nothing for now.
3140 // TODO(gene): use this signal to trigger OSK.
3143 void PDFiumEngine::Form_DoURIAction(FPDF_FORMFILLINFO
* param
,
3144 FPDF_BYTESTRING uri
) {
3145 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3146 engine
->client_
->NavigateTo(std::string(uri
), false);
3149 void PDFiumEngine::Form_DoGoToAction(FPDF_FORMFILLINFO
* param
,
3152 float* position_array
,
3153 int size_of_array
) {
3154 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3155 engine
->client_
->ScrollToPage(page_index
);
3158 int PDFiumEngine::Form_Alert(IPDF_JSPLATFORM
* param
,
3159 FPDF_WIDESTRING message
,
3160 FPDF_WIDESTRING title
,
3163 // See fpdfformfill.h for these values.
3166 ALERT_TYPE_OK_CANCEL
,
3168 ALERT_TYPE_YES_NO_CANCEL
3172 ALERT_RESULT_OK
= 1,
3173 ALERT_RESULT_CANCEL
,
3178 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3179 std::string message_str
=
3180 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(message
));
3181 if (type
== ALERT_TYPE_OK
) {
3182 engine
->client_
->Alert(message_str
);
3183 return ALERT_RESULT_OK
;
3186 bool rv
= engine
->client_
->Confirm(message_str
);
3187 if (type
== ALERT_TYPE_OK_CANCEL
)
3188 return rv
? ALERT_RESULT_OK
: ALERT_RESULT_CANCEL
;
3189 return rv
? ALERT_RESULT_YES
: ALERT_RESULT_NO
;
3192 void PDFiumEngine::Form_Beep(IPDF_JSPLATFORM
* param
, int type
) {
3193 // Beeps are annoying, and not possible using javascript, so ignore for now.
3196 int PDFiumEngine::Form_Response(IPDF_JSPLATFORM
* param
,
3197 FPDF_WIDESTRING question
,
3198 FPDF_WIDESTRING title
,
3199 FPDF_WIDESTRING default_response
,
3200 FPDF_WIDESTRING label
,
3204 std::string question_str
= base::UTF16ToUTF8(
3205 reinterpret_cast<const base::char16
*>(question
));
3206 std::string default_str
= base::UTF16ToUTF8(
3207 reinterpret_cast<const base::char16
*>(default_response
));
3209 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3210 std::string rv
= engine
->client_
->Prompt(question_str
, default_str
);
3211 base::string16 rv_16
= base::UTF8ToUTF16(rv
);
3212 int rv_bytes
= rv_16
.size() * sizeof(base::char16
);
3214 int bytes_to_copy
= rv_bytes
< length
? rv_bytes
: length
;
3215 memcpy(response
, rv_16
.c_str(), bytes_to_copy
);
3220 int PDFiumEngine::Form_GetFilePath(IPDF_JSPLATFORM
* param
,
3223 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3224 std::string rv
= engine
->client_
->GetURL();
3225 if (file_path
&& rv
.size() <= static_cast<size_t>(length
))
3226 memcpy(file_path
, rv
.c_str(), rv
.size());
3230 void PDFiumEngine::Form_Mail(IPDF_JSPLATFORM
* param
,
3235 FPDF_WIDESTRING subject
,
3237 FPDF_WIDESTRING bcc
,
3238 FPDF_WIDESTRING message
) {
3239 DCHECK(length
== 0); // Don't handle attachments; no way with mailto.
3240 std::string to_str
=
3241 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(to
));
3242 std::string cc_str
=
3243 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(cc
));
3244 std::string bcc_str
=
3245 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(bcc
));
3246 std::string subject_str
=
3247 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(subject
));
3248 std::string message_str
=
3249 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(message
));
3251 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3252 engine
->client_
->Email(to_str
, cc_str
, bcc_str
, subject_str
, message_str
);
3255 void PDFiumEngine::Form_Print(IPDF_JSPLATFORM
* param
,
3260 FPDF_BOOL shrink_to_fit
,
3261 FPDF_BOOL print_as_image
,
3263 FPDF_BOOL annotations
) {
3264 // No way to pass the extra information to the print dialog using JavaScript.
3265 // Just opening it is fine for now.
3266 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3267 engine
->client_
->Print();
3270 void PDFiumEngine::Form_SubmitForm(IPDF_JSPLATFORM
* param
,
3273 FPDF_WIDESTRING url
) {
3274 std::string url_str
=
3275 base::UTF16ToUTF8(reinterpret_cast<const base::char16
*>(url
));
3276 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3277 engine
->client_
->SubmitForm(url_str
, form_data
, length
);
3280 void PDFiumEngine::Form_GotoPage(IPDF_JSPLATFORM
* param
,
3282 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3283 engine
->client_
->ScrollToPage(page_number
);
3286 int PDFiumEngine::Form_Browse(IPDF_JSPLATFORM
* param
,
3289 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3290 std::string path
= engine
->client_
->ShowFileSelectionDialog();
3291 if (path
.size() + 1 <= static_cast<size_t>(length
))
3292 memcpy(file_path
, &path
[0], path
.size() + 1);
3293 return path
.size() + 1;
3296 FPDF_BOOL
PDFiumEngine::Pause_NeedToPauseNow(IFSDK_PAUSE
* param
) {
3297 PDFiumEngine
* engine
= static_cast<PDFiumEngine
*>(param
);
3298 return (base::Time::Now() - engine
->last_progressive_start_time_
).
3299 InMilliseconds() > engine
->progressive_paint_timeout_
;
3302 ScopedUnsupportedFeature::ScopedUnsupportedFeature(PDFiumEngine
* engine
)
3303 : engine_(engine
), old_engine_(g_engine_for_unsupported
) {
3304 g_engine_for_unsupported
= engine_
;
3307 ScopedUnsupportedFeature::~ScopedUnsupportedFeature() {
3308 g_engine_for_unsupported
= old_engine_
;
3311 PDFEngineExports
* PDFEngineExports::Create() {
3312 return new PDFiumEngineExports
;
3317 int CalculatePosition(FPDF_PAGE page
,
3318 const PDFiumEngineExports::RenderingSettings
& settings
,
3320 int page_width
= static_cast<int>(
3321 FPDF_GetPageWidth(page
) * settings
.dpi_x
/ kPointsPerInch
);
3322 int page_height
= static_cast<int>(
3323 FPDF_GetPageHeight(page
) * settings
.dpi_y
/ kPointsPerInch
);
3325 // Start by assuming that we will draw exactly to the bounds rect
3327 *dest
= settings
.bounds
;
3329 int rotate
= 0; // normal orientation.
3331 // Auto-rotate landscape pages to print correctly.
3332 if (settings
.autorotate
&&
3333 (dest
->width() > dest
->height()) != (page_width
> page_height
)) {
3334 rotate
= 3; // 90 degrees counter-clockwise.
3335 std::swap(page_width
, page_height
);
3338 // See if we need to scale the output
3339 bool scale_to_bounds
= false;
3340 if (settings
.fit_to_bounds
&&
3341 ((page_width
> dest
->width()) || (page_height
> dest
->height()))) {
3342 scale_to_bounds
= true;
3343 } else if (settings
.stretch_to_bounds
&&
3344 ((page_width
< dest
->width()) || (page_height
< dest
->height()))) {
3345 scale_to_bounds
= true;
3348 if (scale_to_bounds
) {
3349 // If we need to maintain aspect ratio, calculate the actual width and
3351 if (settings
.keep_aspect_ratio
) {
3352 double scale_factor_x
= page_width
;
3353 scale_factor_x
/= dest
->width();
3354 double scale_factor_y
= page_height
;
3355 scale_factor_y
/= dest
->height();
3356 if (scale_factor_x
> scale_factor_y
) {
3357 dest
->set_height(page_height
/ scale_factor_x
);
3359 dest
->set_width(page_width
/ scale_factor_y
);
3363 // We are not scaling to bounds. Draw in the actual page size. If the
3364 // actual page size is larger than the bounds, the output will be
3366 dest
->set_width(page_width
);
3367 dest
->set_height(page_height
);
3370 if (settings
.center_in_bounds
) {
3371 pp::Point
offset((settings
.bounds
.width() - dest
->width()) / 2,
3372 (settings
.bounds
.height() - dest
->height()) / 2);
3373 dest
->Offset(offset
);
3381 bool PDFiumEngineExports::RenderPDFPageToDC(const void* pdf_buffer
,
3384 const RenderingSettings
& settings
,
3386 FPDF_DOCUMENT doc
= FPDF_LoadMemDocument(pdf_buffer
, buffer_size
, NULL
);
3389 FPDF_PAGE page
= FPDF_LoadPage(doc
, page_number
);
3391 FPDF_CloseDocument(doc
);
3394 RenderingSettings new_settings
= settings
;
3395 // calculate the page size
3396 if (new_settings
.dpi_x
== -1)
3397 new_settings
.dpi_x
= GetDeviceCaps(dc
, LOGPIXELSX
);
3398 if (new_settings
.dpi_y
== -1)
3399 new_settings
.dpi_y
= GetDeviceCaps(dc
, LOGPIXELSY
);
3402 int rotate
= CalculatePosition(page
, new_settings
, &dest
);
3404 int save_state
= SaveDC(dc
);
3405 // The caller wanted all drawing to happen within the bounds specified.
3406 // Based on scale calculations, our destination rect might be larger
3407 // than the bounds. Set the clip rect to the bounds.
3408 IntersectClipRect(dc
, settings
.bounds
.x(), settings
.bounds
.y(),
3409 settings
.bounds
.x() + settings
.bounds
.width(),
3410 settings
.bounds
.y() + settings
.bounds
.height());
3412 // A temporary hack. PDFs generated by Cairo (used by Chrome OS to generate
3413 // a PDF output from a webpage) result in very large metafiles and the
3414 // rendering using FPDF_RenderPage is incorrect. In this case, render as a
3415 // bitmap. Note that this code does not kick in for PDFs printed from Chrome
3416 // because in that case we create a temp PDF first before printing and this
3417 // temp PDF does not have a creator string that starts with "cairo".
3418 base::string16 creator
;
3419 size_t buffer_bytes
= FPDF_GetMetaText(doc
, "Creator", NULL
, 0);
3420 if (buffer_bytes
> 1) {
3422 doc
, "Creator", WriteInto(&creator
, buffer_bytes
+ 1), buffer_bytes
);
3424 bool use_bitmap
= false;
3425 if (StartsWith(creator
, L
"cairo", false))
3428 // Another temporary hack. Some PDFs seems to render very slowly if
3429 // FPDF_RenderPage is directly used on a printer DC. I suspect it is
3430 // because of the code to talk Postscript directly to the printer if
3431 // the printer supports this. Need to discuss this with PDFium. For now,
3432 // render to a bitmap and then blit the bitmap to the DC if we have been
3433 // supplied a printer DC.
3434 int device_type
= GetDeviceCaps(dc
, TECHNOLOGY
);
3436 (device_type
== DT_RASPRINTER
) || (device_type
== DT_PLOTTER
)) {
3437 FPDF_BITMAP bitmap
= FPDFBitmap_Create(dest
.width(), dest
.height(),
3440 FPDFBitmap_FillRect(bitmap
, 0, 0, dest
.width(), dest
.height(), 0xFFFFFFFF);
3441 FPDF_RenderPageBitmap(
3442 bitmap
, page
, 0, 0, dest
.width(), dest
.height(), rotate
,
3443 FPDF_ANNOT
| FPDF_PRINTING
| FPDF_NO_CATCH
);
3444 int stride
= FPDFBitmap_GetStride(bitmap
);
3446 memset(&bmi
, 0, sizeof(bmi
));
3447 bmi
.bmiHeader
.biSize
= sizeof(BITMAPINFOHEADER
);
3448 bmi
.bmiHeader
.biWidth
= dest
.width();
3449 bmi
.bmiHeader
.biHeight
= -dest
.height(); // top-down image
3450 bmi
.bmiHeader
.biPlanes
= 1;
3451 bmi
.bmiHeader
.biBitCount
= 32;
3452 bmi
.bmiHeader
.biCompression
= BI_RGB
;
3453 bmi
.bmiHeader
.biSizeImage
= stride
* dest
.height();
3454 StretchDIBits(dc
, dest
.x(), dest
.y(), dest
.width(), dest
.height(),
3455 0, 0, dest
.width(), dest
.height(),
3456 FPDFBitmap_GetBuffer(bitmap
), &bmi
, DIB_RGB_COLORS
, SRCCOPY
);
3457 FPDFBitmap_Destroy(bitmap
);
3459 FPDF_RenderPage(dc
, page
, dest
.x(), dest
.y(), dest
.width(), dest
.height(),
3460 rotate
, FPDF_ANNOT
| FPDF_PRINTING
| FPDF_NO_CATCH
);
3462 RestoreDC(dc
, save_state
);
3463 FPDF_ClosePage(page
);
3464 FPDF_CloseDocument(doc
);
3469 bool PDFiumEngineExports::RenderPDFPageToBitmap(
3470 const void* pdf_buffer
,
3471 int pdf_buffer_size
,
3473 const RenderingSettings
& settings
,
3474 void* bitmap_buffer
) {
3475 FPDF_DOCUMENT doc
= FPDF_LoadMemDocument(pdf_buffer
, pdf_buffer_size
, NULL
);
3478 FPDF_PAGE page
= FPDF_LoadPage(doc
, page_number
);
3480 FPDF_CloseDocument(doc
);
3485 int rotate
= CalculatePosition(page
, settings
, &dest
);
3487 FPDF_BITMAP bitmap
=
3488 FPDFBitmap_CreateEx(settings
.bounds
.width(), settings
.bounds
.height(),
3489 FPDFBitmap_BGRA
, bitmap_buffer
,
3490 settings
.bounds
.width() * 4);
3492 FPDFBitmap_FillRect(bitmap
, 0, 0, settings
.bounds
.width(),
3493 settings
.bounds
.height(), 0xFFFFFFFF);
3494 // Shift top-left corner of bounds to (0, 0) if it's not there.
3495 dest
.set_point(dest
.point() - settings
.bounds
.point());
3496 FPDF_RenderPageBitmap(
3497 bitmap
, page
, dest
.x(), dest
.y(), dest
.width(), dest
.height(), rotate
,
3498 FPDF_ANNOT
| FPDF_PRINTING
| FPDF_NO_CATCH
);
3499 FPDFBitmap_Destroy(bitmap
);
3500 FPDF_ClosePage(page
);
3501 FPDF_CloseDocument(doc
);
3505 bool PDFiumEngineExports::GetPDFDocInfo(const void* pdf_buffer
,
3508 double* max_page_width
) {
3509 FPDF_DOCUMENT doc
= FPDF_LoadMemDocument(pdf_buffer
, buffer_size
, NULL
);
3512 int page_count_local
= FPDF_GetPageCount(doc
);
3514 *page_count
= page_count_local
;
3516 if (max_page_width
) {
3517 *max_page_width
= 0;
3518 for (int page_number
= 0; page_number
< page_count_local
; page_number
++) {
3519 double page_width
= 0;
3520 double page_height
= 0;
3521 FPDF_GetPageSizeByIndex(doc
, page_number
, &page_width
, &page_height
);
3522 if (page_width
> *max_page_width
) {
3523 *max_page_width
= page_width
;
3527 FPDF_CloseDocument(doc
);
3531 bool PDFiumEngineExports::GetPDFPageSizeByIndex(
3532 const void* pdf_buffer
,
3533 int pdf_buffer_size
,
3537 FPDF_DOCUMENT doc
= FPDF_LoadMemDocument(pdf_buffer
, pdf_buffer_size
, NULL
);
3540 bool success
= FPDF_GetPageSizeByIndex(doc
, page_number
, width
, height
) != 0;
3541 FPDF_CloseDocument(doc
);
3545 } // namespace chrome_pdf