Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / pdf / pdfium / pdfium_engine.cc
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.
4
5 #include "pdf/pdfium/pdfium_engine.h"
6
7 #include <math.h>
8
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"
45
46 namespace chrome_pdf {
47
48 #define kPageShadowTop    3
49 #define kPageShadowBottom 7
50 #define kPageShadowLeft   5
51 #define kPageShadowRight  5
52
53 #define kPageSeparatorThickness 4
54 #define kHighlightColorR 153
55 #define kHighlightColorG 193
56 #define kHighlightColorB 218
57
58 const uint32 kPendingPageColor = 0xFFEEEEEE;
59
60 #define kFormHighlightColor 0xFFE4DD
61 #define kFormHighlightAlpha 100
62
63 #define kMaxPasswordTries 3
64
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
71
72 #define kLoadingTextVerticalOffset 50
73
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
77
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
88
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;
93
94 struct ClipBox {
95   float left;
96   float right;
97   float top;
98   float bottom;
99 };
100
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;
109   }
110 }
111
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);
120     }
121   }
122   return page_numbers;
123 }
124
125 #if defined(OS_LINUX)
126
127 PP_Instance g_last_instance_id;
128
129 struct PDFFontSubstitution {
130   const char* pdf_name;
131   const char* face;
132   bool bold;
133   bool italic;
134 };
135
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);
147 }
148
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);
154
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;
161   }
162 }
163
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},
177
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},
200 };
201
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;
209
210   pp::BrowserFontDescription description;
211
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;
216
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);
221   }
222
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;
233     }
234   }
235
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);
240
241     description.set_weight(WeightToBrowserFontTrustedWeight(weight));
242     description.set_italic(italic > 0);
243   }
244
245   if (!pp::PDF::IsAvailable()) {
246     NOTREACHED();
247     return NULL;
248   }
249
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);
256 }
257
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;
264   }
265
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;
271 }
272
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);
276 }
277
278 FPDF_SYSFONTINFO g_font_info = {
279   1,
280   0,
281   EnumFonts,
282   MapFont,
283   0,
284   GetFontData,
285   0,
286   0,
287   DeleteFont
288 };
289 #endif  // defined(OS_LINUX)
290
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();
297 }
298
299 OOM_INFO g_oom_info = {
300   1,
301   OOM_Handler
302 };
303
304 PDFiumEngine* g_engine_for_unsupported;
305
306 void Unsupported_Handler(UNSUPPORT_INFO*, int type) {
307   if (!g_engine_for_unsupported) {
308     NOTREACHED();
309     return;
310   }
311
312   g_engine_for_unsupported->UnsupportedFeature(type);
313 }
314
315 UNSUPPORT_INFO g_unsuppored_info = {
316   1,
317   Unsupported_Handler
318 };
319
320 // Set the destination page size and content area in points based on source
321 // page rotation and orientation.
322 //
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());
340   }
341 }
342
343 // Calculate the scale factor between |content_rect| and a page of size
344 // |src_width| x |src_height|.
345 //
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;
357
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);
365 }
366
367 // Compute source clip box boundaries based on the crop box / media box of
368 // source page and scale factor.
369 //
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;
390     }
391   }
392   clip_box->left *= scale_factor;
393   clip_box->right *= scale_factor;
394   clip_box->bottom *= scale_factor;
395   clip_box->top *= scale_factor;
396 }
397
398 // Calculate the clip box translation offset for a page that does need to be
399 // scaled. All parameters are in points.
400 //
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;
412
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;
418 }
419
420 // Calculate the clip box offset for a page that does not need to be scaled.
421 // All parameters are in points.
422 //
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;
458   }
459 }
460
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|.
464 //
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.
472
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);
477
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);
482
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);
489   }
490   FPDFPage_TransformAnnots(page, scale_factor, 0, 0, scale_factor,
491                            offset_x, offset_y);
492   FPDFPage_GenerateContent(page);
493
494   // Add a extra clip path to the new pdf page here.
495   FPDFPage_InsertClipPath(page, clip_path);
496
497   // Destroy the clip path.
498   FPDF_DestroyClipPath(clip_path);
499 }
500
501 bool InitializeSDK(void* data) {
502   FPDF_InitLibrary(data);
503
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
508
509   FSDK_SetOOMHandler(&g_oom_info);
510   FSDK_SetUnSpObjProcessHandler(&g_unsuppored_info);
511
512   return true;
513 }
514
515 void ShutdownSDK() {
516   FPDF_DestroyLibrary();
517 }
518
519 PDFEngine* PDFEngine::Create(PDFEngine::Client* client) {
520   return new PDFiumEngine(client);
521 }
522
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);
549
550   file_access_.m_FileLen = 0;
551   file_access_.m_GetBlock = &GetBlock;
552   file_access_.m_Param = &doc_loader_;
553
554   file_availability_.version = 1;
555   file_availability_.IsDataAvail = &IsDataAvail;
556   file_availability_.loader = &doc_loader_;
557
558   download_hints_.version = 1;
559   download_hints_.AddSegment = &AddSegment;
560   download_hints_.loader = &doc_loader_;
561
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;
583
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;
594
595   IFSDK_PAUSE::version = 1;
596   IFSDK_PAUSE::user = NULL;
597   IFSDK_PAUSE::NeedToPauseNow = Pause_NeedToPauseNow;
598 }
599
600 PDFiumEngine::~PDFiumEngine() {
601   STLDeleteElements(&pages_);
602   if (doc_) {
603     if (form_) {
604       FORM_DoDocumentAAction(form_, FPDFDOC_AACTION_WC);
605       FPDFDOC_ExitFormFillEnviroument(form_);
606     }
607     FPDF_CloseDocument(doc_);
608   }
609
610   if (fpdf_availability_)
611     FPDFAvail_Destroy(fpdf_availability_);
612 }
613
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);
618 }
619
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);
625 }
626
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);
632 }
633
634 bool PDFiumEngine::New(const char* url) {
635   url_ = url;
636   headers_ = std::string();
637   return true;
638 }
639
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;
648 }
649
650 void PDFiumEngine::PageOffsetUpdated(const pp::Point& page_offset) {
651   page_offset_ = page_offset;
652 }
653
654 void PDFiumEngine::PluginSizeUpdated(const pp::Size& size) {
655   CancelPaints();
656
657   plugin_size_ = size;
658   CalculateVisiblePages();
659 }
660
661 void PDFiumEngine::ScrolledToXPosition(int position) {
662   CancelPaints();
663
664   int old_x = position_.x();
665   position_.set_x(position);
666   CalculateVisiblePages();
667   client_->Scroll(pp::Point(old_x - position, 0));
668 }
669
670 void PDFiumEngine::ScrolledToYPosition(int position) {
671   CancelPaints();
672
673   int old_y = position_.y();
674   position_.set_y(position);
675   CalculateVisiblePages();
676   client_->Scroll(pp::Point(0, old_y - position));
677 }
678
679 void PDFiumEngine::PrePaint() {
680   for (size_t i = 0; i < progressive_paints_.size(); ++i)
681     progressive_paints_[i].painted_ = false;
682 }
683
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;
701
702     leftover = leftover.Subtract(dirty_in_screen);
703
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;
715       }
716
717       if (progressive == -1) {
718         progressive = StartPaint(index, dirty_in_screen);
719         progressive_paint_timeout_ = kMaxInitialProgressivePaintTimeMs;
720       } else {
721         progressive_paint_timeout_ = kMaxProgressivePaintTimeMs;
722       }
723
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);
730       }
731     } else {
732       PaintUnavailablePage(index, dirty_in_screen, image_data);
733       ready->push_back(dirty_in_screen);
734     }
735   }
736 }
737
738 void PDFiumEngine::PostPaint() {
739   for (size_t i = 0; i < progressive_paints_.size(); ++i) {
740     if (progressive_paints_[i].painted_)
741       continue;
742
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;
751   }
752 }
753
754 bool PDFiumEngine::HandleDocumentLoad(const pp::URLLoader& loader) {
755   password_tries_remaining_ = kMaxPasswordTries;
756   return doc_loader_.Init(loader, url_, headers_);
757 }
758
759 pp::Instance* PDFiumEngine::GetPluginInstance() {
760   return client_->GetPluginInstance();
761 }
762
763 pp::URLLoader PDFiumEngine::CreateURLLoader() {
764   return client_->CreateURLLoader();
765 }
766
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));
781 }
782
783 pp::Point PDFiumEngine::GetScrollPosition() {
784   return position_;
785 }
786
787 void PDFiumEngine::SetScrollPosition(const pp::Point& position) {
788   position_ = position;
789 }
790
791 bool PDFiumEngine::IsProgressiveLoad() {
792   return doc_loader_.is_partial_document();
793 }
794
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_);
799
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;
806   }
807
808   LoadDocument();
809 }
810
811 void PDFiumEngine::OnPendingRequestComplete() {
812   if (!doc_ || !form_) {
813     LoadDocument();
814     return;
815   }
816
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]));
826     }
827   }
828   pending_pages_.swap(still_pending);
829   if (update_pages)
830     LoadPageInfo(true);
831 }
832
833 void PDFiumEngine::OnNewDataAvailable() {
834   client_->DocumentLoadProgress(doc_loader_.GetAvailableData(),
835                                 doc_loader_.document_size());
836 }
837
838 void PDFiumEngine::OnDocumentComplete() {
839   if (!doc_ || !form_) {
840     file_access_.m_FileLen = doc_loader_.document_size();
841     LoadDocument();
842     return;
843   }
844
845   bool need_update = false;
846   for (size_t i = 0; i < pages_.size(); ++i) {
847     if (pages_[i]->available())
848       continue;
849
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));
857   }
858   if (need_update)
859     LoadPageInfo(true);
860
861   FinishLoadingDocument();
862 }
863
864 void PDFiumEngine::FinishLoadingDocument() {
865   DCHECK(doc_loader_.IsDocumentComplete() && doc_);
866   if (called_do_document_action_)
867     return;
868   called_do_document_action_ = true;
869
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);
876   }
877
878   if (doc_) // This can only happen if loading |doc_| fails.
879     client_->DocumentLoadComplete(pages_.size());
880 }
881
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;
922   }
923   client_->DocumentHasUnsupportedFeature(feature);
924 }
925
926 void PDFiumEngine::ContinueFind(int32_t result) {
927   StartFind(current_find_text_.c_str(), !!result);
928 }
929
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;
955   }
956
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;
963 }
964
965 uint32_t PDFiumEngine::QuerySupportedPrintOutputFormats() {
966   if (!HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY))
967     return 0;
968   return PP_PRINTOUTPUTFORMAT_PDF;
969 }
970
971 void PDFiumEngine::PrintBegin() {
972   FORM_DoDocumentAAction(form_, FPDFDOC_AACTION_WP);
973 }
974
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();
983 }
984
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();
990
991   // If document is not downloaded yet, disable printing.
992   if (doc_ && !doc_loader_.IsDocumentComplete())
993     return pp::Buffer_Dev();
994
995   FPDF_DOCUMENT output_doc = FPDF_CreateNewDocument();
996   if (!output_doc)
997     return pp::Buffer_Dev();
998
999   SaveSelectedFormForPrint();
1000
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));
1014
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);
1021
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);
1025   }
1026
1027 #if defined(OS_LINUX)
1028   g_last_instance_id = client_->GetPluginInstance()->pp_instance();
1029 #endif
1030
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());
1036
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;
1041
1042     FPDF_PAGE output_page = FPDFPage_New(temp_doc, 0, source_page_width,
1043                                          source_page_height);
1044
1045     pp::ImageData image = pp::ImageData(client_->GetPluginInstance(),
1046                                         PP_IMAGEDATAFORMAT_BGRA_PREMUL,
1047                                         bitmap_size,
1048                                         false);
1049
1050     FPDF_BITMAP bitmap = FPDFBitmap_CreateEx(bitmap_size.width(),
1051                                              bitmap_size.height(),
1052                                              FPDFBitmap_BGRx,
1053                                              image.data(),
1054                                              image.stride());
1055
1056     // Clear the bitmap
1057     FPDFBitmap_FillRect(bitmap, 0, 0, bitmap_size.width(),
1058                         bitmap_size.height(), 0xFFFFFFFF);
1059
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);
1066
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;
1071
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);
1080
1081     pages_to_print[i].ClosePrintPage();
1082     FPDFBitmap_Destroy(bitmap);
1083
1084     pp::Buffer_Dev buffer = GetFlattenedPrintData(temp_doc);
1085     FPDF_CloseDocument(temp_doc);
1086
1087     PDFiumMemBufferFileRead file_read(buffer.data(), buffer.size());
1088     temp_doc = FPDF_LoadCustomDocument(&file_read, NULL);
1089     if (!temp_doc)
1090       break;
1091
1092     FPDF_BOOL imported = FPDF_ImportPages(output_doc, temp_doc, "1", i);
1093     FPDF_CloseDocument(temp_doc);
1094     if (!imported)
1095       break;
1096   }
1097
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);
1104   }
1105   FPDF_CloseDocument(output_doc);
1106   return buffer;
1107 }
1108
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;
1121       }
1122     } else {
1123       flatten_succeeded = false;
1124       break;
1125     }
1126   }
1127   if (!flatten_succeeded) {
1128     FPDF_CloseDocument(doc);
1129     return pp::Buffer_Dev();
1130   }
1131
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());
1140     }
1141   }
1142   return buffer;
1143 }
1144
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();
1150
1151   DCHECK(doc_);
1152   FPDF_DOCUMENT output_doc = FPDF_CreateNewDocument();
1153   if (!output_doc)
1154     return pp::Buffer_Dev();
1155
1156   SaveSelectedFormForPrint();
1157
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));
1169     }
1170   }
1171
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();
1179   }
1180
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();
1185   }
1186
1187   FitContentsToPrintableAreaIfRequired(output_doc, print_settings);
1188
1189   // Now flatten all the output pages.
1190   pp::Buffer_Dev buffer = GetFlattenedPrintData(output_doc);
1191   FPDF_CloseDocument(output_doc);
1192   return buffer;
1193 }
1194
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);
1208     }
1209   }
1210 }
1211
1212 void PDFiumEngine::SaveSelectedFormForPrint() {
1213   FORM_ForceToKillFocus(form_);
1214   client_->FormTextFieldFocusChange(false);
1215 }
1216
1217 void PDFiumEngine::PrintEnd() {
1218   FORM_DoDocumentAAction(form_, FPDFDOC_AACTION_DP);
1219 }
1220
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);
1230 }
1231
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;
1242     }
1243   }
1244   if (page == -1)
1245     return PDFiumPage::NONSELECTABLE_AREA;
1246
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;
1252   }
1253
1254   *page_index = page;
1255   return pages_[page]->GetCharIndex(point, current_rotation_, char_index,
1256                                     target);
1257 }
1258
1259 bool PDFiumEngine::OnMouseDown(const pp::MouseInputEvent& event) {
1260   if (event.GetButton() != PP_INPUTEVENT_MOUSEBUTTON_LEFT)
1261     return false;
1262
1263   SelectionChangeInvalidator selection_invalidator(this);
1264   selection_.clear();
1265
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;
1276   }
1277
1278   if (area == PDFiumPage::DOCLINK_AREA) {
1279     client_->ScrollToPage(target.page);
1280     client_->FormTextFieldFocusChange(false);
1281     return true;
1282   }
1283
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);
1289
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.
1297     }
1298   }
1299
1300   client_->FormTextFieldFocusChange(false);
1301
1302   if (area != PDFiumPage::TEXT_AREA)
1303     return true;  // Return true so WebKit doesn't do its own highlighting.
1304
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);
1310   }
1311
1312   return true;
1313 }
1314
1315 void PDFiumEngine::OnSingleClick(int page_index, int char_index) {
1316   selecting_ = true;
1317   selection_.push_back(PDFiumRange(pages_[page_index], char_index, 0));
1318 }
1319
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++;
1335
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;
1342   }
1343
1344   selection_.push_back(PDFiumRange(
1345       pages_[page_index], start_index, end_index - start_index));
1346 }
1347
1348 bool PDFiumEngine::OnMouseUp(const pp::MouseInputEvent& event) {
1349   if (event.GetButton() != PP_INPUTEVENT_MOUSEBUTTON_LEFT)
1350     return false;
1351
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);
1361   }
1362
1363   if (!selecting_)
1364     return false;
1365
1366   selecting_ = false;
1367   return true;
1368 }
1369
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;
1388     }
1389
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);
1394
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;
1411       }
1412     }
1413
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());
1420     }
1421     // No need to swallow the event, since this might interfere with the
1422     // scrollbars if the user is dragging them.
1423     return false;
1424   }
1425
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;
1431   }
1432
1433   SelectionChangeInvalidator selection_invalidator(this);
1434
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;
1442     }
1443   }
1444
1445   if (selection_.size() == 0)
1446     return false;
1447
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;
1457     }
1458     selection_[last].SetCharCount(count);
1459   } else if (selection_[last].page_index() < page_index) {
1460     // Selecting into the next page.
1461
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()));
1467     }
1468
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());
1475
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()));
1481     }
1482
1483     int count = pages_[page_index]->GetCharCount();
1484     selection_.push_back(
1485         PDFiumRange(pages_[page_index], count, count - char_index));
1486   }
1487
1488   return true;
1489 }
1490
1491 bool PDFiumEngine::OnKeyDown(const pp::KeyboardInputEvent& event) {
1492   if (last_page_mouse_down_ == -1)
1493     return false;
1494
1495   bool rv = !!FORM_OnKeyDown(
1496       form_, pages_[last_page_mouse_down_]->GetPage(),
1497       event.GetKeyCode(), event.GetModifiers());
1498
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);
1515   }
1516
1517   return rv;
1518 }
1519
1520 bool PDFiumEngine::OnKeyUp(const pp::KeyboardInputEvent& event) {
1521   if (last_page_mouse_down_ == -1)
1522     return false;
1523
1524   return !!FORM_OnKeyUp(
1525       form_, pages_[last_page_mouse_down_]->GetPage(),
1526       event.GetKeyCode(), event.GetModifiers());
1527 }
1528
1529 bool PDFiumEngine::OnChar(const pp::KeyboardInputEvent& event) {
1530   if (last_page_mouse_down_ == -1)
1531     return false;
1532
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());
1538 }
1539
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;
1545
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;
1553
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_;
1565     }
1566   }
1567
1568   int current_page = next_page_to_search_;
1569
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);
1582     }
1583
1584     if (!IsPageVisible(current_page))
1585       pages_[current_page]->Unload();
1586   }
1587
1588   if (next_page_to_search_ != last_page_to_search_ ||
1589       (first_search && last_character_index_to_search_ != -1)) {
1590     ++next_page_to_search_;
1591   }
1592
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_));
1605
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);
1614   }
1615 }
1616
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);
1628
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));
1636
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;
1642     }
1643
1644     AddFindResult(result);
1645   }
1646
1647   FPDFText_FindClose(find);
1648 }
1649
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_;
1663   }
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));
1685   }
1686 }
1687
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;
1699     }
1700   }
1701   find_results_.insert(find_results_.begin() + i, result);
1702   UpdateTickMarks();
1703
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_);
1711   }
1712   client_->NotifyNumberOfFindResultsChanged(find_results_.size(), false);
1713 }
1714
1715 bool PDFiumEngine::SelectFindResult(bool forward) {
1716   if (find_results_.empty()) {
1717     NOTREACHED();
1718     return false;
1719   }
1720
1721   SelectionChangeInvalidator selection_invalidator(this);
1722
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;
1730     }
1731   }
1732
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_]);
1737
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);
1755
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);
1763     }
1764   }
1765
1766   client_->NotifySelectedFindResultChanged(current_find_index_);
1767
1768   return true;
1769 }
1770
1771 void PDFiumEngine::StopFind() {
1772   SelectionChangeInvalidator selection_invalidator(this);
1773
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();
1784 }
1785
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);
1796   }
1797
1798   client_->UpdateTickMarks(tickmarks);
1799 }
1800
1801 void PDFiumEngine::ZoomUpdated(double new_zoom_level) {
1802   CancelPaints();
1803
1804   current_zoom_ = new_zoom_level;
1805
1806   CalculateVisiblePages();
1807   UpdateTickMarks();
1808 }
1809
1810 void PDFiumEngine::RotateClockwise() {
1811   current_rotation_ = (current_rotation_ + 1) % 4;
1812   InvalidateAllPages();
1813 }
1814
1815 void PDFiumEngine::RotateCounterclockwise() {
1816   current_rotation_ = (current_rotation_ - 1) % 4;
1817   InvalidateAllPages();
1818 }
1819
1820 void PDFiumEngine::InvalidateAllPages() {
1821   selection_.clear();
1822   find_results_.clear();
1823
1824   CancelPaints();
1825   LoadPageInfo(true);
1826   UpdateTickMarks();
1827   client_->Invalidate(pp::Rect(plugin_size_));
1828 }
1829
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());
1838     }
1839   }
1840
1841   return base::UTF16ToUTF8(result);
1842 }
1843
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();
1851 }
1852
1853 bool PDFiumEngine::IsSelecting() {
1854   return selecting_;
1855 }
1856
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;
1870   };
1871 }
1872
1873 void PDFiumEngine::SelectAll() {
1874   SelectionChangeInvalidator selection_invalidator(this);
1875
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()));
1881     }
1882 }
1883
1884 int PDFiumEngine::GetNumberOfPages() {
1885   return pages_.size();
1886 }
1887
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);
1900   }
1901   return dest ? FPDFDest_GetPageIndex(doc_, dest) : -1;
1902 }
1903
1904 int PDFiumEngine::GetFirstVisiblePage() {
1905   CalculateVisiblePages();
1906   return first_visible_page_;
1907 }
1908
1909 int PDFiumEngine::GetMostVisiblePage() {
1910   CalculateVisiblePages();
1911   return most_visible_page_;
1912 }
1913
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;
1919 }
1920
1921 pp::Rect PDFiumEngine::GetPageContentsRect(int index) {
1922   return GetScreenRect(pages_[index]->rect());
1923 }
1924
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());
1929
1930   if (pages_[index]->available()) {
1931     FPDFBitmap_FillRect(bitmap, 0, 0, image_data->size().width(),
1932                         image_data->size().height(), 0xFFFFFFFF);
1933
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);
1940   }
1941
1942   FPDFBitmap_Destroy(bitmap);
1943 }
1944
1945 void PDFiumEngine::SetGrayscale(bool grayscale) {
1946   render_grayscale_ = grayscale;
1947 }
1948
1949 void PDFiumEngine::OnCallback(int id) {
1950   if (!timers_.count(id))
1951     return;
1952
1953   timers_[id].second(id);
1954   if (timers_.count(id))  // The callback might delete the timer.
1955     client_->ScheduleCallback(id, timers_[id].first);
1956 }
1957
1958 std::string PDFiumEngine::GetPageAsJSON(int index) {
1959   if (!(HasPermission(PERMISSION_COPY) ||
1960         HasPermission(PERMISSION_COPY_ACCESSIBLE))) {
1961     return "{}";
1962   }
1963
1964   if (index < 0 || static_cast<size_t>(index) > pages_.size() - 1)
1965     return "{}";
1966
1967   // TODO(thestig) Remove after debugging http://crbug.com/402035
1968   CHECK(pages_[index]);
1969   scoped_ptr<base::Value> node(
1970       pages_[index]->GetAccessibleContentAsValue(current_rotation_));
1971   std::string page_json;
1972   base::JSONWriter::Write(node.get(), &page_json);
1973   return page_json;
1974 }
1975
1976 bool PDFiumEngine::GetPrintScaling() {
1977   return !!FPDF_VIEWERREF_GetPrintScaling(doc_);
1978 }
1979
1980 void PDFiumEngine::AppendBlankPages(int num_pages) {
1981   DCHECK(num_pages != 0);
1982
1983   if (!doc_)
1984     return;
1985
1986   selection_.clear();
1987   pending_pages_.clear();
1988
1989   // Delete all pages except the first one.
1990   while (pages_.size() > 1) {
1991     delete pages_.back();
1992     pages_.pop_back();
1993     FPDFPage_Delete(doc_, pages_.size());
1994   }
1995
1996   // Calculate document size and all page sizes.
1997   std::vector<pp::Rect> page_rects;
1998   pp::Size page_size = GetPageSize(0);
1999   page_size.Enlarge(kPageShadowLeft + kPageShadowRight,
2000                     kPageShadowTop + kPageShadowBottom);
2001   pp::Size old_document_size = document_size_;
2002   document_size_ = pp::Size(page_size.width(), 0);
2003   for (int i = 0; i < num_pages; ++i) {
2004     if (i != 0) {
2005       // Add space for horizontal separator.
2006       document_size_.Enlarge(0, kPageSeparatorThickness);
2007     }
2008
2009     pp::Rect rect(pp::Point(0, document_size_.height()), page_size);
2010     page_rects.push_back(rect);
2011
2012     document_size_.Enlarge(0, page_size.height());
2013   }
2014
2015   // Create blank pages.
2016   for (int i = 1; i < num_pages; ++i) {
2017     pp::Rect page_rect(page_rects[i]);
2018     page_rect.Inset(kPageShadowLeft, kPageShadowTop,
2019                     kPageShadowRight, kPageShadowBottom);
2020     double width_in_points =
2021         page_rect.width() * kPointsPerInch / kPixelsPerInch;
2022     double height_in_points =
2023         page_rect.height() * kPointsPerInch / kPixelsPerInch;
2024     FPDFPage_New(doc_, i, width_in_points, height_in_points);
2025     pages_.push_back(new PDFiumPage(this, i, page_rect, true));
2026     // TODO(thestig) Remove after debugging http://crbug.com/402035
2027     CHECK(pages_.back());
2028   }
2029
2030   CalculateVisiblePages();
2031   if (document_size_ != old_document_size)
2032     client_->DocumentSizeUpdated(document_size_);
2033 }
2034
2035 void PDFiumEngine::LoadDocument() {
2036   // Check if the document is ready for loading. If it isn't just bail for now,
2037   // we will call LoadDocument() again later.
2038   if (!doc_ && !doc_loader_.IsDocumentComplete() &&
2039       !FPDFAvail_IsDocAvail(fpdf_availability_, &download_hints_)) {
2040     return;
2041   }
2042
2043   // If we're in the middle of getting a password, just return. We will retry
2044   // loading the document after we get the password anyway.
2045   if (getting_password_)
2046     return;
2047
2048   ScopedUnsupportedFeature scoped_unsupported_feature(this);
2049   bool needs_password = false;
2050   if (TryLoadingDoc(false, std::string(), &needs_password)) {
2051     ContinueLoadingDocument(false, std::string());
2052     return;
2053   }
2054   if (needs_password)
2055     GetPasswordAndLoad();
2056   else
2057     client_->DocumentLoadFailed();
2058 }
2059
2060 bool PDFiumEngine::TryLoadingDoc(bool with_password,
2061                                  const std::string& password,
2062                                  bool* needs_password) {
2063   *needs_password = false;
2064   if (doc_)
2065     return true;
2066
2067   const char* password_cstr = NULL;
2068   if (with_password) {
2069     password_cstr = password.c_str();
2070     password_tries_remaining_--;
2071   }
2072   if (doc_loader_.IsDocumentComplete())
2073     doc_ = FPDF_LoadCustomDocument(&file_access_, password_cstr);
2074   else
2075     doc_ = FPDFAvail_GetDocument(fpdf_availability_, password_cstr);
2076
2077   if (!doc_ && FPDF_GetLastError() == FPDF_ERR_PASSWORD)
2078     *needs_password = true;
2079
2080   return doc_ != NULL;
2081 }
2082
2083 void PDFiumEngine::GetPasswordAndLoad() {
2084   getting_password_ = true;
2085   DCHECK(!doc_ && FPDF_GetLastError() == FPDF_ERR_PASSWORD);
2086   client_->GetDocumentPassword(password_factory_.NewCallbackWithOutput(
2087       &PDFiumEngine::OnGetPasswordComplete));
2088 }
2089
2090 void PDFiumEngine::OnGetPasswordComplete(int32_t result,
2091                                          const pp::Var& password) {
2092   getting_password_ = false;
2093
2094   bool password_given = false;
2095   std::string password_text;
2096   if (result == PP_OK && password.is_string()) {
2097     password_text = password.AsString();
2098     if (!password_text.empty())
2099       password_given = true;
2100   }
2101   ContinueLoadingDocument(password_given, password_text);
2102 }
2103
2104 void PDFiumEngine::ContinueLoadingDocument(
2105     bool has_password,
2106     const std::string& password) {
2107   ScopedUnsupportedFeature scoped_unsupported_feature(this);
2108
2109   bool needs_password = false;
2110   bool loaded = TryLoadingDoc(has_password, password, &needs_password);
2111   bool password_incorrect = !loaded && has_password && needs_password;
2112   if (password_incorrect && password_tries_remaining_ > 0) {
2113     GetPasswordAndLoad();
2114     return;
2115   }
2116
2117   if (!doc_) {
2118     client_->DocumentLoadFailed();
2119     return;
2120   }
2121
2122   if (FPDFDoc_GetPageMode(doc_) == PAGEMODE_USEOUTLINES)
2123     client_->DocumentHasUnsupportedFeature("Bookmarks");
2124
2125   permissions_ = FPDF_GetDocPermissions(doc_);
2126
2127   if (!form_) {
2128     // Only returns 0 when data isn't available.  If form data is downloaded, or
2129     // if this isn't a form, returns positive values.
2130     if (!doc_loader_.IsDocumentComplete() &&
2131         !FPDFAvail_IsFormAvail(fpdf_availability_, &download_hints_)) {
2132       return;
2133     }
2134
2135     form_ = FPDFDOC_InitFormFillEnviroument(
2136         doc_, static_cast<FPDF_FORMFILLINFO*>(this));
2137     FPDF_SetFormFieldHighlightColor(form_, 0, kFormHighlightColor);
2138     FPDF_SetFormFieldHighlightAlpha(form_, kFormHighlightAlpha);
2139   }
2140
2141   if (!doc_loader_.IsDocumentComplete()) {
2142     // Check if the first page is available.  In a linearized PDF, that is not
2143     // always page 0.  Doing this gives us the default page size, since when the
2144     // document is available, the first page is available as well.
2145     CheckPageAvailable(FPDFAvail_GetFirstPageNum(doc_), &pending_pages_);
2146   }
2147
2148   LoadPageInfo(false);
2149
2150   if (doc_loader_.IsDocumentComplete())
2151     FinishLoadingDocument();
2152 }
2153
2154 void PDFiumEngine::LoadPageInfo(bool reload) {
2155   pending_pages_.clear();
2156   pp::Size old_document_size = document_size_;
2157   document_size_ = pp::Size();
2158   std::vector<pp::Rect> page_rects;
2159   int page_count = FPDF_GetPageCount(doc_);
2160   bool doc_complete = doc_loader_.IsDocumentComplete();
2161   for (int i = 0; i < page_count; ++i) {
2162     if (i != 0) {
2163       // Add space for horizontal separator.
2164       document_size_.Enlarge(0, kPageSeparatorThickness);
2165     }
2166
2167     // Get page availability. If reload==false, and document is not loaded yet
2168     // (we are using async loading) - mark all pages as unavailable.
2169     // If reload==true (we have document constructed already), get page
2170     // availability flag from already existing PDFiumPage class.
2171     bool page_available = reload ? pages_[i]->available() : doc_complete;
2172
2173     pp::Size size = page_available ? GetPageSize(i) : default_page_size_;
2174     size.Enlarge(kPageShadowLeft + kPageShadowRight,
2175                  kPageShadowTop + kPageShadowBottom);
2176     pp::Rect rect(pp::Point(0, document_size_.height()), size);
2177     page_rects.push_back(rect);
2178
2179     if (size.width() > document_size_.width())
2180       document_size_.set_width(size.width());
2181
2182     document_size_.Enlarge(0, size.height());
2183   }
2184
2185   for (int i = 0; i < page_count; ++i) {
2186     // Center pages relative to the entire document.
2187     page_rects[i].set_x((document_size_.width() - page_rects[i].width()) / 2);
2188     pp::Rect page_rect(page_rects[i]);
2189     page_rect.Inset(kPageShadowLeft, kPageShadowTop,
2190                     kPageShadowRight, kPageShadowBottom);
2191     if (reload) {
2192       pages_[i]->set_rect(page_rect);
2193     } else {
2194       pages_.push_back(new PDFiumPage(this, i, page_rect, doc_complete));
2195       // TODO(thestig) Remove after debugging http://crbug.com/402035
2196       CHECK(pages_.back());
2197     }
2198   }
2199
2200   CalculateVisiblePages();
2201   if (document_size_ != old_document_size)
2202     client_->DocumentSizeUpdated(document_size_);
2203 }
2204
2205 void PDFiumEngine::CalculateVisiblePages() {
2206   // Clear pending requests queue, since it may contain requests to the pages
2207   // that are already invisible (after scrolling for example).
2208   pending_pages_.clear();
2209   doc_loader_.ClearPendingRequests();
2210
2211   visible_pages_.clear();
2212   pp::Rect visible_rect(plugin_size_);
2213   for (size_t i = 0; i < pages_.size(); ++i) {
2214     // Check an entire PageScreenRect, since we might need to repaint side
2215     // borders and shadows even if the page itself is not visible.
2216     // For example, when user use pdf with different page sizes and zoomed in
2217     // outside page area.
2218     if (visible_rect.Intersects(GetPageScreenRect(i))) {
2219       visible_pages_.push_back(i);
2220       CheckPageAvailable(i, &pending_pages_);
2221     } else {
2222       // Need to unload pages when we're not using them, since some PDFs use a
2223       // lot of memory.  See http://crbug.com/48791
2224       if (defer_page_unload_) {
2225         deferred_page_unloads_.push_back(i);
2226       } else {
2227         pages_[i]->Unload();
2228       }
2229
2230       // If the last mouse down was on a page that's no longer visible, reset
2231       // that variable so that we don't send keyboard events to it (the focus
2232       // will be lost when the page is first closed anyways).
2233       if (static_cast<int>(i) == last_page_mouse_down_)
2234         last_page_mouse_down_ = -1;
2235     }
2236   }
2237
2238   // Any pending highlighting of form fields will be invalid since these are in
2239   // screen coordinates.
2240   form_highlights_.clear();
2241
2242   if (visible_pages_.size() == 0)
2243     first_visible_page_ = -1;
2244   else
2245     first_visible_page_ = visible_pages_.front();
2246
2247   int most_visible_page = first_visible_page_;
2248   // Check if the next page is more visible than the first one.
2249   if (most_visible_page != -1 &&
2250       pages_.size() > 0 &&
2251       most_visible_page < static_cast<int>(pages_.size()) - 1) {
2252     pp::Rect rc_first =
2253         visible_rect.Intersect(GetPageScreenRect(most_visible_page));
2254     pp::Rect rc_next =
2255         visible_rect.Intersect(GetPageScreenRect(most_visible_page + 1));
2256     if (rc_next.height() > rc_first.height())
2257       most_visible_page++;
2258   }
2259
2260   SetCurrentPage(most_visible_page);
2261 }
2262
2263 bool PDFiumEngine::IsPageVisible(int index) const {
2264   for (size_t i = 0; i < visible_pages_.size(); ++i) {
2265     if (visible_pages_[i] == index)
2266       return true;
2267   }
2268
2269   return false;
2270 }
2271
2272 bool PDFiumEngine::CheckPageAvailable(int index, std::vector<int>* pending) {
2273   if (!doc_ || !form_)
2274     return false;
2275
2276   if (static_cast<int>(pages_.size()) > index && pages_[index]->available())
2277     return true;
2278
2279   if (!FPDFAvail_IsPageAvail(fpdf_availability_, index, &download_hints_)) {
2280     size_t j;
2281     for (j = 0; j < pending->size(); ++j) {
2282       if ((*pending)[j] == index)
2283         break;
2284     }
2285
2286     if (j == pending->size())
2287       pending->push_back(index);
2288     return false;
2289   }
2290
2291   if (static_cast<int>(pages_.size()) > index)
2292     pages_[index]->set_available(true);
2293   if (!default_page_size_.GetArea())
2294     default_page_size_ = GetPageSize(index);
2295   return true;
2296 }
2297
2298 pp::Size PDFiumEngine::GetPageSize(int index) {
2299   pp::Size size;
2300   double width_in_points = 0;
2301   double height_in_points = 0;
2302   int rv = FPDF_GetPageSizeByIndex(
2303       doc_, index, &width_in_points, &height_in_points);
2304
2305   if (rv) {
2306     int width_in_pixels = static_cast<int>(
2307         width_in_points * kPixelsPerInch / kPointsPerInch);
2308     int height_in_pixels = static_cast<int>(
2309         height_in_points * kPixelsPerInch / kPointsPerInch);
2310     if (current_rotation_ % 2 == 1)
2311       std::swap(width_in_pixels, height_in_pixels);
2312     size = pp::Size(width_in_pixels, height_in_pixels);
2313   }
2314   return size;
2315 }
2316
2317 int PDFiumEngine::StartPaint(int page_index, const pp::Rect& dirty) {
2318   // For the first time we hit paint, do nothing and just record the paint for
2319   // the next callback.  This keeps the UI responsive in case the user is doing
2320   // a lot of scrolling.
2321   ProgressivePaint progressive;
2322   progressive.rect = dirty;
2323   progressive.page_index = page_index;
2324   progressive.bitmap = NULL;
2325   progressive.painted_ = false;
2326   progressive_paints_.push_back(progressive);
2327   return progressive_paints_.size() - 1;
2328 }
2329
2330 bool PDFiumEngine::ContinuePaint(int progressive_index,
2331                                  pp::ImageData* image_data) {
2332 #if defined(OS_LINUX)
2333   g_last_instance_id = client_->GetPluginInstance()->pp_instance();
2334 #endif
2335
2336   int rv;
2337   int page_index = progressive_paints_[progressive_index].page_index;
2338   last_progressive_start_time_ = base::Time::Now();
2339   if (progressive_paints_[progressive_index].bitmap) {
2340     rv = FPDF_RenderPage_Continue(
2341         pages_[page_index]->GetPage(), static_cast<IFSDK_PAUSE*>(this));
2342   } else {
2343     pp::Rect dirty = progressive_paints_[progressive_index].rect;
2344     progressive_paints_[progressive_index].bitmap = CreateBitmap(dirty,
2345                                                                  image_data);
2346     int start_x, start_y, size_x, size_y;
2347     GetPDFiumRect(
2348         page_index, dirty, &start_x, &start_y, &size_x, &size_y);
2349     FPDFBitmap_FillRect(progressive_paints_[progressive_index].bitmap, start_x,
2350                         start_y, size_x, size_y, 0xFFFFFFFF);
2351     rv = FPDF_RenderPageBitmap_Start(
2352         progressive_paints_[progressive_index].bitmap,
2353         pages_[page_index]->GetPage(), start_x, start_y, size_x, size_y,
2354         current_rotation_,
2355         GetRenderingFlags(), static_cast<IFSDK_PAUSE*>(this));
2356   }
2357   return rv != FPDF_RENDER_TOBECOUNTINUED;
2358 }
2359
2360 void PDFiumEngine::FinishPaint(int progressive_index,
2361                                pp::ImageData* image_data) {
2362   int page_index = progressive_paints_[progressive_index].page_index;
2363   pp::Rect dirty_in_screen = progressive_paints_[progressive_index].rect;
2364   FPDF_BITMAP bitmap = progressive_paints_[progressive_index].bitmap;
2365   int start_x, start_y, size_x, size_y;
2366   GetPDFiumRect(
2367       page_index, dirty_in_screen, &start_x, &start_y, &size_x, &size_y);
2368
2369   // Draw the forms.
2370   FPDF_FFLDraw(
2371       form_, bitmap, pages_[page_index]->GetPage(), start_x, start_y, size_x,
2372       size_y, current_rotation_, GetRenderingFlags());
2373
2374   FillPageSides(progressive_index);
2375
2376   // Paint the page shadows.
2377   PaintPageShadow(progressive_index, image_data);
2378
2379   DrawSelections(progressive_index, image_data);
2380
2381   FPDF_RenderPage_Close(pages_[page_index]->GetPage());
2382   FPDFBitmap_Destroy(bitmap);
2383   progressive_paints_.erase(progressive_paints_.begin() + progressive_index);
2384
2385   client_->DocumentPaintOccurred();
2386 }
2387
2388 void PDFiumEngine::CancelPaints() {
2389   for (size_t i = 0; i < progressive_paints_.size(); ++i) {
2390     FPDF_RenderPage_Close(pages_[progressive_paints_[i].page_index]->GetPage());
2391     FPDFBitmap_Destroy(progressive_paints_[i].bitmap);
2392   }
2393   progressive_paints_.clear();
2394 }
2395
2396 void PDFiumEngine::FillPageSides(int progressive_index) {
2397   int page_index = progressive_paints_[progressive_index].page_index;
2398   pp::Rect dirty_in_screen = progressive_paints_[progressive_index].rect;
2399   FPDF_BITMAP bitmap = progressive_paints_[progressive_index].bitmap;
2400
2401   pp::Rect page_rect = pages_[page_index]->rect();
2402   if (page_rect.x() > 0) {
2403     pp::Rect left(0,
2404                   page_rect.y() - kPageShadowTop,
2405                   page_rect.x() - kPageShadowLeft,
2406                   page_rect.height() + kPageShadowTop +
2407                       kPageShadowBottom + kPageSeparatorThickness);
2408     left = GetScreenRect(left).Intersect(dirty_in_screen);
2409
2410     FPDFBitmap_FillRect(bitmap, left.x() - dirty_in_screen.x(),
2411                         left.y() - dirty_in_screen.y(), left.width(),
2412                         left.height(), kBackgroundColor);
2413   }
2414
2415   if (page_rect.right() < document_size_.width()) {
2416     pp::Rect right(page_rect.right() + kPageShadowRight,
2417                    page_rect.y() - kPageShadowTop,
2418                    document_size_.width() - page_rect.right() -
2419                       kPageShadowRight,
2420                    page_rect.height() + kPageShadowTop +
2421                        kPageShadowBottom + kPageSeparatorThickness);
2422     right = GetScreenRect(right).Intersect(dirty_in_screen);
2423
2424     FPDFBitmap_FillRect(bitmap, right.x() - dirty_in_screen.x(),
2425                         right.y() - dirty_in_screen.y(), right.width(),
2426                         right.height(), kBackgroundColor);
2427   }
2428
2429   // Paint separator.
2430   pp::Rect bottom(page_rect.x() - kPageShadowLeft,
2431                   page_rect.bottom() + kPageShadowBottom,
2432                   page_rect.width() + kPageShadowLeft + kPageShadowRight,
2433                   kPageSeparatorThickness);
2434   bottom = GetScreenRect(bottom).Intersect(dirty_in_screen);
2435
2436   FPDFBitmap_FillRect(bitmap, bottom.x() - dirty_in_screen.x(),
2437                       bottom.y() - dirty_in_screen.y(), bottom.width(),
2438                       bottom.height(), kBackgroundColor);
2439 }
2440
2441 void PDFiumEngine::PaintPageShadow(int progressive_index,
2442                                    pp::ImageData* image_data) {
2443   int page_index = progressive_paints_[progressive_index].page_index;
2444   pp::Rect dirty_in_screen = progressive_paints_[progressive_index].rect;
2445   pp::Rect page_rect = pages_[page_index]->rect();
2446   pp::Rect shadow_rect(page_rect);
2447   shadow_rect.Inset(-kPageShadowLeft, -kPageShadowTop,
2448                     -kPageShadowRight, -kPageShadowBottom);
2449
2450   // Due to the rounding errors of the GetScreenRect it is possible to get
2451   // different size shadows on the left and right sides even they are defined
2452   // the same. To fix this issue let's calculate shadow rect and then shrink
2453   // it by the size of the shadows.
2454   shadow_rect = GetScreenRect(shadow_rect);
2455   page_rect = shadow_rect;
2456
2457   page_rect.Inset(static_cast<int>(ceil(kPageShadowLeft * current_zoom_)),
2458                   static_cast<int>(ceil(kPageShadowTop * current_zoom_)),
2459                   static_cast<int>(ceil(kPageShadowRight * current_zoom_)),
2460                   static_cast<int>(ceil(kPageShadowBottom * current_zoom_)));
2461
2462   DrawPageShadow(page_rect, shadow_rect, dirty_in_screen, image_data);
2463 }
2464
2465 void PDFiumEngine::DrawSelections(int progressive_index,
2466                                   pp::ImageData* image_data) {
2467   int page_index = progressive_paints_[progressive_index].page_index;
2468   pp::Rect dirty_in_screen = progressive_paints_[progressive_index].rect;
2469
2470   void* region = NULL;
2471   int stride;
2472   GetRegion(dirty_in_screen.point(), image_data, &region, &stride);
2473
2474   std::vector<pp::Rect> highlighted_rects;
2475   pp::Rect visible_rect = GetVisibleRect();
2476   for (size_t k = 0; k < selection_.size(); ++k) {
2477     if (selection_[k].page_index() != page_index)
2478       continue;
2479     std::vector<pp::Rect> rects = selection_[k].GetScreenRects(
2480         visible_rect.point(), current_zoom_, current_rotation_);
2481     for (size_t j = 0; j < rects.size(); ++j) {
2482       pp::Rect visible_selection = rects[j].Intersect(dirty_in_screen);
2483       if (visible_selection.IsEmpty())
2484         continue;
2485
2486       visible_selection.Offset(
2487           -dirty_in_screen.point().x(), -dirty_in_screen.point().y());
2488       Highlight(region, stride, visible_selection, &highlighted_rects);
2489     }
2490   }
2491
2492   for (size_t k = 0; k < form_highlights_.size(); ++k) {
2493     pp::Rect visible_selection = form_highlights_[k].Intersect(dirty_in_screen);
2494       if (visible_selection.IsEmpty())
2495         continue;
2496
2497     visible_selection.Offset(
2498         -dirty_in_screen.point().x(), -dirty_in_screen.point().y());
2499     Highlight(region, stride, visible_selection, &highlighted_rects);
2500   }
2501   form_highlights_.clear();
2502 }
2503
2504 void PDFiumEngine::PaintUnavailablePage(int page_index,
2505                                         const pp::Rect& dirty,
2506                                         pp::ImageData* image_data) {
2507   int start_x, start_y, size_x, size_y;
2508   GetPDFiumRect(page_index, dirty, &start_x, &start_y, &size_x, &size_y);
2509   FPDF_BITMAP bitmap = CreateBitmap(dirty, image_data);
2510   FPDFBitmap_FillRect(bitmap, start_x, start_y, size_x, size_y,
2511                       kPendingPageColor);
2512
2513   pp::Rect loading_text_in_screen(
2514       pages_[page_index]->rect().width() / 2,
2515       pages_[page_index]->rect().y() + kLoadingTextVerticalOffset, 0, 0);
2516   loading_text_in_screen = GetScreenRect(loading_text_in_screen);
2517   FPDFBitmap_Destroy(bitmap);
2518 }
2519
2520 int PDFiumEngine::GetProgressiveIndex(int page_index) const {
2521   for (size_t i = 0; i < progressive_paints_.size(); ++i) {
2522     if (progressive_paints_[i].page_index == page_index)
2523       return i;
2524   }
2525   return -1;
2526 }
2527
2528 FPDF_BITMAP PDFiumEngine::CreateBitmap(const pp::Rect& rect,
2529                                        pp::ImageData* image_data) const {
2530   void* region;
2531   int stride;
2532   GetRegion(rect.point(), image_data, &region, &stride);
2533   if (!region)
2534     return NULL;
2535   return FPDFBitmap_CreateEx(
2536       rect.width(), rect.height(), FPDFBitmap_BGRx, region, stride);
2537 }
2538
2539 void PDFiumEngine::GetPDFiumRect(
2540     int page_index, const pp::Rect& rect, int* start_x, int* start_y,
2541     int* size_x, int* size_y) const {
2542   pp::Rect page_rect = GetScreenRect(pages_[page_index]->rect());
2543   page_rect.Offset(-rect.x(), -rect.y());
2544
2545   *start_x = page_rect.x();
2546   *start_y = page_rect.y();
2547   *size_x = page_rect.width();
2548   *size_y = page_rect.height();
2549 }
2550
2551 int PDFiumEngine::GetRenderingFlags() const {
2552   int flags = FPDF_LCD_TEXT | FPDF_NO_CATCH;
2553   if (render_grayscale_)
2554     flags |= FPDF_GRAYSCALE;
2555   if (client_->IsPrintPreview())
2556     flags |= FPDF_PRINTING;
2557   return flags;
2558 }
2559
2560 pp::Rect PDFiumEngine::GetVisibleRect() const {
2561   pp::Rect rv;
2562   rv.set_x(static_cast<int>(position_.x() / current_zoom_));
2563   rv.set_y(static_cast<int>(position_.y() / current_zoom_));
2564   rv.set_width(static_cast<int>(ceil(plugin_size_.width() / current_zoom_)));
2565   rv.set_height(static_cast<int>(ceil(plugin_size_.height() / current_zoom_)));
2566   return rv;
2567 }
2568
2569 pp::Rect PDFiumEngine::GetPageScreenRect(int page_index) const {
2570   // Since we use this rect for creating the PDFium bitmap, also include other
2571   // areas around the page that we might need to update such as the page
2572   // separator and the sides if the page is narrower than the document.
2573   return GetScreenRect(pp::Rect(
2574       0,
2575       pages_[page_index]->rect().y() - kPageShadowTop,
2576       document_size_.width(),
2577       pages_[page_index]->rect().height() + kPageShadowTop +
2578           kPageShadowBottom + kPageSeparatorThickness));
2579 }
2580
2581 pp::Rect PDFiumEngine::GetScreenRect(const pp::Rect& rect) const {
2582   pp::Rect rv;
2583   int right =
2584       static_cast<int>(ceil(rect.right() * current_zoom_ - position_.x()));
2585   int bottom =
2586     static_cast<int>(ceil(rect.bottom() * current_zoom_ - position_.y()));
2587
2588   rv.set_x(static_cast<int>(rect.x() * current_zoom_ - position_.x()));
2589   rv.set_y(static_cast<int>(rect.y() * current_zoom_ - position_.y()));
2590   rv.set_width(right - rv.x());
2591   rv.set_height(bottom - rv.y());
2592   return rv;
2593 }
2594
2595 void PDFiumEngine::Highlight(void* buffer,
2596                              int stride,
2597                              const pp::Rect& rect,
2598                              std::vector<pp::Rect>* highlighted_rects) {
2599   if (!buffer)
2600     return;
2601
2602   pp::Rect new_rect = rect;
2603   for (size_t i = 0; i < highlighted_rects->size(); ++i)
2604     new_rect = new_rect.Subtract((*highlighted_rects)[i]);
2605
2606   highlighted_rects->push_back(new_rect);
2607   int l = new_rect.x();
2608   int t = new_rect.y();
2609   int w = new_rect.width();
2610   int h = new_rect.height();
2611
2612   for (int y = t; y < t + h; ++y) {
2613     for (int x = l; x < l + w; ++x) {
2614       uint8* pixel = static_cast<uint8*>(buffer) + y * stride + x * 4;
2615       //  This is our highlight color.
2616       pixel[0] = static_cast<uint8>(
2617           pixel[0] * (kHighlightColorB / 255.0));
2618       pixel[1] = static_cast<uint8>(
2619           pixel[1] * (kHighlightColorG / 255.0));
2620       pixel[2] = static_cast<uint8>(
2621           pixel[2] * (kHighlightColorR / 255.0));
2622     }
2623   }
2624 }
2625
2626 PDFiumEngine::SelectionChangeInvalidator::SelectionChangeInvalidator(
2627     PDFiumEngine* engine) : engine_(engine) {
2628   previous_origin_ = engine_->GetVisibleRect().point();
2629   GetVisibleSelectionsScreenRects(&old_selections_);
2630 }
2631
2632 PDFiumEngine::SelectionChangeInvalidator::~SelectionChangeInvalidator() {
2633   // Offset the old selections if the document scrolled since we recorded them.
2634   pp::Point offset = previous_origin_ - engine_->GetVisibleRect().point();
2635   for (size_t i = 0; i < old_selections_.size(); ++i)
2636     old_selections_[i].Offset(offset);
2637
2638   std::vector<pp::Rect> new_selections;
2639   GetVisibleSelectionsScreenRects(&new_selections);
2640   for (size_t i = 0; i < new_selections.size(); ++i) {
2641     for (size_t j = 0; j < old_selections_.size(); ++j) {
2642       if (new_selections[i] == old_selections_[j]) {
2643         // Rectangle was selected before and after, so no need to invalidate it.
2644         // Mark the rectangles by setting them to empty.
2645         new_selections[i] = old_selections_[j] = pp::Rect();
2646       }
2647     }
2648   }
2649
2650   for (size_t i = 0; i < old_selections_.size(); ++i) {
2651     if (!old_selections_[i].IsEmpty())
2652       engine_->client_->Invalidate(old_selections_[i]);
2653   }
2654   for (size_t i = 0; i < new_selections.size(); ++i) {
2655     if (!new_selections[i].IsEmpty())
2656       engine_->client_->Invalidate(new_selections[i]);
2657   }
2658   engine_->OnSelectionChanged();
2659 }
2660
2661 void
2662 PDFiumEngine::SelectionChangeInvalidator::GetVisibleSelectionsScreenRects(
2663     std::vector<pp::Rect>* rects) {
2664   pp::Rect visible_rect = engine_->GetVisibleRect();
2665   for (size_t i = 0; i < engine_->selection_.size(); ++i) {
2666     int page_index = engine_->selection_[i].page_index();
2667     if (!engine_->IsPageVisible(page_index))
2668       continue;  // This selection is on a page that's not currently visible.
2669
2670     std::vector<pp::Rect> selection_rects =
2671         engine_->selection_[i].GetScreenRects(
2672             visible_rect.point(),
2673             engine_->current_zoom_,
2674             engine_->current_rotation_);
2675     rects->insert(rects->end(), selection_rects.begin(), selection_rects.end());
2676   }
2677 }
2678
2679 void PDFiumEngine::DeviceToPage(int page_index,
2680                                 float device_x,
2681                                 float device_y,
2682                                 double* page_x,
2683                                 double* page_y) {
2684   *page_x = *page_y = 0;
2685   int temp_x = static_cast<int>((device_x + position_.x())/ current_zoom_ -
2686       pages_[page_index]->rect().x());
2687   int temp_y = static_cast<int>((device_y + position_.y())/ current_zoom_ -
2688       pages_[page_index]->rect().y());
2689   FPDF_DeviceToPage(
2690       pages_[page_index]->GetPage(), 0, 0,
2691       pages_[page_index]->rect().width(),  pages_[page_index]->rect().height(),
2692       current_rotation_, temp_x, temp_y, page_x, page_y);
2693 }
2694
2695 int PDFiumEngine::GetVisiblePageIndex(FPDF_PAGE page) {
2696   for (size_t i = 0; i < visible_pages_.size(); ++i) {
2697     if (pages_[visible_pages_[i]]->GetPage() == page)
2698       return visible_pages_[i];
2699   }
2700   return -1;
2701 }
2702
2703 void PDFiumEngine::SetCurrentPage(int index) {
2704   if (index == most_visible_page_ || !form_)
2705     return;
2706   if (most_visible_page_ != -1 && called_do_document_action_) {
2707     FPDF_PAGE old_page = pages_[most_visible_page_]->GetPage();
2708     FORM_DoPageAAction(old_page, form_, FPDFPAGE_AACTION_CLOSE);
2709   }
2710   most_visible_page_ = index;
2711 #if defined(OS_LINUX)
2712     g_last_instance_id = client_->GetPluginInstance()->pp_instance();
2713 #endif
2714   if (most_visible_page_ != -1 && called_do_document_action_) {
2715     FPDF_PAGE new_page = pages_[most_visible_page_]->GetPage();
2716     FORM_DoPageAAction(new_page, form_, FPDFPAGE_AACTION_OPEN);
2717   }
2718 }
2719
2720 void PDFiumEngine::TransformPDFPageForPrinting(
2721     FPDF_PAGE page,
2722     const PP_PrintSettings_Dev& print_settings) {
2723   // Get the source page width and height in points.
2724   const double src_page_width = FPDF_GetPageWidth(page);
2725   const double src_page_height = FPDF_GetPageHeight(page);
2726
2727   const int src_page_rotation = FPDFPage_GetRotation(page);
2728   const bool fit_to_page = print_settings.print_scaling_option ==
2729       PP_PRINTSCALINGOPTION_FIT_TO_PRINTABLE_AREA;
2730
2731   pp::Size page_size(print_settings.paper_size);
2732   pp::Rect content_rect(print_settings.printable_area);
2733   const bool rotated = (src_page_rotation % 2 == 1);
2734   SetPageSizeAndContentRect(rotated,
2735                             src_page_width > src_page_height,
2736                             &page_size,
2737                             &content_rect);
2738
2739   // Compute the screen page width and height in points.
2740   const int actual_page_width =
2741       rotated ? page_size.height() : page_size.width();
2742   const int actual_page_height =
2743       rotated ? page_size.width() : page_size.height();
2744
2745   const double scale_factor = CalculateScaleFactor(fit_to_page, content_rect,
2746                                                    src_page_width,
2747                                                    src_page_height, rotated);
2748
2749   // Calculate positions for the clip box.
2750   ClipBox source_clip_box;
2751   CalculateClipBoxBoundary(page, scale_factor, rotated, &source_clip_box);
2752
2753   // Calculate the translation offset values.
2754   double offset_x = 0;
2755   double offset_y = 0;
2756   if (fit_to_page) {
2757     CalculateScaledClipBoxOffset(content_rect, source_clip_box, &offset_x,
2758                                  &offset_y);
2759   } else {
2760     CalculateNonScaledClipBoxOffset(content_rect, src_page_rotation,
2761                                     actual_page_width, actual_page_height,
2762                                     source_clip_box, &offset_x, &offset_y);
2763   }
2764
2765   // Reset the media box and crop box. When the page has crop box and media box,
2766   // the plugin will display the crop box contents and not the entire media box.
2767   // If the pages have different crop box values, the plugin will display a
2768   // document of multiple page sizes. To give better user experience, we
2769   // decided to have same crop box and media box values. Hence, the user will
2770   // see a list of uniform pages.
2771   FPDFPage_SetMediaBox(page, 0, 0, page_size.width(), page_size.height());
2772   FPDFPage_SetCropBox(page, 0, 0, page_size.width(), page_size.height());
2773
2774   // Transformation is not required, return. Do this check only after updating
2775   // the media box and crop box. For more detailed information, please refer to
2776   // the comment block right before FPDF_SetMediaBox and FPDF_GetMediaBox calls.
2777   if (scale_factor == 1.0 && offset_x == 0 && offset_y == 0)
2778     return;
2779
2780
2781   // All the positions have been calculated, now manipulate the PDF.
2782   FS_MATRIX matrix = {static_cast<float>(scale_factor),
2783                       0,
2784                       0,
2785                       static_cast<float>(scale_factor),
2786                       static_cast<float>(offset_x),
2787                       static_cast<float>(offset_y)};
2788   FS_RECTF cliprect = {static_cast<float>(source_clip_box.left+offset_x),
2789                        static_cast<float>(source_clip_box.top+offset_y),
2790                        static_cast<float>(source_clip_box.right+offset_x),
2791                        static_cast<float>(source_clip_box.bottom+offset_y)};
2792   FPDFPage_TransFormWithClip(page, &matrix, &cliprect);
2793   FPDFPage_TransformAnnots(page, scale_factor, 0, 0, scale_factor,
2794                            offset_x, offset_y);
2795 }
2796
2797 void PDFiumEngine::DrawPageShadow(const pp::Rect& page_rc,
2798                                   const pp::Rect& shadow_rc,
2799                                   const pp::Rect& clip_rc,
2800                                   pp::ImageData* image_data) {
2801   pp::Rect page_rect(page_rc);
2802   page_rect.Offset(page_offset_);
2803
2804   pp::Rect shadow_rect(shadow_rc);
2805   shadow_rect.Offset(page_offset_);
2806
2807   pp::Rect clip_rect(clip_rc);
2808   clip_rect.Offset(page_offset_);
2809
2810   // Page drop shadow parameters.
2811   const double factor = 0.5;
2812   uint32 depth = std::max(
2813       std::max(page_rect.x() - shadow_rect.x(),
2814                page_rect.y() - shadow_rect.y()),
2815       std::max(shadow_rect.right() - page_rect.right(),
2816                shadow_rect.bottom() - page_rect.bottom()));
2817   depth = static_cast<uint32>(depth * 1.5) + 1;
2818
2819   // We need to check depth only to verify our copy of shadow matrix is correct.
2820   if (!page_shadow_.get() || page_shadow_->depth() != depth)
2821     page_shadow_.reset(new ShadowMatrix(depth, factor, kBackgroundColor));
2822
2823   DCHECK(!image_data->is_null());
2824   DrawShadow(image_data, shadow_rect, page_rect, clip_rect, *page_shadow_);
2825 }
2826
2827 void PDFiumEngine::GetRegion(const pp::Point& location,
2828                              pp::ImageData* image_data,
2829                              void** region,
2830                              int* stride) const {
2831   if (image_data->is_null()) {
2832     DCHECK(plugin_size_.IsEmpty());
2833     *stride = 0;
2834     *region = NULL;
2835     return;
2836   }
2837   char* buffer = static_cast<char*>(image_data->data());
2838   *stride = image_data->stride();
2839
2840   pp::Point offset_location = location + page_offset_;
2841   // TODO: update this when we support BIDI and scrollbars can be on the left.
2842   if (!buffer ||
2843       !pp::Rect(page_offset_, plugin_size_).Contains(offset_location)) {
2844     *region = NULL;
2845     return;
2846   }
2847
2848   buffer += location.y() * (*stride);
2849   buffer += (location.x() + page_offset_.x()) * 4;
2850   *region = buffer;
2851 }
2852
2853 void PDFiumEngine::OnSelectionChanged() {
2854   if (HasPermission(PDFEngine::PERMISSION_COPY))
2855     pp::PDF::SetSelectedText(GetPluginInstance(), GetSelectedText().c_str());
2856 }
2857
2858 void PDFiumEngine::Form_Invalidate(FPDF_FORMFILLINFO* param,
2859                                    FPDF_PAGE page,
2860                                    double left,
2861                                    double top,
2862                                    double right,
2863                                    double bottom) {
2864   PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
2865   int page_index = engine->GetVisiblePageIndex(page);
2866   if (page_index == -1) {
2867     // This can sometime happen when the page is closed because it went off
2868     // screen, and PDFium invalidates the control as it's being deleted.
2869     return;
2870   }
2871
2872   pp::Rect rect = engine->pages_[page_index]->PageToScreen(
2873       engine->GetVisibleRect().point(), engine->current_zoom_, left, top, right,
2874       bottom, engine->current_rotation_);
2875   engine->client_->Invalidate(rect);
2876 }
2877
2878 void PDFiumEngine::Form_OutputSelectedRect(FPDF_FORMFILLINFO* param,
2879                                            FPDF_PAGE page,
2880                                            double left,
2881                                            double top,
2882                                            double right,
2883                                            double bottom) {
2884   PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
2885   int page_index = engine->GetVisiblePageIndex(page);
2886   if (page_index == -1) {
2887     NOTREACHED();
2888     return;
2889   }
2890   pp::Rect rect = engine->pages_[page_index]->PageToScreen(
2891       engine->GetVisibleRect().point(), engine->current_zoom_, left, top, right,
2892       bottom, engine->current_rotation_);
2893   engine->form_highlights_.push_back(rect);
2894 }
2895
2896 void PDFiumEngine::Form_SetCursor(FPDF_FORMFILLINFO* param, int cursor_type) {
2897   // We don't need this since it's not enough to change the cursor in all
2898   // scenarios.  Instead, we check which form field we're under in OnMouseMove.
2899 }
2900
2901 int PDFiumEngine::Form_SetTimer(FPDF_FORMFILLINFO* param,
2902                                 int elapse,
2903                                 TimerCallback timer_func) {
2904   PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
2905   engine->timers_[++engine->next_timer_id_] =
2906       std::pair<int, TimerCallback>(elapse, timer_func);
2907   engine->client_->ScheduleCallback(engine->next_timer_id_, elapse);
2908   return engine->next_timer_id_;
2909 }
2910
2911 void PDFiumEngine::Form_KillTimer(FPDF_FORMFILLINFO* param, int timer_id) {
2912   PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
2913   engine->timers_.erase(timer_id);
2914 }
2915
2916 FPDF_SYSTEMTIME PDFiumEngine::Form_GetLocalTime(FPDF_FORMFILLINFO* param) {
2917   base::Time time = base::Time::Now();
2918   base::Time::Exploded exploded;
2919   time.LocalExplode(&exploded);
2920
2921   FPDF_SYSTEMTIME rv;
2922   rv.wYear = exploded.year;
2923   rv.wMonth = exploded.month;
2924   rv.wDayOfWeek = exploded.day_of_week;
2925   rv.wDay = exploded.day_of_month;
2926   rv.wHour = exploded.hour;
2927   rv.wMinute = exploded.minute;
2928   rv.wSecond = exploded.second;
2929   rv.wMilliseconds = exploded.millisecond;
2930   return rv;
2931 }
2932
2933 void PDFiumEngine::Form_OnChange(FPDF_FORMFILLINFO* param) {
2934   // Don't care about.
2935 }
2936
2937 FPDF_PAGE PDFiumEngine::Form_GetPage(FPDF_FORMFILLINFO* param,
2938                                      FPDF_DOCUMENT document,
2939                                      int page_index) {
2940   PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
2941   if (page_index < 0 || page_index >= static_cast<int>(engine->pages_.size()))
2942     return NULL;
2943   return engine->pages_[page_index]->GetPage();
2944 }
2945
2946 FPDF_PAGE PDFiumEngine::Form_GetCurrentPage(FPDF_FORMFILLINFO* param,
2947                                             FPDF_DOCUMENT document) {
2948   // TODO(jam): find out what this is used for.
2949   PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
2950   int index = engine->last_page_mouse_down_;
2951   if (index == -1) {
2952     index = engine->GetMostVisiblePage();
2953     if (index == -1) {
2954       NOTREACHED();
2955       return NULL;
2956     }
2957   }
2958
2959   return engine->pages_[index]->GetPage();
2960 }
2961
2962 int PDFiumEngine::Form_GetRotation(FPDF_FORMFILLINFO* param, FPDF_PAGE page) {
2963   return 0;
2964 }
2965
2966 void PDFiumEngine::Form_ExecuteNamedAction(FPDF_FORMFILLINFO* param,
2967                                            FPDF_BYTESTRING named_action) {
2968   PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
2969   std::string action(named_action);
2970   if (action == "Print") {
2971     engine->client_->Print();
2972     return;
2973   }
2974
2975   int index = engine->last_page_mouse_down_;
2976   /* Don't try to calculate the most visible page if we don't have a left click
2977      before this event (this code originally copied Form_GetCurrentPage which of
2978      course needs to do that and which doesn't have recursion). This can end up
2979      causing infinite recursion. See http://crbug.com/240413 for more
2980      information. Either way, it's not necessary for the spec'd list of named
2981      actions.
2982   if (index == -1)
2983     index = engine->GetMostVisiblePage();
2984   */
2985   if (index == -1)
2986     return;
2987
2988   // This is the only list of named actions per the spec (see 12.6.4.11). Adobe
2989   // Reader supports more, like FitWidth, but since they're not part of the spec
2990   // and we haven't got bugs about them, no need to now.
2991   if (action == "NextPage") {
2992     engine->client_->ScrollToPage(index + 1);
2993   } else if (action == "PrevPage") {
2994     engine->client_->ScrollToPage(index - 1);
2995   } else if (action == "FirstPage") {
2996     engine->client_->ScrollToPage(0);
2997   } else if (action == "LastPage") {
2998     engine->client_->ScrollToPage(engine->pages_.size() - 1);
2999   }
3000 }
3001
3002 void PDFiumEngine::Form_SetTextFieldFocus(FPDF_FORMFILLINFO* param,
3003                                           FPDF_WIDESTRING value,
3004                                           FPDF_DWORD valueLen,
3005                                           FPDF_BOOL is_focus) {
3006   // Do nothing for now.
3007   // TODO(gene): use this signal to trigger OSK.
3008 }
3009
3010 void PDFiumEngine::Form_DoURIAction(FPDF_FORMFILLINFO* param,
3011                                     FPDF_BYTESTRING uri) {
3012   PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3013   engine->client_->NavigateTo(std::string(uri), false);
3014 }
3015
3016 void PDFiumEngine::Form_DoGoToAction(FPDF_FORMFILLINFO* param,
3017                                      int page_index,
3018                                      int zoom_mode,
3019                                      float* position_array,
3020                                      int size_of_array) {
3021   PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3022   engine->client_->ScrollToPage(page_index);
3023 }
3024
3025 int PDFiumEngine::Form_Alert(IPDF_JSPLATFORM* param,
3026                              FPDF_WIDESTRING message,
3027                              FPDF_WIDESTRING title,
3028                              int type,
3029                              int icon) {
3030   // See fpdfformfill.h for these values.
3031   enum AlertType {
3032     ALERT_TYPE_OK = 0,
3033     ALERT_TYPE_OK_CANCEL,
3034     ALERT_TYPE_YES_ON,
3035     ALERT_TYPE_YES_NO_CANCEL
3036   };
3037
3038   enum AlertResult {
3039     ALERT_RESULT_OK = 1,
3040     ALERT_RESULT_CANCEL,
3041     ALERT_RESULT_NO,
3042     ALERT_RESULT_YES
3043   };
3044
3045   PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3046   std::string message_str =
3047       base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(message));
3048   if (type == ALERT_TYPE_OK) {
3049     engine->client_->Alert(message_str);
3050     return ALERT_RESULT_OK;
3051   }
3052
3053   bool rv = engine->client_->Confirm(message_str);
3054   if (type == ALERT_TYPE_OK_CANCEL)
3055     return rv ? ALERT_RESULT_OK : ALERT_RESULT_CANCEL;
3056   return rv ? ALERT_RESULT_YES : ALERT_RESULT_NO;
3057 }
3058
3059 void PDFiumEngine::Form_Beep(IPDF_JSPLATFORM* param, int type) {
3060   // Beeps are annoying, and not possible using javascript, so ignore for now.
3061 }
3062
3063 int PDFiumEngine::Form_Response(IPDF_JSPLATFORM* param,
3064                                 FPDF_WIDESTRING question,
3065                                 FPDF_WIDESTRING title,
3066                                 FPDF_WIDESTRING default_response,
3067                                 FPDF_WIDESTRING label,
3068                                 FPDF_BOOL password,
3069                                 void* response,
3070                                 int length) {
3071   std::string question_str = base::UTF16ToUTF8(
3072       reinterpret_cast<const base::char16*>(question));
3073   std::string default_str = base::UTF16ToUTF8(
3074       reinterpret_cast<const base::char16*>(default_response));
3075
3076   PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3077   std::string rv = engine->client_->Prompt(question_str, default_str);
3078   base::string16 rv_16 = base::UTF8ToUTF16(rv);
3079   int rv_bytes = rv_16.size() * sizeof(base::char16);
3080   if (response) {
3081     int bytes_to_copy = rv_bytes < length ? rv_bytes : length;
3082     memcpy(response, rv_16.c_str(), bytes_to_copy);
3083   }
3084   return rv_bytes;
3085 }
3086
3087 int PDFiumEngine::Form_GetFilePath(IPDF_JSPLATFORM* param,
3088                                    void* file_path,
3089                                    int length) {
3090   PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3091   std::string rv = engine->client_->GetURL();
3092   if (file_path && rv.size() <= static_cast<size_t>(length))
3093     memcpy(file_path, rv.c_str(), rv.size());
3094   return rv.size();
3095 }
3096
3097 void PDFiumEngine::Form_Mail(IPDF_JSPLATFORM* param,
3098                              void* mail_data,
3099                              int length,
3100                              FPDF_BOOL ui,
3101                              FPDF_WIDESTRING to,
3102                              FPDF_WIDESTRING subject,
3103                              FPDF_WIDESTRING cc,
3104                              FPDF_WIDESTRING bcc,
3105                              FPDF_WIDESTRING message) {
3106   DCHECK(length == 0);  // Don't handle attachments; no way with mailto.
3107   std::string to_str =
3108       base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(to));
3109   std::string cc_str =
3110       base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(cc));
3111   std::string bcc_str =
3112       base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(bcc));
3113   std::string subject_str =
3114       base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(subject));
3115   std::string message_str =
3116       base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(message));
3117
3118   PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3119   engine->client_->Email(to_str, cc_str, bcc_str, subject_str, message_str);
3120 }
3121
3122 void PDFiumEngine::Form_Print(IPDF_JSPLATFORM* param,
3123                               FPDF_BOOL ui,
3124                               int start,
3125                               int end,
3126                               FPDF_BOOL silent,
3127                               FPDF_BOOL shrink_to_fit,
3128                               FPDF_BOOL print_as_image,
3129                               FPDF_BOOL reverse,
3130                               FPDF_BOOL annotations) {
3131   // No way to pass the extra information to the print dialog using JavaScript.
3132   // Just opening it is fine for now.
3133   PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3134   engine->client_->Print();
3135 }
3136
3137 void PDFiumEngine::Form_SubmitForm(IPDF_JSPLATFORM* param,
3138                                    void* form_data,
3139                                    int length,
3140                                    FPDF_WIDESTRING url) {
3141   std::string url_str =
3142       base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(url));
3143   PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3144   engine->client_->SubmitForm(url_str, form_data, length);
3145 }
3146
3147 void PDFiumEngine::Form_GotoPage(IPDF_JSPLATFORM* param,
3148                                  int page_number) {
3149   PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3150   engine->client_->ScrollToPage(page_number);
3151 }
3152
3153 int PDFiumEngine::Form_Browse(IPDF_JSPLATFORM* param,
3154                               void* file_path,
3155                               int length) {
3156   PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3157   std::string path = engine->client_->ShowFileSelectionDialog();
3158   if (path.size() + 1 <= static_cast<size_t>(length))
3159     memcpy(file_path, &path[0], path.size() + 1);
3160   return path.size() + 1;
3161 }
3162
3163 FPDF_BOOL PDFiumEngine::Pause_NeedToPauseNow(IFSDK_PAUSE* param) {
3164   PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
3165   return (base::Time::Now() - engine->last_progressive_start_time_).
3166       InMilliseconds() > engine->progressive_paint_timeout_;
3167 }
3168
3169 ScopedUnsupportedFeature::ScopedUnsupportedFeature(PDFiumEngine* engine)
3170     : engine_(engine), old_engine_(g_engine_for_unsupported) {
3171   g_engine_for_unsupported = engine_;
3172 }
3173
3174 ScopedUnsupportedFeature::~ScopedUnsupportedFeature() {
3175   g_engine_for_unsupported = old_engine_;
3176 }
3177
3178 PDFEngineExports* PDFEngineExports::Create() {
3179   return new PDFiumEngineExports;
3180 }
3181
3182 namespace {
3183
3184 int CalculatePosition(FPDF_PAGE page,
3185                       const PDFiumEngineExports::RenderingSettings& settings,
3186                       pp::Rect* dest) {
3187   int page_width = static_cast<int>(
3188       FPDF_GetPageWidth(page) * settings.dpi_x / kPointsPerInch);
3189   int page_height = static_cast<int>(
3190       FPDF_GetPageHeight(page) * settings.dpi_y / kPointsPerInch);
3191
3192   // Start by assuming that we will draw exactly to the bounds rect
3193   // specified.
3194   *dest = settings.bounds;
3195
3196   int rotate = 0;  // normal orientation.
3197
3198   // Auto-rotate landscape pages to print correctly.
3199   if (settings.autorotate &&
3200       (dest->width() > dest->height()) != (page_width > page_height)) {
3201     rotate = 3;  // 90 degrees counter-clockwise.
3202     std::swap(page_width, page_height);
3203   }
3204
3205   // See if we need to scale the output
3206   bool scale_to_bounds = false;
3207   if (settings.fit_to_bounds &&
3208       ((page_width > dest->width()) || (page_height > dest->height()))) {
3209     scale_to_bounds = true;
3210   } else if (settings.stretch_to_bounds &&
3211              ((page_width < dest->width()) || (page_height < dest->height()))) {
3212     scale_to_bounds = true;
3213   }
3214
3215   if (scale_to_bounds) {
3216     // If we need to maintain aspect ratio, calculate the actual width and
3217     // height.
3218     if (settings.keep_aspect_ratio) {
3219       double scale_factor_x = page_width;
3220       scale_factor_x /= dest->width();
3221       double scale_factor_y = page_height;
3222       scale_factor_y /= dest->height();
3223       if (scale_factor_x > scale_factor_y) {
3224         dest->set_height(page_height / scale_factor_x);
3225       } else {
3226         dest->set_width(page_width / scale_factor_y);
3227       }
3228     }
3229   } else {
3230     // We are not scaling to bounds. Draw in the actual page size. If the
3231     // actual page size is larger than the bounds, the output will be
3232     // clipped.
3233     dest->set_width(page_width);
3234     dest->set_height(page_height);
3235   }
3236
3237   if (settings.center_in_bounds) {
3238     pp::Point offset((settings.bounds.width() - dest->width()) / 2,
3239                      (settings.bounds.height() - dest->height()) / 2);
3240     dest->Offset(offset);
3241   }
3242   return rotate;
3243 }
3244
3245 }  // namespace
3246
3247 #if defined(OS_WIN)
3248 bool PDFiumEngineExports::RenderPDFPageToDC(const void* pdf_buffer,
3249                                             int buffer_size,
3250                                             int page_number,
3251                                             const RenderingSettings& settings,
3252                                             HDC dc) {
3253   FPDF_DOCUMENT doc = FPDF_LoadMemDocument(pdf_buffer, buffer_size, NULL);
3254   if (!doc)
3255     return false;
3256   FPDF_PAGE page = FPDF_LoadPage(doc, page_number);
3257   if (!page) {
3258     FPDF_CloseDocument(doc);
3259     return false;
3260   }
3261   RenderingSettings new_settings = settings;
3262   // calculate the page size
3263   if (new_settings.dpi_x == -1)
3264     new_settings.dpi_x = GetDeviceCaps(dc, LOGPIXELSX);
3265   if (new_settings.dpi_y == -1)
3266     new_settings.dpi_y = GetDeviceCaps(dc, LOGPIXELSY);
3267
3268   pp::Rect dest;
3269   int rotate = CalculatePosition(page, new_settings, &dest);
3270
3271   int save_state = SaveDC(dc);
3272   // The caller wanted all drawing to happen within the bounds specified.
3273   // Based on scale calculations, our destination rect might be larger
3274   // than the bounds. Set the clip rect to the bounds.
3275   IntersectClipRect(dc, settings.bounds.x(), settings.bounds.y(),
3276                     settings.bounds.x() + settings.bounds.width(),
3277                     settings.bounds.y() + settings.bounds.height());
3278
3279   // A temporary hack. PDFs generated by Cairo (used by Chrome OS to generate
3280   // a PDF output from a webpage) result in very large metafiles and the
3281   // rendering using FPDF_RenderPage is incorrect. In this case, render as a
3282   // bitmap. Note that this code does not kick in for PDFs printed from Chrome
3283   // because in that case we create a temp PDF first before printing and this
3284   // temp PDF does not have a creator string that starts with "cairo".
3285   base::string16 creator;
3286   size_t buffer_bytes = FPDF_GetMetaText(doc, "Creator", NULL, 0);
3287   if (buffer_bytes > 1) {
3288     FPDF_GetMetaText(doc, "Creator", WriteInto(&creator, buffer_bytes),
3289                      buffer_bytes);
3290   }
3291   bool use_bitmap = false;
3292   if (StartsWith(creator, L"cairo", false))
3293     use_bitmap = true;
3294
3295   // Another temporary hack. Some PDFs seems to render very slowly if
3296   // FPDF_RenderPage is directly used on a printer DC. I suspect it is
3297   // because of the code to talk Postscript directly to the printer if
3298   // the printer supports this. Need to discuss this with PDFium. For now,
3299   // render to a bitmap and then blit the bitmap to the DC if we have been
3300   // supplied a printer DC.
3301   int device_type = GetDeviceCaps(dc, TECHNOLOGY);
3302   if (use_bitmap ||
3303       (device_type == DT_RASPRINTER) || (device_type == DT_PLOTTER)) {
3304     FPDF_BITMAP bitmap = FPDFBitmap_Create(dest.width(), dest.height(),
3305                                            FPDFBitmap_BGRx);
3306       // Clear the bitmap
3307     FPDFBitmap_FillRect(bitmap, 0, 0, dest.width(), dest.height(), 0xFFFFFFFF);
3308     FPDF_RenderPageBitmap(
3309         bitmap, page, 0, 0, dest.width(), dest.height(), rotate,
3310         FPDF_ANNOT | FPDF_PRINTING | FPDF_NO_CATCH);
3311     int stride = FPDFBitmap_GetStride(bitmap);
3312     BITMAPINFO bmi;
3313     memset(&bmi, 0, sizeof(bmi));
3314     bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
3315     bmi.bmiHeader.biWidth = dest.width();
3316     bmi.bmiHeader.biHeight = -dest.height();  // top-down image
3317     bmi.bmiHeader.biPlanes = 1;
3318     bmi.bmiHeader.biBitCount = 32;
3319     bmi.bmiHeader.biCompression = BI_RGB;
3320     bmi.bmiHeader.biSizeImage = stride * dest.height();
3321     StretchDIBits(dc, dest.x(), dest.y(), dest.width(), dest.height(),
3322                   0, 0, dest.width(), dest.height(),
3323                   FPDFBitmap_GetBuffer(bitmap), &bmi, DIB_RGB_COLORS, SRCCOPY);
3324     FPDFBitmap_Destroy(bitmap);
3325   } else {
3326     FPDF_RenderPage(dc, page, dest.x(), dest.y(), dest.width(), dest.height(),
3327                     rotate, FPDF_ANNOT | FPDF_PRINTING | FPDF_NO_CATCH);
3328   }
3329   RestoreDC(dc, save_state);
3330   FPDF_ClosePage(page);
3331   FPDF_CloseDocument(doc);
3332   return true;
3333 }
3334 #endif  // OS_WIN
3335
3336 bool PDFiumEngineExports::RenderPDFPageToBitmap(
3337     const void* pdf_buffer,
3338     int pdf_buffer_size,
3339     int page_number,
3340     const RenderingSettings& settings,
3341     void* bitmap_buffer) {
3342   FPDF_DOCUMENT doc = FPDF_LoadMemDocument(pdf_buffer, pdf_buffer_size, NULL);
3343   if (!doc)
3344     return false;
3345   FPDF_PAGE page = FPDF_LoadPage(doc, page_number);
3346   if (!page) {
3347     FPDF_CloseDocument(doc);
3348     return false;
3349   }
3350
3351   pp::Rect dest;
3352   int rotate = CalculatePosition(page, settings, &dest);
3353
3354   FPDF_BITMAP bitmap =
3355       FPDFBitmap_CreateEx(settings.bounds.width(), settings.bounds.height(),
3356                           FPDFBitmap_BGRA, bitmap_buffer,
3357                           settings.bounds.width() * 4);
3358   // Clear the bitmap
3359   FPDFBitmap_FillRect(bitmap, 0, 0, settings.bounds.width(),
3360                       settings.bounds.height(), 0xFFFFFFFF);
3361   // Shift top-left corner of bounds to (0, 0) if it's not there.
3362   dest.set_point(dest.point() - settings.bounds.point());
3363   FPDF_RenderPageBitmap(
3364       bitmap, page, dest.x(), dest.y(), dest.width(), dest.height(), rotate,
3365       FPDF_ANNOT | FPDF_PRINTING | FPDF_NO_CATCH);
3366   FPDFBitmap_Destroy(bitmap);
3367   FPDF_ClosePage(page);
3368   FPDF_CloseDocument(doc);
3369   return true;
3370 }
3371
3372 bool PDFiumEngineExports::GetPDFDocInfo(const void* pdf_buffer,
3373                                         int buffer_size,
3374                                         int* page_count,
3375                                         double* max_page_width) {
3376   FPDF_DOCUMENT doc = FPDF_LoadMemDocument(pdf_buffer, buffer_size, NULL);
3377   if (!doc)
3378     return false;
3379   int page_count_local = FPDF_GetPageCount(doc);
3380   if (page_count) {
3381     *page_count = page_count_local;
3382   }
3383   if (max_page_width) {
3384     *max_page_width = 0;
3385     for (int page_number = 0; page_number < page_count_local; page_number++) {
3386       double page_width = 0;
3387       double page_height = 0;
3388       FPDF_GetPageSizeByIndex(doc, page_number, &page_width, &page_height);
3389       if (page_width > *max_page_width) {
3390         *max_page_width = page_width;
3391       }
3392     }
3393   }
3394   FPDF_CloseDocument(doc);
3395   return true;
3396 }
3397
3398 bool PDFiumEngineExports::GetPDFPageSizeByIndex(
3399     const void* pdf_buffer,
3400     int pdf_buffer_size,
3401     int page_number,
3402     double* width,
3403     double* height) {
3404   FPDF_DOCUMENT doc = FPDF_LoadMemDocument(pdf_buffer, pdf_buffer_size, NULL);
3405   if (!doc)
3406     return false;
3407   bool success = FPDF_GetPageSizeByIndex(doc, page_number, width, height) != 0;
3408   FPDF_CloseDocument(doc);
3409   return success;
3410 }
3411
3412 }  // namespace chrome_pdf