Merge XFA to PDFium master at 4dc95e7 on 10/28/2014
[pdfium.git] / xfa_test / pdf / instance.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/instance.h"
6
7 #include <algorithm>  // for min()
8 #define _USE_MATH_DEFINES  // for M_PI
9 #include <cmath>      // for log() and pow()
10 #include <math.h>
11 #include <list>
12
13 #include "base/json/json_reader.h"
14 #include "base/json/json_writer.h"
15 #include "base/logging.h"
16 #include "base/strings/string_number_conversions.h"
17 #include "base/strings/string_split.h"
18 #include "base/strings/string_util.h"
19 #include "base/values.h"
20 #include "chrome/browser/chrome_page_zoom_constants.h"
21 #include "chrome/common/content_restriction.h"
22 #include "content/public/common/page_zoom.h"
23 #include "net/base/escape.h"
24 #include "pdf/draw_utils.h"
25 #include "pdf/number_image_generator.h"
26 #include "pdf/pdf.h"
27 #include "pdf/resource_consts.h"
28 #include "ppapi/c/dev/ppb_cursor_control_dev.h"
29 #include "ppapi/c/pp_errors.h"
30 #include "ppapi/c/pp_rect.h"
31 #include "ppapi/c/private/ppp_pdf.h"
32 #include "ppapi/c/trusted/ppb_url_loader_trusted.h"
33 #include "ppapi/cpp/core.h"
34 #include "ppapi/cpp/dev/font_dev.h"
35 #include "ppapi/cpp/dev/memory_dev.h"
36 #include "ppapi/cpp/dev/text_input_dev.h"
37 #include "ppapi/cpp/module.h"
38 #include "ppapi/cpp/point.h"
39 #include "ppapi/cpp/private/pdf.h"
40 #include "ppapi/cpp/rect.h"
41 #include "ppapi/cpp/resource.h"
42 #include "ppapi/cpp/url_request_info.h"
43 #include "ui/events/keycodes/keyboard_codes.h"
44
45 #if defined(OS_MACOSX)
46 #include "base/mac/mac_util.h"
47 #endif
48
49 namespace chrome_pdf {
50
51 struct ToolbarButtonInfo {
52   uint32 id;
53   Button::ButtonStyle style;
54   PP_ResourceImage normal;
55   PP_ResourceImage highlighted;
56   PP_ResourceImage pressed;
57 };
58
59 namespace {
60
61 // Uncomment following #define to enable thumbnails.
62 // #define ENABLE_THUMBNAILS
63
64 const uint32 kToolbarSplashTimeoutMs = 6000;
65 const uint32 kMessageTextColor = 0xFF575757;
66 const uint32 kMessageTextSize = 22;
67 const uint32 kProgressFadeTimeoutMs = 250;
68 const uint32 kProgressDelayTimeoutMs = 1000;
69 const uint32 kAutoScrollTimeoutMs = 50;
70 const double kAutoScrollFactor = 0.2;
71
72 // Javascript methods.
73 const char kJSAccessibility[] = "accessibility";
74 const char kJSDocumentLoadComplete[] = "documentLoadComplete";
75 const char kJSGetHeight[] = "getHeight";
76 const char kJSGetHorizontalScrollbarThickness[] =
77     "getHorizontalScrollbarThickness";
78 const char kJSGetPageLocationNormalized[] = "getPageLocationNormalized";
79 const char kJSGetSelectedText[] = "getSelectedText";
80 const char kJSGetVerticalScrollbarThickness[] = "getVerticalScrollbarThickness";
81 const char kJSGetWidth[] = "getWidth";
82 const char kJSGetZoomLevel[] = "getZoomLevel";
83 const char kJSGoToPage[] = "goToPage";
84 const char kJSGrayscale[] = "grayscale";
85 const char kJSLoadPreviewPage[] = "loadPreviewPage";
86 const char kJSOnLoad[] = "onload";
87 const char kJSOnPluginSizeChanged[] = "onPluginSizeChanged";
88 const char kJSOnScroll[] = "onScroll";
89 const char kJSPageXOffset[] = "pageXOffset";
90 const char kJSPageYOffset[] = "pageYOffset";
91 const char kJSPrintPreviewPageCount[] = "printPreviewPageCount";
92 const char kJSReload[] = "reload";
93 const char kJSRemovePrintButton[] = "removePrintButton";
94 const char kJSResetPrintPreviewUrl[] = "resetPrintPreviewUrl";
95 const char kJSSendKeyEvent[] = "sendKeyEvent";
96 const char kJSSetPageNumbers[] = "setPageNumbers";
97 const char kJSSetPageXOffset[] = "setPageXOffset";
98 const char kJSSetPageYOffset[] = "setPageYOffset";
99 const char kJSSetZoomLevel[] = "setZoomLevel";
100 const char kJSZoomFitToHeight[] = "fitToHeight";
101 const char kJSZoomFitToWidth[] = "fitToWidth";
102 const char kJSZoomIn[] = "zoomIn";
103 const char kJSZoomOut[] = "zoomOut";
104
105 // URL reference parameters.
106 // For more possible parameters, see RFC 3778 and the "PDF Open Parameters"
107 // document from Adobe.
108 const char kDelimiters[] = "#&";
109 const char kNamedDest[] = "nameddest";
110 const char kPage[] = "page";
111
112 const char kChromePrint[] = "chrome://print/";
113
114 // Dictionary Value key names for the document accessibility info
115 const char kAccessibleNumberOfPages[] = "numberOfPages";
116 const char kAccessibleLoaded[] = "loaded";
117 const char kAccessibleCopyable[] = "copyable";
118
119 const ToolbarButtonInfo kPDFToolbarButtons[] = {
120   { kFitToPageButtonId, Button::BUTTON_STATE,
121       PP_RESOURCEIMAGE_PDF_BUTTON_FTP,
122       PP_RESOURCEIMAGE_PDF_BUTTON_FTP_HOVER,
123       PP_RESOURCEIMAGE_PDF_BUTTON_FTP_PRESSED },
124   { kFitToWidthButtonId, Button::BUTTON_STATE,
125       PP_RESOURCEIMAGE_PDF_BUTTON_FTW,
126       PP_RESOURCEIMAGE_PDF_BUTTON_FTW_HOVER,
127       PP_RESOURCEIMAGE_PDF_BUTTON_FTW_PRESSED },
128   { kZoomOutButtonId, Button::BUTTON_CLICKABLE,
129       PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT,
130       PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_HOVER,
131       PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_PRESSED },
132   { kZoomInButtonId, Button::BUTTON_CLICKABLE,
133       PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN,
134       PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_HOVER,
135       PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_PRESSED },
136   { kSaveButtonId, Button::BUTTON_CLICKABLE,
137       PP_RESOURCEIMAGE_PDF_BUTTON_SAVE,
138       PP_RESOURCEIMAGE_PDF_BUTTON_SAVE_HOVER,
139       PP_RESOURCEIMAGE_PDF_BUTTON_SAVE_PRESSED },
140   { kPrintButtonId, Button::BUTTON_CLICKABLE,
141       PP_RESOURCEIMAGE_PDF_BUTTON_PRINT,
142       PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_HOVER,
143       PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_PRESSED },
144 };
145
146 const ToolbarButtonInfo kPDFNoPrintToolbarButtons[] = {
147   { kFitToPageButtonId, Button::BUTTON_STATE,
148       PP_RESOURCEIMAGE_PDF_BUTTON_FTP,
149       PP_RESOURCEIMAGE_PDF_BUTTON_FTP_HOVER,
150       PP_RESOURCEIMAGE_PDF_BUTTON_FTP_PRESSED },
151   { kFitToWidthButtonId, Button::BUTTON_STATE,
152       PP_RESOURCEIMAGE_PDF_BUTTON_FTW,
153       PP_RESOURCEIMAGE_PDF_BUTTON_FTW_HOVER,
154       PP_RESOURCEIMAGE_PDF_BUTTON_FTW_PRESSED },
155   { kZoomOutButtonId, Button::BUTTON_CLICKABLE,
156       PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT,
157       PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_HOVER,
158       PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_PRESSED },
159   { kZoomInButtonId, Button::BUTTON_CLICKABLE,
160       PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN,
161       PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_HOVER,
162       PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_PRESSED },
163   { kSaveButtonId, Button::BUTTON_CLICKABLE,
164       PP_RESOURCEIMAGE_PDF_BUTTON_SAVE,
165       PP_RESOURCEIMAGE_PDF_BUTTON_SAVE_HOVER,
166       PP_RESOURCEIMAGE_PDF_BUTTON_SAVE_PRESSED },
167   { kPrintButtonId, Button::BUTTON_CLICKABLE,
168       PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_DISABLED,
169       PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_DISABLED,
170       PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_DISABLED }
171 };
172
173 const ToolbarButtonInfo kPrintPreviewToolbarButtons[] = {
174   { kFitToPageButtonId, Button::BUTTON_STATE,
175       PP_RESOURCEIMAGE_PDF_BUTTON_FTP,
176       PP_RESOURCEIMAGE_PDF_BUTTON_FTP_HOVER,
177       PP_RESOURCEIMAGE_PDF_BUTTON_FTP_PRESSED },
178   { kFitToWidthButtonId, Button::BUTTON_STATE,
179       PP_RESOURCEIMAGE_PDF_BUTTON_FTW,
180       PP_RESOURCEIMAGE_PDF_BUTTON_FTW_HOVER,
181       PP_RESOURCEIMAGE_PDF_BUTTON_FTW_PRESSED },
182   { kZoomOutButtonId, Button::BUTTON_CLICKABLE,
183       PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT,
184       PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_HOVER,
185       PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_PRESSED },
186   { kZoomInButtonId, Button::BUTTON_CLICKABLE,
187       PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_END,
188       PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_END_HOVER,
189       PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_END_PRESSED },
190 };
191
192 static const char kPPPPdfInterface[] = PPP_PDF_INTERFACE_1;
193
194 PP_Var GetLinkAtPosition(PP_Instance instance, PP_Point point) {
195   pp::Var var;
196   void* object =
197       pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
198   if (object)
199     var = static_cast<Instance*>(object)->GetLinkAtPosition(pp::Point(point));
200   return var.Detach();
201 }
202
203 void Transform(PP_Instance instance, PP_PrivatePageTransformType type) {
204   void* object =
205       pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
206   if (object) {
207     Instance* obj_instance = static_cast<Instance*>(object);
208     switch (type) {
209       case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CW:
210         obj_instance->RotateClockwise();
211         break;
212       case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CCW:
213         obj_instance->RotateCounterclockwise();
214         break;
215     }
216   }
217 }
218
219 const PPP_Pdf ppp_private = {
220   &GetLinkAtPosition,
221   &Transform
222 };
223
224 int ExtractPrintPreviewPageIndex(const std::string& src_url) {
225   // Sample |src_url| format: chrome://print/id/page_index/print.pdf
226   std::vector<std::string> url_substr;
227   base::SplitString(src_url.substr(strlen(kChromePrint)), '/', &url_substr);
228   if (url_substr.size() != 3)
229     return -1;
230
231   if (url_substr[2] != "print.pdf")
232     return -1;
233
234   int page_index = 0;
235   if (!base::StringToInt(url_substr[1], &page_index))
236     return -1;
237   return page_index;
238 }
239
240 bool IsPrintPreviewUrl(const std::string& url) {
241   return url.substr(0, strlen(kChromePrint)) == kChromePrint;
242 }
243
244 void ScalePoint(float scale, pp::Point* point) {
245   point->set_x(static_cast<int>(point->x() * scale));
246   point->set_y(static_cast<int>(point->y() * scale));
247 }
248
249 void ScaleRect(float scale, pp::Rect* rect) {
250   int left = static_cast<int>(floorf(rect->x() * scale));
251   int top = static_cast<int>(floorf(rect->y() * scale));
252   int right = static_cast<int>(ceilf((rect->x() + rect->width()) * scale));
253   int bottom = static_cast<int>(ceilf((rect->y() + rect->height()) * scale));
254   rect->SetRect(left, top, right - left, bottom - top);
255 }
256
257 template<class T>
258 T ClipToRange(T value, T lower_boundary, T upper_boundary) {
259   DCHECK(lower_boundary <= upper_boundary);
260   return std::max<T>(lower_boundary, std::min<T>(value, upper_boundary));
261 }
262
263 }  // namespace
264
265 Instance::Instance(PP_Instance instance)
266     : pp::InstancePrivate(instance),
267       pp::Find_Private(this),
268       pp::Printing_Dev(this),
269       pp::Selection_Dev(this),
270       pp::WidgetClient_Dev(this),
271       pp::Zoom_Dev(this),
272       cursor_(PP_CURSORTYPE_POINTER),
273       timer_pending_(false),
274       current_timer_id_(0),
275       zoom_(1.0),
276       device_scale_(1.0),
277       printing_enabled_(true),
278       hidpi_enabled_(false),
279       full_(IsFullFrame()),
280       zoom_mode_(full_ ? ZOOM_AUTO : ZOOM_SCALE),
281       did_call_start_loading_(false),
282       is_autoscroll_(false),
283       scrollbar_thickness_(-1),
284       scrollbar_reserved_thickness_(-1),
285       current_tb_info_(NULL),
286       current_tb_info_size_(0),
287       paint_manager_(this, this, true),
288       delayed_progress_timer_id_(0),
289       first_paint_(true),
290       painted_first_page_(false),
291       show_page_indicator_(false),
292       document_load_state_(LOAD_STATE_LOADING),
293       preview_document_load_state_(LOAD_STATE_COMPLETE),
294       told_browser_about_unsupported_feature_(false),
295       print_preview_page_count_(0) {
296   loader_factory_.Initialize(this);
297   timer_factory_.Initialize(this);
298   form_factory_.Initialize(this);
299   callback_factory_.Initialize(this);
300   engine_.reset(PDFEngine::Create(this));
301   pp::Module::Get()->AddPluginInterface(kPPPPdfInterface, &ppp_private);
302   AddPerInstanceObject(kPPPPdfInterface, this);
303
304   RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_MOUSE);
305   RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_WHEEL);
306   RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_KEYBOARD);
307   RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_TOUCH);
308 }
309
310 Instance::~Instance() {
311   if (timer_pending_) {
312     timer_factory_.CancelAll();
313     timer_pending_ = false;
314   }
315   // The engine may try to access this instance during its destruction.
316   // Make sure this happens early while the instance is still intact.
317   engine_.reset();
318   RemovePerInstanceObject(kPPPPdfInterface, this);
319 }
320
321 bool Instance::Init(uint32_t argc, const char* argn[], const char* argv[]) {
322   // For now, we hide HiDPI support behind a flag.
323   if (pp::PDF::IsFeatureEnabled(this, PP_PDFFEATURE_HIDPI))
324     hidpi_enabled_ = true;
325
326   printing_enabled_ = pp::PDF::IsFeatureEnabled(this, PP_PDFFEATURE_PRINTING);
327   if (printing_enabled_) {
328     CreateToolbar(kPDFToolbarButtons, arraysize(kPDFToolbarButtons));
329   } else {
330     CreateToolbar(kPDFNoPrintToolbarButtons,
331                   arraysize(kPDFNoPrintToolbarButtons));
332   }
333
334   CreateProgressBar();
335
336   // Load autoscroll anchor image.
337   autoscroll_anchor_ =
338       CreateResourceImage(PP_RESOURCEIMAGE_PDF_PAN_SCROLL_ICON);
339
340 #ifdef ENABLE_THUMBNAILS
341   CreateThumbnails();
342 #endif
343   const char* url = NULL;
344   for (uint32_t i = 0; i < argc; ++i) {
345     if (strcmp(argn[i], "src") == 0) {
346       url = argv[i];
347       break;
348     }
349   }
350
351   if (!url)
352     return false;
353
354   CreatePageIndicator(IsPrintPreviewUrl(url));
355
356   if (!full_) {
357     // For PDFs embedded in a frame, we don't get the data automatically like we
358     // do for full-frame loads.  Start loading the data manually.
359     LoadUrl(url);
360   } else {
361     DCHECK(!did_call_start_loading_);
362     pp::PDF::DidStartLoading(this);
363     did_call_start_loading_ = true;
364   }
365
366   ZoomLimitsChanged(kMinZoom, kMaxZoom);
367
368   text_input_.reset(new pp::TextInput_Dev(this));
369
370   url_ = url;
371   return engine_->New(url);
372 }
373
374 bool Instance::HandleDocumentLoad(const pp::URLLoader& loader) {
375   delayed_progress_timer_id_ = ScheduleTimer(kProgressBarId,
376                                              kProgressDelayTimeoutMs);
377   return engine_->HandleDocumentLoad(loader);
378 }
379
380 bool Instance::HandleInputEvent(const pp::InputEvent& event) {
381   // To simplify things, convert the event into device coordinates if it is
382   // a mouse event.
383   pp::InputEvent event_device_res(event);
384   {
385     pp::MouseInputEvent mouse_event(event);
386     if (!mouse_event.is_null()) {
387       pp::Point point = mouse_event.GetPosition();
388       pp::Point movement = mouse_event.GetMovement();
389       ScalePoint(device_scale_, &point);
390       ScalePoint(device_scale_, &movement);
391       mouse_event = pp::MouseInputEvent(
392           this,
393           event.GetType(),
394           event.GetTimeStamp(),
395           event.GetModifiers(),
396           mouse_event.GetButton(),
397           point,
398           mouse_event.GetClickCount(),
399           movement);
400       event_device_res = mouse_event;
401     }
402   }
403
404   // Check if we need to go to autoscroll mode.
405   if (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE &&
406      (event.GetModifiers() & PP_INPUTEVENT_MODIFIER_MIDDLEBUTTONDOWN)) {
407     pp::MouseInputEvent mouse_event(event_device_res);
408     pp::Point pos = mouse_event.GetPosition();
409     EnableAutoscroll(pos);
410     UpdateCursor(CalculateAutoscroll(pos));
411     return true;
412   } else {
413     // Quit autoscrolling on any other event.
414     DisableAutoscroll();
415   }
416
417 #ifdef ENABLE_THUMBNAILS
418   if (event.GetType() == PP_INPUTEVENT_TYPE_MOUSELEAVE)
419     thumbnails_.SlideOut();
420
421   if (thumbnails_.HandleEvent(event_device_res))
422     return true;
423 #endif
424
425   if (toolbar_->HandleEvent(event_device_res))
426     return true;
427
428 #ifdef ENABLE_THUMBNAILS
429   if (v_scrollbar_.get() && event.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE) {
430     pp::MouseInputEvent mouse_event(event);
431     pp::Point pt = mouse_event.GetPosition();
432     pp::Rect v_scrollbar_rc;
433     v_scrollbar_->GetLocation(&v_scrollbar_rc);
434     // There is a bug (https://bugs.webkit.org/show_bug.cgi?id=45208)
435     // in the webkit that makes event.u.mouse.button
436     // equal to PP_INPUTEVENT_MOUSEBUTTON_LEFT, even when no button is pressed.
437     // To work around this issue we use modifier for now, and will switch
438     // to button once the bug is fixed and webkit got merged back to our tree.
439     if (v_scrollbar_rc.Contains(pt) &&
440         (event.GetModifiers() & PP_INPUTEVENT_MODIFIER_LEFTBUTTONDOWN)) {
441       thumbnails_.SlideIn();
442     }
443
444     // When scrollbar is in the scrolling mode we should display thumbnails
445     // even the mouse is outside the thumbnail and scrollbar areas.
446     // If mouse is outside plugin area, we are still getting mouse move events
447     // while scrolling. See bug description for details:
448     // http://code.google.com/p/chromium/issues/detail?id=56444
449     if (!v_scrollbar_rc.Contains(pt) && thumbnails_.visible() &&
450         !(event.GetModifiers() & PP_INPUTEVENT_MODIFIER_LEFTBUTTONDOWN) &&
451         !thumbnails_.rect().Contains(pt)) {
452       thumbnails_.SlideOut();
453     }
454   }
455 #endif
456
457   // Need to pass the event to the engine first, since if we're over an edit
458   // control we want it to get keyboard events (like space) instead of the
459   // scrollbar.
460   // TODO: will have to offset the mouse coordinates once we support bidi and
461   // there could be scrollbars on the left.
462   pp::InputEvent offset_event(event_device_res);
463   bool try_engine_first = true;
464   switch (offset_event.GetType()) {
465     case PP_INPUTEVENT_TYPE_MOUSEDOWN:
466     case PP_INPUTEVENT_TYPE_MOUSEUP:
467     case PP_INPUTEVENT_TYPE_MOUSEMOVE:
468     case PP_INPUTEVENT_TYPE_MOUSEENTER:
469     case PP_INPUTEVENT_TYPE_MOUSELEAVE: {
470       pp::MouseInputEvent mouse_event(event_device_res);
471       pp::MouseInputEvent mouse_event_dip(event);
472       pp::Point point = mouse_event.GetPosition();
473       point.set_x(point.x() - available_area_.x());
474       offset_event = pp::MouseInputEvent(
475           this,
476           event.GetType(),
477           event.GetTimeStamp(),
478           event.GetModifiers(),
479           mouse_event.GetButton(),
480           point,
481           mouse_event.GetClickCount(),
482           mouse_event.GetMovement());
483       if (!engine_->IsSelecting()) {
484         if (!IsOverlayScrollbar() &&
485             !available_area_.Contains(mouse_event.GetPosition())) {
486           try_engine_first = false;
487         } else if (IsOverlayScrollbar()) {
488           pp::Rect temp;
489           if ((v_scrollbar_.get() && v_scrollbar_->GetLocation(&temp) &&
490               temp.Contains(mouse_event_dip.GetPosition())) ||
491               (h_scrollbar_.get() && h_scrollbar_->GetLocation(&temp) &&
492               temp.Contains(mouse_event_dip.GetPosition()))) {
493             try_engine_first = false;
494           }
495         }
496       }
497       break;
498     }
499     default:
500       break;
501   }
502   if (try_engine_first && engine_->HandleEvent(offset_event))
503     return true;
504
505   // Left/Right arrows should scroll to the beginning of the Prev/Next page if
506   // there is no horizontal scroll bar.
507   // If fit-to-height, PgDown/PgUp should scroll to the beginning of the
508   // Prev/Next page. Spacebar / shift+spacebar should do the same.
509   if (v_scrollbar_.get() && event.GetType() == PP_INPUTEVENT_TYPE_KEYDOWN) {
510     pp::KeyboardInputEvent keyboard_event(event);
511     bool no_h_scrollbar = !h_scrollbar_.get();
512     uint32_t key_code = keyboard_event.GetKeyCode();
513     bool page_down = no_h_scrollbar && key_code == ui::VKEY_RIGHT;
514     bool page_up = no_h_scrollbar && key_code == ui::VKEY_LEFT;
515     if (zoom_mode_ == ZOOM_FIT_TO_PAGE) {
516       bool has_shift =
517           keyboard_event.GetModifiers() & PP_INPUTEVENT_MODIFIER_SHIFTKEY;
518       bool key_is_space = key_code == ui::VKEY_SPACE;
519       page_down |= key_is_space || key_code == ui::VKEY_NEXT;
520       page_up |= (key_is_space && has_shift) || (key_code == ui::VKEY_PRIOR);
521     }
522     if (page_down) {
523       int page = engine_->GetFirstVisiblePage();
524       if (page == -1)
525         return true;
526       // Engine calculates visible page including delimiter to the page size.
527       // We need to check here if the page itself is completely out of view and
528       // scroll to the next one in that case.
529       if (engine_->GetPageRect(page).bottom() * zoom_ <=
530           v_scrollbar_->GetValue())
531         page++;
532       ScrollToPage(page + 1);
533       UpdateCursor(PP_CURSORTYPE_POINTER);
534       return true;
535     } else if (page_up) {
536       int page = engine_->GetFirstVisiblePage();
537       if (page == -1)
538         return true;
539       if (engine_->GetPageRect(page).y() * zoom_ >= v_scrollbar_->GetValue())
540         page--;
541       ScrollToPage(page);
542       UpdateCursor(PP_CURSORTYPE_POINTER);
543       return true;
544     }
545   }
546
547   if (v_scrollbar_.get() && v_scrollbar_->HandleEvent(event)) {
548     UpdateCursor(PP_CURSORTYPE_POINTER);
549     return true;
550   }
551
552   if (h_scrollbar_.get() && h_scrollbar_->HandleEvent(event)) {
553     UpdateCursor(PP_CURSORTYPE_POINTER);
554     return true;
555   }
556
557   if (timer_pending_ &&
558       (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEUP ||
559        event.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE)) {
560     timer_factory_.CancelAll();
561     timer_pending_ = false;
562   } else if (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE &&
563              engine_->IsSelecting()) {
564     bool set_timer = false;
565     pp::MouseInputEvent mouse_event(event);
566     if (v_scrollbar_.get() &&
567         (mouse_event.GetPosition().y() <= 0 ||
568          mouse_event.GetPosition().y() >= (plugin_dip_size_.height() - 1))) {
569       v_scrollbar_->ScrollBy(
570           PP_SCROLLBY_LINE, mouse_event.GetPosition().y() >= 0 ? 1: -1);
571       set_timer = true;
572     }
573     if (h_scrollbar_.get() &&
574         (mouse_event.GetPosition().x() <= 0 ||
575          mouse_event.GetPosition().x() >= (plugin_dip_size_.width() - 1))) {
576       h_scrollbar_->ScrollBy(PP_SCROLLBY_LINE,
577           mouse_event.GetPosition().x() >= 0 ? 1: -1);
578       set_timer = true;
579     }
580
581     if (set_timer) {
582       last_mouse_event_ = pp::MouseInputEvent(event);
583
584       pp::CompletionCallback callback =
585           timer_factory_.NewCallback(&Instance::OnTimerFired);
586       pp::Module::Get()->core()->CallOnMainThread(kDragTimerMs, callback);
587       timer_pending_ = true;
588     }
589   }
590
591   if (event.GetType() == PP_INPUTEVENT_TYPE_KEYDOWN) {
592     pp::KeyboardInputEvent keyboard_event(event);
593     const uint32 modifier = event.GetModifiers();
594     if (modifier & kDefaultKeyModifier) {
595       switch (keyboard_event.GetKeyCode()) {
596         case 'A':
597           engine_->SelectAll();
598           return true;
599       }
600     } else if (modifier & PP_INPUTEVENT_MODIFIER_CONTROLKEY) {
601       switch (keyboard_event.GetKeyCode()) {
602         case ui::VKEY_OEM_4:
603           // Left bracket.
604           engine_->RotateCounterclockwise();
605           return true;
606         case ui::VKEY_OEM_6:
607           // Right bracket.
608           engine_->RotateClockwise();
609           return true;
610       }
611     }
612   }
613
614   // Return true for unhandled clicks so the plugin takes focus.
615   return (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN);
616 }
617
618 void Instance::DidChangeView(const pp::View& view) {
619   pp::Rect view_rect(view.GetRect());
620   float device_scale = 1.0f;
621   float old_device_scale = device_scale_;
622   if (hidpi_enabled_)
623     device_scale = view.GetDeviceScale();
624   pp::Size view_device_size(view_rect.width() * device_scale,
625                             view_rect.height() * device_scale);
626   if (view_device_size == plugin_size_ && device_scale == device_scale_)
627     return;  // We don't care about the position, only the size.
628
629   image_data_ = pp::ImageData();
630   device_scale_ = device_scale;
631   plugin_dip_size_ = view_rect.size();
632   plugin_size_ = view_device_size;
633
634   paint_manager_.SetSize(view_device_size, device_scale_);
635
636   image_data_ = pp::ImageData(this,
637                               PP_IMAGEDATAFORMAT_BGRA_PREMUL,
638                               plugin_size_,
639                               false);
640   if (image_data_.is_null()) {
641     DCHECK(plugin_size_.IsEmpty());
642     return;
643   }
644
645   // View dimensions changed, disable autoscroll (if it was enabled).
646   DisableAutoscroll();
647
648   OnGeometryChanged(zoom_, old_device_scale);
649 }
650
651 pp::Var Instance::GetInstanceObject() {
652   if (instance_object_.is_undefined()) {
653     PDFScriptableObject* object = new PDFScriptableObject(this);
654     // The pp::Var takes ownership of object here.
655     instance_object_ = pp::VarPrivate(this, object);
656   }
657
658   return instance_object_;
659 }
660
661 pp::Var Instance::GetLinkAtPosition(const pp::Point& point) {
662   pp::Point offset_point(point);
663   ScalePoint(device_scale_, &offset_point);
664   offset_point.set_x(offset_point.x() - available_area_.x());
665   return engine_->GetLinkAtPosition(offset_point);
666 }
667
668 pp::Var Instance::GetSelectedText(bool html) {
669   if (html || !engine_->HasPermission(PDFEngine::PERMISSION_COPY))
670     return pp::Var();
671   return engine_->GetSelectedText();
672 }
673
674 void Instance::InvalidateWidget(pp::Widget_Dev widget,
675                                 const pp::Rect& dirty_rect) {
676   if (v_scrollbar_.get() && *v_scrollbar_ == widget) {
677     if (!image_data_.is_null())
678       v_scrollbar_->Paint(dirty_rect.pp_rect(), &image_data_);
679   } else if (h_scrollbar_.get() && *h_scrollbar_ == widget) {
680     if (!image_data_.is_null())
681       h_scrollbar_->Paint(dirty_rect.pp_rect(), &image_data_);
682   } else {
683     // Possible to hit this condition since sometimes the scrollbar codes posts
684     // a task to do something later, and we could have deleted our reference in
685     // the meantime.
686     return;
687   }
688
689   pp::Rect dirty_rect_scaled = dirty_rect;
690   ScaleRect(device_scale_, &dirty_rect_scaled);
691   paint_manager_.InvalidateRect(dirty_rect_scaled);
692 }
693
694 void Instance::ScrollbarValueChanged(pp::Scrollbar_Dev scrollbar,
695                                      uint32_t value) {
696   value = GetScaled(value);
697   if (v_scrollbar_.get() && *v_scrollbar_ == scrollbar) {
698     engine_->ScrolledToYPosition(value);
699     pp::Rect rc;
700     v_scrollbar_->GetLocation(&rc);
701     int32 doc_height = GetDocumentPixelHeight();
702     doc_height -= GetScaled(rc.height());
703 #ifdef ENABLE_THUMBNAILS
704     if (thumbnails_.visible()) {
705       thumbnails_.SetPosition(value, doc_height, true);
706     }
707 #endif
708     pp::Point origin(
709         plugin_size_.width() - page_indicator_.rect().width() -
710             GetScaled(GetScrollbarReservedThickness()),
711         page_indicator_.GetYPosition(value, doc_height, plugin_size_.height()));
712     page_indicator_.MoveTo(origin, page_indicator_.visible());
713   } else if (h_scrollbar_.get() && *h_scrollbar_ == scrollbar) {
714     engine_->ScrolledToXPosition(value);
715   }
716 }
717
718 void Instance::ScrollbarOverlayChanged(pp::Scrollbar_Dev scrollbar,
719                                        bool overlay) {
720   scrollbar_reserved_thickness_ = overlay ? 0 : scrollbar_thickness_;
721   OnGeometryChanged(zoom_, device_scale_);
722 }
723
724 uint32_t Instance::QuerySupportedPrintOutputFormats() {
725   return engine_->QuerySupportedPrintOutputFormats();
726 }
727
728 int32_t Instance::PrintBegin(const PP_PrintSettings_Dev& print_settings) {
729   // For us num_pages is always equal to the number of pages in the PDF
730   // document irrespective of the printable area.
731   int32_t ret = engine_->GetNumberOfPages();
732   if (!ret)
733     return 0;
734
735   uint32_t supported_formats = engine_->QuerySupportedPrintOutputFormats();
736   if ((print_settings.format & supported_formats) == 0)
737     return 0;
738
739   print_settings_.is_printing = true;
740   print_settings_.pepper_print_settings = print_settings;
741   engine_->PrintBegin();
742   return ret;
743 }
744
745 pp::Resource Instance::PrintPages(
746     const PP_PrintPageNumberRange_Dev* page_ranges,
747     uint32_t page_range_count) {
748   if (!print_settings_.is_printing)
749     return pp::Resource();
750
751   print_settings_.print_pages_called_ = true;
752   return engine_->PrintPages(page_ranges, page_range_count,
753                              print_settings_.pepper_print_settings);
754 }
755
756 void Instance::PrintEnd() {
757   if (print_settings_.print_pages_called_)
758     UserMetricsRecordAction("PDF.PrintPage");
759   print_settings_.Clear();
760   engine_->PrintEnd();
761 }
762
763 bool Instance::IsPrintScalingDisabled() {
764   return !engine_->GetPrintScaling();
765 }
766
767 bool Instance::StartFind(const std::string& text, bool case_sensitive) {
768   engine_->StartFind(text.c_str(), case_sensitive);
769   return true;
770 }
771
772 void Instance::SelectFindResult(bool forward) {
773   engine_->SelectFindResult(forward);
774 }
775
776 void Instance::StopFind() {
777   engine_->StopFind();
778 }
779
780 void Instance::Zoom(double scale, bool text_only) {
781   UserMetricsRecordAction("PDF.ZoomFromBrowser");
782
783   // If the zoom level doesn't change it means that this zoom change might have
784   // been initiated by the plugin. In that case, we don't want to change the
785   // zoom mode to ZOOM_SCALE as it may have been intentionally set to
786   // ZOOM_FIT_TO_PAGE or some other value when the zoom was last changed.
787   if (scale == zoom_)
788     return;
789
790   SetZoom(ZOOM_SCALE, scale);
791 }
792
793 void Instance::ZoomChanged(double factor) {
794   if (full_)
795     Zoom_Dev::ZoomChanged(factor);
796 }
797
798 void Instance::OnPaint(const std::vector<pp::Rect>& paint_rects,
799                        std::vector<PaintManager::ReadyRect>* ready,
800                        std::vector<pp::Rect>* pending) {
801   if (image_data_.is_null()) {
802     DCHECK(plugin_size_.IsEmpty());
803     return;
804   }
805   if (first_paint_) {
806     first_paint_ = false;
807     pp::Rect rect = pp::Rect(pp::Point(), plugin_size_);
808     FillRect(rect, kBackgroundColor);
809     ready->push_back(PaintManager::ReadyRect(rect, image_data_, true));
810     *pending = paint_rects;
811     return;
812   }
813
814   engine_->PrePaint();
815
816   for (size_t i = 0; i < paint_rects.size(); i++) {
817     // Intersect with plugin area since there could be pending invalidates from
818     // when the plugin area was larger.
819     pp::Rect rect =
820         paint_rects[i].Intersect(pp::Rect(pp::Point(), plugin_size_));
821     if (rect.IsEmpty())
822       continue;
823
824     pp::Rect pdf_rect = available_area_.Intersect(rect);
825     if (!pdf_rect.IsEmpty()) {
826       pdf_rect.Offset(available_area_.x() * -1, 0);
827
828       std::vector<pp::Rect> pdf_ready;
829       std::vector<pp::Rect> pdf_pending;
830       engine_->Paint(pdf_rect, &image_data_, &pdf_ready, &pdf_pending);
831       for (size_t j = 0; j < pdf_ready.size(); ++j) {
832         pdf_ready[j].Offset(available_area_.point());
833         ready->push_back(
834             PaintManager::ReadyRect(pdf_ready[j], image_data_, false));
835       }
836       for (size_t j = 0; j < pdf_pending.size(); ++j) {
837         pdf_pending[j].Offset(available_area_.point());
838         pending->push_back(pdf_pending[j]);
839       }
840     }
841
842     for (size_t j = 0; j < background_parts_.size(); ++j) {
843       pp::Rect intersection = background_parts_[j].location.Intersect(rect);
844       if (!intersection.IsEmpty()) {
845         FillRect(intersection, background_parts_[j].color);
846         ready->push_back(
847             PaintManager::ReadyRect(intersection, image_data_, false));
848       }
849     }
850
851     if (document_load_state_ == LOAD_STATE_FAILED) {
852       pp::Point top_center;
853       top_center.set_x(plugin_size_.width() / 2);
854       top_center.set_y(plugin_size_.height() / 2);
855       DrawText(top_center, PP_RESOURCESTRING_PDFLOAD_FAILED);
856     }
857
858 #ifdef ENABLE_THUMBNAILS
859     thumbnails_.Paint(&image_data_, rect);
860 #endif
861   }
862
863   engine_->PostPaint();
864
865   // Must paint scrollbars after the background parts, in case we have an
866   // overlay scrollbar that's over the background. We also do this in a separate
867   // loop because the scrollbar painting logic uses the signal of whether there
868   // are pending paints or not to figure out if it should draw right away or
869   // not.
870   for (size_t i = 0; i < paint_rects.size(); i++) {
871     PaintIfWidgetIntersects(h_scrollbar_.get(), paint_rects[i], ready, pending);
872     PaintIfWidgetIntersects(v_scrollbar_.get(), paint_rects[i], ready, pending);
873   }
874
875   if (progress_bar_.visible())
876     PaintOverlayControl(&progress_bar_, &image_data_, ready);
877
878   if (page_indicator_.visible())
879     PaintOverlayControl(&page_indicator_, &image_data_, ready);
880
881   if (toolbar_->current_transparency() != kTransparentAlpha)
882     PaintOverlayControl(toolbar_.get(), &image_data_, ready);
883
884   // Paint autoscroll anchor if needed.
885   if (is_autoscroll_) {
886     size_t limit = ready->size();
887     for (size_t i = 0; i < limit; i++) {
888       pp::Rect anchor_rect = autoscroll_rect_.Intersect((*ready)[i].rect);
889       if (!anchor_rect.IsEmpty()) {
890         pp::Rect draw_rc = pp::Rect(
891             pp::Point(anchor_rect.x() - autoscroll_rect_.x(),
892                       anchor_rect.y() - autoscroll_rect_.y()),
893             anchor_rect.size());
894         // Paint autoscroll anchor.
895         AlphaBlend(autoscroll_anchor_, draw_rc,
896                    &image_data_, anchor_rect.point(), kOpaqueAlpha);
897       }
898     }
899   }
900 }
901
902 void Instance::PaintOverlayControl(
903     Control* ctrl,
904     pp::ImageData* image_data,
905     std::vector<PaintManager::ReadyRect>* ready) {
906   // Make sure that we only paint overlay controls over an area that's ready,
907   // i.e. not pending.  Otherwise we'll mark the control rect as ready and
908   // it'll overwrite the pdf region.
909   std::list<pp::Rect> ctrl_rects;
910   for (size_t i = 0; i < ready->size(); i++) {
911     pp::Rect rc = ctrl->rect().Intersect((*ready)[i].rect);
912     if (!rc.IsEmpty())
913       ctrl_rects.push_back(rc);
914   }
915
916   if (!ctrl_rects.empty()) {
917     ctrl->PaintMultipleRects(image_data, ctrl_rects);
918
919     std::list<pp::Rect>::iterator iter;
920     for (iter = ctrl_rects.begin(); iter != ctrl_rects.end(); ++iter) {
921       ready->push_back(PaintManager::ReadyRect(*iter, *image_data, false));
922     }
923   }
924 }
925
926 void Instance::DidOpen(int32_t result) {
927   if (result == PP_OK) {
928     engine_->HandleDocumentLoad(embed_loader_);
929   } else if (result != PP_ERROR_ABORTED) {  // Can happen in tests.
930     NOTREACHED();
931   }
932 }
933
934 void Instance::DidOpenPreview(int32_t result) {
935   if (result == PP_OK) {
936     preview_engine_.reset(PDFEngine::Create(new PreviewModeClient(this)));
937     preview_engine_->HandleDocumentLoad(embed_preview_loader_);
938   } else {
939     NOTREACHED();
940   }
941 }
942
943 void Instance::PaintIfWidgetIntersects(
944     pp::Widget_Dev* widget,
945     const pp::Rect& rect,
946     std::vector<PaintManager::ReadyRect>* ready,
947     std::vector<pp::Rect>* pending) {
948   if (!widget)
949     return;
950
951   pp::Rect location;
952   if (!widget->GetLocation(&location))
953     return;
954
955   ScaleRect(device_scale_, &location);
956   location = location.Intersect(rect);
957   if (location.IsEmpty())
958     return;
959
960   if (IsOverlayScrollbar()) {
961     // If we're using overlay scrollbars, and there are pending paints under the
962     // scrollbar, don't update the scrollbar instantly. While it would be nice,
963     // we would need to double buffer the plugin area in order to make this
964     // work. This is because we'd need to always have a copy of what the pdf
965     // under the scrollbar looks like, and additionally we couldn't paint the
966     // pdf under the scrollbar if it's ready until we got the preceding flush.
967     // So in practice, it would make painting slower and introduce extra buffer
968     // copies for the general case.
969     for (size_t i = 0; i < pending->size(); ++i) {
970       if ((*pending)[i].Intersects(location))
971         return;
972     }
973
974     // Even if none of the pending paints are under the scrollbar, we never want
975     // to paint it if it's over the pdf if there are other pending paints.
976     // Otherwise different parts of the pdf plugin would display at different
977     // scroll offsets.
978     if (!pending->empty() && available_area_.Intersects(rect)) {
979       pending->push_back(location);
980       return;
981     }
982   }
983
984   pp::Rect location_dip = location;
985   ScaleRect(1.0f / device_scale_, &location_dip);
986
987   DCHECK(!image_data_.is_null());
988   widget->Paint(location_dip, &image_data_);
989
990   ready->push_back(PaintManager::ReadyRect(location, image_data_, true));
991 }
992
993 void Instance::OnTimerFired(int32_t) {
994   HandleInputEvent(last_mouse_event_);
995 }
996
997 void Instance::OnClientTimerFired(int32_t id) {
998   engine_->OnCallback(id);
999 }
1000
1001 void Instance::OnControlTimerFired(int32_t,
1002                                    const uint32& control_id,
1003                                    const uint32& timer_id) {
1004   if (control_id == toolbar_->id()) {
1005     toolbar_->OnTimerFired(timer_id);
1006   } else if (control_id == progress_bar_.id()) {
1007     if (timer_id == delayed_progress_timer_id_) {
1008       if (document_load_state_ == LOAD_STATE_LOADING &&
1009           !progress_bar_.visible()) {
1010         progress_bar_.Fade(true, kProgressFadeTimeoutMs);
1011       }
1012       delayed_progress_timer_id_ = 0;
1013     } else {
1014       progress_bar_.OnTimerFired(timer_id);
1015     }
1016   } else if (control_id == kAutoScrollId) {
1017     if (is_autoscroll_) {
1018       if (autoscroll_x_ != 0 && h_scrollbar_.get()) {
1019         h_scrollbar_->ScrollBy(PP_SCROLLBY_PIXEL, autoscroll_x_);
1020       }
1021       if (autoscroll_y_ != 0 && v_scrollbar_.get()) {
1022         v_scrollbar_->ScrollBy(PP_SCROLLBY_PIXEL, autoscroll_y_);
1023       }
1024
1025       // Reschedule timer.
1026       ScheduleTimer(kAutoScrollId, kAutoScrollTimeoutMs);
1027     }
1028   } else if (control_id == kPageIndicatorId) {
1029     page_indicator_.OnTimerFired(timer_id);
1030   }
1031 #ifdef ENABLE_THUMBNAILS
1032   else if (control_id == thumbnails_.id()) {
1033     thumbnails_.OnTimerFired(timer_id);
1034   }
1035 #endif
1036 }
1037
1038 void Instance::CalculateBackgroundParts() {
1039   background_parts_.clear();
1040   int v_scrollbar_thickness =
1041       GetScaled(v_scrollbar_.get() ? GetScrollbarReservedThickness() : 0);
1042   int h_scrollbar_thickness =
1043       GetScaled(h_scrollbar_.get() ? GetScrollbarReservedThickness() : 0);
1044   int width_without_scrollbar = std::max(
1045       plugin_size_.width() - v_scrollbar_thickness, 0);
1046   int height_without_scrollbar = std::max(
1047       plugin_size_.height() - h_scrollbar_thickness, 0);
1048   int left_width = available_area_.x();
1049   int right_start = available_area_.right();
1050   int right_width = abs(width_without_scrollbar - available_area_.right());
1051   int bottom = std::min(available_area_.bottom(), height_without_scrollbar);
1052
1053   // Add the left, right, and bottom rectangles.  Note: we assume only
1054   // horizontal centering.
1055   BackgroundPart part = {
1056     pp::Rect(0, 0, left_width, bottom),
1057     kBackgroundColor
1058   };
1059   if (!part.location.IsEmpty())
1060     background_parts_.push_back(part);
1061   part.location = pp::Rect(right_start, 0, right_width, bottom);
1062   if (!part.location.IsEmpty())
1063     background_parts_.push_back(part);
1064   part.location = pp::Rect(
1065       0, bottom, width_without_scrollbar, height_without_scrollbar - bottom);
1066   if (!part.location.IsEmpty())
1067     background_parts_.push_back(part);
1068
1069   if (h_scrollbar_thickness
1070 #if defined(OS_MACOSX)
1071       ||
1072 #else
1073       &&
1074 #endif
1075       v_scrollbar_thickness) {
1076     part.color = 0xFFFFFFFF;
1077     part.location = pp::Rect(plugin_size_.width() - v_scrollbar_thickness,
1078                              plugin_size_.height() - h_scrollbar_thickness,
1079                              h_scrollbar_thickness,
1080                              v_scrollbar_thickness);
1081     background_parts_.push_back(part);
1082   }
1083 }
1084
1085 int Instance::GetDocumentPixelWidth() const {
1086   return static_cast<int>(ceil(document_size_.width() * zoom_ * device_scale_));
1087 }
1088
1089 int Instance::GetDocumentPixelHeight() const {
1090   return static_cast<int>(ceil(document_size_.height() *
1091                                zoom_ *
1092                                device_scale_));
1093 }
1094
1095 void Instance::FillRect(const pp::Rect& rect, uint32 color) {
1096   DCHECK(!image_data_.is_null() || rect.IsEmpty());
1097   uint32* buffer_start = static_cast<uint32*>(image_data_.data());
1098   int stride = image_data_.stride();
1099   uint32* ptr = buffer_start + rect.y() * stride / 4 + rect.x();
1100   int height = rect.height();
1101   int width = rect.width();
1102   for (int y = 0; y < height; ++y) {
1103     for (int x = 0; x < width; ++x)
1104       *(ptr + x) = color;
1105     ptr += stride / 4;
1106   }
1107 }
1108
1109 void Instance::DocumentSizeUpdated(const pp::Size& size) {
1110   document_size_ = size;
1111
1112   OnGeometryChanged(zoom_, device_scale_);
1113 }
1114
1115 void Instance::Invalidate(const pp::Rect& rect) {
1116   pp::Rect offset_rect(rect);
1117   offset_rect.Offset(available_area_.point());
1118   paint_manager_.InvalidateRect(offset_rect);
1119 }
1120
1121 void Instance::Scroll(const pp::Point& point) {
1122   pp::Rect scroll_area = available_area_;
1123   if (IsOverlayScrollbar()) {
1124     pp::Rect rc;
1125     if (h_scrollbar_.get()) {
1126       h_scrollbar_->GetLocation(&rc);
1127       ScaleRect(device_scale_, &rc);
1128       if (scroll_area.bottom() > rc.y()) {
1129         scroll_area.set_height(rc.y() - scroll_area.y());
1130         paint_manager_.InvalidateRect(rc);
1131       }
1132     }
1133     if (v_scrollbar_.get()) {
1134       v_scrollbar_->GetLocation(&rc);
1135       ScaleRect(device_scale_, &rc);
1136       if (scroll_area.right() > rc.x()) {
1137         scroll_area.set_width(rc.x() - scroll_area.x());
1138         paint_manager_.InvalidateRect(rc);
1139       }
1140     }
1141   }
1142   paint_manager_.ScrollRect(scroll_area, point);
1143
1144   if (toolbar_->current_transparency() != kTransparentAlpha)
1145     paint_manager_.InvalidateRect(toolbar_->GetControlsRect());
1146
1147   if (progress_bar_.visible())
1148     paint_manager_.InvalidateRect(progress_bar_.rect());
1149
1150   if (is_autoscroll_)
1151     paint_manager_.InvalidateRect(autoscroll_rect_);
1152
1153   if (show_page_indicator_) {
1154     page_indicator_.set_current_page(GetPageNumberToDisplay());
1155     page_indicator_.Splash();
1156   }
1157
1158   if (page_indicator_.visible())
1159     paint_manager_.InvalidateRect(page_indicator_.rect());
1160
1161   // Run the scroll callback asynchronously. This function can be invoked by a
1162   // layout change which should not re-enter into JS synchronously.
1163   pp::CompletionCallback callback =
1164       callback_factory_.NewCallback(&Instance::RunCallback,
1165                                     on_scroll_callback_);
1166   pp::Module::Get()->core()->CallOnMainThread(0, callback);
1167 }
1168
1169 void Instance::ScrollToX(int position) {
1170   if (!h_scrollbar_.get()) {
1171     NOTREACHED();
1172     return;
1173   }
1174   int position_dip = static_cast<int>(position / device_scale_);
1175   h_scrollbar_->SetValue(position_dip);
1176 }
1177
1178 void Instance::ScrollToY(int position) {
1179   if (!v_scrollbar_.get()) {
1180     NOTREACHED();
1181     return;
1182   }
1183   int position_dip = static_cast<int>(position / device_scale_);
1184   v_scrollbar_->SetValue(ClipToRange(position_dip, 0, valid_v_range_));
1185 }
1186
1187 void Instance::ScrollToPage(int page) {
1188   if (!v_scrollbar_.get())
1189     return;
1190
1191   if (engine_->GetNumberOfPages() == 0)
1192     return;
1193
1194   int index = ClipToRange(page, 0, engine_->GetNumberOfPages() - 1);
1195   pp::Rect rect = engine_->GetPageRect(index);
1196   // If we are trying to scroll pass the last page,
1197   // scroll to the end of the last page.
1198   int position = index < page ? rect.bottom() : rect.y();
1199   ScrollToY(position * zoom_ * device_scale_);
1200 }
1201
1202 void Instance::NavigateTo(const std::string& url, bool open_in_new_tab) {
1203   std::string url_copy(url);
1204
1205   // Empty |url_copy| is ok, and will effectively be a reload.
1206   // Skip the code below so an empty URL does not turn into "http://", which
1207   // will cause GURL to fail a DCHECK.
1208   if (!url_copy.empty()) {
1209     // If |url_copy| starts with '#', then it's for the same URL with a
1210     // different URL fragment.
1211     if (url_copy[0] == '#') {
1212       url_copy = url_ + url_copy;
1213       // Changing the href does not actually do anything when navigating in the
1214       // same tab, so do the actual page scroll here. Then fall through so the
1215       // href gets updated.
1216       if (!open_in_new_tab) {
1217         int page_number = GetInitialPage(url_copy);
1218         if (page_number >= 0)
1219           ScrollToPage(page_number);
1220       }
1221     }
1222     // If there's no scheme, add http.
1223     if (url_copy.find("://") == std::string::npos &&
1224         url_copy.find("mailto:") == std::string::npos) {
1225       url_copy = "http://" + url_copy;
1226     }
1227     // Make sure |url_copy| starts with a valid scheme.
1228     if (url_copy.find("http://") != 0 &&
1229         url_copy.find("https://") != 0 &&
1230         url_copy.find("ftp://") != 0 &&
1231         url_copy.find("file://") != 0 &&
1232         url_copy.find("mailto:") != 0) {
1233       return;
1234     }
1235     // Make sure |url_copy| is not only a scheme.
1236     if (url_copy == "http://" ||
1237         url_copy == "https://" ||
1238         url_copy == "ftp://" ||
1239         url_copy == "file://" ||
1240         url_copy == "mailto:") {
1241       return;
1242     }
1243   }
1244   if (open_in_new_tab) {
1245     GetWindowObject().Call("open", url_copy);
1246   } else {
1247     GetWindowObject().GetProperty("top").GetProperty("location").
1248         SetProperty("href", url_copy);
1249   }
1250 }
1251
1252 void Instance::UpdateCursor(PP_CursorType_Dev cursor) {
1253   if (cursor == cursor_)
1254     return;
1255   cursor_ = cursor;
1256
1257   const PPB_CursorControl_Dev* cursor_interface =
1258       reinterpret_cast<const PPB_CursorControl_Dev*>(
1259       pp::Module::Get()->GetBrowserInterface(PPB_CURSOR_CONTROL_DEV_INTERFACE));
1260   if (!cursor_interface) {
1261     NOTREACHED();
1262     return;
1263   }
1264
1265   cursor_interface->SetCursor(
1266       pp_instance(), cursor_, pp::ImageData().pp_resource(), NULL);
1267 }
1268
1269 void Instance::UpdateTickMarks(const std::vector<pp::Rect>& tickmarks) {
1270   if (!v_scrollbar_.get())
1271     return;
1272
1273   float inverse_scale = 1.0f / device_scale_;
1274   std::vector<pp::Rect> scaled_tickmarks = tickmarks;
1275   for (size_t i = 0; i < scaled_tickmarks.size(); i++) {
1276     ScaleRect(inverse_scale, &scaled_tickmarks[i]);
1277   }
1278
1279   v_scrollbar_->SetTickMarks(
1280       scaled_tickmarks.empty() ? NULL : &scaled_tickmarks[0], tickmarks.size());
1281 }
1282
1283 void Instance::NotifyNumberOfFindResultsChanged(int total, bool final_result) {
1284   NumberOfFindResultsChanged(total, final_result);
1285 }
1286
1287 void Instance::NotifySelectedFindResultChanged(int current_find_index) {
1288   SelectedFindResultChanged(current_find_index);
1289 }
1290
1291 void Instance::OnEvent(uint32 control_id, uint32 event_id, void* data) {
1292   if (event_id == Button::EVENT_ID_BUTTON_CLICKED ||
1293       event_id == Button::EVENT_ID_BUTTON_STATE_CHANGED) {
1294     switch (control_id) {
1295       case kFitToPageButtonId:
1296         UserMetricsRecordAction("PDF.FitToPageButton");
1297         SetZoom(ZOOM_FIT_TO_PAGE, 0);
1298         ZoomChanged(zoom_);
1299         break;
1300       case kFitToWidthButtonId:
1301         UserMetricsRecordAction("PDF.FitToWidthButton");
1302         SetZoom(ZOOM_FIT_TO_WIDTH, 0);
1303         ZoomChanged(zoom_);
1304         break;
1305       case kZoomOutButtonId:
1306       case kZoomInButtonId:
1307         UserMetricsRecordAction(control_id == kZoomOutButtonId ?
1308             "PDF.ZoomOutButton" : "PDF.ZoomInButton");
1309         SetZoom(ZOOM_SCALE, CalculateZoom(control_id));
1310         ZoomChanged(zoom_);
1311         break;
1312       case kSaveButtonId:
1313         UserMetricsRecordAction("PDF.SaveButton");
1314         SaveAs();
1315         break;
1316       case kPrintButtonId:
1317         UserMetricsRecordAction("PDF.PrintButton");
1318         Print();
1319         break;
1320     }
1321   }
1322   if (control_id == kThumbnailsId &&
1323       event_id == ThumbnailControl::EVENT_ID_THUMBNAIL_SELECTED) {
1324     int page = *static_cast<int*>(data);
1325     pp::Rect page_rc(engine_->GetPageRect(page));
1326     ScrollToY(static_cast<int>(page_rc.y() * zoom_ * device_scale_));
1327   }
1328 }
1329
1330 void Instance::Invalidate(uint32 control_id, const pp::Rect& rc) {
1331   paint_manager_.InvalidateRect(rc);
1332 }
1333
1334 uint32 Instance::ScheduleTimer(uint32 control_id, uint32 timeout_ms) {
1335   current_timer_id_++;
1336   pp::CompletionCallback callback =
1337       timer_factory_.NewCallback(&Instance::OnControlTimerFired,
1338                                  control_id,
1339                                  current_timer_id_);
1340   pp::Module::Get()->core()->CallOnMainThread(timeout_ms, callback);
1341   return current_timer_id_;
1342 }
1343
1344 void Instance::SetEventCapture(uint32 control_id, bool set_capture) {
1345   // TODO(gene): set event capture here.
1346 }
1347
1348 void Instance::SetCursor(uint32 control_id, PP_CursorType_Dev cursor_type) {
1349   UpdateCursor(cursor_type);
1350 }
1351
1352 pp::Instance* Instance::GetInstance() {
1353   return this;
1354 }
1355
1356 void Instance::GetDocumentPassword(
1357     pp::CompletionCallbackWithOutput<pp::Var> callback) {
1358   std::string message(GetLocalizedString(PP_RESOURCESTRING_PDFGETPASSWORD));
1359   pp::Var result = pp::PDF::ModalPromptForPassword(this, message);
1360   *callback.output() = result.pp_var();
1361   callback.Run(PP_OK);
1362 }
1363
1364 void Instance::Alert(const std::string& message) {
1365   GetWindowObject().Call("alert", message);
1366 }
1367
1368 bool Instance::Confirm(const std::string& message) {
1369   pp::Var result = GetWindowObject().Call("confirm", message);
1370   return result.is_bool() ? result.AsBool() : false;
1371 }
1372
1373 std::string Instance::Prompt(const std::string& question,
1374                              const std::string& default_answer) {
1375   pp::Var result = GetWindowObject().Call("prompt", question, default_answer);
1376   return result.is_string() ? result.AsString() : std::string();
1377 }
1378
1379 std::string Instance::GetURL() {
1380   return url_;
1381 }
1382
1383 void Instance::Email(const std::string& to,
1384                      const std::string& cc,
1385                      const std::string& bcc,
1386                      const std::string& subject,
1387                      const std::string& body) {
1388   std::string javascript =
1389       "var href = 'mailto:" + net::EscapeUrlEncodedData(to, false) +
1390       "?cc=" + net::EscapeUrlEncodedData(cc, false) +
1391       "&bcc=" + net::EscapeUrlEncodedData(bcc, false) +
1392       "&subject=" + net::EscapeUrlEncodedData(subject, false) +
1393       "&body=" + net::EscapeUrlEncodedData(body, false) +
1394       "';var temp = window.open(href, '_blank', " +
1395       "'width=1,height=1');if(temp) temp.close();";
1396   ExecuteScript(javascript);
1397 }
1398
1399 void Instance::Print() {
1400   if (!printing_enabled_ ||
1401       (!engine_->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY) &&
1402        !engine_->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY))) {
1403     return;
1404   }
1405
1406   pp::CompletionCallback callback =
1407       callback_factory_.NewCallback(&Instance::OnPrint);
1408   pp::Module::Get()->core()->CallOnMainThread(0, callback);
1409 }
1410
1411 void Instance::OnPrint(int32_t) {
1412   pp::PDF::Print(this);
1413 }
1414
1415 void Instance::SaveAs() {
1416   pp::PDF::SaveAs(this);
1417 }
1418
1419 void Instance::SubmitForm(const std::string& url,
1420                           const void* data,
1421                           int length) {
1422   pp::URLRequestInfo request(this);
1423   request.SetURL(url);
1424   request.SetMethod("POST");
1425   request.AppendDataToBody(reinterpret_cast<const char*>(data), length);
1426
1427   pp::CompletionCallback callback =
1428       form_factory_.NewCallback(&Instance::FormDidOpen);
1429   form_loader_ = CreateURLLoaderInternal();
1430   int rv = form_loader_.Open(request, callback);
1431   if (rv != PP_OK_COMPLETIONPENDING)
1432     callback.Run(rv);
1433 }
1434
1435 void Instance::FormDidOpen(int32_t result) {
1436   // TODO: inform the user of success/failure.
1437   if (result != PP_OK) {
1438     NOTREACHED();
1439   }
1440 }
1441
1442 std::string Instance::ShowFileSelectionDialog() {
1443   // Seems like very low priority to implement, since the pdf has no way to get
1444   // the file data anyways.  Javascript doesn't let you do this synchronously.
1445   NOTREACHED();
1446   return std::string();
1447 }
1448
1449 pp::URLLoader Instance::CreateURLLoader() {
1450   if (full_) {
1451     if (!did_call_start_loading_) {
1452       did_call_start_loading_ = true;
1453       pp::PDF::DidStartLoading(this);
1454     }
1455
1456     // Disable save and print until the document is fully loaded, since they
1457     // would generate an incomplete document.  Need to do this each time we
1458     // call DidStartLoading since that resets the content restrictions.
1459     pp::PDF::SetContentRestriction(this, CONTENT_RESTRICTION_SAVE |
1460                                    CONTENT_RESTRICTION_PRINT);
1461   }
1462
1463   return CreateURLLoaderInternal();
1464 }
1465
1466 void Instance::ScheduleCallback(int id, int delay_in_ms) {
1467   pp::CompletionCallback callback =
1468       timer_factory_.NewCallback(&Instance::OnClientTimerFired);
1469   pp::Module::Get()->core()->CallOnMainThread(delay_in_ms, callback, id);
1470 }
1471
1472 void Instance::SearchString(const base::char16* string,
1473                             const base::char16* term,
1474                             bool case_sensitive,
1475                             std::vector<SearchStringResult>* results) {
1476   if (!pp::PDF::IsAvailable()) {
1477     NOTREACHED();
1478     return;
1479   }
1480
1481   PP_PrivateFindResult* pp_results;
1482   int count = 0;
1483   pp::PDF::SearchString(
1484       this,
1485       reinterpret_cast<const unsigned short*>(string),
1486       reinterpret_cast<const unsigned short*>(term),
1487       case_sensitive,
1488       &pp_results,
1489       &count);
1490
1491   results->resize(count);
1492   for (int i = 0; i < count; ++i) {
1493     (*results)[i].start_index = pp_results[i].start_index;
1494     (*results)[i].length = pp_results[i].length;
1495   }
1496
1497   pp::Memory_Dev memory;
1498   memory.MemFree(pp_results);
1499 }
1500
1501 void Instance::DocumentPaintOccurred() {
1502   if (painted_first_page_)
1503     return;
1504
1505   painted_first_page_ = true;
1506   UpdateToolbarPosition(false);
1507   toolbar_->Splash(kToolbarSplashTimeoutMs);
1508
1509   if (engine_->GetNumberOfPages() > 1)
1510     show_page_indicator_ = true;
1511   else
1512     show_page_indicator_ = false;
1513
1514   if (v_scrollbar_.get() && show_page_indicator_) {
1515     page_indicator_.set_current_page(GetPageNumberToDisplay());
1516     page_indicator_.Splash(kToolbarSplashTimeoutMs,
1517                            kPageIndicatorInitialFadeTimeoutMs);
1518   }
1519 }
1520
1521 void Instance::DocumentLoadComplete(int page_count) {
1522   // Clear focus state for OSK.
1523   FormTextFieldFocusChange(false);
1524
1525   // Update progress control.
1526   if (progress_bar_.visible())
1527     progress_bar_.Fade(false, kProgressFadeTimeoutMs);
1528
1529   DCHECK(document_load_state_ == LOAD_STATE_LOADING);
1530   document_load_state_ = LOAD_STATE_COMPLETE;
1531   UserMetricsRecordAction("PDF.LoadSuccess");
1532
1533   if (did_call_start_loading_) {
1534     pp::PDF::DidStopLoading(this);
1535     did_call_start_loading_ = false;
1536   }
1537
1538   if (on_load_callback_.is_string())
1539     ExecuteScript(on_load_callback_);
1540   // Note: If we are in print preview mode on_load_callback_ might call
1541   // ScrollTo{X|Y}() and we don't want to scroll again and override it.
1542   // #page=N is not supported in Print Preview.
1543   if (!IsPrintPreview()) {
1544     int initial_page = GetInitialPage(url_);
1545     if (initial_page >= 0)
1546       ScrollToPage(initial_page);
1547   }
1548
1549   if (!full_)
1550     return;
1551   if (!pp::PDF::IsAvailable())
1552     return;
1553
1554   int content_restrictions =
1555       CONTENT_RESTRICTION_CUT | CONTENT_RESTRICTION_PASTE;
1556   if (!engine_->HasPermission(PDFEngine::PERMISSION_COPY))
1557     content_restrictions |= CONTENT_RESTRICTION_COPY;
1558
1559   if (!engine_->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY) &&
1560       !engine_->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY)) {
1561     printing_enabled_ = false;
1562     if (current_tb_info_ == kPDFToolbarButtons) {
1563       // Remove Print button.
1564       CreateToolbar(kPDFNoPrintToolbarButtons,
1565                     arraysize(kPDFNoPrintToolbarButtons));
1566       UpdateToolbarPosition(false);
1567       Invalidate(pp::Rect(plugin_size_));
1568     }
1569   }
1570
1571   pp::PDF::SetContentRestriction(this, content_restrictions);
1572
1573   pp::PDF::HistogramPDFPageCount(this, page_count);
1574 }
1575
1576 void Instance::RotateClockwise() {
1577   engine_->RotateClockwise();
1578 }
1579
1580 void Instance::RotateCounterclockwise() {
1581   engine_->RotateCounterclockwise();
1582 }
1583
1584 void Instance::PreviewDocumentLoadComplete() {
1585   if (preview_document_load_state_ != LOAD_STATE_LOADING ||
1586       preview_pages_info_.empty()) {
1587     return;
1588   }
1589
1590   preview_document_load_state_ = LOAD_STATE_COMPLETE;
1591
1592   int dest_page_index = preview_pages_info_.front().second;
1593   int src_page_index =
1594       ExtractPrintPreviewPageIndex(preview_pages_info_.front().first);
1595   if (src_page_index > 0 &&  dest_page_index > -1 && preview_engine_.get())
1596     engine_->AppendPage(preview_engine_.get(), dest_page_index);
1597
1598   preview_pages_info_.pop();
1599   // |print_preview_page_count_| is not updated yet. Do not load any
1600   // other preview pages till we get this information.
1601   if (print_preview_page_count_ == 0)
1602     return;
1603
1604   if (preview_pages_info_.size())
1605     LoadAvailablePreviewPage();
1606 }
1607
1608 void Instance::DocumentLoadFailed() {
1609   DCHECK(document_load_state_ == LOAD_STATE_LOADING);
1610   UserMetricsRecordAction("PDF.LoadFailure");
1611
1612   // Hide progress control.
1613   progress_bar_.Fade(false, kProgressFadeTimeoutMs);
1614
1615   if (did_call_start_loading_) {
1616     pp::PDF::DidStopLoading(this);
1617     did_call_start_loading_ = false;
1618   }
1619
1620   document_load_state_ = LOAD_STATE_FAILED;
1621   paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
1622 }
1623
1624 void Instance::PreviewDocumentLoadFailed() {
1625   UserMetricsRecordAction("PDF.PreviewDocumentLoadFailure");
1626   if (preview_document_load_state_ != LOAD_STATE_LOADING ||
1627       preview_pages_info_.empty()) {
1628     return;
1629   }
1630
1631   preview_document_load_state_ = LOAD_STATE_FAILED;
1632   preview_pages_info_.pop();
1633
1634   if (preview_pages_info_.size())
1635     LoadAvailablePreviewPage();
1636 }
1637
1638 pp::Instance* Instance::GetPluginInstance() {
1639   return GetInstance();
1640 }
1641
1642 void Instance::DocumentHasUnsupportedFeature(const std::string& feature) {
1643   std::string metric("PDF_Unsupported_");
1644   metric += feature;
1645   if (!unsupported_features_reported_.count(metric)) {
1646     unsupported_features_reported_.insert(metric);
1647     UserMetricsRecordAction(metric);
1648   }
1649
1650   // Since we use an info bar, only do this for full frame plugins..
1651   if (!full_)
1652     return;
1653
1654   if (told_browser_about_unsupported_feature_)
1655     return;
1656   told_browser_about_unsupported_feature_ = true;
1657
1658   pp::PDF::HasUnsupportedFeature(this);
1659 }
1660
1661 void Instance::DocumentLoadProgress(uint32 available, uint32 doc_size) {
1662   double progress = 0.0;
1663   if (doc_size == 0) {
1664     // Document size is unknown. Use heuristics.
1665     // We'll make progress logarithmic from 0 to 100M.
1666     static const double kFactor = log(100000000.0) / 100.0;
1667     if (available > 0) {
1668       progress = log(static_cast<double>(available)) / kFactor;
1669       if (progress > 100.0)
1670         progress = 100.0;
1671     }
1672   } else {
1673     progress = 100.0 * static_cast<double>(available) / doc_size;
1674   }
1675   progress_bar_.SetProgress(progress);
1676 }
1677
1678 void Instance::FormTextFieldFocusChange(bool in_focus) {
1679   if (!text_input_.get())
1680     return;
1681   if (in_focus)
1682     text_input_->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_TEXT);
1683   else
1684     text_input_->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_NONE);
1685 }
1686
1687 // Called by PDFScriptableObject.
1688 bool Instance::HasScriptableMethod(const pp::Var& method, pp::Var* exception) {
1689   std::string method_str = method.AsString();
1690   return (method_str == kJSAccessibility ||
1691           method_str == kJSDocumentLoadComplete ||
1692           method_str == kJSGetHeight ||
1693           method_str == kJSGetHorizontalScrollbarThickness ||
1694           method_str == kJSGetPageLocationNormalized ||
1695           method_str == kJSGetSelectedText ||
1696           method_str == kJSGetVerticalScrollbarThickness ||
1697           method_str == kJSGetWidth ||
1698           method_str == kJSGetZoomLevel ||
1699           method_str == kJSGoToPage ||
1700           method_str == kJSGrayscale ||
1701           method_str == kJSLoadPreviewPage ||
1702           method_str == kJSOnLoad ||
1703           method_str == kJSOnPluginSizeChanged ||
1704           method_str == kJSOnScroll ||
1705           method_str == kJSPageXOffset ||
1706           method_str == kJSPageYOffset ||
1707           method_str == kJSPrintPreviewPageCount ||
1708           method_str == kJSReload ||
1709           method_str == kJSRemovePrintButton ||
1710           method_str == kJSResetPrintPreviewUrl ||
1711           method_str == kJSSendKeyEvent ||
1712           method_str == kJSSetPageNumbers ||
1713           method_str == kJSSetPageXOffset ||
1714           method_str == kJSSetPageYOffset ||
1715           method_str == kJSSetZoomLevel ||
1716           method_str == kJSZoomFitToHeight ||
1717           method_str == kJSZoomFitToWidth ||
1718           method_str == kJSZoomIn ||
1719           method_str == kJSZoomOut);
1720 }
1721
1722 pp::Var Instance::CallScriptableMethod(const pp::Var& method,
1723                                        const std::vector<pp::Var>& args,
1724                                        pp::Var* exception) {
1725   std::string method_str = method.AsString();
1726   if (method_str == kJSGrayscale) {
1727     if (args.size() == 1 && args[0].is_bool()) {
1728       engine_->SetGrayscale(args[0].AsBool());
1729       // Redraw
1730       paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
1731 #ifdef ENABLE_THUMBNAILS
1732       if (thumbnails_.visible())
1733         thumbnails_.Show(true, true);
1734 #endif
1735       return pp::Var(true);
1736     }
1737     return pp::Var(false);
1738   }
1739   if (method_str == kJSOnLoad) {
1740     if (args.size() == 1 && args[0].is_string()) {
1741       on_load_callback_ = args[0];
1742       return pp::Var(true);
1743     }
1744     return pp::Var(false);
1745   }
1746   if (method_str == kJSOnScroll) {
1747     if (args.size() == 1 && args[0].is_string()) {
1748       on_scroll_callback_ = args[0];
1749       return pp::Var(true);
1750     }
1751     return pp::Var(false);
1752   }
1753   if (method_str == kJSOnPluginSizeChanged) {
1754     if (args.size() == 1 && args[0].is_string()) {
1755       on_plugin_size_changed_callback_ = args[0];
1756       return pp::Var(true);
1757     }
1758     return pp::Var(false);
1759   }
1760   if (method_str == kJSReload) {
1761     document_load_state_ = LOAD_STATE_LOADING;
1762     if (!full_)
1763       LoadUrl(url_);
1764     preview_engine_.reset();
1765     print_preview_page_count_ = 0;
1766     engine_.reset(PDFEngine::Create(this));
1767     engine_->New(url_.c_str());
1768 #ifdef ENABLE_THUMBNAILS
1769     thumbnails_.ResetEngine(engine_.get());
1770 #endif
1771     return pp::Var();
1772   }
1773   if (method_str == kJSResetPrintPreviewUrl) {
1774     if (args.size() == 1 && args[0].is_string()) {
1775       url_ = args[0].AsString();
1776       preview_pages_info_ = std::queue<PreviewPageInfo>();
1777       preview_document_load_state_ = LOAD_STATE_COMPLETE;
1778     }
1779     return pp::Var();
1780   }
1781   if (method_str == kJSZoomFitToHeight) {
1782     SetZoom(ZOOM_FIT_TO_PAGE, 0);
1783     return pp::Var();
1784   }
1785   if (method_str == kJSZoomFitToWidth) {
1786     SetZoom(ZOOM_FIT_TO_WIDTH, 0);
1787     return pp::Var();
1788   }
1789   if (method_str == kJSZoomIn) {
1790     SetZoom(ZOOM_SCALE, CalculateZoom(kZoomInButtonId));
1791     return pp::Var();
1792   }
1793   if (method_str == kJSZoomOut) {
1794     SetZoom(ZOOM_SCALE, CalculateZoom(kZoomOutButtonId));
1795     return pp::Var();
1796   }
1797   if (method_str == kJSSetZoomLevel) {
1798     if (args.size() == 1 && args[0].is_number())
1799       SetZoom(ZOOM_SCALE, args[0].AsDouble());
1800     return pp::Var();
1801   }
1802   if (method_str == kJSGetZoomLevel) {
1803     return pp::Var(zoom_);
1804   }
1805   if (method_str == kJSGetHeight) {
1806     return pp::Var(plugin_size_.height());
1807   }
1808   if (method_str == kJSGetWidth) {
1809     return pp::Var(plugin_size_.width());
1810   }
1811   if (method_str == kJSGetHorizontalScrollbarThickness) {
1812     return pp::Var(
1813           h_scrollbar_.get() ? GetScrollbarReservedThickness() : 0);
1814   }
1815   if (method_str == kJSGetVerticalScrollbarThickness) {
1816     return pp::Var(
1817           v_scrollbar_.get() ? GetScrollbarReservedThickness() : 0);
1818   }
1819   if (method_str == kJSGetSelectedText) {
1820     return GetSelectedText(false);
1821   }
1822   if (method_str == kJSDocumentLoadComplete) {
1823     return pp::Var((document_load_state_ != LOAD_STATE_LOADING));
1824   }
1825   if (method_str == kJSPageYOffset) {
1826     return pp::Var(static_cast<int32_t>(
1827         v_scrollbar_.get() ? v_scrollbar_->GetValue() : 0));
1828   }
1829   if (method_str == kJSSetPageYOffset) {
1830     if (args.size() == 1 && args[0].is_number() && v_scrollbar_.get())
1831       ScrollToY(GetScaled(args[0].AsInt()));
1832     return pp::Var();
1833   }
1834   if (method_str == kJSPageXOffset) {
1835     return pp::Var(static_cast<int32_t>(
1836         h_scrollbar_.get() ? h_scrollbar_->GetValue() : 0));
1837   }
1838   if (method_str == kJSSetPageXOffset) {
1839     if (args.size() == 1 && args[0].is_number() && h_scrollbar_.get())
1840       ScrollToX(GetScaled(args[0].AsInt()));
1841     return pp::Var();
1842   }
1843   if (method_str == kJSRemovePrintButton) {
1844     CreateToolbar(kPrintPreviewToolbarButtons,
1845                   arraysize(kPrintPreviewToolbarButtons));
1846     UpdateToolbarPosition(false);
1847     Invalidate(pp::Rect(plugin_size_));
1848     return pp::Var();
1849   }
1850   if (method_str == kJSGoToPage) {
1851     if (args.size() == 1 && args[0].is_string()) {
1852       ScrollToPage(atoi(args[0].AsString().c_str()));
1853     }
1854     return pp::Var();
1855   }
1856   if (method_str == kJSAccessibility) {
1857     if (args.size() == 0) {
1858       base::DictionaryValue node;
1859       node.SetInteger(kAccessibleNumberOfPages, engine_->GetNumberOfPages());
1860       node.SetBoolean(kAccessibleLoaded,
1861                       document_load_state_ != LOAD_STATE_LOADING);
1862       bool has_permissions =
1863           engine_->HasPermission(PDFEngine::PERMISSION_COPY) ||
1864           engine_->HasPermission(PDFEngine::PERMISSION_COPY_ACCESSIBLE);
1865       node.SetBoolean(kAccessibleCopyable, has_permissions);
1866       std::string json;
1867       base::JSONWriter::Write(&node, &json);
1868       return pp::Var(json);
1869     } else if (args[0].is_number()) {
1870       return pp::Var(engine_->GetPageAsJSON(args[0].AsInt()));
1871     }
1872   }
1873   if (method_str == kJSPrintPreviewPageCount) {
1874     if (args.size() == 1 && args[0].is_number())
1875       SetPrintPreviewMode(args[0].AsInt());
1876     return pp::Var();
1877   }
1878   if (method_str == kJSLoadPreviewPage) {
1879     if (args.size() == 2 && args[0].is_string() && args[1].is_number())
1880       ProcessPreviewPageInfo(args[0].AsString(), args[1].AsInt());
1881     return pp::Var();
1882   }
1883   if (method_str == kJSGetPageLocationNormalized) {
1884     const size_t kMaxLength = 30;
1885     char location_info[kMaxLength];
1886     int page_idx = engine_->GetMostVisiblePage();
1887     if (page_idx < 0)
1888       return pp::Var(std::string());
1889     pp::Rect rect = engine_->GetPageContentsRect(page_idx);
1890     int v_scrollbar_reserved_thickness =
1891         v_scrollbar_.get() ? GetScaled(GetScrollbarReservedThickness()) : 0;
1892
1893     rect.set_x(rect.x() + ((plugin_size_.width() -
1894         v_scrollbar_reserved_thickness - available_area_.width()) / 2));
1895     base::snprintf(location_info,
1896                    kMaxLength,
1897                    "%0.4f;%0.4f;%0.4f;%0.4f;",
1898                    rect.x() / static_cast<float>(plugin_size_.width()),
1899                    rect.y() / static_cast<float>(plugin_size_.height()),
1900                    rect.width() / static_cast<float>(plugin_size_.width()),
1901                    rect.height()/ static_cast<float>(plugin_size_.height()));
1902     return pp::Var(std::string(location_info));
1903   }
1904   if (method_str == kJSSetPageNumbers) {
1905     if (args.size() != 1 || !args[0].is_string())
1906       return pp::Var();
1907     const int num_pages_signed = engine_->GetNumberOfPages();
1908     if (num_pages_signed <= 0)
1909       return pp::Var();
1910     scoped_ptr<base::ListValue> page_ranges(static_cast<base::ListValue*>(
1911         base::JSONReader::Read(args[0].AsString(), false)));
1912     const size_t num_pages = static_cast<size_t>(num_pages_signed);
1913     if (!page_ranges.get() || page_ranges->GetSize() != num_pages)
1914       return pp::Var();
1915
1916     std::vector<int> print_preview_page_numbers;
1917     for (size_t index = 0; index < num_pages; ++index) {
1918       int page_number = 0;  // |page_number| is 1-based.
1919       if (!page_ranges->GetInteger(index, &page_number) || page_number < 1)
1920         return pp::Var();
1921       print_preview_page_numbers.push_back(page_number);
1922     }
1923     print_preview_page_numbers_ = print_preview_page_numbers;
1924     page_indicator_.set_current_page(GetPageNumberToDisplay());
1925     return pp::Var();
1926   }
1927   // This is here to work around https://bugs.webkit.org/show_bug.cgi?id=16735.
1928   // In JS, creating a synthetic keyboard event and dispatching it always
1929   // result in a keycode of 0.
1930   if (method_str == kJSSendKeyEvent) {
1931     if (args.size() == 1 && args[0].is_number()) {
1932       pp::KeyboardInputEvent event(
1933           this,                        // instance
1934           PP_INPUTEVENT_TYPE_KEYDOWN,  // HandleInputEvent only care about this.
1935           0,                           // timestamp, not used for kbd events.
1936           0,                           // no modifiers.
1937           args[0].AsInt(),             // keycode.
1938           pp::Var());                  // no char text needed.
1939       HandleInputEvent(event);
1940     }
1941   }
1942   return pp::Var();
1943 }
1944
1945 void Instance::OnGeometryChanged(double old_zoom, float old_device_scale) {
1946   bool force_no_horizontal_scrollbar = false;
1947   int scrollbar_thickness = GetScrollbarThickness();
1948
1949   if (old_device_scale != device_scale_) {
1950     // Change in device scale forces us to recreate resources
1951     ConfigureNumberImageGenerator();
1952
1953     CreateToolbar(current_tb_info_, current_tb_info_size_);
1954     // Load autoscroll anchor image.
1955     autoscroll_anchor_ =
1956         CreateResourceImage(PP_RESOURCEIMAGE_PDF_PAN_SCROLL_ICON);
1957
1958     ConfigurePageIndicator();
1959     ConfigureProgressBar();
1960
1961     pp::Point scroll_position = engine_->GetScrollPosition();
1962     ScalePoint(device_scale_ / old_device_scale, &scroll_position);
1963     engine_->SetScrollPosition(scroll_position);
1964   }
1965
1966   UpdateZoomScale();
1967   if (zoom_ != old_zoom || device_scale_ != old_device_scale)
1968     engine_->ZoomUpdated(zoom_ * device_scale_);
1969   if (zoom_ != old_zoom)
1970     ZoomChanged(zoom_);
1971
1972   available_area_ = pp::Rect(plugin_size_);
1973   if (GetDocumentPixelHeight() > plugin_size_.height()) {
1974     CreateVerticalScrollbar();
1975   } else {
1976     DestroyVerticalScrollbar();
1977   }
1978
1979   int v_scrollbar_reserved_thickness =
1980       v_scrollbar_.get() ? GetScaled(GetScrollbarReservedThickness()) : 0;
1981
1982   if (!force_no_horizontal_scrollbar &&
1983       GetDocumentPixelWidth() >
1984       (plugin_size_.width() - v_scrollbar_reserved_thickness)) {
1985     CreateHorizontalScrollbar();
1986
1987     // Adding the horizontal scrollbar now might cause us to need vertical
1988     // scrollbars.
1989     if (GetDocumentPixelHeight() >
1990         plugin_size_.height() - GetScaled(GetScrollbarReservedThickness())) {
1991       CreateVerticalScrollbar();
1992     }
1993
1994   } else {
1995     DestroyHorizontalScrollbar();
1996   }
1997
1998 #ifdef ENABLE_THUMBNAILS
1999   int thumbnails_pos = 0, thumbnails_total = 0;
2000 #endif
2001   if (v_scrollbar_.get()) {
2002     v_scrollbar_->SetScale(device_scale_);
2003     available_area_.set_width(
2004       std::max(0, plugin_size_.width() - v_scrollbar_reserved_thickness));
2005
2006 #ifdef ENABLE_THUMBNAILS
2007     int height = plugin_size_.height();
2008 #endif
2009     int height_dip = plugin_dip_size_.height();
2010
2011 #if defined(OS_MACOSX)
2012     // Before Lion, Mac always had the resize at the bottom. After that, it
2013     // never did.
2014     if ((base::mac::IsOSSnowLeopard() && full_) ||
2015         (base::mac::IsOSLionOrLater() && h_scrollbar_.get())) {
2016 #else
2017     if (h_scrollbar_.get()) {
2018 #endif  // defined(OS_MACOSX)
2019 #ifdef ENABLE_THUMBNAILS
2020       height -= GetScaled(GetScrollbarThickness());
2021 #endif
2022       height_dip -= GetScrollbarThickness();
2023     }
2024 #ifdef ENABLE_THUMBNAILS
2025     int32 doc_height = GetDocumentPixelHeight();
2026 #endif
2027     int32 doc_height_dip =
2028         static_cast<int32>(GetDocumentPixelHeight() / device_scale_);
2029 #if defined(OS_MACOSX)
2030     // On the Mac we always allow room for the resize button (whose width is
2031     // the same as that of the scrollbar) in full mode. However, if there is no
2032     // no horizontal scrollbar, the end of the scrollbar will scroll past the
2033     // end of the document. This is because the scrollbar assumes that its own
2034     // height (in the case of a vscroll bar) is the same as the height of the
2035     // viewport. Since the viewport is actually larger, we compensate by
2036     // adjusting the document height. Similar logic applies below for the
2037     // horizontal scrollbar.
2038     // For example, if the document size is 1000, and the viewport size is 200,
2039     // then the scrollbar position at the end will be 800. In this case the
2040     // viewport is actally 215 (assuming 15 as the scrollbar width) but the
2041     // scrollbar thinks it is 200. We want the scrollbar position at the end to
2042     // be 785. Making the document size 985 achieves this.
2043     if (full_ && !h_scrollbar_.get()) {
2044 #ifdef ENABLE_THUMBNAILS
2045       doc_height -= GetScaled(GetScrollbarThickness());
2046 #endif
2047       doc_height_dip -= GetScrollbarThickness();
2048     }
2049 #endif  // defined(OS_MACOSX)
2050
2051     int32 position;
2052     position = v_scrollbar_->GetValue();
2053     position = static_cast<int>(position * zoom_ / old_zoom);
2054     valid_v_range_ = doc_height_dip - height_dip;
2055     if (position > valid_v_range_)
2056       position = valid_v_range_;
2057
2058     v_scrollbar_->SetValue(position);
2059
2060     PP_Rect loc;
2061     loc.point.x = static_cast<int>(available_area_.right() / device_scale_);
2062     if (IsOverlayScrollbar())
2063       loc.point.x -= scrollbar_thickness;
2064     loc.point.y = 0;
2065     loc.size.width = scrollbar_thickness;
2066     loc.size.height = height_dip;
2067     v_scrollbar_->SetLocation(loc);
2068     v_scrollbar_->SetDocumentSize(doc_height_dip);
2069
2070 #ifdef ENABLE_THUMBNAILS
2071     thumbnails_pos = position;
2072     thumbnails_total = doc_height - height;
2073 #endif
2074   }
2075
2076   if (h_scrollbar_.get()) {
2077     h_scrollbar_->SetScale(device_scale_);
2078     available_area_.set_height(
2079         std::max(0, plugin_size_.height() -
2080                     GetScaled(GetScrollbarReservedThickness())));
2081
2082     int width_dip = plugin_dip_size_.width();
2083
2084     // See note above.
2085 #if defined(OS_MACOSX)
2086     if ((base::mac::IsOSSnowLeopard() && full_) ||
2087         (base::mac::IsOSLionOrLater() && v_scrollbar_.get())) {
2088 #else
2089     if (v_scrollbar_.get()) {
2090 #endif
2091       width_dip -= GetScrollbarThickness();
2092     }
2093     int32 doc_width_dip =
2094         static_cast<int32>(GetDocumentPixelWidth() / device_scale_);
2095 #if defined(OS_MACOSX)
2096     // See comment in the above if (v_scrollbar_.get()) block.
2097     if (full_ && !v_scrollbar_.get())
2098       doc_width_dip -= GetScrollbarThickness();
2099 #endif  // defined(OS_MACOSX)
2100
2101     int32 position;
2102     position = h_scrollbar_->GetValue();
2103     position = static_cast<int>(position * zoom_ / old_zoom);
2104     position = std::min(position, doc_width_dip - width_dip);
2105
2106     h_scrollbar_->SetValue(position);
2107
2108     PP_Rect loc;
2109     loc.point.x = 0;
2110     loc.point.y = static_cast<int>(available_area_.bottom() / device_scale_);
2111     if (IsOverlayScrollbar())
2112       loc.point.y -= scrollbar_thickness;
2113     loc.size.width = width_dip;
2114     loc.size.height = scrollbar_thickness;
2115     h_scrollbar_->SetLocation(loc);
2116     h_scrollbar_->SetDocumentSize(doc_width_dip);
2117   }
2118
2119   int doc_width = GetDocumentPixelWidth();
2120   if (doc_width < available_area_.width()) {
2121     available_area_.Offset((available_area_.width() - doc_width) / 2, 0);
2122     available_area_.set_width(doc_width);
2123   }
2124   int doc_height = GetDocumentPixelHeight();
2125   if (doc_height < available_area_.height()) {
2126     available_area_.set_height(doc_height);
2127   }
2128
2129   // We'll invalidate the entire plugin anyways.
2130   UpdateToolbarPosition(false);
2131   UpdateProgressBarPosition(false);
2132   UpdatePageIndicatorPosition(false);
2133
2134 #ifdef ENABLE_THUMBNAILS
2135   // Update thumbnail control position.
2136   thumbnails_.SetPosition(thumbnails_pos, thumbnails_total, false);
2137   pp::Rect thumbnails_rc(plugin_size_.width() - GetScaled(kThumbnailsWidth), 0,
2138     GetScaled(kThumbnailsWidth), plugin_size_.height());
2139   if (v_scrollbar_.get())
2140     thumbnails_rc.Offset(-v_scrollbar_reserved_thickness, 0);
2141   if (h_scrollbar_.get())
2142     thumbnails_rc.Inset(0, 0, 0, v_scrollbar_reserved_thickness);
2143   thumbnails_.SetRect(thumbnails_rc, false);
2144 #endif
2145
2146   CalculateBackgroundParts();
2147   engine_->PageOffsetUpdated(available_area_.point());
2148   engine_->PluginSizeUpdated(available_area_.size());
2149
2150   if (!document_size_.GetArea())
2151     return;
2152   paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
2153
2154   // Run the plugin size change callback asynchronously. This function can be
2155   // invoked by a layout change which should not re-enter into JS synchronously.
2156   pp::CompletionCallback callback =
2157       callback_factory_.NewCallback(&Instance::RunCallback,
2158                                     on_plugin_size_changed_callback_);
2159   pp::Module::Get()->core()->CallOnMainThread(0, callback);
2160 }
2161
2162 void Instance::RunCallback(int32_t, pp::Var callback) {
2163   if (callback.is_string())
2164     ExecuteScript(callback);
2165 }
2166
2167 void Instance::CreateHorizontalScrollbar() {
2168   if (h_scrollbar_.get())
2169     return;
2170
2171   h_scrollbar_.reset(new pp::Scrollbar_Dev(this, false));
2172 }
2173
2174 void Instance::CreateVerticalScrollbar() {
2175   if (v_scrollbar_.get())
2176     return;
2177
2178   v_scrollbar_.reset(new pp::Scrollbar_Dev(this, true));
2179 }
2180
2181 void Instance::DestroyHorizontalScrollbar() {
2182   if (!h_scrollbar_.get())
2183     return;
2184   if (h_scrollbar_->GetValue())
2185     engine_->ScrolledToXPosition(0);
2186   h_scrollbar_.reset();
2187 }
2188
2189 void Instance::DestroyVerticalScrollbar() {
2190   if (!v_scrollbar_.get())
2191     return;
2192   if (v_scrollbar_->GetValue())
2193     engine_->ScrolledToYPosition(0);
2194   v_scrollbar_.reset();
2195   page_indicator_.Show(false, true);
2196 }
2197
2198 int Instance::GetScrollbarThickness() {
2199   if (scrollbar_thickness_ == -1) {
2200     pp::Scrollbar_Dev temp_scrollbar(this, false);
2201     scrollbar_thickness_ = temp_scrollbar.GetThickness();
2202     scrollbar_reserved_thickness_ =
2203       temp_scrollbar.IsOverlay() ? 0 : scrollbar_thickness_;
2204   }
2205
2206   return scrollbar_thickness_;
2207 }
2208
2209 int Instance::GetScrollbarReservedThickness() {
2210   GetScrollbarThickness();
2211   return scrollbar_reserved_thickness_;
2212 }
2213
2214 bool Instance::IsOverlayScrollbar() {
2215   return GetScrollbarReservedThickness() == 0;
2216 }
2217
2218 void Instance::CreateToolbar(const ToolbarButtonInfo* tb_info, size_t size) {
2219   toolbar_.reset(new FadingControls());
2220
2221   DCHECK(tb_info);
2222   DCHECK(size >= 0);
2223
2224   // Remember the current toolbar information in case we need to recreate the
2225   // images later.
2226   current_tb_info_ = tb_info;
2227   current_tb_info_size_ = size;
2228
2229   int max_height = 0;
2230   pp::Point origin(kToolbarFadingOffsetLeft, kToolbarFadingOffsetTop);
2231   ScalePoint(device_scale_, &origin);
2232
2233   std::list<Button*> buttons;
2234   for (size_t i = 0; i < size; i++) {
2235     Button* btn = new Button;
2236     pp::ImageData normal_face =
2237         CreateResourceImage(tb_info[i].normal);
2238     btn->CreateButton(tb_info[i].id,
2239                       origin,
2240                       true,
2241                       toolbar_.get(),
2242                       tb_info[i].style,
2243                       normal_face,
2244                       CreateResourceImage(tb_info[i].highlighted),
2245                       CreateResourceImage(tb_info[i].pressed));
2246     buttons.push_back(btn);
2247
2248     origin += pp::Point(normal_face.size().width(), 0);
2249     max_height = std::max(max_height, normal_face.size().height());
2250   }
2251
2252   pp::Rect rc_toolbar(0, 0,
2253       origin.x() + GetToolbarRightOffset(),
2254       origin.y() + max_height + GetToolbarBottomOffset());
2255   toolbar_->CreateFadingControls(
2256       kToolbarId, rc_toolbar, false, this, kTransparentAlpha);
2257
2258   std::list<Button*>::iterator iter;
2259   for (iter = buttons.begin(); iter != buttons.end(); ++iter) {
2260     toolbar_->AddControl(*iter);
2261   }
2262 }
2263
2264 int Instance::GetToolbarRightOffset() {
2265   int scrollbar_thickness = GetScrollbarThickness();
2266   return GetScaled(kToolbarFadingOffsetRight) + 2 * scrollbar_thickness;
2267 }
2268
2269 int Instance::GetToolbarBottomOffset() {
2270   int scrollbar_thickness = GetScrollbarThickness();
2271   return GetScaled(kToolbarFadingOffsetBottom) + scrollbar_thickness;
2272 }
2273
2274 std::vector<pp::ImageData> Instance::GetThumbnailResources() {
2275   std::vector<pp::ImageData> num_images(10);
2276   num_images[0] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_0);
2277   num_images[1] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_1);
2278   num_images[2] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_2);
2279   num_images[3] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_3);
2280   num_images[4] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_4);
2281   num_images[5] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_5);
2282   num_images[6] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_6);
2283   num_images[7] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_7);
2284   num_images[8] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_8);
2285   num_images[9] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_9);
2286   return num_images;
2287 }
2288
2289 std::vector<pp::ImageData> Instance::GetProgressBarResources(
2290     pp::ImageData* background) {
2291   std::vector<pp::ImageData> result(9);
2292   result[0] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_0);
2293   result[1] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_1);
2294   result[2] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_2);
2295   result[3] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_3);
2296   result[4] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_4);
2297   result[5] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_5);
2298   result[6] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_6);
2299   result[7] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_7);
2300   result[8] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_8);
2301   *background = CreateResourceImage(
2302       PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_BACKGROUND);
2303   return result;
2304 }
2305
2306 void Instance::CreatePageIndicator(bool always_visible) {
2307   page_indicator_.CreatePageIndicator(kPageIndicatorId, false, this,
2308       number_image_generator(), always_visible);
2309   ConfigurePageIndicator();
2310 }
2311
2312 void Instance::ConfigurePageIndicator() {
2313   pp::ImageData background =
2314       CreateResourceImage(PP_RESOURCEIMAGE_PDF_PAGE_INDICATOR_BACKGROUND);
2315   page_indicator_.Configure(pp::Point(), background);
2316 }
2317
2318 void Instance::CreateProgressBar() {
2319   pp::ImageData background;
2320   std::vector<pp::ImageData> images = GetProgressBarResources(&background);
2321   std::string text = GetLocalizedString(PP_RESOURCESTRING_PDFPROGRESSLOADING);
2322   progress_bar_.CreateProgressControl(kProgressBarId, false, this, 0.0,
2323       device_scale_, images, background, text);
2324 }
2325
2326 void Instance::ConfigureProgressBar() {
2327   pp::ImageData background;
2328   std::vector<pp::ImageData> images = GetProgressBarResources(&background);
2329   progress_bar_.Reconfigure(background, images, device_scale_);
2330 }
2331
2332 void Instance::CreateThumbnails() {
2333   thumbnails_.CreateThumbnailControl(
2334       kThumbnailsId, pp::Rect(), false, this, engine_.get(),
2335       number_image_generator());
2336 }
2337
2338 void Instance::LoadUrl(const std::string& url) {
2339   LoadUrlInternal(url, &embed_loader_, &Instance::DidOpen);
2340 }
2341
2342 void Instance::LoadPreviewUrl(const std::string& url) {
2343   LoadUrlInternal(url, &embed_preview_loader_, &Instance::DidOpenPreview);
2344 }
2345
2346 void Instance::LoadUrlInternal(const std::string& url, pp::URLLoader* loader,
2347                                void (Instance::* method)(int32_t)) {
2348   pp::URLRequestInfo request(this);
2349   request.SetURL(url);
2350   request.SetMethod("GET");
2351
2352   *loader = CreateURLLoaderInternal();
2353   pp::CompletionCallback callback = loader_factory_.NewCallback(method);
2354   int rv = loader->Open(request, callback);
2355   if (rv != PP_OK_COMPLETIONPENDING)
2356     callback.Run(rv);
2357 }
2358
2359 pp::URLLoader Instance::CreateURLLoaderInternal() {
2360   pp::URLLoader loader(this);
2361
2362   const PPB_URLLoaderTrusted* trusted_interface =
2363       reinterpret_cast<const PPB_URLLoaderTrusted*>(
2364           pp::Module::Get()->GetBrowserInterface(
2365               PPB_URLLOADERTRUSTED_INTERFACE));
2366   if (trusted_interface)
2367     trusted_interface->GrantUniversalAccess(loader.pp_resource());
2368   return loader;
2369 }
2370
2371 int Instance::GetInitialPage(const std::string& url) {
2372   size_t found_idx = url.find('#');
2373   if (found_idx == std::string::npos)
2374     return -1;
2375
2376   const std::string& ref = url.substr(found_idx + 1);
2377   std::vector<std::string> fragments;
2378   Tokenize(ref, kDelimiters, &fragments);
2379
2380   // Page number to return, zero-based.
2381   int page = -1;
2382
2383   // Handle the case of http://foo.com/bar#NAMEDDEST. This is not explicitly
2384   // mentioned except by example in the Adobe "PDF Open Parameters" document.
2385   if ((fragments.size() == 1) && (fragments[0].find('=') == std::string::npos))
2386     return engine_->GetNamedDestinationPage(fragments[0]);
2387
2388   for (size_t i = 0; i < fragments.size(); ++i) {
2389     std::vector<std::string> key_value;
2390     base::SplitString(fragments[i], '=', &key_value);
2391     if (key_value.size() != 2)
2392       continue;
2393     const std::string& key = key_value[0];
2394     const std::string& value = key_value[1];
2395
2396     if (base::strcasecmp(kPage, key.c_str()) == 0) {
2397       // |page_value| is 1-based.
2398       int page_value = -1;
2399       if (base::StringToInt(value, &page_value) && page_value > 0)
2400         page = page_value - 1;
2401       continue;
2402     }
2403     if (base::strcasecmp(kNamedDest, key.c_str()) == 0) {
2404       // |page_value| is 0-based.
2405       int page_value = engine_->GetNamedDestinationPage(value);
2406       if (page_value >= 0)
2407         page = page_value;
2408       continue;
2409     }
2410   }
2411   return page;
2412 }
2413
2414 void Instance::UpdateToolbarPosition(bool invalidate) {
2415   pp::Rect ctrl_rc = toolbar_->GetControlsRect();
2416   int min_toolbar_width = ctrl_rc.width() + GetToolbarRightOffset() +
2417       GetScaled(kToolbarFadingOffsetLeft);
2418   int min_toolbar_height = ctrl_rc.width() + GetToolbarBottomOffset() +
2419       GetScaled(kToolbarFadingOffsetBottom);
2420
2421   // Update toolbar position
2422   if (plugin_size_.width() < min_toolbar_width ||
2423       plugin_size_.height() < min_toolbar_height) {
2424     // Disable toolbar if it does not fit on the screen.
2425     toolbar_->Show(false, invalidate);
2426   } else {
2427     pp::Point offset(
2428         plugin_size_.width() - GetToolbarRightOffset() - ctrl_rc.right(),
2429         plugin_size_.height() - GetToolbarBottomOffset() - ctrl_rc.bottom());
2430     toolbar_->MoveBy(offset, invalidate);
2431
2432     int toolbar_width = std::max(plugin_size_.width() / 2, min_toolbar_width);
2433     toolbar_->ExpandLeft(toolbar_width - toolbar_->rect().width());
2434     toolbar_->Show(painted_first_page_, invalidate);
2435   }
2436 }
2437
2438 void Instance::UpdateProgressBarPosition(bool invalidate) {
2439   // TODO(gene): verify we don't overlap with toolbar.
2440   int scrollbar_thickness = GetScrollbarThickness();
2441   pp::Point progress_origin(
2442       scrollbar_thickness + GetScaled(kProgressOffsetLeft),
2443       plugin_size_.height() - progress_bar_.rect().height() -
2444           scrollbar_thickness - GetScaled(kProgressOffsetBottom));
2445   progress_bar_.MoveTo(progress_origin, invalidate);
2446 }
2447
2448 void Instance::UpdatePageIndicatorPosition(bool invalidate) {
2449   int32 doc_height = static_cast<int>(document_size_.height() * zoom_);
2450   pp::Point origin(
2451       plugin_size_.width() - page_indicator_.rect().width() -
2452           GetScaled(GetScrollbarReservedThickness()),
2453       page_indicator_.GetYPosition(engine_->GetVerticalScrollbarYPosition(),
2454                                    doc_height, plugin_size_.height()));
2455   page_indicator_.MoveTo(origin, invalidate);
2456 }
2457
2458 void Instance::SetZoom(ZoomMode zoom_mode, double scale) {
2459   double old_zoom = zoom_;
2460
2461   zoom_mode_ = zoom_mode;
2462   if (zoom_mode_ == ZOOM_SCALE)
2463     zoom_ = scale;
2464   UpdateZoomScale();
2465
2466   engine_->ZoomUpdated(zoom_ * device_scale_);
2467   OnGeometryChanged(old_zoom, device_scale_);
2468
2469   // If fit-to-height, snap to the beginning of the most visible page.
2470   if (zoom_mode_ == ZOOM_FIT_TO_PAGE) {
2471     ScrollToPage(engine_->GetMostVisiblePage());
2472   }
2473
2474   // Update sticky buttons to the current zoom style.
2475   Button* ftp_btn = static_cast<Button*>(
2476       toolbar_->GetControl(kFitToPageButtonId));
2477   Button* ftw_btn = static_cast<Button*>(
2478       toolbar_->GetControl(kFitToWidthButtonId));
2479   switch (zoom_mode_) {
2480     case ZOOM_FIT_TO_PAGE:
2481       ftp_btn->SetPressedState(true);
2482       ftw_btn->SetPressedState(false);
2483       break;
2484     case ZOOM_FIT_TO_WIDTH:
2485       ftw_btn->SetPressedState(true);
2486       ftp_btn->SetPressedState(false);
2487       break;
2488     default:
2489       ftw_btn->SetPressedState(false);
2490       ftp_btn->SetPressedState(false);
2491   }
2492 }
2493
2494 void Instance::UpdateZoomScale() {
2495   switch (zoom_mode_) {
2496     case ZOOM_SCALE:
2497       break;  // Keep current scale.
2498     case ZOOM_FIT_TO_PAGE: {
2499       int page_num = engine_->GetFirstVisiblePage();
2500       if (page_num == -1)
2501         break;
2502       pp::Rect rc = engine_->GetPageRect(page_num);
2503       if (!rc.height())
2504         break;
2505       // Calculate fit to width zoom level.
2506       double ftw_zoom = static_cast<double>(plugin_dip_size_.width() -
2507           GetScrollbarReservedThickness()) / document_size_.width();
2508       // Calculate fit to height zoom level. If document will not fit
2509       // horizontally, adjust zoom level to allow space for horizontal
2510       // scrollbar.
2511       double fth_zoom =
2512           static_cast<double>(plugin_dip_size_.height()) / rc.height();
2513       if (fth_zoom * document_size_.width() >
2514           plugin_dip_size_.width() - GetScrollbarReservedThickness())
2515         fth_zoom = static_cast<double>(plugin_dip_size_.height()
2516             - GetScrollbarReservedThickness()) / rc.height();
2517       zoom_ = std::min(ftw_zoom, fth_zoom);
2518     } break;
2519     case ZOOM_FIT_TO_WIDTH:
2520     case ZOOM_AUTO:
2521       if (!document_size_.width())
2522         break;
2523       zoom_ = static_cast<double>(plugin_dip_size_.width() -
2524           GetScrollbarReservedThickness()) / document_size_.width();
2525       if (zoom_mode_ == ZOOM_AUTO && zoom_ > 1.0)
2526         zoom_ = 1.0;
2527       break;
2528   }
2529   zoom_ = ClipToRange(zoom_, kMinZoom, kMaxZoom);
2530 }
2531
2532 double Instance::CalculateZoom(uint32 control_id) const {
2533   if (control_id == kZoomInButtonId) {
2534     for (size_t i = 0; i < chrome_page_zoom::kPresetZoomFactorsSize; ++i) {
2535       double current_zoom = chrome_page_zoom::kPresetZoomFactors[i];
2536       if (current_zoom - content::kEpsilon > zoom_)
2537         return current_zoom;
2538     }
2539   } else {
2540     for (size_t i = chrome_page_zoom::kPresetZoomFactorsSize; i > 0; --i) {
2541       double current_zoom = chrome_page_zoom::kPresetZoomFactors[i - 1];
2542       if (current_zoom + content::kEpsilon < zoom_)
2543         return current_zoom;
2544     }
2545   }
2546   return zoom_;
2547 }
2548
2549 pp::ImageData Instance::CreateResourceImage(PP_ResourceImage image_id) {
2550   pp::ImageData resource_data;
2551   if (hidpi_enabled_) {
2552     resource_data =
2553         pp::PDF::GetResourceImageForScale(this, image_id, device_scale_);
2554   }
2555
2556   return resource_data.data() ? resource_data
2557                               : pp::PDF::GetResourceImage(this, image_id);
2558 }
2559
2560 std::string Instance::GetLocalizedString(PP_ResourceString id) {
2561   pp::Var rv(pp::PDF::GetLocalizedString(this, id));
2562   if (!rv.is_string())
2563     return std::string();
2564
2565   return rv.AsString();
2566 }
2567
2568 void Instance::DrawText(const pp::Point& top_center, PP_ResourceString id) {
2569   std::string str(GetLocalizedString(id));
2570
2571   pp::FontDescription_Dev description;
2572   description.set_family(PP_FONTFAMILY_SANSSERIF);
2573   description.set_size(kMessageTextSize * device_scale_);
2574   pp::Font_Dev font(this, description);
2575   int length = font.MeasureSimpleText(str);
2576   pp::Point point(top_center);
2577   point.set_x(point.x() - length / 2);
2578   DCHECK(!image_data_.is_null());
2579   font.DrawSimpleText(&image_data_, str, point, kMessageTextColor);
2580 }
2581
2582 void Instance::SetPrintPreviewMode(int page_count) {
2583   if (!IsPrintPreview() || page_count <= 0) {
2584     print_preview_page_count_ = 0;
2585     return;
2586   }
2587
2588   print_preview_page_count_ = page_count;
2589   ScrollToPage(0);
2590   engine_->AppendBlankPages(print_preview_page_count_);
2591   if (preview_pages_info_.size() > 0)
2592     LoadAvailablePreviewPage();
2593 }
2594
2595 bool Instance::IsPrintPreview() {
2596   return IsPrintPreviewUrl(url_);
2597 }
2598
2599 int Instance::GetPageNumberToDisplay() {
2600   int page = engine_->GetMostVisiblePage();
2601   if (IsPrintPreview() && !print_preview_page_numbers_.empty()) {
2602     page = ClipToRange<int>(page, 0, print_preview_page_numbers_.size() - 1);
2603     return print_preview_page_numbers_[page];
2604   }
2605   return page + 1;
2606 }
2607
2608 void Instance::ProcessPreviewPageInfo(const std::string& url,
2609                                       int dst_page_index) {
2610   if (!IsPrintPreview() || print_preview_page_count_ < 0)
2611     return;
2612
2613   int src_page_index = ExtractPrintPreviewPageIndex(url);
2614   if (src_page_index < 1)
2615     return;
2616
2617   preview_pages_info_.push(std::make_pair(url, dst_page_index));
2618   LoadAvailablePreviewPage();
2619 }
2620
2621 void Instance::LoadAvailablePreviewPage() {
2622   if (preview_pages_info_.size() <= 0)
2623     return;
2624
2625   std::string url = preview_pages_info_.front().first;
2626   int dst_page_index = preview_pages_info_.front().second;
2627   int src_page_index = ExtractPrintPreviewPageIndex(url);
2628   if (src_page_index < 1 ||
2629       dst_page_index >= print_preview_page_count_ ||
2630       preview_document_load_state_ == LOAD_STATE_LOADING) {
2631     return;
2632   }
2633
2634   preview_document_load_state_ = LOAD_STATE_LOADING;
2635   LoadPreviewUrl(url);
2636 }
2637
2638 void Instance::EnableAutoscroll(const pp::Point& origin) {
2639   if (is_autoscroll_)
2640     return;
2641
2642   pp::Size client_size = plugin_size_;
2643   if (v_scrollbar_.get())
2644     client_size.Enlarge(-GetScrollbarThickness(), 0);
2645   if (h_scrollbar_.get())
2646     client_size.Enlarge(0, -GetScrollbarThickness());
2647
2648   // Do not allow autoscroll if client area is too small.
2649   if (autoscroll_anchor_.size().width() > client_size.width() ||
2650       autoscroll_anchor_.size().height() > client_size.height())
2651     return;
2652
2653   autoscroll_rect_ = pp::Rect(
2654       pp::Point(origin.x() - autoscroll_anchor_.size().width() / 2,
2655                 origin.y() - autoscroll_anchor_.size().height() / 2),
2656       autoscroll_anchor_.size());
2657
2658   // Make sure autoscroll anchor is in the client area.
2659   if (autoscroll_rect_.right() > client_size.width()) {
2660     autoscroll_rect_.set_x(
2661         client_size.width() - autoscroll_anchor_.size().width());
2662   }
2663   if (autoscroll_rect_.bottom() > client_size.height()) {
2664     autoscroll_rect_.set_y(
2665         client_size.height() - autoscroll_anchor_.size().height());
2666   }
2667
2668   if (autoscroll_rect_.x() < 0)
2669     autoscroll_rect_.set_x(0);
2670   if (autoscroll_rect_.y() < 0)
2671     autoscroll_rect_.set_y(0);
2672
2673   is_autoscroll_ = true;
2674   Invalidate(kAutoScrollId, autoscroll_rect_);
2675
2676   ScheduleTimer(kAutoScrollId, kAutoScrollTimeoutMs);
2677 }
2678
2679 void Instance::DisableAutoscroll() {
2680   if (is_autoscroll_) {
2681     is_autoscroll_ = false;
2682     Invalidate(kAutoScrollId, autoscroll_rect_);
2683   }
2684 }
2685
2686 PP_CursorType_Dev Instance::CalculateAutoscroll(const pp::Point& mouse_pos) {
2687   // Scroll only if mouse pointer is outside of the anchor area.
2688   if (autoscroll_rect_.Contains(mouse_pos)) {
2689     autoscroll_x_ = 0;
2690     autoscroll_y_ = 0;
2691     return PP_CURSORTYPE_MIDDLEPANNING;
2692   }
2693
2694   // Relative position to the center of anchor area.
2695   pp::Point rel_pos = mouse_pos - autoscroll_rect_.CenterPoint();
2696
2697   // Calculate angle from the X axis. Angle is in range from -pi to pi.
2698   double angle = atan2(static_cast<double>(rel_pos.y()),
2699                        static_cast<double>(rel_pos.x()));
2700
2701   autoscroll_x_ = rel_pos.x() * kAutoScrollFactor;
2702   autoscroll_y_ = rel_pos.y() * kAutoScrollFactor;
2703
2704   // Angle is from -pi to pi. Screen Y is increasing toward bottom,
2705   // so negative angle represent north direction.
2706   if (angle < - (M_PI * 7.0 / 8.0)) {
2707     // going west
2708     return PP_CURSORTYPE_WESTPANNING;
2709   } else if (angle < - (M_PI * 5.0 / 8.0)) {
2710     // going north-west
2711     return PP_CURSORTYPE_NORTHWESTPANNING;
2712   } else if (angle < - (M_PI * 3.0 / 8.0)) {
2713     // going north.
2714     return PP_CURSORTYPE_NORTHPANNING;
2715   } else if (angle < - (M_PI * 1.0 / 8.0)) {
2716     // going north-east
2717     return PP_CURSORTYPE_NORTHEASTPANNING;
2718   } else if (angle < M_PI * 1.0 / 8.0) {
2719     // going east.
2720     return PP_CURSORTYPE_EASTPANNING;
2721   } else if (angle < M_PI * 3.0 / 8.0) {
2722     // going south-east
2723     return PP_CURSORTYPE_SOUTHEASTPANNING;
2724   } else if (angle < M_PI * 5.0 / 8.0) {
2725     // going south.
2726     return PP_CURSORTYPE_SOUTHPANNING;
2727   } else if (angle < M_PI * 7.0 / 8.0) {
2728     // going south-west
2729     return PP_CURSORTYPE_SOUTHWESTPANNING;
2730   }
2731
2732   // went around the circle, going west again
2733   return PP_CURSORTYPE_WESTPANNING;
2734 }
2735
2736 void Instance::ConfigureNumberImageGenerator() {
2737   std::vector<pp::ImageData> num_images = GetThumbnailResources();
2738   pp::ImageData number_background = CreateResourceImage(
2739       PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_NUM_BACKGROUND);
2740   number_image_generator_->Configure(number_background,
2741                                      num_images,
2742                                      device_scale_);
2743 }
2744
2745 NumberImageGenerator* Instance::number_image_generator() {
2746   if (!number_image_generator_.get()) {
2747     number_image_generator_.reset(new NumberImageGenerator(this));
2748     ConfigureNumberImageGenerator();
2749   }
2750   return number_image_generator_.get();
2751 }
2752
2753 int Instance::GetScaled(int x) const {
2754   return static_cast<int>(x * device_scale_);
2755 }
2756
2757 void Instance::UserMetricsRecordAction(const std::string& action) {
2758   pp::PDF::UserMetricsRecordAction(this, pp::Var(action));
2759 }
2760
2761 PDFScriptableObject::PDFScriptableObject(Instance* instance)
2762     : instance_(instance) {
2763 }
2764
2765 PDFScriptableObject::~PDFScriptableObject() {
2766 }
2767
2768 bool PDFScriptableObject::HasMethod(const pp::Var& name, pp::Var* exception) {
2769   return instance_->HasScriptableMethod(name, exception);
2770 }
2771
2772 pp::Var PDFScriptableObject::Call(const pp::Var& method,
2773                                   const std::vector<pp::Var>& args,
2774                                   pp::Var* exception) {
2775   return instance_->CallScriptableMethod(method, args, exception);
2776 }
2777
2778 }  // namespace chrome_pdf