Hide the "Add new services" menu from Files app when running as dialog.
[chromium-blink-merge.git] / pdf / pdfium / pdfium_engine.cc
blobe580fede6aba69640b283f2395d9c2b5252c2021
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"
7 #include <math.h>
9 #include "base/json/json_writer.h"
10 #include "base/logging.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/numerics/safe_conversions.h"
13 #include "base/stl_util.h"
14 #include "base/strings/string_number_conversions.h"
15 #include "base/strings/string_piece.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "base/values.h"
19 #include "pdf/draw_utils.h"
20 #include "pdf/pdfium/pdfium_api_string_buffer_adapter.h"
21 #include "pdf/pdfium/pdfium_mem_buffer_file_read.h"
22 #include "pdf/pdfium/pdfium_mem_buffer_file_write.h"
23 #include "ppapi/c/pp_errors.h"
24 #include "ppapi/c/pp_input_event.h"
25 #include "ppapi/c/ppb_core.h"
26 #include "ppapi/c/private/ppb_pdf.h"
27 #include "ppapi/cpp/dev/memory_dev.h"
28 #include "ppapi/cpp/input_event.h"
29 #include "ppapi/cpp/instance.h"
30 #include "ppapi/cpp/module.h"
31 #include "ppapi/cpp/private/pdf.h"
32 #include "ppapi/cpp/trusted/browser_font_trusted.h"
33 #include "ppapi/cpp/url_response_info.h"
34 #include "ppapi/cpp/var.h"
35 #include "ppapi/cpp/var_dictionary.h"
36 #include "printing/units.h"
37 #include "third_party/pdfium/public/fpdf_edit.h"
38 #include "third_party/pdfium/public/fpdf_ext.h"
39 #include "third_party/pdfium/public/fpdf_flatten.h"
40 #include "third_party/pdfium/public/fpdf_ppo.h"
41 #include "third_party/pdfium/public/fpdf_save.h"
42 #include "third_party/pdfium/public/fpdf_searchex.h"
43 #include "third_party/pdfium/public/fpdf_sysfontinfo.h"
44 #include "third_party/pdfium/public/fpdf_transformpage.h"
45 #include "ui/events/keycodes/keyboard_codes.h"
47 using printing::ConvertUnit;
48 using printing::ConvertUnitDouble;
49 using printing::kPointsPerInch;
50 using printing::kPixelsPerInch;
52 namespace chrome_pdf {
54 namespace {
56 #define kPageShadowTop 3
57 #define kPageShadowBottom 7
58 #define kPageShadowLeft 5
59 #define kPageShadowRight 5
61 #define kPageSeparatorThickness 4
62 #define kHighlightColorR 153
63 #define kHighlightColorG 193
64 #define kHighlightColorB 218
66 const uint32 kPendingPageColor = 0xFFEEEEEE;
68 #define kFormHighlightColor 0xFFE4DD
69 #define kFormHighlightAlpha 100
71 #define kMaxPasswordTries 3
73 // See Table 3.20 in
74 // http://www.adobe.com/devnet/acrobat/pdfs/pdf_reference_1-7.pdf
75 #define kPDFPermissionPrintLowQualityMask 1 << 2
76 #define kPDFPermissionPrintHighQualityMask 1 << 11
77 #define kPDFPermissionCopyMask 1 << 4
78 #define kPDFPermissionCopyAccessibleMask 1 << 9
80 #define kLoadingTextVerticalOffset 50
82 // The maximum amount of time we'll spend doing a paint before we give back
83 // control of the thread.
84 #define kMaxProgressivePaintTimeMs 50
86 // The maximum amount of time we'll spend doing the first paint. This is less
87 // than the above to keep things smooth if the user is scrolling quickly. We
88 // try painting a little because with accelerated compositing, we get flushes
89 // only every 16 ms. If we were to wait until the next flush to paint the rest
90 // of the pdf, we would never get to draw the pdf and would only draw the
91 // scrollbars. This value is picked to give enough time for gpu related code to
92 // do its thing and still fit within the timelimit for 60Hz. For the
93 // non-composited case, this doesn't make things worse since we're still
94 // painting the scrollbars > 60 Hz.
95 #define kMaxInitialProgressivePaintTimeMs 10
97 struct ClipBox {
98 float left;
99 float right;
100 float top;
101 float bottom;
104 std::vector<uint32_t> GetPageNumbersFromPrintPageNumberRange(
105 const PP_PrintPageNumberRange_Dev* page_ranges,
106 uint32_t page_range_count) {
107 std::vector<uint32_t> page_numbers;
108 for (uint32_t index = 0; index < page_range_count; ++index) {
109 for (uint32_t page_number = page_ranges[index].first_page_number;
110 page_number <= page_ranges[index].last_page_number; ++page_number) {
111 page_numbers.push_back(page_number);
114 return page_numbers;
117 #if defined(OS_LINUX)
119 PP_Instance g_last_instance_id;
121 struct PDFFontSubstitution {
122 const char* pdf_name;
123 const char* face;
124 bool bold;
125 bool italic;
128 PP_BrowserFont_Trusted_Weight WeightToBrowserFontTrustedWeight(int weight) {
129 static_assert(PP_BROWSERFONT_TRUSTED_WEIGHT_100 == 0,
130 "PP_BrowserFont_Trusted_Weight min");
131 static_assert(PP_BROWSERFONT_TRUSTED_WEIGHT_900 == 8,
132 "PP_BrowserFont_Trusted_Weight max");
133 const int kMinimumWeight = 100;
134 const int kMaximumWeight = 900;
135 int normalized_weight =
136 std::min(std::max(weight, kMinimumWeight), kMaximumWeight);
137 normalized_weight = (normalized_weight / 100) - 1;
138 return static_cast<PP_BrowserFont_Trusted_Weight>(normalized_weight);
141 // This list is for CPWL_FontMap::GetDefaultFontByCharset().
142 // We pretend to have these font natively and let the browser (or underlying
143 // fontconfig) to pick the proper font on the system.
144 void EnumFonts(struct _FPDF_SYSFONTINFO* sysfontinfo, void* mapper) {
145 FPDF_AddInstalledFont(mapper, "Arial", FXFONT_DEFAULT_CHARSET);
147 const FPDF_CharsetFontMap* font_map = FPDF_GetDefaultTTFMap();
148 for (; font_map->charset != -1; ++font_map) {
149 FPDF_AddInstalledFont(mapper, font_map->fontname, font_map->charset);
153 const PDFFontSubstitution PDFFontSubstitutions[] = {
154 {"Courier", "Courier New", false, false},
155 {"Courier-Bold", "Courier New", true, false},
156 {"Courier-BoldOblique", "Courier New", true, true},
157 {"Courier-Oblique", "Courier New", false, true},
158 {"Helvetica", "Arial", false, false},
159 {"Helvetica-Bold", "Arial", true, false},
160 {"Helvetica-BoldOblique", "Arial", true, true},
161 {"Helvetica-Oblique", "Arial", false, true},
162 {"Times-Roman", "Times New Roman", false, false},
163 {"Times-Bold", "Times New Roman", true, false},
164 {"Times-BoldItalic", "Times New Roman", true, true},
165 {"Times-Italic", "Times New Roman", false, true},
167 // MS P?(Mincho|Gothic) are the most notable fonts in Japanese PDF files
168 // without embedding the glyphs. Sometimes the font names are encoded
169 // in Japanese Windows's locale (CP932/Shift_JIS) without space.
170 // Most Linux systems don't have the exact font, but for outsourcing
171 // fontconfig to find substitutable font in the system, we pass ASCII
172 // font names to it.
173 {"MS-PGothic", "MS PGothic", false, false},
174 {"MS-Gothic", "MS Gothic", false, false},
175 {"MS-PMincho", "MS PMincho", false, false},
176 {"MS-Mincho", "MS Mincho", false, false},
177 // MS PGothic in Shift_JIS encoding.
178 {"\x82\x6C\x82\x72\x82\x6F\x83\x53\x83\x56\x83\x62\x83\x4E",
179 "MS PGothic", false, false},
180 // MS Gothic in Shift_JIS encoding.
181 {"\x82\x6C\x82\x72\x83\x53\x83\x56\x83\x62\x83\x4E",
182 "MS Gothic", false, false},
183 // MS PMincho in Shift_JIS encoding.
184 {"\x82\x6C\x82\x72\x82\x6F\x96\xBE\x92\xA9",
185 "MS PMincho", false, false},
186 // MS Mincho in Shift_JIS encoding.
187 {"\x82\x6C\x82\x72\x96\xBE\x92\xA9",
188 "MS Mincho", false, false},
191 void* MapFont(struct _FPDF_SYSFONTINFO*, int weight, int italic,
192 int charset, int pitch_family, const char* face, int* exact) {
193 // Do not attempt to map fonts if pepper is not initialized (for privet local
194 // printing).
195 // TODO(noamsml): Real font substitution (http://crbug.com/391978)
196 if (!pp::Module::Get())
197 return NULL;
199 pp::BrowserFontDescription description;
201 // Pretend the system does not have the Symbol font to force a fallback to
202 // the built in Symbol font in CFX_FontMapper::FindSubstFont().
203 if (strcmp(face, "Symbol") == 0)
204 return NULL;
206 if (pitch_family & FXFONT_FF_FIXEDPITCH) {
207 description.set_family(PP_BROWSERFONT_TRUSTED_FAMILY_MONOSPACE);
208 } else if (pitch_family & FXFONT_FF_ROMAN) {
209 description.set_family(PP_BROWSERFONT_TRUSTED_FAMILY_SERIF);
212 // Map from the standard PDF fonts to TrueType font names.
213 size_t i;
214 for (i = 0; i < arraysize(PDFFontSubstitutions); ++i) {
215 if (strcmp(face, PDFFontSubstitutions[i].pdf_name) == 0) {
216 description.set_face(PDFFontSubstitutions[i].face);
217 if (PDFFontSubstitutions[i].bold)
218 description.set_weight(PP_BROWSERFONT_TRUSTED_WEIGHT_BOLD);
219 if (PDFFontSubstitutions[i].italic)
220 description.set_italic(true);
221 break;
225 if (i == arraysize(PDFFontSubstitutions)) {
226 // TODO(kochi): Pass the face in UTF-8. If face is not encoded in UTF-8,
227 // convert to UTF-8 before passing.
228 description.set_face(face);
230 description.set_weight(WeightToBrowserFontTrustedWeight(weight));
231 description.set_italic(italic > 0);
234 if (!pp::PDF::IsAvailable()) {
235 NOTREACHED();
236 return NULL;
239 PP_Resource font_resource = pp::PDF::GetFontFileWithFallback(
240 pp::InstanceHandle(g_last_instance_id),
241 &description.pp_font_description(),
242 static_cast<PP_PrivateFontCharset>(charset));
243 long res_id = font_resource;
244 return reinterpret_cast<void*>(res_id);
247 unsigned long GetFontData(struct _FPDF_SYSFONTINFO*, void* font_id,
248 unsigned int table, unsigned char* buffer,
249 unsigned long buf_size) {
250 if (!pp::PDF::IsAvailable()) {
251 NOTREACHED();
252 return 0;
255 uint32_t size = buf_size;
256 long res_id = reinterpret_cast<long>(font_id);
257 if (!pp::PDF::GetFontTableForPrivateFontFile(res_id, table, buffer, &size))
258 return 0;
259 return size;
262 void DeleteFont(struct _FPDF_SYSFONTINFO*, void* font_id) {
263 long res_id = reinterpret_cast<long>(font_id);
264 pp::Module::Get()->core()->ReleaseResource(res_id);
267 FPDF_SYSFONTINFO g_font_info = {
270 EnumFonts,
271 MapFont,
273 GetFontData,
276 DeleteFont
278 #endif // defined(OS_LINUX)
280 PDFiumEngine* g_engine_for_unsupported;
282 void Unsupported_Handler(UNSUPPORT_INFO*, int type) {
283 if (!g_engine_for_unsupported) {
284 NOTREACHED();
285 return;
288 g_engine_for_unsupported->UnsupportedFeature(type);
291 UNSUPPORT_INFO g_unsuppored_info = {
293 Unsupported_Handler
296 // Set the destination page size and content area in points based on source
297 // page rotation and orientation.
299 // |rotated| True if source page is rotated 90 degree or 270 degree.
300 // |is_src_page_landscape| is true if the source page orientation is landscape.
301 // |page_size| has the actual destination page size in points.
302 // |content_rect| has the actual destination page printable area values in
303 // points.
304 void SetPageSizeAndContentRect(bool rotated,
305 bool is_src_page_landscape,
306 pp::Size* page_size,
307 pp::Rect* content_rect) {
308 bool is_dst_page_landscape = page_size->width() > page_size->height();
309 bool page_orientation_mismatched = is_src_page_landscape !=
310 is_dst_page_landscape;
311 bool rotate_dst_page = rotated ^ page_orientation_mismatched;
312 if (rotate_dst_page) {
313 page_size->SetSize(page_size->height(), page_size->width());
314 content_rect->SetRect(content_rect->y(), content_rect->x(),
315 content_rect->height(), content_rect->width());
319 // Calculate the scale factor between |content_rect| and a page of size
320 // |src_width| x |src_height|.
322 // |scale_to_fit| is true, if we need to calculate the scale factor.
323 // |content_rect| specifies the printable area of the destination page, with
324 // origin at left-bottom. Values are in points.
325 // |src_width| specifies the source page width in points.
326 // |src_height| specifies the source page height in points.
327 // |rotated| True if source page is rotated 90 degree or 270 degree.
328 double CalculateScaleFactor(bool scale_to_fit,
329 const pp::Rect& content_rect,
330 double src_width, double src_height, bool rotated) {
331 if (!scale_to_fit || src_width == 0 || src_height == 0)
332 return 1.0;
334 double actual_source_page_width = rotated ? src_height : src_width;
335 double actual_source_page_height = rotated ? src_width : src_height;
336 double ratio_x = static_cast<double>(content_rect.width()) /
337 actual_source_page_width;
338 double ratio_y = static_cast<double>(content_rect.height()) /
339 actual_source_page_height;
340 return std::min(ratio_x, ratio_y);
343 // Compute source clip box boundaries based on the crop box / media box of
344 // source page and scale factor.
346 // |page| Handle to the source page. Returned by FPDF_LoadPage function.
347 // |scale_factor| specifies the scale factor that should be applied to source
348 // clip box boundaries.
349 // |rotated| True if source page is rotated 90 degree or 270 degree.
350 // |clip_box| out param to hold the computed source clip box values.
351 void CalculateClipBoxBoundary(FPDF_PAGE page, double scale_factor, bool rotated,
352 ClipBox* clip_box) {
353 if (!FPDFPage_GetCropBox(page, &clip_box->left, &clip_box->bottom,
354 &clip_box->right, &clip_box->top)) {
355 if (!FPDFPage_GetMediaBox(page, &clip_box->left, &clip_box->bottom,
356 &clip_box->right, &clip_box->top)) {
357 // Make the default size to be letter size (8.5" X 11"). We are just
358 // following the PDFium way of handling these corner cases. PDFium always
359 // consider US-Letter as the default page size.
360 float paper_width = 612;
361 float paper_height = 792;
362 clip_box->left = 0;
363 clip_box->bottom = 0;
364 clip_box->right = rotated ? paper_height : paper_width;
365 clip_box->top = rotated ? paper_width : paper_height;
368 clip_box->left *= scale_factor;
369 clip_box->right *= scale_factor;
370 clip_box->bottom *= scale_factor;
371 clip_box->top *= scale_factor;
374 // Calculate the clip box translation offset for a page that does need to be
375 // scaled. All parameters are in points.
377 // |content_rect| specifies the printable area of the destination page, with
378 // origin at left-bottom.
379 // |source_clip_box| specifies the source clip box positions, relative to
380 // origin at left-bottom.
381 // |offset_x| and |offset_y| will contain the final translation offsets for the
382 // source clip box, relative to origin at left-bottom.
383 void CalculateScaledClipBoxOffset(const pp::Rect& content_rect,
384 const ClipBox& source_clip_box,
385 double* offset_x, double* offset_y) {
386 const float clip_box_width = source_clip_box.right - source_clip_box.left;
387 const float clip_box_height = source_clip_box.top - source_clip_box.bottom;
389 // Center the intended clip region to real clip region.
390 *offset_x = (content_rect.width() - clip_box_width) / 2 + content_rect.x() -
391 source_clip_box.left;
392 *offset_y = (content_rect.height() - clip_box_height) / 2 + content_rect.y() -
393 source_clip_box.bottom;
396 // Calculate the clip box offset for a page that does not need to be scaled.
397 // All parameters are in points.
399 // |content_rect| specifies the printable area of the destination page, with
400 // origin at left-bottom.
401 // |rotation| specifies the source page rotation values which are N / 90
402 // degrees.
403 // |page_width| specifies the screen destination page width.
404 // |page_height| specifies the screen destination page height.
405 // |source_clip_box| specifies the source clip box positions, relative to origin
406 // 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 CalculateNonScaledClipBoxOffset(const pp::Rect& content_rect, int rotation,
410 int page_width, int page_height,
411 const ClipBox& source_clip_box,
412 double* offset_x, double* offset_y) {
413 // Align the intended clip region to left-top corner of real clip region.
414 switch (rotation) {
415 case 0:
416 *offset_x = -1 * source_clip_box.left;
417 *offset_y = page_height - source_clip_box.top;
418 break;
419 case 1:
420 *offset_x = 0;
421 *offset_y = -1 * source_clip_box.bottom;
422 break;
423 case 2:
424 *offset_x = page_width - source_clip_box.right;
425 *offset_y = 0;
426 break;
427 case 3:
428 *offset_x = page_height - source_clip_box.right;
429 *offset_y = page_width - source_clip_box.top;
430 break;
431 default:
432 NOTREACHED();
433 break;
437 // This formats a string with special 0xfffe end-of-line hyphens the same way
438 // as Adobe Reader. When a hyphen is encountered, the next non-CR/LF whitespace
439 // becomes CR+LF and the hyphen is erased. If there is no whitespace between
440 // two hyphens, the latter hyphen is erased and ignored.
441 void FormatStringWithHyphens(base::string16* text) {
442 // First pass marks all the hyphen positions.
443 struct HyphenPosition {
444 HyphenPosition() : position(0), next_whitespace_position(0) {}
445 size_t position;
446 size_t next_whitespace_position; // 0 for none
448 std::vector<HyphenPosition> hyphen_positions;
449 HyphenPosition current_hyphen_position;
450 bool current_hyphen_position_is_valid = false;
451 const base::char16 kPdfiumHyphenEOL = 0xfffe;
453 for (size_t i = 0; i < text->size(); ++i) {
454 const base::char16& current_char = (*text)[i];
455 if (current_char == kPdfiumHyphenEOL) {
456 if (current_hyphen_position_is_valid)
457 hyphen_positions.push_back(current_hyphen_position);
458 current_hyphen_position = HyphenPosition();
459 current_hyphen_position.position = i;
460 current_hyphen_position_is_valid = true;
461 } else if (IsWhitespace(current_char)) {
462 if (current_hyphen_position_is_valid) {
463 if (current_char != L'\r' && current_char != L'\n')
464 current_hyphen_position.next_whitespace_position = i;
465 hyphen_positions.push_back(current_hyphen_position);
466 current_hyphen_position_is_valid = false;
470 if (current_hyphen_position_is_valid)
471 hyphen_positions.push_back(current_hyphen_position);
473 // With all the hyphen positions, do the search and replace.
474 while (!hyphen_positions.empty()) {
475 static const base::char16 kCr[] = {L'\r', L'\0'};
476 const HyphenPosition& position = hyphen_positions.back();
477 if (position.next_whitespace_position != 0) {
478 (*text)[position.next_whitespace_position] = L'\n';
479 text->insert(position.next_whitespace_position, kCr);
481 text->erase(position.position, 1);
482 hyphen_positions.pop_back();
485 // Adobe Reader also get rid of trailing spaces right before a CRLF.
486 static const base::char16 kSpaceCrCn[] = {L' ', L'\r', L'\n', L'\0'};
487 static const base::char16 kCrCn[] = {L'\r', L'\n', L'\0'};
488 ReplaceSubstringsAfterOffset(text, 0, kSpaceCrCn, kCrCn);
491 // Replace CR/LF with just LF on POSIX.
492 void FormatStringForOS(base::string16* text) {
493 #if defined(OS_POSIX)
494 static const base::char16 kCr[] = {L'\r', L'\0'};
495 static const base::char16 kBlank[] = {L'\0'};
496 base::ReplaceChars(*text, kCr, kBlank, text);
497 #elif defined(OS_WIN)
498 // Do nothing
499 #else
500 NOTIMPLEMENTED();
501 #endif
504 // Returns a VarDictionary (representing a bookmark), which in turn contains
505 // child VarDictionaries (representing the child bookmarks).
506 // If NULL is passed in as the bookmark then we traverse from the "root".
507 // Note that the "root" bookmark contains no useful information.
508 pp::VarDictionary TraverseBookmarks(FPDF_DOCUMENT doc, FPDF_BOOKMARK bookmark) {
509 pp::VarDictionary dict;
510 base::string16 title;
511 unsigned long buffer_size = FPDFBookmark_GetTitle(bookmark, NULL, 0);
512 size_t title_length = base::checked_cast<size_t>(buffer_size) /
513 sizeof(base::string16::value_type);
514 if (title_length > 0) {
515 PDFiumAPIStringBufferAdapter<base::string16> api_string_adapter(
516 &title, title_length, true);
517 void* data = api_string_adapter.GetData();
518 FPDFBookmark_GetTitle(bookmark, data, buffer_size);
519 api_string_adapter.Close(title_length);
521 dict.Set(pp::Var("title"), pp::Var(base::UTF16ToUTF8(title)));
523 FPDF_DEST dest = FPDFBookmark_GetDest(doc, bookmark);
524 // Some bookmarks don't have a page to select.
525 if (dest) {
526 int page_index = FPDFDest_GetPageIndex(doc, dest);
527 dict.Set(pp::Var("page"), pp::Var(page_index));
530 pp::VarArray children;
531 int child_index = 0;
532 for (FPDF_BOOKMARK child_bookmark = FPDFBookmark_GetFirstChild(doc, bookmark);
533 child_bookmark != NULL;
534 child_bookmark = FPDFBookmark_GetNextSibling(doc, child_bookmark)) {
535 children.Set(child_index, TraverseBookmarks(doc, child_bookmark));
536 child_index++;
538 dict.Set(pp::Var("children"), children);
539 return dict;
542 } // namespace
544 bool InitializeSDK() {
545 FPDF_InitLibrary();
547 #if defined(OS_LINUX)
548 // Font loading doesn't work in the renderer sandbox in Linux.
549 FPDF_SetSystemFontInfo(&g_font_info);
550 #endif
552 FSDK_SetUnSpObjProcessHandler(&g_unsuppored_info);
554 return true;
557 void ShutdownSDK() {
558 FPDF_DestroyLibrary();
561 PDFEngine* PDFEngine::Create(PDFEngine::Client* client) {
562 return new PDFiumEngine(client);
565 PDFiumEngine::PDFiumEngine(PDFEngine::Client* client)
566 : client_(client),
567 current_zoom_(1.0),
568 current_rotation_(0),
569 doc_loader_(this),
570 password_tries_remaining_(0),
571 doc_(NULL),
572 form_(NULL),
573 defer_page_unload_(false),
574 selecting_(false),
575 mouse_down_state_(PDFiumPage::NONSELECTABLE_AREA,
576 PDFiumPage::LinkTarget()),
577 next_page_to_search_(-1),
578 last_page_to_search_(-1),
579 last_character_index_to_search_(-1),
580 permissions_(0),
581 fpdf_availability_(NULL),
582 next_timer_id_(0),
583 last_page_mouse_down_(-1),
584 first_visible_page_(-1),
585 most_visible_page_(-1),
586 called_do_document_action_(false),
587 render_grayscale_(false),
588 progressive_paint_timeout_(0),
589 getting_password_(false) {
590 find_factory_.Initialize(this);
591 password_factory_.Initialize(this);
593 file_access_.m_FileLen = 0;
594 file_access_.m_GetBlock = &GetBlock;
595 file_access_.m_Param = &doc_loader_;
597 file_availability_.version = 1;
598 file_availability_.IsDataAvail = &IsDataAvail;
599 file_availability_.loader = &doc_loader_;
601 download_hints_.version = 1;
602 download_hints_.AddSegment = &AddSegment;
603 download_hints_.loader = &doc_loader_;
605 // Initialize FPDF_FORMFILLINFO member variables. Deriving from this struct
606 // allows the static callbacks to be able to cast the FPDF_FORMFILLINFO in
607 // callbacks to ourself instead of maintaining a map of them to
608 // PDFiumEngine.
609 FPDF_FORMFILLINFO::version = 1;
610 FPDF_FORMFILLINFO::m_pJsPlatform = this;
611 FPDF_FORMFILLINFO::Release = NULL;
612 FPDF_FORMFILLINFO::FFI_Invalidate = Form_Invalidate;
613 FPDF_FORMFILLINFO::FFI_OutputSelectedRect = Form_OutputSelectedRect;
614 FPDF_FORMFILLINFO::FFI_SetCursor = Form_SetCursor;
615 FPDF_FORMFILLINFO::FFI_SetTimer = Form_SetTimer;
616 FPDF_FORMFILLINFO::FFI_KillTimer = Form_KillTimer;
617 FPDF_FORMFILLINFO::FFI_GetLocalTime = Form_GetLocalTime;
618 FPDF_FORMFILLINFO::FFI_OnChange = Form_OnChange;
619 FPDF_FORMFILLINFO::FFI_GetPage = Form_GetPage;
620 FPDF_FORMFILLINFO::FFI_GetCurrentPage = Form_GetCurrentPage;
621 FPDF_FORMFILLINFO::FFI_GetRotation = Form_GetRotation;
622 FPDF_FORMFILLINFO::FFI_ExecuteNamedAction = Form_ExecuteNamedAction;
623 FPDF_FORMFILLINFO::FFI_SetTextFieldFocus = Form_SetTextFieldFocus;
624 FPDF_FORMFILLINFO::FFI_DoURIAction = Form_DoURIAction;
625 FPDF_FORMFILLINFO::FFI_DoGoToAction = Form_DoGoToAction;
626 #ifdef PDF_USE_XFA
627 FPDF_FORMFILLINFO::version = 2;
628 FPDF_FORMFILLINFO::FFI_EmailTo = Form_EmailTo;
629 FPDF_FORMFILLINFO::FFI_DisplayCaret = Form_DisplayCaret;
630 FPDF_FORMFILLINFO::FFI_SetCurrentPage = Form_SetCurrentPage;
631 FPDF_FORMFILLINFO::FFI_GetCurrentPageIndex = Form_GetCurrentPageIndex;
632 FPDF_FORMFILLINFO::FFI_GetPageViewRect = Form_GetPageViewRect;
633 FPDF_FORMFILLINFO::FFI_GetPlatform = Form_GetPlatform;
634 FPDF_FORMFILLINFO::FFI_PopupMenu = Form_PopupMenu;
635 FPDF_FORMFILLINFO::FFI_PostRequestURL = Form_PostRequestURL;
636 FPDF_FORMFILLINFO::FFI_PutRequestURL = Form_PutRequestURL;
637 FPDF_FORMFILLINFO::FFI_UploadTo = Form_UploadTo;
638 FPDF_FORMFILLINFO::FFI_DownloadFromURL = Form_DownloadFromURL;
639 FPDF_FORMFILLINFO::FFI_OpenFile = Form_OpenFile;
640 FPDF_FORMFILLINFO::FFI_GotoURL = Form_GotoURL;
641 FPDF_FORMFILLINFO::FFI_GetLanguage = Form_GetLanguage;
642 #endif // PDF_USE_XFA
643 IPDF_JSPLATFORM::version = 1;
644 IPDF_JSPLATFORM::app_alert = Form_Alert;
645 IPDF_JSPLATFORM::app_beep = Form_Beep;
646 IPDF_JSPLATFORM::app_response = Form_Response;
647 IPDF_JSPLATFORM::Doc_getFilePath = Form_GetFilePath;
648 IPDF_JSPLATFORM::Doc_mail = Form_Mail;
649 IPDF_JSPLATFORM::Doc_print = Form_Print;
650 IPDF_JSPLATFORM::Doc_submitForm = Form_SubmitForm;
651 IPDF_JSPLATFORM::Doc_gotoPage = Form_GotoPage;
652 IPDF_JSPLATFORM::Field_browse = Form_Browse;
654 IFSDK_PAUSE::version = 1;
655 IFSDK_PAUSE::user = NULL;
656 IFSDK_PAUSE::NeedToPauseNow = Pause_NeedToPauseNow;
659 PDFiumEngine::~PDFiumEngine() {
660 for (size_t i = 0; i < pages_.size(); ++i)
661 pages_[i]->Unload();
663 if (doc_) {
664 if (form_) {
665 FORM_DoDocumentAAction(form_, FPDFDOC_AACTION_WC);
667 FPDF_CloseDocument(doc_);
668 if (form_) {
669 FPDFDOC_ExitFormFillEnvironment(form_);
673 if (fpdf_availability_)
674 FPDFAvail_Destroy(fpdf_availability_);
676 STLDeleteElements(&pages_);
679 #ifdef PDF_USE_XFA
681 // This is just for testing, needs to be removed later
682 #if defined(WIN32)
683 #define XFA_TESTFILE(filename) "E:/"#filename
684 #else
685 #define XFA_TESTFILE(filename) "/home/"#filename
686 #endif
688 struct FPDF_FILE {
689 FPDF_FILEHANDLER file_handler;
690 FILE* file;
693 void Sample_Release(FPDF_LPVOID client_data) {
694 if (!client_data)
695 return;
696 FPDF_FILE* file_wrapper = (FPDF_FILE*)client_data;
697 fclose(file_wrapper->file);
698 delete file_wrapper;
701 FPDF_DWORD Sample_GetSize(FPDF_LPVOID client_data) {
702 if (!client_data)
703 return 0;
704 FPDF_FILE* file_wrapper = (FPDF_FILE*)client_data;
705 long cur_pos = ftell(file_wrapper->file);
706 if (cur_pos == -1)
707 return 0;
708 if (fseek(file_wrapper->file, 0, SEEK_END))
709 return 0;
710 long size = ftell(file_wrapper->file);
711 fseek(file_wrapper->file, cur_pos, SEEK_SET);
712 return (FPDF_DWORD)size;
715 FPDF_RESULT Sample_ReadBlock(FPDF_LPVOID client_data,
716 FPDF_DWORD offset,
717 FPDF_LPVOID buffer,
718 FPDF_DWORD size) {
719 if (!client_data)
720 return -1;
721 FPDF_FILE* file_wrapper = (FPDF_FILE*)client_data;
722 if (fseek(file_wrapper->file, (long)offset, SEEK_SET))
723 return -1;
724 size_t read_size = fread(buffer, 1, size, file_wrapper->file);
725 return read_size == size ? 0 : -1;
728 FPDF_RESULT Sample_WriteBlock(FPDF_LPVOID client_data,
729 FPDF_DWORD offset,
730 FPDF_LPCVOID buffer,
731 FPDF_DWORD size) {
732 if (!client_data)
733 return -1;
734 FPDF_FILE* file_wrapper = (FPDF_FILE*)client_data;
735 if (fseek(file_wrapper->file, (long)offset, SEEK_SET))
736 return -1;
737 // Write data
738 size_t write_size = fwrite(buffer, 1, size, file_wrapper->file);
739 return write_size == size ? 0 : -1;
742 FPDF_RESULT Sample_Flush(FPDF_LPVOID client_data) {
743 if (!client_data)
744 return -1;
745 // Flush file
746 fflush(((FPDF_FILE*)client_data)->file);
747 return 0;
750 FPDF_RESULT Sample_Truncate(FPDF_LPVOID client_data, FPDF_DWORD size) {
751 return 0;
754 void PDFiumEngine::Form_EmailTo(FPDF_FORMFILLINFO* param,
755 FPDF_FILEHANDLER* file_handler,
756 FPDF_WIDESTRING to,
757 FPDF_WIDESTRING subject,
758 FPDF_WIDESTRING cc,
759 FPDF_WIDESTRING bcc,
760 FPDF_WIDESTRING message) {
761 std::string to_str =
762 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(to));
763 std::string subject_str =
764 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(subject));
765 std::string cc_str =
766 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(cc));
767 std::string bcc_str =
768 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(bcc));
769 std::string message_str =
770 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(message));
772 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
773 engine->client_->Email(to_str, cc_str, bcc_str, subject_str, message_str);
776 void PDFiumEngine::Form_DisplayCaret(FPDF_FORMFILLINFO* param,
777 FPDF_PAGE page,
778 FPDF_BOOL visible,
779 double left,
780 double top,
781 double right,
782 double bottom) {
783 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
784 engine->client_->UpdateCursor(PP_CURSORTYPE_IBEAM);
785 std::vector<pp::Rect> tickmarks;
786 pp::Rect rect(left, top, right, bottom);
787 tickmarks.push_back(rect);
788 engine->client_->UpdateTickMarks(tickmarks);
791 void PDFiumEngine::Form_SetCurrentPage(FPDF_FORMFILLINFO* param,
792 FPDF_DOCUMENT document,
793 int page) {
794 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
795 pp::Rect page_view_rect = engine->GetPageContentsRect(page);
796 engine->ScrolledToYPosition(page_view_rect.height());
797 pp::Point pos(1, page_view_rect.height());
798 engine->SetScrollPosition(pos);
801 int PDFiumEngine::Form_GetCurrentPageIndex(FPDF_FORMFILLINFO* param,
802 FPDF_DOCUMENT document) {
803 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
804 return engine->GetMostVisiblePage();
807 void PDFiumEngine::Form_GetPageViewRect(FPDF_FORMFILLINFO* param,
808 FPDF_PAGE page,
809 double* left,
810 double* top,
811 double* right,
812 double* bottom) {
813 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
814 int page_index = engine->GetMostVisiblePage();
815 pp::Rect page_view_rect = engine->GetPageContentsRect(page_index);
817 *left = page_view_rect.x();
818 *right = page_view_rect.right();
819 *top = page_view_rect.y();
820 *bottom = page_view_rect.bottom();
823 int PDFiumEngine::Form_GetPlatform(FPDF_FORMFILLINFO* param,
824 void* platform,
825 int length) {
826 int platform_flag = -1;
828 #if defined(WIN32)
829 platform_flag = 0;
830 #elif defined(__linux__)
831 platform_flag = 1;
832 #else
833 platform_flag = 2;
834 #endif
836 std::string javascript = "alert(\"Platform:"
837 + base::DoubleToString(platform_flag)
838 + "\")";
840 return platform_flag;
843 FPDF_BOOL PDFiumEngine::Form_PopupMenu(FPDF_FORMFILLINFO* param,
844 FPDF_PAGE page,
845 FPDF_WIDGET widget,
846 int menu_flag,
847 float x,
848 float y) {
849 return false;
852 FPDF_BOOL PDFiumEngine::Form_PostRequestURL(FPDF_FORMFILLINFO* param,
853 FPDF_WIDESTRING url,
854 FPDF_WIDESTRING data,
855 FPDF_WIDESTRING content_type,
856 FPDF_WIDESTRING encode,
857 FPDF_WIDESTRING header,
858 FPDF_BSTR* response) {
859 std::string url_str =
860 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(url));
861 std::string data_str =
862 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(data));
863 std::string content_type_str =
864 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(content_type));
865 std::string encode_str =
866 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(encode));
867 std::string header_str =
868 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(header));
870 std::string javascript = "alert(\"Post:"
871 + url_str + "," + data_str + "," + content_type_str + ","
872 + encode_str + "," + header_str
873 + "\")";
874 return true;
877 FPDF_BOOL PDFiumEngine::Form_PutRequestURL(FPDF_FORMFILLINFO* param,
878 FPDF_WIDESTRING url,
879 FPDF_WIDESTRING data,
880 FPDF_WIDESTRING encode) {
881 std::string url_str =
882 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(url));
883 std::string data_str =
884 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(data));
885 std::string encode_str =
886 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(encode));
888 std::string javascript = "alert(\"Put:"
889 + url_str + "," + data_str + "," + encode_str
890 + "\")";
892 return true;
895 void PDFiumEngine::Form_UploadTo(FPDF_FORMFILLINFO* param,
896 FPDF_FILEHANDLER* file_handle,
897 int file_flag,
898 FPDF_WIDESTRING to) {
899 std::string to_str =
900 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(to));
901 // TODO: needs the full implementation of form uploading
904 FPDF_LPFILEHANDLER PDFiumEngine::Form_DownloadFromURL(FPDF_FORMFILLINFO* param,
905 FPDF_WIDESTRING url) {
906 std::string url_str =
907 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(url));
909 // Now should get data from url.
910 // For testing purpose, use data read from file
911 // TODO: needs the full implementation here
912 FILE* file = fopen(XFA_TESTFILE("downloadtest.tem"), "w");
914 FPDF_FILE* file_wrapper = new FPDF_FILE;
915 file_wrapper->file = file;
916 file_wrapper->file_handler.clientData = file_wrapper;
917 file_wrapper->file_handler.Flush = Sample_Flush;
918 file_wrapper->file_handler.GetSize = Sample_GetSize;
919 file_wrapper->file_handler.ReadBlock = Sample_ReadBlock;
920 file_wrapper->file_handler.Release = Sample_Release;
921 file_wrapper->file_handler.Truncate = Sample_Truncate;
922 file_wrapper->file_handler.WriteBlock = Sample_WriteBlock;
924 return &file_wrapper->file_handler;
927 FPDF_FILEHANDLER* PDFiumEngine::Form_OpenFile(FPDF_FORMFILLINFO* param,
928 int file_flag,
929 FPDF_WIDESTRING url,
930 const char* mode) {
931 std::string url_str = "NULL";
932 if (url != NULL) {
933 url_str =
934 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(url));
936 // TODO: need to implement open file from the url
937 // Use a file path for the ease of testing
938 FILE* file = fopen(XFA_TESTFILE("tem.txt"), mode);
939 FPDF_FILE* file_wrapper = new FPDF_FILE;
940 file_wrapper->file = file;
941 file_wrapper->file_handler.clientData = file_wrapper;
942 file_wrapper->file_handler.Flush = Sample_Flush;
943 file_wrapper->file_handler.GetSize = Sample_GetSize;
944 file_wrapper->file_handler.ReadBlock = Sample_ReadBlock;
945 file_wrapper->file_handler.Release = Sample_Release;
946 file_wrapper->file_handler.Truncate = Sample_Truncate;
947 file_wrapper->file_handler.WriteBlock = Sample_WriteBlock;
948 return &file_wrapper->file_handler;
951 void PDFiumEngine::Form_GotoURL(FPDF_FORMFILLINFO* param,
952 FPDF_DOCUMENT document,
953 FPDF_WIDESTRING url) {
954 std::string url_str =
955 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(url));
956 // TODO: needs to implement GOTO URL action
959 int PDFiumEngine::Form_GetLanguage(FPDF_FORMFILLINFO* param,
960 void* language,
961 int length) {
962 return 0;
965 #endif // PDF_USE_XFA
967 int PDFiumEngine::GetBlock(void* param, unsigned long position,
968 unsigned char* buffer, unsigned long size) {
969 DocumentLoader* loader = static_cast<DocumentLoader*>(param);
970 return loader->GetBlock(position, size, buffer);
973 bool PDFiumEngine::IsDataAvail(FX_FILEAVAIL* param,
974 size_t offset, size_t size) {
975 PDFiumEngine::FileAvail* file_avail =
976 static_cast<PDFiumEngine::FileAvail*>(param);
977 return file_avail->loader->IsDataAvailable(offset, size);
980 void PDFiumEngine::AddSegment(FX_DOWNLOADHINTS* param,
981 size_t offset, size_t size) {
982 PDFiumEngine::DownloadHints* download_hints =
983 static_cast<PDFiumEngine::DownloadHints*>(param);
984 return download_hints->loader->RequestData(offset, size);
987 bool PDFiumEngine::New(const char* url) {
988 url_ = url;
989 headers_ = std::string();
990 return true;
993 bool PDFiumEngine::New(const char* url,
994 const char* headers) {
995 url_ = url;
996 if (!headers)
997 headers_ = std::string();
998 else
999 headers_ = headers;
1000 return true;
1003 void PDFiumEngine::PageOffsetUpdated(const pp::Point& page_offset) {
1004 page_offset_ = page_offset;
1007 void PDFiumEngine::PluginSizeUpdated(const pp::Size& size) {
1008 CancelPaints();
1010 plugin_size_ = size;
1011 CalculateVisiblePages();
1014 void PDFiumEngine::ScrolledToXPosition(int position) {
1015 CancelPaints();
1017 int old_x = position_.x();
1018 position_.set_x(position);
1019 CalculateVisiblePages();
1020 client_->Scroll(pp::Point(old_x - position, 0));
1023 void PDFiumEngine::ScrolledToYPosition(int position) {
1024 CancelPaints();
1026 int old_y = position_.y();
1027 position_.set_y(position);
1028 CalculateVisiblePages();
1029 client_->Scroll(pp::Point(0, old_y - position));
1032 void PDFiumEngine::PrePaint() {
1033 for (size_t i = 0; i < progressive_paints_.size(); ++i)
1034 progressive_paints_[i].painted_ = false;
1037 void PDFiumEngine::Paint(const pp::Rect& rect,
1038 pp::ImageData* image_data,
1039 std::vector<pp::Rect>* ready,
1040 std::vector<pp::Rect>* pending) {
1041 DCHECK(image_data);
1042 DCHECK(ready);
1043 DCHECK(pending);
1045 pp::Rect leftover = rect;
1046 for (size_t i = 0; i < visible_pages_.size(); ++i) {
1047 int index = visible_pages_[i];
1048 pp::Rect page_rect = pages_[index]->rect();
1049 // Convert the current page's rectangle to screen rectangle. We do this
1050 // instead of the reverse (converting the dirty rectangle from screen to
1051 // page coordinates) because then we'd have to convert back to screen
1052 // coordinates, and the rounding errors sometime leave pixels dirty or even
1053 // move the text up or down a pixel when zoomed.
1054 pp::Rect page_rect_in_screen = GetPageScreenRect(index);
1055 pp::Rect dirty_in_screen = page_rect_in_screen.Intersect(leftover);
1056 if (dirty_in_screen.IsEmpty())
1057 continue;
1059 leftover = leftover.Subtract(dirty_in_screen);
1061 if (pages_[index]->available()) {
1062 int progressive = GetProgressiveIndex(index);
1063 if (progressive != -1) {
1064 DCHECK_GE(progressive, 0);
1065 DCHECK_LT(static_cast<size_t>(progressive), progressive_paints_.size());
1066 if (progressive_paints_[progressive].rect != dirty_in_screen) {
1067 // The PDFium code can only handle one progressive paint at a time, so
1068 // queue this up. Previously we used to merge the rects when this
1069 // happened, but it made scrolling up on complex PDFs very slow since
1070 // there would be a damaged rect at the top (from scroll) and at the
1071 // bottom (from toolbar).
1072 pending->push_back(dirty_in_screen);
1073 continue;
1077 if (progressive == -1) {
1078 progressive = StartPaint(index, dirty_in_screen);
1079 progressive_paint_timeout_ = kMaxInitialProgressivePaintTimeMs;
1080 } else {
1081 progressive_paint_timeout_ = kMaxProgressivePaintTimeMs;
1084 progressive_paints_[progressive].painted_ = true;
1085 if (ContinuePaint(progressive, image_data)) {
1086 FinishPaint(progressive, image_data);
1087 ready->push_back(dirty_in_screen);
1088 } else {
1089 pending->push_back(dirty_in_screen);
1091 } else {
1092 PaintUnavailablePage(index, dirty_in_screen, image_data);
1093 ready->push_back(dirty_in_screen);
1098 void PDFiumEngine::PostPaint() {
1099 for (size_t i = 0; i < progressive_paints_.size(); ++i) {
1100 if (progressive_paints_[i].painted_)
1101 continue;
1103 // This rectangle must have been merged with another one, that's why we
1104 // weren't asked to paint it. Remove it or otherwise we'll never finish
1105 // painting.
1106 FPDF_RenderPage_Close(
1107 pages_[progressive_paints_[i].page_index]->GetPage());
1108 FPDFBitmap_Destroy(progressive_paints_[i].bitmap);
1109 progressive_paints_.erase(progressive_paints_.begin() + i);
1110 --i;
1114 bool PDFiumEngine::HandleDocumentLoad(const pp::URLLoader& loader) {
1115 password_tries_remaining_ = kMaxPasswordTries;
1116 return doc_loader_.Init(loader, url_, headers_);
1119 pp::Instance* PDFiumEngine::GetPluginInstance() {
1120 return client_->GetPluginInstance();
1123 pp::URLLoader PDFiumEngine::CreateURLLoader() {
1124 return client_->CreateURLLoader();
1127 void PDFiumEngine::AppendPage(PDFEngine* engine, int index) {
1128 // Unload and delete the blank page before appending.
1129 pages_[index]->Unload();
1130 pages_[index]->set_calculated_links(false);
1131 pp::Size curr_page_size = GetPageSize(index);
1132 FPDFPage_Delete(doc_, index);
1133 FPDF_ImportPages(doc_,
1134 static_cast<PDFiumEngine*>(engine)->doc(),
1135 "1",
1136 index);
1137 pp::Size new_page_size = GetPageSize(index);
1138 if (curr_page_size != new_page_size)
1139 LoadPageInfo(true);
1140 client_->Invalidate(GetPageScreenRect(index));
1143 pp::Point PDFiumEngine::GetScrollPosition() {
1144 return position_;
1147 void PDFiumEngine::SetScrollPosition(const pp::Point& position) {
1148 position_ = position;
1151 bool PDFiumEngine::IsProgressiveLoad() {
1152 return doc_loader_.is_partial_document();
1155 void PDFiumEngine::OnPartialDocumentLoaded() {
1156 file_access_.m_FileLen = doc_loader_.document_size();
1157 fpdf_availability_ = FPDFAvail_Create(&file_availability_, &file_access_);
1158 DCHECK(fpdf_availability_);
1160 // Currently engine does not deal efficiently with some non-linearized files.
1161 // See http://code.google.com/p/chromium/issues/detail?id=59400
1162 // To improve user experience we download entire file for non-linearized PDF.
1163 if (!FPDFAvail_IsLinearized(fpdf_availability_)) {
1164 doc_loader_.RequestData(0, doc_loader_.document_size());
1165 return;
1168 LoadDocument();
1171 void PDFiumEngine::OnPendingRequestComplete() {
1172 if (!doc_ || !form_) {
1173 LoadDocument();
1174 return;
1177 // LoadDocument() will result in |pending_pages_| being reset so there's no
1178 // need to run the code below in that case.
1179 bool update_pages = false;
1180 std::vector<int> still_pending;
1181 for (size_t i = 0; i < pending_pages_.size(); ++i) {
1182 if (CheckPageAvailable(pending_pages_[i], &still_pending)) {
1183 update_pages = true;
1184 if (IsPageVisible(pending_pages_[i]))
1185 client_->Invalidate(GetPageScreenRect(pending_pages_[i]));
1188 pending_pages_.swap(still_pending);
1189 if (update_pages)
1190 LoadPageInfo(true);
1193 void PDFiumEngine::OnNewDataAvailable() {
1194 client_->DocumentLoadProgress(doc_loader_.GetAvailableData(),
1195 doc_loader_.document_size());
1198 void PDFiumEngine::OnDocumentComplete() {
1199 if (!doc_ || !form_) {
1200 file_access_.m_FileLen = doc_loader_.document_size();
1201 LoadDocument();
1202 return;
1205 bool need_update = false;
1206 for (size_t i = 0; i < pages_.size(); ++i) {
1207 if (pages_[i]->available())
1208 continue;
1210 pages_[i]->set_available(true);
1211 // We still need to call IsPageAvail() even if the whole document is
1212 // already downloaded.
1213 FPDFAvail_IsPageAvail(fpdf_availability_, i, &download_hints_);
1214 need_update = true;
1215 if (IsPageVisible(i))
1216 client_->Invalidate(GetPageScreenRect(i));
1218 if (need_update)
1219 LoadPageInfo(true);
1221 FinishLoadingDocument();
1224 void PDFiumEngine::FinishLoadingDocument() {
1225 DCHECK(doc_loader_.IsDocumentComplete() && doc_);
1226 if (called_do_document_action_)
1227 return;
1228 called_do_document_action_ = true;
1230 // These can only be called now, as the JS might end up needing a page.
1231 FORM_DoDocumentJSAction(form_);
1232 FORM_DoDocumentOpenAction(form_);
1233 if (most_visible_page_ != -1) {
1234 FPDF_PAGE new_page = pages_[most_visible_page_]->GetPage();
1235 FORM_DoPageAAction(new_page, form_, FPDFPAGE_AACTION_OPEN);
1238 if (doc_) // This can only happen if loading |doc_| fails.
1239 client_->DocumentLoadComplete(pages_.size());
1242 void PDFiumEngine::UnsupportedFeature(int type) {
1243 std::string feature;
1244 switch (type) {
1245 #ifndef PDF_USE_XFA
1246 case FPDF_UNSP_DOC_XFAFORM:
1247 feature = "XFA";
1248 break;
1249 #endif
1250 case FPDF_UNSP_DOC_PORTABLECOLLECTION:
1251 feature = "Portfolios_Packages";
1252 break;
1253 case FPDF_UNSP_DOC_ATTACHMENT:
1254 case FPDF_UNSP_ANNOT_ATTACHMENT:
1255 feature = "Attachment";
1256 break;
1257 case FPDF_UNSP_DOC_SECURITY:
1258 feature = "Rights_Management";
1259 break;
1260 case FPDF_UNSP_DOC_SHAREDREVIEW:
1261 feature = "Shared_Review";
1262 break;
1263 case FPDF_UNSP_DOC_SHAREDFORM_ACROBAT:
1264 case FPDF_UNSP_DOC_SHAREDFORM_FILESYSTEM:
1265 case FPDF_UNSP_DOC_SHAREDFORM_EMAIL:
1266 feature = "Shared_Form";
1267 break;
1268 case FPDF_UNSP_ANNOT_3DANNOT:
1269 feature = "3D";
1270 break;
1271 case FPDF_UNSP_ANNOT_MOVIE:
1272 feature = "Movie";
1273 break;
1274 case FPDF_UNSP_ANNOT_SOUND:
1275 feature = "Sound";
1276 break;
1277 case FPDF_UNSP_ANNOT_SCREEN_MEDIA:
1278 case FPDF_UNSP_ANNOT_SCREEN_RICHMEDIA:
1279 feature = "Screen";
1280 break;
1281 case FPDF_UNSP_ANNOT_SIG:
1282 feature = "Digital_Signature";
1283 break;
1285 client_->DocumentHasUnsupportedFeature(feature);
1288 void PDFiumEngine::ContinueFind(int32_t result) {
1289 StartFind(current_find_text_.c_str(), !!result);
1292 bool PDFiumEngine::HandleEvent(const pp::InputEvent& event) {
1293 DCHECK(!defer_page_unload_);
1294 defer_page_unload_ = true;
1295 bool rv = false;
1296 switch (event.GetType()) {
1297 case PP_INPUTEVENT_TYPE_MOUSEDOWN:
1298 rv = OnMouseDown(pp::MouseInputEvent(event));
1299 break;
1300 case PP_INPUTEVENT_TYPE_MOUSEUP:
1301 rv = OnMouseUp(pp::MouseInputEvent(event));
1302 break;
1303 case PP_INPUTEVENT_TYPE_MOUSEMOVE:
1304 rv = OnMouseMove(pp::MouseInputEvent(event));
1305 break;
1306 case PP_INPUTEVENT_TYPE_KEYDOWN:
1307 rv = OnKeyDown(pp::KeyboardInputEvent(event));
1308 break;
1309 case PP_INPUTEVENT_TYPE_KEYUP:
1310 rv = OnKeyUp(pp::KeyboardInputEvent(event));
1311 break;
1312 case PP_INPUTEVENT_TYPE_CHAR:
1313 rv = OnChar(pp::KeyboardInputEvent(event));
1314 break;
1315 default:
1316 break;
1319 DCHECK(defer_page_unload_);
1320 defer_page_unload_ = false;
1321 for (size_t i = 0; i < deferred_page_unloads_.size(); ++i)
1322 pages_[deferred_page_unloads_[i]]->Unload();
1323 deferred_page_unloads_.clear();
1324 return rv;
1327 uint32_t PDFiumEngine::QuerySupportedPrintOutputFormats() {
1328 if (!HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY))
1329 return 0;
1330 return PP_PRINTOUTPUTFORMAT_PDF;
1333 void PDFiumEngine::PrintBegin() {
1334 FORM_DoDocumentAAction(form_, FPDFDOC_AACTION_WP);
1337 pp::Resource PDFiumEngine::PrintPages(
1338 const PP_PrintPageNumberRange_Dev* page_ranges, uint32_t page_range_count,
1339 const PP_PrintSettings_Dev& print_settings) {
1340 if (HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY))
1341 return PrintPagesAsPDF(page_ranges, page_range_count, print_settings);
1342 else if (HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY))
1343 return PrintPagesAsRasterPDF(page_ranges, page_range_count, print_settings);
1344 return pp::Resource();
1347 FPDF_DOCUMENT PDFiumEngine::CreateSinglePageRasterPdf(
1348 double source_page_width,
1349 double source_page_height,
1350 const PP_PrintSettings_Dev& print_settings,
1351 PDFiumPage* page_to_print) {
1352 FPDF_DOCUMENT temp_doc = FPDF_CreateNewDocument();
1353 if (!temp_doc)
1354 return temp_doc;
1356 const pp::Size& bitmap_size(page_to_print->rect().size());
1358 FPDF_PAGE temp_page =
1359 FPDFPage_New(temp_doc, 0, source_page_width, source_page_height);
1361 pp::ImageData image = pp::ImageData(client_->GetPluginInstance(),
1362 PP_IMAGEDATAFORMAT_BGRA_PREMUL,
1363 bitmap_size,
1364 false);
1366 FPDF_BITMAP bitmap = FPDFBitmap_CreateEx(bitmap_size.width(),
1367 bitmap_size.height(),
1368 FPDFBitmap_BGRx,
1369 image.data(),
1370 image.stride());
1372 // Clear the bitmap
1373 FPDFBitmap_FillRect(
1374 bitmap, 0, 0, bitmap_size.width(), bitmap_size.height(), 0xFFFFFFFF);
1376 pp::Rect page_rect = page_to_print->rect();
1377 FPDF_RenderPageBitmap(bitmap,
1378 page_to_print->GetPrintPage(),
1379 page_rect.x(),
1380 page_rect.y(),
1381 page_rect.width(),
1382 page_rect.height(),
1383 print_settings.orientation,
1384 FPDF_ANNOT | FPDF_PRINTING | FPDF_NO_CATCH);
1386 double ratio_x = ConvertUnitDouble(bitmap_size.width(),
1387 print_settings.dpi,
1388 kPointsPerInch);
1389 double ratio_y = ConvertUnitDouble(bitmap_size.height(),
1390 print_settings.dpi,
1391 kPointsPerInch);
1393 // Add the bitmap to an image object and add the image object to the output
1394 // page.
1395 FPDF_PAGEOBJECT temp_img = FPDFPageObj_NewImgeObj(temp_doc);
1396 FPDFImageObj_SetBitmap(&temp_page, 1, temp_img, bitmap);
1397 FPDFImageObj_SetMatrix(temp_img, ratio_x, 0, 0, ratio_y, 0, 0);
1398 FPDFPage_InsertObject(temp_page, temp_img);
1399 FPDFPage_GenerateContent(temp_page);
1400 FPDF_ClosePage(temp_page);
1402 page_to_print->ClosePrintPage();
1403 FPDFBitmap_Destroy(bitmap);
1405 return temp_doc;
1408 pp::Buffer_Dev PDFiumEngine::PrintPagesAsRasterPDF(
1409 const PP_PrintPageNumberRange_Dev* page_ranges, uint32_t page_range_count,
1410 const PP_PrintSettings_Dev& print_settings) {
1411 if (!page_range_count)
1412 return pp::Buffer_Dev();
1414 // If document is not downloaded yet, disable printing.
1415 if (doc_ && !doc_loader_.IsDocumentComplete())
1416 return pp::Buffer_Dev();
1418 FPDF_DOCUMENT output_doc = FPDF_CreateNewDocument();
1419 if (!output_doc)
1420 return pp::Buffer_Dev();
1422 SaveSelectedFormForPrint();
1424 std::vector<PDFiumPage> pages_to_print;
1425 // width and height of source PDF pages.
1426 std::vector<std::pair<double, double> > source_page_sizes;
1427 // Collect pages to print and sizes of source pages.
1428 std::vector<uint32_t> page_numbers =
1429 GetPageNumbersFromPrintPageNumberRange(page_ranges, page_range_count);
1430 for (size_t i = 0; i < page_numbers.size(); ++i) {
1431 uint32_t page_number = page_numbers[i];
1432 FPDF_PAGE pdf_page = FPDF_LoadPage(doc_, page_number);
1433 double source_page_width = FPDF_GetPageWidth(pdf_page);
1434 double source_page_height = FPDF_GetPageHeight(pdf_page);
1435 source_page_sizes.push_back(std::make_pair(source_page_width,
1436 source_page_height));
1438 int width_in_pixels = ConvertUnit(source_page_width,
1439 kPointsPerInch,
1440 print_settings.dpi);
1441 int height_in_pixels = ConvertUnit(source_page_height,
1442 kPointsPerInch,
1443 print_settings.dpi);
1445 pp::Rect rect(width_in_pixels, height_in_pixels);
1446 pages_to_print.push_back(PDFiumPage(this, page_number, rect, true));
1447 FPDF_ClosePage(pdf_page);
1450 #if defined(OS_LINUX)
1451 g_last_instance_id = client_->GetPluginInstance()->pp_instance();
1452 #endif
1454 size_t i = 0;
1455 for (; i < pages_to_print.size(); ++i) {
1456 double source_page_width = source_page_sizes[i].first;
1457 double source_page_height = source_page_sizes[i].second;
1459 // Use temp_doc to compress image by saving PDF to buffer.
1460 FPDF_DOCUMENT temp_doc = CreateSinglePageRasterPdf(source_page_width,
1461 source_page_height,
1462 print_settings,
1463 &pages_to_print[i]);
1465 if (!temp_doc)
1466 break;
1468 pp::Buffer_Dev buffer = GetFlattenedPrintData(temp_doc);
1469 FPDF_CloseDocument(temp_doc);
1471 PDFiumMemBufferFileRead file_read(buffer.data(), buffer.size());
1472 temp_doc = FPDF_LoadCustomDocument(&file_read, NULL);
1474 FPDF_BOOL imported = FPDF_ImportPages(output_doc, temp_doc, "1", i);
1475 FPDF_CloseDocument(temp_doc);
1476 if (!imported)
1477 break;
1480 pp::Buffer_Dev buffer;
1481 if (i == pages_to_print.size()) {
1482 FPDF_CopyViewerPreferences(output_doc, doc_);
1483 FitContentsToPrintableAreaIfRequired(output_doc, print_settings);
1484 // Now flatten all the output pages.
1485 buffer = GetFlattenedPrintData(output_doc);
1487 FPDF_CloseDocument(output_doc);
1488 return buffer;
1491 pp::Buffer_Dev PDFiumEngine::GetFlattenedPrintData(const FPDF_DOCUMENT& doc) {
1492 int page_count = FPDF_GetPageCount(doc);
1493 bool flatten_succeeded = true;
1494 for (int i = 0; i < page_count; ++i) {
1495 FPDF_PAGE page = FPDF_LoadPage(doc, i);
1496 DCHECK(page);
1497 if (page) {
1498 int flatten_ret = FPDFPage_Flatten(page, FLAT_PRINT);
1499 FPDF_ClosePage(page);
1500 if (flatten_ret == FLATTEN_FAIL) {
1501 flatten_succeeded = false;
1502 break;
1504 } else {
1505 flatten_succeeded = false;
1506 break;
1509 if (!flatten_succeeded) {
1510 FPDF_CloseDocument(doc);
1511 return pp::Buffer_Dev();
1514 pp::Buffer_Dev buffer;
1515 PDFiumMemBufferFileWrite output_file_write;
1516 if (FPDF_SaveAsCopy(doc, &output_file_write, 0)) {
1517 buffer = pp::Buffer_Dev(
1518 client_->GetPluginInstance(), output_file_write.size());
1519 if (!buffer.is_null()) {
1520 memcpy(buffer.data(), output_file_write.buffer().c_str(),
1521 output_file_write.size());
1524 return buffer;
1527 pp::Buffer_Dev PDFiumEngine::PrintPagesAsPDF(
1528 const PP_PrintPageNumberRange_Dev* page_ranges, uint32_t page_range_count,
1529 const PP_PrintSettings_Dev& print_settings) {
1530 if (!page_range_count)
1531 return pp::Buffer_Dev();
1533 DCHECK(doc_);
1534 FPDF_DOCUMENT output_doc = FPDF_CreateNewDocument();
1535 if (!output_doc)
1536 return pp::Buffer_Dev();
1538 SaveSelectedFormForPrint();
1540 std::string page_number_str;
1541 for (uint32_t index = 0; index < page_range_count; ++index) {
1542 if (!page_number_str.empty())
1543 page_number_str.append(",");
1544 page_number_str.append(
1545 base::IntToString(page_ranges[index].first_page_number + 1));
1546 if (page_ranges[index].first_page_number !=
1547 page_ranges[index].last_page_number) {
1548 page_number_str.append("-");
1549 page_number_str.append(
1550 base::IntToString(page_ranges[index].last_page_number + 1));
1554 std::vector<uint32_t> page_numbers =
1555 GetPageNumbersFromPrintPageNumberRange(page_ranges, page_range_count);
1556 for (size_t i = 0; i < page_numbers.size(); ++i) {
1557 uint32_t page_number = page_numbers[i];
1558 pages_[page_number]->GetPage();
1559 if (!IsPageVisible(page_numbers[i]))
1560 pages_[page_number]->Unload();
1563 FPDF_CopyViewerPreferences(output_doc, doc_);
1564 if (!FPDF_ImportPages(output_doc, doc_, page_number_str.c_str(), 0)) {
1565 FPDF_CloseDocument(output_doc);
1566 return pp::Buffer_Dev();
1569 FitContentsToPrintableAreaIfRequired(output_doc, print_settings);
1571 // Now flatten all the output pages.
1572 pp::Buffer_Dev buffer = GetFlattenedPrintData(output_doc);
1573 FPDF_CloseDocument(output_doc);
1574 return buffer;
1577 void PDFiumEngine::FitContentsToPrintableAreaIfRequired(
1578 const FPDF_DOCUMENT& doc, const PP_PrintSettings_Dev& print_settings) {
1579 // Check to see if we need to fit pdf contents to printer paper size.
1580 if (print_settings.print_scaling_option !=
1581 PP_PRINTSCALINGOPTION_SOURCE_SIZE) {
1582 int num_pages = FPDF_GetPageCount(doc);
1583 // In-place transformation is more efficient than creating a new
1584 // transformed document from the source document. Therefore, transform
1585 // every page to fit the contents in the selected printer paper.
1586 for (int i = 0; i < num_pages; ++i) {
1587 FPDF_PAGE page = FPDF_LoadPage(doc, i);
1588 TransformPDFPageForPrinting(page, print_settings);
1589 FPDF_ClosePage(page);
1594 void PDFiumEngine::SaveSelectedFormForPrint() {
1595 FORM_ForceToKillFocus(form_);
1596 client_->FormTextFieldFocusChange(false);
1599 void PDFiumEngine::PrintEnd() {
1600 FORM_DoDocumentAAction(form_, FPDFDOC_AACTION_DP);
1603 PDFiumPage::Area PDFiumEngine::GetCharIndex(const pp::MouseInputEvent& event,
1604 int* page_index,
1605 int* char_index,
1606 int* form_type,
1607 PDFiumPage::LinkTarget* target) {
1608 // First figure out which page this is in.
1609 pp::Point mouse_point = event.GetPosition();
1610 return GetCharIndex(mouse_point, page_index, char_index, form_type, target);
1613 PDFiumPage::Area PDFiumEngine::GetCharIndex(const pp::Point& point,
1614 int* page_index,
1615 int* char_index,
1616 int* form_type,
1617 PDFiumPage::LinkTarget* target) {
1618 int page = -1;
1619 pp::Point point_in_page(
1620 static_cast<int>((point.x() + position_.x()) / current_zoom_),
1621 static_cast<int>((point.y() + position_.y()) / current_zoom_));
1622 for (size_t i = 0; i < visible_pages_.size(); ++i) {
1623 if (pages_[visible_pages_[i]]->rect().Contains(point_in_page)) {
1624 page = visible_pages_[i];
1625 break;
1628 if (page == -1)
1629 return PDFiumPage::NONSELECTABLE_AREA;
1631 // If the page hasn't finished rendering, calling into the page sometimes
1632 // leads to hangs.
1633 for (size_t i = 0; i < progressive_paints_.size(); ++i) {
1634 if (progressive_paints_[i].page_index == page)
1635 return PDFiumPage::NONSELECTABLE_AREA;
1638 *page_index = page;
1639 return pages_[page]->GetCharIndex(
1640 point_in_page, current_rotation_, char_index, form_type, target);
1643 bool PDFiumEngine::OnMouseDown(const pp::MouseInputEvent& event) {
1644 if (event.GetButton() == PP_INPUTEVENT_MOUSEBUTTON_RIGHT) {
1645 if (!selection_.size())
1646 return false;
1647 std::vector<pp::Rect> selection_rect_vector;
1648 GetAllScreenRectsUnion(&selection_, GetVisibleRect().point(),
1649 &selection_rect_vector);
1650 pp::Point point = event.GetPosition();
1651 for (size_t i = 0; i < selection_rect_vector.size(); ++i) {
1652 if (selection_rect_vector[i].Contains(point.x(), point.y()))
1653 return false;
1655 SelectionChangeInvalidator selection_invalidator(this);
1656 selection_.clear();
1657 return true;
1659 if (event.GetButton() != PP_INPUTEVENT_MOUSEBUTTON_LEFT)
1660 return false;
1662 SelectionChangeInvalidator selection_invalidator(this);
1663 selection_.clear();
1665 int page_index = -1;
1666 int char_index = -1;
1667 int form_type = FPDF_FORMFIELD_UNKNOWN;
1668 PDFiumPage::LinkTarget target;
1669 PDFiumPage::Area area =
1670 GetCharIndex(event, &page_index, &char_index, &form_type, &target);
1671 mouse_down_state_.Set(area, target);
1673 // Decide whether to open link or not based on user action in mouse up and
1674 // mouse move events.
1675 if (area == PDFiumPage::WEBLINK_AREA)
1676 return true;
1678 if (area == PDFiumPage::DOCLINK_AREA) {
1679 client_->ScrollToPage(target.page);
1680 client_->FormTextFieldFocusChange(false);
1681 return true;
1684 if (page_index != -1) {
1685 last_page_mouse_down_ = page_index;
1686 double page_x, page_y;
1687 pp::Point point = event.GetPosition();
1688 DeviceToPage(page_index, point.x(), point.y(), &page_x, &page_y);
1690 FORM_OnLButtonDown(form_, pages_[page_index]->GetPage(), 0, page_x, page_y);
1691 if (form_type > FPDF_FORMFIELD_UNKNOWN) { // returns -1 sometimes...
1692 mouse_down_state_.Set(PDFiumPage::NONSELECTABLE_AREA, target);
1693 bool is_valid_control = (form_type == FPDF_FORMFIELD_TEXTFIELD ||
1694 form_type == FPDF_FORMFIELD_COMBOBOX);
1695 #ifdef PDF_USE_XFA
1696 is_valid_control |= (form_type == FPDF_FORMFIELD_XFA);
1697 #endif
1698 client_->FormTextFieldFocusChange(is_valid_control);
1699 return true; // Return now before we get into the selection code.
1703 client_->FormTextFieldFocusChange(false);
1705 if (area != PDFiumPage::TEXT_AREA)
1706 return true; // Return true so WebKit doesn't do its own highlighting.
1708 if (event.GetClickCount() == 1) {
1709 OnSingleClick(page_index, char_index);
1710 } else if (event.GetClickCount() == 2 ||
1711 event.GetClickCount() == 3) {
1712 OnMultipleClick(event.GetClickCount(), page_index, char_index);
1715 return true;
1718 void PDFiumEngine::OnSingleClick(int page_index, int char_index) {
1719 SetSelecting(true);
1720 selection_.push_back(PDFiumRange(pages_[page_index], char_index, 0));
1723 void PDFiumEngine::OnMultipleClick(int click_count,
1724 int page_index,
1725 int char_index) {
1726 // It would be more efficient if the SDK could support finding a space, but
1727 // now it doesn't.
1728 int start_index = char_index;
1729 do {
1730 base::char16 cur = pages_[page_index]->GetCharAtIndex(start_index);
1731 // For double click, we want to select one word so we look for whitespace
1732 // boundaries. For triple click, we want the whole line.
1733 if (cur == '\n' || (click_count == 2 && (cur == ' ' || cur == '\t')))
1734 break;
1735 } while (--start_index >= 0);
1736 if (start_index)
1737 start_index++;
1739 int end_index = char_index;
1740 int total = pages_[page_index]->GetCharCount();
1741 while (end_index++ <= total) {
1742 base::char16 cur = pages_[page_index]->GetCharAtIndex(end_index);
1743 if (cur == '\n' || (click_count == 2 && (cur == ' ' || cur == '\t')))
1744 break;
1747 selection_.push_back(PDFiumRange(
1748 pages_[page_index], start_index, end_index - start_index));
1751 bool PDFiumEngine::OnMouseUp(const pp::MouseInputEvent& event) {
1752 if (event.GetButton() != PP_INPUTEVENT_MOUSEBUTTON_LEFT)
1753 return false;
1755 int page_index = -1;
1756 int char_index = -1;
1757 int form_type = FPDF_FORMFIELD_UNKNOWN;
1758 PDFiumPage::LinkTarget target;
1759 PDFiumPage::Area area =
1760 GetCharIndex(event, &page_index, &char_index, &form_type, &target);
1762 // Open link on mouse up for same link for which mouse down happened earlier.
1763 if (mouse_down_state_.Matches(area, target)) {
1764 if (area == PDFiumPage::WEBLINK_AREA) {
1765 bool open_in_new_tab = !!(event.GetModifiers() & kDefaultKeyModifier);
1766 client_->NavigateTo(target.url, open_in_new_tab);
1767 client_->FormTextFieldFocusChange(false);
1768 return true;
1772 if (page_index != -1) {
1773 double page_x, page_y;
1774 pp::Point point = event.GetPosition();
1775 DeviceToPage(page_index, point.x(), point.y(), &page_x, &page_y);
1776 FORM_OnLButtonUp(
1777 form_, pages_[page_index]->GetPage(), 0, page_x, page_y);
1780 if (!selecting_)
1781 return false;
1783 SetSelecting(false);
1784 return true;
1787 bool PDFiumEngine::OnMouseMove(const pp::MouseInputEvent& event) {
1788 int page_index = -1;
1789 int char_index = -1;
1790 int form_type = FPDF_FORMFIELD_UNKNOWN;
1791 PDFiumPage::LinkTarget target;
1792 PDFiumPage::Area area =
1793 GetCharIndex(event, &page_index, &char_index, &form_type, &target);
1795 // Clear |mouse_down_state_| if mouse moves away from where the mouse down
1796 // happened.
1797 if (!mouse_down_state_.Matches(area, target))
1798 mouse_down_state_.Reset();
1800 if (!selecting_) {
1801 PP_CursorType_Dev cursor;
1802 switch (area) {
1803 case PDFiumPage::TEXT_AREA:
1804 cursor = PP_CURSORTYPE_IBEAM;
1805 break;
1806 case PDFiumPage::WEBLINK_AREA:
1807 case PDFiumPage::DOCLINK_AREA:
1808 cursor = PP_CURSORTYPE_HAND;
1809 break;
1810 case PDFiumPage::NONSELECTABLE_AREA:
1811 default:
1812 switch (form_type) {
1813 case FPDF_FORMFIELD_PUSHBUTTON:
1814 case FPDF_FORMFIELD_CHECKBOX:
1815 case FPDF_FORMFIELD_RADIOBUTTON:
1816 case FPDF_FORMFIELD_COMBOBOX:
1817 case FPDF_FORMFIELD_LISTBOX:
1818 cursor = PP_CURSORTYPE_HAND;
1819 break;
1820 case FPDF_FORMFIELD_TEXTFIELD:
1821 cursor = PP_CURSORTYPE_IBEAM;
1822 break;
1823 default:
1824 cursor = PP_CURSORTYPE_POINTER;
1825 break;
1827 break;
1830 if (page_index != -1) {
1831 double page_x, page_y;
1832 pp::Point point = event.GetPosition();
1833 DeviceToPage(page_index, point.x(), point.y(), &page_x, &page_y);
1834 FORM_OnMouseMove(form_, pages_[page_index]->GetPage(), 0, page_x, page_y);
1837 client_->UpdateCursor(cursor);
1838 pp::Point point = event.GetPosition();
1839 std::string url = GetLinkAtPosition(event.GetPosition());
1840 if (url != link_under_cursor_) {
1841 link_under_cursor_ = url;
1842 pp::PDF::SetLinkUnderCursor(GetPluginInstance(), url.c_str());
1844 // No need to swallow the event, since this might interfere with the
1845 // scrollbars if the user is dragging them.
1846 return false;
1849 // We're selecting but right now we're not over text, so don't change the
1850 // current selection.
1851 if (area != PDFiumPage::TEXT_AREA && area != PDFiumPage::WEBLINK_AREA &&
1852 area != PDFiumPage::DOCLINK_AREA) {
1853 return false;
1856 SelectionChangeInvalidator selection_invalidator(this);
1858 // Check if the user has descreased their selection area and we need to remove
1859 // pages from selection_.
1860 for (size_t i = 0; i < selection_.size(); ++i) {
1861 if (selection_[i].page_index() == page_index) {
1862 // There should be no other pages after this.
1863 selection_.erase(selection_.begin() + i + 1, selection_.end());
1864 break;
1868 if (selection_.size() == 0)
1869 return false;
1871 int last = selection_.size() - 1;
1872 if (selection_[last].page_index() == page_index) {
1873 // Selecting within a page.
1874 int count;
1875 if (char_index >= selection_[last].char_index()) {
1876 // Selecting forward.
1877 count = char_index - selection_[last].char_index() + 1;
1878 } else {
1879 count = char_index - selection_[last].char_index() - 1;
1881 selection_[last].SetCharCount(count);
1882 } else if (selection_[last].page_index() < page_index) {
1883 // Selecting into the next page.
1885 // First make sure that there are no gaps in selection, i.e. if mousedown on
1886 // page one but we only get mousemove over page three, we want page two.
1887 for (int i = selection_[last].page_index() + 1; i < page_index; ++i) {
1888 selection_.push_back(PDFiumRange(pages_[i], 0,
1889 pages_[i]->GetCharCount()));
1892 int count = pages_[selection_[last].page_index()]->GetCharCount();
1893 selection_[last].SetCharCount(count - selection_[last].char_index());
1894 selection_.push_back(PDFiumRange(pages_[page_index], 0, char_index));
1895 } else {
1896 // Selecting into the previous page.
1897 // The selection's char_index is 0-based, so the character count is one
1898 // more than the index. The character count needs to be negative to
1899 // indicate a backwards selection.
1900 selection_[last].SetCharCount(-(selection_[last].char_index() + 1));
1902 // First make sure that there are no gaps in selection, i.e. if mousedown on
1903 // page three but we only get mousemove over page one, we want page two.
1904 for (int i = selection_[last].page_index() - 1; i > page_index; --i) {
1905 selection_.push_back(PDFiumRange(pages_[i], 0,
1906 pages_[i]->GetCharCount()));
1909 int count = pages_[page_index]->GetCharCount();
1910 selection_.push_back(
1911 PDFiumRange(pages_[page_index], count, count - char_index));
1914 return true;
1917 bool PDFiumEngine::OnKeyDown(const pp::KeyboardInputEvent& event) {
1918 if (last_page_mouse_down_ == -1)
1919 return false;
1921 bool rv = !!FORM_OnKeyDown(
1922 form_, pages_[last_page_mouse_down_]->GetPage(),
1923 event.GetKeyCode(), event.GetModifiers());
1925 if (event.GetKeyCode() == ui::VKEY_BACK ||
1926 event.GetKeyCode() == ui::VKEY_ESCAPE) {
1927 // Chrome doesn't send char events for backspace or escape keys, see
1928 // PlatformKeyboardEventBuilder::isCharacterKey() and
1929 // http://chrome-corpsvn.mtv.corp.google.com/viewvc?view=rev&root=chrome&revision=31805
1930 // for more information. So just fake one since PDFium uses it.
1931 std::string str;
1932 str.push_back(event.GetKeyCode());
1933 pp::KeyboardInputEvent synthesized(pp::KeyboardInputEvent(
1934 client_->GetPluginInstance(),
1935 PP_INPUTEVENT_TYPE_CHAR,
1936 event.GetTimeStamp(),
1937 event.GetModifiers(),
1938 event.GetKeyCode(),
1939 str));
1940 OnChar(synthesized);
1943 return rv;
1946 bool PDFiumEngine::OnKeyUp(const pp::KeyboardInputEvent& event) {
1947 if (last_page_mouse_down_ == -1)
1948 return false;
1950 return !!FORM_OnKeyUp(
1951 form_, pages_[last_page_mouse_down_]->GetPage(),
1952 event.GetKeyCode(), event.GetModifiers());
1955 bool PDFiumEngine::OnChar(const pp::KeyboardInputEvent& event) {
1956 if (last_page_mouse_down_ == -1)
1957 return false;
1959 base::string16 str = base::UTF8ToUTF16(event.GetCharacterText().AsString());
1960 return !!FORM_OnChar(
1961 form_, pages_[last_page_mouse_down_]->GetPage(),
1962 str[0],
1963 event.GetModifiers());
1966 void PDFiumEngine::StartFind(const char* text, bool case_sensitive) {
1967 // We can get a call to StartFind before we have any page information (i.e.
1968 // before the first call to LoadDocument has happened). Handle this case.
1969 if (pages_.empty())
1970 return;
1972 bool first_search = false;
1973 int character_to_start_searching_from = 0;
1974 if (current_find_text_ != text) { // First time we search for this text.
1975 first_search = true;
1976 std::vector<PDFiumRange> old_selection = selection_;
1977 StopFind();
1978 current_find_text_ = text;
1980 if (old_selection.empty()) {
1981 // Start searching from the beginning of the document.
1982 next_page_to_search_ = 0;
1983 last_page_to_search_ = pages_.size() - 1;
1984 last_character_index_to_search_ = -1;
1985 } else {
1986 // There's a current selection, so start from it.
1987 next_page_to_search_ = old_selection[0].page_index();
1988 last_character_index_to_search_ = old_selection[0].char_index();
1989 character_to_start_searching_from = old_selection[0].char_index();
1990 last_page_to_search_ = next_page_to_search_;
1994 int current_page = next_page_to_search_;
1996 if (pages_[current_page]->available()) {
1997 base::string16 str = base::UTF8ToUTF16(text);
1998 // Don't use PDFium to search for now, since it doesn't support unicode text.
1999 // Leave the code for now to avoid bit-rot, in case it's fixed later.
2000 if (0) {
2001 SearchUsingPDFium(
2002 str, case_sensitive, first_search, character_to_start_searching_from,
2003 current_page);
2004 } else {
2005 SearchUsingICU(
2006 str, case_sensitive, first_search, character_to_start_searching_from,
2007 current_page);
2010 if (!IsPageVisible(current_page))
2011 pages_[current_page]->Unload();
2014 if (next_page_to_search_ != last_page_to_search_ ||
2015 (first_search && last_character_index_to_search_ != -1)) {
2016 ++next_page_to_search_;
2019 if (next_page_to_search_ == static_cast<int>(pages_.size()))
2020 next_page_to_search_ = 0;
2021 // If there's only one page in the document and we start searching midway,
2022 // then we'll want to search the page one more time.
2023 bool end_of_search =
2024 next_page_to_search_ == last_page_to_search_ &&
2025 // Only one page but didn't start midway.
2026 ((pages_.size() == 1 && last_character_index_to_search_ == -1) ||
2027 // Started midway, but only 1 page and we already looped around.
2028 (pages_.size() == 1 && !first_search) ||
2029 // Started midway, and we've just looped around.
2030 (pages_.size() > 1 && current_page == next_page_to_search_));
2032 if (end_of_search) {
2033 // Send the final notification.
2034 client_->NotifyNumberOfFindResultsChanged(find_results_.size(), true);
2036 // When searching is complete, resume finding at a particular index.
2037 // Assuming the user has not clicked the find button in the meanwhile.
2038 if (resume_find_index_.valid() && !current_find_index_.valid()) {
2039 size_t resume_index = resume_find_index_.GetIndex();
2040 if (resume_index >= find_results_.size()) {
2041 // This might happen if the PDF has some dynamically generated text?
2042 resume_index = 0;
2044 current_find_index_.SetIndex(resume_index);
2045 client_->NotifySelectedFindResultChanged(resume_index);
2047 resume_find_index_.Invalidate();
2048 } else {
2049 pp::CompletionCallback callback =
2050 find_factory_.NewCallback(&PDFiumEngine::ContinueFind);
2051 pp::Module::Get()->core()->CallOnMainThread(
2052 0, callback, case_sensitive ? 1 : 0);
2056 void PDFiumEngine::SearchUsingPDFium(const base::string16& term,
2057 bool case_sensitive,
2058 bool first_search,
2059 int character_to_start_searching_from,
2060 int current_page) {
2061 // Find all the matches in the current page.
2062 unsigned long flags = case_sensitive ? FPDF_MATCHCASE : 0;
2063 FPDF_SCHHANDLE find = FPDFText_FindStart(
2064 pages_[current_page]->GetTextPage(),
2065 reinterpret_cast<const unsigned short*>(term.c_str()),
2066 flags, character_to_start_searching_from);
2068 // Note: since we search one page at a time, we don't find matches across
2069 // page boundaries. We could do this manually ourself, but it seems low
2070 // priority since Reader itself doesn't do it.
2071 while (FPDFText_FindNext(find)) {
2072 PDFiumRange result(pages_[current_page],
2073 FPDFText_GetSchResultIndex(find),
2074 FPDFText_GetSchCount(find));
2076 if (!first_search &&
2077 last_character_index_to_search_ != -1 &&
2078 result.page_index() == last_page_to_search_ &&
2079 result.char_index() >= last_character_index_to_search_) {
2080 break;
2083 AddFindResult(result);
2086 FPDFText_FindClose(find);
2089 void PDFiumEngine::SearchUsingICU(const base::string16& term,
2090 bool case_sensitive,
2091 bool first_search,
2092 int character_to_start_searching_from,
2093 int current_page) {
2094 base::string16 page_text;
2095 int text_length = pages_[current_page]->GetCharCount();
2096 if (character_to_start_searching_from) {
2097 text_length -= character_to_start_searching_from;
2098 } else if (!first_search &&
2099 last_character_index_to_search_ != -1 &&
2100 current_page == last_page_to_search_) {
2101 text_length = last_character_index_to_search_;
2103 if (text_length <= 0)
2104 return;
2106 PDFiumAPIStringBufferAdapter<base::string16> api_string_adapter(&page_text,
2107 text_length,
2108 false);
2109 unsigned short* data =
2110 reinterpret_cast<unsigned short*>(api_string_adapter.GetData());
2111 int written = FPDFText_GetText(pages_[current_page]->GetTextPage(),
2112 character_to_start_searching_from,
2113 text_length,
2114 data);
2115 api_string_adapter.Close(written);
2117 std::vector<PDFEngine::Client::SearchStringResult> results;
2118 client_->SearchString(
2119 page_text.c_str(), term.c_str(), case_sensitive, &results);
2120 for (size_t i = 0; i < results.size(); ++i) {
2121 // Need to map the indexes from the page text, which may have generated
2122 // characters like space etc, to character indices from the page.
2123 int temp_start = results[i].start_index + character_to_start_searching_from;
2124 int start = FPDFText_GetCharIndexFromTextIndex(
2125 pages_[current_page]->GetTextPage(), temp_start);
2126 int end = FPDFText_GetCharIndexFromTextIndex(
2127 pages_[current_page]->GetTextPage(),
2128 temp_start + results[i].length);
2129 AddFindResult(PDFiumRange(pages_[current_page], start, end - start));
2133 void PDFiumEngine::AddFindResult(const PDFiumRange& result) {
2134 // Figure out where to insert the new location, since we could have
2135 // started searching midway and now we wrapped.
2136 size_t result_index;
2137 int page_index = result.page_index();
2138 int char_index = result.char_index();
2139 for (result_index = 0; result_index < find_results_.size(); ++result_index) {
2140 if (find_results_[result_index].page_index() > page_index ||
2141 (find_results_[result_index].page_index() == page_index &&
2142 find_results_[result_index].char_index() > char_index)) {
2143 break;
2146 find_results_.insert(find_results_.begin() + result_index, result);
2147 UpdateTickMarks();
2149 if (current_find_index_.valid()) {
2150 if (result_index <= current_find_index_.GetIndex()) {
2151 // Update the current match index
2152 size_t find_index = current_find_index_.IncrementIndex();
2153 DCHECK_LT(find_index, find_results_.size());
2154 client_->NotifySelectedFindResultChanged(current_find_index_.GetIndex());
2156 } else if (!resume_find_index_.valid()) {
2157 // Both indices are invalid. Select the first match.
2158 SelectFindResult(true);
2160 client_->NotifyNumberOfFindResultsChanged(find_results_.size(), false);
2163 bool PDFiumEngine::SelectFindResult(bool forward) {
2164 if (find_results_.empty()) {
2165 NOTREACHED();
2166 return false;
2169 SelectionChangeInvalidator selection_invalidator(this);
2171 // Move back/forward through the search locations we previously found.
2172 size_t new_index;
2173 const size_t last_index = find_results_.size() - 1;
2174 if (current_find_index_.valid()) {
2175 size_t current_index = current_find_index_.GetIndex();
2176 if (forward) {
2177 new_index = (current_index >= last_index) ? 0 : current_index + 1;
2178 } else {
2179 new_index = (current_find_index_.GetIndex() == 0) ?
2180 last_index : current_index - 1;
2182 } else {
2183 new_index = forward ? 0 : last_index;
2185 current_find_index_.SetIndex(new_index);
2187 // Update the selection before telling the client to scroll, since it could
2188 // paint then.
2189 selection_.clear();
2190 selection_.push_back(find_results_[current_find_index_.GetIndex()]);
2192 // If the result is not in view, scroll to it.
2193 pp::Rect bounding_rect;
2194 pp::Rect visible_rect = GetVisibleRect();
2195 // Use zoom of 1.0 since visible_rect is without zoom.
2196 std::vector<pp::Rect> rects;
2197 rects = find_results_[current_find_index_.GetIndex()].GetScreenRects(
2198 pp::Point(), 1.0, current_rotation_);
2199 for (size_t i = 0; i < rects.size(); ++i)
2200 bounding_rect = bounding_rect.Union(rects[i]);
2201 if (!visible_rect.Contains(bounding_rect)) {
2202 pp::Point center = bounding_rect.CenterPoint();
2203 // Make the page centered.
2204 int new_y = static_cast<int>(center.y() * current_zoom_) -
2205 static_cast<int>(visible_rect.height() * current_zoom_ / 2);
2206 if (new_y < 0)
2207 new_y = 0;
2208 client_->ScrollToY(new_y);
2210 // Only move horizontally if it's not visible.
2211 if (center.x() < visible_rect.x() || center.x() > visible_rect.right()) {
2212 int new_x = static_cast<int>(center.x() * current_zoom_) -
2213 static_cast<int>(visible_rect.width() * current_zoom_ / 2);
2214 if (new_x < 0)
2215 new_x = 0;
2216 client_->ScrollToX(new_x);
2220 client_->NotifySelectedFindResultChanged(current_find_index_.GetIndex());
2221 return true;
2224 void PDFiumEngine::StopFind() {
2225 SelectionChangeInvalidator selection_invalidator(this);
2227 selection_.clear();
2228 selecting_ = false;
2229 find_results_.clear();
2230 next_page_to_search_ = -1;
2231 last_page_to_search_ = -1;
2232 last_character_index_to_search_ = -1;
2233 current_find_index_.Invalidate();
2234 current_find_text_.clear();
2235 UpdateTickMarks();
2236 find_factory_.CancelAll();
2239 void PDFiumEngine::GetAllScreenRectsUnion(std::vector<PDFiumRange>* rect_range,
2240 const pp::Point& offset_point,
2241 std::vector<pp::Rect>* rect_vector) {
2242 for (std::vector<PDFiumRange>::iterator it = rect_range->begin();
2243 it != rect_range->end(); ++it) {
2244 pp::Rect rect;
2245 std::vector<pp::Rect> rects =
2246 it->GetScreenRects(offset_point, current_zoom_, current_rotation_);
2247 for (size_t j = 0; j < rects.size(); ++j)
2248 rect = rect.Union(rects[j]);
2249 rect_vector->push_back(rect);
2253 void PDFiumEngine::UpdateTickMarks() {
2254 std::vector<pp::Rect> tickmarks;
2255 GetAllScreenRectsUnion(&find_results_, pp::Point(0, 0), &tickmarks);
2256 client_->UpdateTickMarks(tickmarks);
2259 void PDFiumEngine::ZoomUpdated(double new_zoom_level) {
2260 CancelPaints();
2262 current_zoom_ = new_zoom_level;
2264 CalculateVisiblePages();
2265 UpdateTickMarks();
2268 void PDFiumEngine::RotateClockwise() {
2269 current_rotation_ = (current_rotation_ + 1) % 4;
2270 RotateInternal();
2273 void PDFiumEngine::RotateCounterclockwise() {
2274 current_rotation_ = (current_rotation_ - 1) % 4;
2275 RotateInternal();
2278 void PDFiumEngine::InvalidateAllPages() {
2279 CancelPaints();
2280 StopFind();
2281 LoadPageInfo(true);
2282 client_->Invalidate(pp::Rect(plugin_size_));
2285 std::string PDFiumEngine::GetSelectedText() {
2286 if (!HasPermission(PDFEngine::PERMISSION_COPY))
2287 return std::string();
2289 base::string16 result;
2290 base::string16 new_line_char = base::UTF8ToUTF16("\n");
2291 for (size_t i = 0; i < selection_.size(); ++i) {
2292 if (i > 0 &&
2293 selection_[i - 1].page_index() > selection_[i].page_index()) {
2294 result = selection_[i].GetText() + new_line_char + result;
2295 } else {
2296 if (i > 0)
2297 result.append(new_line_char);
2298 result.append(selection_[i].GetText());
2302 FormatStringWithHyphens(&result);
2303 FormatStringForOS(&result);
2304 return base::UTF16ToUTF8(result);
2307 std::string PDFiumEngine::GetLinkAtPosition(const pp::Point& point) {
2308 std::string url;
2309 int temp;
2310 int page_index = -1;
2311 int form_type = FPDF_FORMFIELD_UNKNOWN;
2312 PDFiumPage::LinkTarget target;
2313 PDFiumPage::Area area =
2314 GetCharIndex(point, &page_index, &temp, &form_type, &target);
2315 if (area == PDFiumPage::WEBLINK_AREA)
2316 url = target.url;
2317 return url;
2320 bool PDFiumEngine::IsSelecting() {
2321 return selecting_;
2324 bool PDFiumEngine::HasPermission(DocumentPermission permission) const {
2325 switch (permission) {
2326 case PERMISSION_COPY:
2327 return (permissions_ & kPDFPermissionCopyMask) != 0;
2328 case PERMISSION_COPY_ACCESSIBLE:
2329 return (permissions_ & kPDFPermissionCopyAccessibleMask) != 0;
2330 case PERMISSION_PRINT_LOW_QUALITY:
2331 return (permissions_ & kPDFPermissionPrintLowQualityMask) != 0;
2332 case PERMISSION_PRINT_HIGH_QUALITY:
2333 return (permissions_ & kPDFPermissionPrintLowQualityMask) != 0 &&
2334 (permissions_ & kPDFPermissionPrintHighQualityMask) != 0;
2335 default:
2336 return true;
2340 void PDFiumEngine::SelectAll() {
2341 SelectionChangeInvalidator selection_invalidator(this);
2343 selection_.clear();
2344 for (size_t i = 0; i < pages_.size(); ++i)
2345 if (pages_[i]->available()) {
2346 selection_.push_back(PDFiumRange(pages_[i], 0,
2347 pages_[i]->GetCharCount()));
2351 int PDFiumEngine::GetNumberOfPages() {
2352 return pages_.size();
2355 pp::VarArray PDFiumEngine::GetBookmarks() {
2356 pp::VarDictionary dict = TraverseBookmarks(doc_, NULL);
2357 // The root bookmark contains no useful information.
2358 return pp::VarArray(dict.Get(pp::Var("children")));
2361 int PDFiumEngine::GetNamedDestinationPage(const std::string& destination) {
2362 // Look for the destination.
2363 FPDF_DEST dest = FPDF_GetNamedDestByName(doc_, destination.c_str());
2364 if (!dest) {
2365 // Look for a bookmark with the same name.
2366 base::string16 destination_wide = base::UTF8ToUTF16(destination);
2367 FPDF_WIDESTRING destination_pdf_wide =
2368 reinterpret_cast<FPDF_WIDESTRING>(destination_wide.c_str());
2369 FPDF_BOOKMARK bookmark = FPDFBookmark_Find(doc_, destination_pdf_wide);
2370 if (!bookmark)
2371 return -1;
2372 dest = FPDFBookmark_GetDest(doc_, bookmark);
2374 return dest ? FPDFDest_GetPageIndex(doc_, dest) : -1;
2377 int PDFiumEngine::GetFirstVisiblePage() {
2378 CalculateVisiblePages();
2379 return first_visible_page_;
2382 int PDFiumEngine::GetMostVisiblePage() {
2383 CalculateVisiblePages();
2384 return most_visible_page_;
2387 pp::Rect PDFiumEngine::GetPageRect(int index) {
2388 pp::Rect rc(pages_[index]->rect());
2389 rc.Inset(-kPageShadowLeft, -kPageShadowTop,
2390 -kPageShadowRight, -kPageShadowBottom);
2391 return rc;
2394 pp::Rect PDFiumEngine::GetPageContentsRect(int index) {
2395 return GetScreenRect(pages_[index]->rect());
2398 void PDFiumEngine::PaintThumbnail(pp::ImageData* image_data, int index) {
2399 FPDF_BITMAP bitmap = FPDFBitmap_CreateEx(
2400 image_data->size().width(), image_data->size().height(),
2401 FPDFBitmap_BGRx, image_data->data(), image_data->stride());
2403 if (pages_[index]->available()) {
2404 FPDFBitmap_FillRect(bitmap, 0, 0, image_data->size().width(),
2405 image_data->size().height(), 0xFFFFFFFF);
2407 FPDF_RenderPageBitmap(
2408 bitmap, pages_[index]->GetPage(), 0, 0, image_data->size().width(),
2409 image_data->size().height(), 0, GetRenderingFlags());
2410 } else {
2411 FPDFBitmap_FillRect(bitmap, 0, 0, image_data->size().width(),
2412 image_data->size().height(), kPendingPageColor);
2415 FPDFBitmap_Destroy(bitmap);
2418 void PDFiumEngine::SetGrayscale(bool grayscale) {
2419 render_grayscale_ = grayscale;
2422 void PDFiumEngine::OnCallback(int id) {
2423 if (!timers_.count(id))
2424 return;
2426 timers_[id].second(id);
2427 if (timers_.count(id)) // The callback might delete the timer.
2428 client_->ScheduleCallback(id, timers_[id].first);
2431 std::string PDFiumEngine::GetPageAsJSON(int index) {
2432 if (!(HasPermission(PERMISSION_COPY) ||
2433 HasPermission(PERMISSION_COPY_ACCESSIBLE))) {
2434 return "{}";
2437 if (index < 0 || static_cast<size_t>(index) > pages_.size() - 1)
2438 return "{}";
2440 scoped_ptr<base::Value> node(
2441 pages_[index]->GetAccessibleContentAsValue(current_rotation_));
2442 std::string page_json;
2443 base::JSONWriter::Write(node.get(), &page_json);
2444 return page_json;
2447 bool PDFiumEngine::GetPrintScaling() {
2448 return !!FPDF_VIEWERREF_GetPrintScaling(doc_);
2451 int PDFiumEngine::GetCopiesToPrint() {
2452 return FPDF_VIEWERREF_GetNumCopies(doc_);
2455 int PDFiumEngine::GetDuplexType() {
2456 return static_cast<int>(FPDF_VIEWERREF_GetDuplex(doc_));
2459 bool PDFiumEngine::GetPageSizeAndUniformity(pp::Size* size) {
2460 if (pages_.empty())
2461 return false;
2463 pp::Size page_size = GetPageSize(0);
2464 for (size_t i = 1; i < pages_.size(); ++i) {
2465 if (page_size != GetPageSize(i))
2466 return false;
2469 // Convert |page_size| back to points.
2470 size->set_width(
2471 ConvertUnit(page_size.width(), kPixelsPerInch, kPointsPerInch));
2472 size->set_height(
2473 ConvertUnit(page_size.height(), kPixelsPerInch, kPointsPerInch));
2474 return true;
2477 void PDFiumEngine::AppendBlankPages(int num_pages) {
2478 DCHECK(num_pages != 0);
2480 if (!doc_)
2481 return;
2483 selection_.clear();
2484 pending_pages_.clear();
2486 // Delete all pages except the first one.
2487 while (pages_.size() > 1) {
2488 delete pages_.back();
2489 pages_.pop_back();
2490 FPDFPage_Delete(doc_, pages_.size());
2493 // Calculate document size and all page sizes.
2494 std::vector<pp::Rect> page_rects;
2495 pp::Size page_size = GetPageSize(0);
2496 page_size.Enlarge(kPageShadowLeft + kPageShadowRight,
2497 kPageShadowTop + kPageShadowBottom);
2498 pp::Size old_document_size = document_size_;
2499 document_size_ = pp::Size(page_size.width(), 0);
2500 for (int i = 0; i < num_pages; ++i) {
2501 if (i != 0) {
2502 // Add space for horizontal separator.
2503 document_size_.Enlarge(0, kPageSeparatorThickness);
2506 pp::Rect rect(pp::Point(0, document_size_.height()), page_size);
2507 page_rects.push_back(rect);
2509 document_size_.Enlarge(0, page_size.height());
2512 // Create blank pages.
2513 for (int i = 1; i < num_pages; ++i) {
2514 pp::Rect page_rect(page_rects[i]);
2515 page_rect.Inset(kPageShadowLeft, kPageShadowTop,
2516 kPageShadowRight, kPageShadowBottom);
2517 double width_in_points = ConvertUnitDouble(page_rect.width(),
2518 kPixelsPerInch,
2519 kPointsPerInch);
2520 double height_in_points = ConvertUnitDouble(page_rect.height(),
2521 kPixelsPerInch,
2522 kPointsPerInch);
2523 FPDFPage_New(doc_, i, width_in_points, height_in_points);
2524 pages_.push_back(new PDFiumPage(this, i, page_rect, true));
2527 CalculateVisiblePages();
2528 if (document_size_ != old_document_size)
2529 client_->DocumentSizeUpdated(document_size_);
2532 void PDFiumEngine::LoadDocument() {
2533 // Check if the document is ready for loading. If it isn't just bail for now,
2534 // we will call LoadDocument() again later.
2535 if (!doc_ && !doc_loader_.IsDocumentComplete() &&
2536 !FPDFAvail_IsDocAvail(fpdf_availability_, &download_hints_)) {
2537 return;
2540 // If we're in the middle of getting a password, just return. We will retry
2541 // loading the document after we get the password anyway.
2542 if (getting_password_)
2543 return;
2545 ScopedUnsupportedFeature scoped_unsupported_feature(this);
2546 bool needs_password = false;
2547 if (TryLoadingDoc(false, std::string(), &needs_password)) {
2548 ContinueLoadingDocument(false, std::string());
2549 return;
2551 if (needs_password)
2552 GetPasswordAndLoad();
2553 else
2554 client_->DocumentLoadFailed();
2557 bool PDFiumEngine::TryLoadingDoc(bool with_password,
2558 const std::string& password,
2559 bool* needs_password) {
2560 *needs_password = false;
2561 if (doc_)
2562 return true;
2564 const char* password_cstr = NULL;
2565 if (with_password) {
2566 password_cstr = password.c_str();
2567 password_tries_remaining_--;
2569 if (doc_loader_.IsDocumentComplete())
2570 doc_ = FPDF_LoadCustomDocument(&file_access_, password_cstr);
2571 else
2572 doc_ = FPDFAvail_GetDocument(fpdf_availability_, password_cstr);
2574 if (!doc_ && FPDF_GetLastError() == FPDF_ERR_PASSWORD)
2575 *needs_password = true;
2577 return doc_ != NULL;
2580 void PDFiumEngine::GetPasswordAndLoad() {
2581 getting_password_ = true;
2582 DCHECK(!doc_ && FPDF_GetLastError() == FPDF_ERR_PASSWORD);
2583 client_->GetDocumentPassword(password_factory_.NewCallbackWithOutput(
2584 &PDFiumEngine::OnGetPasswordComplete));
2587 void PDFiumEngine::OnGetPasswordComplete(int32_t result,
2588 const pp::Var& password) {
2589 getting_password_ = false;
2591 bool password_given = false;
2592 std::string password_text;
2593 if (result == PP_OK && password.is_string()) {
2594 password_text = password.AsString();
2595 if (!password_text.empty())
2596 password_given = true;
2598 ContinueLoadingDocument(password_given, password_text);
2601 void PDFiumEngine::ContinueLoadingDocument(
2602 bool has_password,
2603 const std::string& password) {
2604 ScopedUnsupportedFeature scoped_unsupported_feature(this);
2606 bool needs_password = false;
2607 bool loaded = TryLoadingDoc(has_password, password, &needs_password);
2608 bool password_incorrect = !loaded && has_password && needs_password;
2609 if (password_incorrect && password_tries_remaining_ > 0) {
2610 GetPasswordAndLoad();
2611 return;
2614 if (!doc_) {
2615 client_->DocumentLoadFailed();
2616 return;
2619 if (FPDFDoc_GetPageMode(doc_) == PAGEMODE_USEOUTLINES)
2620 client_->DocumentHasUnsupportedFeature("Bookmarks");
2622 permissions_ = FPDF_GetDocPermissions(doc_);
2624 if (!form_) {
2625 // Only returns 0 when data isn't available. If form data is downloaded, or
2626 // if this isn't a form, returns positive values.
2627 if (!doc_loader_.IsDocumentComplete() &&
2628 !FPDFAvail_IsFormAvail(fpdf_availability_, &download_hints_)) {
2629 return;
2632 form_ = FPDFDOC_InitFormFillEnvironment(
2633 doc_, static_cast<FPDF_FORMFILLINFO*>(this));
2634 #ifdef PDF_USE_XFA
2635 FPDF_LoadXFA(doc_);
2636 #endif
2638 FPDF_SetFormFieldHighlightColor(form_, 0, kFormHighlightColor);
2639 FPDF_SetFormFieldHighlightAlpha(form_, kFormHighlightAlpha);
2642 if (!doc_loader_.IsDocumentComplete()) {
2643 // Check if the first page is available. In a linearized PDF, that is not
2644 // always page 0. Doing this gives us the default page size, since when the
2645 // document is available, the first page is available as well.
2646 CheckPageAvailable(FPDFAvail_GetFirstPageNum(doc_), &pending_pages_);
2649 LoadPageInfo(false);
2651 if (doc_loader_.IsDocumentComplete())
2652 FinishLoadingDocument();
2655 void PDFiumEngine::LoadPageInfo(bool reload) {
2656 pending_pages_.clear();
2657 pp::Size old_document_size = document_size_;
2658 document_size_ = pp::Size();
2659 std::vector<pp::Rect> page_rects;
2660 int page_count = FPDF_GetPageCount(doc_);
2661 bool doc_complete = doc_loader_.IsDocumentComplete();
2662 for (int i = 0; i < page_count; ++i) {
2663 if (i != 0) {
2664 // Add space for horizontal separator.
2665 document_size_.Enlarge(0, kPageSeparatorThickness);
2668 // Get page availability. If reload==false, and document is not loaded yet
2669 // (we are using async loading) - mark all pages as unavailable.
2670 // If reload==true (we have document constructed already), get page
2671 // availability flag from already existing PDFiumPage class.
2672 bool page_available = reload ? pages_[i]->available() : doc_complete;
2674 pp::Size size = page_available ? GetPageSize(i) : default_page_size_;
2675 size.Enlarge(kPageShadowLeft + kPageShadowRight,
2676 kPageShadowTop + kPageShadowBottom);
2677 pp::Rect rect(pp::Point(0, document_size_.height()), size);
2678 page_rects.push_back(rect);
2680 if (size.width() > document_size_.width())
2681 document_size_.set_width(size.width());
2683 document_size_.Enlarge(0, size.height());
2686 for (int i = 0; i < page_count; ++i) {
2687 // Center pages relative to the entire document.
2688 page_rects[i].set_x((document_size_.width() - page_rects[i].width()) / 2);
2689 pp::Rect page_rect(page_rects[i]);
2690 page_rect.Inset(kPageShadowLeft, kPageShadowTop,
2691 kPageShadowRight, kPageShadowBottom);
2692 if (reload) {
2693 pages_[i]->set_rect(page_rect);
2694 } else {
2695 pages_.push_back(new PDFiumPage(this, i, page_rect, doc_complete));
2699 CalculateVisiblePages();
2700 if (document_size_ != old_document_size)
2701 client_->DocumentSizeUpdated(document_size_);
2704 void PDFiumEngine::CalculateVisiblePages() {
2705 // Clear pending requests queue, since it may contain requests to the pages
2706 // that are already invisible (after scrolling for example).
2707 pending_pages_.clear();
2708 doc_loader_.ClearPendingRequests();
2710 visible_pages_.clear();
2711 pp::Rect visible_rect(plugin_size_);
2712 for (size_t i = 0; i < pages_.size(); ++i) {
2713 // Check an entire PageScreenRect, since we might need to repaint side
2714 // borders and shadows even if the page itself is not visible.
2715 // For example, when user use pdf with different page sizes and zoomed in
2716 // outside page area.
2717 if (visible_rect.Intersects(GetPageScreenRect(i))) {
2718 visible_pages_.push_back(i);
2719 CheckPageAvailable(i, &pending_pages_);
2720 } else {
2721 // Need to unload pages when we're not using them, since some PDFs use a
2722 // lot of memory. See http://crbug.com/48791
2723 if (defer_page_unload_) {
2724 deferred_page_unloads_.push_back(i);
2725 } else {
2726 pages_[i]->Unload();
2729 // If the last mouse down was on a page that's no longer visible, reset
2730 // that variable so that we don't send keyboard events to it (the focus
2731 // will be lost when the page is first closed anyways).
2732 if (static_cast<int>(i) == last_page_mouse_down_)
2733 last_page_mouse_down_ = -1;
2737 // Any pending highlighting of form fields will be invalid since these are in
2738 // screen coordinates.
2739 form_highlights_.clear();
2741 if (visible_pages_.size() == 0)
2742 first_visible_page_ = -1;
2743 else
2744 first_visible_page_ = visible_pages_.front();
2746 int most_visible_page = first_visible_page_;
2747 // Check if the next page is more visible than the first one.
2748 if (most_visible_page != -1 &&
2749 pages_.size() > 0 &&
2750 most_visible_page < static_cast<int>(pages_.size()) - 1) {
2751 pp::Rect rc_first =
2752 visible_rect.Intersect(GetPageScreenRect(most_visible_page));
2753 pp::Rect rc_next =
2754 visible_rect.Intersect(GetPageScreenRect(most_visible_page + 1));
2755 if (rc_next.height() > rc_first.height())
2756 most_visible_page++;
2759 SetCurrentPage(most_visible_page);
2762 bool PDFiumEngine::IsPageVisible(int index) const {
2763 for (size_t i = 0; i < visible_pages_.size(); ++i) {
2764 if (visible_pages_[i] == index)
2765 return true;
2768 return false;
2771 bool PDFiumEngine::CheckPageAvailable(int index, std::vector<int>* pending) {
2772 if (!doc_ || !form_)
2773 return false;
2775 if (static_cast<int>(pages_.size()) > index && pages_[index]->available())
2776 return true;
2778 if (!FPDFAvail_IsPageAvail(fpdf_availability_, index, &download_hints_)) {
2779 size_t j;
2780 for (j = 0; j < pending->size(); ++j) {
2781 if ((*pending)[j] == index)
2782 break;
2785 if (j == pending->size())
2786 pending->push_back(index);
2787 return false;
2790 if (static_cast<int>(pages_.size()) > index)
2791 pages_[index]->set_available(true);
2792 if (!default_page_size_.GetArea())
2793 default_page_size_ = GetPageSize(index);
2794 return true;
2797 pp::Size PDFiumEngine::GetPageSize(int index) {
2798 pp::Size size;
2799 double width_in_points = 0;
2800 double height_in_points = 0;
2801 int rv = FPDF_GetPageSizeByIndex(
2802 doc_, index, &width_in_points, &height_in_points);
2804 if (rv) {
2805 int width_in_pixels = static_cast<int>(
2806 ConvertUnitDouble(width_in_points, kPointsPerInch, kPixelsPerInch));
2807 int height_in_pixels = static_cast<int>(
2808 ConvertUnitDouble(height_in_points, kPointsPerInch, kPixelsPerInch));
2809 if (current_rotation_ % 2 == 1)
2810 std::swap(width_in_pixels, height_in_pixels);
2811 size = pp::Size(width_in_pixels, height_in_pixels);
2813 return size;
2816 int PDFiumEngine::StartPaint(int page_index, const pp::Rect& dirty) {
2817 // For the first time we hit paint, do nothing and just record the paint for
2818 // the next callback. This keeps the UI responsive in case the user is doing
2819 // a lot of scrolling.
2820 ProgressivePaint progressive;
2821 progressive.rect = dirty;
2822 progressive.page_index = page_index;
2823 progressive.bitmap = NULL;
2824 progressive.painted_ = false;
2825 progressive_paints_.push_back(progressive);
2826 return progressive_paints_.size() - 1;
2829 bool PDFiumEngine::ContinuePaint(int progressive_index,
2830 pp::ImageData* image_data) {
2831 DCHECK_GE(progressive_index, 0);
2832 DCHECK_LT(static_cast<size_t>(progressive_index), progressive_paints_.size());
2833 DCHECK(image_data);
2835 #if defined(OS_LINUX)
2836 g_last_instance_id = client_->GetPluginInstance()->pp_instance();
2837 #endif
2839 int rv;
2840 FPDF_BITMAP bitmap = progressive_paints_[progressive_index].bitmap;
2841 int page_index = progressive_paints_[progressive_index].page_index;
2842 DCHECK_GE(page_index, 0);
2843 DCHECK_LT(static_cast<size_t>(page_index), pages_.size());
2844 FPDF_PAGE page = pages_[page_index]->GetPage();
2846 last_progressive_start_time_ = base::Time::Now();
2847 if (bitmap) {
2848 rv = FPDF_RenderPage_Continue(page, static_cast<IFSDK_PAUSE*>(this));
2849 } else {
2850 pp::Rect dirty = progressive_paints_[progressive_index].rect;
2851 bitmap = CreateBitmap(dirty, image_data);
2852 int start_x, start_y, size_x, size_y;
2853 GetPDFiumRect(page_index, dirty, &start_x, &start_y, &size_x, &size_y);
2854 FPDFBitmap_FillRect(bitmap, start_x, start_y, size_x, size_y, 0xFFFFFFFF);
2855 rv = FPDF_RenderPageBitmap_Start(
2856 bitmap, page, start_x, start_y, size_x, size_y,
2857 current_rotation_,
2858 GetRenderingFlags(), static_cast<IFSDK_PAUSE*>(this));
2859 progressive_paints_[progressive_index].bitmap = bitmap;
2861 return rv != FPDF_RENDER_TOBECOUNTINUED;
2864 void PDFiumEngine::FinishPaint(int progressive_index,
2865 pp::ImageData* image_data) {
2866 DCHECK_GE(progressive_index, 0);
2867 DCHECK_LT(static_cast<size_t>(progressive_index), progressive_paints_.size());
2868 DCHECK(image_data);
2870 int page_index = progressive_paints_[progressive_index].page_index;
2871 pp::Rect dirty_in_screen = progressive_paints_[progressive_index].rect;
2872 FPDF_BITMAP bitmap = progressive_paints_[progressive_index].bitmap;
2873 int start_x, start_y, size_x, size_y;
2874 GetPDFiumRect(
2875 page_index, dirty_in_screen, &start_x, &start_y, &size_x, &size_y);
2877 // Draw the forms.
2878 FPDF_FFLDraw(
2879 form_, bitmap, pages_[page_index]->GetPage(), start_x, start_y, size_x,
2880 size_y, current_rotation_, GetRenderingFlags());
2882 FillPageSides(progressive_index);
2884 // Paint the page shadows.
2885 PaintPageShadow(progressive_index, image_data);
2887 DrawSelections(progressive_index, image_data);
2889 FPDF_RenderPage_Close(pages_[page_index]->GetPage());
2890 FPDFBitmap_Destroy(bitmap);
2891 progressive_paints_.erase(progressive_paints_.begin() + progressive_index);
2893 client_->DocumentPaintOccurred();
2896 void PDFiumEngine::CancelPaints() {
2897 for (size_t i = 0; i < progressive_paints_.size(); ++i) {
2898 FPDF_RenderPage_Close(pages_[progressive_paints_[i].page_index]->GetPage());
2899 FPDFBitmap_Destroy(progressive_paints_[i].bitmap);
2901 progressive_paints_.clear();
2904 void PDFiumEngine::FillPageSides(int progressive_index) {
2905 DCHECK_GE(progressive_index, 0);
2906 DCHECK_LT(static_cast<size_t>(progressive_index), progressive_paints_.size());
2908 int page_index = progressive_paints_[progressive_index].page_index;
2909 pp::Rect dirty_in_screen = progressive_paints_[progressive_index].rect;
2910 FPDF_BITMAP bitmap = progressive_paints_[progressive_index].bitmap;
2912 pp::Rect page_rect = pages_[page_index]->rect();
2913 if (page_rect.x() > 0) {
2914 pp::Rect left(0,
2915 page_rect.y() - kPageShadowTop,
2916 page_rect.x() - kPageShadowLeft,
2917 page_rect.height() + kPageShadowTop +
2918 kPageShadowBottom + kPageSeparatorThickness);
2919 left = GetScreenRect(left).Intersect(dirty_in_screen);
2921 FPDFBitmap_FillRect(bitmap, left.x() - dirty_in_screen.x(),
2922 left.y() - dirty_in_screen.y(), left.width(),
2923 left.height(), client_->GetBackgroundColor());
2926 if (page_rect.right() < document_size_.width()) {
2927 pp::Rect right(page_rect.right() + kPageShadowRight,
2928 page_rect.y() - kPageShadowTop,
2929 document_size_.width() - page_rect.right() -
2930 kPageShadowRight,
2931 page_rect.height() + kPageShadowTop +
2932 kPageShadowBottom + kPageSeparatorThickness);
2933 right = GetScreenRect(right).Intersect(dirty_in_screen);
2935 FPDFBitmap_FillRect(bitmap, right.x() - dirty_in_screen.x(),
2936 right.y() - dirty_in_screen.y(), right.width(),
2937 right.height(), client_->GetBackgroundColor());
2940 // Paint separator.
2941 pp::Rect bottom(page_rect.x() - kPageShadowLeft,
2942 page_rect.bottom() + kPageShadowBottom,
2943 page_rect.width() + kPageShadowLeft + kPageShadowRight,
2944 kPageSeparatorThickness);
2945 bottom = GetScreenRect(bottom).Intersect(dirty_in_screen);
2947 FPDFBitmap_FillRect(bitmap, bottom.x() - dirty_in_screen.x(),
2948 bottom.y() - dirty_in_screen.y(), bottom.width(),
2949 bottom.height(), client_->GetBackgroundColor());
2952 void PDFiumEngine::PaintPageShadow(int progressive_index,
2953 pp::ImageData* image_data) {
2954 DCHECK_GE(progressive_index, 0);
2955 DCHECK_LT(static_cast<size_t>(progressive_index), progressive_paints_.size());
2956 DCHECK(image_data);
2958 int page_index = progressive_paints_[progressive_index].page_index;
2959 pp::Rect dirty_in_screen = progressive_paints_[progressive_index].rect;
2960 pp::Rect page_rect = pages_[page_index]->rect();
2961 pp::Rect shadow_rect(page_rect);
2962 shadow_rect.Inset(-kPageShadowLeft, -kPageShadowTop,
2963 -kPageShadowRight, -kPageShadowBottom);
2965 // Due to the rounding errors of the GetScreenRect it is possible to get
2966 // different size shadows on the left and right sides even they are defined
2967 // the same. To fix this issue let's calculate shadow rect and then shrink
2968 // it by the size of the shadows.
2969 shadow_rect = GetScreenRect(shadow_rect);
2970 page_rect = shadow_rect;
2972 page_rect.Inset(static_cast<int>(ceil(kPageShadowLeft * current_zoom_)),
2973 static_cast<int>(ceil(kPageShadowTop * current_zoom_)),
2974 static_cast<int>(ceil(kPageShadowRight * current_zoom_)),
2975 static_cast<int>(ceil(kPageShadowBottom * current_zoom_)));
2977 DrawPageShadow(page_rect, shadow_rect, dirty_in_screen, image_data);
2980 void PDFiumEngine::DrawSelections(int progressive_index,
2981 pp::ImageData* image_data) {
2982 DCHECK_GE(progressive_index, 0);
2983 DCHECK_LT(static_cast<size_t>(progressive_index), progressive_paints_.size());
2984 DCHECK(image_data);
2986 int page_index = progressive_paints_[progressive_index].page_index;
2987 pp::Rect dirty_in_screen = progressive_paints_[progressive_index].rect;
2989 void* region = NULL;
2990 int stride;
2991 GetRegion(dirty_in_screen.point(), image_data, &region, &stride);
2993 std::vector<pp::Rect> highlighted_rects;
2994 pp::Rect visible_rect = GetVisibleRect();
2995 for (size_t k = 0; k < selection_.size(); ++k) {
2996 if (selection_[k].page_index() != page_index)
2997 continue;
2998 std::vector<pp::Rect> rects = selection_[k].GetScreenRects(
2999 visible_rect.point(), current_zoom_, current_rotation_);
3000 for (size_t j = 0; j < rects.size(); ++j) {
3001 pp::Rect visible_selection = rects[j].Intersect(dirty_in_screen);
3002 if (visible_selection.IsEmpty())
3003 continue;
3005 visible_selection.Offset(
3006 -dirty_in_screen.point().x(), -dirty_in_screen.point().y());
3007 Highlight(region, stride, visible_selection, &highlighted_rects);
3011 for (size_t k = 0; k < form_highlights_.size(); ++k) {
3012 pp::Rect visible_selection = form_highlights_[k].Intersect(dirty_in_screen);
3013 if (visible_selection.IsEmpty())
3014 continue;
3016 visible_selection.Offset(
3017 -dirty_in_screen.point().x(), -dirty_in_screen.point().y());
3018 Highlight(region, stride, visible_selection, &highlighted_rects);
3020 form_highlights_.clear();
3023 void PDFiumEngine::PaintUnavailablePage(int page_index,
3024 const pp::Rect& dirty,
3025 pp::ImageData* image_data) {
3026 int start_x, start_y, size_x, size_y;
3027 GetPDFiumRect(page_index, dirty, &start_x, &start_y, &size_x, &size_y);
3028 FPDF_BITMAP bitmap = CreateBitmap(dirty, image_data);
3029 FPDFBitmap_FillRect(bitmap, start_x, start_y, size_x, size_y,
3030 kPendingPageColor);
3032 pp::Rect loading_text_in_screen(
3033 pages_[page_index]->rect().width() / 2,
3034 pages_[page_index]->rect().y() + kLoadingTextVerticalOffset, 0, 0);
3035 loading_text_in_screen = GetScreenRect(loading_text_in_screen);
3036 FPDFBitmap_Destroy(bitmap);
3039 int PDFiumEngine::GetProgressiveIndex(int page_index) const {
3040 for (size_t i = 0; i < progressive_paints_.size(); ++i) {
3041 if (progressive_paints_[i].page_index == page_index)
3042 return i;
3044 return -1;
3047 FPDF_BITMAP PDFiumEngine::CreateBitmap(const pp::Rect& rect,
3048 pp::ImageData* image_data) const {
3049 void* region;
3050 int stride;
3051 GetRegion(rect.point(), image_data, &region, &stride);
3052 if (!region)
3053 return NULL;
3054 return FPDFBitmap_CreateEx(
3055 rect.width(), rect.height(), FPDFBitmap_BGRx, region, stride);
3058 void PDFiumEngine::GetPDFiumRect(
3059 int page_index, const pp::Rect& rect, int* start_x, int* start_y,
3060 int* size_x, int* size_y) const {
3061 pp::Rect page_rect = GetScreenRect(pages_[page_index]->rect());
3062 page_rect.Offset(-rect.x(), -rect.y());
3064 *start_x = page_rect.x();
3065 *start_y = page_rect.y();
3066 *size_x = page_rect.width();
3067 *size_y = page_rect.height();
3070 int PDFiumEngine::GetRenderingFlags() const {
3071 int flags = FPDF_LCD_TEXT | FPDF_NO_CATCH;
3072 if (render_grayscale_)
3073 flags |= FPDF_GRAYSCALE;
3074 if (client_->IsPrintPreview())
3075 flags |= FPDF_PRINTING;
3076 return flags;
3079 pp::Rect PDFiumEngine::GetVisibleRect() const {
3080 pp::Rect rv;
3081 rv.set_x(static_cast<int>(position_.x() / current_zoom_));
3082 rv.set_y(static_cast<int>(position_.y() / current_zoom_));
3083 rv.set_width(static_cast<int>(ceil(plugin_size_.width() / current_zoom_)));
3084 rv.set_height(static_cast<int>(ceil(plugin_size_.height() / current_zoom_)));
3085 return rv;
3088 pp::Rect PDFiumEngine::GetPageScreenRect(int page_index) const {
3089 // Since we use this rect for creating the PDFium bitmap, also include other
3090 // areas around the page that we might need to update such as the page
3091 // separator and the sides if the page is narrower than the document.
3092 return GetScreenRect(pp::Rect(
3094 pages_[page_index]->rect().y() - kPageShadowTop,
3095 document_size_.width(),
3096 pages_[page_index]->rect().height() + kPageShadowTop +
3097 kPageShadowBottom + kPageSeparatorThickness));
3100 pp::Rect PDFiumEngine::GetScreenRect(const pp::Rect& rect) const {
3101 pp::Rect rv;
3102 int right =
3103 static_cast<int>(ceil(rect.right() * current_zoom_ - position_.x()));
3104 int bottom =
3105 static_cast<int>(ceil(rect.bottom() * current_zoom_ - position_.y()));
3107 rv.set_x(static_cast<int>(rect.x() * current_zoom_ - position_.x()));
3108 rv.set_y(static_cast<int>(rect.y() * current_zoom_ - position_.y()));
3109 rv.set_width(right - rv.x());
3110 rv.set_height(bottom - rv.y());
3111 return rv;
3114 void PDFiumEngine::Highlight(void* buffer,
3115 int stride,
3116 const pp::Rect& rect,
3117 std::vector<pp::Rect>* highlighted_rects) {
3118 if (!buffer)
3119 return;
3121 pp::Rect new_rect = rect;
3122 for (size_t i = 0; i < highlighted_rects->size(); ++i)
3123 new_rect = new_rect.Subtract((*highlighted_rects)[i]);
3125 highlighted_rects->push_back(new_rect);
3126 int l = new_rect.x();
3127 int t = new_rect.y();
3128 int w = new_rect.width();
3129 int h = new_rect.height();
3131 for (int y = t; y < t + h; ++y) {
3132 for (int x = l; x < l + w; ++x) {
3133 uint8* pixel = static_cast<uint8*>(buffer) + y * stride + x * 4;
3134 // This is our highlight color.
3135 pixel[0] = static_cast<uint8>(
3136 pixel[0] * (kHighlightColorB / 255.0));
3137 pixel[1] = static_cast<uint8>(
3138 pixel[1] * (kHighlightColorG / 255.0));
3139 pixel[2] = static_cast<uint8>(
3140 pixel[2] * (kHighlightColorR / 255.0));
3145 PDFiumEngine::SelectionChangeInvalidator::SelectionChangeInvalidator(
3146 PDFiumEngine* engine) : engine_(engine) {
3147 previous_origin_ = engine_->GetVisibleRect().point();
3148 GetVisibleSelectionsScreenRects(&old_selections_);
3151 PDFiumEngine::SelectionChangeInvalidator::~SelectionChangeInvalidator() {
3152 // Offset the old selections if the document scrolled since we recorded them.
3153 pp::Point offset = previous_origin_ - engine_->GetVisibleRect().point();
3154 for (size_t i = 0; i < old_selections_.size(); ++i)
3155 old_selections_[i].Offset(offset);
3157 std::vector<pp::Rect> new_selections;
3158 GetVisibleSelectionsScreenRects(&new_selections);
3159 for (size_t i = 0; i < new_selections.size(); ++i) {
3160 for (size_t j = 0; j < old_selections_.size(); ++j) {
3161 if (!old_selections_[j].IsEmpty() &&
3162 new_selections[i] == old_selections_[j]) {
3163 // Rectangle was selected before and after, so no need to invalidate it.
3164 // Mark the rectangles by setting them to empty.
3165 new_selections[i] = old_selections_[j] = pp::Rect();
3166 break;
3171 for (size_t i = 0; i < old_selections_.size(); ++i) {
3172 if (!old_selections_[i].IsEmpty())
3173 engine_->client_->Invalidate(old_selections_[i]);
3175 for (size_t i = 0; i < new_selections.size(); ++i) {
3176 if (!new_selections[i].IsEmpty())
3177 engine_->client_->Invalidate(new_selections[i]);
3179 engine_->OnSelectionChanged();
3182 void
3183 PDFiumEngine::SelectionChangeInvalidator::GetVisibleSelectionsScreenRects(
3184 std::vector<pp::Rect>* rects) {
3185 pp::Rect visible_rect = engine_->GetVisibleRect();
3186 for (size_t i = 0; i < engine_->selection_.size(); ++i) {
3187 int page_index = engine_->selection_[i].page_index();
3188 if (!engine_->IsPageVisible(page_index))
3189 continue; // This selection is on a page that's not currently visible.
3191 std::vector<pp::Rect> selection_rects =
3192 engine_->selection_[i].GetScreenRects(
3193 visible_rect.point(),
3194 engine_->current_zoom_,
3195 engine_->current_rotation_);
3196 rects->insert(rects->end(), selection_rects.begin(), selection_rects.end());
3200 PDFiumEngine::MouseDownState::MouseDownState(
3201 const PDFiumPage::Area& area,
3202 const PDFiumPage::LinkTarget& target)
3203 : area_(area), target_(target) {
3206 PDFiumEngine::MouseDownState::~MouseDownState() {
3209 void PDFiumEngine::MouseDownState::Set(const PDFiumPage::Area& area,
3210 const PDFiumPage::LinkTarget& target) {
3211 area_ = area;
3212 target_ = target;
3215 void PDFiumEngine::MouseDownState::Reset() {
3216 area_ = PDFiumPage::NONSELECTABLE_AREA;
3217 target_ = PDFiumPage::LinkTarget();
3220 bool PDFiumEngine::MouseDownState::Matches(
3221 const PDFiumPage::Area& area,
3222 const PDFiumPage::LinkTarget& target) const {
3223 if (area_ == area) {
3224 if (area == PDFiumPage::WEBLINK_AREA)
3225 return target_.url == target.url;
3226 if (area == PDFiumPage::DOCLINK_AREA)
3227 return target_.page == target.page;
3228 return true;
3230 return false;
3233 PDFiumEngine::FindTextIndex::FindTextIndex()
3234 : valid_(false), index_(0) {
3237 PDFiumEngine::FindTextIndex::~FindTextIndex() {
3240 void PDFiumEngine::FindTextIndex::Invalidate() {
3241 valid_ = false;
3244 size_t PDFiumEngine::FindTextIndex::GetIndex() const {
3245 DCHECK(valid_);
3246 return index_;
3249 void PDFiumEngine::FindTextIndex::SetIndex(size_t index) {
3250 valid_ = true;
3251 index_ = index;
3254 size_t PDFiumEngine::FindTextIndex::IncrementIndex() {
3255 DCHECK(valid_);
3256 return ++index_;
3259 void PDFiumEngine::DeviceToPage(int page_index,
3260 float device_x,
3261 float device_y,
3262 double* page_x,
3263 double* page_y) {
3264 *page_x = *page_y = 0;
3265 int temp_x = static_cast<int>((device_x + position_.x())/ current_zoom_ -
3266 pages_[page_index]->rect().x());
3267 int temp_y = static_cast<int>((device_y + position_.y())/ current_zoom_ -
3268 pages_[page_index]->rect().y());
3269 FPDF_DeviceToPage(
3270 pages_[page_index]->GetPage(), 0, 0,
3271 pages_[page_index]->rect().width(), pages_[page_index]->rect().height(),
3272 current_rotation_, temp_x, temp_y, page_x, page_y);
3275 int PDFiumEngine::GetVisiblePageIndex(FPDF_PAGE page) {
3276 for (size_t i = 0; i < visible_pages_.size(); ++i) {
3277 if (pages_[visible_pages_[i]]->GetPage() == page)
3278 return visible_pages_[i];
3280 return -1;
3283 void PDFiumEngine::SetCurrentPage(int index) {
3284 if (index == most_visible_page_ || !form_)
3285 return;
3286 if (most_visible_page_ != -1 && called_do_document_action_) {
3287 FPDF_PAGE old_page = pages_[most_visible_page_]->GetPage();
3288 FORM_DoPageAAction(old_page, form_, FPDFPAGE_AACTION_CLOSE);
3290 most_visible_page_ = index;
3291 #if defined(OS_LINUX)
3292 g_last_instance_id = client_->GetPluginInstance()->pp_instance();
3293 #endif
3294 if (most_visible_page_ != -1 && called_do_document_action_) {
3295 FPDF_PAGE new_page = pages_[most_visible_page_]->GetPage();
3296 FORM_DoPageAAction(new_page, form_, FPDFPAGE_AACTION_OPEN);
3300 void PDFiumEngine::TransformPDFPageForPrinting(
3301 FPDF_PAGE page,
3302 const PP_PrintSettings_Dev& print_settings) {
3303 // Get the source page width and height in points.
3304 const double src_page_width = FPDF_GetPageWidth(page);
3305 const double src_page_height = FPDF_GetPageHeight(page);
3307 const int src_page_rotation = FPDFPage_GetRotation(page);
3308 const bool fit_to_page = print_settings.print_scaling_option ==
3309 PP_PRINTSCALINGOPTION_FIT_TO_PRINTABLE_AREA;
3311 pp::Size page_size(print_settings.paper_size);
3312 pp::Rect content_rect(print_settings.printable_area);
3313 const bool rotated = (src_page_rotation % 2 == 1);
3314 SetPageSizeAndContentRect(rotated,
3315 src_page_width > src_page_height,
3316 &page_size,
3317 &content_rect);
3319 // Compute the screen page width and height in points.
3320 const int actual_page_width =
3321 rotated ? page_size.height() : page_size.width();
3322 const int actual_page_height =
3323 rotated ? page_size.width() : page_size.height();
3325 const double scale_factor = CalculateScaleFactor(fit_to_page, content_rect,
3326 src_page_width,
3327 src_page_height, rotated);
3329 // Calculate positions for the clip box.
3330 ClipBox source_clip_box;
3331 CalculateClipBoxBoundary(page, scale_factor, rotated, &source_clip_box);
3333 // Calculate the translation offset values.
3334 double offset_x = 0;
3335 double offset_y = 0;
3336 if (fit_to_page) {
3337 CalculateScaledClipBoxOffset(content_rect, source_clip_box, &offset_x,
3338 &offset_y);
3339 } else {
3340 CalculateNonScaledClipBoxOffset(content_rect, src_page_rotation,
3341 actual_page_width, actual_page_height,
3342 source_clip_box, &offset_x, &offset_y);
3345 // Reset the media box and crop box. When the page has crop box and media box,
3346 // the plugin will display the crop box contents and not the entire media box.
3347 // If the pages have different crop box values, the plugin will display a
3348 // document of multiple page sizes. To give better user experience, we
3349 // decided to have same crop box and media box values. Hence, the user will
3350 // see a list of uniform pages.
3351 FPDFPage_SetMediaBox(page, 0, 0, page_size.width(), page_size.height());
3352 FPDFPage_SetCropBox(page, 0, 0, page_size.width(), page_size.height());
3354 // Transformation is not required, return. Do this check only after updating
3355 // the media box and crop box. For more detailed information, please refer to
3356 // the comment block right before FPDF_SetMediaBox and FPDF_GetMediaBox calls.
3357 if (scale_factor == 1.0 && offset_x == 0 && offset_y == 0)
3358 return;
3361 // All the positions have been calculated, now manipulate the PDF.
3362 FS_MATRIX matrix = {static_cast<float>(scale_factor),
3365 static_cast<float>(scale_factor),
3366 static_cast<float>(offset_x),
3367 static_cast<float>(offset_y)};
3368 FS_RECTF cliprect = {static_cast<float>(source_clip_box.left+offset_x),
3369 static_cast<float>(source_clip_box.top+offset_y),
3370 static_cast<float>(source_clip_box.right+offset_x),
3371 static_cast<float>(source_clip_box.bottom+offset_y)};
3372 FPDFPage_TransFormWithClip(page, &matrix, &cliprect);
3373 FPDFPage_TransformAnnots(page, scale_factor, 0, 0, scale_factor,
3374 offset_x, offset_y);
3377 void PDFiumEngine::DrawPageShadow(const pp::Rect& page_rc,
3378 const pp::Rect& shadow_rc,
3379 const pp::Rect& clip_rc,
3380 pp::ImageData* image_data) {
3381 pp::Rect page_rect(page_rc);
3382 page_rect.Offset(page_offset_);
3384 pp::Rect shadow_rect(shadow_rc);
3385 shadow_rect.Offset(page_offset_);
3387 pp::Rect clip_rect(clip_rc);
3388 clip_rect.Offset(page_offset_);
3390 // Page drop shadow parameters.
3391 const double factor = 0.5;
3392 uint32 depth = std::max(
3393 std::max(page_rect.x() - shadow_rect.x(),
3394 page_rect.y() - shadow_rect.y()),
3395 std::max(shadow_rect.right() - page_rect.right(),
3396 shadow_rect.bottom() - page_rect.bottom()));
3397 depth = static_cast<uint32>(depth * 1.5) + 1;
3399 // We need to check depth only to verify our copy of shadow matrix is correct.
3400 if (!page_shadow_.get() || page_shadow_->depth() != depth)
3401 page_shadow_.reset(new ShadowMatrix(depth, factor,
3402 client_->GetBackgroundColor()));
3404 DCHECK(!image_data->is_null());
3405 DrawShadow(image_data, shadow_rect, page_rect, clip_rect, *page_shadow_);
3408 void PDFiumEngine::GetRegion(const pp::Point& location,
3409 pp::ImageData* image_data,
3410 void** region,
3411 int* stride) const {
3412 if (image_data->is_null()) {
3413 DCHECK(plugin_size_.IsEmpty());
3414 *stride = 0;
3415 *region = NULL;
3416 return;
3418 char* buffer = static_cast<char*>(image_data->data());
3419 *stride = image_data->stride();
3421 pp::Point offset_location = location + page_offset_;
3422 // TODO: update this when we support BIDI and scrollbars can be on the left.
3423 if (!buffer ||
3424 !pp::Rect(page_offset_, plugin_size_).Contains(offset_location)) {
3425 *region = NULL;
3426 return;
3429 buffer += location.y() * (*stride);
3430 buffer += (location.x() + page_offset_.x()) * 4;
3431 *region = buffer;
3434 void PDFiumEngine::OnSelectionChanged() {
3435 pp::PDF::SetSelectedText(GetPluginInstance(), GetSelectedText().c_str());
3438 void PDFiumEngine::RotateInternal() {
3439 // Store the current find index so that we can resume finding at that
3440 // particular index after we have recomputed the find results.
3441 std::string current_find_text = current_find_text_;
3442 if (current_find_index_.valid())
3443 resume_find_index_.SetIndex(current_find_index_.GetIndex());
3444 else
3445 resume_find_index_.Invalidate();
3447 InvalidateAllPages();
3449 if (!current_find_text.empty()) {
3450 // Clear the UI.
3451 client_->NotifyNumberOfFindResultsChanged(0, false);
3452 StartFind(current_find_text.c_str(), false);
3456 void PDFiumEngine::SetSelecting(bool selecting) {
3457 bool was_selecting = selecting_;
3458 selecting_ = selecting;
3459 if (selecting_ != was_selecting)
3460 client_->IsSelectingChanged(selecting);
3463 void PDFiumEngine::Form_Invalidate(FPDF_FORMFILLINFO* param,
3464 FPDF_PAGE page,
3465 double left,
3466 double top,
3467 double right,
3468 double bottom) {
3469 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3470 int page_index = engine->GetVisiblePageIndex(page);
3471 if (page_index == -1) {
3472 // This can sometime happen when the page is closed because it went off
3473 // screen, and PDFium invalidates the control as it's being deleted.
3474 return;
3477 pp::Rect rect = engine->pages_[page_index]->PageToScreen(
3478 engine->GetVisibleRect().point(), engine->current_zoom_, left, top, right,
3479 bottom, engine->current_rotation_);
3480 engine->client_->Invalidate(rect);
3483 void PDFiumEngine::Form_OutputSelectedRect(FPDF_FORMFILLINFO* param,
3484 FPDF_PAGE page,
3485 double left,
3486 double top,
3487 double right,
3488 double bottom) {
3489 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3490 int page_index = engine->GetVisiblePageIndex(page);
3491 if (page_index == -1) {
3492 NOTREACHED();
3493 return;
3495 pp::Rect rect = engine->pages_[page_index]->PageToScreen(
3496 engine->GetVisibleRect().point(), engine->current_zoom_, left, top, right,
3497 bottom, engine->current_rotation_);
3498 engine->form_highlights_.push_back(rect);
3501 void PDFiumEngine::Form_SetCursor(FPDF_FORMFILLINFO* param, int cursor_type) {
3502 // We don't need this since it's not enough to change the cursor in all
3503 // scenarios. Instead, we check which form field we're under in OnMouseMove.
3506 int PDFiumEngine::Form_SetTimer(FPDF_FORMFILLINFO* param,
3507 int elapse,
3508 TimerCallback timer_func) {
3509 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3510 engine->timers_[++engine->next_timer_id_] =
3511 std::pair<int, TimerCallback>(elapse, timer_func);
3512 engine->client_->ScheduleCallback(engine->next_timer_id_, elapse);
3513 return engine->next_timer_id_;
3516 void PDFiumEngine::Form_KillTimer(FPDF_FORMFILLINFO* param, int timer_id) {
3517 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3518 engine->timers_.erase(timer_id);
3521 FPDF_SYSTEMTIME PDFiumEngine::Form_GetLocalTime(FPDF_FORMFILLINFO* param) {
3522 base::Time time = base::Time::Now();
3523 base::Time::Exploded exploded;
3524 time.LocalExplode(&exploded);
3526 FPDF_SYSTEMTIME rv;
3527 rv.wYear = exploded.year;
3528 rv.wMonth = exploded.month;
3529 rv.wDayOfWeek = exploded.day_of_week;
3530 rv.wDay = exploded.day_of_month;
3531 rv.wHour = exploded.hour;
3532 rv.wMinute = exploded.minute;
3533 rv.wSecond = exploded.second;
3534 rv.wMilliseconds = exploded.millisecond;
3535 return rv;
3538 void PDFiumEngine::Form_OnChange(FPDF_FORMFILLINFO* param) {
3539 // Don't care about.
3542 FPDF_PAGE PDFiumEngine::Form_GetPage(FPDF_FORMFILLINFO* param,
3543 FPDF_DOCUMENT document,
3544 int page_index) {
3545 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3546 if (page_index < 0 || page_index >= static_cast<int>(engine->pages_.size()))
3547 return NULL;
3548 return engine->pages_[page_index]->GetPage();
3551 FPDF_PAGE PDFiumEngine::Form_GetCurrentPage(FPDF_FORMFILLINFO* param,
3552 FPDF_DOCUMENT document) {
3553 // TODO(jam): find out what this is used for.
3554 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3555 int index = engine->last_page_mouse_down_;
3556 if (index == -1) {
3557 index = engine->GetMostVisiblePage();
3558 if (index == -1) {
3559 NOTREACHED();
3560 return NULL;
3564 return engine->pages_[index]->GetPage();
3567 int PDFiumEngine::Form_GetRotation(FPDF_FORMFILLINFO* param, FPDF_PAGE page) {
3568 return 0;
3571 void PDFiumEngine::Form_ExecuteNamedAction(FPDF_FORMFILLINFO* param,
3572 FPDF_BYTESTRING named_action) {
3573 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3574 std::string action(named_action);
3575 if (action == "Print") {
3576 engine->client_->Print();
3577 return;
3580 int index = engine->last_page_mouse_down_;
3581 /* Don't try to calculate the most visible page if we don't have a left click
3582 before this event (this code originally copied Form_GetCurrentPage which of
3583 course needs to do that and which doesn't have recursion). This can end up
3584 causing infinite recursion. See http://crbug.com/240413 for more
3585 information. Either way, it's not necessary for the spec'd list of named
3586 actions.
3587 if (index == -1)
3588 index = engine->GetMostVisiblePage();
3590 if (index == -1)
3591 return;
3593 // This is the only list of named actions per the spec (see 12.6.4.11). Adobe
3594 // Reader supports more, like FitWidth, but since they're not part of the spec
3595 // and we haven't got bugs about them, no need to now.
3596 if (action == "NextPage") {
3597 engine->client_->ScrollToPage(index + 1);
3598 } else if (action == "PrevPage") {
3599 engine->client_->ScrollToPage(index - 1);
3600 } else if (action == "FirstPage") {
3601 engine->client_->ScrollToPage(0);
3602 } else if (action == "LastPage") {
3603 engine->client_->ScrollToPage(engine->pages_.size() - 1);
3607 void PDFiumEngine::Form_SetTextFieldFocus(FPDF_FORMFILLINFO* param,
3608 FPDF_WIDESTRING value,
3609 FPDF_DWORD valueLen,
3610 FPDF_BOOL is_focus) {
3611 // Do nothing for now.
3612 // TODO(gene): use this signal to trigger OSK.
3615 void PDFiumEngine::Form_DoURIAction(FPDF_FORMFILLINFO* param,
3616 FPDF_BYTESTRING uri) {
3617 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3618 engine->client_->NavigateTo(std::string(uri), false);
3621 void PDFiumEngine::Form_DoGoToAction(FPDF_FORMFILLINFO* param,
3622 int page_index,
3623 int zoom_mode,
3624 float* position_array,
3625 int size_of_array) {
3626 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3627 engine->client_->ScrollToPage(page_index);
3630 int PDFiumEngine::Form_Alert(IPDF_JSPLATFORM* param,
3631 FPDF_WIDESTRING message,
3632 FPDF_WIDESTRING title,
3633 int type,
3634 int icon) {
3635 // See fpdfformfill.h for these values.
3636 enum AlertType {
3637 ALERT_TYPE_OK = 0,
3638 ALERT_TYPE_OK_CANCEL,
3639 ALERT_TYPE_YES_ON,
3640 ALERT_TYPE_YES_NO_CANCEL
3643 enum AlertResult {
3644 ALERT_RESULT_OK = 1,
3645 ALERT_RESULT_CANCEL,
3646 ALERT_RESULT_NO,
3647 ALERT_RESULT_YES
3650 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3651 std::string message_str =
3652 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(message));
3653 if (type == ALERT_TYPE_OK) {
3654 engine->client_->Alert(message_str);
3655 return ALERT_RESULT_OK;
3658 bool rv = engine->client_->Confirm(message_str);
3659 if (type == ALERT_TYPE_OK_CANCEL)
3660 return rv ? ALERT_RESULT_OK : ALERT_RESULT_CANCEL;
3661 return rv ? ALERT_RESULT_YES : ALERT_RESULT_NO;
3664 void PDFiumEngine::Form_Beep(IPDF_JSPLATFORM* param, int type) {
3665 // Beeps are annoying, and not possible using javascript, so ignore for now.
3668 int PDFiumEngine::Form_Response(IPDF_JSPLATFORM* param,
3669 FPDF_WIDESTRING question,
3670 FPDF_WIDESTRING title,
3671 FPDF_WIDESTRING default_response,
3672 FPDF_WIDESTRING label,
3673 FPDF_BOOL password,
3674 void* response,
3675 int length) {
3676 std::string question_str = base::UTF16ToUTF8(
3677 reinterpret_cast<const base::char16*>(question));
3678 std::string default_str = base::UTF16ToUTF8(
3679 reinterpret_cast<const base::char16*>(default_response));
3681 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3682 std::string rv = engine->client_->Prompt(question_str, default_str);
3683 base::string16 rv_16 = base::UTF8ToUTF16(rv);
3684 int rv_bytes = rv_16.size() * sizeof(base::char16);
3685 if (response) {
3686 int bytes_to_copy = rv_bytes < length ? rv_bytes : length;
3687 memcpy(response, rv_16.c_str(), bytes_to_copy);
3689 return rv_bytes;
3692 int PDFiumEngine::Form_GetFilePath(IPDF_JSPLATFORM* param,
3693 void* file_path,
3694 int length) {
3695 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3696 std::string rv = engine->client_->GetURL();
3697 if (file_path && rv.size() <= static_cast<size_t>(length))
3698 memcpy(file_path, rv.c_str(), rv.size());
3699 return rv.size();
3702 void PDFiumEngine::Form_Mail(IPDF_JSPLATFORM* param,
3703 void* mail_data,
3704 int length,
3705 FPDF_BOOL ui,
3706 FPDF_WIDESTRING to,
3707 FPDF_WIDESTRING subject,
3708 FPDF_WIDESTRING cc,
3709 FPDF_WIDESTRING bcc,
3710 FPDF_WIDESTRING message) {
3711 // Note: |mail_data| and |length| are ignored. We don't handle attachments;
3712 // there is no way with mailto.
3713 std::string to_str =
3714 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(to));
3715 std::string cc_str =
3716 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(cc));
3717 std::string bcc_str =
3718 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(bcc));
3719 std::string subject_str =
3720 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(subject));
3721 std::string message_str =
3722 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(message));
3724 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3725 engine->client_->Email(to_str, cc_str, bcc_str, subject_str, message_str);
3728 void PDFiumEngine::Form_Print(IPDF_JSPLATFORM* param,
3729 FPDF_BOOL ui,
3730 int start,
3731 int end,
3732 FPDF_BOOL silent,
3733 FPDF_BOOL shrink_to_fit,
3734 FPDF_BOOL print_as_image,
3735 FPDF_BOOL reverse,
3736 FPDF_BOOL annotations) {
3737 // No way to pass the extra information to the print dialog using JavaScript.
3738 // Just opening it is fine for now.
3739 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3740 engine->client_->Print();
3743 void PDFiumEngine::Form_SubmitForm(IPDF_JSPLATFORM* param,
3744 void* form_data,
3745 int length,
3746 FPDF_WIDESTRING url) {
3747 std::string url_str =
3748 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(url));
3749 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3750 engine->client_->SubmitForm(url_str, form_data, length);
3753 void PDFiumEngine::Form_GotoPage(IPDF_JSPLATFORM* param,
3754 int page_number) {
3755 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3756 engine->client_->ScrollToPage(page_number);
3759 int PDFiumEngine::Form_Browse(IPDF_JSPLATFORM* param,
3760 void* file_path,
3761 int length) {
3762 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3763 std::string path = engine->client_->ShowFileSelectionDialog();
3764 if (path.size() + 1 <= static_cast<size_t>(length))
3765 memcpy(file_path, &path[0], path.size() + 1);
3766 return path.size() + 1;
3769 FPDF_BOOL PDFiumEngine::Pause_NeedToPauseNow(IFSDK_PAUSE* param) {
3770 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3771 return (base::Time::Now() - engine->last_progressive_start_time_).
3772 InMilliseconds() > engine->progressive_paint_timeout_;
3775 ScopedUnsupportedFeature::ScopedUnsupportedFeature(PDFiumEngine* engine)
3776 : engine_(engine), old_engine_(g_engine_for_unsupported) {
3777 g_engine_for_unsupported = engine_;
3780 ScopedUnsupportedFeature::~ScopedUnsupportedFeature() {
3781 g_engine_for_unsupported = old_engine_;
3784 PDFEngineExports* PDFEngineExports::Create() {
3785 return new PDFiumEngineExports;
3788 namespace {
3790 int CalculatePosition(FPDF_PAGE page,
3791 const PDFiumEngineExports::RenderingSettings& settings,
3792 pp::Rect* dest) {
3793 int page_width = static_cast<int>(ConvertUnitDouble(FPDF_GetPageWidth(page),
3794 kPointsPerInch,
3795 settings.dpi_x));
3796 int page_height = static_cast<int>(ConvertUnitDouble(FPDF_GetPageHeight(page),
3797 kPointsPerInch,
3798 settings.dpi_y));
3800 // Start by assuming that we will draw exactly to the bounds rect
3801 // specified.
3802 *dest = settings.bounds;
3804 int rotate = 0; // normal orientation.
3806 // Auto-rotate landscape pages to print correctly.
3807 if (settings.autorotate &&
3808 (dest->width() > dest->height()) != (page_width > page_height)) {
3809 rotate = 3; // 90 degrees counter-clockwise.
3810 std::swap(page_width, page_height);
3813 // See if we need to scale the output
3814 bool scale_to_bounds = false;
3815 if (settings.fit_to_bounds &&
3816 ((page_width > dest->width()) || (page_height > dest->height()))) {
3817 scale_to_bounds = true;
3818 } else if (settings.stretch_to_bounds &&
3819 ((page_width < dest->width()) || (page_height < dest->height()))) {
3820 scale_to_bounds = true;
3823 if (scale_to_bounds) {
3824 // If we need to maintain aspect ratio, calculate the actual width and
3825 // height.
3826 if (settings.keep_aspect_ratio) {
3827 double scale_factor_x = page_width;
3828 scale_factor_x /= dest->width();
3829 double scale_factor_y = page_height;
3830 scale_factor_y /= dest->height();
3831 if (scale_factor_x > scale_factor_y) {
3832 dest->set_height(page_height / scale_factor_x);
3833 } else {
3834 dest->set_width(page_width / scale_factor_y);
3837 } else {
3838 // We are not scaling to bounds. Draw in the actual page size. If the
3839 // actual page size is larger than the bounds, the output will be
3840 // clipped.
3841 dest->set_width(page_width);
3842 dest->set_height(page_height);
3845 if (settings.center_in_bounds) {
3846 pp::Point offset((settings.bounds.width() - dest->width()) / 2,
3847 (settings.bounds.height() - dest->height()) / 2);
3848 dest->Offset(offset);
3850 return rotate;
3853 } // namespace
3855 #if defined(OS_WIN)
3856 bool PDFiumEngineExports::RenderPDFPageToDC(const void* pdf_buffer,
3857 int buffer_size,
3858 int page_number,
3859 const RenderingSettings& settings,
3860 HDC dc) {
3861 FPDF_DOCUMENT doc = FPDF_LoadMemDocument(pdf_buffer, buffer_size, NULL);
3862 if (!doc)
3863 return false;
3864 FPDF_PAGE page = FPDF_LoadPage(doc, page_number);
3865 if (!page) {
3866 FPDF_CloseDocument(doc);
3867 return false;
3869 RenderingSettings new_settings = settings;
3870 // calculate the page size
3871 if (new_settings.dpi_x == -1)
3872 new_settings.dpi_x = GetDeviceCaps(dc, LOGPIXELSX);
3873 if (new_settings.dpi_y == -1)
3874 new_settings.dpi_y = GetDeviceCaps(dc, LOGPIXELSY);
3876 pp::Rect dest;
3877 int rotate = CalculatePosition(page, new_settings, &dest);
3879 int save_state = SaveDC(dc);
3880 // The caller wanted all drawing to happen within the bounds specified.
3881 // Based on scale calculations, our destination rect might be larger
3882 // than the bounds. Set the clip rect to the bounds.
3883 IntersectClipRect(dc, settings.bounds.x(), settings.bounds.y(),
3884 settings.bounds.x() + settings.bounds.width(),
3885 settings.bounds.y() + settings.bounds.height());
3887 // A temporary hack. PDFs generated by Cairo (used by Chrome OS to generate
3888 // a PDF output from a webpage) result in very large metafiles and the
3889 // rendering using FPDF_RenderPage is incorrect. In this case, render as a
3890 // bitmap. Note that this code does not kick in for PDFs printed from Chrome
3891 // because in that case we create a temp PDF first before printing and this
3892 // temp PDF does not have a creator string that starts with "cairo".
3893 base::string16 creator;
3894 size_t buffer_bytes = FPDF_GetMetaText(doc, "Creator", NULL, 0);
3895 if (buffer_bytes > 1) {
3896 FPDF_GetMetaText(
3897 doc, "Creator", WriteInto(&creator, buffer_bytes + 1), buffer_bytes);
3899 bool use_bitmap = false;
3900 if (StartsWith(creator, L"cairo", false))
3901 use_bitmap = true;
3903 // Another temporary hack. Some PDFs seems to render very slowly if
3904 // FPDF_RenderPage is directly used on a printer DC. I suspect it is
3905 // because of the code to talk Postscript directly to the printer if
3906 // the printer supports this. Need to discuss this with PDFium. For now,
3907 // render to a bitmap and then blit the bitmap to the DC if we have been
3908 // supplied a printer DC.
3909 int device_type = GetDeviceCaps(dc, TECHNOLOGY);
3910 if (use_bitmap ||
3911 (device_type == DT_RASPRINTER) || (device_type == DT_PLOTTER)) {
3912 FPDF_BITMAP bitmap = FPDFBitmap_Create(dest.width(), dest.height(),
3913 FPDFBitmap_BGRx);
3914 // Clear the bitmap
3915 FPDFBitmap_FillRect(bitmap, 0, 0, dest.width(), dest.height(), 0xFFFFFFFF);
3916 FPDF_RenderPageBitmap(
3917 bitmap, page, 0, 0, dest.width(), dest.height(), rotate,
3918 FPDF_ANNOT | FPDF_PRINTING | FPDF_NO_CATCH);
3919 int stride = FPDFBitmap_GetStride(bitmap);
3920 BITMAPINFO bmi;
3921 memset(&bmi, 0, sizeof(bmi));
3922 bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
3923 bmi.bmiHeader.biWidth = dest.width();
3924 bmi.bmiHeader.biHeight = -dest.height(); // top-down image
3925 bmi.bmiHeader.biPlanes = 1;
3926 bmi.bmiHeader.biBitCount = 32;
3927 bmi.bmiHeader.biCompression = BI_RGB;
3928 bmi.bmiHeader.biSizeImage = stride * dest.height();
3929 StretchDIBits(dc, dest.x(), dest.y(), dest.width(), dest.height(),
3930 0, 0, dest.width(), dest.height(),
3931 FPDFBitmap_GetBuffer(bitmap), &bmi, DIB_RGB_COLORS, SRCCOPY);
3932 FPDFBitmap_Destroy(bitmap);
3933 } else {
3934 FPDF_RenderPage(dc, page, dest.x(), dest.y(), dest.width(), dest.height(),
3935 rotate, FPDF_ANNOT | FPDF_PRINTING | FPDF_NO_CATCH);
3937 RestoreDC(dc, save_state);
3938 FPDF_ClosePage(page);
3939 FPDF_CloseDocument(doc);
3940 return true;
3942 #endif // OS_WIN
3944 bool PDFiumEngineExports::RenderPDFPageToBitmap(
3945 const void* pdf_buffer,
3946 int pdf_buffer_size,
3947 int page_number,
3948 const RenderingSettings& settings,
3949 void* bitmap_buffer) {
3950 FPDF_DOCUMENT doc = FPDF_LoadMemDocument(pdf_buffer, pdf_buffer_size, NULL);
3951 if (!doc)
3952 return false;
3953 FPDF_PAGE page = FPDF_LoadPage(doc, page_number);
3954 if (!page) {
3955 FPDF_CloseDocument(doc);
3956 return false;
3959 pp::Rect dest;
3960 int rotate = CalculatePosition(page, settings, &dest);
3962 FPDF_BITMAP bitmap =
3963 FPDFBitmap_CreateEx(settings.bounds.width(), settings.bounds.height(),
3964 FPDFBitmap_BGRA, bitmap_buffer,
3965 settings.bounds.width() * 4);
3966 // Clear the bitmap
3967 FPDFBitmap_FillRect(bitmap, 0, 0, settings.bounds.width(),
3968 settings.bounds.height(), 0xFFFFFFFF);
3969 // Shift top-left corner of bounds to (0, 0) if it's not there.
3970 dest.set_point(dest.point() - settings.bounds.point());
3971 FPDF_RenderPageBitmap(
3972 bitmap, page, dest.x(), dest.y(), dest.width(), dest.height(), rotate,
3973 FPDF_ANNOT | FPDF_PRINTING | FPDF_NO_CATCH);
3974 FPDFBitmap_Destroy(bitmap);
3975 FPDF_ClosePage(page);
3976 FPDF_CloseDocument(doc);
3977 return true;
3980 bool PDFiumEngineExports::GetPDFDocInfo(const void* pdf_buffer,
3981 int buffer_size,
3982 int* page_count,
3983 double* max_page_width) {
3984 FPDF_DOCUMENT doc = FPDF_LoadMemDocument(pdf_buffer, buffer_size, NULL);
3985 if (!doc)
3986 return false;
3987 int page_count_local = FPDF_GetPageCount(doc);
3988 if (page_count) {
3989 *page_count = page_count_local;
3991 if (max_page_width) {
3992 *max_page_width = 0;
3993 for (int page_number = 0; page_number < page_count_local; page_number++) {
3994 double page_width = 0;
3995 double page_height = 0;
3996 FPDF_GetPageSizeByIndex(doc, page_number, &page_width, &page_height);
3997 if (page_width > *max_page_width) {
3998 *max_page_width = page_width;
4002 FPDF_CloseDocument(doc);
4003 return true;
4006 bool PDFiumEngineExports::GetPDFPageSizeByIndex(
4007 const void* pdf_buffer,
4008 int pdf_buffer_size,
4009 int page_number,
4010 double* width,
4011 double* height) {
4012 FPDF_DOCUMENT doc = FPDF_LoadMemDocument(pdf_buffer, pdf_buffer_size, NULL);
4013 if (!doc)
4014 return false;
4015 bool success = FPDF_GetPageSizeByIndex(doc, page_number, width, height) != 0;
4016 FPDF_CloseDocument(doc);
4017 return success;
4020 } // namespace chrome_pdf