don't pretend to support dbus on windows in dbus_export.h
[chromium-blink-merge.git] / pdf / pdfium / pdfium_engine.cc
blobe8c164b03ac0dd2f8066ef7b385e59a8803d1449
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/stl_util.h"
13 #include "base/strings/string_number_conversions.h"
14 #include "base/strings/string_piece.h"
15 #include "base/strings/string_util.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "base/values.h"
18 #include "pdf/draw_utils.h"
19 #include "pdf/pdfium/pdfium_mem_buffer_file_read.h"
20 #include "pdf/pdfium/pdfium_mem_buffer_file_write.h"
21 #include "ppapi/c/pp_errors.h"
22 #include "ppapi/c/pp_input_event.h"
23 #include "ppapi/c/ppb_core.h"
24 #include "ppapi/c/private/ppb_pdf.h"
25 #include "ppapi/cpp/dev/memory_dev.h"
26 #include "ppapi/cpp/input_event.h"
27 #include "ppapi/cpp/instance.h"
28 #include "ppapi/cpp/module.h"
29 #include "ppapi/cpp/private/pdf.h"
30 #include "ppapi/cpp/trusted/browser_font_trusted.h"
31 #include "ppapi/cpp/url_response_info.h"
32 #include "ppapi/cpp/var.h"
33 #include "third_party/pdfium/fpdfsdk/include/fpdf_ext.h"
34 #include "third_party/pdfium/fpdfsdk/include/fpdf_flatten.h"
35 #include "third_party/pdfium/fpdfsdk/include/fpdf_searchex.h"
36 #include "third_party/pdfium/fpdfsdk/include/fpdf_sysfontinfo.h"
37 #include "third_party/pdfium/fpdfsdk/include/fpdf_transformpage.h"
38 #include "third_party/pdfium/fpdfsdk/include/fpdfedit.h"
39 #include "third_party/pdfium/fpdfsdk/include/fpdfoom.h"
40 #include "third_party/pdfium/fpdfsdk/include/fpdfppo.h"
41 #include "third_party/pdfium/fpdfsdk/include/fpdfsave.h"
42 #include "third_party/pdfium/fpdfsdk/include/pdfwindow/PDFWindow.h"
43 #include "third_party/pdfium/fpdfsdk/include/pdfwindow/PWL_FontMap.h"
44 #include "ui/events/keycodes/keyboard_codes.h"
46 namespace chrome_pdf {
48 #define kPageShadowTop 3
49 #define kPageShadowBottom 7
50 #define kPageShadowLeft 5
51 #define kPageShadowRight 5
53 #define kPageSeparatorThickness 4
54 #define kHighlightColorR 153
55 #define kHighlightColorG 193
56 #define kHighlightColorB 218
58 const uint32 kPendingPageColor = 0xFFEEEEEE;
60 #define kFormHighlightColor 0xFFE4DD
61 #define kFormHighlightAlpha 100
63 #define kMaxPasswordTries 3
65 // See Table 3.20 in
66 // http://www.adobe.com/devnet/acrobat/pdfs/pdf_reference_1-7.pdf
67 #define kPDFPermissionPrintLowQualityMask 1 << 2
68 #define kPDFPermissionPrintHighQualityMask 1 << 11
69 #define kPDFPermissionCopyMask 1 << 4
70 #define kPDFPermissionCopyAccessibleMask 1 << 9
72 #define kLoadingTextVerticalOffset 50
74 // The maximum amount of time we'll spend doing a paint before we give back
75 // control of the thread.
76 #define kMaxProgressivePaintTimeMs 50
78 // The maximum amount of time we'll spend doing the first paint. This is less
79 // than the above to keep things smooth if the user is scrolling quickly. We
80 // try painting a little because with accelerated compositing, we get flushes
81 // only every 16 ms. If we were to wait until the next flush to paint the rest
82 // of the pdf, we would never get to draw the pdf and would only draw the
83 // scrollbars. This value is picked to give enough time for gpu related code to
84 // do its thing and still fit within the timelimit for 60Hz. For the
85 // non-composited case, this doesn't make things worse since we're still
86 // painting the scrollbars > 60 Hz.
87 #define kMaxInitialProgressivePaintTimeMs 10
89 // Copied from printing/units.cc because we don't want to depend on printing
90 // since it brings in libpng which causes duplicate symbols with PDFium.
91 const int kPointsPerInch = 72;
92 const int kPixelsPerInch = 96;
94 struct ClipBox {
95 float left;
96 float right;
97 float top;
98 float bottom;
101 int ConvertUnit(int value, int old_unit, int new_unit) {
102 // With integer arithmetic, to divide a value with correct rounding, you need
103 // to add half of the divisor value to the dividend value. You need to do the
104 // reverse with negative number.
105 if (value >= 0) {
106 return ((value * new_unit) + (old_unit / 2)) / old_unit;
107 } else {
108 return ((value * new_unit) - (old_unit / 2)) / old_unit;
112 std::vector<uint32_t> GetPageNumbersFromPrintPageNumberRange(
113 const PP_PrintPageNumberRange_Dev* page_ranges,
114 uint32_t page_range_count) {
115 std::vector<uint32_t> page_numbers;
116 for (uint32_t index = 0; index < page_range_count; ++index) {
117 for (uint32_t page_number = page_ranges[index].first_page_number;
118 page_number <= page_ranges[index].last_page_number; ++page_number) {
119 page_numbers.push_back(page_number);
122 return page_numbers;
125 #if defined(OS_LINUX)
127 PP_Instance g_last_instance_id;
129 struct PDFFontSubstitution {
130 const char* pdf_name;
131 const char* face;
132 bool bold;
133 bool italic;
136 PP_BrowserFont_Trusted_Weight WeightToBrowserFontTrustedWeight(int weight) {
137 COMPILE_ASSERT(PP_BROWSERFONT_TRUSTED_WEIGHT_100 == 0,
138 PP_BrowserFont_Trusted_Weight_Min);
139 COMPILE_ASSERT(PP_BROWSERFONT_TRUSTED_WEIGHT_900 == 8,
140 PP_BrowserFont_Trusted_Weight_Max);
141 const int kMinimumWeight = 100;
142 const int kMaximumWeight = 900;
143 int normalized_weight =
144 std::min(std::max(weight, kMinimumWeight), kMaximumWeight);
145 normalized_weight = (normalized_weight / 100) - 1;
146 return static_cast<PP_BrowserFont_Trusted_Weight>(normalized_weight);
149 // This list is for CPWL_FontMap::GetDefaultFontByCharset().
150 // We pretend to have these font natively and let the browser (or underlying
151 // fontconfig) to pick the proper font on the system.
152 void EnumFonts(struct _FPDF_SYSFONTINFO* sysfontinfo, void* mapper) {
153 FPDF_AddInstalledFont(mapper, "Arial", FXFONT_DEFAULT_CHARSET);
155 int i = 0;
156 while (CPWL_FontMap::defaultTTFMap[i].charset != -1) {
157 FPDF_AddInstalledFont(mapper,
158 CPWL_FontMap::defaultTTFMap[i].fontname,
159 CPWL_FontMap::defaultTTFMap[i].charset);
160 ++i;
164 const PDFFontSubstitution PDFFontSubstitutions[] = {
165 {"Courier", "Courier New", false, false},
166 {"Courier-Bold", "Courier New", true, false},
167 {"Courier-BoldOblique", "Courier New", true, true},
168 {"Courier-Oblique", "Courier New", false, true},
169 {"Helvetica", "Arial", false, false},
170 {"Helvetica-Bold", "Arial", true, false},
171 {"Helvetica-BoldOblique", "Arial", true, true},
172 {"Helvetica-Oblique", "Arial", false, true},
173 {"Times-Roman", "Times New Roman", false, false},
174 {"Times-Bold", "Times New Roman", true, false},
175 {"Times-BoldItalic", "Times New Roman", true, true},
176 {"Times-Italic", "Times New Roman", false, true},
178 // MS P?(Mincho|Gothic) are the most notable fonts in Japanese PDF files
179 // without embedding the glyphs. Sometimes the font names are encoded
180 // in Japanese Windows's locale (CP932/Shift_JIS) without space.
181 // Most Linux systems don't have the exact font, but for outsourcing
182 // fontconfig to find substitutable font in the system, we pass ASCII
183 // font names to it.
184 {"MS-PGothic", "MS PGothic", false, false},
185 {"MS-Gothic", "MS Gothic", false, false},
186 {"MS-PMincho", "MS PMincho", false, false},
187 {"MS-Mincho", "MS Mincho", false, false},
188 // MS PGothic in Shift_JIS encoding.
189 {"\x82\x6C\x82\x72\x82\x6F\x83\x53\x83\x56\x83\x62\x83\x4E",
190 "MS PGothic", false, false},
191 // MS Gothic in Shift_JIS encoding.
192 {"\x82\x6C\x82\x72\x83\x53\x83\x56\x83\x62\x83\x4E",
193 "MS Gothic", false, false},
194 // MS PMincho in Shift_JIS encoding.
195 {"\x82\x6C\x82\x72\x82\x6F\x96\xBE\x92\xA9",
196 "MS PMincho", false, false},
197 // MS Mincho in Shift_JIS encoding.
198 {"\x82\x6C\x82\x72\x96\xBE\x92\xA9",
199 "MS Mincho", false, false},
202 void* MapFont(struct _FPDF_SYSFONTINFO*, int weight, int italic,
203 int charset, int pitch_family, const char* face, int* exact) {
204 // Do not attempt to map fonts if pepper is not initialized (for privet local
205 // printing).
206 // TODO(noamsml): Real font substitution (http://crbug.com/391978)
207 if (!pp::Module::Get())
208 return NULL;
210 pp::BrowserFontDescription description;
212 // Pretend the system does not have the Symbol font to force a fallback to
213 // the built in Symbol font in CFX_FontMapper::FindSubstFont().
214 if (strcmp(face, "Symbol") == 0)
215 return NULL;
217 if (pitch_family & FXFONT_FF_FIXEDPITCH) {
218 description.set_family(PP_BROWSERFONT_TRUSTED_FAMILY_MONOSPACE);
219 } else if (pitch_family & FXFONT_FF_ROMAN) {
220 description.set_family(PP_BROWSERFONT_TRUSTED_FAMILY_SERIF);
223 // Map from the standard PDF fonts to TrueType font names.
224 size_t i;
225 for (i = 0; i < arraysize(PDFFontSubstitutions); ++i) {
226 if (strcmp(face, PDFFontSubstitutions[i].pdf_name) == 0) {
227 description.set_face(PDFFontSubstitutions[i].face);
228 if (PDFFontSubstitutions[i].bold)
229 description.set_weight(PP_BROWSERFONT_TRUSTED_WEIGHT_BOLD);
230 if (PDFFontSubstitutions[i].italic)
231 description.set_italic(true);
232 break;
236 if (i == arraysize(PDFFontSubstitutions)) {
237 // TODO(kochi): Pass the face in UTF-8. If face is not encoded in UTF-8,
238 // convert to UTF-8 before passing.
239 description.set_face(face);
241 description.set_weight(WeightToBrowserFontTrustedWeight(weight));
242 description.set_italic(italic > 0);
245 if (!pp::PDF::IsAvailable()) {
246 NOTREACHED();
247 return NULL;
250 PP_Resource font_resource = pp::PDF::GetFontFileWithFallback(
251 pp::InstanceHandle(g_last_instance_id),
252 &description.pp_font_description(),
253 static_cast<PP_PrivateFontCharset>(charset));
254 long res_id = font_resource;
255 return reinterpret_cast<void*>(res_id);
258 unsigned long GetFontData(struct _FPDF_SYSFONTINFO*, void* font_id,
259 unsigned int table, unsigned char* buffer,
260 unsigned long buf_size) {
261 if (!pp::PDF::IsAvailable()) {
262 NOTREACHED();
263 return 0;
266 uint32_t size = buf_size;
267 long res_id = reinterpret_cast<long>(font_id);
268 if (!pp::PDF::GetFontTableForPrivateFontFile(res_id, table, buffer, &size))
269 return 0;
270 return size;
273 void DeleteFont(struct _FPDF_SYSFONTINFO*, void* font_id) {
274 long res_id = reinterpret_cast<long>(font_id);
275 pp::Module::Get()->core()->ReleaseResource(res_id);
278 FPDF_SYSFONTINFO g_font_info = {
281 EnumFonts,
282 MapFont,
284 GetFontData,
287 DeleteFont
289 #endif // defined(OS_LINUX)
291 void OOM_Handler(_OOM_INFO*) {
292 // Kill the process. This is important for security, since the code doesn't
293 // NULL-check many memory allocations. If a malloc fails, returns NULL, and
294 // the buffer is then used, it provides a handy mapping of memory starting at
295 // address 0 for an attacker to utilize.
296 abort();
299 OOM_INFO g_oom_info = {
301 OOM_Handler
304 PDFiumEngine* g_engine_for_unsupported;
306 void Unsupported_Handler(UNSUPPORT_INFO*, int type) {
307 if (!g_engine_for_unsupported) {
308 NOTREACHED();
309 return;
312 g_engine_for_unsupported->UnsupportedFeature(type);
315 UNSUPPORT_INFO g_unsuppored_info = {
317 Unsupported_Handler
320 // Set the destination page size and content area in points based on source
321 // page rotation and orientation.
323 // |rotated| True if source page is rotated 90 degree or 270 degree.
324 // |is_src_page_landscape| is true if the source page orientation is landscape.
325 // |page_size| has the actual destination page size in points.
326 // |content_rect| has the actual destination page printable area values in
327 // points.
328 void SetPageSizeAndContentRect(bool rotated,
329 bool is_src_page_landscape,
330 pp::Size* page_size,
331 pp::Rect* content_rect) {
332 bool is_dst_page_landscape = page_size->width() > page_size->height();
333 bool page_orientation_mismatched = is_src_page_landscape !=
334 is_dst_page_landscape;
335 bool rotate_dst_page = rotated ^ page_orientation_mismatched;
336 if (rotate_dst_page) {
337 page_size->SetSize(page_size->height(), page_size->width());
338 content_rect->SetRect(content_rect->y(), content_rect->x(),
339 content_rect->height(), content_rect->width());
343 // Calculate the scale factor between |content_rect| and a page of size
344 // |src_width| x |src_height|.
346 // |scale_to_fit| is true, if we need to calculate the scale factor.
347 // |content_rect| specifies the printable area of the destination page, with
348 // origin at left-bottom. Values are in points.
349 // |src_width| specifies the source page width in points.
350 // |src_height| specifies the source page height in points.
351 // |rotated| True if source page is rotated 90 degree or 270 degree.
352 double CalculateScaleFactor(bool scale_to_fit,
353 const pp::Rect& content_rect,
354 double src_width, double src_height, bool rotated) {
355 if (!scale_to_fit || src_width == 0 || src_height == 0)
356 return 1.0;
358 double actual_source_page_width = rotated ? src_height : src_width;
359 double actual_source_page_height = rotated ? src_width : src_height;
360 double ratio_x = static_cast<double>(content_rect.width()) /
361 actual_source_page_width;
362 double ratio_y = static_cast<double>(content_rect.height()) /
363 actual_source_page_height;
364 return std::min(ratio_x, ratio_y);
367 // Compute source clip box boundaries based on the crop box / media box of
368 // source page and scale factor.
370 // |page| Handle to the source page. Returned by FPDF_LoadPage function.
371 // |scale_factor| specifies the scale factor that should be applied to source
372 // clip box boundaries.
373 // |rotated| True if source page is rotated 90 degree or 270 degree.
374 // |clip_box| out param to hold the computed source clip box values.
375 void CalculateClipBoxBoundary(FPDF_PAGE page, double scale_factor, bool rotated,
376 ClipBox* clip_box) {
377 if (!FPDFPage_GetCropBox(page, &clip_box->left, &clip_box->bottom,
378 &clip_box->right, &clip_box->top)) {
379 if (!FPDFPage_GetMediaBox(page, &clip_box->left, &clip_box->bottom,
380 &clip_box->right, &clip_box->top)) {
381 // Make the default size to be letter size (8.5" X 11"). We are just
382 // following the PDFium way of handling these corner cases. PDFium always
383 // consider US-Letter as the default page size.
384 float paper_width = 612;
385 float paper_height = 792;
386 clip_box->left = 0;
387 clip_box->bottom = 0;
388 clip_box->right = rotated ? paper_height : paper_width;
389 clip_box->top = rotated ? paper_width : paper_height;
392 clip_box->left *= scale_factor;
393 clip_box->right *= scale_factor;
394 clip_box->bottom *= scale_factor;
395 clip_box->top *= scale_factor;
398 // Calculate the clip box translation offset for a page that does need to be
399 // scaled. All parameters are in points.
401 // |content_rect| specifies the printable area of the destination page, with
402 // origin at left-bottom.
403 // |source_clip_box| specifies the source clip box positions, relative to
404 // origin at left-bottom.
405 // |offset_x| and |offset_y| will contain the final translation offsets for the
406 // source clip box, relative to origin at left-bottom.
407 void CalculateScaledClipBoxOffset(const pp::Rect& content_rect,
408 const ClipBox& source_clip_box,
409 double* offset_x, double* offset_y) {
410 const float clip_box_width = source_clip_box.right - source_clip_box.left;
411 const float clip_box_height = source_clip_box.top - source_clip_box.bottom;
413 // Center the intended clip region to real clip region.
414 *offset_x = (content_rect.width() - clip_box_width) / 2 + content_rect.x() -
415 source_clip_box.left;
416 *offset_y = (content_rect.height() - clip_box_height) / 2 + content_rect.y() -
417 source_clip_box.bottom;
420 // Calculate the clip box offset for a page that does not need to be scaled.
421 // All parameters are in points.
423 // |content_rect| specifies the printable area of the destination page, with
424 // origin at left-bottom.
425 // |rotation| specifies the source page rotation values which are N / 90
426 // degrees.
427 // |page_width| specifies the screen destination page width.
428 // |page_height| specifies the screen destination page height.
429 // |source_clip_box| specifies the source clip box positions, relative to origin
430 // at left-bottom.
431 // |offset_x| and |offset_y| will contain the final translation offsets for the
432 // source clip box, relative to origin at left-bottom.
433 void CalculateNonScaledClipBoxOffset(const pp::Rect& content_rect, int rotation,
434 int page_width, int page_height,
435 const ClipBox& source_clip_box,
436 double* offset_x, double* offset_y) {
437 // Align the intended clip region to left-top corner of real clip region.
438 switch (rotation) {
439 case 0:
440 *offset_x = -1 * source_clip_box.left;
441 *offset_y = page_height - source_clip_box.top;
442 break;
443 case 1:
444 *offset_x = 0;
445 *offset_y = -1 * source_clip_box.bottom;
446 break;
447 case 2:
448 *offset_x = page_width - source_clip_box.right;
449 *offset_y = 0;
450 break;
451 case 3:
452 *offset_x = page_height - source_clip_box.right;
453 *offset_y = page_width - source_clip_box.top;
454 break;
455 default:
456 NOTREACHED();
457 break;
461 // Do an in-place transformation of objects on |page|. Translate all objects on
462 // |page| in |source_clip_box| by (|offset_x|, |offset_y|) and scale them by
463 // |scale_factor|.
465 // |page| Handle to the page. Returned by FPDF_LoadPage function.
466 // |source_clip_box| specifies the source clip box positions, relative to
467 // origin at left-bottom.
468 // |scale_factor| specifies the scale factor that should be applied to page
469 // objects.
470 // |offset_x| and |offset_y| specifies the translation offsets for the page
471 // objects, relative to origin at left-bottom.
473 void TransformPageObjects(FPDF_PAGE page, const ClipBox& source_clip_box,
474 const double scale_factor, double offset_x,
475 double offset_y) {
476 const int obj_count = FPDFPage_CountObject(page);
478 // Create a new clip path.
479 FPDF_CLIPPATH clip_path = FPDF_CreateClipPath(
480 source_clip_box.left + offset_x, source_clip_box.bottom + offset_y,
481 source_clip_box.right + offset_x, source_clip_box.top + offset_y);
483 for (int obj_idx = 0; obj_idx < obj_count; ++obj_idx) {
484 FPDF_PAGEOBJECT page_obj = FPDFPage_GetObject(page, obj_idx);
485 FPDFPageObj_Transform(page_obj, scale_factor, 0, 0, scale_factor,
486 offset_x, offset_y);
487 FPDFPageObj_TransformClipPath(page_obj, scale_factor, 0, 0, scale_factor,
488 offset_x, offset_y);
490 FPDFPage_TransformAnnots(page, scale_factor, 0, 0, scale_factor,
491 offset_x, offset_y);
492 FPDFPage_GenerateContent(page);
494 // Add a extra clip path to the new pdf page here.
495 FPDFPage_InsertClipPath(page, clip_path);
497 // Destroy the clip path.
498 FPDF_DestroyClipPath(clip_path);
501 bool InitializeSDK(void* data) {
502 FPDF_InitLibrary(data);
504 #if defined(OS_LINUX)
505 // Font loading doesn't work in the renderer sandbox in Linux.
506 FPDF_SetSystemFontInfo(&g_font_info);
507 #endif
509 FSDK_SetOOMHandler(&g_oom_info);
510 FSDK_SetUnSpObjProcessHandler(&g_unsuppored_info);
512 return true;
515 void ShutdownSDK() {
516 FPDF_DestroyLibrary();
519 PDFEngine* PDFEngine::Create(PDFEngine::Client* client) {
520 return new PDFiumEngine(client);
523 PDFiumEngine::PDFiumEngine(PDFEngine::Client* client)
524 : client_(client),
525 current_zoom_(1.0),
526 current_rotation_(0),
527 doc_loader_(this),
528 password_tries_remaining_(0),
529 doc_(NULL),
530 form_(NULL),
531 defer_page_unload_(false),
532 selecting_(false),
533 next_page_to_search_(-1),
534 last_page_to_search_(-1),
535 last_character_index_to_search_(-1),
536 current_find_index_(-1),
537 permissions_(0),
538 fpdf_availability_(NULL),
539 next_timer_id_(0),
540 last_page_mouse_down_(-1),
541 first_visible_page_(-1),
542 most_visible_page_(-1),
543 called_do_document_action_(false),
544 render_grayscale_(false),
545 progressive_paint_timeout_(0),
546 getting_password_(false) {
547 find_factory_.Initialize(this);
548 password_factory_.Initialize(this);
550 file_access_.m_FileLen = 0;
551 file_access_.m_GetBlock = &GetBlock;
552 file_access_.m_Param = &doc_loader_;
554 file_availability_.version = 1;
555 file_availability_.IsDataAvail = &IsDataAvail;
556 file_availability_.loader = &doc_loader_;
558 download_hints_.version = 1;
559 download_hints_.AddSegment = &AddSegment;
560 download_hints_.loader = &doc_loader_;
562 // Initialize FPDF_FORMFILLINFO member variables. Deriving from this struct
563 // allows the static callbacks to be able to cast the FPDF_FORMFILLINFO in
564 // callbacks to ourself instead of maintaining a map of them to
565 // PDFiumEngine.
566 FPDF_FORMFILLINFO::version = 1;
567 FPDF_FORMFILLINFO::m_pJsPlatform = this;
568 FPDF_FORMFILLINFO::Release = NULL;
569 FPDF_FORMFILLINFO::FFI_Invalidate = Form_Invalidate;
570 FPDF_FORMFILLINFO::FFI_OutputSelectedRect = Form_OutputSelectedRect;
571 FPDF_FORMFILLINFO::FFI_SetCursor = Form_SetCursor;
572 FPDF_FORMFILLINFO::FFI_SetTimer = Form_SetTimer;
573 FPDF_FORMFILLINFO::FFI_KillTimer = Form_KillTimer;
574 FPDF_FORMFILLINFO::FFI_GetLocalTime = Form_GetLocalTime;
575 FPDF_FORMFILLINFO::FFI_OnChange = Form_OnChange;
576 FPDF_FORMFILLINFO::FFI_GetPage = Form_GetPage;
577 FPDF_FORMFILLINFO::FFI_GetCurrentPage = Form_GetCurrentPage;
578 FPDF_FORMFILLINFO::FFI_GetRotation = Form_GetRotation;
579 FPDF_FORMFILLINFO::FFI_ExecuteNamedAction = Form_ExecuteNamedAction;
580 FPDF_FORMFILLINFO::FFI_SetTextFieldFocus = Form_SetTextFieldFocus;
581 FPDF_FORMFILLINFO::FFI_DoURIAction = Form_DoURIAction;
582 FPDF_FORMFILLINFO::FFI_DoGoToAction = Form_DoGoToAction;
584 IPDF_JSPLATFORM::version = 1;
585 IPDF_JSPLATFORM::app_alert = Form_Alert;
586 IPDF_JSPLATFORM::app_beep = Form_Beep;
587 IPDF_JSPLATFORM::app_response = Form_Response;
588 IPDF_JSPLATFORM::Doc_getFilePath = Form_GetFilePath;
589 IPDF_JSPLATFORM::Doc_mail = Form_Mail;
590 IPDF_JSPLATFORM::Doc_print = Form_Print;
591 IPDF_JSPLATFORM::Doc_submitForm = Form_SubmitForm;
592 IPDF_JSPLATFORM::Doc_gotoPage = Form_GotoPage;
593 IPDF_JSPLATFORM::Field_browse = Form_Browse;
595 IFSDK_PAUSE::version = 1;
596 IFSDK_PAUSE::user = NULL;
597 IFSDK_PAUSE::NeedToPauseNow = Pause_NeedToPauseNow;
600 PDFiumEngine::~PDFiumEngine() {
601 STLDeleteElements(&pages_);
602 if (doc_) {
603 if (form_) {
604 FORM_DoDocumentAAction(form_, FPDFDOC_AACTION_WC);
605 FPDFDOC_ExitFormFillEnviroument(form_);
607 FPDF_CloseDocument(doc_);
610 if (fpdf_availability_)
611 FPDFAvail_Destroy(fpdf_availability_);
614 int PDFiumEngine::GetBlock(void* param, unsigned long position,
615 unsigned char* buffer, unsigned long size) {
616 DocumentLoader* loader = static_cast<DocumentLoader*>(param);
617 return loader->GetBlock(position, size, buffer);
620 bool PDFiumEngine::IsDataAvail(FX_FILEAVAIL* param,
621 size_t offset, size_t size) {
622 PDFiumEngine::FileAvail* file_avail =
623 static_cast<PDFiumEngine::FileAvail*>(param);
624 return file_avail->loader->IsDataAvailable(offset, size);
627 void PDFiumEngine::AddSegment(FX_DOWNLOADHINTS* param,
628 size_t offset, size_t size) {
629 PDFiumEngine::DownloadHints* download_hints =
630 static_cast<PDFiumEngine::DownloadHints*>(param);
631 return download_hints->loader->RequestData(offset, size);
634 bool PDFiumEngine::New(const char* url) {
635 url_ = url;
636 headers_ = std::string();
637 return true;
640 bool PDFiumEngine::New(const char* url,
641 const char* headers) {
642 url_ = url;
643 if (!headers)
644 headers_ = std::string();
645 else
646 headers_ = headers;
647 return true;
650 void PDFiumEngine::PageOffsetUpdated(const pp::Point& page_offset) {
651 page_offset_ = page_offset;
654 void PDFiumEngine::PluginSizeUpdated(const pp::Size& size) {
655 CancelPaints();
657 plugin_size_ = size;
658 CalculateVisiblePages();
661 void PDFiumEngine::ScrolledToXPosition(int position) {
662 CancelPaints();
664 int old_x = position_.x();
665 position_.set_x(position);
666 CalculateVisiblePages();
667 client_->Scroll(pp::Point(old_x - position, 0));
670 void PDFiumEngine::ScrolledToYPosition(int position) {
671 CancelPaints();
673 int old_y = position_.y();
674 position_.set_y(position);
675 CalculateVisiblePages();
676 client_->Scroll(pp::Point(0, old_y - position));
679 void PDFiumEngine::PrePaint() {
680 for (size_t i = 0; i < progressive_paints_.size(); ++i)
681 progressive_paints_[i].painted_ = false;
684 void PDFiumEngine::Paint(const pp::Rect& rect,
685 pp::ImageData* image_data,
686 std::vector<pp::Rect>* ready,
687 std::vector<pp::Rect>* pending) {
688 pp::Rect leftover = rect;
689 for (size_t i = 0; i < visible_pages_.size(); ++i) {
690 int index = visible_pages_[i];
691 pp::Rect page_rect = pages_[index]->rect();
692 // Convert the current page's rectangle to screen rectangle. We do this
693 // instead of the reverse (converting the dirty rectangle from screen to
694 // page coordinates) because then we'd have to convert back to screen
695 // coordinates, and the rounding errors sometime leave pixels dirty or even
696 // move the text up or down a pixel when zoomed.
697 pp::Rect page_rect_in_screen = GetPageScreenRect(index);
698 pp::Rect dirty_in_screen = page_rect_in_screen.Intersect(leftover);
699 if (dirty_in_screen.IsEmpty())
700 continue;
702 leftover = leftover.Subtract(dirty_in_screen);
704 if (pages_[index]->available()) {
705 int progressive = GetProgressiveIndex(index);
706 if (progressive != -1 &&
707 progressive_paints_[progressive].rect != dirty_in_screen) {
708 // The PDFium code can only handle one progressive paint at a time, so
709 // queue this up. Previously we used to merge the rects when this
710 // happened, but it made scrolling up on complex PDFs very slow since
711 // there would be a damaged rect at the top (from scroll) and at the
712 // bottom (from toolbar).
713 pending->push_back(dirty_in_screen);
714 continue;
717 if (progressive == -1) {
718 progressive = StartPaint(index, dirty_in_screen);
719 progressive_paint_timeout_ = kMaxInitialProgressivePaintTimeMs;
720 } else {
721 progressive_paint_timeout_ = kMaxProgressivePaintTimeMs;
724 progressive_paints_[progressive].painted_ = true;
725 if (ContinuePaint(progressive, image_data)) {
726 FinishPaint(progressive, image_data);
727 ready->push_back(dirty_in_screen);
728 } else {
729 pending->push_back(dirty_in_screen);
731 } else {
732 PaintUnavailablePage(index, dirty_in_screen, image_data);
733 ready->push_back(dirty_in_screen);
738 void PDFiumEngine::PostPaint() {
739 for (size_t i = 0; i < progressive_paints_.size(); ++i) {
740 if (progressive_paints_[i].painted_)
741 continue;
743 // This rectangle must have been merged with another one, that's why we
744 // weren't asked to paint it. Remove it or otherwise we'll never finish
745 // painting.
746 FPDF_RenderPage_Close(
747 pages_[progressive_paints_[i].page_index]->GetPage());
748 FPDFBitmap_Destroy(progressive_paints_[i].bitmap);
749 progressive_paints_.erase(progressive_paints_.begin() + i);
750 --i;
754 bool PDFiumEngine::HandleDocumentLoad(const pp::URLLoader& loader) {
755 password_tries_remaining_ = kMaxPasswordTries;
756 return doc_loader_.Init(loader, url_, headers_);
759 pp::Instance* PDFiumEngine::GetPluginInstance() {
760 return client_->GetPluginInstance();
763 pp::URLLoader PDFiumEngine::CreateURLLoader() {
764 return client_->CreateURLLoader();
767 void PDFiumEngine::AppendPage(PDFEngine* engine, int index) {
768 // Unload and delete the blank page before appending.
769 pages_[index]->Unload();
770 pages_[index]->set_calculated_links(false);
771 pp::Size curr_page_size = GetPageSize(index);
772 FPDFPage_Delete(doc_, index);
773 FPDF_ImportPages(doc_,
774 static_cast<PDFiumEngine*>(engine)->doc(),
775 "1",
776 index);
777 pp::Size new_page_size = GetPageSize(index);
778 if (curr_page_size != new_page_size)
779 LoadPageInfo(true);
780 client_->Invalidate(GetPageScreenRect(index));
783 pp::Point PDFiumEngine::GetScrollPosition() {
784 return position_;
787 void PDFiumEngine::SetScrollPosition(const pp::Point& position) {
788 position_ = position;
791 bool PDFiumEngine::IsProgressiveLoad() {
792 return doc_loader_.is_partial_document();
795 void PDFiumEngine::OnPartialDocumentLoaded() {
796 file_access_.m_FileLen = doc_loader_.document_size();
797 fpdf_availability_ = FPDFAvail_Create(&file_availability_, &file_access_);
798 DCHECK(fpdf_availability_);
800 // Currently engine does not deal efficiently with some non-linearized files.
801 // See http://code.google.com/p/chromium/issues/detail?id=59400
802 // To improve user experience we download entire file for non-linearized PDF.
803 if (!FPDFAvail_IsLinearized(fpdf_availability_)) {
804 doc_loader_.RequestData(0, doc_loader_.document_size());
805 return;
808 LoadDocument();
811 void PDFiumEngine::OnPendingRequestComplete() {
812 if (!doc_ || !form_) {
813 LoadDocument();
814 return;
817 // LoadDocument() will result in |pending_pages_| being reset so there's no
818 // need to run the code below in that case.
819 bool update_pages = false;
820 std::vector<int> still_pending;
821 for (size_t i = 0; i < pending_pages_.size(); ++i) {
822 if (CheckPageAvailable(pending_pages_[i], &still_pending)) {
823 update_pages = true;
824 if (IsPageVisible(pending_pages_[i]))
825 client_->Invalidate(GetPageScreenRect(pending_pages_[i]));
828 pending_pages_.swap(still_pending);
829 if (update_pages)
830 LoadPageInfo(true);
833 void PDFiumEngine::OnNewDataAvailable() {
834 client_->DocumentLoadProgress(doc_loader_.GetAvailableData(),
835 doc_loader_.document_size());
838 void PDFiumEngine::OnDocumentComplete() {
839 if (!doc_ || !form_) {
840 file_access_.m_FileLen = doc_loader_.document_size();
841 LoadDocument();
842 return;
845 bool need_update = false;
846 for (size_t i = 0; i < pages_.size(); ++i) {
847 if (pages_[i]->available())
848 continue;
850 pages_[i]->set_available(true);
851 // We still need to call IsPageAvail() even if the whole document is
852 // already downloaded.
853 FPDFAvail_IsPageAvail(fpdf_availability_, i, &download_hints_);
854 need_update = true;
855 if (IsPageVisible(i))
856 client_->Invalidate(GetPageScreenRect(i));
858 if (need_update)
859 LoadPageInfo(true);
861 FinishLoadingDocument();
864 void PDFiumEngine::FinishLoadingDocument() {
865 DCHECK(doc_loader_.IsDocumentComplete() && doc_);
866 if (called_do_document_action_)
867 return;
868 called_do_document_action_ = true;
870 // These can only be called now, as the JS might end up needing a page.
871 FORM_DoDocumentJSAction(form_);
872 FORM_DoDocumentOpenAction(form_);
873 if (most_visible_page_ != -1) {
874 FPDF_PAGE new_page = pages_[most_visible_page_]->GetPage();
875 FORM_DoPageAAction(new_page, form_, FPDFPAGE_AACTION_OPEN);
878 if (doc_) // This can only happen if loading |doc_| fails.
879 client_->DocumentLoadComplete(pages_.size());
882 void PDFiumEngine::UnsupportedFeature(int type) {
883 std::string feature;
884 switch (type) {
885 case FPDF_UNSP_DOC_XFAFORM:
886 feature = "XFA";
887 break;
888 case FPDF_UNSP_DOC_PORTABLECOLLECTION:
889 feature = "Portfolios_Packages";
890 break;
891 case FPDF_UNSP_DOC_ATTACHMENT:
892 case FPDF_UNSP_ANNOT_ATTACHMENT:
893 feature = "Attachment";
894 break;
895 case FPDF_UNSP_DOC_SECURITY:
896 feature = "Rights_Management";
897 break;
898 case FPDF_UNSP_DOC_SHAREDREVIEW:
899 feature = "Shared_Review";
900 break;
901 case FPDF_UNSP_DOC_SHAREDFORM_ACROBAT:
902 case FPDF_UNSP_DOC_SHAREDFORM_FILESYSTEM:
903 case FPDF_UNSP_DOC_SHAREDFORM_EMAIL:
904 feature = "Shared_Form";
905 break;
906 case FPDF_UNSP_ANNOT_3DANNOT:
907 feature = "3D";
908 break;
909 case FPDF_UNSP_ANNOT_MOVIE:
910 feature = "Movie";
911 break;
912 case FPDF_UNSP_ANNOT_SOUND:
913 feature = "Sound";
914 break;
915 case FPDF_UNSP_ANNOT_SCREEN_MEDIA:
916 case FPDF_UNSP_ANNOT_SCREEN_RICHMEDIA:
917 feature = "Screen";
918 break;
919 case FPDF_UNSP_ANNOT_SIG:
920 feature = "Digital_Signature";
921 break;
923 client_->DocumentHasUnsupportedFeature(feature);
926 void PDFiumEngine::ContinueFind(int32_t result) {
927 StartFind(current_find_text_.c_str(), !!result);
930 bool PDFiumEngine::HandleEvent(const pp::InputEvent& event) {
931 DCHECK(!defer_page_unload_);
932 defer_page_unload_ = true;
933 bool rv = false;
934 switch (event.GetType()) {
935 case PP_INPUTEVENT_TYPE_MOUSEDOWN:
936 rv = OnMouseDown(pp::MouseInputEvent(event));
937 break;
938 case PP_INPUTEVENT_TYPE_MOUSEUP:
939 rv = OnMouseUp(pp::MouseInputEvent(event));
940 break;
941 case PP_INPUTEVENT_TYPE_MOUSEMOVE:
942 rv = OnMouseMove(pp::MouseInputEvent(event));
943 break;
944 case PP_INPUTEVENT_TYPE_KEYDOWN:
945 rv = OnKeyDown(pp::KeyboardInputEvent(event));
946 break;
947 case PP_INPUTEVENT_TYPE_KEYUP:
948 rv = OnKeyUp(pp::KeyboardInputEvent(event));
949 break;
950 case PP_INPUTEVENT_TYPE_CHAR:
951 rv = OnChar(pp::KeyboardInputEvent(event));
952 break;
953 default:
954 break;
957 DCHECK(defer_page_unload_);
958 defer_page_unload_ = false;
959 for (size_t i = 0; i < deferred_page_unloads_.size(); ++i)
960 pages_[deferred_page_unloads_[i]]->Unload();
961 deferred_page_unloads_.clear();
962 return rv;
965 uint32_t PDFiumEngine::QuerySupportedPrintOutputFormats() {
966 if (!HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY))
967 return 0;
968 return PP_PRINTOUTPUTFORMAT_PDF;
971 void PDFiumEngine::PrintBegin() {
972 FORM_DoDocumentAAction(form_, FPDFDOC_AACTION_WP);
975 pp::Resource PDFiumEngine::PrintPages(
976 const PP_PrintPageNumberRange_Dev* page_ranges, uint32_t page_range_count,
977 const PP_PrintSettings_Dev& print_settings) {
978 if (HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY))
979 return PrintPagesAsPDF(page_ranges, page_range_count, print_settings);
980 else if (HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY))
981 return PrintPagesAsRasterPDF(page_ranges, page_range_count, print_settings);
982 return pp::Resource();
985 pp::Buffer_Dev PDFiumEngine::PrintPagesAsRasterPDF(
986 const PP_PrintPageNumberRange_Dev* page_ranges, uint32_t page_range_count,
987 const PP_PrintSettings_Dev& print_settings) {
988 if (!page_range_count)
989 return pp::Buffer_Dev();
991 // If document is not downloaded yet, disable printing.
992 if (doc_ && !doc_loader_.IsDocumentComplete())
993 return pp::Buffer_Dev();
995 FPDF_DOCUMENT output_doc = FPDF_CreateNewDocument();
996 if (!output_doc)
997 return pp::Buffer_Dev();
999 SaveSelectedFormForPrint();
1001 std::vector<PDFiumPage> pages_to_print;
1002 // width and height of source PDF pages.
1003 std::vector<std::pair<double, double> > source_page_sizes;
1004 // Collect pages to print and sizes of source pages.
1005 std::vector<uint32_t> page_numbers =
1006 GetPageNumbersFromPrintPageNumberRange(page_ranges, page_range_count);
1007 for (size_t i = 0; i < page_numbers.size(); ++i) {
1008 uint32_t page_number = page_numbers[i];
1009 FPDF_PAGE pdf_page = FPDF_LoadPage(doc_, page_number);
1010 double source_page_width = FPDF_GetPageWidth(pdf_page);
1011 double source_page_height = FPDF_GetPageHeight(pdf_page);
1012 source_page_sizes.push_back(std::make_pair(source_page_width,
1013 source_page_height));
1015 int width_in_pixels = ConvertUnit(source_page_width,
1016 static_cast<int>(kPointsPerInch),
1017 print_settings.dpi);
1018 int height_in_pixels = ConvertUnit(source_page_height,
1019 static_cast<int>(kPointsPerInch),
1020 print_settings.dpi);
1022 pp::Rect rect(width_in_pixels, height_in_pixels);
1023 pages_to_print.push_back(PDFiumPage(this, page_number, rect, true));
1024 FPDF_ClosePage(pdf_page);
1027 #if defined(OS_LINUX)
1028 g_last_instance_id = client_->GetPluginInstance()->pp_instance();
1029 #endif
1031 size_t i = 0;
1032 for (; i < pages_to_print.size(); ++i) {
1033 double source_page_width = source_page_sizes[i].first;
1034 double source_page_height = source_page_sizes[i].second;
1035 const pp::Size& bitmap_size(pages_to_print[i].rect().size());
1037 // Use temp_doc to compress image by saving PDF to buffer.
1038 FPDF_DOCUMENT temp_doc = FPDF_CreateNewDocument();
1039 if (!temp_doc)
1040 break;
1042 FPDF_PAGE output_page = FPDFPage_New(temp_doc, 0, source_page_width,
1043 source_page_height);
1045 pp::ImageData image = pp::ImageData(client_->GetPluginInstance(),
1046 PP_IMAGEDATAFORMAT_BGRA_PREMUL,
1047 bitmap_size,
1048 false);
1050 FPDF_BITMAP bitmap = FPDFBitmap_CreateEx(bitmap_size.width(),
1051 bitmap_size.height(),
1052 FPDFBitmap_BGRx,
1053 image.data(),
1054 image.stride());
1056 // Clear the bitmap
1057 FPDFBitmap_FillRect(bitmap, 0, 0, bitmap_size.width(),
1058 bitmap_size.height(), 0xFFFFFFFF);
1060 pp::Rect page_rect = pages_to_print[i].rect();
1061 FPDF_RenderPageBitmap(bitmap, pages_to_print[i].GetPrintPage(),
1062 page_rect.x(), page_rect.y(),
1063 page_rect.width(), page_rect.height(),
1064 print_settings.orientation,
1065 FPDF_ANNOT | FPDF_PRINTING | FPDF_NO_CATCH);
1067 double ratio_x = (static_cast<double>(bitmap_size.width()) *
1068 kPointsPerInch) / print_settings.dpi;
1069 double ratio_y = (static_cast<double>(bitmap_size.height()) *
1070 kPointsPerInch) / print_settings.dpi;
1072 // Add the bitmap to an image object and add the image object to the output
1073 // page.
1074 FPDF_PAGEOBJECT img_obj = FPDFPageObj_NewImgeObj(output_doc);
1075 FPDFImageObj_SetBitmap(&output_page, 1, img_obj, bitmap);
1076 FPDFImageObj_SetMatrix(img_obj, ratio_x, 0, 0, ratio_y, 0, 0);
1077 FPDFPage_InsertObject(output_page, img_obj);
1078 FPDFPage_GenerateContent(output_page);
1079 FPDF_ClosePage(output_page);
1081 pages_to_print[i].ClosePrintPage();
1082 FPDFBitmap_Destroy(bitmap);
1084 pp::Buffer_Dev buffer = GetFlattenedPrintData(temp_doc);
1085 FPDF_CloseDocument(temp_doc);
1087 PDFiumMemBufferFileRead file_read(buffer.data(), buffer.size());
1088 temp_doc = FPDF_LoadCustomDocument(&file_read, NULL);
1089 if (!temp_doc)
1090 break;
1092 FPDF_BOOL imported = FPDF_ImportPages(output_doc, temp_doc, "1", i);
1093 FPDF_CloseDocument(temp_doc);
1094 if (!imported)
1095 break;
1098 pp::Buffer_Dev buffer;
1099 if (i == pages_to_print.size()) {
1100 FPDF_CopyViewerPreferences(output_doc, doc_);
1101 FitContentsToPrintableAreaIfRequired(output_doc, print_settings);
1102 // Now flatten all the output pages.
1103 buffer = GetFlattenedPrintData(output_doc);
1105 FPDF_CloseDocument(output_doc);
1106 return buffer;
1109 pp::Buffer_Dev PDFiumEngine::GetFlattenedPrintData(const FPDF_DOCUMENT& doc) {
1110 int page_count = FPDF_GetPageCount(doc);
1111 bool flatten_succeeded = true;
1112 for (int i = 0; i < page_count; ++i) {
1113 FPDF_PAGE page = FPDF_LoadPage(doc, i);
1114 DCHECK(page);
1115 if (page) {
1116 int flatten_ret = FPDFPage_Flatten(page, FLAT_PRINT);
1117 FPDF_ClosePage(page);
1118 if (flatten_ret == FLATTEN_FAIL) {
1119 flatten_succeeded = false;
1120 break;
1122 } else {
1123 flatten_succeeded = false;
1124 break;
1127 if (!flatten_succeeded) {
1128 FPDF_CloseDocument(doc);
1129 return pp::Buffer_Dev();
1132 pp::Buffer_Dev buffer;
1133 PDFiumMemBufferFileWrite output_file_write;
1134 if (FPDF_SaveAsCopy(doc, &output_file_write, 0)) {
1135 buffer = pp::Buffer_Dev(
1136 client_->GetPluginInstance(), output_file_write.size());
1137 if (!buffer.is_null()) {
1138 memcpy(buffer.data(), output_file_write.buffer().c_str(),
1139 output_file_write.size());
1142 return buffer;
1145 pp::Buffer_Dev PDFiumEngine::PrintPagesAsPDF(
1146 const PP_PrintPageNumberRange_Dev* page_ranges, uint32_t page_range_count,
1147 const PP_PrintSettings_Dev& print_settings) {
1148 if (!page_range_count)
1149 return pp::Buffer_Dev();
1151 DCHECK(doc_);
1152 FPDF_DOCUMENT output_doc = FPDF_CreateNewDocument();
1153 if (!output_doc)
1154 return pp::Buffer_Dev();
1156 SaveSelectedFormForPrint();
1158 std::string page_number_str;
1159 for (uint32_t index = 0; index < page_range_count; ++index) {
1160 if (!page_number_str.empty())
1161 page_number_str.append(",");
1162 page_number_str.append(
1163 base::IntToString(page_ranges[index].first_page_number + 1));
1164 if (page_ranges[index].first_page_number !=
1165 page_ranges[index].last_page_number) {
1166 page_number_str.append("-");
1167 page_number_str.append(
1168 base::IntToString(page_ranges[index].last_page_number + 1));
1172 std::vector<uint32_t> page_numbers =
1173 GetPageNumbersFromPrintPageNumberRange(page_ranges, page_range_count);
1174 for (size_t i = 0; i < page_numbers.size(); ++i) {
1175 uint32_t page_number = page_numbers[i];
1176 pages_[page_number]->GetPage();
1177 if (!IsPageVisible(page_numbers[i]))
1178 pages_[page_number]->Unload();
1181 FPDF_CopyViewerPreferences(output_doc, doc_);
1182 if (!FPDF_ImportPages(output_doc, doc_, page_number_str.c_str(), 0)) {
1183 FPDF_CloseDocument(output_doc);
1184 return pp::Buffer_Dev();
1187 FitContentsToPrintableAreaIfRequired(output_doc, print_settings);
1189 // Now flatten all the output pages.
1190 pp::Buffer_Dev buffer = GetFlattenedPrintData(output_doc);
1191 FPDF_CloseDocument(output_doc);
1192 return buffer;
1195 void PDFiumEngine::FitContentsToPrintableAreaIfRequired(
1196 const FPDF_DOCUMENT& doc, const PP_PrintSettings_Dev& print_settings) {
1197 // Check to see if we need to fit pdf contents to printer paper size.
1198 if (print_settings.print_scaling_option !=
1199 PP_PRINTSCALINGOPTION_SOURCE_SIZE) {
1200 int num_pages = FPDF_GetPageCount(doc);
1201 // In-place transformation is more efficient than creating a new
1202 // transformed document from the source document. Therefore, transform
1203 // every page to fit the contents in the selected printer paper.
1204 for (int i = 0; i < num_pages; ++i) {
1205 FPDF_PAGE page = FPDF_LoadPage(doc, i);
1206 TransformPDFPageForPrinting(page, print_settings);
1207 FPDF_ClosePage(page);
1212 void PDFiumEngine::SaveSelectedFormForPrint() {
1213 FORM_ForceToKillFocus(form_);
1214 client_->FormTextFieldFocusChange(false);
1217 void PDFiumEngine::PrintEnd() {
1218 FORM_DoDocumentAAction(form_, FPDFDOC_AACTION_DP);
1221 PDFiumPage::Area PDFiumEngine::GetCharIndex(
1222 const pp::MouseInputEvent& event, int* page_index,
1223 int* char_index, PDFiumPage::LinkTarget* target) {
1224 // First figure out which page this is in.
1225 pp::Point mouse_point = event.GetPosition();
1226 pp::Point point(
1227 static_cast<int>((mouse_point.x() + position_.x()) / current_zoom_),
1228 static_cast<int>((mouse_point.y() + position_.y()) / current_zoom_));
1229 return GetCharIndex(point, page_index, char_index, target);
1232 PDFiumPage::Area PDFiumEngine::GetCharIndex(
1233 const pp::Point& point,
1234 int* page_index,
1235 int* char_index,
1236 PDFiumPage::LinkTarget* target) {
1237 int page = -1;
1238 for (size_t i = 0; i < visible_pages_.size(); ++i) {
1239 if (pages_[visible_pages_[i]]->rect().Contains(point)) {
1240 page = visible_pages_[i];
1241 break;
1244 if (page == -1)
1245 return PDFiumPage::NONSELECTABLE_AREA;
1247 // If the page hasn't finished rendering, calling into the page sometimes
1248 // leads to hangs.
1249 for (size_t i = 0; i < progressive_paints_.size(); ++i) {
1250 if (progressive_paints_[i].page_index == page)
1251 return PDFiumPage::NONSELECTABLE_AREA;
1254 *page_index = page;
1255 return pages_[page]->GetCharIndex(point, current_rotation_, char_index,
1256 target);
1259 bool PDFiumEngine::OnMouseDown(const pp::MouseInputEvent& event) {
1260 if (event.GetButton() != PP_INPUTEVENT_MOUSEBUTTON_LEFT)
1261 return false;
1263 SelectionChangeInvalidator selection_invalidator(this);
1264 selection_.clear();
1266 int page_index = -1;
1267 int char_index = -1;
1268 PDFiumPage::LinkTarget target;
1269 PDFiumPage::Area area = GetCharIndex(event, &page_index,
1270 &char_index, &target);
1271 if (area == PDFiumPage::WEBLINK_AREA) {
1272 bool open_in_new_tab = !!(event.GetModifiers() & kDefaultKeyModifier);
1273 client_->NavigateTo(target.url, open_in_new_tab);
1274 client_->FormTextFieldFocusChange(false);
1275 return true;
1278 if (area == PDFiumPage::DOCLINK_AREA) {
1279 client_->ScrollToPage(target.page);
1280 client_->FormTextFieldFocusChange(false);
1281 return true;
1284 if (page_index != -1) {
1285 last_page_mouse_down_ = page_index;
1286 double page_x, page_y;
1287 pp::Point point = event.GetPosition();
1288 DeviceToPage(page_index, point.x(), point.y(), &page_x, &page_y);
1290 FORM_OnLButtonDown(form_, pages_[page_index]->GetPage(), 0, page_x, page_y);
1291 int control = FPDPage_HasFormFieldAtPoint(
1292 form_, pages_[page_index]->GetPage(), page_x, page_y);
1293 if (control > FPDF_FORMFIELD_UNKNOWN) { // returns -1 sometimes...
1294 client_->FormTextFieldFocusChange(control == FPDF_FORMFIELD_TEXTFIELD ||
1295 control == FPDF_FORMFIELD_COMBOBOX);
1296 return true; // Return now before we get into the selection code.
1300 client_->FormTextFieldFocusChange(false);
1302 if (area != PDFiumPage::TEXT_AREA)
1303 return true; // Return true so WebKit doesn't do its own highlighting.
1305 if (event.GetClickCount() == 1) {
1306 OnSingleClick(page_index, char_index);
1307 } else if (event.GetClickCount() == 2 ||
1308 event.GetClickCount() == 3) {
1309 OnMultipleClick(event.GetClickCount(), page_index, char_index);
1312 return true;
1315 void PDFiumEngine::OnSingleClick(int page_index, int char_index) {
1316 selecting_ = true;
1317 selection_.push_back(PDFiumRange(pages_[page_index], char_index, 0));
1320 void PDFiumEngine::OnMultipleClick(int click_count,
1321 int page_index,
1322 int char_index) {
1323 // It would be more efficient if the SDK could support finding a space, but
1324 // now it doesn't.
1325 int start_index = char_index;
1326 do {
1327 base::char16 cur = pages_[page_index]->GetCharAtIndex(start_index);
1328 // For double click, we want to select one word so we look for whitespace
1329 // boundaries. For triple click, we want the whole line.
1330 if (cur == '\n' || (click_count == 2 && (cur == ' ' || cur == '\t')))
1331 break;
1332 } while (--start_index >= 0);
1333 if (start_index)
1334 start_index++;
1336 int end_index = char_index;
1337 int total = pages_[page_index]->GetCharCount();
1338 while (end_index++ <= total) {
1339 base::char16 cur = pages_[page_index]->GetCharAtIndex(end_index);
1340 if (cur == '\n' || (click_count == 2 && (cur == ' ' || cur == '\t')))
1341 break;
1344 selection_.push_back(PDFiumRange(
1345 pages_[page_index], start_index, end_index - start_index));
1348 bool PDFiumEngine::OnMouseUp(const pp::MouseInputEvent& event) {
1349 if (event.GetButton() != PP_INPUTEVENT_MOUSEBUTTON_LEFT)
1350 return false;
1352 int page_index = -1;
1353 int char_index = -1;
1354 GetCharIndex(event, &page_index, &char_index, NULL);
1355 if (page_index != -1) {
1356 double page_x, page_y;
1357 pp::Point point = event.GetPosition();
1358 DeviceToPage(page_index, point.x(), point.y(), &page_x, &page_y);
1359 FORM_OnLButtonUp(
1360 form_, pages_[page_index]->GetPage(), 0, page_x, page_y);
1363 if (!selecting_)
1364 return false;
1366 selecting_ = false;
1367 return true;
1370 bool PDFiumEngine::OnMouseMove(const pp::MouseInputEvent& event) {
1371 int page_index = -1;
1372 int char_index = -1;
1373 PDFiumPage::Area area = GetCharIndex(event, &page_index, &char_index, NULL);
1374 if (!selecting_) {
1375 PP_CursorType_Dev cursor;
1376 switch (area) {
1377 case PDFiumPage::TEXT_AREA:
1378 cursor = PP_CURSORTYPE_IBEAM;
1379 break;
1380 case PDFiumPage::WEBLINK_AREA:
1381 case PDFiumPage::DOCLINK_AREA:
1382 cursor = PP_CURSORTYPE_HAND;
1383 break;
1384 case PDFiumPage::NONSELECTABLE_AREA:
1385 default:
1386 cursor = PP_CURSORTYPE_POINTER;
1387 break;
1390 if (page_index != -1) {
1391 double page_x, page_y;
1392 pp::Point point = event.GetPosition();
1393 DeviceToPage(page_index, point.x(), point.y(), &page_x, &page_y);
1395 FORM_OnMouseMove(form_, pages_[page_index]->GetPage(), 0, page_x, page_y);
1396 int control = FPDPage_HasFormFieldAtPoint(
1397 form_, pages_[page_index]->GetPage(), page_x, page_y);
1398 switch (control) {
1399 case FPDF_FORMFIELD_PUSHBUTTON:
1400 case FPDF_FORMFIELD_CHECKBOX:
1401 case FPDF_FORMFIELD_RADIOBUTTON:
1402 case FPDF_FORMFIELD_COMBOBOX:
1403 case FPDF_FORMFIELD_LISTBOX:
1404 cursor = PP_CURSORTYPE_HAND;
1405 break;
1406 case FPDF_FORMFIELD_TEXTFIELD:
1407 cursor = PP_CURSORTYPE_IBEAM;
1408 break;
1409 default:
1410 break;
1414 client_->UpdateCursor(cursor);
1415 pp::Point point = event.GetPosition();
1416 std::string url = GetLinkAtPosition(event.GetPosition());
1417 if (url != link_under_cursor_) {
1418 link_under_cursor_ = url;
1419 pp::PDF::SetLinkUnderCursor(GetPluginInstance(), url.c_str());
1421 // No need to swallow the event, since this might interfere with the
1422 // scrollbars if the user is dragging them.
1423 return false;
1426 // We're selecting but right now we're not over text, so don't change the
1427 // current selection.
1428 if (area != PDFiumPage::TEXT_AREA && area != PDFiumPage::WEBLINK_AREA &&
1429 area != PDFiumPage::DOCLINK_AREA) {
1430 return false;
1433 SelectionChangeInvalidator selection_invalidator(this);
1435 // Check if the user has descreased their selection area and we need to remove
1436 // pages from selection_.
1437 for (size_t i = 0; i < selection_.size(); ++i) {
1438 if (selection_[i].page_index() == page_index) {
1439 // There should be no other pages after this.
1440 selection_.erase(selection_.begin() + i + 1, selection_.end());
1441 break;
1445 if (selection_.size() == 0)
1446 return false;
1448 int last = selection_.size() - 1;
1449 if (selection_[last].page_index() == page_index) {
1450 // Selecting within a page.
1451 int count;
1452 if (char_index >= selection_[last].char_index()) {
1453 // Selecting forward.
1454 count = char_index - selection_[last].char_index() + 1;
1455 } else {
1456 count = char_index - selection_[last].char_index() - 1;
1458 selection_[last].SetCharCount(count);
1459 } else if (selection_[last].page_index() < page_index) {
1460 // Selecting into the next page.
1462 // First make sure that there are no gaps in selection, i.e. if mousedown on
1463 // page one but we only get mousemove over page three, we want page two.
1464 for (int i = selection_[last].page_index() + 1; i < page_index; ++i) {
1465 selection_.push_back(PDFiumRange(pages_[i], 0,
1466 pages_[i]->GetCharCount()));
1469 int count = pages_[selection_[last].page_index()]->GetCharCount();
1470 selection_[last].SetCharCount(count - selection_[last].char_index());
1471 selection_.push_back(PDFiumRange(pages_[page_index], 0, char_index));
1472 } else {
1473 // Selecting into the previous page.
1474 selection_[last].SetCharCount(-selection_[last].char_index());
1476 // First make sure that there are no gaps in selection, i.e. if mousedown on
1477 // page three but we only get mousemove over page one, we want page two.
1478 for (int i = selection_[last].page_index() - 1; i > page_index; --i) {
1479 selection_.push_back(PDFiumRange(pages_[i], 0,
1480 pages_[i]->GetCharCount()));
1483 int count = pages_[page_index]->GetCharCount();
1484 selection_.push_back(
1485 PDFiumRange(pages_[page_index], count, count - char_index));
1488 return true;
1491 bool PDFiumEngine::OnKeyDown(const pp::KeyboardInputEvent& event) {
1492 if (last_page_mouse_down_ == -1)
1493 return false;
1495 bool rv = !!FORM_OnKeyDown(
1496 form_, pages_[last_page_mouse_down_]->GetPage(),
1497 event.GetKeyCode(), event.GetModifiers());
1499 if (event.GetKeyCode() == ui::VKEY_BACK ||
1500 event.GetKeyCode() == ui::VKEY_ESCAPE) {
1501 // Chrome doesn't send char events for backspace or escape keys, see
1502 // PlatformKeyboardEventBuilder::isCharacterKey() and
1503 // http://chrome-corpsvn.mtv.corp.google.com/viewvc?view=rev&root=chrome&revision=31805
1504 // for more information. So just fake one since PDFium uses it.
1505 std::string str;
1506 str.push_back(event.GetKeyCode());
1507 pp::KeyboardInputEvent synthesized(pp::KeyboardInputEvent(
1508 client_->GetPluginInstance(),
1509 PP_INPUTEVENT_TYPE_CHAR,
1510 event.GetTimeStamp(),
1511 event.GetModifiers(),
1512 event.GetKeyCode(),
1513 str));
1514 OnChar(synthesized);
1517 return rv;
1520 bool PDFiumEngine::OnKeyUp(const pp::KeyboardInputEvent& event) {
1521 if (last_page_mouse_down_ == -1)
1522 return false;
1524 return !!FORM_OnKeyUp(
1525 form_, pages_[last_page_mouse_down_]->GetPage(),
1526 event.GetKeyCode(), event.GetModifiers());
1529 bool PDFiumEngine::OnChar(const pp::KeyboardInputEvent& event) {
1530 if (last_page_mouse_down_ == -1)
1531 return false;
1533 base::string16 str = base::UTF8ToUTF16(event.GetCharacterText().AsString());
1534 return !!FORM_OnChar(
1535 form_, pages_[last_page_mouse_down_]->GetPage(),
1536 str[0],
1537 event.GetModifiers());
1540 void PDFiumEngine::StartFind(const char* text, bool case_sensitive) {
1541 // We can get a call to StartFind before we have any page information (i.e.
1542 // before the first call to LoadDocument has happened). Handle this case.
1543 if (pages_.empty())
1544 return;
1546 bool first_search = false;
1547 int character_to_start_searching_from = 0;
1548 if (current_find_text_ != text) { // First time we search for this text.
1549 first_search = true;
1550 std::vector<PDFiumRange> old_selection = selection_;
1551 StopFind();
1552 current_find_text_ = text;
1554 if (old_selection.empty()) {
1555 // Start searching from the beginning of the document.
1556 next_page_to_search_ = 0;
1557 last_page_to_search_ = pages_.size() - 1;
1558 last_character_index_to_search_ = -1;
1559 } else {
1560 // There's a current selection, so start from it.
1561 next_page_to_search_ = old_selection[0].page_index();
1562 last_character_index_to_search_ = old_selection[0].char_index();
1563 character_to_start_searching_from = old_selection[0].char_index();
1564 last_page_to_search_ = next_page_to_search_;
1568 int current_page = next_page_to_search_;
1570 if (pages_[current_page]->available()) {
1571 base::string16 str = base::UTF8ToUTF16(text);
1572 // Don't use PDFium to search for now, since it doesn't support unicode text.
1573 // Leave the code for now to avoid bit-rot, in case it's fixed later.
1574 if (0) {
1575 SearchUsingPDFium(
1576 str, case_sensitive, first_search, character_to_start_searching_from,
1577 current_page);
1578 } else {
1579 SearchUsingICU(
1580 str, case_sensitive, first_search, character_to_start_searching_from,
1581 current_page);
1584 if (!IsPageVisible(current_page))
1585 pages_[current_page]->Unload();
1588 if (next_page_to_search_ != last_page_to_search_ ||
1589 (first_search && last_character_index_to_search_ != -1)) {
1590 ++next_page_to_search_;
1593 if (next_page_to_search_ == static_cast<int>(pages_.size()))
1594 next_page_to_search_ = 0;
1595 // If there's only one page in the document and we start searching midway,
1596 // then we'll want to search the page one more time.
1597 bool end_of_search =
1598 next_page_to_search_ == last_page_to_search_ &&
1599 // Only one page but didn't start midway.
1600 ((pages_.size() == 1 && last_character_index_to_search_ == -1) ||
1601 // Started midway, but only 1 page and we already looped around.
1602 (pages_.size() == 1 && !first_search) ||
1603 // Started midway, and we've just looped around.
1604 (pages_.size() > 1 && current_page == next_page_to_search_));
1606 if (end_of_search) {
1607 // Send the final notification.
1608 client_->NotifyNumberOfFindResultsChanged(find_results_.size(), true);
1609 } else {
1610 pp::CompletionCallback callback =
1611 find_factory_.NewCallback(&PDFiumEngine::ContinueFind);
1612 pp::Module::Get()->core()->CallOnMainThread(
1613 0, callback, case_sensitive ? 1 : 0);
1617 void PDFiumEngine::SearchUsingPDFium(const base::string16& term,
1618 bool case_sensitive,
1619 bool first_search,
1620 int character_to_start_searching_from,
1621 int current_page) {
1622 // Find all the matches in the current page.
1623 unsigned long flags = case_sensitive ? FPDF_MATCHCASE : 0;
1624 FPDF_SCHHANDLE find = FPDFText_FindStart(
1625 pages_[current_page]->GetTextPage(),
1626 reinterpret_cast<const unsigned short*>(term.c_str()),
1627 flags, character_to_start_searching_from);
1629 // Note: since we search one page at a time, we don't find matches across
1630 // page boundaries. We could do this manually ourself, but it seems low
1631 // priority since Reader itself doesn't do it.
1632 while (FPDFText_FindNext(find)) {
1633 PDFiumRange result(pages_[current_page],
1634 FPDFText_GetSchResultIndex(find),
1635 FPDFText_GetSchCount(find));
1637 if (!first_search &&
1638 last_character_index_to_search_ != -1 &&
1639 result.page_index() == last_page_to_search_ &&
1640 result.char_index() >= last_character_index_to_search_) {
1641 break;
1644 AddFindResult(result);
1647 FPDFText_FindClose(find);
1650 void PDFiumEngine::SearchUsingICU(const base::string16& term,
1651 bool case_sensitive,
1652 bool first_search,
1653 int character_to_start_searching_from,
1654 int current_page) {
1655 base::string16 page_text;
1656 int text_length = pages_[current_page]->GetCharCount();
1657 if (character_to_start_searching_from) {
1658 text_length -= character_to_start_searching_from;
1659 } else if (!first_search &&
1660 last_character_index_to_search_ != -1 &&
1661 current_page == last_page_to_search_) {
1662 text_length = last_character_index_to_search_;
1664 if (text_length <= 0)
1665 return;
1666 unsigned short* data =
1667 reinterpret_cast<unsigned short*>(WriteInto(&page_text, text_length + 1));
1668 FPDFText_GetText(pages_[current_page]->GetTextPage(),
1669 character_to_start_searching_from,
1670 text_length,
1671 data);
1672 std::vector<PDFEngine::Client::SearchStringResult> results;
1673 client_->SearchString(
1674 page_text.c_str(), term.c_str(), case_sensitive, &results);
1675 for (size_t i = 0; i < results.size(); ++i) {
1676 // Need to map the indexes from the page text, which may have generated
1677 // characters like space etc, to character indices from the page.
1678 int temp_start = results[i].start_index + character_to_start_searching_from;
1679 int start = FPDFText_GetCharIndexFromTextIndex(
1680 pages_[current_page]->GetTextPage(), temp_start);
1681 int end = FPDFText_GetCharIndexFromTextIndex(
1682 pages_[current_page]->GetTextPage(),
1683 temp_start + results[i].length);
1684 AddFindResult(PDFiumRange(pages_[current_page], start, end - start));
1688 void PDFiumEngine::AddFindResult(const PDFiumRange& result) {
1689 // Figure out where to insert the new location, since we could have
1690 // started searching midway and now we wrapped.
1691 size_t i;
1692 int page_index = result.page_index();
1693 int char_index = result.char_index();
1694 for (i = 0; i < find_results_.size(); ++i) {
1695 if (find_results_[i].page_index() > page_index ||
1696 (find_results_[i].page_index() == page_index &&
1697 find_results_[i].char_index() > char_index)) {
1698 break;
1701 find_results_.insert(find_results_.begin() + i, result);
1702 UpdateTickMarks();
1704 if (current_find_index_ == -1) {
1705 // Select the first match.
1706 SelectFindResult(true);
1707 } else if (static_cast<int>(i) <= current_find_index_) {
1708 // Update the current match index
1709 current_find_index_++;
1710 client_->NotifySelectedFindResultChanged(current_find_index_);
1712 client_->NotifyNumberOfFindResultsChanged(find_results_.size(), false);
1715 bool PDFiumEngine::SelectFindResult(bool forward) {
1716 if (find_results_.empty()) {
1717 NOTREACHED();
1718 return false;
1721 SelectionChangeInvalidator selection_invalidator(this);
1723 // Move back/forward through the search locations we previously found.
1724 if (forward) {
1725 if (++current_find_index_ == static_cast<int>(find_results_.size()))
1726 current_find_index_ = 0;
1727 } else {
1728 if (--current_find_index_ < 0) {
1729 current_find_index_ = find_results_.size() - 1;
1733 // Update the selection before telling the client to scroll, since it could
1734 // paint then.
1735 selection_.clear();
1736 selection_.push_back(find_results_[current_find_index_]);
1738 // If the result is not in view, scroll to it.
1739 size_t i;
1740 pp::Rect bounding_rect;
1741 pp::Rect visible_rect = GetVisibleRect();
1742 // Use zoom of 1.0 since visible_rect is without zoom.
1743 std::vector<pp::Rect> rects = find_results_[current_find_index_].
1744 GetScreenRects(pp::Point(), 1.0, current_rotation_);
1745 for (i = 0; i < rects.size(); ++i)
1746 bounding_rect = bounding_rect.Union(rects[i]);
1747 if (!visible_rect.Contains(bounding_rect)) {
1748 pp::Point center = bounding_rect.CenterPoint();
1749 // Make the page centered.
1750 int new_y = static_cast<int>(center.y() * current_zoom_) -
1751 static_cast<int>(visible_rect.height() * current_zoom_ / 2);
1752 if (new_y < 0)
1753 new_y = 0;
1754 client_->ScrollToY(new_y);
1756 // Only move horizontally if it's not visible.
1757 if (center.x() < visible_rect.x() || center.x() > visible_rect.right()) {
1758 int new_x = static_cast<int>(center.x() * current_zoom_) -
1759 static_cast<int>(visible_rect.width() * current_zoom_ / 2);
1760 if (new_x < 0)
1761 new_x = 0;
1762 client_->ScrollToX(new_x);
1766 client_->NotifySelectedFindResultChanged(current_find_index_);
1768 return true;
1771 void PDFiumEngine::StopFind() {
1772 SelectionChangeInvalidator selection_invalidator(this);
1774 selection_.clear();
1775 selecting_ = false;
1776 find_results_.clear();
1777 next_page_to_search_ = -1;
1778 last_page_to_search_ = -1;
1779 last_character_index_to_search_ = -1;
1780 current_find_index_ = -1;
1781 current_find_text_.clear();
1782 UpdateTickMarks();
1783 find_factory_.CancelAll();
1786 void PDFiumEngine::UpdateTickMarks() {
1787 std::vector<pp::Rect> tickmarks;
1788 for (size_t i = 0; i < find_results_.size(); ++i) {
1789 pp::Rect rect;
1790 // Always use an origin of 0,0 since scroll positions don't affect tickmark.
1791 std::vector<pp::Rect> rects = find_results_[i].GetScreenRects(
1792 pp::Point(0, 0), current_zoom_, current_rotation_);
1793 for (size_t j = 0; j < rects.size(); ++j)
1794 rect = rect.Union(rects[j]);
1795 tickmarks.push_back(rect);
1798 client_->UpdateTickMarks(tickmarks);
1801 void PDFiumEngine::ZoomUpdated(double new_zoom_level) {
1802 CancelPaints();
1804 current_zoom_ = new_zoom_level;
1806 CalculateVisiblePages();
1807 UpdateTickMarks();
1810 void PDFiumEngine::RotateClockwise() {
1811 current_rotation_ = (current_rotation_ + 1) % 4;
1812 InvalidateAllPages();
1815 void PDFiumEngine::RotateCounterclockwise() {
1816 current_rotation_ = (current_rotation_ - 1) % 4;
1817 InvalidateAllPages();
1820 void PDFiumEngine::InvalidateAllPages() {
1821 selection_.clear();
1822 find_results_.clear();
1824 CancelPaints();
1825 LoadPageInfo(true);
1826 UpdateTickMarks();
1827 client_->Invalidate(pp::Rect(plugin_size_));
1830 std::string PDFiumEngine::GetSelectedText() {
1831 base::string16 result;
1832 for (size_t i = 0; i < selection_.size(); ++i) {
1833 if (i > 0 &&
1834 selection_[i - 1].page_index() > selection_[i].page_index()) {
1835 result = selection_[i].GetText() + result;
1836 } else {
1837 result.append(selection_[i].GetText());
1841 return base::UTF16ToUTF8(result);
1844 std::string PDFiumEngine::GetLinkAtPosition(const pp::Point& point) {
1845 int temp;
1846 PDFiumPage::LinkTarget target;
1847 PDFiumPage::Area area = GetCharIndex(point, &temp, &temp, &target);
1848 if (area == PDFiumPage::WEBLINK_AREA)
1849 return target.url;
1850 return std::string();
1853 bool PDFiumEngine::IsSelecting() {
1854 return selecting_;
1857 bool PDFiumEngine::HasPermission(DocumentPermission permission) const {
1858 switch (permission) {
1859 case PERMISSION_COPY:
1860 return (permissions_ & kPDFPermissionCopyMask) != 0;
1861 case PERMISSION_COPY_ACCESSIBLE:
1862 return (permissions_ & kPDFPermissionCopyAccessibleMask) != 0;
1863 case PERMISSION_PRINT_LOW_QUALITY:
1864 return (permissions_ & kPDFPermissionPrintLowQualityMask) != 0;
1865 case PERMISSION_PRINT_HIGH_QUALITY:
1866 return (permissions_ & kPDFPermissionPrintLowQualityMask) != 0 &&
1867 (permissions_ & kPDFPermissionPrintHighQualityMask) != 0;
1868 default:
1869 return true;
1873 void PDFiumEngine::SelectAll() {
1874 SelectionChangeInvalidator selection_invalidator(this);
1876 selection_.clear();
1877 for (size_t i = 0; i < pages_.size(); ++i)
1878 if (pages_[i]->available()) {
1879 selection_.push_back(PDFiumRange(pages_[i], 0,
1880 pages_[i]->GetCharCount()));
1884 int PDFiumEngine::GetNumberOfPages() {
1885 return pages_.size();
1888 int PDFiumEngine::GetNamedDestinationPage(const std::string& destination) {
1889 // Look for the destination.
1890 FPDF_DEST dest = FPDF_GetNamedDestByName(doc_, destination.c_str());
1891 if (!dest) {
1892 // Look for a bookmark with the same name.
1893 base::string16 destination_wide = base::UTF8ToUTF16(destination);
1894 FPDF_WIDESTRING destination_pdf_wide =
1895 reinterpret_cast<FPDF_WIDESTRING>(destination_wide.c_str());
1896 FPDF_BOOKMARK bookmark = FPDFBookmark_Find(doc_, destination_pdf_wide);
1897 if (!bookmark)
1898 return -1;
1899 dest = FPDFBookmark_GetDest(doc_, bookmark);
1901 return dest ? FPDFDest_GetPageIndex(doc_, dest) : -1;
1904 int PDFiumEngine::GetFirstVisiblePage() {
1905 CalculateVisiblePages();
1906 return first_visible_page_;
1909 int PDFiumEngine::GetMostVisiblePage() {
1910 CalculateVisiblePages();
1911 return most_visible_page_;
1914 pp::Rect PDFiumEngine::GetPageRect(int index) {
1915 pp::Rect rc(pages_[index]->rect());
1916 rc.Inset(-kPageShadowLeft, -kPageShadowTop,
1917 -kPageShadowRight, -kPageShadowBottom);
1918 return rc;
1921 pp::Rect PDFiumEngine::GetPageContentsRect(int index) {
1922 return GetScreenRect(pages_[index]->rect());
1925 void PDFiumEngine::PaintThumbnail(pp::ImageData* image_data, int index) {
1926 FPDF_BITMAP bitmap = FPDFBitmap_CreateEx(
1927 image_data->size().width(), image_data->size().height(),
1928 FPDFBitmap_BGRx, image_data->data(), image_data->stride());
1930 if (pages_[index]->available()) {
1931 FPDFBitmap_FillRect(bitmap, 0, 0, image_data->size().width(),
1932 image_data->size().height(), 0xFFFFFFFF);
1934 FPDF_RenderPageBitmap(
1935 bitmap, pages_[index]->GetPage(), 0, 0, image_data->size().width(),
1936 image_data->size().height(), 0, GetRenderingFlags());
1937 } else {
1938 FPDFBitmap_FillRect(bitmap, 0, 0, image_data->size().width(),
1939 image_data->size().height(), kPendingPageColor);
1942 FPDFBitmap_Destroy(bitmap);
1945 void PDFiumEngine::SetGrayscale(bool grayscale) {
1946 render_grayscale_ = grayscale;
1949 void PDFiumEngine::OnCallback(int id) {
1950 if (!timers_.count(id))
1951 return;
1953 timers_[id].second(id);
1954 if (timers_.count(id)) // The callback might delete the timer.
1955 client_->ScheduleCallback(id, timers_[id].first);
1958 std::string PDFiumEngine::GetPageAsJSON(int index) {
1959 if (!(HasPermission(PERMISSION_COPY) ||
1960 HasPermission(PERMISSION_COPY_ACCESSIBLE))) {
1961 return "{}";
1964 if (index < 0 || static_cast<size_t>(index) > pages_.size() - 1)
1965 return "{}";
1967 scoped_ptr<base::Value> node(
1968 pages_[index]->GetAccessibleContentAsValue(current_rotation_));
1969 std::string page_json;
1970 base::JSONWriter::Write(node.get(), &page_json);
1971 return page_json;
1974 bool PDFiumEngine::GetPrintScaling() {
1975 return !!FPDF_VIEWERREF_GetPrintScaling(doc_);
1978 void PDFiumEngine::AppendBlankPages(int num_pages) {
1979 DCHECK(num_pages != 0);
1981 if (!doc_)
1982 return;
1984 selection_.clear();
1985 pending_pages_.clear();
1987 // Delete all pages except the first one.
1988 while (pages_.size() > 1) {
1989 delete pages_.back();
1990 pages_.pop_back();
1991 FPDFPage_Delete(doc_, pages_.size());
1994 // Calculate document size and all page sizes.
1995 std::vector<pp::Rect> page_rects;
1996 pp::Size page_size = GetPageSize(0);
1997 page_size.Enlarge(kPageShadowLeft + kPageShadowRight,
1998 kPageShadowTop + kPageShadowBottom);
1999 pp::Size old_document_size = document_size_;
2000 document_size_ = pp::Size(page_size.width(), 0);
2001 for (int i = 0; i < num_pages; ++i) {
2002 if (i != 0) {
2003 // Add space for horizontal separator.
2004 document_size_.Enlarge(0, kPageSeparatorThickness);
2007 pp::Rect rect(pp::Point(0, document_size_.height()), page_size);
2008 page_rects.push_back(rect);
2010 document_size_.Enlarge(0, page_size.height());
2013 // Create blank pages.
2014 for (int i = 1; i < num_pages; ++i) {
2015 pp::Rect page_rect(page_rects[i]);
2016 page_rect.Inset(kPageShadowLeft, kPageShadowTop,
2017 kPageShadowRight, kPageShadowBottom);
2018 double width_in_points =
2019 page_rect.width() * kPointsPerInch / kPixelsPerInch;
2020 double height_in_points =
2021 page_rect.height() * kPointsPerInch / kPixelsPerInch;
2022 FPDFPage_New(doc_, i, width_in_points, height_in_points);
2023 pages_.push_back(new PDFiumPage(this, i, page_rect, true));
2026 CalculateVisiblePages();
2027 if (document_size_ != old_document_size)
2028 client_->DocumentSizeUpdated(document_size_);
2031 void PDFiumEngine::LoadDocument() {
2032 // Check if the document is ready for loading. If it isn't just bail for now,
2033 // we will call LoadDocument() again later.
2034 if (!doc_ && !doc_loader_.IsDocumentComplete() &&
2035 !FPDFAvail_IsDocAvail(fpdf_availability_, &download_hints_)) {
2036 return;
2039 // If we're in the middle of getting a password, just return. We will retry
2040 // loading the document after we get the password anyway.
2041 if (getting_password_)
2042 return;
2044 ScopedUnsupportedFeature scoped_unsupported_feature(this);
2045 bool needs_password = false;
2046 if (TryLoadingDoc(false, std::string(), &needs_password)) {
2047 ContinueLoadingDocument(false, std::string());
2048 return;
2050 if (needs_password)
2051 GetPasswordAndLoad();
2052 else
2053 client_->DocumentLoadFailed();
2056 bool PDFiumEngine::TryLoadingDoc(bool with_password,
2057 const std::string& password,
2058 bool* needs_password) {
2059 *needs_password = false;
2060 if (doc_)
2061 return true;
2063 const char* password_cstr = NULL;
2064 if (with_password) {
2065 password_cstr = password.c_str();
2066 password_tries_remaining_--;
2068 if (doc_loader_.IsDocumentComplete())
2069 doc_ = FPDF_LoadCustomDocument(&file_access_, password_cstr);
2070 else
2071 doc_ = FPDFAvail_GetDocument(fpdf_availability_, password_cstr);
2073 if (!doc_ && FPDF_GetLastError() == FPDF_ERR_PASSWORD)
2074 *needs_password = true;
2076 return doc_ != NULL;
2079 void PDFiumEngine::GetPasswordAndLoad() {
2080 getting_password_ = true;
2081 DCHECK(!doc_ && FPDF_GetLastError() == FPDF_ERR_PASSWORD);
2082 client_->GetDocumentPassword(password_factory_.NewCallbackWithOutput(
2083 &PDFiumEngine::OnGetPasswordComplete));
2086 void PDFiumEngine::OnGetPasswordComplete(int32_t result,
2087 const pp::Var& password) {
2088 getting_password_ = false;
2090 bool password_given = false;
2091 std::string password_text;
2092 if (result == PP_OK && password.is_string()) {
2093 password_text = password.AsString();
2094 if (!password_text.empty())
2095 password_given = true;
2097 ContinueLoadingDocument(password_given, password_text);
2100 void PDFiumEngine::ContinueLoadingDocument(
2101 bool has_password,
2102 const std::string& password) {
2103 ScopedUnsupportedFeature scoped_unsupported_feature(this);
2105 bool needs_password = false;
2106 bool loaded = TryLoadingDoc(has_password, password, &needs_password);
2107 bool password_incorrect = !loaded && has_password && needs_password;
2108 if (password_incorrect && password_tries_remaining_ > 0) {
2109 GetPasswordAndLoad();
2110 return;
2113 if (!doc_) {
2114 client_->DocumentLoadFailed();
2115 return;
2118 if (FPDFDoc_GetPageMode(doc_) == PAGEMODE_USEOUTLINES)
2119 client_->DocumentHasUnsupportedFeature("Bookmarks");
2121 permissions_ = FPDF_GetDocPermissions(doc_);
2123 if (!form_) {
2124 // Only returns 0 when data isn't available. If form data is downloaded, or
2125 // if this isn't a form, returns positive values.
2126 if (!doc_loader_.IsDocumentComplete() &&
2127 !FPDFAvail_IsFormAvail(fpdf_availability_, &download_hints_)) {
2128 return;
2131 form_ = FPDFDOC_InitFormFillEnviroument(
2132 doc_, static_cast<FPDF_FORMFILLINFO*>(this));
2133 FPDF_SetFormFieldHighlightColor(form_, 0, kFormHighlightColor);
2134 FPDF_SetFormFieldHighlightAlpha(form_, kFormHighlightAlpha);
2137 if (!doc_loader_.IsDocumentComplete()) {
2138 // Check if the first page is available. In a linearized PDF, that is not
2139 // always page 0. Doing this gives us the default page size, since when the
2140 // document is available, the first page is available as well.
2141 CheckPageAvailable(FPDFAvail_GetFirstPageNum(doc_), &pending_pages_);
2144 LoadPageInfo(false);
2146 if (doc_loader_.IsDocumentComplete())
2147 FinishLoadingDocument();
2150 void PDFiumEngine::LoadPageInfo(bool reload) {
2151 pending_pages_.clear();
2152 pp::Size old_document_size = document_size_;
2153 document_size_ = pp::Size();
2154 std::vector<pp::Rect> page_rects;
2155 int page_count = FPDF_GetPageCount(doc_);
2156 bool doc_complete = doc_loader_.IsDocumentComplete();
2157 for (int i = 0; i < page_count; ++i) {
2158 if (i != 0) {
2159 // Add space for horizontal separator.
2160 document_size_.Enlarge(0, kPageSeparatorThickness);
2163 // Get page availability. If reload==false, and document is not loaded yet
2164 // (we are using async loading) - mark all pages as unavailable.
2165 // If reload==true (we have document constructed already), get page
2166 // availability flag from already existing PDFiumPage class.
2167 bool page_available = reload ? pages_[i]->available() : doc_complete;
2169 pp::Size size = page_available ? GetPageSize(i) : default_page_size_;
2170 size.Enlarge(kPageShadowLeft + kPageShadowRight,
2171 kPageShadowTop + kPageShadowBottom);
2172 pp::Rect rect(pp::Point(0, document_size_.height()), size);
2173 page_rects.push_back(rect);
2175 if (size.width() > document_size_.width())
2176 document_size_.set_width(size.width());
2178 document_size_.Enlarge(0, size.height());
2181 for (int i = 0; i < page_count; ++i) {
2182 // Center pages relative to the entire document.
2183 page_rects[i].set_x((document_size_.width() - page_rects[i].width()) / 2);
2184 pp::Rect page_rect(page_rects[i]);
2185 page_rect.Inset(kPageShadowLeft, kPageShadowTop,
2186 kPageShadowRight, kPageShadowBottom);
2187 if (reload) {
2188 pages_[i]->set_rect(page_rect);
2189 } else {
2190 pages_.push_back(new PDFiumPage(this, i, page_rect, doc_complete));
2194 CalculateVisiblePages();
2195 if (document_size_ != old_document_size)
2196 client_->DocumentSizeUpdated(document_size_);
2199 void PDFiumEngine::CalculateVisiblePages() {
2200 // Clear pending requests queue, since it may contain requests to the pages
2201 // that are already invisible (after scrolling for example).
2202 pending_pages_.clear();
2203 doc_loader_.ClearPendingRequests();
2205 visible_pages_.clear();
2206 pp::Rect visible_rect(plugin_size_);
2207 for (size_t i = 0; i < pages_.size(); ++i) {
2208 // Check an entire PageScreenRect, since we might need to repaint side
2209 // borders and shadows even if the page itself is not visible.
2210 // For example, when user use pdf with different page sizes and zoomed in
2211 // outside page area.
2212 if (visible_rect.Intersects(GetPageScreenRect(i))) {
2213 visible_pages_.push_back(i);
2214 CheckPageAvailable(i, &pending_pages_);
2215 } else {
2216 // Need to unload pages when we're not using them, since some PDFs use a
2217 // lot of memory. See http://crbug.com/48791
2218 if (defer_page_unload_) {
2219 deferred_page_unloads_.push_back(i);
2220 } else {
2221 pages_[i]->Unload();
2224 // If the last mouse down was on a page that's no longer visible, reset
2225 // that variable so that we don't send keyboard events to it (the focus
2226 // will be lost when the page is first closed anyways).
2227 if (static_cast<int>(i) == last_page_mouse_down_)
2228 last_page_mouse_down_ = -1;
2232 // Any pending highlighting of form fields will be invalid since these are in
2233 // screen coordinates.
2234 form_highlights_.clear();
2236 if (visible_pages_.size() == 0)
2237 first_visible_page_ = -1;
2238 else
2239 first_visible_page_ = visible_pages_.front();
2241 int most_visible_page = first_visible_page_;
2242 // Check if the next page is more visible than the first one.
2243 if (most_visible_page != -1 &&
2244 pages_.size() > 0 &&
2245 most_visible_page < static_cast<int>(pages_.size()) - 1) {
2246 pp::Rect rc_first =
2247 visible_rect.Intersect(GetPageScreenRect(most_visible_page));
2248 pp::Rect rc_next =
2249 visible_rect.Intersect(GetPageScreenRect(most_visible_page + 1));
2250 if (rc_next.height() > rc_first.height())
2251 most_visible_page++;
2254 SetCurrentPage(most_visible_page);
2257 bool PDFiumEngine::IsPageVisible(int index) const {
2258 for (size_t i = 0; i < visible_pages_.size(); ++i) {
2259 if (visible_pages_[i] == index)
2260 return true;
2263 return false;
2266 bool PDFiumEngine::CheckPageAvailable(int index, std::vector<int>* pending) {
2267 if (!doc_ || !form_)
2268 return false;
2270 if (static_cast<int>(pages_.size()) > index && pages_[index]->available())
2271 return true;
2273 if (!FPDFAvail_IsPageAvail(fpdf_availability_, index, &download_hints_)) {
2274 size_t j;
2275 for (j = 0; j < pending->size(); ++j) {
2276 if ((*pending)[j] == index)
2277 break;
2280 if (j == pending->size())
2281 pending->push_back(index);
2282 return false;
2285 if (static_cast<int>(pages_.size()) > index)
2286 pages_[index]->set_available(true);
2287 if (!default_page_size_.GetArea())
2288 default_page_size_ = GetPageSize(index);
2289 return true;
2292 pp::Size PDFiumEngine::GetPageSize(int index) {
2293 pp::Size size;
2294 double width_in_points = 0;
2295 double height_in_points = 0;
2296 int rv = FPDF_GetPageSizeByIndex(
2297 doc_, index, &width_in_points, &height_in_points);
2299 if (rv) {
2300 int width_in_pixels = static_cast<int>(
2301 width_in_points * kPixelsPerInch / kPointsPerInch);
2302 int height_in_pixels = static_cast<int>(
2303 height_in_points * kPixelsPerInch / kPointsPerInch);
2304 if (current_rotation_ % 2 == 1)
2305 std::swap(width_in_pixels, height_in_pixels);
2306 size = pp::Size(width_in_pixels, height_in_pixels);
2308 return size;
2311 int PDFiumEngine::StartPaint(int page_index, const pp::Rect& dirty) {
2312 // For the first time we hit paint, do nothing and just record the paint for
2313 // the next callback. This keeps the UI responsive in case the user is doing
2314 // a lot of scrolling.
2315 ProgressivePaint progressive;
2316 progressive.rect = dirty;
2317 progressive.page_index = page_index;
2318 progressive.bitmap = NULL;
2319 progressive.painted_ = false;
2320 progressive_paints_.push_back(progressive);
2321 return progressive_paints_.size() - 1;
2324 bool PDFiumEngine::ContinuePaint(int progressive_index,
2325 pp::ImageData* image_data) {
2326 #if defined(OS_LINUX)
2327 g_last_instance_id = client_->GetPluginInstance()->pp_instance();
2328 #endif
2330 int rv;
2331 int page_index = progressive_paints_[progressive_index].page_index;
2332 last_progressive_start_time_ = base::Time::Now();
2333 if (progressive_paints_[progressive_index].bitmap) {
2334 rv = FPDF_RenderPage_Continue(
2335 pages_[page_index]->GetPage(), static_cast<IFSDK_PAUSE*>(this));
2336 } else {
2337 pp::Rect dirty = progressive_paints_[progressive_index].rect;
2338 progressive_paints_[progressive_index].bitmap = CreateBitmap(dirty,
2339 image_data);
2340 int start_x, start_y, size_x, size_y;
2341 GetPDFiumRect(
2342 page_index, dirty, &start_x, &start_y, &size_x, &size_y);
2343 FPDFBitmap_FillRect(progressive_paints_[progressive_index].bitmap, start_x,
2344 start_y, size_x, size_y, 0xFFFFFFFF);
2345 rv = FPDF_RenderPageBitmap_Start(
2346 progressive_paints_[progressive_index].bitmap,
2347 pages_[page_index]->GetPage(), start_x, start_y, size_x, size_y,
2348 current_rotation_,
2349 GetRenderingFlags(), static_cast<IFSDK_PAUSE*>(this));
2351 return rv != FPDF_RENDER_TOBECOUNTINUED;
2354 void PDFiumEngine::FinishPaint(int progressive_index,
2355 pp::ImageData* image_data) {
2356 int page_index = progressive_paints_[progressive_index].page_index;
2357 pp::Rect dirty_in_screen = progressive_paints_[progressive_index].rect;
2358 FPDF_BITMAP bitmap = progressive_paints_[progressive_index].bitmap;
2359 int start_x, start_y, size_x, size_y;
2360 GetPDFiumRect(
2361 page_index, dirty_in_screen, &start_x, &start_y, &size_x, &size_y);
2363 // Draw the forms.
2364 FPDF_FFLDraw(
2365 form_, bitmap, pages_[page_index]->GetPage(), start_x, start_y, size_x,
2366 size_y, current_rotation_, GetRenderingFlags());
2368 FillPageSides(progressive_index);
2370 // Paint the page shadows.
2371 PaintPageShadow(progressive_index, image_data);
2373 DrawSelections(progressive_index, image_data);
2375 FPDF_RenderPage_Close(pages_[page_index]->GetPage());
2376 FPDFBitmap_Destroy(bitmap);
2377 progressive_paints_.erase(progressive_paints_.begin() + progressive_index);
2379 client_->DocumentPaintOccurred();
2382 void PDFiumEngine::CancelPaints() {
2383 for (size_t i = 0; i < progressive_paints_.size(); ++i) {
2384 FPDF_RenderPage_Close(pages_[progressive_paints_[i].page_index]->GetPage());
2385 FPDFBitmap_Destroy(progressive_paints_[i].bitmap);
2387 progressive_paints_.clear();
2390 void PDFiumEngine::FillPageSides(int progressive_index) {
2391 int page_index = progressive_paints_[progressive_index].page_index;
2392 pp::Rect dirty_in_screen = progressive_paints_[progressive_index].rect;
2393 FPDF_BITMAP bitmap = progressive_paints_[progressive_index].bitmap;
2395 pp::Rect page_rect = pages_[page_index]->rect();
2396 if (page_rect.x() > 0) {
2397 pp::Rect left(0,
2398 page_rect.y() - kPageShadowTop,
2399 page_rect.x() - kPageShadowLeft,
2400 page_rect.height() + kPageShadowTop +
2401 kPageShadowBottom + kPageSeparatorThickness);
2402 left = GetScreenRect(left).Intersect(dirty_in_screen);
2404 FPDFBitmap_FillRect(bitmap, left.x() - dirty_in_screen.x(),
2405 left.y() - dirty_in_screen.y(), left.width(),
2406 left.height(), kBackgroundColor);
2409 if (page_rect.right() < document_size_.width()) {
2410 pp::Rect right(page_rect.right() + kPageShadowRight,
2411 page_rect.y() - kPageShadowTop,
2412 document_size_.width() - page_rect.right() -
2413 kPageShadowRight,
2414 page_rect.height() + kPageShadowTop +
2415 kPageShadowBottom + kPageSeparatorThickness);
2416 right = GetScreenRect(right).Intersect(dirty_in_screen);
2418 FPDFBitmap_FillRect(bitmap, right.x() - dirty_in_screen.x(),
2419 right.y() - dirty_in_screen.y(), right.width(),
2420 right.height(), kBackgroundColor);
2423 // Paint separator.
2424 pp::Rect bottom(page_rect.x() - kPageShadowLeft,
2425 page_rect.bottom() + kPageShadowBottom,
2426 page_rect.width() + kPageShadowLeft + kPageShadowRight,
2427 kPageSeparatorThickness);
2428 bottom = GetScreenRect(bottom).Intersect(dirty_in_screen);
2430 FPDFBitmap_FillRect(bitmap, bottom.x() - dirty_in_screen.x(),
2431 bottom.y() - dirty_in_screen.y(), bottom.width(),
2432 bottom.height(), kBackgroundColor);
2435 void PDFiumEngine::PaintPageShadow(int progressive_index,
2436 pp::ImageData* image_data) {
2437 int page_index = progressive_paints_[progressive_index].page_index;
2438 pp::Rect dirty_in_screen = progressive_paints_[progressive_index].rect;
2439 pp::Rect page_rect = pages_[page_index]->rect();
2440 pp::Rect shadow_rect(page_rect);
2441 shadow_rect.Inset(-kPageShadowLeft, -kPageShadowTop,
2442 -kPageShadowRight, -kPageShadowBottom);
2444 // Due to the rounding errors of the GetScreenRect it is possible to get
2445 // different size shadows on the left and right sides even they are defined
2446 // the same. To fix this issue let's calculate shadow rect and then shrink
2447 // it by the size of the shadows.
2448 shadow_rect = GetScreenRect(shadow_rect);
2449 page_rect = shadow_rect;
2451 page_rect.Inset(static_cast<int>(ceil(kPageShadowLeft * current_zoom_)),
2452 static_cast<int>(ceil(kPageShadowTop * current_zoom_)),
2453 static_cast<int>(ceil(kPageShadowRight * current_zoom_)),
2454 static_cast<int>(ceil(kPageShadowBottom * current_zoom_)));
2456 DrawPageShadow(page_rect, shadow_rect, dirty_in_screen, image_data);
2459 void PDFiumEngine::DrawSelections(int progressive_index,
2460 pp::ImageData* image_data) {
2461 int page_index = progressive_paints_[progressive_index].page_index;
2462 pp::Rect dirty_in_screen = progressive_paints_[progressive_index].rect;
2464 void* region = NULL;
2465 int stride;
2466 GetRegion(dirty_in_screen.point(), image_data, &region, &stride);
2468 std::vector<pp::Rect> highlighted_rects;
2469 pp::Rect visible_rect = GetVisibleRect();
2470 for (size_t k = 0; k < selection_.size(); ++k) {
2471 if (selection_[k].page_index() != page_index)
2472 continue;
2473 std::vector<pp::Rect> rects = selection_[k].GetScreenRects(
2474 visible_rect.point(), current_zoom_, current_rotation_);
2475 for (size_t j = 0; j < rects.size(); ++j) {
2476 pp::Rect visible_selection = rects[j].Intersect(dirty_in_screen);
2477 if (visible_selection.IsEmpty())
2478 continue;
2480 visible_selection.Offset(
2481 -dirty_in_screen.point().x(), -dirty_in_screen.point().y());
2482 Highlight(region, stride, visible_selection, &highlighted_rects);
2486 for (size_t k = 0; k < form_highlights_.size(); ++k) {
2487 pp::Rect visible_selection = form_highlights_[k].Intersect(dirty_in_screen);
2488 if (visible_selection.IsEmpty())
2489 continue;
2491 visible_selection.Offset(
2492 -dirty_in_screen.point().x(), -dirty_in_screen.point().y());
2493 Highlight(region, stride, visible_selection, &highlighted_rects);
2495 form_highlights_.clear();
2498 void PDFiumEngine::PaintUnavailablePage(int page_index,
2499 const pp::Rect& dirty,
2500 pp::ImageData* image_data) {
2501 int start_x, start_y, size_x, size_y;
2502 GetPDFiumRect(page_index, dirty, &start_x, &start_y, &size_x, &size_y);
2503 FPDF_BITMAP bitmap = CreateBitmap(dirty, image_data);
2504 FPDFBitmap_FillRect(bitmap, start_x, start_y, size_x, size_y,
2505 kPendingPageColor);
2507 pp::Rect loading_text_in_screen(
2508 pages_[page_index]->rect().width() / 2,
2509 pages_[page_index]->rect().y() + kLoadingTextVerticalOffset, 0, 0);
2510 loading_text_in_screen = GetScreenRect(loading_text_in_screen);
2511 FPDFBitmap_Destroy(bitmap);
2514 int PDFiumEngine::GetProgressiveIndex(int page_index) const {
2515 for (size_t i = 0; i < progressive_paints_.size(); ++i) {
2516 if (progressive_paints_[i].page_index == page_index)
2517 return i;
2519 return -1;
2522 FPDF_BITMAP PDFiumEngine::CreateBitmap(const pp::Rect& rect,
2523 pp::ImageData* image_data) const {
2524 void* region;
2525 int stride;
2526 GetRegion(rect.point(), image_data, &region, &stride);
2527 if (!region)
2528 return NULL;
2529 return FPDFBitmap_CreateEx(
2530 rect.width(), rect.height(), FPDFBitmap_BGRx, region, stride);
2533 void PDFiumEngine::GetPDFiumRect(
2534 int page_index, const pp::Rect& rect, int* start_x, int* start_y,
2535 int* size_x, int* size_y) const {
2536 pp::Rect page_rect = GetScreenRect(pages_[page_index]->rect());
2537 page_rect.Offset(-rect.x(), -rect.y());
2539 *start_x = page_rect.x();
2540 *start_y = page_rect.y();
2541 *size_x = page_rect.width();
2542 *size_y = page_rect.height();
2545 int PDFiumEngine::GetRenderingFlags() const {
2546 int flags = FPDF_LCD_TEXT | FPDF_NO_CATCH;
2547 if (render_grayscale_)
2548 flags |= FPDF_GRAYSCALE;
2549 if (client_->IsPrintPreview())
2550 flags |= FPDF_PRINTING;
2551 return flags;
2554 pp::Rect PDFiumEngine::GetVisibleRect() const {
2555 pp::Rect rv;
2556 rv.set_x(static_cast<int>(position_.x() / current_zoom_));
2557 rv.set_y(static_cast<int>(position_.y() / current_zoom_));
2558 rv.set_width(static_cast<int>(ceil(plugin_size_.width() / current_zoom_)));
2559 rv.set_height(static_cast<int>(ceil(plugin_size_.height() / current_zoom_)));
2560 return rv;
2563 pp::Rect PDFiumEngine::GetPageScreenRect(int page_index) const {
2564 // Since we use this rect for creating the PDFium bitmap, also include other
2565 // areas around the page that we might need to update such as the page
2566 // separator and the sides if the page is narrower than the document.
2567 return GetScreenRect(pp::Rect(
2569 pages_[page_index]->rect().y() - kPageShadowTop,
2570 document_size_.width(),
2571 pages_[page_index]->rect().height() + kPageShadowTop +
2572 kPageShadowBottom + kPageSeparatorThickness));
2575 pp::Rect PDFiumEngine::GetScreenRect(const pp::Rect& rect) const {
2576 pp::Rect rv;
2577 int right =
2578 static_cast<int>(ceil(rect.right() * current_zoom_ - position_.x()));
2579 int bottom =
2580 static_cast<int>(ceil(rect.bottom() * current_zoom_ - position_.y()));
2582 rv.set_x(static_cast<int>(rect.x() * current_zoom_ - position_.x()));
2583 rv.set_y(static_cast<int>(rect.y() * current_zoom_ - position_.y()));
2584 rv.set_width(right - rv.x());
2585 rv.set_height(bottom - rv.y());
2586 return rv;
2589 void PDFiumEngine::Highlight(void* buffer,
2590 int stride,
2591 const pp::Rect& rect,
2592 std::vector<pp::Rect>* highlighted_rects) {
2593 if (!buffer)
2594 return;
2596 pp::Rect new_rect = rect;
2597 for (size_t i = 0; i < highlighted_rects->size(); ++i)
2598 new_rect = new_rect.Subtract((*highlighted_rects)[i]);
2600 highlighted_rects->push_back(new_rect);
2601 int l = new_rect.x();
2602 int t = new_rect.y();
2603 int w = new_rect.width();
2604 int h = new_rect.height();
2606 for (int y = t; y < t + h; ++y) {
2607 for (int x = l; x < l + w; ++x) {
2608 uint8* pixel = static_cast<uint8*>(buffer) + y * stride + x * 4;
2609 // This is our highlight color.
2610 pixel[0] = static_cast<uint8>(
2611 pixel[0] * (kHighlightColorB / 255.0));
2612 pixel[1] = static_cast<uint8>(
2613 pixel[1] * (kHighlightColorG / 255.0));
2614 pixel[2] = static_cast<uint8>(
2615 pixel[2] * (kHighlightColorR / 255.0));
2620 PDFiumEngine::SelectionChangeInvalidator::SelectionChangeInvalidator(
2621 PDFiumEngine* engine) : engine_(engine) {
2622 previous_origin_ = engine_->GetVisibleRect().point();
2623 GetVisibleSelectionsScreenRects(&old_selections_);
2626 PDFiumEngine::SelectionChangeInvalidator::~SelectionChangeInvalidator() {
2627 // Offset the old selections if the document scrolled since we recorded them.
2628 pp::Point offset = previous_origin_ - engine_->GetVisibleRect().point();
2629 for (size_t i = 0; i < old_selections_.size(); ++i)
2630 old_selections_[i].Offset(offset);
2632 std::vector<pp::Rect> new_selections;
2633 GetVisibleSelectionsScreenRects(&new_selections);
2634 for (size_t i = 0; i < new_selections.size(); ++i) {
2635 for (size_t j = 0; j < old_selections_.size(); ++j) {
2636 if (new_selections[i] == old_selections_[j]) {
2637 // Rectangle was selected before and after, so no need to invalidate it.
2638 // Mark the rectangles by setting them to empty.
2639 new_selections[i] = old_selections_[j] = pp::Rect();
2644 for (size_t i = 0; i < old_selections_.size(); ++i) {
2645 if (!old_selections_[i].IsEmpty())
2646 engine_->client_->Invalidate(old_selections_[i]);
2648 for (size_t i = 0; i < new_selections.size(); ++i) {
2649 if (!new_selections[i].IsEmpty())
2650 engine_->client_->Invalidate(new_selections[i]);
2652 engine_->OnSelectionChanged();
2655 void
2656 PDFiumEngine::SelectionChangeInvalidator::GetVisibleSelectionsScreenRects(
2657 std::vector<pp::Rect>* rects) {
2658 pp::Rect visible_rect = engine_->GetVisibleRect();
2659 for (size_t i = 0; i < engine_->selection_.size(); ++i) {
2660 int page_index = engine_->selection_[i].page_index();
2661 if (!engine_->IsPageVisible(page_index))
2662 continue; // This selection is on a page that's not currently visible.
2664 std::vector<pp::Rect> selection_rects =
2665 engine_->selection_[i].GetScreenRects(
2666 visible_rect.point(),
2667 engine_->current_zoom_,
2668 engine_->current_rotation_);
2669 rects->insert(rects->end(), selection_rects.begin(), selection_rects.end());
2673 void PDFiumEngine::DeviceToPage(int page_index,
2674 float device_x,
2675 float device_y,
2676 double* page_x,
2677 double* page_y) {
2678 *page_x = *page_y = 0;
2679 int temp_x = static_cast<int>((device_x + position_.x())/ current_zoom_ -
2680 pages_[page_index]->rect().x());
2681 int temp_y = static_cast<int>((device_y + position_.y())/ current_zoom_ -
2682 pages_[page_index]->rect().y());
2683 FPDF_DeviceToPage(
2684 pages_[page_index]->GetPage(), 0, 0,
2685 pages_[page_index]->rect().width(), pages_[page_index]->rect().height(),
2686 current_rotation_, temp_x, temp_y, page_x, page_y);
2689 int PDFiumEngine::GetVisiblePageIndex(FPDF_PAGE page) {
2690 for (size_t i = 0; i < visible_pages_.size(); ++i) {
2691 if (pages_[visible_pages_[i]]->GetPage() == page)
2692 return visible_pages_[i];
2694 return -1;
2697 void PDFiumEngine::SetCurrentPage(int index) {
2698 if (index == most_visible_page_ || !form_)
2699 return;
2700 if (most_visible_page_ != -1 && called_do_document_action_) {
2701 FPDF_PAGE old_page = pages_[most_visible_page_]->GetPage();
2702 FORM_DoPageAAction(old_page, form_, FPDFPAGE_AACTION_CLOSE);
2704 most_visible_page_ = index;
2705 #if defined(OS_LINUX)
2706 g_last_instance_id = client_->GetPluginInstance()->pp_instance();
2707 #endif
2708 if (most_visible_page_ != -1 && called_do_document_action_) {
2709 FPDF_PAGE new_page = pages_[most_visible_page_]->GetPage();
2710 FORM_DoPageAAction(new_page, form_, FPDFPAGE_AACTION_OPEN);
2714 void PDFiumEngine::TransformPDFPageForPrinting(
2715 FPDF_PAGE page,
2716 const PP_PrintSettings_Dev& print_settings) {
2717 // Get the source page width and height in points.
2718 const double src_page_width = FPDF_GetPageWidth(page);
2719 const double src_page_height = FPDF_GetPageHeight(page);
2721 const int src_page_rotation = FPDFPage_GetRotation(page);
2722 const bool fit_to_page = print_settings.print_scaling_option ==
2723 PP_PRINTSCALINGOPTION_FIT_TO_PRINTABLE_AREA;
2725 pp::Size page_size(print_settings.paper_size);
2726 pp::Rect content_rect(print_settings.printable_area);
2727 const bool rotated = (src_page_rotation % 2 == 1);
2728 SetPageSizeAndContentRect(rotated,
2729 src_page_width > src_page_height,
2730 &page_size,
2731 &content_rect);
2733 // Compute the screen page width and height in points.
2734 const int actual_page_width =
2735 rotated ? page_size.height() : page_size.width();
2736 const int actual_page_height =
2737 rotated ? page_size.width() : page_size.height();
2739 const double scale_factor = CalculateScaleFactor(fit_to_page, content_rect,
2740 src_page_width,
2741 src_page_height, rotated);
2743 // Calculate positions for the clip box.
2744 ClipBox source_clip_box;
2745 CalculateClipBoxBoundary(page, scale_factor, rotated, &source_clip_box);
2747 // Calculate the translation offset values.
2748 double offset_x = 0;
2749 double offset_y = 0;
2750 if (fit_to_page) {
2751 CalculateScaledClipBoxOffset(content_rect, source_clip_box, &offset_x,
2752 &offset_y);
2753 } else {
2754 CalculateNonScaledClipBoxOffset(content_rect, src_page_rotation,
2755 actual_page_width, actual_page_height,
2756 source_clip_box, &offset_x, &offset_y);
2759 // Reset the media box and crop box. When the page has crop box and media box,
2760 // the plugin will display the crop box contents and not the entire media box.
2761 // If the pages have different crop box values, the plugin will display a
2762 // document of multiple page sizes. To give better user experience, we
2763 // decided to have same crop box and media box values. Hence, the user will
2764 // see a list of uniform pages.
2765 FPDFPage_SetMediaBox(page, 0, 0, page_size.width(), page_size.height());
2766 FPDFPage_SetCropBox(page, 0, 0, page_size.width(), page_size.height());
2768 // Transformation is not required, return. Do this check only after updating
2769 // the media box and crop box. For more detailed information, please refer to
2770 // the comment block right before FPDF_SetMediaBox and FPDF_GetMediaBox calls.
2771 if (scale_factor == 1.0 && offset_x == 0 && offset_y == 0)
2772 return;
2775 // All the positions have been calculated, now manipulate the PDF.
2776 FS_MATRIX matrix = {static_cast<float>(scale_factor),
2779 static_cast<float>(scale_factor),
2780 static_cast<float>(offset_x),
2781 static_cast<float>(offset_y)};
2782 FS_RECTF cliprect = {static_cast<float>(source_clip_box.left+offset_x),
2783 static_cast<float>(source_clip_box.top+offset_y),
2784 static_cast<float>(source_clip_box.right+offset_x),
2785 static_cast<float>(source_clip_box.bottom+offset_y)};
2786 FPDFPage_TransFormWithClip(page, &matrix, &cliprect);
2787 FPDFPage_TransformAnnots(page, scale_factor, 0, 0, scale_factor,
2788 offset_x, offset_y);
2791 void PDFiumEngine::DrawPageShadow(const pp::Rect& page_rc,
2792 const pp::Rect& shadow_rc,
2793 const pp::Rect& clip_rc,
2794 pp::ImageData* image_data) {
2795 pp::Rect page_rect(page_rc);
2796 page_rect.Offset(page_offset_);
2798 pp::Rect shadow_rect(shadow_rc);
2799 shadow_rect.Offset(page_offset_);
2801 pp::Rect clip_rect(clip_rc);
2802 clip_rect.Offset(page_offset_);
2804 // Page drop shadow parameters.
2805 const double factor = 0.5;
2806 uint32 depth = std::max(
2807 std::max(page_rect.x() - shadow_rect.x(),
2808 page_rect.y() - shadow_rect.y()),
2809 std::max(shadow_rect.right() - page_rect.right(),
2810 shadow_rect.bottom() - page_rect.bottom()));
2811 depth = static_cast<uint32>(depth * 1.5) + 1;
2813 // We need to check depth only to verify our copy of shadow matrix is correct.
2814 if (!page_shadow_.get() || page_shadow_->depth() != depth)
2815 page_shadow_.reset(new ShadowMatrix(depth, factor, kBackgroundColor));
2817 DCHECK(!image_data->is_null());
2818 DrawShadow(image_data, shadow_rect, page_rect, clip_rect, *page_shadow_);
2821 void PDFiumEngine::GetRegion(const pp::Point& location,
2822 pp::ImageData* image_data,
2823 void** region,
2824 int* stride) const {
2825 if (image_data->is_null()) {
2826 DCHECK(plugin_size_.IsEmpty());
2827 *stride = 0;
2828 *region = NULL;
2829 return;
2831 char* buffer = static_cast<char*>(image_data->data());
2832 *stride = image_data->stride();
2834 pp::Point offset_location = location + page_offset_;
2835 // TODO: update this when we support BIDI and scrollbars can be on the left.
2836 if (!buffer ||
2837 !pp::Rect(page_offset_, plugin_size_).Contains(offset_location)) {
2838 *region = NULL;
2839 return;
2842 buffer += location.y() * (*stride);
2843 buffer += (location.x() + page_offset_.x()) * 4;
2844 *region = buffer;
2847 void PDFiumEngine::OnSelectionChanged() {
2848 if (HasPermission(PDFEngine::PERMISSION_COPY))
2849 pp::PDF::SetSelectedText(GetPluginInstance(), GetSelectedText().c_str());
2852 void PDFiumEngine::Form_Invalidate(FPDF_FORMFILLINFO* param,
2853 FPDF_PAGE page,
2854 double left,
2855 double top,
2856 double right,
2857 double bottom) {
2858 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
2859 int page_index = engine->GetVisiblePageIndex(page);
2860 if (page_index == -1) {
2861 // This can sometime happen when the page is closed because it went off
2862 // screen, and PDFium invalidates the control as it's being deleted.
2863 return;
2866 pp::Rect rect = engine->pages_[page_index]->PageToScreen(
2867 engine->GetVisibleRect().point(), engine->current_zoom_, left, top, right,
2868 bottom, engine->current_rotation_);
2869 engine->client_->Invalidate(rect);
2872 void PDFiumEngine::Form_OutputSelectedRect(FPDF_FORMFILLINFO* param,
2873 FPDF_PAGE page,
2874 double left,
2875 double top,
2876 double right,
2877 double bottom) {
2878 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
2879 int page_index = engine->GetVisiblePageIndex(page);
2880 if (page_index == -1) {
2881 NOTREACHED();
2882 return;
2884 pp::Rect rect = engine->pages_[page_index]->PageToScreen(
2885 engine->GetVisibleRect().point(), engine->current_zoom_, left, top, right,
2886 bottom, engine->current_rotation_);
2887 engine->form_highlights_.push_back(rect);
2890 void PDFiumEngine::Form_SetCursor(FPDF_FORMFILLINFO* param, int cursor_type) {
2891 // We don't need this since it's not enough to change the cursor in all
2892 // scenarios. Instead, we check which form field we're under in OnMouseMove.
2895 int PDFiumEngine::Form_SetTimer(FPDF_FORMFILLINFO* param,
2896 int elapse,
2897 TimerCallback timer_func) {
2898 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
2899 engine->timers_[++engine->next_timer_id_] =
2900 std::pair<int, TimerCallback>(elapse, timer_func);
2901 engine->client_->ScheduleCallback(engine->next_timer_id_, elapse);
2902 return engine->next_timer_id_;
2905 void PDFiumEngine::Form_KillTimer(FPDF_FORMFILLINFO* param, int timer_id) {
2906 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
2907 engine->timers_.erase(timer_id);
2910 FPDF_SYSTEMTIME PDFiumEngine::Form_GetLocalTime(FPDF_FORMFILLINFO* param) {
2911 base::Time time = base::Time::Now();
2912 base::Time::Exploded exploded;
2913 time.LocalExplode(&exploded);
2915 FPDF_SYSTEMTIME rv;
2916 rv.wYear = exploded.year;
2917 rv.wMonth = exploded.month;
2918 rv.wDayOfWeek = exploded.day_of_week;
2919 rv.wDay = exploded.day_of_month;
2920 rv.wHour = exploded.hour;
2921 rv.wMinute = exploded.minute;
2922 rv.wSecond = exploded.second;
2923 rv.wMilliseconds = exploded.millisecond;
2924 return rv;
2927 void PDFiumEngine::Form_OnChange(FPDF_FORMFILLINFO* param) {
2928 // Don't care about.
2931 FPDF_PAGE PDFiumEngine::Form_GetPage(FPDF_FORMFILLINFO* param,
2932 FPDF_DOCUMENT document,
2933 int page_index) {
2934 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
2935 if (page_index < 0 || page_index >= static_cast<int>(engine->pages_.size()))
2936 return NULL;
2937 return engine->pages_[page_index]->GetPage();
2940 FPDF_PAGE PDFiumEngine::Form_GetCurrentPage(FPDF_FORMFILLINFO* param,
2941 FPDF_DOCUMENT document) {
2942 // TODO(jam): find out what this is used for.
2943 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
2944 int index = engine->last_page_mouse_down_;
2945 if (index == -1) {
2946 index = engine->GetMostVisiblePage();
2947 if (index == -1) {
2948 NOTREACHED();
2949 return NULL;
2953 return engine->pages_[index]->GetPage();
2956 int PDFiumEngine::Form_GetRotation(FPDF_FORMFILLINFO* param, FPDF_PAGE page) {
2957 return 0;
2960 void PDFiumEngine::Form_ExecuteNamedAction(FPDF_FORMFILLINFO* param,
2961 FPDF_BYTESTRING named_action) {
2962 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
2963 std::string action(named_action);
2964 if (action == "Print") {
2965 engine->client_->Print();
2966 return;
2969 int index = engine->last_page_mouse_down_;
2970 /* Don't try to calculate the most visible page if we don't have a left click
2971 before this event (this code originally copied Form_GetCurrentPage which of
2972 course needs to do that and which doesn't have recursion). This can end up
2973 causing infinite recursion. See http://crbug.com/240413 for more
2974 information. Either way, it's not necessary for the spec'd list of named
2975 actions.
2976 if (index == -1)
2977 index = engine->GetMostVisiblePage();
2979 if (index == -1)
2980 return;
2982 // This is the only list of named actions per the spec (see 12.6.4.11). Adobe
2983 // Reader supports more, like FitWidth, but since they're not part of the spec
2984 // and we haven't got bugs about them, no need to now.
2985 if (action == "NextPage") {
2986 engine->client_->ScrollToPage(index + 1);
2987 } else if (action == "PrevPage") {
2988 engine->client_->ScrollToPage(index - 1);
2989 } else if (action == "FirstPage") {
2990 engine->client_->ScrollToPage(0);
2991 } else if (action == "LastPage") {
2992 engine->client_->ScrollToPage(engine->pages_.size() - 1);
2996 void PDFiumEngine::Form_SetTextFieldFocus(FPDF_FORMFILLINFO* param,
2997 FPDF_WIDESTRING value,
2998 FPDF_DWORD valueLen,
2999 FPDF_BOOL is_focus) {
3000 // Do nothing for now.
3001 // TODO(gene): use this signal to trigger OSK.
3004 void PDFiumEngine::Form_DoURIAction(FPDF_FORMFILLINFO* param,
3005 FPDF_BYTESTRING uri) {
3006 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3007 engine->client_->NavigateTo(std::string(uri), false);
3010 void PDFiumEngine::Form_DoGoToAction(FPDF_FORMFILLINFO* param,
3011 int page_index,
3012 int zoom_mode,
3013 float* position_array,
3014 int size_of_array) {
3015 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3016 engine->client_->ScrollToPage(page_index);
3019 int PDFiumEngine::Form_Alert(IPDF_JSPLATFORM* param,
3020 FPDF_WIDESTRING message,
3021 FPDF_WIDESTRING title,
3022 int type,
3023 int icon) {
3024 // See fpdfformfill.h for these values.
3025 enum AlertType {
3026 ALERT_TYPE_OK = 0,
3027 ALERT_TYPE_OK_CANCEL,
3028 ALERT_TYPE_YES_ON,
3029 ALERT_TYPE_YES_NO_CANCEL
3032 enum AlertResult {
3033 ALERT_RESULT_OK = 1,
3034 ALERT_RESULT_CANCEL,
3035 ALERT_RESULT_NO,
3036 ALERT_RESULT_YES
3039 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3040 std::string message_str =
3041 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(message));
3042 if (type == ALERT_TYPE_OK) {
3043 engine->client_->Alert(message_str);
3044 return ALERT_RESULT_OK;
3047 bool rv = engine->client_->Confirm(message_str);
3048 if (type == ALERT_TYPE_OK_CANCEL)
3049 return rv ? ALERT_RESULT_OK : ALERT_RESULT_CANCEL;
3050 return rv ? ALERT_RESULT_YES : ALERT_RESULT_NO;
3053 void PDFiumEngine::Form_Beep(IPDF_JSPLATFORM* param, int type) {
3054 // Beeps are annoying, and not possible using javascript, so ignore for now.
3057 int PDFiumEngine::Form_Response(IPDF_JSPLATFORM* param,
3058 FPDF_WIDESTRING question,
3059 FPDF_WIDESTRING title,
3060 FPDF_WIDESTRING default_response,
3061 FPDF_WIDESTRING label,
3062 FPDF_BOOL password,
3063 void* response,
3064 int length) {
3065 std::string question_str = base::UTF16ToUTF8(
3066 reinterpret_cast<const base::char16*>(question));
3067 std::string default_str = base::UTF16ToUTF8(
3068 reinterpret_cast<const base::char16*>(default_response));
3070 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3071 std::string rv = engine->client_->Prompt(question_str, default_str);
3072 base::string16 rv_16 = base::UTF8ToUTF16(rv);
3073 int rv_bytes = rv_16.size() * sizeof(base::char16);
3074 if (response) {
3075 int bytes_to_copy = rv_bytes < length ? rv_bytes : length;
3076 memcpy(response, rv_16.c_str(), bytes_to_copy);
3078 return rv_bytes;
3081 int PDFiumEngine::Form_GetFilePath(IPDF_JSPLATFORM* param,
3082 void* file_path,
3083 int length) {
3084 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3085 std::string rv = engine->client_->GetURL();
3086 if (file_path && rv.size() <= static_cast<size_t>(length))
3087 memcpy(file_path, rv.c_str(), rv.size());
3088 return rv.size();
3091 void PDFiumEngine::Form_Mail(IPDF_JSPLATFORM* param,
3092 void* mail_data,
3093 int length,
3094 FPDF_BOOL ui,
3095 FPDF_WIDESTRING to,
3096 FPDF_WIDESTRING subject,
3097 FPDF_WIDESTRING cc,
3098 FPDF_WIDESTRING bcc,
3099 FPDF_WIDESTRING message) {
3100 DCHECK(length == 0); // Don't handle attachments; no way with mailto.
3101 std::string to_str =
3102 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(to));
3103 std::string cc_str =
3104 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(cc));
3105 std::string bcc_str =
3106 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(bcc));
3107 std::string subject_str =
3108 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(subject));
3109 std::string message_str =
3110 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(message));
3112 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3113 engine->client_->Email(to_str, cc_str, bcc_str, subject_str, message_str);
3116 void PDFiumEngine::Form_Print(IPDF_JSPLATFORM* param,
3117 FPDF_BOOL ui,
3118 int start,
3119 int end,
3120 FPDF_BOOL silent,
3121 FPDF_BOOL shrink_to_fit,
3122 FPDF_BOOL print_as_image,
3123 FPDF_BOOL reverse,
3124 FPDF_BOOL annotations) {
3125 // No way to pass the extra information to the print dialog using JavaScript.
3126 // Just opening it is fine for now.
3127 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3128 engine->client_->Print();
3131 void PDFiumEngine::Form_SubmitForm(IPDF_JSPLATFORM* param,
3132 void* form_data,
3133 int length,
3134 FPDF_WIDESTRING url) {
3135 std::string url_str =
3136 base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(url));
3137 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3138 engine->client_->SubmitForm(url_str, form_data, length);
3141 void PDFiumEngine::Form_GotoPage(IPDF_JSPLATFORM* param,
3142 int page_number) {
3143 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3144 engine->client_->ScrollToPage(page_number);
3147 int PDFiumEngine::Form_Browse(IPDF_JSPLATFORM* param,
3148 void* file_path,
3149 int length) {
3150 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3151 std::string path = engine->client_->ShowFileSelectionDialog();
3152 if (path.size() + 1 <= static_cast<size_t>(length))
3153 memcpy(file_path, &path[0], path.size() + 1);
3154 return path.size() + 1;
3157 FPDF_BOOL PDFiumEngine::Pause_NeedToPauseNow(IFSDK_PAUSE* param) {
3158 PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3159 return (base::Time::Now() - engine->last_progressive_start_time_).
3160 InMilliseconds() > engine->progressive_paint_timeout_;
3163 ScopedUnsupportedFeature::ScopedUnsupportedFeature(PDFiumEngine* engine)
3164 : engine_(engine), old_engine_(g_engine_for_unsupported) {
3165 g_engine_for_unsupported = engine_;
3168 ScopedUnsupportedFeature::~ScopedUnsupportedFeature() {
3169 g_engine_for_unsupported = old_engine_;
3172 PDFEngineExports* PDFEngineExports::Create() {
3173 return new PDFiumEngineExports;
3176 namespace {
3178 int CalculatePosition(FPDF_PAGE page,
3179 const PDFiumEngineExports::RenderingSettings& settings,
3180 pp::Rect* dest) {
3181 int page_width = static_cast<int>(
3182 FPDF_GetPageWidth(page) * settings.dpi_x / kPointsPerInch);
3183 int page_height = static_cast<int>(
3184 FPDF_GetPageHeight(page) * settings.dpi_y / kPointsPerInch);
3186 // Start by assuming that we will draw exactly to the bounds rect
3187 // specified.
3188 *dest = settings.bounds;
3190 int rotate = 0; // normal orientation.
3192 // Auto-rotate landscape pages to print correctly.
3193 if (settings.autorotate &&
3194 (dest->width() > dest->height()) != (page_width > page_height)) {
3195 rotate = 3; // 90 degrees counter-clockwise.
3196 std::swap(page_width, page_height);
3199 // See if we need to scale the output
3200 bool scale_to_bounds = false;
3201 if (settings.fit_to_bounds &&
3202 ((page_width > dest->width()) || (page_height > dest->height()))) {
3203 scale_to_bounds = true;
3204 } else if (settings.stretch_to_bounds &&
3205 ((page_width < dest->width()) || (page_height < dest->height()))) {
3206 scale_to_bounds = true;
3209 if (scale_to_bounds) {
3210 // If we need to maintain aspect ratio, calculate the actual width and
3211 // height.
3212 if (settings.keep_aspect_ratio) {
3213 double scale_factor_x = page_width;
3214 scale_factor_x /= dest->width();
3215 double scale_factor_y = page_height;
3216 scale_factor_y /= dest->height();
3217 if (scale_factor_x > scale_factor_y) {
3218 dest->set_height(page_height / scale_factor_x);
3219 } else {
3220 dest->set_width(page_width / scale_factor_y);
3223 } else {
3224 // We are not scaling to bounds. Draw in the actual page size. If the
3225 // actual page size is larger than the bounds, the output will be
3226 // clipped.
3227 dest->set_width(page_width);
3228 dest->set_height(page_height);
3231 if (settings.center_in_bounds) {
3232 pp::Point offset((settings.bounds.width() - dest->width()) / 2,
3233 (settings.bounds.height() - dest->height()) / 2);
3234 dest->Offset(offset);
3236 return rotate;
3239 } // namespace
3241 #if defined(OS_WIN)
3242 bool PDFiumEngineExports::RenderPDFPageToDC(const void* pdf_buffer,
3243 int buffer_size,
3244 int page_number,
3245 const RenderingSettings& settings,
3246 HDC dc) {
3247 FPDF_DOCUMENT doc = FPDF_LoadMemDocument(pdf_buffer, buffer_size, NULL);
3248 if (!doc)
3249 return false;
3250 FPDF_PAGE page = FPDF_LoadPage(doc, page_number);
3251 if (!page) {
3252 FPDF_CloseDocument(doc);
3253 return false;
3255 RenderingSettings new_settings = settings;
3256 // calculate the page size
3257 if (new_settings.dpi_x == -1)
3258 new_settings.dpi_x = GetDeviceCaps(dc, LOGPIXELSX);
3259 if (new_settings.dpi_y == -1)
3260 new_settings.dpi_y = GetDeviceCaps(dc, LOGPIXELSY);
3262 pp::Rect dest;
3263 int rotate = CalculatePosition(page, new_settings, &dest);
3265 int save_state = SaveDC(dc);
3266 // The caller wanted all drawing to happen within the bounds specified.
3267 // Based on scale calculations, our destination rect might be larger
3268 // than the bounds. Set the clip rect to the bounds.
3269 IntersectClipRect(dc, settings.bounds.x(), settings.bounds.y(),
3270 settings.bounds.x() + settings.bounds.width(),
3271 settings.bounds.y() + settings.bounds.height());
3273 // A temporary hack. PDFs generated by Cairo (used by Chrome OS to generate
3274 // a PDF output from a webpage) result in very large metafiles and the
3275 // rendering using FPDF_RenderPage is incorrect. In this case, render as a
3276 // bitmap. Note that this code does not kick in for PDFs printed from Chrome
3277 // because in that case we create a temp PDF first before printing and this
3278 // temp PDF does not have a creator string that starts with "cairo".
3279 base::string16 creator;
3280 size_t buffer_bytes = FPDF_GetMetaText(doc, "Creator", NULL, 0);
3281 if (buffer_bytes > 1) {
3282 FPDF_GetMetaText(doc, "Creator", WriteInto(&creator, buffer_bytes),
3283 buffer_bytes);
3285 bool use_bitmap = false;
3286 if (StartsWith(creator, L"cairo", false))
3287 use_bitmap = true;
3289 // Another temporary hack. Some PDFs seems to render very slowly if
3290 // FPDF_RenderPage is directly used on a printer DC. I suspect it is
3291 // because of the code to talk Postscript directly to the printer if
3292 // the printer supports this. Need to discuss this with PDFium. For now,
3293 // render to a bitmap and then blit the bitmap to the DC if we have been
3294 // supplied a printer DC.
3295 int device_type = GetDeviceCaps(dc, TECHNOLOGY);
3296 if (use_bitmap ||
3297 (device_type == DT_RASPRINTER) || (device_type == DT_PLOTTER)) {
3298 FPDF_BITMAP bitmap = FPDFBitmap_Create(dest.width(), dest.height(),
3299 FPDFBitmap_BGRx);
3300 // Clear the bitmap
3301 FPDFBitmap_FillRect(bitmap, 0, 0, dest.width(), dest.height(), 0xFFFFFFFF);
3302 FPDF_RenderPageBitmap(
3303 bitmap, page, 0, 0, dest.width(), dest.height(), rotate,
3304 FPDF_ANNOT | FPDF_PRINTING | FPDF_NO_CATCH);
3305 int stride = FPDFBitmap_GetStride(bitmap);
3306 BITMAPINFO bmi;
3307 memset(&bmi, 0, sizeof(bmi));
3308 bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
3309 bmi.bmiHeader.biWidth = dest.width();
3310 bmi.bmiHeader.biHeight = -dest.height(); // top-down image
3311 bmi.bmiHeader.biPlanes = 1;
3312 bmi.bmiHeader.biBitCount = 32;
3313 bmi.bmiHeader.biCompression = BI_RGB;
3314 bmi.bmiHeader.biSizeImage = stride * dest.height();
3315 StretchDIBits(dc, dest.x(), dest.y(), dest.width(), dest.height(),
3316 0, 0, dest.width(), dest.height(),
3317 FPDFBitmap_GetBuffer(bitmap), &bmi, DIB_RGB_COLORS, SRCCOPY);
3318 FPDFBitmap_Destroy(bitmap);
3319 } else {
3320 FPDF_RenderPage(dc, page, dest.x(), dest.y(), dest.width(), dest.height(),
3321 rotate, FPDF_ANNOT | FPDF_PRINTING | FPDF_NO_CATCH);
3323 RestoreDC(dc, save_state);
3324 FPDF_ClosePage(page);
3325 FPDF_CloseDocument(doc);
3326 return true;
3328 #endif // OS_WIN
3330 bool PDFiumEngineExports::RenderPDFPageToBitmap(
3331 const void* pdf_buffer,
3332 int pdf_buffer_size,
3333 int page_number,
3334 const RenderingSettings& settings,
3335 void* bitmap_buffer) {
3336 FPDF_DOCUMENT doc = FPDF_LoadMemDocument(pdf_buffer, pdf_buffer_size, NULL);
3337 if (!doc)
3338 return false;
3339 FPDF_PAGE page = FPDF_LoadPage(doc, page_number);
3340 if (!page) {
3341 FPDF_CloseDocument(doc);
3342 return false;
3345 pp::Rect dest;
3346 int rotate = CalculatePosition(page, settings, &dest);
3348 FPDF_BITMAP bitmap =
3349 FPDFBitmap_CreateEx(settings.bounds.width(), settings.bounds.height(),
3350 FPDFBitmap_BGRA, bitmap_buffer,
3351 settings.bounds.width() * 4);
3352 // Clear the bitmap
3353 FPDFBitmap_FillRect(bitmap, 0, 0, settings.bounds.width(),
3354 settings.bounds.height(), 0xFFFFFFFF);
3355 // Shift top-left corner of bounds to (0, 0) if it's not there.
3356 dest.set_point(dest.point() - settings.bounds.point());
3357 FPDF_RenderPageBitmap(
3358 bitmap, page, dest.x(), dest.y(), dest.width(), dest.height(), rotate,
3359 FPDF_ANNOT | FPDF_PRINTING | FPDF_NO_CATCH);
3360 FPDFBitmap_Destroy(bitmap);
3361 FPDF_ClosePage(page);
3362 FPDF_CloseDocument(doc);
3363 return true;
3366 bool PDFiumEngineExports::GetPDFDocInfo(const void* pdf_buffer,
3367 int buffer_size,
3368 int* page_count,
3369 double* max_page_width) {
3370 FPDF_DOCUMENT doc = FPDF_LoadMemDocument(pdf_buffer, buffer_size, NULL);
3371 if (!doc)
3372 return false;
3373 int page_count_local = FPDF_GetPageCount(doc);
3374 if (page_count) {
3375 *page_count = page_count_local;
3377 if (max_page_width) {
3378 *max_page_width = 0;
3379 for (int page_number = 0; page_number < page_count_local; page_number++) {
3380 double page_width = 0;
3381 double page_height = 0;
3382 FPDF_GetPageSizeByIndex(doc, page_number, &page_width, &page_height);
3383 if (page_width > *max_page_width) {
3384 *max_page_width = page_width;
3388 FPDF_CloseDocument(doc);
3389 return true;
3392 bool PDFiumEngineExports::GetPDFPageSizeByIndex(
3393 const void* pdf_buffer,
3394 int pdf_buffer_size,
3395 int page_number,
3396 double* width,
3397 double* height) {
3398 FPDF_DOCUMENT doc = FPDF_LoadMemDocument(pdf_buffer, pdf_buffer_size, NULL);
3399 if (!doc)
3400 return false;
3401 bool success = FPDF_GetPageSizeByIndex(doc, page_number, width, height) != 0;
3402 FPDF_CloseDocument(doc);
3403 return success;
3406 } // namespace chrome_pdf