[Telemetry] Add SurfaceFlingerStats to timeline_based_measurement
[chromium-blink-merge.git] / pdf / instance.cc
blob83cb5123a4739e32d6b477783da4467c2743da40
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "pdf/instance.h"
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>
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"
45 #if defined(OS_MACOSX)
46 #include "base/mac/mac_util.h"
47 #endif
49 namespace chrome_pdf {
51 struct ToolbarButtonInfo {
52 uint32 id;
53 Button::ButtonStyle style;
54 PP_ResourceImage normal;
55 PP_ResourceImage highlighted;
56 PP_ResourceImage pressed;
59 namespace {
61 // Uncomment following #define to enable thumbnails.
62 // #define ENABLE_THUMBNAILS
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;
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";
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";
112 const char kChromePrint[] = "chrome://print/";
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";
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 },
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 }
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 },
192 static const char kPPPPdfInterface[] = PPP_PDF_INTERFACE_1;
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();
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;
219 PP_Bool GetPrintPresetOptionsFromDocument(
220 PP_Instance instance,
221 PP_PdfPrintPresetOptions_Dev* options) {
222 void* object = pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
223 if (object) {
224 Instance* obj_instance = static_cast<Instance*>(object);
225 obj_instance->GetPrintPresetOptionsFromDocument(options);
227 return PP_TRUE;
230 const PPP_Pdf ppp_private = {
231 &GetLinkAtPosition,
232 &Transform,
233 &GetPrintPresetOptionsFromDocument
236 int ExtractPrintPreviewPageIndex(const std::string& src_url) {
237 // Sample |src_url| format: chrome://print/id/page_index/print.pdf
238 std::vector<std::string> url_substr;
239 base::SplitString(src_url.substr(strlen(kChromePrint)), '/', &url_substr);
240 if (url_substr.size() != 3)
241 return -1;
243 if (url_substr[2] != "print.pdf")
244 return -1;
246 int page_index = 0;
247 if (!base::StringToInt(url_substr[1], &page_index))
248 return -1;
249 return page_index;
252 bool IsPrintPreviewUrl(const std::string& url) {
253 return url.substr(0, strlen(kChromePrint)) == kChromePrint;
256 void ScalePoint(float scale, pp::Point* point) {
257 point->set_x(static_cast<int>(point->x() * scale));
258 point->set_y(static_cast<int>(point->y() * scale));
261 void ScaleRect(float scale, pp::Rect* rect) {
262 int left = static_cast<int>(floorf(rect->x() * scale));
263 int top = static_cast<int>(floorf(rect->y() * scale));
264 int right = static_cast<int>(ceilf((rect->x() + rect->width()) * scale));
265 int bottom = static_cast<int>(ceilf((rect->y() + rect->height()) * scale));
266 rect->SetRect(left, top, right - left, bottom - top);
269 template<class T>
270 T ClipToRange(T value, T lower_boundary, T upper_boundary) {
271 DCHECK(lower_boundary <= upper_boundary);
272 return std::max<T>(lower_boundary, std::min<T>(value, upper_boundary));
275 } // namespace
277 Instance::Instance(PP_Instance instance)
278 : pp::InstancePrivate(instance),
279 pp::Find_Private(this),
280 pp::Printing_Dev(this),
281 pp::Selection_Dev(this),
282 pp::WidgetClient_Dev(this),
283 pp::Zoom_Dev(this),
284 cursor_(PP_CURSORTYPE_POINTER),
285 timer_pending_(false),
286 current_timer_id_(0),
287 zoom_(1.0),
288 device_scale_(1.0),
289 printing_enabled_(true),
290 hidpi_enabled_(false),
291 full_(IsFullFrame()),
292 zoom_mode_(full_ ? ZOOM_AUTO : ZOOM_SCALE),
293 did_call_start_loading_(false),
294 is_autoscroll_(false),
295 scrollbar_thickness_(-1),
296 scrollbar_reserved_thickness_(-1),
297 current_tb_info_(NULL),
298 current_tb_info_size_(0),
299 paint_manager_(this, this, true),
300 delayed_progress_timer_id_(0),
301 first_paint_(true),
302 painted_first_page_(false),
303 show_page_indicator_(false),
304 document_load_state_(LOAD_STATE_LOADING),
305 preview_document_load_state_(LOAD_STATE_COMPLETE),
306 told_browser_about_unsupported_feature_(false),
307 print_preview_page_count_(0) {
308 loader_factory_.Initialize(this);
309 timer_factory_.Initialize(this);
310 form_factory_.Initialize(this);
311 callback_factory_.Initialize(this);
312 engine_.reset(PDFEngine::Create(this));
313 pp::Module::Get()->AddPluginInterface(kPPPPdfInterface, &ppp_private);
314 AddPerInstanceObject(kPPPPdfInterface, this);
316 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_MOUSE);
317 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_WHEEL);
318 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_KEYBOARD);
319 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_TOUCH);
322 Instance::~Instance() {
323 if (timer_pending_) {
324 timer_factory_.CancelAll();
325 timer_pending_ = false;
327 // The engine may try to access this instance during its destruction.
328 // Make sure this happens early while the instance is still intact.
329 engine_.reset();
330 RemovePerInstanceObject(kPPPPdfInterface, this);
333 bool Instance::Init(uint32_t argc, const char* argn[], const char* argv[]) {
334 // For now, we hide HiDPI support behind a flag.
335 if (pp::PDF::IsFeatureEnabled(this, PP_PDFFEATURE_HIDPI))
336 hidpi_enabled_ = true;
338 printing_enabled_ = pp::PDF::IsFeatureEnabled(this, PP_PDFFEATURE_PRINTING);
339 if (printing_enabled_) {
340 CreateToolbar(kPDFToolbarButtons, arraysize(kPDFToolbarButtons));
341 } else {
342 CreateToolbar(kPDFNoPrintToolbarButtons,
343 arraysize(kPDFNoPrintToolbarButtons));
346 CreateProgressBar();
348 // Load autoscroll anchor image.
349 autoscroll_anchor_ =
350 CreateResourceImage(PP_RESOURCEIMAGE_PDF_PAN_SCROLL_ICON);
352 #ifdef ENABLE_THUMBNAILS
353 CreateThumbnails();
354 #endif
355 const char* url = NULL;
356 for (uint32_t i = 0; i < argc; ++i) {
357 if (strcmp(argn[i], "src") == 0) {
358 url = argv[i];
359 break;
363 if (!url)
364 return false;
366 CreatePageIndicator(IsPrintPreviewUrl(url));
368 if (!full_) {
369 // For PDFs embedded in a frame, we don't get the data automatically like we
370 // do for full-frame loads. Start loading the data manually.
371 LoadUrl(url);
372 } else {
373 DCHECK(!did_call_start_loading_);
374 pp::PDF::DidStartLoading(this);
375 did_call_start_loading_ = true;
378 ZoomLimitsChanged(kMinZoom, kMaxZoom);
380 text_input_.reset(new pp::TextInput_Dev(this));
382 url_ = url;
383 return engine_->New(url);
386 bool Instance::HandleDocumentLoad(const pp::URLLoader& loader) {
387 delayed_progress_timer_id_ = ScheduleTimer(kProgressBarId,
388 kProgressDelayTimeoutMs);
389 return engine_->HandleDocumentLoad(loader);
392 bool Instance::HandleInputEvent(const pp::InputEvent& event) {
393 // To simplify things, convert the event into device coordinates if it is
394 // a mouse event.
395 pp::InputEvent event_device_res(event);
397 pp::MouseInputEvent mouse_event(event);
398 if (!mouse_event.is_null()) {
399 pp::Point point = mouse_event.GetPosition();
400 pp::Point movement = mouse_event.GetMovement();
401 ScalePoint(device_scale_, &point);
402 ScalePoint(device_scale_, &movement);
403 mouse_event = pp::MouseInputEvent(
404 this,
405 event.GetType(),
406 event.GetTimeStamp(),
407 event.GetModifiers(),
408 mouse_event.GetButton(),
409 point,
410 mouse_event.GetClickCount(),
411 movement);
412 event_device_res = mouse_event;
416 // Check if we need to go to autoscroll mode.
417 if (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE &&
418 (event.GetModifiers() & PP_INPUTEVENT_MODIFIER_MIDDLEBUTTONDOWN)) {
419 pp::MouseInputEvent mouse_event(event_device_res);
420 pp::Point pos = mouse_event.GetPosition();
421 EnableAutoscroll(pos);
422 UpdateCursor(CalculateAutoscroll(pos));
423 return true;
424 } else {
425 // Quit autoscrolling on any other event.
426 DisableAutoscroll();
429 #ifdef ENABLE_THUMBNAILS
430 if (event.GetType() == PP_INPUTEVENT_TYPE_MOUSELEAVE)
431 thumbnails_.SlideOut();
433 if (thumbnails_.HandleEvent(event_device_res))
434 return true;
435 #endif
437 if (!IsMouseOnScrollbar(event_device_res) &&
438 toolbar_->HandleEvent(event_device_res))
439 return true;
441 #ifdef ENABLE_THUMBNAILS
442 if (v_scrollbar_.get() && event.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE) {
443 pp::MouseInputEvent mouse_event(event);
444 pp::Point pt = mouse_event.GetPosition();
445 pp::Rect v_scrollbar_rc;
446 v_scrollbar_->GetLocation(&v_scrollbar_rc);
447 // There is a bug (https://bugs.webkit.org/show_bug.cgi?id=45208)
448 // in the webkit that makes event.u.mouse.button
449 // equal to PP_INPUTEVENT_MOUSEBUTTON_LEFT, even when no button is pressed.
450 // To work around this issue we use modifier for now, and will switch
451 // to button once the bug is fixed and webkit got merged back to our tree.
452 if (v_scrollbar_rc.Contains(pt) &&
453 (event.GetModifiers() & PP_INPUTEVENT_MODIFIER_LEFTBUTTONDOWN)) {
454 thumbnails_.SlideIn();
457 // When scrollbar is in the scrolling mode we should display thumbnails
458 // even the mouse is outside the thumbnail and scrollbar areas.
459 // If mouse is outside plugin area, we are still getting mouse move events
460 // while scrolling. See bug description for details:
461 // http://code.google.com/p/chromium/issues/detail?id=56444
462 if (!v_scrollbar_rc.Contains(pt) && thumbnails_.visible() &&
463 !(event.GetModifiers() & PP_INPUTEVENT_MODIFIER_LEFTBUTTONDOWN) &&
464 !thumbnails_.rect().Contains(pt)) {
465 thumbnails_.SlideOut();
468 #endif
470 // Need to pass the event to the engine first, since if we're over an edit
471 // control we want it to get keyboard events (like space) instead of the
472 // scrollbar.
473 // TODO: will have to offset the mouse coordinates once we support bidi and
474 // there could be scrollbars on the left.
475 pp::InputEvent offset_event(event_device_res);
476 bool try_engine_first = true;
477 switch (offset_event.GetType()) {
478 case PP_INPUTEVENT_TYPE_MOUSEDOWN:
479 case PP_INPUTEVENT_TYPE_MOUSEUP:
480 case PP_INPUTEVENT_TYPE_MOUSEMOVE:
481 case PP_INPUTEVENT_TYPE_MOUSEENTER:
482 case PP_INPUTEVENT_TYPE_MOUSELEAVE: {
483 pp::MouseInputEvent mouse_event(event_device_res);
484 pp::MouseInputEvent mouse_event_dip(event);
485 pp::Point point = mouse_event.GetPosition();
486 point.set_x(point.x() - available_area_.x());
487 offset_event = pp::MouseInputEvent(
488 this,
489 event.GetType(),
490 event.GetTimeStamp(),
491 event.GetModifiers(),
492 mouse_event.GetButton(),
493 point,
494 mouse_event.GetClickCount(),
495 mouse_event.GetMovement());
496 if (!engine_->IsSelecting()) {
497 if (!IsOverlayScrollbar() &&
498 !available_area_.Contains(mouse_event.GetPosition())) {
499 try_engine_first = false;
500 } else if (IsOverlayScrollbar() && IsMouseOnScrollbar(event)) {
501 try_engine_first = false;
504 break;
506 default:
507 break;
509 if (try_engine_first && engine_->HandleEvent(offset_event))
510 return true;
512 // Left/Right arrows should scroll to the beginning of the Prev/Next page if
513 // there is no horizontal scroll bar.
514 // If fit-to-height, PgDown/PgUp should scroll to the beginning of the
515 // Prev/Next page. Spacebar / shift+spacebar should do the same.
516 if (v_scrollbar_.get() && event.GetType() == PP_INPUTEVENT_TYPE_KEYDOWN) {
517 pp::KeyboardInputEvent keyboard_event(event);
518 bool no_h_scrollbar = !h_scrollbar_.get();
519 uint32_t key_code = keyboard_event.GetKeyCode();
520 bool has_modifiers = keyboard_event.GetModifiers() != 0;
521 bool page_down =
522 no_h_scrollbar && !has_modifiers && key_code == ui::VKEY_RIGHT;
523 bool page_up =
524 no_h_scrollbar && !has_modifiers && key_code == ui::VKEY_LEFT;
525 if (zoom_mode_ == ZOOM_FIT_TO_PAGE) {
526 bool has_shift =
527 keyboard_event.GetModifiers() & PP_INPUTEVENT_MODIFIER_SHIFTKEY;
528 bool key_is_space = key_code == ui::VKEY_SPACE;
529 page_down |= key_is_space || key_code == ui::VKEY_NEXT;
530 page_up |= (key_is_space && has_shift) || (key_code == ui::VKEY_PRIOR);
532 if (page_down) {
533 int page = engine_->GetFirstVisiblePage();
534 if (page == -1)
535 return true;
536 // Engine calculates visible page including delimiter to the page size.
537 // We need to check here if the page itself is completely out of view and
538 // scroll to the next one in that case.
539 if (engine_->GetPageRect(page).bottom() * zoom_ <=
540 v_scrollbar_->GetValue())
541 page++;
542 ScrollToPage(page + 1);
543 UpdateCursor(PP_CURSORTYPE_POINTER);
544 return true;
545 } else if (page_up) {
546 int page = engine_->GetFirstVisiblePage();
547 if (page == -1)
548 return true;
549 if (engine_->GetPageRect(page).y() * zoom_ >= v_scrollbar_->GetValue())
550 page--;
551 ScrollToPage(page);
552 UpdateCursor(PP_CURSORTYPE_POINTER);
553 return true;
557 if (v_scrollbar_.get() && v_scrollbar_->HandleEvent(event)) {
558 UpdateCursor(PP_CURSORTYPE_POINTER);
559 return true;
562 if (h_scrollbar_.get() && h_scrollbar_->HandleEvent(event)) {
563 UpdateCursor(PP_CURSORTYPE_POINTER);
564 return true;
567 if (timer_pending_ &&
568 (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEUP ||
569 event.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE)) {
570 timer_factory_.CancelAll();
571 timer_pending_ = false;
572 } else if (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE &&
573 engine_->IsSelecting()) {
574 bool set_timer = false;
575 pp::MouseInputEvent mouse_event(event);
576 if (v_scrollbar_.get() &&
577 (mouse_event.GetPosition().y() <= 0 ||
578 mouse_event.GetPosition().y() >= (plugin_dip_size_.height() - 1))) {
579 v_scrollbar_->ScrollBy(
580 PP_SCROLLBY_LINE, mouse_event.GetPosition().y() >= 0 ? 1: -1);
581 set_timer = true;
583 if (h_scrollbar_.get() &&
584 (mouse_event.GetPosition().x() <= 0 ||
585 mouse_event.GetPosition().x() >= (plugin_dip_size_.width() - 1))) {
586 h_scrollbar_->ScrollBy(PP_SCROLLBY_LINE,
587 mouse_event.GetPosition().x() >= 0 ? 1: -1);
588 set_timer = true;
591 if (set_timer) {
592 last_mouse_event_ = pp::MouseInputEvent(event);
594 pp::CompletionCallback callback =
595 timer_factory_.NewCallback(&Instance::OnTimerFired);
596 pp::Module::Get()->core()->CallOnMainThread(kDragTimerMs, callback);
597 timer_pending_ = true;
601 if (event.GetType() == PP_INPUTEVENT_TYPE_KEYDOWN) {
602 pp::KeyboardInputEvent keyboard_event(event);
603 const uint32 modifier = event.GetModifiers();
604 if (modifier & kDefaultKeyModifier) {
605 switch (keyboard_event.GetKeyCode()) {
606 case 'A':
607 engine_->SelectAll();
608 return true;
611 if (modifier & PP_INPUTEVENT_MODIFIER_CONTROLKEY) {
612 switch (keyboard_event.GetKeyCode()) {
613 case ui::VKEY_OEM_4:
614 // Left bracket.
615 engine_->RotateCounterclockwise();
616 return true;
617 case ui::VKEY_OEM_6:
618 // Right bracket.
619 engine_->RotateClockwise();
620 return true;
625 // Return true for unhandled clicks so the plugin takes focus.
626 return (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN);
629 void Instance::DidChangeView(const pp::View& view) {
630 pp::Rect view_rect(view.GetRect());
631 float device_scale = 1.0f;
632 float old_device_scale = device_scale_;
633 if (hidpi_enabled_)
634 device_scale = view.GetDeviceScale();
635 pp::Size view_device_size(view_rect.width() * device_scale,
636 view_rect.height() * device_scale);
637 if (view_device_size == plugin_size_ && device_scale == device_scale_)
638 return; // We don't care about the position, only the size.
640 image_data_ = pp::ImageData();
641 device_scale_ = device_scale;
642 plugin_dip_size_ = view_rect.size();
643 plugin_size_ = view_device_size;
645 paint_manager_.SetSize(view_device_size, device_scale_);
647 image_data_ = pp::ImageData(this,
648 PP_IMAGEDATAFORMAT_BGRA_PREMUL,
649 plugin_size_,
650 false);
651 if (image_data_.is_null()) {
652 DCHECK(plugin_size_.IsEmpty());
653 return;
656 // View dimensions changed, disable autoscroll (if it was enabled).
657 DisableAutoscroll();
659 OnGeometryChanged(zoom_, old_device_scale);
662 pp::Var Instance::GetInstanceObject() {
663 if (instance_object_.is_undefined()) {
664 PDFScriptableObject* object = new PDFScriptableObject(this);
665 // The pp::Var takes ownership of object here.
666 instance_object_ = pp::VarPrivate(this, object);
669 return instance_object_;
672 void Instance::GetPrintPresetOptionsFromDocument(
673 PP_PdfPrintPresetOptions_Dev* options) {
674 options->is_scaling_disabled = PP_FromBool(IsPrintScalingDisabled());
675 options->copies = engine_->GetCopiesToPrint();
678 pp::Var Instance::GetLinkAtPosition(const pp::Point& point) {
679 pp::Point offset_point(point);
680 ScalePoint(device_scale_, &offset_point);
681 offset_point.set_x(offset_point.x() - available_area_.x());
682 return engine_->GetLinkAtPosition(offset_point);
685 pp::Var Instance::GetSelectedText(bool html) {
686 if (html || !engine_->HasPermission(PDFEngine::PERMISSION_COPY))
687 return pp::Var();
688 return engine_->GetSelectedText();
691 void Instance::InvalidateWidget(pp::Widget_Dev widget,
692 const pp::Rect& dirty_rect) {
693 if (v_scrollbar_.get() && *v_scrollbar_ == widget) {
694 if (!image_data_.is_null())
695 v_scrollbar_->Paint(dirty_rect.pp_rect(), &image_data_);
696 } else if (h_scrollbar_.get() && *h_scrollbar_ == widget) {
697 if (!image_data_.is_null())
698 h_scrollbar_->Paint(dirty_rect.pp_rect(), &image_data_);
699 } else {
700 // Possible to hit this condition since sometimes the scrollbar codes posts
701 // a task to do something later, and we could have deleted our reference in
702 // the meantime.
703 return;
706 pp::Rect dirty_rect_scaled = dirty_rect;
707 ScaleRect(device_scale_, &dirty_rect_scaled);
708 paint_manager_.InvalidateRect(dirty_rect_scaled);
711 void Instance::ScrollbarValueChanged(pp::Scrollbar_Dev scrollbar,
712 uint32_t value) {
713 value = GetScaled(value);
714 if (v_scrollbar_.get() && *v_scrollbar_ == scrollbar) {
715 engine_->ScrolledToYPosition(value);
716 pp::Rect rc;
717 v_scrollbar_->GetLocation(&rc);
718 int32 doc_height = GetDocumentPixelHeight();
719 doc_height -= GetScaled(rc.height());
720 #ifdef ENABLE_THUMBNAILS
721 if (thumbnails_.visible()) {
722 thumbnails_.SetPosition(value, doc_height, true);
724 #endif
725 pp::Point origin(
726 plugin_size_.width() - page_indicator_.rect().width() -
727 GetScaled(GetScrollbarReservedThickness()),
728 page_indicator_.GetYPosition(value, doc_height, plugin_size_.height()));
729 page_indicator_.MoveTo(origin, page_indicator_.visible());
730 } else if (h_scrollbar_.get() && *h_scrollbar_ == scrollbar) {
731 engine_->ScrolledToXPosition(value);
735 void Instance::ScrollbarOverlayChanged(pp::Scrollbar_Dev scrollbar,
736 bool overlay) {
737 scrollbar_reserved_thickness_ = overlay ? 0 : scrollbar_thickness_;
738 OnGeometryChanged(zoom_, device_scale_);
741 uint32_t Instance::QuerySupportedPrintOutputFormats() {
742 return engine_->QuerySupportedPrintOutputFormats();
745 int32_t Instance::PrintBegin(const PP_PrintSettings_Dev& print_settings) {
746 // For us num_pages is always equal to the number of pages in the PDF
747 // document irrespective of the printable area.
748 int32_t ret = engine_->GetNumberOfPages();
749 if (!ret)
750 return 0;
752 uint32_t supported_formats = engine_->QuerySupportedPrintOutputFormats();
753 if ((print_settings.format & supported_formats) == 0)
754 return 0;
756 print_settings_.is_printing = true;
757 print_settings_.pepper_print_settings = print_settings;
758 engine_->PrintBegin();
759 return ret;
762 pp::Resource Instance::PrintPages(
763 const PP_PrintPageNumberRange_Dev* page_ranges,
764 uint32_t page_range_count) {
765 if (!print_settings_.is_printing)
766 return pp::Resource();
768 print_settings_.print_pages_called_ = true;
769 return engine_->PrintPages(page_ranges, page_range_count,
770 print_settings_.pepper_print_settings);
773 void Instance::PrintEnd() {
774 if (print_settings_.print_pages_called_)
775 UserMetricsRecordAction("PDF.PrintPage");
776 print_settings_.Clear();
777 engine_->PrintEnd();
780 bool Instance::IsPrintScalingDisabled() {
781 return !engine_->GetPrintScaling();
784 bool Instance::StartFind(const std::string& text, bool case_sensitive) {
785 engine_->StartFind(text.c_str(), case_sensitive);
786 return true;
789 void Instance::SelectFindResult(bool forward) {
790 engine_->SelectFindResult(forward);
793 void Instance::StopFind() {
794 engine_->StopFind();
797 void Instance::Zoom(double scale, bool text_only) {
798 UserMetricsRecordAction("PDF.ZoomFromBrowser");
800 // If the zoom level doesn't change it means that this zoom change might have
801 // been initiated by the plugin. In that case, we don't want to change the
802 // zoom mode to ZOOM_SCALE as it may have been intentionally set to
803 // ZOOM_FIT_TO_PAGE or some other value when the zoom was last changed.
804 if (scale == zoom_)
805 return;
807 SetZoom(ZOOM_SCALE, scale);
810 void Instance::ZoomChanged(double factor) {
811 if (full_)
812 Zoom_Dev::ZoomChanged(factor);
815 void Instance::OnPaint(const std::vector<pp::Rect>& paint_rects,
816 std::vector<PaintManager::ReadyRect>* ready,
817 std::vector<pp::Rect>* pending) {
818 if (image_data_.is_null()) {
819 DCHECK(plugin_size_.IsEmpty());
820 return;
822 if (first_paint_) {
823 first_paint_ = false;
824 pp::Rect rect = pp::Rect(pp::Point(), plugin_size_);
825 FillRect(rect, kBackgroundColor);
826 ready->push_back(PaintManager::ReadyRect(rect, image_data_, true));
827 *pending = paint_rects;
828 return;
831 engine_->PrePaint();
833 for (size_t i = 0; i < paint_rects.size(); i++) {
834 // Intersect with plugin area since there could be pending invalidates from
835 // when the plugin area was larger.
836 pp::Rect rect =
837 paint_rects[i].Intersect(pp::Rect(pp::Point(), plugin_size_));
838 if (rect.IsEmpty())
839 continue;
841 pp::Rect pdf_rect = available_area_.Intersect(rect);
842 if (!pdf_rect.IsEmpty()) {
843 pdf_rect.Offset(available_area_.x() * -1, 0);
845 std::vector<pp::Rect> pdf_ready;
846 std::vector<pp::Rect> pdf_pending;
847 engine_->Paint(pdf_rect, &image_data_, &pdf_ready, &pdf_pending);
848 for (size_t j = 0; j < pdf_ready.size(); ++j) {
849 pdf_ready[j].Offset(available_area_.point());
850 ready->push_back(
851 PaintManager::ReadyRect(pdf_ready[j], image_data_, false));
853 for (size_t j = 0; j < pdf_pending.size(); ++j) {
854 pdf_pending[j].Offset(available_area_.point());
855 pending->push_back(pdf_pending[j]);
859 for (size_t j = 0; j < background_parts_.size(); ++j) {
860 pp::Rect intersection = background_parts_[j].location.Intersect(rect);
861 if (!intersection.IsEmpty()) {
862 FillRect(intersection, background_parts_[j].color);
863 ready->push_back(
864 PaintManager::ReadyRect(intersection, image_data_, false));
868 if (document_load_state_ == LOAD_STATE_FAILED) {
869 pp::Point top_center;
870 top_center.set_x(plugin_size_.width() / 2);
871 top_center.set_y(plugin_size_.height() / 2);
872 DrawText(top_center, PP_RESOURCESTRING_PDFLOAD_FAILED);
875 #ifdef ENABLE_THUMBNAILS
876 thumbnails_.Paint(&image_data_, rect);
877 #endif
880 engine_->PostPaint();
882 // Must paint scrollbars after the background parts, in case we have an
883 // overlay scrollbar that's over the background. We also do this in a separate
884 // loop because the scrollbar painting logic uses the signal of whether there
885 // are pending paints or not to figure out if it should draw right away or
886 // not.
887 for (size_t i = 0; i < paint_rects.size(); i++) {
888 PaintIfWidgetIntersects(h_scrollbar_.get(), paint_rects[i], ready, pending);
889 PaintIfWidgetIntersects(v_scrollbar_.get(), paint_rects[i], ready, pending);
892 if (progress_bar_.visible())
893 PaintOverlayControl(&progress_bar_, &image_data_, ready);
895 if (page_indicator_.visible())
896 PaintOverlayControl(&page_indicator_, &image_data_, ready);
898 if (toolbar_->current_transparency() != kTransparentAlpha)
899 PaintOverlayControl(toolbar_.get(), &image_data_, ready);
901 // Paint autoscroll anchor if needed.
902 if (is_autoscroll_) {
903 size_t limit = ready->size();
904 for (size_t i = 0; i < limit; i++) {
905 pp::Rect anchor_rect = autoscroll_rect_.Intersect((*ready)[i].rect);
906 if (!anchor_rect.IsEmpty()) {
907 pp::Rect draw_rc = pp::Rect(
908 pp::Point(anchor_rect.x() - autoscroll_rect_.x(),
909 anchor_rect.y() - autoscroll_rect_.y()),
910 anchor_rect.size());
911 // Paint autoscroll anchor.
912 AlphaBlend(autoscroll_anchor_, draw_rc,
913 &image_data_, anchor_rect.point(), kOpaqueAlpha);
919 void Instance::PaintOverlayControl(
920 Control* ctrl,
921 pp::ImageData* image_data,
922 std::vector<PaintManager::ReadyRect>* ready) {
923 // Make sure that we only paint overlay controls over an area that's ready,
924 // i.e. not pending. Otherwise we'll mark the control rect as ready and
925 // it'll overwrite the pdf region.
926 std::list<pp::Rect> ctrl_rects;
927 for (size_t i = 0; i < ready->size(); i++) {
928 pp::Rect rc = ctrl->rect().Intersect((*ready)[i].rect);
929 if (!rc.IsEmpty())
930 ctrl_rects.push_back(rc);
933 if (!ctrl_rects.empty()) {
934 ctrl->PaintMultipleRects(image_data, ctrl_rects);
936 std::list<pp::Rect>::iterator iter;
937 for (iter = ctrl_rects.begin(); iter != ctrl_rects.end(); ++iter) {
938 ready->push_back(PaintManager::ReadyRect(*iter, *image_data, false));
943 void Instance::DidOpen(int32_t result) {
944 if (result == PP_OK) {
945 engine_->HandleDocumentLoad(embed_loader_);
946 } else if (result != PP_ERROR_ABORTED) { // Can happen in tests.
947 NOTREACHED();
951 void Instance::DidOpenPreview(int32_t result) {
952 if (result == PP_OK) {
953 preview_engine_.reset(PDFEngine::Create(new PreviewModeClient(this)));
954 preview_engine_->HandleDocumentLoad(embed_preview_loader_);
955 } else {
956 NOTREACHED();
960 void Instance::PaintIfWidgetIntersects(
961 pp::Widget_Dev* widget,
962 const pp::Rect& rect,
963 std::vector<PaintManager::ReadyRect>* ready,
964 std::vector<pp::Rect>* pending) {
965 if (!widget)
966 return;
968 pp::Rect location;
969 if (!widget->GetLocation(&location))
970 return;
972 ScaleRect(device_scale_, &location);
973 location = location.Intersect(rect);
974 if (location.IsEmpty())
975 return;
977 if (IsOverlayScrollbar()) {
978 // If we're using overlay scrollbars, and there are pending paints under the
979 // scrollbar, don't update the scrollbar instantly. While it would be nice,
980 // we would need to double buffer the plugin area in order to make this
981 // work. This is because we'd need to always have a copy of what the pdf
982 // under the scrollbar looks like, and additionally we couldn't paint the
983 // pdf under the scrollbar if it's ready until we got the preceding flush.
984 // So in practice, it would make painting slower and introduce extra buffer
985 // copies for the general case.
986 for (size_t i = 0; i < pending->size(); ++i) {
987 if ((*pending)[i].Intersects(location))
988 return;
991 // Even if none of the pending paints are under the scrollbar, we never want
992 // to paint it if it's over the pdf if there are other pending paints.
993 // Otherwise different parts of the pdf plugin would display at different
994 // scroll offsets.
995 if (!pending->empty() && available_area_.Intersects(rect)) {
996 pending->push_back(location);
997 return;
1001 pp::Rect location_dip = location;
1002 ScaleRect(1.0f / device_scale_, &location_dip);
1004 DCHECK(!image_data_.is_null());
1005 widget->Paint(location_dip, &image_data_);
1007 ready->push_back(PaintManager::ReadyRect(location, image_data_, true));
1010 void Instance::OnTimerFired(int32_t) {
1011 HandleInputEvent(last_mouse_event_);
1014 void Instance::OnClientTimerFired(int32_t id) {
1015 engine_->OnCallback(id);
1018 void Instance::OnControlTimerFired(int32_t,
1019 const uint32& control_id,
1020 const uint32& timer_id) {
1021 if (control_id == toolbar_->id()) {
1022 toolbar_->OnTimerFired(timer_id);
1023 } else if (control_id == progress_bar_.id()) {
1024 if (timer_id == delayed_progress_timer_id_) {
1025 if (document_load_state_ == LOAD_STATE_LOADING &&
1026 !progress_bar_.visible()) {
1027 progress_bar_.Fade(true, kProgressFadeTimeoutMs);
1029 delayed_progress_timer_id_ = 0;
1030 } else {
1031 progress_bar_.OnTimerFired(timer_id);
1033 } else if (control_id == kAutoScrollId) {
1034 if (is_autoscroll_) {
1035 if (autoscroll_x_ != 0 && h_scrollbar_.get()) {
1036 h_scrollbar_->ScrollBy(PP_SCROLLBY_PIXEL, autoscroll_x_);
1038 if (autoscroll_y_ != 0 && v_scrollbar_.get()) {
1039 v_scrollbar_->ScrollBy(PP_SCROLLBY_PIXEL, autoscroll_y_);
1042 // Reschedule timer.
1043 ScheduleTimer(kAutoScrollId, kAutoScrollTimeoutMs);
1045 } else if (control_id == kPageIndicatorId) {
1046 page_indicator_.OnTimerFired(timer_id);
1048 #ifdef ENABLE_THUMBNAILS
1049 else if (control_id == thumbnails_.id()) {
1050 thumbnails_.OnTimerFired(timer_id);
1052 #endif
1055 void Instance::CalculateBackgroundParts() {
1056 background_parts_.clear();
1057 int v_scrollbar_thickness =
1058 GetScaled(v_scrollbar_.get() ? GetScrollbarReservedThickness() : 0);
1059 int h_scrollbar_thickness =
1060 GetScaled(h_scrollbar_.get() ? GetScrollbarReservedThickness() : 0);
1061 int width_without_scrollbar = std::max(
1062 plugin_size_.width() - v_scrollbar_thickness, 0);
1063 int height_without_scrollbar = std::max(
1064 plugin_size_.height() - h_scrollbar_thickness, 0);
1065 int left_width = available_area_.x();
1066 int right_start = available_area_.right();
1067 int right_width = abs(width_without_scrollbar - available_area_.right());
1068 int bottom = std::min(available_area_.bottom(), height_without_scrollbar);
1070 // Add the left, right, and bottom rectangles. Note: we assume only
1071 // horizontal centering.
1072 BackgroundPart part = {
1073 pp::Rect(0, 0, left_width, bottom),
1074 kBackgroundColor
1076 if (!part.location.IsEmpty())
1077 background_parts_.push_back(part);
1078 part.location = pp::Rect(right_start, 0, right_width, bottom);
1079 if (!part.location.IsEmpty())
1080 background_parts_.push_back(part);
1081 part.location = pp::Rect(
1082 0, bottom, width_without_scrollbar, height_without_scrollbar - bottom);
1083 if (!part.location.IsEmpty())
1084 background_parts_.push_back(part);
1086 if (h_scrollbar_thickness
1087 #if defined(OS_MACOSX)
1089 #else
1091 #endif
1092 v_scrollbar_thickness) {
1093 part.color = 0xFFFFFFFF;
1094 part.location = pp::Rect(plugin_size_.width() - v_scrollbar_thickness,
1095 plugin_size_.height() - h_scrollbar_thickness,
1096 h_scrollbar_thickness,
1097 v_scrollbar_thickness);
1098 background_parts_.push_back(part);
1102 int Instance::GetDocumentPixelWidth() const {
1103 return static_cast<int>(ceil(document_size_.width() * zoom_ * device_scale_));
1106 int Instance::GetDocumentPixelHeight() const {
1107 return static_cast<int>(ceil(document_size_.height() *
1108 zoom_ *
1109 device_scale_));
1112 void Instance::FillRect(const pp::Rect& rect, uint32 color) {
1113 DCHECK(!image_data_.is_null() || rect.IsEmpty());
1114 uint32* buffer_start = static_cast<uint32*>(image_data_.data());
1115 int stride = image_data_.stride();
1116 uint32* ptr = buffer_start + rect.y() * stride / 4 + rect.x();
1117 int height = rect.height();
1118 int width = rect.width();
1119 for (int y = 0; y < height; ++y) {
1120 for (int x = 0; x < width; ++x)
1121 *(ptr + x) = color;
1122 ptr += stride / 4;
1126 void Instance::DocumentSizeUpdated(const pp::Size& size) {
1127 document_size_ = size;
1129 OnGeometryChanged(zoom_, device_scale_);
1132 void Instance::Invalidate(const pp::Rect& rect) {
1133 pp::Rect offset_rect(rect);
1134 offset_rect.Offset(available_area_.point());
1135 paint_manager_.InvalidateRect(offset_rect);
1138 void Instance::Scroll(const pp::Point& point) {
1139 pp::Rect scroll_area = available_area_;
1140 if (IsOverlayScrollbar()) {
1141 pp::Rect rc;
1142 if (h_scrollbar_.get()) {
1143 h_scrollbar_->GetLocation(&rc);
1144 ScaleRect(device_scale_, &rc);
1145 if (scroll_area.bottom() > rc.y()) {
1146 scroll_area.set_height(rc.y() - scroll_area.y());
1147 paint_manager_.InvalidateRect(rc);
1150 if (v_scrollbar_.get()) {
1151 v_scrollbar_->GetLocation(&rc);
1152 ScaleRect(device_scale_, &rc);
1153 if (scroll_area.right() > rc.x()) {
1154 scroll_area.set_width(rc.x() - scroll_area.x());
1155 paint_manager_.InvalidateRect(rc);
1159 paint_manager_.ScrollRect(scroll_area, point);
1161 if (toolbar_->current_transparency() != kTransparentAlpha)
1162 paint_manager_.InvalidateRect(toolbar_->GetControlsRect());
1164 if (progress_bar_.visible())
1165 paint_manager_.InvalidateRect(progress_bar_.rect());
1167 if (is_autoscroll_)
1168 paint_manager_.InvalidateRect(autoscroll_rect_);
1170 if (show_page_indicator_) {
1171 page_indicator_.set_current_page(GetPageNumberToDisplay());
1172 page_indicator_.Splash();
1175 if (page_indicator_.visible())
1176 paint_manager_.InvalidateRect(page_indicator_.rect());
1178 // Run the scroll callback asynchronously. This function can be invoked by a
1179 // layout change which should not re-enter into JS synchronously.
1180 pp::CompletionCallback callback =
1181 callback_factory_.NewCallback(&Instance::RunCallback,
1182 on_scroll_callback_);
1183 pp::Module::Get()->core()->CallOnMainThread(0, callback);
1186 void Instance::ScrollToX(int position) {
1187 if (!h_scrollbar_.get()) {
1188 NOTREACHED();
1189 return;
1191 int position_dip = static_cast<int>(position / device_scale_);
1192 h_scrollbar_->SetValue(position_dip);
1195 void Instance::ScrollToY(int position) {
1196 if (!v_scrollbar_.get()) {
1197 NOTREACHED();
1198 return;
1200 int position_dip = static_cast<int>(position / device_scale_);
1201 v_scrollbar_->SetValue(ClipToRange(position_dip, 0, valid_v_range_));
1204 void Instance::ScrollToPage(int page) {
1205 if (!v_scrollbar_.get())
1206 return;
1208 if (engine_->GetNumberOfPages() == 0)
1209 return;
1211 int index = ClipToRange(page, 0, engine_->GetNumberOfPages() - 1);
1212 pp::Rect rect = engine_->GetPageRect(index);
1213 // If we are trying to scroll pass the last page,
1214 // scroll to the end of the last page.
1215 int position = index < page ? rect.bottom() : rect.y();
1216 ScrollToY(position * zoom_ * device_scale_);
1219 void Instance::NavigateTo(const std::string& url, bool open_in_new_tab) {
1220 std::string url_copy(url);
1222 // Empty |url_copy| is ok, and will effectively be a reload.
1223 // Skip the code below so an empty URL does not turn into "http://", which
1224 // will cause GURL to fail a DCHECK.
1225 if (!url_copy.empty()) {
1226 // If |url_copy| starts with '#', then it's for the same URL with a
1227 // different URL fragment.
1228 if (url_copy[0] == '#') {
1229 // if '#' is already present in |url_| then remove old fragment and add
1230 // new |url_copy| fragment.
1231 std::size_t index = url_.find('#');
1232 if (index != std::string::npos)
1233 url_copy = url_.substr(0, index) + url_copy;
1234 else
1235 url_copy = url_ + url_copy;
1236 // Changing the href does not actually do anything when navigating in the
1237 // same tab, so do the actual page scroll here. Then fall through so the
1238 // href gets updated.
1239 if (!open_in_new_tab) {
1240 int page_number = GetInitialPage(url_copy);
1241 if (page_number >= 0)
1242 ScrollToPage(page_number);
1245 // If there's no scheme, add http.
1246 if (url_copy.find("://") == std::string::npos &&
1247 url_copy.find("mailto:") == std::string::npos) {
1248 url_copy = "http://" + url_copy;
1250 // Make sure |url_copy| starts with a valid scheme.
1251 if (url_copy.find("http://") != 0 &&
1252 url_copy.find("https://") != 0 &&
1253 url_copy.find("ftp://") != 0 &&
1254 url_copy.find("file://") != 0 &&
1255 url_copy.find("mailto:") != 0) {
1256 return;
1258 // Make sure |url_copy| is not only a scheme.
1259 if (url_copy == "http://" ||
1260 url_copy == "https://" ||
1261 url_copy == "ftp://" ||
1262 url_copy == "file://" ||
1263 url_copy == "mailto:") {
1264 return;
1267 if (open_in_new_tab) {
1268 GetWindowObject().Call("open", url_copy);
1269 } else {
1270 GetWindowObject().GetProperty("top").GetProperty("location").
1271 SetProperty("href", url_copy);
1275 void Instance::UpdateCursor(PP_CursorType_Dev cursor) {
1276 if (cursor == cursor_)
1277 return;
1278 cursor_ = cursor;
1280 const PPB_CursorControl_Dev* cursor_interface =
1281 reinterpret_cast<const PPB_CursorControl_Dev*>(
1282 pp::Module::Get()->GetBrowserInterface(PPB_CURSOR_CONTROL_DEV_INTERFACE));
1283 if (!cursor_interface) {
1284 NOTREACHED();
1285 return;
1288 cursor_interface->SetCursor(
1289 pp_instance(), cursor_, pp::ImageData().pp_resource(), NULL);
1292 void Instance::UpdateTickMarks(const std::vector<pp::Rect>& tickmarks) {
1293 if (!v_scrollbar_.get())
1294 return;
1296 float inverse_scale = 1.0f / device_scale_;
1297 std::vector<pp::Rect> scaled_tickmarks = tickmarks;
1298 for (size_t i = 0; i < scaled_tickmarks.size(); i++) {
1299 ScaleRect(inverse_scale, &scaled_tickmarks[i]);
1302 v_scrollbar_->SetTickMarks(
1303 scaled_tickmarks.empty() ? NULL : &scaled_tickmarks[0], tickmarks.size());
1306 void Instance::NotifyNumberOfFindResultsChanged(int total, bool final_result) {
1307 NumberOfFindResultsChanged(total, final_result);
1310 void Instance::NotifySelectedFindResultChanged(int current_find_index) {
1311 DCHECK_GE(current_find_index, 0);
1312 SelectedFindResultChanged(current_find_index);
1315 void Instance::OnEvent(uint32 control_id, uint32 event_id, void* data) {
1316 if (event_id == Button::EVENT_ID_BUTTON_CLICKED ||
1317 event_id == Button::EVENT_ID_BUTTON_STATE_CHANGED) {
1318 switch (control_id) {
1319 case kFitToPageButtonId:
1320 UserMetricsRecordAction("PDF.FitToPageButton");
1321 SetZoom(ZOOM_FIT_TO_PAGE, 0);
1322 ZoomChanged(zoom_);
1323 break;
1324 case kFitToWidthButtonId:
1325 UserMetricsRecordAction("PDF.FitToWidthButton");
1326 SetZoom(ZOOM_FIT_TO_WIDTH, 0);
1327 ZoomChanged(zoom_);
1328 break;
1329 case kZoomOutButtonId:
1330 case kZoomInButtonId:
1331 UserMetricsRecordAction(control_id == kZoomOutButtonId ?
1332 "PDF.ZoomOutButton" : "PDF.ZoomInButton");
1333 SetZoom(ZOOM_SCALE, CalculateZoom(control_id));
1334 ZoomChanged(zoom_);
1335 break;
1336 case kSaveButtonId:
1337 UserMetricsRecordAction("PDF.SaveButton");
1338 SaveAs();
1339 break;
1340 case kPrintButtonId:
1341 UserMetricsRecordAction("PDF.PrintButton");
1342 Print();
1343 break;
1346 if (control_id == kThumbnailsId &&
1347 event_id == ThumbnailControl::EVENT_ID_THUMBNAIL_SELECTED) {
1348 int page = *static_cast<int*>(data);
1349 pp::Rect page_rc(engine_->GetPageRect(page));
1350 ScrollToY(static_cast<int>(page_rc.y() * zoom_ * device_scale_));
1354 void Instance::Invalidate(uint32 control_id, const pp::Rect& rc) {
1355 paint_manager_.InvalidateRect(rc);
1358 uint32 Instance::ScheduleTimer(uint32 control_id, uint32 timeout_ms) {
1359 current_timer_id_++;
1360 pp::CompletionCallback callback =
1361 timer_factory_.NewCallback(&Instance::OnControlTimerFired,
1362 control_id,
1363 current_timer_id_);
1364 pp::Module::Get()->core()->CallOnMainThread(timeout_ms, callback);
1365 return current_timer_id_;
1368 void Instance::SetEventCapture(uint32 control_id, bool set_capture) {
1369 // TODO(gene): set event capture here.
1372 void Instance::SetCursor(uint32 control_id, PP_CursorType_Dev cursor_type) {
1373 UpdateCursor(cursor_type);
1376 pp::Instance* Instance::GetInstance() {
1377 return this;
1380 void Instance::GetDocumentPassword(
1381 pp::CompletionCallbackWithOutput<pp::Var> callback) {
1382 std::string message(GetLocalizedString(PP_RESOURCESTRING_PDFGETPASSWORD));
1383 pp::Var result = pp::PDF::ModalPromptForPassword(this, message);
1384 *callback.output() = result.pp_var();
1385 callback.Run(PP_OK);
1388 void Instance::Alert(const std::string& message) {
1389 GetWindowObject().Call("alert", message);
1392 bool Instance::Confirm(const std::string& message) {
1393 pp::Var result = GetWindowObject().Call("confirm", message);
1394 return result.is_bool() ? result.AsBool() : false;
1397 std::string Instance::Prompt(const std::string& question,
1398 const std::string& default_answer) {
1399 pp::Var result = GetWindowObject().Call("prompt", question, default_answer);
1400 return result.is_string() ? result.AsString() : std::string();
1403 std::string Instance::GetURL() {
1404 return url_;
1407 void Instance::Email(const std::string& to,
1408 const std::string& cc,
1409 const std::string& bcc,
1410 const std::string& subject,
1411 const std::string& body) {
1412 std::string javascript =
1413 "var href = 'mailto:" + net::EscapeUrlEncodedData(to, false) +
1414 "?cc=" + net::EscapeUrlEncodedData(cc, false) +
1415 "&bcc=" + net::EscapeUrlEncodedData(bcc, false) +
1416 "&subject=" + net::EscapeUrlEncodedData(subject, false) +
1417 "&body=" + net::EscapeUrlEncodedData(body, false) +
1418 "';var temp = window.open(href, '_blank', " +
1419 "'width=1,height=1');if(temp) temp.close();";
1420 ExecuteScript(javascript);
1423 void Instance::Print() {
1424 if (!printing_enabled_ ||
1425 (!engine_->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY) &&
1426 !engine_->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY))) {
1427 return;
1430 pp::CompletionCallback callback =
1431 callback_factory_.NewCallback(&Instance::OnPrint);
1432 pp::Module::Get()->core()->CallOnMainThread(0, callback);
1435 void Instance::OnPrint(int32_t) {
1436 pp::PDF::Print(this);
1439 void Instance::SaveAs() {
1440 pp::PDF::SaveAs(this);
1443 void Instance::SubmitForm(const std::string& url,
1444 const void* data,
1445 int length) {
1446 pp::URLRequestInfo request(this);
1447 request.SetURL(url);
1448 request.SetMethod("POST");
1449 request.AppendDataToBody(reinterpret_cast<const char*>(data), length);
1451 pp::CompletionCallback callback =
1452 form_factory_.NewCallback(&Instance::FormDidOpen);
1453 form_loader_ = CreateURLLoaderInternal();
1454 int rv = form_loader_.Open(request, callback);
1455 if (rv != PP_OK_COMPLETIONPENDING)
1456 callback.Run(rv);
1459 void Instance::FormDidOpen(int32_t result) {
1460 // TODO: inform the user of success/failure.
1461 if (result != PP_OK) {
1462 NOTREACHED();
1466 std::string Instance::ShowFileSelectionDialog() {
1467 // Seems like very low priority to implement, since the pdf has no way to get
1468 // the file data anyways. Javascript doesn't let you do this synchronously.
1469 NOTREACHED();
1470 return std::string();
1473 pp::URLLoader Instance::CreateURLLoader() {
1474 if (full_) {
1475 if (!did_call_start_loading_) {
1476 did_call_start_loading_ = true;
1477 pp::PDF::DidStartLoading(this);
1480 // Disable save and print until the document is fully loaded, since they
1481 // would generate an incomplete document. Need to do this each time we
1482 // call DidStartLoading since that resets the content restrictions.
1483 pp::PDF::SetContentRestriction(this, CONTENT_RESTRICTION_SAVE |
1484 CONTENT_RESTRICTION_PRINT);
1487 return CreateURLLoaderInternal();
1490 void Instance::ScheduleCallback(int id, int delay_in_ms) {
1491 pp::CompletionCallback callback =
1492 timer_factory_.NewCallback(&Instance::OnClientTimerFired);
1493 pp::Module::Get()->core()->CallOnMainThread(delay_in_ms, callback, id);
1496 void Instance::SearchString(const base::char16* string,
1497 const base::char16* term,
1498 bool case_sensitive,
1499 std::vector<SearchStringResult>* results) {
1500 if (!pp::PDF::IsAvailable()) {
1501 NOTREACHED();
1502 return;
1505 PP_PrivateFindResult* pp_results;
1506 int count = 0;
1507 pp::PDF::SearchString(
1508 this,
1509 reinterpret_cast<const unsigned short*>(string),
1510 reinterpret_cast<const unsigned short*>(term),
1511 case_sensitive,
1512 &pp_results,
1513 &count);
1515 results->resize(count);
1516 for (int i = 0; i < count; ++i) {
1517 (*results)[i].start_index = pp_results[i].start_index;
1518 (*results)[i].length = pp_results[i].length;
1521 pp::Memory_Dev memory;
1522 memory.MemFree(pp_results);
1525 void Instance::DocumentPaintOccurred() {
1526 if (painted_first_page_)
1527 return;
1529 painted_first_page_ = true;
1530 UpdateToolbarPosition(false);
1531 toolbar_->Splash(kToolbarSplashTimeoutMs);
1533 if (engine_->GetNumberOfPages() > 1)
1534 show_page_indicator_ = true;
1535 else
1536 show_page_indicator_ = false;
1538 if (v_scrollbar_.get() && show_page_indicator_) {
1539 page_indicator_.set_current_page(GetPageNumberToDisplay());
1540 page_indicator_.Splash(kToolbarSplashTimeoutMs,
1541 kPageIndicatorInitialFadeTimeoutMs);
1545 void Instance::DocumentLoadComplete(int page_count) {
1546 // Clear focus state for OSK.
1547 FormTextFieldFocusChange(false);
1549 // Update progress control.
1550 if (progress_bar_.visible())
1551 progress_bar_.Fade(false, kProgressFadeTimeoutMs);
1553 DCHECK(document_load_state_ == LOAD_STATE_LOADING);
1554 document_load_state_ = LOAD_STATE_COMPLETE;
1555 UserMetricsRecordAction("PDF.LoadSuccess");
1557 if (did_call_start_loading_) {
1558 pp::PDF::DidStopLoading(this);
1559 did_call_start_loading_ = false;
1562 if (on_load_callback_.is_string())
1563 ExecuteScript(on_load_callback_);
1564 // Note: If we are in print preview mode on_load_callback_ might call
1565 // ScrollTo{X|Y}() and we don't want to scroll again and override it.
1566 // #page=N is not supported in Print Preview.
1567 if (!IsPrintPreview()) {
1568 int initial_page = GetInitialPage(url_);
1569 if (initial_page >= 0)
1570 ScrollToPage(initial_page);
1573 if (!full_)
1574 return;
1575 if (!pp::PDF::IsAvailable())
1576 return;
1578 int content_restrictions =
1579 CONTENT_RESTRICTION_CUT | CONTENT_RESTRICTION_PASTE;
1580 if (!engine_->HasPermission(PDFEngine::PERMISSION_COPY))
1581 content_restrictions |= CONTENT_RESTRICTION_COPY;
1583 if (!engine_->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY) &&
1584 !engine_->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY)) {
1585 printing_enabled_ = false;
1586 if (current_tb_info_ == kPDFToolbarButtons) {
1587 // Remove Print button.
1588 CreateToolbar(kPDFNoPrintToolbarButtons,
1589 arraysize(kPDFNoPrintToolbarButtons));
1590 UpdateToolbarPosition(false);
1591 Invalidate(pp::Rect(plugin_size_));
1595 pp::PDF::SetContentRestriction(this, content_restrictions);
1597 pp::PDF::HistogramPDFPageCount(this, page_count);
1600 void Instance::RotateClockwise() {
1601 engine_->RotateClockwise();
1604 void Instance::RotateCounterclockwise() {
1605 engine_->RotateCounterclockwise();
1608 bool Instance::IsMouseOnScrollbar(const pp::InputEvent& event) {
1609 pp::MouseInputEvent mouse_event(event);
1610 if (mouse_event.is_null())
1611 return false;
1613 pp::Point pt = mouse_event.GetPosition();
1614 pp::Rect temp;
1615 if ((v_scrollbar_.get() && v_scrollbar_->GetLocation(&temp) &&
1616 temp.Contains(pt)) ||
1617 (h_scrollbar_.get() && h_scrollbar_->GetLocation(&temp) &&
1618 temp.Contains(pt))) {
1619 return true;
1621 return false;
1624 void Instance::PreviewDocumentLoadComplete() {
1625 if (preview_document_load_state_ != LOAD_STATE_LOADING ||
1626 preview_pages_info_.empty()) {
1627 return;
1630 preview_document_load_state_ = LOAD_STATE_COMPLETE;
1632 int dest_page_index = preview_pages_info_.front().second;
1633 int src_page_index =
1634 ExtractPrintPreviewPageIndex(preview_pages_info_.front().first);
1635 if (src_page_index > 0 && dest_page_index > -1 && preview_engine_.get())
1636 engine_->AppendPage(preview_engine_.get(), dest_page_index);
1638 preview_pages_info_.pop();
1639 // |print_preview_page_count_| is not updated yet. Do not load any
1640 // other preview pages till we get this information.
1641 if (print_preview_page_count_ == 0)
1642 return;
1644 if (preview_pages_info_.size())
1645 LoadAvailablePreviewPage();
1648 void Instance::DocumentLoadFailed() {
1649 DCHECK(document_load_state_ == LOAD_STATE_LOADING);
1650 UserMetricsRecordAction("PDF.LoadFailure");
1652 // Hide progress control.
1653 progress_bar_.Fade(false, kProgressFadeTimeoutMs);
1655 if (did_call_start_loading_) {
1656 pp::PDF::DidStopLoading(this);
1657 did_call_start_loading_ = false;
1660 document_load_state_ = LOAD_STATE_FAILED;
1661 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
1664 void Instance::PreviewDocumentLoadFailed() {
1665 UserMetricsRecordAction("PDF.PreviewDocumentLoadFailure");
1666 if (preview_document_load_state_ != LOAD_STATE_LOADING ||
1667 preview_pages_info_.empty()) {
1668 return;
1671 preview_document_load_state_ = LOAD_STATE_FAILED;
1672 preview_pages_info_.pop();
1674 if (preview_pages_info_.size())
1675 LoadAvailablePreviewPage();
1678 pp::Instance* Instance::GetPluginInstance() {
1679 return GetInstance();
1682 void Instance::DocumentHasUnsupportedFeature(const std::string& feature) {
1683 std::string metric("PDF_Unsupported_");
1684 metric += feature;
1685 if (!unsupported_features_reported_.count(metric)) {
1686 unsupported_features_reported_.insert(metric);
1687 UserMetricsRecordAction(metric);
1690 // Since we use an info bar, only do this for full frame plugins..
1691 if (!full_)
1692 return;
1694 if (told_browser_about_unsupported_feature_)
1695 return;
1696 told_browser_about_unsupported_feature_ = true;
1698 pp::PDF::HasUnsupportedFeature(this);
1701 void Instance::DocumentLoadProgress(uint32 available, uint32 doc_size) {
1702 double progress = 0.0;
1703 if (doc_size == 0) {
1704 // Document size is unknown. Use heuristics.
1705 // We'll make progress logarithmic from 0 to 100M.
1706 static const double kFactor = log(100000000.0) / 100.0;
1707 if (available > 0) {
1708 progress = log(static_cast<double>(available)) / kFactor;
1709 if (progress > 100.0)
1710 progress = 100.0;
1712 } else {
1713 progress = 100.0 * static_cast<double>(available) / doc_size;
1715 progress_bar_.SetProgress(progress);
1718 void Instance::FormTextFieldFocusChange(bool in_focus) {
1719 if (!text_input_.get())
1720 return;
1721 if (in_focus)
1722 text_input_->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_TEXT);
1723 else
1724 text_input_->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_NONE);
1727 // Called by PDFScriptableObject.
1728 bool Instance::HasScriptableMethod(const pp::Var& method, pp::Var* exception) {
1729 std::string method_str = method.AsString();
1730 return (method_str == kJSAccessibility ||
1731 method_str == kJSDocumentLoadComplete ||
1732 method_str == kJSGetHeight ||
1733 method_str == kJSGetHorizontalScrollbarThickness ||
1734 method_str == kJSGetPageLocationNormalized ||
1735 method_str == kJSGetSelectedText ||
1736 method_str == kJSGetVerticalScrollbarThickness ||
1737 method_str == kJSGetWidth ||
1738 method_str == kJSGetZoomLevel ||
1739 method_str == kJSGoToPage ||
1740 method_str == kJSGrayscale ||
1741 method_str == kJSLoadPreviewPage ||
1742 method_str == kJSOnLoad ||
1743 method_str == kJSOnPluginSizeChanged ||
1744 method_str == kJSOnScroll ||
1745 method_str == kJSPageXOffset ||
1746 method_str == kJSPageYOffset ||
1747 method_str == kJSPrintPreviewPageCount ||
1748 method_str == kJSReload ||
1749 method_str == kJSRemovePrintButton ||
1750 method_str == kJSResetPrintPreviewUrl ||
1751 method_str == kJSSendKeyEvent ||
1752 method_str == kJSSetPageNumbers ||
1753 method_str == kJSSetPageXOffset ||
1754 method_str == kJSSetPageYOffset ||
1755 method_str == kJSSetZoomLevel ||
1756 method_str == kJSZoomFitToHeight ||
1757 method_str == kJSZoomFitToWidth ||
1758 method_str == kJSZoomIn ||
1759 method_str == kJSZoomOut);
1762 pp::Var Instance::CallScriptableMethod(const pp::Var& method,
1763 const std::vector<pp::Var>& args,
1764 pp::Var* exception) {
1765 std::string method_str = method.AsString();
1766 if (method_str == kJSGrayscale) {
1767 if (args.size() == 1 && args[0].is_bool()) {
1768 engine_->SetGrayscale(args[0].AsBool());
1769 // Redraw
1770 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
1771 #ifdef ENABLE_THUMBNAILS
1772 if (thumbnails_.visible())
1773 thumbnails_.Show(true, true);
1774 #endif
1775 return pp::Var(true);
1777 return pp::Var(false);
1779 if (method_str == kJSOnLoad) {
1780 if (args.size() == 1 && args[0].is_string()) {
1781 on_load_callback_ = args[0];
1782 return pp::Var(true);
1784 return pp::Var(false);
1786 if (method_str == kJSOnScroll) {
1787 if (args.size() == 1 && args[0].is_string()) {
1788 on_scroll_callback_ = args[0];
1789 return pp::Var(true);
1791 return pp::Var(false);
1793 if (method_str == kJSOnPluginSizeChanged) {
1794 if (args.size() == 1 && args[0].is_string()) {
1795 on_plugin_size_changed_callback_ = args[0];
1796 return pp::Var(true);
1798 return pp::Var(false);
1800 if (method_str == kJSReload) {
1801 document_load_state_ = LOAD_STATE_LOADING;
1802 if (!full_)
1803 LoadUrl(url_);
1804 preview_engine_.reset();
1805 print_preview_page_count_ = 0;
1806 engine_.reset(PDFEngine::Create(this));
1807 engine_->New(url_.c_str());
1808 #ifdef ENABLE_THUMBNAILS
1809 thumbnails_.ResetEngine(engine_.get());
1810 #endif
1811 return pp::Var();
1813 if (method_str == kJSResetPrintPreviewUrl) {
1814 if (args.size() == 1 && args[0].is_string()) {
1815 url_ = args[0].AsString();
1816 preview_pages_info_ = std::queue<PreviewPageInfo>();
1817 preview_document_load_state_ = LOAD_STATE_COMPLETE;
1819 return pp::Var();
1821 if (method_str == kJSZoomFitToHeight) {
1822 SetZoom(ZOOM_FIT_TO_PAGE, 0);
1823 return pp::Var();
1825 if (method_str == kJSZoomFitToWidth) {
1826 SetZoom(ZOOM_FIT_TO_WIDTH, 0);
1827 return pp::Var();
1829 if (method_str == kJSZoomIn) {
1830 SetZoom(ZOOM_SCALE, CalculateZoom(kZoomInButtonId));
1831 return pp::Var();
1833 if (method_str == kJSZoomOut) {
1834 SetZoom(ZOOM_SCALE, CalculateZoom(kZoomOutButtonId));
1835 return pp::Var();
1837 if (method_str == kJSSetZoomLevel) {
1838 if (args.size() == 1 && args[0].is_number())
1839 SetZoom(ZOOM_SCALE, args[0].AsDouble());
1840 return pp::Var();
1842 if (method_str == kJSGetZoomLevel) {
1843 return pp::Var(zoom_);
1845 if (method_str == kJSGetHeight) {
1846 return pp::Var(plugin_size_.height());
1848 if (method_str == kJSGetWidth) {
1849 return pp::Var(plugin_size_.width());
1851 if (method_str == kJSGetHorizontalScrollbarThickness) {
1852 return pp::Var(
1853 h_scrollbar_.get() ? GetScrollbarReservedThickness() : 0);
1855 if (method_str == kJSGetVerticalScrollbarThickness) {
1856 return pp::Var(
1857 v_scrollbar_.get() ? GetScrollbarReservedThickness() : 0);
1859 if (method_str == kJSGetSelectedText) {
1860 return GetSelectedText(false);
1862 if (method_str == kJSDocumentLoadComplete) {
1863 return pp::Var((document_load_state_ != LOAD_STATE_LOADING));
1865 if (method_str == kJSPageYOffset) {
1866 return pp::Var(static_cast<int32_t>(
1867 v_scrollbar_.get() ? v_scrollbar_->GetValue() : 0));
1869 if (method_str == kJSSetPageYOffset) {
1870 if (args.size() == 1 && args[0].is_number() && v_scrollbar_.get())
1871 ScrollToY(GetScaled(args[0].AsInt()));
1872 return pp::Var();
1874 if (method_str == kJSPageXOffset) {
1875 return pp::Var(static_cast<int32_t>(
1876 h_scrollbar_.get() ? h_scrollbar_->GetValue() : 0));
1878 if (method_str == kJSSetPageXOffset) {
1879 if (args.size() == 1 && args[0].is_number() && h_scrollbar_.get())
1880 ScrollToX(GetScaled(args[0].AsInt()));
1881 return pp::Var();
1883 if (method_str == kJSRemovePrintButton) {
1884 CreateToolbar(kPrintPreviewToolbarButtons,
1885 arraysize(kPrintPreviewToolbarButtons));
1886 UpdateToolbarPosition(false);
1887 Invalidate(pp::Rect(plugin_size_));
1888 return pp::Var();
1890 if (method_str == kJSGoToPage) {
1891 if (args.size() == 1 && args[0].is_string()) {
1892 ScrollToPage(atoi(args[0].AsString().c_str()));
1894 return pp::Var();
1896 if (method_str == kJSAccessibility) {
1897 if (args.size() == 0) {
1898 base::DictionaryValue node;
1899 node.SetInteger(kAccessibleNumberOfPages, engine_->GetNumberOfPages());
1900 node.SetBoolean(kAccessibleLoaded,
1901 document_load_state_ != LOAD_STATE_LOADING);
1902 bool has_permissions =
1903 engine_->HasPermission(PDFEngine::PERMISSION_COPY) ||
1904 engine_->HasPermission(PDFEngine::PERMISSION_COPY_ACCESSIBLE);
1905 node.SetBoolean(kAccessibleCopyable, has_permissions);
1906 std::string json;
1907 base::JSONWriter::Write(&node, &json);
1908 return pp::Var(json);
1909 } else if (args[0].is_number()) {
1910 return pp::Var(engine_->GetPageAsJSON(args[0].AsInt()));
1913 if (method_str == kJSPrintPreviewPageCount) {
1914 if (args.size() == 1 && args[0].is_number())
1915 SetPrintPreviewMode(args[0].AsInt());
1916 return pp::Var();
1918 if (method_str == kJSLoadPreviewPage) {
1919 if (args.size() == 2 && args[0].is_string() && args[1].is_number())
1920 ProcessPreviewPageInfo(args[0].AsString(), args[1].AsInt());
1921 return pp::Var();
1923 if (method_str == kJSGetPageLocationNormalized) {
1924 const size_t kMaxLength = 30;
1925 char location_info[kMaxLength];
1926 int page_idx = engine_->GetMostVisiblePage();
1927 if (page_idx < 0)
1928 return pp::Var(std::string());
1929 pp::Rect rect = engine_->GetPageContentsRect(page_idx);
1930 int v_scrollbar_reserved_thickness =
1931 v_scrollbar_.get() ? GetScaled(GetScrollbarReservedThickness()) : 0;
1933 rect.set_x(rect.x() + ((plugin_size_.width() -
1934 v_scrollbar_reserved_thickness - available_area_.width()) / 2));
1935 base::snprintf(location_info,
1936 kMaxLength,
1937 "%0.4f;%0.4f;%0.4f;%0.4f;",
1938 rect.x() / static_cast<float>(plugin_size_.width()),
1939 rect.y() / static_cast<float>(plugin_size_.height()),
1940 rect.width() / static_cast<float>(plugin_size_.width()),
1941 rect.height()/ static_cast<float>(plugin_size_.height()));
1942 return pp::Var(std::string(location_info));
1944 if (method_str == kJSSetPageNumbers) {
1945 if (args.size() != 1 || !args[0].is_string())
1946 return pp::Var();
1947 const int num_pages_signed = engine_->GetNumberOfPages();
1948 if (num_pages_signed <= 0)
1949 return pp::Var();
1950 scoped_ptr<base::ListValue> page_ranges(static_cast<base::ListValue*>(
1951 base::JSONReader::Read(args[0].AsString(), false)));
1952 const size_t num_pages = static_cast<size_t>(num_pages_signed);
1953 if (!page_ranges.get() || page_ranges->GetSize() != num_pages)
1954 return pp::Var();
1956 std::vector<int> print_preview_page_numbers;
1957 for (size_t index = 0; index < num_pages; ++index) {
1958 int page_number = 0; // |page_number| is 1-based.
1959 if (!page_ranges->GetInteger(index, &page_number) || page_number < 1)
1960 return pp::Var();
1961 print_preview_page_numbers.push_back(page_number);
1963 print_preview_page_numbers_ = print_preview_page_numbers;
1964 page_indicator_.set_current_page(GetPageNumberToDisplay());
1965 return pp::Var();
1967 // This is here to work around https://bugs.webkit.org/show_bug.cgi?id=16735.
1968 // In JS, creating a synthetic keyboard event and dispatching it always
1969 // result in a keycode of 0.
1970 if (method_str == kJSSendKeyEvent) {
1971 if (args.size() == 1 && args[0].is_number()) {
1972 pp::KeyboardInputEvent event(
1973 this, // instance
1974 PP_INPUTEVENT_TYPE_KEYDOWN, // HandleInputEvent only care about this.
1975 0, // timestamp, not used for kbd events.
1976 0, // no modifiers.
1977 args[0].AsInt(), // keycode.
1978 pp::Var()); // no char text needed.
1979 HandleInputEvent(event);
1982 return pp::Var();
1985 void Instance::OnGeometryChanged(double old_zoom, float old_device_scale) {
1986 bool force_no_horizontal_scrollbar = false;
1987 int scrollbar_thickness = GetScrollbarThickness();
1989 if (old_device_scale != device_scale_) {
1990 // Change in device scale forces us to recreate resources
1991 ConfigureNumberImageGenerator();
1993 CreateToolbar(current_tb_info_, current_tb_info_size_);
1994 // Load autoscroll anchor image.
1995 autoscroll_anchor_ =
1996 CreateResourceImage(PP_RESOURCEIMAGE_PDF_PAN_SCROLL_ICON);
1998 ConfigurePageIndicator();
1999 ConfigureProgressBar();
2001 pp::Point scroll_position = engine_->GetScrollPosition();
2002 ScalePoint(device_scale_ / old_device_scale, &scroll_position);
2003 engine_->SetScrollPosition(scroll_position);
2006 UpdateZoomScale();
2007 if (zoom_ != old_zoom || device_scale_ != old_device_scale)
2008 engine_->ZoomUpdated(zoom_ * device_scale_);
2009 if (zoom_ != old_zoom)
2010 ZoomChanged(zoom_);
2012 available_area_ = pp::Rect(plugin_size_);
2013 if (GetDocumentPixelHeight() > plugin_size_.height()) {
2014 CreateVerticalScrollbar();
2015 } else {
2016 DestroyVerticalScrollbar();
2019 int v_scrollbar_reserved_thickness =
2020 v_scrollbar_.get() ? GetScaled(GetScrollbarReservedThickness()) : 0;
2022 if (!force_no_horizontal_scrollbar &&
2023 GetDocumentPixelWidth() >
2024 (plugin_size_.width() - v_scrollbar_reserved_thickness)) {
2025 CreateHorizontalScrollbar();
2027 // Adding the horizontal scrollbar now might cause us to need vertical
2028 // scrollbars.
2029 if (GetDocumentPixelHeight() >
2030 plugin_size_.height() - GetScaled(GetScrollbarReservedThickness())) {
2031 CreateVerticalScrollbar();
2034 } else {
2035 DestroyHorizontalScrollbar();
2038 #ifdef ENABLE_THUMBNAILS
2039 int thumbnails_pos = 0, thumbnails_total = 0;
2040 #endif
2041 if (v_scrollbar_.get()) {
2042 v_scrollbar_->SetScale(device_scale_);
2043 available_area_.set_width(
2044 std::max(0, plugin_size_.width() - v_scrollbar_reserved_thickness));
2046 #ifdef ENABLE_THUMBNAILS
2047 int height = plugin_size_.height();
2048 #endif
2049 int height_dip = plugin_dip_size_.height();
2051 #if defined(OS_MACOSX)
2052 // Before Lion, Mac always had the resize at the bottom. After that, it
2053 // never did.
2054 if ((base::mac::IsOSSnowLeopard() && full_) ||
2055 (base::mac::IsOSLionOrLater() && h_scrollbar_.get())) {
2056 #else
2057 if (h_scrollbar_.get()) {
2058 #endif // defined(OS_MACOSX)
2059 #ifdef ENABLE_THUMBNAILS
2060 height -= GetScaled(GetScrollbarThickness());
2061 #endif
2062 height_dip -= GetScrollbarThickness();
2064 #ifdef ENABLE_THUMBNAILS
2065 int32 doc_height = GetDocumentPixelHeight();
2066 #endif
2067 int32 doc_height_dip =
2068 static_cast<int32>(GetDocumentPixelHeight() / device_scale_);
2069 #if defined(OS_MACOSX)
2070 // On the Mac we always allow room for the resize button (whose width is
2071 // the same as that of the scrollbar) in full mode. However, if there is no
2072 // no horizontal scrollbar, the end of the scrollbar will scroll past the
2073 // end of the document. This is because the scrollbar assumes that its own
2074 // height (in the case of a vscroll bar) is the same as the height of the
2075 // viewport. Since the viewport is actually larger, we compensate by
2076 // adjusting the document height. Similar logic applies below for the
2077 // horizontal scrollbar.
2078 // For example, if the document size is 1000, and the viewport size is 200,
2079 // then the scrollbar position at the end will be 800. In this case the
2080 // viewport is actally 215 (assuming 15 as the scrollbar width) but the
2081 // scrollbar thinks it is 200. We want the scrollbar position at the end to
2082 // be 785. Making the document size 985 achieves this.
2083 if (full_ && !h_scrollbar_.get()) {
2084 #ifdef ENABLE_THUMBNAILS
2085 doc_height -= GetScaled(GetScrollbarThickness());
2086 #endif
2087 doc_height_dip -= GetScrollbarThickness();
2089 #endif // defined(OS_MACOSX)
2091 int32 position;
2092 position = v_scrollbar_->GetValue();
2093 position = static_cast<int>(position * zoom_ / old_zoom);
2094 valid_v_range_ = doc_height_dip - height_dip;
2095 if (position > valid_v_range_)
2096 position = valid_v_range_;
2098 v_scrollbar_->SetValue(position);
2100 PP_Rect loc;
2101 loc.point.x = static_cast<int>(available_area_.right() / device_scale_);
2102 if (IsOverlayScrollbar())
2103 loc.point.x -= scrollbar_thickness;
2104 loc.point.y = 0;
2105 loc.size.width = scrollbar_thickness;
2106 loc.size.height = height_dip;
2107 v_scrollbar_->SetLocation(loc);
2108 v_scrollbar_->SetDocumentSize(doc_height_dip);
2110 #ifdef ENABLE_THUMBNAILS
2111 thumbnails_pos = position;
2112 thumbnails_total = doc_height - height;
2113 #endif
2116 if (h_scrollbar_.get()) {
2117 h_scrollbar_->SetScale(device_scale_);
2118 available_area_.set_height(
2119 std::max(0, plugin_size_.height() -
2120 GetScaled(GetScrollbarReservedThickness())));
2122 int width_dip = plugin_dip_size_.width();
2124 // See note above.
2125 #if defined(OS_MACOSX)
2126 if ((base::mac::IsOSSnowLeopard() && full_) ||
2127 (base::mac::IsOSLionOrLater() && v_scrollbar_.get())) {
2128 #else
2129 if (v_scrollbar_.get()) {
2130 #endif
2131 width_dip -= GetScrollbarThickness();
2133 int32 doc_width_dip =
2134 static_cast<int32>(GetDocumentPixelWidth() / device_scale_);
2135 #if defined(OS_MACOSX)
2136 // See comment in the above if (v_scrollbar_.get()) block.
2137 if (full_ && !v_scrollbar_.get())
2138 doc_width_dip -= GetScrollbarThickness();
2139 #endif // defined(OS_MACOSX)
2141 int32 position;
2142 position = h_scrollbar_->GetValue();
2143 position = static_cast<int>(position * zoom_ / old_zoom);
2144 position = std::min(position, doc_width_dip - width_dip);
2146 h_scrollbar_->SetValue(position);
2148 PP_Rect loc;
2149 loc.point.x = 0;
2150 loc.point.y = static_cast<int>(available_area_.bottom() / device_scale_);
2151 if (IsOverlayScrollbar())
2152 loc.point.y -= scrollbar_thickness;
2153 loc.size.width = width_dip;
2154 loc.size.height = scrollbar_thickness;
2155 h_scrollbar_->SetLocation(loc);
2156 h_scrollbar_->SetDocumentSize(doc_width_dip);
2159 int doc_width = GetDocumentPixelWidth();
2160 if (doc_width < available_area_.width()) {
2161 available_area_.Offset((available_area_.width() - doc_width) / 2, 0);
2162 available_area_.set_width(doc_width);
2164 int doc_height = GetDocumentPixelHeight();
2165 if (doc_height < available_area_.height()) {
2166 available_area_.set_height(doc_height);
2169 // We'll invalidate the entire plugin anyways.
2170 UpdateToolbarPosition(false);
2171 UpdateProgressBarPosition(false);
2172 UpdatePageIndicatorPosition(false);
2174 #ifdef ENABLE_THUMBNAILS
2175 // Update thumbnail control position.
2176 thumbnails_.SetPosition(thumbnails_pos, thumbnails_total, false);
2177 pp::Rect thumbnails_rc(plugin_size_.width() - GetScaled(kThumbnailsWidth), 0,
2178 GetScaled(kThumbnailsWidth), plugin_size_.height());
2179 if (v_scrollbar_.get())
2180 thumbnails_rc.Offset(-v_scrollbar_reserved_thickness, 0);
2181 if (h_scrollbar_.get())
2182 thumbnails_rc.Inset(0, 0, 0, v_scrollbar_reserved_thickness);
2183 thumbnails_.SetRect(thumbnails_rc, false);
2184 #endif
2186 CalculateBackgroundParts();
2187 engine_->PageOffsetUpdated(available_area_.point());
2188 engine_->PluginSizeUpdated(available_area_.size());
2190 if (!document_size_.GetArea())
2191 return;
2192 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
2194 // Run the plugin size change callback asynchronously. This function can be
2195 // invoked by a layout change which should not re-enter into JS synchronously.
2196 pp::CompletionCallback callback =
2197 callback_factory_.NewCallback(&Instance::RunCallback,
2198 on_plugin_size_changed_callback_);
2199 pp::Module::Get()->core()->CallOnMainThread(0, callback);
2202 void Instance::RunCallback(int32_t, pp::Var callback) {
2203 if (callback.is_string())
2204 ExecuteScript(callback);
2207 void Instance::CreateHorizontalScrollbar() {
2208 if (h_scrollbar_.get())
2209 return;
2211 h_scrollbar_.reset(new pp::Scrollbar_Dev(this, false));
2214 void Instance::CreateVerticalScrollbar() {
2215 if (v_scrollbar_.get())
2216 return;
2218 v_scrollbar_.reset(new pp::Scrollbar_Dev(this, true));
2221 void Instance::DestroyHorizontalScrollbar() {
2222 if (!h_scrollbar_.get())
2223 return;
2224 if (h_scrollbar_->GetValue())
2225 engine_->ScrolledToXPosition(0);
2226 h_scrollbar_.reset();
2229 void Instance::DestroyVerticalScrollbar() {
2230 if (!v_scrollbar_.get())
2231 return;
2232 if (v_scrollbar_->GetValue())
2233 engine_->ScrolledToYPosition(0);
2234 v_scrollbar_.reset();
2235 page_indicator_.Show(false, true);
2238 int Instance::GetScrollbarThickness() {
2239 if (scrollbar_thickness_ == -1) {
2240 pp::Scrollbar_Dev temp_scrollbar(this, false);
2241 scrollbar_thickness_ = temp_scrollbar.GetThickness();
2242 scrollbar_reserved_thickness_ =
2243 temp_scrollbar.IsOverlay() ? 0 : scrollbar_thickness_;
2246 return scrollbar_thickness_;
2249 int Instance::GetScrollbarReservedThickness() {
2250 GetScrollbarThickness();
2251 return scrollbar_reserved_thickness_;
2254 bool Instance::IsOverlayScrollbar() {
2255 return GetScrollbarReservedThickness() == 0;
2258 void Instance::CreateToolbar(const ToolbarButtonInfo* tb_info, size_t size) {
2259 toolbar_.reset(new FadingControls());
2261 DCHECK(tb_info);
2262 DCHECK(size >= 0);
2264 // Remember the current toolbar information in case we need to recreate the
2265 // images later.
2266 current_tb_info_ = tb_info;
2267 current_tb_info_size_ = size;
2269 int max_height = 0;
2270 pp::Point origin(kToolbarFadingOffsetLeft, kToolbarFadingOffsetTop);
2271 ScalePoint(device_scale_, &origin);
2273 std::list<Button*> buttons;
2274 for (size_t i = 0; i < size; i++) {
2275 Button* btn = new Button;
2276 pp::ImageData normal_face =
2277 CreateResourceImage(tb_info[i].normal);
2278 btn->CreateButton(tb_info[i].id,
2279 origin,
2280 true,
2281 toolbar_.get(),
2282 tb_info[i].style,
2283 normal_face,
2284 CreateResourceImage(tb_info[i].highlighted),
2285 CreateResourceImage(tb_info[i].pressed));
2286 buttons.push_back(btn);
2288 origin += pp::Point(normal_face.size().width(), 0);
2289 max_height = std::max(max_height, normal_face.size().height());
2292 pp::Rect rc_toolbar(0, 0,
2293 origin.x() + GetToolbarRightOffset(),
2294 origin.y() + max_height + GetToolbarBottomOffset());
2295 toolbar_->CreateFadingControls(
2296 kToolbarId, rc_toolbar, false, this, kTransparentAlpha);
2298 std::list<Button*>::iterator iter;
2299 for (iter = buttons.begin(); iter != buttons.end(); ++iter) {
2300 toolbar_->AddControl(*iter);
2304 int Instance::GetToolbarRightOffset() {
2305 int scrollbar_thickness = GetScrollbarThickness();
2306 return GetScaled(kToolbarFadingOffsetRight) + 2 * scrollbar_thickness;
2309 int Instance::GetToolbarBottomOffset() {
2310 int scrollbar_thickness = GetScrollbarThickness();
2311 return GetScaled(kToolbarFadingOffsetBottom) + scrollbar_thickness;
2314 std::vector<pp::ImageData> Instance::GetThumbnailResources() {
2315 std::vector<pp::ImageData> num_images(10);
2316 num_images[0] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_0);
2317 num_images[1] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_1);
2318 num_images[2] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_2);
2319 num_images[3] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_3);
2320 num_images[4] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_4);
2321 num_images[5] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_5);
2322 num_images[6] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_6);
2323 num_images[7] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_7);
2324 num_images[8] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_8);
2325 num_images[9] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_9);
2326 return num_images;
2329 std::vector<pp::ImageData> Instance::GetProgressBarResources(
2330 pp::ImageData* background) {
2331 std::vector<pp::ImageData> result(9);
2332 result[0] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_0);
2333 result[1] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_1);
2334 result[2] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_2);
2335 result[3] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_3);
2336 result[4] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_4);
2337 result[5] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_5);
2338 result[6] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_6);
2339 result[7] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_7);
2340 result[8] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_8);
2341 *background = CreateResourceImage(
2342 PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_BACKGROUND);
2343 return result;
2346 void Instance::CreatePageIndicator(bool always_visible) {
2347 page_indicator_.CreatePageIndicator(kPageIndicatorId, false, this,
2348 number_image_generator(), always_visible);
2349 ConfigurePageIndicator();
2352 void Instance::ConfigurePageIndicator() {
2353 pp::ImageData background =
2354 CreateResourceImage(PP_RESOURCEIMAGE_PDF_PAGE_INDICATOR_BACKGROUND);
2355 page_indicator_.Configure(pp::Point(), background);
2358 void Instance::CreateProgressBar() {
2359 pp::ImageData background;
2360 std::vector<pp::ImageData> images = GetProgressBarResources(&background);
2361 std::string text = GetLocalizedString(PP_RESOURCESTRING_PDFPROGRESSLOADING);
2362 progress_bar_.CreateProgressControl(kProgressBarId, false, this, 0.0,
2363 device_scale_, images, background, text);
2366 void Instance::ConfigureProgressBar() {
2367 pp::ImageData background;
2368 std::vector<pp::ImageData> images = GetProgressBarResources(&background);
2369 progress_bar_.Reconfigure(background, images, device_scale_);
2372 void Instance::CreateThumbnails() {
2373 thumbnails_.CreateThumbnailControl(
2374 kThumbnailsId, pp::Rect(), false, this, engine_.get(),
2375 number_image_generator());
2378 void Instance::LoadUrl(const std::string& url) {
2379 LoadUrlInternal(url, &embed_loader_, &Instance::DidOpen);
2382 void Instance::LoadPreviewUrl(const std::string& url) {
2383 LoadUrlInternal(url, &embed_preview_loader_, &Instance::DidOpenPreview);
2386 void Instance::LoadUrlInternal(const std::string& url, pp::URLLoader* loader,
2387 void (Instance::* method)(int32_t)) {
2388 pp::URLRequestInfo request(this);
2389 request.SetURL(url);
2390 request.SetMethod("GET");
2392 *loader = CreateURLLoaderInternal();
2393 pp::CompletionCallback callback = loader_factory_.NewCallback(method);
2394 int rv = loader->Open(request, callback);
2395 if (rv != PP_OK_COMPLETIONPENDING)
2396 callback.Run(rv);
2399 pp::URLLoader Instance::CreateURLLoaderInternal() {
2400 pp::URLLoader loader(this);
2402 const PPB_URLLoaderTrusted* trusted_interface =
2403 reinterpret_cast<const PPB_URLLoaderTrusted*>(
2404 pp::Module::Get()->GetBrowserInterface(
2405 PPB_URLLOADERTRUSTED_INTERFACE));
2406 if (trusted_interface)
2407 trusted_interface->GrantUniversalAccess(loader.pp_resource());
2408 return loader;
2411 int Instance::GetInitialPage(const std::string& url) {
2412 size_t found_idx = url.find('#');
2413 if (found_idx == std::string::npos)
2414 return -1;
2416 const std::string& ref = url.substr(found_idx + 1);
2417 std::vector<std::string> fragments;
2418 Tokenize(ref, kDelimiters, &fragments);
2420 // Page number to return, zero-based.
2421 int page = -1;
2423 // Handle the case of http://foo.com/bar#NAMEDDEST. This is not explicitly
2424 // mentioned except by example in the Adobe "PDF Open Parameters" document.
2425 if ((fragments.size() == 1) && (fragments[0].find('=') == std::string::npos))
2426 return engine_->GetNamedDestinationPage(fragments[0]);
2428 for (size_t i = 0; i < fragments.size(); ++i) {
2429 std::vector<std::string> key_value;
2430 base::SplitString(fragments[i], '=', &key_value);
2431 if (key_value.size() != 2)
2432 continue;
2433 const std::string& key = key_value[0];
2434 const std::string& value = key_value[1];
2436 if (base::strcasecmp(kPage, key.c_str()) == 0) {
2437 // |page_value| is 1-based.
2438 int page_value = -1;
2439 if (base::StringToInt(value, &page_value) && page_value > 0)
2440 page = page_value - 1;
2441 continue;
2443 if (base::strcasecmp(kNamedDest, key.c_str()) == 0) {
2444 // |page_value| is 0-based.
2445 int page_value = engine_->GetNamedDestinationPage(value);
2446 if (page_value >= 0)
2447 page = page_value;
2448 continue;
2451 return page;
2454 void Instance::UpdateToolbarPosition(bool invalidate) {
2455 pp::Rect ctrl_rc = toolbar_->GetControlsRect();
2456 int min_toolbar_width = ctrl_rc.width() + GetToolbarRightOffset() +
2457 GetScaled(kToolbarFadingOffsetLeft);
2458 int min_toolbar_height = ctrl_rc.width() + GetToolbarBottomOffset() +
2459 GetScaled(kToolbarFadingOffsetBottom);
2461 // Update toolbar position
2462 if (plugin_size_.width() < min_toolbar_width ||
2463 plugin_size_.height() < min_toolbar_height) {
2464 // Disable toolbar if it does not fit on the screen.
2465 toolbar_->Show(false, invalidate);
2466 } else {
2467 pp::Point offset(
2468 plugin_size_.width() - GetToolbarRightOffset() - ctrl_rc.right(),
2469 plugin_size_.height() - GetToolbarBottomOffset() - ctrl_rc.bottom());
2470 toolbar_->MoveBy(offset, invalidate);
2472 int toolbar_width = std::max(plugin_size_.width() / 2, min_toolbar_width);
2473 toolbar_->ExpandLeft(toolbar_width - toolbar_->rect().width());
2474 toolbar_->Show(painted_first_page_, invalidate);
2478 void Instance::UpdateProgressBarPosition(bool invalidate) {
2479 // TODO(gene): verify we don't overlap with toolbar.
2480 int scrollbar_thickness = GetScrollbarThickness();
2481 pp::Point progress_origin(
2482 scrollbar_thickness + GetScaled(kProgressOffsetLeft),
2483 plugin_size_.height() - progress_bar_.rect().height() -
2484 scrollbar_thickness - GetScaled(kProgressOffsetBottom));
2485 progress_bar_.MoveTo(progress_origin, invalidate);
2488 void Instance::UpdatePageIndicatorPosition(bool invalidate) {
2489 int32 doc_height = static_cast<int>(document_size_.height() * zoom_);
2490 pp::Point origin(
2491 plugin_size_.width() - page_indicator_.rect().width() -
2492 GetScaled(GetScrollbarReservedThickness()),
2493 page_indicator_.GetYPosition(engine_->GetVerticalScrollbarYPosition(),
2494 doc_height, plugin_size_.height()));
2495 page_indicator_.MoveTo(origin, invalidate);
2498 void Instance::SetZoom(ZoomMode zoom_mode, double scale) {
2499 double old_zoom = zoom_;
2501 zoom_mode_ = zoom_mode;
2502 if (zoom_mode_ == ZOOM_SCALE)
2503 zoom_ = scale;
2504 UpdateZoomScale();
2506 engine_->ZoomUpdated(zoom_ * device_scale_);
2507 OnGeometryChanged(old_zoom, device_scale_);
2509 // If fit-to-height, snap to the beginning of the most visible page.
2510 if (zoom_mode_ == ZOOM_FIT_TO_PAGE) {
2511 ScrollToPage(engine_->GetMostVisiblePage());
2514 // Update sticky buttons to the current zoom style.
2515 Button* ftp_btn = static_cast<Button*>(
2516 toolbar_->GetControl(kFitToPageButtonId));
2517 Button* ftw_btn = static_cast<Button*>(
2518 toolbar_->GetControl(kFitToWidthButtonId));
2519 switch (zoom_mode_) {
2520 case ZOOM_FIT_TO_PAGE:
2521 ftp_btn->SetPressedState(true);
2522 ftw_btn->SetPressedState(false);
2523 break;
2524 case ZOOM_FIT_TO_WIDTH:
2525 ftw_btn->SetPressedState(true);
2526 ftp_btn->SetPressedState(false);
2527 break;
2528 default:
2529 ftw_btn->SetPressedState(false);
2530 ftp_btn->SetPressedState(false);
2534 void Instance::UpdateZoomScale() {
2535 switch (zoom_mode_) {
2536 case ZOOM_SCALE:
2537 break; // Keep current scale.
2538 case ZOOM_FIT_TO_PAGE: {
2539 int page_num = engine_->GetFirstVisiblePage();
2540 if (page_num == -1)
2541 break;
2542 pp::Rect rc = engine_->GetPageRect(page_num);
2543 if (!rc.height())
2544 break;
2545 // Calculate fit to width zoom level.
2546 double ftw_zoom = static_cast<double>(plugin_dip_size_.width() -
2547 GetScrollbarReservedThickness()) / document_size_.width();
2548 // Calculate fit to height zoom level. If document will not fit
2549 // horizontally, adjust zoom level to allow space for horizontal
2550 // scrollbar.
2551 double fth_zoom =
2552 static_cast<double>(plugin_dip_size_.height()) / rc.height();
2553 if (fth_zoom * document_size_.width() >
2554 plugin_dip_size_.width() - GetScrollbarReservedThickness())
2555 fth_zoom = static_cast<double>(plugin_dip_size_.height()
2556 - GetScrollbarReservedThickness()) / rc.height();
2557 zoom_ = std::min(ftw_zoom, fth_zoom);
2558 } break;
2559 case ZOOM_FIT_TO_WIDTH:
2560 case ZOOM_AUTO:
2561 if (!document_size_.width())
2562 break;
2563 zoom_ = static_cast<double>(plugin_dip_size_.width() -
2564 GetScrollbarReservedThickness()) / document_size_.width();
2565 if (zoom_mode_ == ZOOM_AUTO && zoom_ > 1.0)
2566 zoom_ = 1.0;
2567 break;
2569 zoom_ = ClipToRange(zoom_, kMinZoom, kMaxZoom);
2572 double Instance::CalculateZoom(uint32 control_id) const {
2573 if (control_id == kZoomInButtonId) {
2574 for (size_t i = 0; i < chrome_page_zoom::kPresetZoomFactorsSize; ++i) {
2575 double current_zoom = chrome_page_zoom::kPresetZoomFactors[i];
2576 if (current_zoom - content::kEpsilon > zoom_)
2577 return current_zoom;
2579 } else {
2580 for (size_t i = chrome_page_zoom::kPresetZoomFactorsSize; i > 0; --i) {
2581 double current_zoom = chrome_page_zoom::kPresetZoomFactors[i - 1];
2582 if (current_zoom + content::kEpsilon < zoom_)
2583 return current_zoom;
2586 return zoom_;
2589 pp::ImageData Instance::CreateResourceImage(PP_ResourceImage image_id) {
2590 pp::ImageData resource_data;
2591 if (hidpi_enabled_) {
2592 resource_data =
2593 pp::PDF::GetResourceImageForScale(this, image_id, device_scale_);
2596 return resource_data.data() ? resource_data
2597 : pp::PDF::GetResourceImage(this, image_id);
2600 std::string Instance::GetLocalizedString(PP_ResourceString id) {
2601 pp::Var rv(pp::PDF::GetLocalizedString(this, id));
2602 if (!rv.is_string())
2603 return std::string();
2605 return rv.AsString();
2608 void Instance::DrawText(const pp::Point& top_center, PP_ResourceString id) {
2609 std::string str(GetLocalizedString(id));
2611 pp::FontDescription_Dev description;
2612 description.set_family(PP_FONTFAMILY_SANSSERIF);
2613 description.set_size(kMessageTextSize * device_scale_);
2614 pp::Font_Dev font(this, description);
2615 int length = font.MeasureSimpleText(str);
2616 pp::Point point(top_center);
2617 point.set_x(point.x() - length / 2);
2618 DCHECK(!image_data_.is_null());
2619 font.DrawSimpleText(&image_data_, str, point, kMessageTextColor);
2622 void Instance::SetPrintPreviewMode(int page_count) {
2623 if (!IsPrintPreview() || page_count <= 0) {
2624 print_preview_page_count_ = 0;
2625 return;
2628 print_preview_page_count_ = page_count;
2629 ScrollToPage(0);
2630 engine_->AppendBlankPages(print_preview_page_count_);
2631 if (preview_pages_info_.size() > 0)
2632 LoadAvailablePreviewPage();
2635 bool Instance::IsPrintPreview() {
2636 return IsPrintPreviewUrl(url_);
2639 int Instance::GetPageNumberToDisplay() {
2640 int page = engine_->GetMostVisiblePage();
2641 if (IsPrintPreview() && !print_preview_page_numbers_.empty()) {
2642 page = ClipToRange<int>(page, 0, print_preview_page_numbers_.size() - 1);
2643 return print_preview_page_numbers_[page];
2645 return page + 1;
2648 void Instance::ProcessPreviewPageInfo(const std::string& url,
2649 int dst_page_index) {
2650 if (!IsPrintPreview() || print_preview_page_count_ < 0)
2651 return;
2653 int src_page_index = ExtractPrintPreviewPageIndex(url);
2654 if (src_page_index < 1)
2655 return;
2657 preview_pages_info_.push(std::make_pair(url, dst_page_index));
2658 LoadAvailablePreviewPage();
2661 void Instance::LoadAvailablePreviewPage() {
2662 if (preview_pages_info_.size() <= 0)
2663 return;
2665 std::string url = preview_pages_info_.front().first;
2666 int dst_page_index = preview_pages_info_.front().second;
2667 int src_page_index = ExtractPrintPreviewPageIndex(url);
2668 if (src_page_index < 1 ||
2669 dst_page_index >= print_preview_page_count_ ||
2670 preview_document_load_state_ == LOAD_STATE_LOADING) {
2671 return;
2674 preview_document_load_state_ = LOAD_STATE_LOADING;
2675 LoadPreviewUrl(url);
2678 void Instance::EnableAutoscroll(const pp::Point& origin) {
2679 if (is_autoscroll_)
2680 return;
2682 pp::Size client_size = plugin_size_;
2683 if (v_scrollbar_.get())
2684 client_size.Enlarge(-GetScrollbarThickness(), 0);
2685 if (h_scrollbar_.get())
2686 client_size.Enlarge(0, -GetScrollbarThickness());
2688 // Do not allow autoscroll if client area is too small.
2689 if (autoscroll_anchor_.size().width() > client_size.width() ||
2690 autoscroll_anchor_.size().height() > client_size.height())
2691 return;
2693 autoscroll_rect_ = pp::Rect(
2694 pp::Point(origin.x() - autoscroll_anchor_.size().width() / 2,
2695 origin.y() - autoscroll_anchor_.size().height() / 2),
2696 autoscroll_anchor_.size());
2698 // Make sure autoscroll anchor is in the client area.
2699 if (autoscroll_rect_.right() > client_size.width()) {
2700 autoscroll_rect_.set_x(
2701 client_size.width() - autoscroll_anchor_.size().width());
2703 if (autoscroll_rect_.bottom() > client_size.height()) {
2704 autoscroll_rect_.set_y(
2705 client_size.height() - autoscroll_anchor_.size().height());
2708 if (autoscroll_rect_.x() < 0)
2709 autoscroll_rect_.set_x(0);
2710 if (autoscroll_rect_.y() < 0)
2711 autoscroll_rect_.set_y(0);
2713 is_autoscroll_ = true;
2714 Invalidate(kAutoScrollId, autoscroll_rect_);
2716 ScheduleTimer(kAutoScrollId, kAutoScrollTimeoutMs);
2719 void Instance::DisableAutoscroll() {
2720 if (is_autoscroll_) {
2721 is_autoscroll_ = false;
2722 Invalidate(kAutoScrollId, autoscroll_rect_);
2726 PP_CursorType_Dev Instance::CalculateAutoscroll(const pp::Point& mouse_pos) {
2727 // Scroll only if mouse pointer is outside of the anchor area.
2728 if (autoscroll_rect_.Contains(mouse_pos)) {
2729 autoscroll_x_ = 0;
2730 autoscroll_y_ = 0;
2731 return PP_CURSORTYPE_MIDDLEPANNING;
2734 // Relative position to the center of anchor area.
2735 pp::Point rel_pos = mouse_pos - autoscroll_rect_.CenterPoint();
2737 // Calculate angle from the X axis. Angle is in range from -pi to pi.
2738 double angle = atan2(static_cast<double>(rel_pos.y()),
2739 static_cast<double>(rel_pos.x()));
2741 autoscroll_x_ = rel_pos.x() * kAutoScrollFactor;
2742 autoscroll_y_ = rel_pos.y() * kAutoScrollFactor;
2744 // Angle is from -pi to pi. Screen Y is increasing toward bottom,
2745 // so negative angle represent north direction.
2746 if (angle < - (M_PI * 7.0 / 8.0)) {
2747 // going west
2748 return PP_CURSORTYPE_WESTPANNING;
2749 } else if (angle < - (M_PI * 5.0 / 8.0)) {
2750 // going north-west
2751 return PP_CURSORTYPE_NORTHWESTPANNING;
2752 } else if (angle < - (M_PI * 3.0 / 8.0)) {
2753 // going north.
2754 return PP_CURSORTYPE_NORTHPANNING;
2755 } else if (angle < - (M_PI * 1.0 / 8.0)) {
2756 // going north-east
2757 return PP_CURSORTYPE_NORTHEASTPANNING;
2758 } else if (angle < M_PI * 1.0 / 8.0) {
2759 // going east.
2760 return PP_CURSORTYPE_EASTPANNING;
2761 } else if (angle < M_PI * 3.0 / 8.0) {
2762 // going south-east
2763 return PP_CURSORTYPE_SOUTHEASTPANNING;
2764 } else if (angle < M_PI * 5.0 / 8.0) {
2765 // going south.
2766 return PP_CURSORTYPE_SOUTHPANNING;
2767 } else if (angle < M_PI * 7.0 / 8.0) {
2768 // going south-west
2769 return PP_CURSORTYPE_SOUTHWESTPANNING;
2772 // went around the circle, going west again
2773 return PP_CURSORTYPE_WESTPANNING;
2776 void Instance::ConfigureNumberImageGenerator() {
2777 std::vector<pp::ImageData> num_images = GetThumbnailResources();
2778 pp::ImageData number_background = CreateResourceImage(
2779 PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_NUM_BACKGROUND);
2780 number_image_generator_->Configure(number_background,
2781 num_images,
2782 device_scale_);
2785 NumberImageGenerator* Instance::number_image_generator() {
2786 if (!number_image_generator_.get()) {
2787 number_image_generator_.reset(new NumberImageGenerator(this));
2788 ConfigureNumberImageGenerator();
2790 return number_image_generator_.get();
2793 int Instance::GetScaled(int x) const {
2794 return static_cast<int>(x * device_scale_);
2797 void Instance::UserMetricsRecordAction(const std::string& action) {
2798 pp::PDF::UserMetricsRecordAction(this, pp::Var(action));
2801 PDFScriptableObject::PDFScriptableObject(Instance* instance)
2802 : instance_(instance) {
2805 PDFScriptableObject::~PDFScriptableObject() {
2808 bool PDFScriptableObject::HasMethod(const pp::Var& name, pp::Var* exception) {
2809 return instance_->HasScriptableMethod(name, exception);
2812 pp::Var PDFScriptableObject::Call(const pp::Var& method,
2813 const std::vector<pp::Var>& args,
2814 pp::Var* exception) {
2815 return instance_->CallScriptableMethod(method, args, exception);
2818 } // namespace chrome_pdf