chromeos: Move some network related UI in ui/chromeos/
[chromium-blink-merge.git] / pdf / instance.cc
blob9dee0f6aaeca5f3b2ff101085ac9a8f92e2ac5bb
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 kJSGetVerticalScrollbarThickness[] = "getVerticalScrollbarThickness";
80 const char kJSGetWidth[] = "getWidth";
81 const char kJSGetZoomLevel[] = "getZoomLevel";
82 const char kJSGoToPage[] = "goToPage";
83 const char kJSGrayscale[] = "grayscale";
84 const char kJSLoadPreviewPage[] = "loadPreviewPage";
85 const char kJSOnLoad[] = "onload";
86 const char kJSOnPluginSizeChanged[] = "onPluginSizeChanged";
87 const char kJSOnScroll[] = "onScroll";
88 const char kJSPageXOffset[] = "pageXOffset";
89 const char kJSPageYOffset[] = "pageYOffset";
90 const char kJSPrintPreviewPageCount[] = "printPreviewPageCount";
91 const char kJSReload[] = "reload";
92 const char kJSRemovePrintButton[] = "removePrintButton";
93 const char kJSResetPrintPreviewUrl[] = "resetPrintPreviewUrl";
94 const char kJSSendKeyEvent[] = "sendKeyEvent";
95 const char kJSSetPageNumbers[] = "setPageNumbers";
96 const char kJSSetPageXOffset[] = "setPageXOffset";
97 const char kJSSetPageYOffset[] = "setPageYOffset";
98 const char kJSSetZoomLevel[] = "setZoomLevel";
99 const char kJSZoomFitToHeight[] = "fitToHeight";
100 const char kJSZoomFitToWidth[] = "fitToWidth";
101 const char kJSZoomIn[] = "zoomIn";
102 const char kJSZoomOut[] = "zoomOut";
104 // URL reference parameters.
105 // For more possible parameters, see RFC 3778 and the "PDF Open Parameters"
106 // document from Adobe.
107 const char kDelimiters[] = "#&";
108 const char kNamedDest[] = "nameddest";
109 const char kPage[] = "page";
111 const char kChromePrint[] = "chrome://print/";
113 // Dictionary Value key names for the document accessibility info
114 const char kAccessibleNumberOfPages[] = "numberOfPages";
115 const char kAccessibleLoaded[] = "loaded";
116 const char kAccessibleCopyable[] = "copyable";
118 const ToolbarButtonInfo kPDFToolbarButtons[] = {
119 { kFitToPageButtonId, Button::BUTTON_STATE,
120 PP_RESOURCEIMAGE_PDF_BUTTON_FTP,
121 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_HOVER,
122 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_PRESSED },
123 { kFitToWidthButtonId, Button::BUTTON_STATE,
124 PP_RESOURCEIMAGE_PDF_BUTTON_FTW,
125 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_HOVER,
126 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_PRESSED },
127 { kZoomOutButtonId, Button::BUTTON_CLICKABLE,
128 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT,
129 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_HOVER,
130 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_PRESSED },
131 { kZoomInButtonId, Button::BUTTON_CLICKABLE,
132 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN,
133 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_HOVER,
134 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_PRESSED },
135 { kSaveButtonId, Button::BUTTON_CLICKABLE,
136 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE,
137 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE_HOVER,
138 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE_PRESSED },
139 { kPrintButtonId, Button::BUTTON_CLICKABLE,
140 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT,
141 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_HOVER,
142 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_PRESSED },
145 const ToolbarButtonInfo kPDFNoPrintToolbarButtons[] = {
146 { kFitToPageButtonId, Button::BUTTON_STATE,
147 PP_RESOURCEIMAGE_PDF_BUTTON_FTP,
148 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_HOVER,
149 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_PRESSED },
150 { kFitToWidthButtonId, Button::BUTTON_STATE,
151 PP_RESOURCEIMAGE_PDF_BUTTON_FTW,
152 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_HOVER,
153 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_PRESSED },
154 { kZoomOutButtonId, Button::BUTTON_CLICKABLE,
155 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT,
156 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_HOVER,
157 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_PRESSED },
158 { kZoomInButtonId, Button::BUTTON_CLICKABLE,
159 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN,
160 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_HOVER,
161 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_PRESSED },
162 { kSaveButtonId, Button::BUTTON_CLICKABLE,
163 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE,
164 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE_HOVER,
165 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE_PRESSED },
166 { kPrintButtonId, Button::BUTTON_CLICKABLE,
167 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_DISABLED,
168 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_DISABLED,
169 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_DISABLED }
172 const ToolbarButtonInfo kPrintPreviewToolbarButtons[] = {
173 { kFitToPageButtonId, Button::BUTTON_STATE,
174 PP_RESOURCEIMAGE_PDF_BUTTON_FTP,
175 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_HOVER,
176 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_PRESSED },
177 { kFitToWidthButtonId, Button::BUTTON_STATE,
178 PP_RESOURCEIMAGE_PDF_BUTTON_FTW,
179 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_HOVER,
180 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_PRESSED },
181 { kZoomOutButtonId, Button::BUTTON_CLICKABLE,
182 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT,
183 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_HOVER,
184 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_PRESSED },
185 { kZoomInButtonId, Button::BUTTON_CLICKABLE,
186 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_END,
187 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_END_HOVER,
188 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_END_PRESSED },
191 static const char kPPPPdfInterface[] = PPP_PDF_INTERFACE_1;
193 PP_Var GetLinkAtPosition(PP_Instance instance, PP_Point point) {
194 pp::Var var;
195 void* object =
196 pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
197 if (object)
198 var = static_cast<Instance*>(object)->GetLinkAtPosition(pp::Point(point));
199 return var.Detach();
202 void Transform(PP_Instance instance, PP_PrivatePageTransformType type) {
203 void* object =
204 pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
205 if (object) {
206 Instance* obj_instance = static_cast<Instance*>(object);
207 switch (type) {
208 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CW:
209 obj_instance->RotateClockwise();
210 break;
211 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CCW:
212 obj_instance->RotateCounterclockwise();
213 break;
218 const PPP_Pdf ppp_private = {
219 &GetLinkAtPosition,
220 &Transform
223 int ExtractPrintPreviewPageIndex(const std::string& src_url) {
224 // Sample |src_url| format: chrome://print/id/page_index/print.pdf
225 std::vector<std::string> url_substr;
226 base::SplitString(src_url.substr(strlen(kChromePrint)), '/', &url_substr);
227 if (url_substr.size() != 3)
228 return -1;
230 if (url_substr[2] != "print.pdf")
231 return -1;
233 int page_index = 0;
234 if (!base::StringToInt(url_substr[1], &page_index))
235 return -1;
236 return page_index;
239 bool IsPrintPreviewUrl(const std::string& url) {
240 return url.substr(0, strlen(kChromePrint)) == kChromePrint;
243 void ScalePoint(float scale, pp::Point* point) {
244 point->set_x(static_cast<int>(point->x() * scale));
245 point->set_y(static_cast<int>(point->y() * scale));
248 void ScaleRect(float scale, pp::Rect* rect) {
249 int left = static_cast<int>(floorf(rect->x() * scale));
250 int top = static_cast<int>(floorf(rect->y() * scale));
251 int right = static_cast<int>(ceilf((rect->x() + rect->width()) * scale));
252 int bottom = static_cast<int>(ceilf((rect->y() + rect->height()) * scale));
253 rect->SetRect(left, top, right - left, bottom - top);
256 template<class T>
257 T ClipToRange(T value, T lower_boundary, T upper_boundary) {
258 DCHECK(lower_boundary <= upper_boundary);
259 return std::max<T>(lower_boundary, std::min<T>(value, upper_boundary));
262 } // namespace
264 Instance::Instance(PP_Instance instance)
265 : pp::InstancePrivate(instance),
266 pp::Find_Private(this),
267 pp::Printing_Dev(this),
268 pp::Selection_Dev(this),
269 pp::WidgetClient_Dev(this),
270 pp::Zoom_Dev(this),
271 cursor_(PP_CURSORTYPE_POINTER),
272 timer_pending_(false),
273 current_timer_id_(0),
274 zoom_(1.0),
275 device_scale_(1.0),
276 printing_enabled_(true),
277 hidpi_enabled_(false),
278 full_(IsFullFrame()),
279 zoom_mode_(full_ ? ZOOM_AUTO : ZOOM_SCALE),
280 did_call_start_loading_(false),
281 is_autoscroll_(false),
282 scrollbar_thickness_(-1),
283 scrollbar_reserved_thickness_(-1),
284 current_tb_info_(NULL),
285 current_tb_info_size_(0),
286 paint_manager_(this, this, true),
287 delayed_progress_timer_id_(0),
288 first_paint_(true),
289 painted_first_page_(false),
290 show_page_indicator_(false),
291 document_load_state_(LOAD_STATE_LOADING),
292 preview_document_load_state_(LOAD_STATE_COMPLETE),
293 told_browser_about_unsupported_feature_(false),
294 print_preview_page_count_(0) {
295 loader_factory_.Initialize(this);
296 timer_factory_.Initialize(this);
297 form_factory_.Initialize(this);
298 print_callback_factory_.Initialize(this);
299 engine_.reset(PDFEngine::Create(this));
300 pp::Module::Get()->AddPluginInterface(kPPPPdfInterface, &ppp_private);
301 AddPerInstanceObject(kPPPPdfInterface, this);
303 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_MOUSE);
304 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_WHEEL);
305 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_KEYBOARD);
306 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_TOUCH);
309 Instance::~Instance() {
310 RemovePerInstanceObject(kPPPPdfInterface, this);
313 bool Instance::Init(uint32_t argc, const char* argn[], const char* argv[]) {
314 // For now, we hide HiDPI support behind a flag.
315 if (pp::PDF::IsFeatureEnabled(this, PP_PDFFEATURE_HIDPI))
316 hidpi_enabled_ = true;
318 printing_enabled_ = pp::PDF::IsFeatureEnabled(this, PP_PDFFEATURE_PRINTING);
319 if (printing_enabled_) {
320 CreateToolbar(kPDFToolbarButtons, arraysize(kPDFToolbarButtons));
321 } else {
322 CreateToolbar(kPDFNoPrintToolbarButtons,
323 arraysize(kPDFNoPrintToolbarButtons));
326 CreateProgressBar();
328 // Load autoscroll anchor image.
329 autoscroll_anchor_ =
330 CreateResourceImage(PP_RESOURCEIMAGE_PDF_PAN_SCROLL_ICON);
332 #ifdef ENABLE_THUMBNAILS
333 CreateThumbnails();
334 #endif
335 const char* url = NULL;
336 for (uint32_t i = 0; i < argc; ++i) {
337 if (strcmp(argn[i], "src") == 0) {
338 url = argv[i];
339 break;
343 if (!url)
344 return false;
346 CreatePageIndicator(IsPrintPreviewUrl(url));
348 if (!full_) {
349 // For PDFs embedded in a frame, we don't get the data automatically like we
350 // do for full-frame loads. Start loading the data manually.
351 LoadUrl(url);
354 ZoomLimitsChanged(kMinZoom, kMaxZoom);
356 text_input_.reset(new pp::TextInput_Dev(this));
358 url_ = url;
359 return engine_->New(url);
362 bool Instance::HandleDocumentLoad(const pp::URLLoader& loader) {
363 delayed_progress_timer_id_ = ScheduleTimer(kProgressBarId,
364 kProgressDelayTimeoutMs);
365 return engine_->HandleDocumentLoad(loader);
368 bool Instance::HandleInputEvent(const pp::InputEvent& event) {
369 // To simplify things, convert the event into device coordinates if it is
370 // a mouse event.
371 pp::InputEvent event_device_res(event);
373 pp::MouseInputEvent mouse_event(event);
374 if (!mouse_event.is_null()) {
375 pp::Point point = mouse_event.GetPosition();
376 pp::Point movement = mouse_event.GetMovement();
377 ScalePoint(device_scale_, &point);
378 ScalePoint(device_scale_, &movement);
379 mouse_event = pp::MouseInputEvent(
380 this,
381 event.GetType(),
382 event.GetTimeStamp(),
383 event.GetModifiers(),
384 mouse_event.GetButton(),
385 point,
386 mouse_event.GetClickCount(),
387 movement);
388 event_device_res = mouse_event;
392 // Check if we need to go to autoscroll mode.
393 if (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE &&
394 (event.GetModifiers() & PP_INPUTEVENT_MODIFIER_MIDDLEBUTTONDOWN)) {
395 pp::MouseInputEvent mouse_event(event_device_res);
396 pp::Point pos = mouse_event.GetPosition();
397 EnableAutoscroll(pos);
398 UpdateCursor(CalculateAutoscroll(pos));
399 return true;
400 } else {
401 // Quit autoscrolling on any other event.
402 DisableAutoscroll();
405 #ifdef ENABLE_THUMBNAILS
406 if (event.GetType() == PP_INPUTEVENT_TYPE_MOUSELEAVE)
407 thumbnails_.SlideOut();
409 if (thumbnails_.HandleEvent(event_device_res))
410 return true;
411 #endif
413 if (toolbar_->HandleEvent(event_device_res))
414 return true;
416 #ifdef ENABLE_THUMBNAILS
417 if (v_scrollbar_.get() && event.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE) {
418 pp::MouseInputEvent mouse_event(event);
419 pp::Point pt = mouse_event.GetPosition();
420 pp::Rect v_scrollbar_rc;
421 v_scrollbar_->GetLocation(&v_scrollbar_rc);
422 // There is a bug (https://bugs.webkit.org/show_bug.cgi?id=45208)
423 // in the webkit that makes event.u.mouse.button
424 // equal to PP_INPUTEVENT_MOUSEBUTTON_LEFT, even when no button is pressed.
425 // To work around this issue we use modifier for now, and will switch
426 // to button once the bug is fixed and webkit got merged back to our tree.
427 if (v_scrollbar_rc.Contains(pt) &&
428 (event.GetModifiers() & PP_INPUTEVENT_MODIFIER_LEFTBUTTONDOWN)) {
429 thumbnails_.SlideIn();
432 // When scrollbar is in the scrolling mode we should display thumbnails
433 // even the mouse is outside the thumbnail and scrollbar areas.
434 // If mouse is outside plugin area, we are still getting mouse move events
435 // while scrolling. See bug description for details:
436 // http://code.google.com/p/chromium/issues/detail?id=56444
437 if (!v_scrollbar_rc.Contains(pt) && thumbnails_.visible() &&
438 !(event.GetModifiers() & PP_INPUTEVENT_MODIFIER_LEFTBUTTONDOWN) &&
439 !thumbnails_.rect().Contains(pt)) {
440 thumbnails_.SlideOut();
443 #endif
445 // Need to pass the event to the engine first, since if we're over an edit
446 // control we want it to get keyboard events (like space) instead of the
447 // scrollbar.
448 // TODO: will have to offset the mouse coordinates once we support bidi and
449 // there could be scrollbars on the left.
450 pp::InputEvent offset_event(event_device_res);
451 bool try_engine_first = true;
452 switch (offset_event.GetType()) {
453 case PP_INPUTEVENT_TYPE_MOUSEDOWN:
454 case PP_INPUTEVENT_TYPE_MOUSEUP:
455 case PP_INPUTEVENT_TYPE_MOUSEMOVE:
456 case PP_INPUTEVENT_TYPE_MOUSEENTER:
457 case PP_INPUTEVENT_TYPE_MOUSELEAVE: {
458 pp::MouseInputEvent mouse_event(event_device_res);
459 pp::MouseInputEvent mouse_event_dip(event);
460 pp::Point point = mouse_event.GetPosition();
461 point.set_x(point.x() - available_area_.x());
462 offset_event = pp::MouseInputEvent(
463 this,
464 event.GetType(),
465 event.GetTimeStamp(),
466 event.GetModifiers(),
467 mouse_event.GetButton(),
468 point,
469 mouse_event.GetClickCount(),
470 mouse_event.GetMovement());
471 if (!engine_->IsSelecting()) {
472 if (!IsOverlayScrollbar() &&
473 !available_area_.Contains(mouse_event.GetPosition())) {
474 try_engine_first = false;
475 } else if (IsOverlayScrollbar()) {
476 pp::Rect temp;
477 if ((v_scrollbar_.get() && v_scrollbar_->GetLocation(&temp) &&
478 temp.Contains(mouse_event_dip.GetPosition())) ||
479 (h_scrollbar_.get() && h_scrollbar_->GetLocation(&temp) &&
480 temp.Contains(mouse_event_dip.GetPosition()))) {
481 try_engine_first = false;
485 break;
487 default:
488 break;
490 if (try_engine_first && engine_->HandleEvent(offset_event))
491 return true;
493 // Left/Right arrows should scroll to the beginning of the Prev/Next page if
494 // there is no horizontal scroll bar.
495 // If fit-to-height, PgDown/PgUp should scroll to the beginning of the
496 // Prev/Next page.
497 if (v_scrollbar_.get() && event.GetType() == PP_INPUTEVENT_TYPE_KEYDOWN) {
498 pp::KeyboardInputEvent keyboard_event(event);
499 bool page_down =
500 (!h_scrollbar_.get() &&
501 keyboard_event.GetKeyCode() == ui::VKEY_RIGHT) ||
502 (zoom_mode_ == ZOOM_FIT_TO_PAGE &&
503 keyboard_event.GetKeyCode() == ui::VKEY_NEXT);
504 bool page_up =
505 (!h_scrollbar_.get() &&
506 keyboard_event.GetKeyCode() == ui::VKEY_LEFT) ||
507 (zoom_mode_ == ZOOM_FIT_TO_PAGE &&
508 keyboard_event.GetKeyCode() == ui::VKEY_PRIOR);
510 if (page_down) {
511 int page = engine_->GetFirstVisiblePage();
512 // Engine calculates visible page including delimiter to the page size.
513 // We need to check here if the page itself is completely out of view and
514 // scroll to the next one in that case.
515 if (engine_->GetPageRect(page).bottom() * zoom_ <=
516 v_scrollbar_->GetValue())
517 page++;
518 ScrollToPage(page + 1);
519 UpdateCursor(PP_CURSORTYPE_POINTER);
520 return true;
521 } else if (page_up) {
522 int page = engine_->GetFirstVisiblePage();
523 if (engine_->GetPageRect(page).y() * zoom_ >= v_scrollbar_->GetValue())
524 page--;
525 ScrollToPage(page);
526 UpdateCursor(PP_CURSORTYPE_POINTER);
527 return true;
531 if (v_scrollbar_.get() && v_scrollbar_->HandleEvent(event)) {
532 UpdateCursor(PP_CURSORTYPE_POINTER);
533 return true;
536 if (h_scrollbar_.get() && h_scrollbar_->HandleEvent(event)) {
537 UpdateCursor(PP_CURSORTYPE_POINTER);
538 return true;
541 if (timer_pending_ &&
542 (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEUP ||
543 event.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE)) {
544 timer_factory_.CancelAll();
545 timer_pending_ = false;
546 } else if (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE &&
547 engine_->IsSelecting()) {
548 bool set_timer = false;
549 pp::MouseInputEvent mouse_event(event);
550 if (v_scrollbar_.get() &&
551 (mouse_event.GetPosition().y() <= 0 ||
552 mouse_event.GetPosition().y() >= (plugin_dip_size_.height() - 1))) {
553 v_scrollbar_->ScrollBy(
554 PP_SCROLLBY_LINE, mouse_event.GetPosition().y() >= 0 ? 1: -1);
555 set_timer = true;
557 if (h_scrollbar_.get() &&
558 (mouse_event.GetPosition().x() <= 0 ||
559 mouse_event.GetPosition().x() >= (plugin_dip_size_.width() - 1))) {
560 h_scrollbar_->ScrollBy(PP_SCROLLBY_LINE,
561 mouse_event.GetPosition().x() >= 0 ? 1: -1);
562 set_timer = true;
565 if (set_timer) {
566 last_mouse_event_ = pp::MouseInputEvent(event);
568 pp::CompletionCallback callback =
569 timer_factory_.NewCallback(&Instance::OnTimerFired);
570 pp::Module::Get()->core()->CallOnMainThread(kDragTimerMs, callback);
571 timer_pending_ = true;
575 if (event.GetType() == PP_INPUTEVENT_TYPE_KEYDOWN &&
576 event.GetModifiers() & kDefaultKeyModifier) {
577 pp::KeyboardInputEvent keyboard_event(event);
578 switch (keyboard_event.GetKeyCode()) {
579 case 'A':
580 engine_->SelectAll();
581 return true;
585 // Return true for unhandled clicks so the plugin takes focus.
586 return (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN);
589 void Instance::DidChangeView(const pp::View& view) {
590 pp::Rect view_rect(view.GetRect());
591 float device_scale = 1.0f;
592 float old_device_scale = device_scale_;
593 if (hidpi_enabled_)
594 device_scale = view.GetDeviceScale();
595 pp::Size view_device_size(view_rect.width() * device_scale,
596 view_rect.height() * device_scale);
597 if (view_device_size == plugin_size_ && device_scale == device_scale_)
598 return; // We don't care about the position, only the size.
600 image_data_ = pp::ImageData();
601 device_scale_ = device_scale;
602 plugin_dip_size_ = view_rect.size();
603 plugin_size_ = view_device_size;
605 paint_manager_.SetSize(view_device_size, device_scale_);
607 image_data_ = pp::ImageData(this,
608 PP_IMAGEDATAFORMAT_BGRA_PREMUL,
609 plugin_size_,
610 false);
611 if (image_data_.is_null()) {
612 DCHECK(plugin_size_.IsEmpty());
613 return;
616 // View dimensions changed, disable autoscroll (if it was enabled).
617 DisableAutoscroll();
619 OnGeometryChanged(zoom_, old_device_scale);
622 pp::Var Instance::GetInstanceObject() {
623 if (instance_object_.is_undefined()) {
624 PDFScriptableObject* object = new PDFScriptableObject(this);
625 // The pp::Var takes ownership of object here.
626 instance_object_ = pp::VarPrivate(this, object);
629 return instance_object_;
632 pp::Var Instance::GetLinkAtPosition(const pp::Point& point) {
633 pp::Point offset_point(point);
634 ScalePoint(device_scale_, &offset_point);
635 offset_point.set_x(offset_point.x() - available_area_.x());
636 return engine_->GetLinkAtPosition(offset_point);
639 pp::Var Instance::GetSelectedText(bool html) {
640 if (html || !engine_->HasPermission(PDFEngine::PERMISSION_COPY))
641 return pp::Var();
642 return engine_->GetSelectedText();
645 void Instance::InvalidateWidget(pp::Widget_Dev widget,
646 const pp::Rect& dirty_rect) {
647 if (v_scrollbar_.get() && *v_scrollbar_ == widget) {
648 if (!image_data_.is_null())
649 v_scrollbar_->Paint(dirty_rect.pp_rect(), &image_data_);
650 } else if (h_scrollbar_.get() && *h_scrollbar_ == widget) {
651 if (!image_data_.is_null())
652 h_scrollbar_->Paint(dirty_rect.pp_rect(), &image_data_);
653 } else {
654 // Possible to hit this condition since sometimes the scrollbar codes posts
655 // a task to do something later, and we could have deleted our reference in
656 // the meantime.
657 return;
660 pp::Rect dirty_rect_scaled = dirty_rect;
661 ScaleRect(device_scale_, &dirty_rect_scaled);
662 paint_manager_.InvalidateRect(dirty_rect_scaled);
665 void Instance::ScrollbarValueChanged(pp::Scrollbar_Dev scrollbar,
666 uint32_t value) {
667 value = GetScaled(value);
668 if (v_scrollbar_.get() && *v_scrollbar_ == scrollbar) {
669 engine_->ScrolledToYPosition(value);
670 pp::Rect rc;
671 v_scrollbar_->GetLocation(&rc);
672 int32 doc_height = GetDocumentPixelHeight();
673 doc_height -= GetScaled(rc.height());
674 #ifdef ENABLE_THUMBNAILS
675 if (thumbnails_.visible()) {
676 thumbnails_.SetPosition(value, doc_height, true);
678 #endif
679 pp::Point origin(
680 plugin_size_.width() - page_indicator_.rect().width() -
681 GetScaled(GetScrollbarReservedThickness()),
682 page_indicator_.GetYPosition(value, doc_height, plugin_size_.height()));
683 page_indicator_.MoveTo(origin, page_indicator_.visible());
684 } else if (h_scrollbar_.get() && *h_scrollbar_ == scrollbar) {
685 engine_->ScrolledToXPosition(value);
689 void Instance::ScrollbarOverlayChanged(pp::Scrollbar_Dev scrollbar,
690 bool overlay) {
691 scrollbar_reserved_thickness_ = overlay ? 0 : scrollbar_thickness_;
692 OnGeometryChanged(zoom_, device_scale_);
695 uint32_t Instance::QuerySupportedPrintOutputFormats() {
696 return engine_->QuerySupportedPrintOutputFormats();
699 int32_t Instance::PrintBegin(const PP_PrintSettings_Dev& print_settings) {
700 // For us num_pages is always equal to the number of pages in the PDF
701 // document irrespective of the printable area.
702 int32_t ret = engine_->GetNumberOfPages();
703 if (!ret)
704 return 0;
706 uint32_t supported_formats = engine_->QuerySupportedPrintOutputFormats();
707 if ((print_settings.format & supported_formats) == 0)
708 return 0;
710 print_settings_.is_printing = true;
711 print_settings_.pepper_print_settings = print_settings;
712 engine_->PrintBegin();
713 return ret;
716 pp::Resource Instance::PrintPages(
717 const PP_PrintPageNumberRange_Dev* page_ranges,
718 uint32_t page_range_count) {
719 if (!print_settings_.is_printing)
720 return pp::Resource();
722 print_settings_.print_pages_called_ = true;
723 return engine_->PrintPages(page_ranges, page_range_count,
724 print_settings_.pepper_print_settings);
727 void Instance::PrintEnd() {
728 if (print_settings_.print_pages_called_)
729 UserMetricsRecordAction("PDF.PrintPage");
730 print_settings_.Clear();
731 engine_->PrintEnd();
734 bool Instance::IsPrintScalingDisabled() {
735 return !engine_->GetPrintScaling();
738 bool Instance::StartFind(const std::string& text, bool case_sensitive) {
739 engine_->StartFind(text.c_str(), case_sensitive);
740 return true;
743 void Instance::SelectFindResult(bool forward) {
744 engine_->SelectFindResult(forward);
747 void Instance::StopFind() {
748 engine_->StopFind();
751 void Instance::Zoom(double scale, bool text_only) {
752 UserMetricsRecordAction("PDF.ZoomFromBrowser");
753 SetZoom(ZOOM_SCALE, scale);
756 void Instance::ZoomChanged(double factor) {
757 if (full_)
758 Zoom_Dev::ZoomChanged(factor);
761 void Instance::OnPaint(const std::vector<pp::Rect>& paint_rects,
762 std::vector<PaintManager::ReadyRect>* ready,
763 std::vector<pp::Rect>* pending) {
764 if (image_data_.is_null()) {
765 DCHECK(plugin_size_.IsEmpty());
766 return;
768 if (first_paint_) {
769 first_paint_ = false;
770 pp::Rect rect = pp::Rect(pp::Point(), plugin_size_);
771 FillRect(rect, kBackgroundColor);
772 ready->push_back(PaintManager::ReadyRect(rect, image_data_, true));
773 *pending = paint_rects;
774 return;
777 engine_->PrePaint();
779 for (size_t i = 0; i < paint_rects.size(); i++) {
780 // Intersect with plugin area since there could be pending invalidates from
781 // when the plugin area was larger.
782 pp::Rect rect =
783 paint_rects[i].Intersect(pp::Rect(pp::Point(), plugin_size_));
784 if (rect.IsEmpty())
785 continue;
787 pp::Rect pdf_rect = available_area_.Intersect(rect);
788 if (!pdf_rect.IsEmpty()) {
789 pdf_rect.Offset(available_area_.x() * -1, 0);
791 std::vector<pp::Rect> pdf_ready;
792 std::vector<pp::Rect> pdf_pending;
793 engine_->Paint(pdf_rect, &image_data_, &pdf_ready, &pdf_pending);
794 for (size_t j = 0; j < pdf_ready.size(); ++j) {
795 pdf_ready[j].Offset(available_area_.point());
796 ready->push_back(
797 PaintManager::ReadyRect(pdf_ready[j], image_data_, false));
799 for (size_t j = 0; j < pdf_pending.size(); ++j) {
800 pdf_pending[j].Offset(available_area_.point());
801 pending->push_back(pdf_pending[j]);
805 for (size_t j = 0; j < background_parts_.size(); ++j) {
806 pp::Rect intersection = background_parts_[j].location.Intersect(rect);
807 if (!intersection.IsEmpty()) {
808 FillRect(intersection, background_parts_[j].color);
809 ready->push_back(
810 PaintManager::ReadyRect(intersection, image_data_, false));
814 if (document_load_state_ == LOAD_STATE_FAILED) {
815 pp::Point top_center;
816 top_center.set_x(plugin_size_.width() / 2);
817 top_center.set_y(plugin_size_.height() / 2);
818 DrawText(top_center, PP_RESOURCESTRING_PDFLOAD_FAILED);
821 #ifdef ENABLE_THUMBNAILS
822 thumbnails_.Paint(&image_data_, rect);
823 #endif
826 engine_->PostPaint();
828 // Must paint scrollbars after the background parts, in case we have an
829 // overlay scrollbar that's over the background. We also do this in a separate
830 // loop because the scrollbar painting logic uses the signal of whether there
831 // are pending paints or not to figure out if it should draw right away or
832 // not.
833 for (size_t i = 0; i < paint_rects.size(); i++) {
834 PaintIfWidgetIntersects(h_scrollbar_.get(), paint_rects[i], ready, pending);
835 PaintIfWidgetIntersects(v_scrollbar_.get(), paint_rects[i], ready, pending);
838 if (progress_bar_.visible())
839 PaintOverlayControl(&progress_bar_, &image_data_, ready);
841 if (page_indicator_.visible())
842 PaintOverlayControl(&page_indicator_, &image_data_, ready);
844 if (toolbar_->current_transparency() != kTransparentAlpha)
845 PaintOverlayControl(toolbar_.get(), &image_data_, ready);
847 // Paint autoscroll anchor if needed.
848 if (is_autoscroll_) {
849 size_t limit = ready->size();
850 for (size_t i = 0; i < limit; i++) {
851 pp::Rect anchor_rect = autoscroll_rect_.Intersect((*ready)[i].rect);
852 if (!anchor_rect.IsEmpty()) {
853 pp::Rect draw_rc = pp::Rect(
854 pp::Point(anchor_rect.x() - autoscroll_rect_.x(),
855 anchor_rect.y() - autoscroll_rect_.y()),
856 anchor_rect.size());
857 // Paint autoscroll anchor.
858 AlphaBlend(autoscroll_anchor_, draw_rc,
859 &image_data_, anchor_rect.point(), kOpaqueAlpha);
865 void Instance::PaintOverlayControl(
866 Control* ctrl,
867 pp::ImageData* image_data,
868 std::vector<PaintManager::ReadyRect>* ready) {
869 // Make sure that we only paint overlay controls over an area that's ready,
870 // i.e. not pending. Otherwise we'll mark the control rect as ready and
871 // it'll overwrite the pdf region.
872 std::list<pp::Rect> ctrl_rects;
873 for (size_t i = 0; i < ready->size(); i++) {
874 pp::Rect rc = ctrl->rect().Intersect((*ready)[i].rect);
875 if (!rc.IsEmpty())
876 ctrl_rects.push_back(rc);
879 if (!ctrl_rects.empty()) {
880 ctrl->PaintMultipleRects(image_data, ctrl_rects);
882 std::list<pp::Rect>::iterator iter;
883 for (iter = ctrl_rects.begin(); iter != ctrl_rects.end(); ++iter) {
884 ready->push_back(PaintManager::ReadyRect(*iter, *image_data, false));
889 void Instance::DidOpen(int32_t result) {
890 if (result == PP_OK) {
891 engine_->HandleDocumentLoad(embed_loader_);
892 } else if (result != PP_ERROR_ABORTED) { // Can happen in tests.
893 NOTREACHED();
897 void Instance::DidOpenPreview(int32_t result) {
898 if (result == PP_OK) {
899 preview_engine_.reset(PDFEngine::Create(new PreviewModeClient(this)));
900 preview_engine_->HandleDocumentLoad(embed_preview_loader_);
901 } else {
902 NOTREACHED();
906 void Instance::PaintIfWidgetIntersects(
907 pp::Widget_Dev* widget,
908 const pp::Rect& rect,
909 std::vector<PaintManager::ReadyRect>* ready,
910 std::vector<pp::Rect>* pending) {
911 if (!widget)
912 return;
914 pp::Rect location;
915 if (!widget->GetLocation(&location))
916 return;
918 ScaleRect(device_scale_, &location);
919 location = location.Intersect(rect);
920 if (location.IsEmpty())
921 return;
923 if (IsOverlayScrollbar()) {
924 // If we're using overlay scrollbars, and there are pending paints under the
925 // scrollbar, don't update the scrollbar instantly. While it would be nice,
926 // we would need to double buffer the plugin area in order to make this
927 // work. This is because we'd need to always have a copy of what the pdf
928 // under the scrollbar looks like, and additionally we couldn't paint the
929 // pdf under the scrollbar if it's ready until we got the preceding flush.
930 // So in practice, it would make painting slower and introduce extra buffer
931 // copies for the general case.
932 for (size_t i = 0; i < pending->size(); ++i) {
933 if ((*pending)[i].Intersects(location))
934 return;
937 // Even if none of the pending paints are under the scrollbar, we never want
938 // to paint it if it's over the pdf if there are other pending paints.
939 // Otherwise different parts of the pdf plugin would display at different
940 // scroll offsets.
941 if (!pending->empty() && available_area_.Intersects(rect)) {
942 pending->push_back(location);
943 return;
947 pp::Rect location_dip = location;
948 ScaleRect(1.0f / device_scale_, &location_dip);
950 DCHECK(!image_data_.is_null());
951 widget->Paint(location_dip, &image_data_);
953 // Re-scale the rectangle from DIPs to device pixels, so we ensure that we
954 // don't miss any pixels due to rounding outwards in ScaleRect.
955 location = location_dip;
956 ScaleRect(device_scale_, &location);
958 ready->push_back(PaintManager::ReadyRect(location, image_data_, true));
961 void Instance::OnTimerFired(int32_t) {
962 HandleInputEvent(last_mouse_event_);
965 void Instance::OnClientTimerFired(int32_t id) {
966 engine_->OnCallback(id);
969 void Instance::OnControlTimerFired(int32_t,
970 const uint32& control_id,
971 const uint32& timer_id) {
972 if (control_id == toolbar_->id()) {
973 toolbar_->OnTimerFired(timer_id);
974 } else if (control_id == progress_bar_.id()) {
975 if (timer_id == delayed_progress_timer_id_) {
976 if (document_load_state_ == LOAD_STATE_LOADING &&
977 !progress_bar_.visible()) {
978 progress_bar_.Fade(true, kProgressFadeTimeoutMs);
980 delayed_progress_timer_id_ = 0;
981 } else {
982 progress_bar_.OnTimerFired(timer_id);
984 } else if (control_id == kAutoScrollId) {
985 if (is_autoscroll_) {
986 if (autoscroll_x_ != 0 && h_scrollbar_.get()) {
987 h_scrollbar_->ScrollBy(PP_SCROLLBY_PIXEL, autoscroll_x_);
989 if (autoscroll_y_ != 0 && v_scrollbar_.get()) {
990 v_scrollbar_->ScrollBy(PP_SCROLLBY_PIXEL, autoscroll_y_);
993 // Reschedule timer.
994 ScheduleTimer(kAutoScrollId, kAutoScrollTimeoutMs);
996 } else if (control_id == kPageIndicatorId) {
997 page_indicator_.OnTimerFired(timer_id);
999 #ifdef ENABLE_THUMBNAILS
1000 else if (control_id == thumbnails_.id()) {
1001 thumbnails_.OnTimerFired(timer_id);
1003 #endif
1006 void Instance::CalculateBackgroundParts() {
1007 background_parts_.clear();
1008 int v_scrollbar_thickness =
1009 GetScaled(v_scrollbar_.get() ? GetScrollbarReservedThickness() : 0);
1010 int h_scrollbar_thickness =
1011 GetScaled(h_scrollbar_.get() ? GetScrollbarReservedThickness() : 0);
1012 int width_without_scrollbar = std::max(
1013 plugin_size_.width() - v_scrollbar_thickness, 0);
1014 int height_without_scrollbar = std::max(
1015 plugin_size_.height() - h_scrollbar_thickness, 0);
1016 int left_width = available_area_.x();
1017 int right_start = available_area_.right();
1018 int right_width = abs(width_without_scrollbar - available_area_.right());
1019 int bottom = std::min(available_area_.bottom(), height_without_scrollbar);
1021 // Add the left, right, and bottom rectangles. Note: we assume only
1022 // horizontal centering.
1023 BackgroundPart part = {
1024 pp::Rect(0, 0, left_width, bottom),
1025 kBackgroundColor
1027 if (!part.location.IsEmpty())
1028 background_parts_.push_back(part);
1029 part.location = pp::Rect(right_start, 0, right_width, bottom);
1030 if (!part.location.IsEmpty())
1031 background_parts_.push_back(part);
1032 part.location = pp::Rect(
1033 0, bottom, width_without_scrollbar, height_without_scrollbar - bottom);
1034 if (!part.location.IsEmpty())
1035 background_parts_.push_back(part);
1037 if (h_scrollbar_thickness
1038 #if defined(OS_MACOSX)
1040 #else
1042 #endif
1043 v_scrollbar_thickness) {
1044 part.color = 0xFFFFFFFF;
1045 part.location = pp::Rect(plugin_size_.width() - v_scrollbar_thickness,
1046 plugin_size_.height() - h_scrollbar_thickness,
1047 h_scrollbar_thickness,
1048 v_scrollbar_thickness);
1049 background_parts_.push_back(part);
1053 int Instance::GetDocumentPixelWidth() const {
1054 return static_cast<int>(ceil(document_size_.width() * zoom_ * device_scale_));
1057 int Instance::GetDocumentPixelHeight() const {
1058 return static_cast<int>(ceil(document_size_.height() *
1059 zoom_ *
1060 device_scale_));
1063 void Instance::FillRect(const pp::Rect& rect, uint32 color) {
1064 DCHECK(!image_data_.is_null() || rect.IsEmpty());
1065 uint32* buffer_start = static_cast<uint32*>(image_data_.data());
1066 int stride = image_data_.stride();
1067 uint32* ptr = buffer_start + rect.y() * stride / 4 + rect.x();
1068 int height = rect.height();
1069 int width = rect.width();
1070 for (int y = 0; y < height; ++y) {
1071 for (int x = 0; x < width; ++x)
1072 *(ptr + x) = color;
1073 ptr += stride / 4;
1077 void Instance::DocumentSizeUpdated(const pp::Size& size) {
1078 document_size_ = size;
1080 OnGeometryChanged(zoom_, device_scale_);
1083 void Instance::Invalidate(const pp::Rect& rect) {
1084 pp::Rect offset_rect(rect);
1085 offset_rect.Offset(available_area_.point());
1086 paint_manager_.InvalidateRect(offset_rect);
1089 void Instance::Scroll(const pp::Point& point) {
1090 pp::Rect scroll_area = available_area_;
1091 if (IsOverlayScrollbar()) {
1092 pp::Rect rc;
1093 if (h_scrollbar_.get()) {
1094 h_scrollbar_->GetLocation(&rc);
1095 ScaleRect(device_scale_, &rc);
1096 if (scroll_area.bottom() > rc.y()) {
1097 scroll_area.set_height(rc.y() - scroll_area.y());
1098 paint_manager_.InvalidateRect(rc);
1101 if (v_scrollbar_.get()) {
1102 v_scrollbar_->GetLocation(&rc);
1103 ScaleRect(device_scale_, &rc);
1104 if (scroll_area.right() > rc.x()) {
1105 scroll_area.set_width(rc.x() - scroll_area.x());
1106 paint_manager_.InvalidateRect(rc);
1110 paint_manager_.ScrollRect(scroll_area, point);
1112 if (toolbar_->current_transparency() != kTransparentAlpha)
1113 paint_manager_.InvalidateRect(toolbar_->GetControlsRect());
1115 if (progress_bar_.visible())
1116 paint_manager_.InvalidateRect(progress_bar_.rect());
1118 if (is_autoscroll_)
1119 paint_manager_.InvalidateRect(autoscroll_rect_);
1121 if (show_page_indicator_) {
1122 page_indicator_.set_current_page(GetPageNumberToDisplay());
1123 page_indicator_.Splash();
1126 if (page_indicator_.visible())
1127 paint_manager_.InvalidateRect(page_indicator_.rect());
1129 if (on_scroll_callback_.is_string())
1130 ExecuteScript(on_scroll_callback_);
1133 void Instance::ScrollToX(int position) {
1134 if (!h_scrollbar_.get()) {
1135 NOTREACHED();
1136 return;
1138 int position_dip = static_cast<int>(position / device_scale_);
1139 h_scrollbar_->SetValue(position_dip);
1142 void Instance::ScrollToY(int position) {
1143 if (!v_scrollbar_.get()) {
1144 NOTREACHED();
1145 return;
1147 int position_dip = static_cast<int>(position / device_scale_);
1148 v_scrollbar_->SetValue(ClipToRange(position_dip, 0, valid_v_range_));
1151 void Instance::ScrollToPage(int page) {
1152 if (!v_scrollbar_.get())
1153 return;
1155 if (engine_->GetNumberOfPages() == 0)
1156 return;
1158 int index = ClipToRange(page, 0, engine_->GetNumberOfPages() - 1);
1159 pp::Rect rect = engine_->GetPageRect(index);
1160 // If we are trying to scroll pass the last page,
1161 // scroll to the end of the last page.
1162 int position = index < page ? rect.bottom() : rect.y();
1163 ScrollToY(position * zoom_ * device_scale_);
1166 void Instance::NavigateTo(const std::string& url, bool open_in_new_tab) {
1167 std::string url_copy(url);
1169 // Empty |url_copy| is ok, and will effectively be a reload.
1170 // Skip the code below so an empty URL does not turn into "http://", which
1171 // will cause GURL to fail a DCHECK.
1172 if (!url_copy.empty()) {
1173 // If there's no scheme, add http.
1174 if (url_copy.find("://") == std::string::npos &&
1175 url_copy.find("mailto:") == std::string::npos) {
1176 url_copy = std::string("http://") + url_copy;
1178 // Make sure |url_copy| starts with a valid scheme.
1179 if (url_copy.find("http://") != 0 &&
1180 url_copy.find("https://") != 0 &&
1181 url_copy.find("ftp://") != 0 &&
1182 url_copy.find("mailto:") != 0) {
1183 return;
1185 // Make sure |url_copy| is not only a scheme.
1186 if (url_copy == "http://" ||
1187 url_copy == "https://" ||
1188 url_copy == "ftp://" ||
1189 url_copy == "mailto:") {
1190 return;
1193 if (open_in_new_tab) {
1194 GetWindowObject().Call("open", url_copy);
1195 } else {
1196 GetWindowObject().GetProperty("top").GetProperty("location").
1197 SetProperty("href", url_copy);
1201 void Instance::UpdateCursor(PP_CursorType_Dev cursor) {
1202 if (cursor == cursor_)
1203 return;
1204 cursor_ = cursor;
1206 const PPB_CursorControl_Dev* cursor_interface =
1207 reinterpret_cast<const PPB_CursorControl_Dev*>(
1208 pp::Module::Get()->GetBrowserInterface(PPB_CURSOR_CONTROL_DEV_INTERFACE));
1209 if (!cursor_interface) {
1210 NOTREACHED();
1211 return;
1214 cursor_interface->SetCursor(
1215 pp_instance(), cursor_, pp::ImageData().pp_resource(), NULL);
1218 void Instance::UpdateTickMarks(const std::vector<pp::Rect>& tickmarks) {
1219 if (!v_scrollbar_.get())
1220 return;
1222 float inverse_scale = 1.0f / device_scale_;
1223 std::vector<pp::Rect> scaled_tickmarks = tickmarks;
1224 for (size_t i = 0; i < scaled_tickmarks.size(); i++) {
1225 ScaleRect(inverse_scale, &scaled_tickmarks[i]);
1228 v_scrollbar_->SetTickMarks(
1229 scaled_tickmarks.empty() ? NULL : &scaled_tickmarks[0], tickmarks.size());
1232 void Instance::NotifyNumberOfFindResultsChanged(int total, bool final_result) {
1233 NumberOfFindResultsChanged(total, final_result);
1236 void Instance::NotifySelectedFindResultChanged(int current_find_index) {
1237 SelectedFindResultChanged(current_find_index);
1240 void Instance::OnEvent(uint32 control_id, uint32 event_id, void* data) {
1241 if (event_id == Button::EVENT_ID_BUTTON_CLICKED ||
1242 event_id == Button::EVENT_ID_BUTTON_STATE_CHANGED) {
1243 switch (control_id) {
1244 case kFitToPageButtonId:
1245 UserMetricsRecordAction("PDF.FitToPageButton");
1246 SetZoom(ZOOM_FIT_TO_PAGE, 0);
1247 ZoomChanged(zoom_);
1248 break;
1249 case kFitToWidthButtonId:
1250 UserMetricsRecordAction("PDF.FitToWidthButton");
1251 SetZoom(ZOOM_FIT_TO_WIDTH, 0);
1252 ZoomChanged(zoom_);
1253 break;
1254 case kZoomOutButtonId:
1255 case kZoomInButtonId:
1256 UserMetricsRecordAction(control_id == kZoomOutButtonId ?
1257 "PDF.ZoomOutButton" : "PDF.ZoomInButton");
1258 SetZoom(ZOOM_SCALE, CalculateZoom(control_id));
1259 ZoomChanged(zoom_);
1260 break;
1261 case kSaveButtonId:
1262 UserMetricsRecordAction("PDF.SaveButton");
1263 SaveAs();
1264 break;
1265 case kPrintButtonId:
1266 UserMetricsRecordAction("PDF.PrintButton");
1267 Print();
1268 break;
1271 if (control_id == kThumbnailsId &&
1272 event_id == ThumbnailControl::EVENT_ID_THUMBNAIL_SELECTED) {
1273 int page = *static_cast<int*>(data);
1274 pp::Rect page_rc(engine_->GetPageRect(page));
1275 ScrollToY(static_cast<int>(page_rc.y() * zoom_ * device_scale_));
1279 void Instance::Invalidate(uint32 control_id, const pp::Rect& rc) {
1280 paint_manager_.InvalidateRect(rc);
1283 uint32 Instance::ScheduleTimer(uint32 control_id, uint32 timeout_ms) {
1284 current_timer_id_++;
1285 pp::CompletionCallback callback =
1286 timer_factory_.NewCallback(&Instance::OnControlTimerFired,
1287 control_id,
1288 current_timer_id_);
1289 pp::Module::Get()->core()->CallOnMainThread(timeout_ms, callback);
1290 return current_timer_id_;
1293 void Instance::SetEventCapture(uint32 control_id, bool set_capture) {
1294 // TODO(gene): set event capture here.
1297 void Instance::SetCursor(uint32 control_id, PP_CursorType_Dev cursor_type) {
1298 UpdateCursor(cursor_type);
1301 pp::Instance* Instance::GetInstance() {
1302 return this;
1305 void Instance::GetDocumentPassword(
1306 pp::CompletionCallbackWithOutput<pp::Var> callback) {
1307 std::string message(GetLocalizedString(PP_RESOURCESTRING_PDFGETPASSWORD));
1308 pp::Var result = pp::PDF::ModalPromptForPassword(this, message);
1309 *callback.output() = result.pp_var();
1310 callback.Run(PP_OK);
1313 void Instance::Alert(const std::string& message) {
1314 GetWindowObject().Call("alert", message);
1317 bool Instance::Confirm(const std::string& message) {
1318 pp::Var result = GetWindowObject().Call("confirm", message);
1319 return result.is_bool() ? result.AsBool() : false;
1322 std::string Instance::Prompt(const std::string& question,
1323 const std::string& default_answer) {
1324 pp::Var result = GetWindowObject().Call("prompt", question, default_answer);
1325 return result.is_string() ? result.AsString() : std::string();
1328 std::string Instance::GetURL() {
1329 return url_;
1332 void Instance::Email(const std::string& to,
1333 const std::string& cc,
1334 const std::string& bcc,
1335 const std::string& subject,
1336 const std::string& body) {
1337 std::string javascript =
1338 "var href = 'mailto:" + net::EscapeUrlEncodedData(to, false) +
1339 "?cc=" + net::EscapeUrlEncodedData(cc, false) +
1340 "&bcc=" + net::EscapeUrlEncodedData(bcc, false) +
1341 "&subject=" + net::EscapeUrlEncodedData(subject, false) +
1342 "&body=" + net::EscapeUrlEncodedData(body, false) +
1343 "';var temp = window.open(href, '_blank', " +
1344 "'width=1,height=1');if(temp) temp.close();";
1345 ExecuteScript(javascript);
1348 void Instance::Print() {
1349 if (!printing_enabled_ ||
1350 (!engine_->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY) &&
1351 !engine_->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY))) {
1352 return;
1355 pp::CompletionCallback callback =
1356 print_callback_factory_.NewCallback(&Instance::OnPrint);
1357 pp::Module::Get()->core()->CallOnMainThread(0, callback);
1360 void Instance::OnPrint(int32_t) {
1361 pp::PDF::Print(this);
1364 void Instance::SaveAs() {
1365 pp::PDF::SaveAs(this);
1368 void Instance::SubmitForm(const std::string& url,
1369 const void* data,
1370 int length) {
1371 pp::URLRequestInfo request(this);
1372 request.SetURL(url);
1373 request.SetMethod("POST");
1374 request.AppendDataToBody(reinterpret_cast<const char*>(data), length);
1376 pp::CompletionCallback callback =
1377 form_factory_.NewCallback(&Instance::FormDidOpen);
1378 form_loader_ = CreateURLLoaderInternal();
1379 int rv = form_loader_.Open(request, callback);
1380 if (rv != PP_OK_COMPLETIONPENDING)
1381 callback.Run(rv);
1384 void Instance::FormDidOpen(int32_t result) {
1385 // TODO: inform the user of success/failure.
1386 if (result != PP_OK) {
1387 NOTREACHED();
1391 std::string Instance::ShowFileSelectionDialog() {
1392 // Seems like very low priority to implement, since the pdf has no way to get
1393 // the file data anyways. Javascript doesn't let you do this synchronously.
1394 NOTREACHED();
1395 return std::string();
1398 pp::URLLoader Instance::CreateURLLoader() {
1399 if (full_) {
1400 if (!did_call_start_loading_) {
1401 did_call_start_loading_ = true;
1402 pp::PDF::DidStartLoading(this);
1405 // Disable save and print until the document is fully loaded, since they
1406 // would generate an incomplete document. Need to do this each time we
1407 // call DidStartLoading since that resets the content restrictions.
1408 pp::PDF::SetContentRestriction(this, CONTENT_RESTRICTION_SAVE |
1409 CONTENT_RESTRICTION_PRINT);
1412 return CreateURLLoaderInternal();
1415 void Instance::ScheduleCallback(int id, int delay_in_ms) {
1416 pp::CompletionCallback callback =
1417 timer_factory_.NewCallback(&Instance::OnClientTimerFired);
1418 pp::Module::Get()->core()->CallOnMainThread(delay_in_ms, callback, id);
1421 void Instance::SearchString(const base::char16* string,
1422 const base::char16* term,
1423 bool case_sensitive,
1424 std::vector<SearchStringResult>* results) {
1425 if (!pp::PDF::IsAvailable()) {
1426 NOTREACHED();
1427 return;
1430 PP_PrivateFindResult* pp_results;
1431 int count = 0;
1432 pp::PDF::SearchString(
1433 this,
1434 reinterpret_cast<const unsigned short*>(string),
1435 reinterpret_cast<const unsigned short*>(term),
1436 case_sensitive,
1437 &pp_results,
1438 &count);
1440 results->resize(count);
1441 for (int i = 0; i < count; ++i) {
1442 (*results)[i].start_index = pp_results[i].start_index;
1443 (*results)[i].length = pp_results[i].length;
1446 pp::Memory_Dev memory;
1447 memory.MemFree(pp_results);
1450 void Instance::DocumentPaintOccurred() {
1451 if (painted_first_page_)
1452 return;
1454 painted_first_page_ = true;
1455 UpdateToolbarPosition(false);
1456 toolbar_->Splash(kToolbarSplashTimeoutMs);
1458 if (engine_->GetNumberOfPages() > 1)
1459 show_page_indicator_ = true;
1460 else
1461 show_page_indicator_ = false;
1463 if (v_scrollbar_.get() && show_page_indicator_) {
1464 page_indicator_.set_current_page(GetPageNumberToDisplay());
1465 page_indicator_.Splash(kToolbarSplashTimeoutMs,
1466 kPageIndicatorInitialFadeTimeoutMs);
1470 void Instance::DocumentLoadComplete(int page_count) {
1471 // Clear focus state for OSK.
1472 FormTextFieldFocusChange(false);
1474 // Update progress control.
1475 if (progress_bar_.visible())
1476 progress_bar_.Fade(false, kProgressFadeTimeoutMs);
1478 DCHECK(document_load_state_ == LOAD_STATE_LOADING);
1479 document_load_state_ = LOAD_STATE_COMPLETE;
1480 UserMetricsRecordAction("PDF.LoadSuccess");
1481 if (on_load_callback_.is_string())
1482 ExecuteScript(on_load_callback_);
1483 // Note: If we are in print preview mode on_load_callback_ might call
1484 // ScrollTo{X|Y}() and we don't want to scroll again and override it.
1485 // #page=N is not supported in Print Preview.
1486 if (!IsPrintPreview()) {
1487 int initial_page = GetInitialPage(url_);
1488 if (initial_page >= 0)
1489 ScrollToPage(initial_page);
1492 if (!full_)
1493 return;
1494 if (!pp::PDF::IsAvailable())
1495 return;
1497 if (did_call_start_loading_) {
1498 pp::PDF::DidStopLoading(this);
1499 did_call_start_loading_ = false;
1502 int content_restrictions =
1503 CONTENT_RESTRICTION_CUT | CONTENT_RESTRICTION_PASTE;
1504 if (!engine_->HasPermission(PDFEngine::PERMISSION_COPY))
1505 content_restrictions |= CONTENT_RESTRICTION_COPY;
1507 if (!engine_->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY) &&
1508 !engine_->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY)) {
1509 printing_enabled_ = false;
1510 if (current_tb_info_ == kPDFToolbarButtons) {
1511 // Remove Print button.
1512 CreateToolbar(kPDFNoPrintToolbarButtons,
1513 arraysize(kPDFNoPrintToolbarButtons));
1514 UpdateToolbarPosition(false);
1515 Invalidate(pp::Rect(plugin_size_));
1519 pp::PDF::SetContentRestriction(this, content_restrictions);
1521 pp::PDF::HistogramPDFPageCount(this, page_count);
1524 void Instance::RotateClockwise() {
1525 engine_->RotateClockwise();
1528 void Instance::RotateCounterclockwise() {
1529 engine_->RotateCounterclockwise();
1532 void Instance::PreviewDocumentLoadComplete() {
1533 if (preview_document_load_state_ != LOAD_STATE_LOADING ||
1534 preview_pages_info_.empty()) {
1535 return;
1538 preview_document_load_state_ = LOAD_STATE_COMPLETE;
1540 int dest_page_index = preview_pages_info_.front().second;
1541 int src_page_index =
1542 ExtractPrintPreviewPageIndex(preview_pages_info_.front().first);
1543 if (src_page_index > 0 && dest_page_index > -1 && preview_engine_.get())
1544 engine_->AppendPage(preview_engine_.get(), dest_page_index);
1546 preview_pages_info_.pop();
1547 // |print_preview_page_count_| is not updated yet. Do not load any
1548 // other preview pages till we get this information.
1549 if (print_preview_page_count_ == 0)
1550 return;
1552 if (preview_pages_info_.size())
1553 LoadAvailablePreviewPage();
1556 void Instance::DocumentLoadFailed() {
1557 DCHECK(document_load_state_ == LOAD_STATE_LOADING);
1558 UserMetricsRecordAction("PDF.LoadFailure");
1560 // Hide progress control.
1561 progress_bar_.Fade(false, kProgressFadeTimeoutMs);
1563 if (did_call_start_loading_) {
1564 pp::PDF::DidStopLoading(this);
1565 did_call_start_loading_ = false;
1568 document_load_state_ = LOAD_STATE_FAILED;
1569 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
1572 void Instance::PreviewDocumentLoadFailed() {
1573 UserMetricsRecordAction("PDF.PreviewDocumentLoadFailure");
1574 if (preview_document_load_state_ != LOAD_STATE_LOADING ||
1575 preview_pages_info_.empty()) {
1576 return;
1579 preview_document_load_state_ = LOAD_STATE_FAILED;
1580 preview_pages_info_.pop();
1582 if (preview_pages_info_.size())
1583 LoadAvailablePreviewPage();
1586 pp::Instance* Instance::GetPluginInstance() {
1587 return GetInstance();
1590 void Instance::DocumentHasUnsupportedFeature(const std::string& feature) {
1591 std::string metric("PDF_Unsupported_");
1592 metric += feature;
1593 if (!unsupported_features_reported_.count(metric)) {
1594 unsupported_features_reported_.insert(metric);
1595 UserMetricsRecordAction(metric);
1598 // Since we use an info bar, only do this for full frame plugins..
1599 if (!full_)
1600 return;
1602 if (told_browser_about_unsupported_feature_)
1603 return;
1604 told_browser_about_unsupported_feature_ = true;
1606 pp::PDF::HasUnsupportedFeature(this);
1609 void Instance::DocumentLoadProgress(uint32 available, uint32 doc_size) {
1610 double progress = 0.0;
1611 if (doc_size == 0) {
1612 // Document size is unknown. Use heuristics.
1613 // We'll make progress logarithmic from 0 to 100M.
1614 static const double kFactor = log(100000000.0) / 100.0;
1615 if (available > 0) {
1616 progress = log(static_cast<double>(available)) / kFactor;
1617 if (progress > 100.0)
1618 progress = 100.0;
1620 } else {
1621 progress = 100.0 * static_cast<double>(available) / doc_size;
1623 progress_bar_.SetProgress(progress);
1626 void Instance::FormTextFieldFocusChange(bool in_focus) {
1627 if (!text_input_.get())
1628 return;
1629 if (in_focus)
1630 text_input_->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_TEXT);
1631 else
1632 text_input_->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_NONE);
1635 // Called by PDFScriptableObject.
1636 bool Instance::HasScriptableMethod(const pp::Var& method, pp::Var* exception) {
1637 std::string method_str = method.AsString();
1638 return (method_str == kJSAccessibility ||
1639 method_str == kJSDocumentLoadComplete ||
1640 method_str == kJSGetHeight ||
1641 method_str == kJSGetHorizontalScrollbarThickness ||
1642 method_str == kJSGetPageLocationNormalized ||
1643 method_str == kJSGetVerticalScrollbarThickness ||
1644 method_str == kJSGetWidth ||
1645 method_str == kJSGetZoomLevel ||
1646 method_str == kJSGoToPage ||
1647 method_str == kJSGrayscale ||
1648 method_str == kJSLoadPreviewPage ||
1649 method_str == kJSOnLoad ||
1650 method_str == kJSOnPluginSizeChanged ||
1651 method_str == kJSOnScroll ||
1652 method_str == kJSPageXOffset ||
1653 method_str == kJSPageYOffset ||
1654 method_str == kJSPrintPreviewPageCount ||
1655 method_str == kJSReload ||
1656 method_str == kJSRemovePrintButton ||
1657 method_str == kJSResetPrintPreviewUrl ||
1658 method_str == kJSSendKeyEvent ||
1659 method_str == kJSSetPageNumbers ||
1660 method_str == kJSSetPageXOffset ||
1661 method_str == kJSSetPageYOffset ||
1662 method_str == kJSSetZoomLevel ||
1663 method_str == kJSZoomFitToHeight ||
1664 method_str == kJSZoomFitToWidth ||
1665 method_str == kJSZoomIn ||
1666 method_str == kJSZoomOut);
1669 pp::Var Instance::CallScriptableMethod(const pp::Var& method,
1670 const std::vector<pp::Var>& args,
1671 pp::Var* exception) {
1672 std::string method_str = method.AsString();
1673 if (method_str == kJSGrayscale) {
1674 if (args.size() == 1 && args[0].is_bool()) {
1675 engine_->SetGrayscale(args[0].AsBool());
1676 // Redraw
1677 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
1678 #ifdef ENABLE_THUMBNAILS
1679 if (thumbnails_.visible())
1680 thumbnails_.Show(true, true);
1681 #endif
1682 return pp::Var(true);
1684 return pp::Var(false);
1686 if (method_str == kJSOnLoad) {
1687 if (args.size() == 1 && args[0].is_string()) {
1688 on_load_callback_ = args[0];
1689 return pp::Var(true);
1691 return pp::Var(false);
1693 if (method_str == kJSOnScroll) {
1694 if (args.size() == 1 && args[0].is_string()) {
1695 on_scroll_callback_ = args[0];
1696 return pp::Var(true);
1698 return pp::Var(false);
1700 if (method_str == kJSOnPluginSizeChanged) {
1701 if (args.size() == 1 && args[0].is_string()) {
1702 on_plugin_size_changed_callback_ = args[0];
1703 return pp::Var(true);
1705 return pp::Var(false);
1707 if (method_str == kJSReload) {
1708 document_load_state_ = LOAD_STATE_LOADING;
1709 if (!full_)
1710 LoadUrl(url_);
1711 preview_engine_.reset();
1712 print_preview_page_count_ = 0;
1713 engine_.reset(PDFEngine::Create(this));
1714 engine_->New(url_.c_str());
1715 #ifdef ENABLE_THUMBNAILS
1716 thumbnails_.ResetEngine(engine_.get());
1717 #endif
1718 return pp::Var();
1720 if (method_str == kJSResetPrintPreviewUrl) {
1721 if (args.size() == 1 && args[0].is_string()) {
1722 url_ = args[0].AsString();
1723 preview_pages_info_ = std::queue<PreviewPageInfo>();
1724 preview_document_load_state_ = LOAD_STATE_COMPLETE;
1726 return pp::Var();
1728 if (method_str == kJSZoomFitToHeight) {
1729 SetZoom(ZOOM_FIT_TO_PAGE, 0);
1730 return pp::Var();
1732 if (method_str == kJSZoomFitToWidth) {
1733 SetZoom(ZOOM_FIT_TO_WIDTH, 0);
1734 return pp::Var();
1736 if (method_str == kJSZoomIn) {
1737 SetZoom(ZOOM_SCALE, CalculateZoom(kZoomInButtonId));
1738 return pp::Var();
1740 if (method_str == kJSZoomOut) {
1741 SetZoom(ZOOM_SCALE, CalculateZoom(kZoomOutButtonId));
1742 return pp::Var();
1744 if (method_str == kJSSetZoomLevel) {
1745 if (args.size() == 1 && args[0].is_double())
1746 SetZoom(ZOOM_SCALE, args[0].AsDouble());
1747 return pp::Var();
1749 if (method_str == kJSGetZoomLevel) {
1750 return pp::Var(zoom_);
1752 if (method_str == kJSGetHeight) {
1753 return pp::Var(plugin_size_.height());
1755 if (method_str == kJSGetWidth) {
1756 return pp::Var(plugin_size_.width());
1758 if (method_str == kJSGetHorizontalScrollbarThickness) {
1759 return pp::Var(
1760 h_scrollbar_.get() ? GetScrollbarReservedThickness() : 0);
1762 if (method_str == kJSGetVerticalScrollbarThickness) {
1763 return pp::Var(
1764 v_scrollbar_.get() ? GetScrollbarReservedThickness() : 0);
1766 if (method_str == kJSDocumentLoadComplete) {
1767 return pp::Var((document_load_state_ != LOAD_STATE_LOADING));
1769 if (method_str == kJSPageYOffset) {
1770 return pp::Var(static_cast<int32_t>(
1771 v_scrollbar_.get() ? v_scrollbar_->GetValue() : 0));
1773 if (method_str == kJSSetPageYOffset) {
1774 if (args.size() == 1 && args[0].is_number() && v_scrollbar_.get())
1775 ScrollToY(GetScaled(args[0].AsInt()));
1776 return pp::Var();
1778 if (method_str == kJSPageXOffset) {
1779 return pp::Var(static_cast<int32_t>(
1780 h_scrollbar_.get() ? h_scrollbar_->GetValue() : 0));
1782 if (method_str == kJSSetPageXOffset) {
1783 if (args.size() == 1 && args[0].is_number() && h_scrollbar_.get())
1784 ScrollToX(GetScaled(args[0].AsInt()));
1785 return pp::Var();
1787 if (method_str == kJSRemovePrintButton) {
1788 CreateToolbar(kPrintPreviewToolbarButtons,
1789 arraysize(kPrintPreviewToolbarButtons));
1790 UpdateToolbarPosition(false);
1791 Invalidate(pp::Rect(plugin_size_));
1792 return pp::Var();
1794 if (method_str == kJSGoToPage) {
1795 if (args.size() == 1 && args[0].is_string()) {
1796 ScrollToPage(atoi(args[0].AsString().c_str()));
1798 return pp::Var();
1800 if (method_str == kJSAccessibility) {
1801 if (args.size() == 0) {
1802 base::DictionaryValue node;
1803 node.SetInteger(kAccessibleNumberOfPages, engine_->GetNumberOfPages());
1804 node.SetBoolean(kAccessibleLoaded,
1805 document_load_state_ != LOAD_STATE_LOADING);
1806 bool has_permissions =
1807 engine_->HasPermission(PDFEngine::PERMISSION_COPY) ||
1808 engine_->HasPermission(PDFEngine::PERMISSION_COPY_ACCESSIBLE);
1809 node.SetBoolean(kAccessibleCopyable, has_permissions);
1810 std::string json;
1811 base::JSONWriter::Write(&node, &json);
1812 return pp::Var(json);
1813 } else if (args[0].is_number()) {
1814 return pp::Var(engine_->GetPageAsJSON(args[0].AsInt()));
1817 if (method_str == kJSPrintPreviewPageCount) {
1818 if (args.size() == 1 && args[0].is_number())
1819 SetPrintPreviewMode(args[0].AsInt());
1820 return pp::Var();
1822 if (method_str == kJSLoadPreviewPage) {
1823 if (args.size() == 2 && args[0].is_string() && args[1].is_number())
1824 ProcessPreviewPageInfo(args[0].AsString(), args[1].AsInt());
1825 return pp::Var();
1827 if (method_str == kJSGetPageLocationNormalized) {
1828 const size_t kMaxLength = 30;
1829 char location_info[kMaxLength];
1830 int page_idx = engine_->GetMostVisiblePage();
1831 if (page_idx < 0)
1832 return pp::Var(std::string());
1833 pp::Rect rect = engine_->GetPageContentsRect(page_idx);
1834 int v_scrollbar_reserved_thickness =
1835 v_scrollbar_.get() ? GetScaled(GetScrollbarReservedThickness()) : 0;
1837 rect.set_x(rect.x() + ((plugin_size_.width() -
1838 v_scrollbar_reserved_thickness - available_area_.width()) / 2));
1839 base::snprintf(location_info,
1840 kMaxLength,
1841 "%0.4f;%0.4f;%0.4f;%0.4f;",
1842 rect.x() / static_cast<float>(plugin_size_.width()),
1843 rect.y() / static_cast<float>(plugin_size_.height()),
1844 rect.width() / static_cast<float>(plugin_size_.width()),
1845 rect.height()/ static_cast<float>(plugin_size_.height()));
1846 return pp::Var(std::string(location_info));
1848 if (method_str == kJSSetPageNumbers) {
1849 if (args.size() != 1 || !args[0].is_string())
1850 return pp::Var();
1851 const int num_pages_signed = engine_->GetNumberOfPages();
1852 if (num_pages_signed <= 0)
1853 return pp::Var();
1854 scoped_ptr<base::ListValue> page_ranges(static_cast<base::ListValue*>(
1855 base::JSONReader::Read(args[0].AsString(), false)));
1856 const size_t num_pages = static_cast<size_t>(num_pages_signed);
1857 if (!page_ranges.get() || page_ranges->GetSize() != num_pages)
1858 return pp::Var();
1860 std::vector<int> print_preview_page_numbers;
1861 for (size_t index = 0; index < num_pages; ++index) {
1862 int page_number = 0; // |page_number| is 1-based.
1863 if (!page_ranges->GetInteger(index, &page_number) || page_number < 1)
1864 return pp::Var();
1865 print_preview_page_numbers.push_back(page_number);
1867 print_preview_page_numbers_ = print_preview_page_numbers;
1868 page_indicator_.set_current_page(GetPageNumberToDisplay());
1869 return pp::Var();
1871 // This is here to work around https://bugs.webkit.org/show_bug.cgi?id=16735.
1872 // In JS, creating a synthetic keyboard event and dispatching it always
1873 // result in a keycode of 0.
1874 if (method_str == kJSSendKeyEvent) {
1875 if (args.size() == 1 && args[0].is_number()) {
1876 pp::KeyboardInputEvent event(
1877 this, // instance
1878 PP_INPUTEVENT_TYPE_KEYDOWN, // HandleInputEvent only care about this.
1879 0, // timestamp, not used for kbd events.
1880 0, // no modifiers.
1881 args[0].AsInt(), // keycode.
1882 pp::Var()); // no char text needed.
1883 HandleInputEvent(event);
1886 return pp::Var();
1889 void Instance::OnGeometryChanged(double old_zoom, float old_device_scale) {
1890 bool force_no_horizontal_scrollbar = false;
1891 int scrollbar_thickness = GetScrollbarThickness();
1893 if (old_device_scale != device_scale_) {
1894 // Change in device scale forces us to recreate resources
1895 ConfigureNumberImageGenerator();
1897 CreateToolbar(current_tb_info_, current_tb_info_size_);
1898 // Load autoscroll anchor image.
1899 autoscroll_anchor_ =
1900 CreateResourceImage(PP_RESOURCEIMAGE_PDF_PAN_SCROLL_ICON);
1902 ConfigurePageIndicator();
1903 ConfigureProgressBar();
1905 pp::Point scroll_position = engine_->GetScrollPosition();
1906 ScalePoint(device_scale_ / old_device_scale, &scroll_position);
1907 engine_->SetScrollPosition(scroll_position);
1910 UpdateZoomScale();
1911 if (zoom_ != old_zoom || device_scale_ != old_device_scale)
1912 engine_->ZoomUpdated(zoom_ * device_scale_);
1913 if (zoom_ != old_zoom)
1914 ZoomChanged(zoom_);
1916 available_area_ = pp::Rect(plugin_size_);
1917 if (GetDocumentPixelHeight() > plugin_size_.height()) {
1918 CreateVerticalScrollbar();
1919 } else {
1920 DestroyVerticalScrollbar();
1923 int v_scrollbar_reserved_thickness =
1924 v_scrollbar_.get() ? GetScaled(GetScrollbarReservedThickness()) : 0;
1926 if (!force_no_horizontal_scrollbar &&
1927 GetDocumentPixelWidth() >
1928 (plugin_size_.width() - v_scrollbar_reserved_thickness)) {
1929 CreateHorizontalScrollbar();
1931 // Adding the horizontal scrollbar now might cause us to need vertical
1932 // scrollbars.
1933 if (GetDocumentPixelHeight() >
1934 plugin_size_.height() - GetScaled(GetScrollbarReservedThickness())) {
1935 CreateVerticalScrollbar();
1938 } else {
1939 DestroyHorizontalScrollbar();
1942 #ifdef ENABLE_THUMBNAILS
1943 int thumbnails_pos = 0, thumbnails_total = 0;
1944 #endif
1945 if (v_scrollbar_.get()) {
1946 v_scrollbar_->SetScale(device_scale_);
1947 available_area_.set_width(
1948 std::max(0, plugin_size_.width() - v_scrollbar_reserved_thickness));
1950 #ifdef ENABLE_THUMBNAILS
1951 int height = plugin_size_.height();
1952 #endif
1953 int height_dip = plugin_dip_size_.height();
1955 #if defined(OS_MACOSX)
1956 // Before Lion, Mac always had the resize at the bottom. After that, it
1957 // never did.
1958 if ((base::mac::IsOSSnowLeopard() && full_) ||
1959 (base::mac::IsOSLionOrLater() && h_scrollbar_.get())) {
1960 #else
1961 if (h_scrollbar_.get()) {
1962 #endif // defined(OS_MACOSX)
1963 #ifdef ENABLE_THUMBNAILS
1964 height -= GetScaled(GetScrollbarThickness());
1965 #endif
1966 height_dip -= GetScrollbarThickness();
1968 #ifdef ENABLE_THUMBNAILS
1969 int32 doc_height = GetDocumentPixelHeight();
1970 #endif
1971 int32 doc_height_dip =
1972 static_cast<int32>(GetDocumentPixelHeight() / device_scale_);
1973 #if defined(OS_MACOSX)
1974 // On the Mac we always allow room for the resize button (whose width is
1975 // the same as that of the scrollbar) in full mode. However, if there is no
1976 // no horizontal scrollbar, the end of the scrollbar will scroll past the
1977 // end of the document. This is because the scrollbar assumes that its own
1978 // height (in the case of a vscroll bar) is the same as the height of the
1979 // viewport. Since the viewport is actually larger, we compensate by
1980 // adjusting the document height. Similar logic applies below for the
1981 // horizontal scrollbar.
1982 // For example, if the document size is 1000, and the viewport size is 200,
1983 // then the scrollbar position at the end will be 800. In this case the
1984 // viewport is actally 215 (assuming 15 as the scrollbar width) but the
1985 // scrollbar thinks it is 200. We want the scrollbar position at the end to
1986 // be 785. Making the document size 985 achieves this.
1987 if (full_ && !h_scrollbar_.get()) {
1988 #ifdef ENABLE_THUMBNAILS
1989 doc_height -= GetScaled(GetScrollbarThickness());
1990 #endif
1991 doc_height_dip -= GetScrollbarThickness();
1993 #endif // defined(OS_MACOSX)
1995 int32 position;
1996 position = v_scrollbar_->GetValue();
1997 position = static_cast<int>(position * zoom_ / old_zoom);
1998 valid_v_range_ = doc_height_dip - height_dip;
1999 if (position > valid_v_range_)
2000 position = valid_v_range_;
2002 v_scrollbar_->SetValue(position);
2004 PP_Rect loc;
2005 loc.point.x = static_cast<int>(available_area_.right() / device_scale_);
2006 if (IsOverlayScrollbar())
2007 loc.point.x -= scrollbar_thickness;
2008 loc.point.y = 0;
2009 loc.size.width = scrollbar_thickness;
2010 loc.size.height = height_dip;
2011 v_scrollbar_->SetLocation(loc);
2012 v_scrollbar_->SetDocumentSize(doc_height_dip);
2014 #ifdef ENABLE_THUMBNAILS
2015 thumbnails_pos = position;
2016 thumbnails_total = doc_height - height;
2017 #endif
2020 if (h_scrollbar_.get()) {
2021 h_scrollbar_->SetScale(device_scale_);
2022 available_area_.set_height(
2023 std::max(0, plugin_size_.height() -
2024 GetScaled(GetScrollbarReservedThickness())));
2026 int width_dip = plugin_dip_size_.width();
2028 // See note above.
2029 #if defined(OS_MACOSX)
2030 if ((base::mac::IsOSSnowLeopard() && full_) ||
2031 (base::mac::IsOSLionOrLater() && v_scrollbar_.get())) {
2032 #else
2033 if (v_scrollbar_.get()) {
2034 #endif
2035 width_dip -= GetScrollbarThickness();
2037 int32 doc_width_dip =
2038 static_cast<int32>(GetDocumentPixelWidth() / device_scale_);
2039 #if defined(OS_MACOSX)
2040 // See comment in the above if (v_scrollbar_.get()) block.
2041 if (full_ && !v_scrollbar_.get())
2042 doc_width_dip -= GetScrollbarThickness();
2043 #endif // defined(OS_MACOSX)
2045 int32 position;
2046 position = h_scrollbar_->GetValue();
2047 position = static_cast<int>(position * zoom_ / old_zoom);
2048 position = std::min(position, doc_width_dip - width_dip);
2050 h_scrollbar_->SetValue(position);
2052 PP_Rect loc;
2053 loc.point.x = 0;
2054 loc.point.y = static_cast<int>(available_area_.bottom() / device_scale_);
2055 if (IsOverlayScrollbar())
2056 loc.point.y -= scrollbar_thickness;
2057 loc.size.width = width_dip;
2058 loc.size.height = scrollbar_thickness;
2059 h_scrollbar_->SetLocation(loc);
2060 h_scrollbar_->SetDocumentSize(doc_width_dip);
2063 int doc_width = GetDocumentPixelWidth();
2064 if (doc_width < available_area_.width()) {
2065 available_area_.Offset((available_area_.width() - doc_width) / 2, 0);
2066 available_area_.set_width(doc_width);
2068 int doc_height = GetDocumentPixelHeight();
2069 if (doc_height < available_area_.height()) {
2070 available_area_.set_height(doc_height);
2073 // We'll invalidate the entire plugin anyways.
2074 UpdateToolbarPosition(false);
2075 UpdateProgressBarPosition(false);
2076 UpdatePageIndicatorPosition(false);
2078 #ifdef ENABLE_THUMBNAILS
2079 // Update thumbnail control position.
2080 thumbnails_.SetPosition(thumbnails_pos, thumbnails_total, false);
2081 pp::Rect thumbnails_rc(plugin_size_.width() - GetScaled(kThumbnailsWidth), 0,
2082 GetScaled(kThumbnailsWidth), plugin_size_.height());
2083 if (v_scrollbar_.get())
2084 thumbnails_rc.Offset(-v_scrollbar_reserved_thickness, 0);
2085 if (h_scrollbar_.get())
2086 thumbnails_rc.Inset(0, 0, 0, v_scrollbar_reserved_thickness);
2087 thumbnails_.SetRect(thumbnails_rc, false);
2088 #endif
2090 CalculateBackgroundParts();
2091 engine_->PageOffsetUpdated(available_area_.point());
2092 engine_->PluginSizeUpdated(available_area_.size());
2094 if (!document_size_.GetArea())
2095 return;
2096 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
2098 if (on_plugin_size_changed_callback_.is_string())
2099 ExecuteScript(on_plugin_size_changed_callback_);
2102 void Instance::CreateHorizontalScrollbar() {
2103 if (h_scrollbar_.get())
2104 return;
2106 h_scrollbar_.reset(new pp::Scrollbar_Dev(this, false));
2109 void Instance::CreateVerticalScrollbar() {
2110 if (v_scrollbar_.get())
2111 return;
2113 v_scrollbar_.reset(new pp::Scrollbar_Dev(this, true));
2116 void Instance::DestroyHorizontalScrollbar() {
2117 if (!h_scrollbar_.get())
2118 return;
2119 if (h_scrollbar_->GetValue())
2120 engine_->ScrolledToXPosition(0);
2121 h_scrollbar_.reset();
2124 void Instance::DestroyVerticalScrollbar() {
2125 if (!v_scrollbar_.get())
2126 return;
2127 if (v_scrollbar_->GetValue())
2128 engine_->ScrolledToYPosition(0);
2129 v_scrollbar_.reset();
2130 page_indicator_.Show(false, true);
2133 int Instance::GetScrollbarThickness() {
2134 if (scrollbar_thickness_ == -1) {
2135 pp::Scrollbar_Dev temp_scrollbar(this, false);
2136 scrollbar_thickness_ = temp_scrollbar.GetThickness();
2137 scrollbar_reserved_thickness_ =
2138 temp_scrollbar.IsOverlay() ? 0 : scrollbar_thickness_;
2141 return scrollbar_thickness_;
2144 int Instance::GetScrollbarReservedThickness() {
2145 GetScrollbarThickness();
2146 return scrollbar_reserved_thickness_;
2149 bool Instance::IsOverlayScrollbar() {
2150 return GetScrollbarReservedThickness() == 0;
2153 void Instance::CreateToolbar(const ToolbarButtonInfo* tb_info, size_t size) {
2154 toolbar_.reset(new FadingControls());
2156 DCHECK(tb_info);
2157 DCHECK(size >= 0);
2159 // Remember the current toolbar information in case we need to recreate the
2160 // images later.
2161 current_tb_info_ = tb_info;
2162 current_tb_info_size_ = size;
2164 int max_height = 0;
2165 pp::Point origin(kToolbarFadingOffsetLeft, kToolbarFadingOffsetTop);
2166 ScalePoint(device_scale_, &origin);
2168 std::list<Button*> buttons;
2169 for (size_t i = 0; i < size; i++) {
2170 Button* btn = new Button;
2171 pp::ImageData normal_face =
2172 CreateResourceImage(tb_info[i].normal);
2173 btn->CreateButton(tb_info[i].id,
2174 origin,
2175 true,
2176 toolbar_.get(),
2177 tb_info[i].style,
2178 normal_face,
2179 CreateResourceImage(tb_info[i].highlighted),
2180 CreateResourceImage(tb_info[i].pressed));
2181 buttons.push_back(btn);
2183 origin += pp::Point(normal_face.size().width(), 0);
2184 max_height = std::max(max_height, normal_face.size().height());
2187 pp::Rect rc_toolbar(0, 0,
2188 origin.x() + GetToolbarRightOffset(),
2189 origin.y() + max_height + GetToolbarBottomOffset());
2190 toolbar_->CreateFadingControls(
2191 kToolbarId, rc_toolbar, false, this, kTransparentAlpha);
2193 std::list<Button*>::iterator iter;
2194 for (iter = buttons.begin(); iter != buttons.end(); ++iter) {
2195 toolbar_->AddControl(*iter);
2199 int Instance::GetToolbarRightOffset() {
2200 int scrollbar_thickness = GetScrollbarThickness();
2201 return GetScaled(kToolbarFadingOffsetRight) + 2 * scrollbar_thickness;
2204 int Instance::GetToolbarBottomOffset() {
2205 int scrollbar_thickness = GetScrollbarThickness();
2206 return GetScaled(kToolbarFadingOffsetBottom) + scrollbar_thickness;
2209 std::vector<pp::ImageData> Instance::GetThumbnailResources() {
2210 std::vector<pp::ImageData> num_images(10);
2211 num_images[0] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_0);
2212 num_images[1] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_1);
2213 num_images[2] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_2);
2214 num_images[3] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_3);
2215 num_images[4] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_4);
2216 num_images[5] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_5);
2217 num_images[6] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_6);
2218 num_images[7] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_7);
2219 num_images[8] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_8);
2220 num_images[9] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_9);
2221 return num_images;
2224 std::vector<pp::ImageData> Instance::GetProgressBarResources(
2225 pp::ImageData* background) {
2226 std::vector<pp::ImageData> result(9);
2227 result[0] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_0);
2228 result[1] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_1);
2229 result[2] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_2);
2230 result[3] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_3);
2231 result[4] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_4);
2232 result[5] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_5);
2233 result[6] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_6);
2234 result[7] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_7);
2235 result[8] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_8);
2236 *background = CreateResourceImage(
2237 PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_BACKGROUND);
2238 return result;
2241 void Instance::CreatePageIndicator(bool always_visible) {
2242 page_indicator_.CreatePageIndicator(kPageIndicatorId, false, this,
2243 number_image_generator(), always_visible);
2244 ConfigurePageIndicator();
2247 void Instance::ConfigurePageIndicator() {
2248 pp::ImageData background =
2249 CreateResourceImage(PP_RESOURCEIMAGE_PDF_PAGE_INDICATOR_BACKGROUND);
2250 page_indicator_.Configure(pp::Point(), background);
2253 void Instance::CreateProgressBar() {
2254 pp::ImageData background;
2255 std::vector<pp::ImageData> images = GetProgressBarResources(&background);
2256 std::string text = GetLocalizedString(PP_RESOURCESTRING_PDFPROGRESSLOADING);
2257 progress_bar_.CreateProgressControl(kProgressBarId, false, this, 0.0,
2258 device_scale_, images, background, text);
2261 void Instance::ConfigureProgressBar() {
2262 pp::ImageData background;
2263 std::vector<pp::ImageData> images = GetProgressBarResources(&background);
2264 progress_bar_.Reconfigure(background, images, device_scale_);
2267 void Instance::CreateThumbnails() {
2268 thumbnails_.CreateThumbnailControl(
2269 kThumbnailsId, pp::Rect(), false, this, engine_.get(),
2270 number_image_generator());
2273 void Instance::LoadUrl(const std::string& url) {
2274 LoadUrlInternal(url, &embed_loader_, &Instance::DidOpen);
2277 void Instance::LoadPreviewUrl(const std::string& url) {
2278 LoadUrlInternal(url, &embed_preview_loader_, &Instance::DidOpenPreview);
2281 void Instance::LoadUrlInternal(const std::string& url, pp::URLLoader* loader,
2282 void (Instance::* method)(int32_t)) {
2283 pp::URLRequestInfo request(this);
2284 request.SetURL(url);
2285 request.SetMethod("GET");
2287 *loader = CreateURLLoaderInternal();
2288 pp::CompletionCallback callback = loader_factory_.NewCallback(method);
2289 int rv = loader->Open(request, callback);
2290 if (rv != PP_OK_COMPLETIONPENDING)
2291 callback.Run(rv);
2294 pp::URLLoader Instance::CreateURLLoaderInternal() {
2295 pp::URLLoader loader(this);
2297 const PPB_URLLoaderTrusted* trusted_interface =
2298 reinterpret_cast<const PPB_URLLoaderTrusted*>(
2299 pp::Module::Get()->GetBrowserInterface(
2300 PPB_URLLOADERTRUSTED_INTERFACE));
2301 if (trusted_interface)
2302 trusted_interface->GrantUniversalAccess(loader.pp_resource());
2303 return loader;
2306 int Instance::GetInitialPage(const std::string& url) {
2307 #if defined(OS_NACL)
2308 return -1;
2309 #else
2310 size_t found_idx = url.find('#');
2311 if (found_idx == std::string::npos)
2312 return -1;
2314 const std::string& ref = url.substr(found_idx + 1);
2315 std::vector<std::string> fragments;
2316 Tokenize(ref, kDelimiters, &fragments);
2318 // Page number to return, zero-based.
2319 int page = -1;
2321 // Handle the case of http://foo.com/bar#NAMEDDEST. This is not explicitly
2322 // mentioned except by example in the Adobe "PDF Open Parameters" document.
2323 if ((fragments.size() == 1) && (fragments[0].find('=') == std::string::npos))
2324 return engine_->GetNamedDestinationPage(fragments[0]);
2326 for (size_t i = 0; i < fragments.size(); ++i) {
2327 std::vector<std::string> key_value;
2328 base::SplitString(fragments[i], '=', &key_value);
2329 if (key_value.size() != 2)
2330 continue;
2331 const std::string& key = key_value[0];
2332 const std::string& value = key_value[1];
2334 if (base::strcasecmp(kPage, key.c_str()) == 0) {
2335 // |page_value| is 1-based.
2336 int page_value = -1;
2337 if (base::StringToInt(value, &page_value) && page_value > 0)
2338 page = page_value - 1;
2339 continue;
2341 if (base::strcasecmp(kNamedDest, key.c_str()) == 0) {
2342 // |page_value| is 0-based.
2343 int page_value = engine_->GetNamedDestinationPage(value);
2344 if (page_value >= 0)
2345 page = page_value;
2346 continue;
2349 return page;
2350 #endif
2353 void Instance::UpdateToolbarPosition(bool invalidate) {
2354 pp::Rect ctrl_rc = toolbar_->GetControlsRect();
2355 int min_toolbar_width = ctrl_rc.width() + GetToolbarRightOffset() +
2356 GetScaled(kToolbarFadingOffsetLeft);
2357 int min_toolbar_height = ctrl_rc.width() + GetToolbarBottomOffset() +
2358 GetScaled(kToolbarFadingOffsetBottom);
2360 // Update toolbar position
2361 if (plugin_size_.width() < min_toolbar_width ||
2362 plugin_size_.height() < min_toolbar_height) {
2363 // Disable toolbar if it does not fit on the screen.
2364 toolbar_->Show(false, invalidate);
2365 } else {
2366 pp::Point offset(
2367 plugin_size_.width() - GetToolbarRightOffset() - ctrl_rc.right(),
2368 plugin_size_.height() - GetToolbarBottomOffset() - ctrl_rc.bottom());
2369 toolbar_->MoveBy(offset, invalidate);
2371 int toolbar_width = std::max(plugin_size_.width() / 2, min_toolbar_width);
2372 toolbar_->ExpandLeft(toolbar_width - toolbar_->rect().width());
2373 toolbar_->Show(painted_first_page_, invalidate);
2377 void Instance::UpdateProgressBarPosition(bool invalidate) {
2378 // TODO(gene): verify we don't overlap with toolbar.
2379 int scrollbar_thickness = GetScrollbarThickness();
2380 pp::Point progress_origin(
2381 scrollbar_thickness + GetScaled(kProgressOffsetLeft),
2382 plugin_size_.height() - progress_bar_.rect().height() -
2383 scrollbar_thickness - GetScaled(kProgressOffsetBottom));
2384 progress_bar_.MoveTo(progress_origin, invalidate);
2387 void Instance::UpdatePageIndicatorPosition(bool invalidate) {
2388 int32 doc_height = static_cast<int>(document_size_.height() * zoom_);
2389 pp::Point origin(
2390 plugin_size_.width() - page_indicator_.rect().width() -
2391 GetScaled(GetScrollbarReservedThickness()),
2392 page_indicator_.GetYPosition(engine_->GetVerticalScrollbarYPosition(),
2393 doc_height, plugin_size_.height()));
2394 page_indicator_.MoveTo(origin, invalidate);
2397 void Instance::SetZoom(ZoomMode zoom_mode, double scale) {
2398 double old_zoom = zoom_;
2400 zoom_mode_ = zoom_mode;
2401 if (zoom_mode_ == ZOOM_SCALE)
2402 zoom_ = scale;
2403 UpdateZoomScale();
2405 engine_->ZoomUpdated(zoom_ * device_scale_);
2406 OnGeometryChanged(old_zoom, device_scale_);
2408 // If fit-to-height, snap to the beginning of the most visible page.
2409 if (zoom_mode_ == ZOOM_FIT_TO_PAGE) {
2410 ScrollToPage(engine_->GetMostVisiblePage());
2413 // Update sticky buttons to the current zoom style.
2414 Button* ftp_btn = static_cast<Button*>(
2415 toolbar_->GetControl(kFitToPageButtonId));
2416 Button* ftw_btn = static_cast<Button*>(
2417 toolbar_->GetControl(kFitToWidthButtonId));
2418 switch (zoom_mode_) {
2419 case ZOOM_FIT_TO_PAGE:
2420 ftp_btn->SetPressedState(true);
2421 ftw_btn->SetPressedState(false);
2422 break;
2423 case ZOOM_FIT_TO_WIDTH:
2424 ftw_btn->SetPressedState(true);
2425 ftp_btn->SetPressedState(false);
2426 break;
2427 default:
2428 ftw_btn->SetPressedState(false);
2429 ftp_btn->SetPressedState(false);
2433 void Instance::UpdateZoomScale() {
2434 switch (zoom_mode_) {
2435 case ZOOM_SCALE:
2436 break; // Keep current scale.
2437 case ZOOM_FIT_TO_PAGE: {
2438 int page_num = engine_->GetFirstVisiblePage();
2439 if (page_num == -1)
2440 break;
2441 pp::Rect rc = engine_->GetPageRect(page_num);
2442 if (!rc.height())
2443 break;
2444 // Calculate fit to width zoom level.
2445 double ftw_zoom = static_cast<double>(plugin_dip_size_.width() -
2446 GetScrollbarReservedThickness()) / document_size_.width();
2447 // Calculate fit to height zoom level. If document will not fit
2448 // horizontally, adjust zoom level to allow space for horizontal
2449 // scrollbar.
2450 double fth_zoom =
2451 static_cast<double>(plugin_dip_size_.height()) / rc.height();
2452 if (fth_zoom * document_size_.width() >
2453 plugin_dip_size_.width() - GetScrollbarReservedThickness())
2454 fth_zoom = static_cast<double>(plugin_dip_size_.height()
2455 - GetScrollbarReservedThickness()) / rc.height();
2456 zoom_ = std::min(ftw_zoom, fth_zoom);
2457 } break;
2458 case ZOOM_FIT_TO_WIDTH:
2459 case ZOOM_AUTO:
2460 if (!document_size_.width())
2461 break;
2462 zoom_ = static_cast<double>(plugin_dip_size_.width() -
2463 GetScrollbarReservedThickness()) / document_size_.width();
2464 if (zoom_mode_ == ZOOM_AUTO && zoom_ > 1.0)
2465 zoom_ = 1.0;
2466 break;
2468 zoom_ = ClipToRange(zoom_, kMinZoom, kMaxZoom);
2471 double Instance::CalculateZoom(uint32 control_id) const {
2472 if (control_id == kZoomInButtonId) {
2473 for (size_t i = 0; i < chrome_page_zoom::kPresetZoomFactorsSize; ++i) {
2474 double current_zoom = chrome_page_zoom::kPresetZoomFactors[i];
2475 if (current_zoom - content::kEpsilon > zoom_)
2476 return current_zoom;
2478 } else {
2479 for (size_t i = chrome_page_zoom::kPresetZoomFactorsSize; i > 0; --i) {
2480 double current_zoom = chrome_page_zoom::kPresetZoomFactors[i - 1];
2481 if (current_zoom + content::kEpsilon < zoom_)
2482 return current_zoom;
2485 return zoom_;
2488 pp::ImageData Instance::CreateResourceImage(PP_ResourceImage image_id) {
2489 if (hidpi_enabled_)
2490 return pp::PDF::GetResourceImageForScale(this, image_id, device_scale_);
2492 return pp::PDF::GetResourceImage(this, image_id);
2495 std::string Instance::GetLocalizedString(PP_ResourceString id) {
2496 pp::Var rv(pp::PDF::GetLocalizedString(this, id));
2497 if (!rv.is_string())
2498 return std::string();
2500 return rv.AsString();
2503 void Instance::DrawText(const pp::Point& top_center, PP_ResourceString id) {
2504 std::string str(GetLocalizedString(id));
2506 pp::FontDescription_Dev description;
2507 description.set_family(PP_FONTFAMILY_SANSSERIF);
2508 description.set_size(kMessageTextSize * device_scale_);
2509 pp::Font_Dev font(this, description);
2510 int length = font.MeasureSimpleText(str);
2511 pp::Point point(top_center);
2512 point.set_x(point.x() - length / 2);
2513 DCHECK(!image_data_.is_null());
2514 font.DrawSimpleText(&image_data_, str, point, kMessageTextColor);
2517 void Instance::SetPrintPreviewMode(int page_count) {
2518 if (!IsPrintPreview() || page_count <= 0) {
2519 print_preview_page_count_ = 0;
2520 return;
2523 print_preview_page_count_ = page_count;
2524 ScrollToPage(0);
2525 engine_->AppendBlankPages(print_preview_page_count_);
2526 if (preview_pages_info_.size() > 0)
2527 LoadAvailablePreviewPage();
2530 bool Instance::IsPrintPreview() {
2531 return IsPrintPreviewUrl(url_);
2534 int Instance::GetPageNumberToDisplay() {
2535 int page = engine_->GetMostVisiblePage();
2536 if (IsPrintPreview() && !print_preview_page_numbers_.empty()) {
2537 page = ClipToRange<int>(page, 0, print_preview_page_numbers_.size() - 1);
2538 return print_preview_page_numbers_[page];
2540 return page + 1;
2543 void Instance::ProcessPreviewPageInfo(const std::string& url,
2544 int dst_page_index) {
2545 if (!IsPrintPreview() || print_preview_page_count_ < 0)
2546 return;
2548 int src_page_index = ExtractPrintPreviewPageIndex(url);
2549 if (src_page_index < 1)
2550 return;
2552 preview_pages_info_.push(std::make_pair(url, dst_page_index));
2553 LoadAvailablePreviewPage();
2556 void Instance::LoadAvailablePreviewPage() {
2557 if (preview_pages_info_.size() <= 0)
2558 return;
2560 std::string url = preview_pages_info_.front().first;
2561 int dst_page_index = preview_pages_info_.front().second;
2562 int src_page_index = ExtractPrintPreviewPageIndex(url);
2563 if (src_page_index < 1 ||
2564 dst_page_index >= print_preview_page_count_ ||
2565 preview_document_load_state_ == LOAD_STATE_LOADING) {
2566 return;
2569 preview_document_load_state_ = LOAD_STATE_LOADING;
2570 LoadPreviewUrl(url);
2573 void Instance::EnableAutoscroll(const pp::Point& origin) {
2574 if (is_autoscroll_)
2575 return;
2577 pp::Size client_size = plugin_size_;
2578 if (v_scrollbar_.get())
2579 client_size.Enlarge(-GetScrollbarThickness(), 0);
2580 if (h_scrollbar_.get())
2581 client_size.Enlarge(0, -GetScrollbarThickness());
2583 // Do not allow autoscroll if client area is too small.
2584 if (autoscroll_anchor_.size().width() > client_size.width() ||
2585 autoscroll_anchor_.size().height() > client_size.height())
2586 return;
2588 autoscroll_rect_ = pp::Rect(
2589 pp::Point(origin.x() - autoscroll_anchor_.size().width() / 2,
2590 origin.y() - autoscroll_anchor_.size().height() / 2),
2591 autoscroll_anchor_.size());
2593 // Make sure autoscroll anchor is in the client area.
2594 if (autoscroll_rect_.right() > client_size.width()) {
2595 autoscroll_rect_.set_x(
2596 client_size.width() - autoscroll_anchor_.size().width());
2598 if (autoscroll_rect_.bottom() > client_size.height()) {
2599 autoscroll_rect_.set_y(
2600 client_size.height() - autoscroll_anchor_.size().height());
2603 if (autoscroll_rect_.x() < 0)
2604 autoscroll_rect_.set_x(0);
2605 if (autoscroll_rect_.y() < 0)
2606 autoscroll_rect_.set_y(0);
2608 is_autoscroll_ = true;
2609 Invalidate(kAutoScrollId, autoscroll_rect_);
2611 ScheduleTimer(kAutoScrollId, kAutoScrollTimeoutMs);
2614 void Instance::DisableAutoscroll() {
2615 if (is_autoscroll_) {
2616 is_autoscroll_ = false;
2617 Invalidate(kAutoScrollId, autoscroll_rect_);
2621 PP_CursorType_Dev Instance::CalculateAutoscroll(const pp::Point& mouse_pos) {
2622 // Scroll only if mouse pointer is outside of the anchor area.
2623 if (autoscroll_rect_.Contains(mouse_pos)) {
2624 autoscroll_x_ = 0;
2625 autoscroll_y_ = 0;
2626 return PP_CURSORTYPE_MIDDLEPANNING;
2629 // Relative position to the center of anchor area.
2630 pp::Point rel_pos = mouse_pos - autoscroll_rect_.CenterPoint();
2632 // Calculate angle from the X axis. Angle is in range from -pi to pi.
2633 double angle = atan2(static_cast<double>(rel_pos.y()),
2634 static_cast<double>(rel_pos.x()));
2636 autoscroll_x_ = rel_pos.x() * kAutoScrollFactor;
2637 autoscroll_y_ = rel_pos.y() * kAutoScrollFactor;
2639 // Angle is from -pi to pi. Screen Y is increasing toward bottom,
2640 // so negative angle represent north direction.
2641 if (angle < - (M_PI * 7.0 / 8.0)) {
2642 // going west
2643 return PP_CURSORTYPE_WESTPANNING;
2644 } else if (angle < - (M_PI * 5.0 / 8.0)) {
2645 // going north-west
2646 return PP_CURSORTYPE_NORTHWESTPANNING;
2647 } else if (angle < - (M_PI * 3.0 / 8.0)) {
2648 // going north.
2649 return PP_CURSORTYPE_NORTHPANNING;
2650 } else if (angle < - (M_PI * 1.0 / 8.0)) {
2651 // going north-east
2652 return PP_CURSORTYPE_NORTHEASTPANNING;
2653 } else if (angle < M_PI * 1.0 / 8.0) {
2654 // going east.
2655 return PP_CURSORTYPE_EASTPANNING;
2656 } else if (angle < M_PI * 3.0 / 8.0) {
2657 // going south-east
2658 return PP_CURSORTYPE_SOUTHEASTPANNING;
2659 } else if (angle < M_PI * 5.0 / 8.0) {
2660 // going south.
2661 return PP_CURSORTYPE_SOUTHPANNING;
2662 } else if (angle < M_PI * 7.0 / 8.0) {
2663 // going south-west
2664 return PP_CURSORTYPE_SOUTHWESTPANNING;
2667 // went around the circle, going west again
2668 return PP_CURSORTYPE_WESTPANNING;
2671 void Instance::ConfigureNumberImageGenerator() {
2672 std::vector<pp::ImageData> num_images = GetThumbnailResources();
2673 pp::ImageData number_background = CreateResourceImage(
2674 PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_NUM_BACKGROUND);
2675 number_image_generator_->Configure(number_background,
2676 num_images,
2677 device_scale_);
2680 NumberImageGenerator* Instance::number_image_generator() {
2681 if (!number_image_generator_.get()) {
2682 number_image_generator_.reset(new NumberImageGenerator(this));
2683 ConfigureNumberImageGenerator();
2685 return number_image_generator_.get();
2688 int Instance::GetScaled(int x) const {
2689 return static_cast<int>(x * device_scale_);
2692 void Instance::UserMetricsRecordAction(const std::string& action) {
2693 pp::PDF::UserMetricsRecordAction(this, pp::Var(action));
2696 PDFScriptableObject::PDFScriptableObject(Instance* instance)
2697 : instance_(instance) {
2700 PDFScriptableObject::~PDFScriptableObject() {
2703 bool PDFScriptableObject::HasMethod(const pp::Var& name, pp::Var* exception) {
2704 return instance_->HasScriptableMethod(name, exception);
2707 pp::Var PDFScriptableObject::Call(const pp::Var& method,
2708 const std::vector<pp::Var>& args,
2709 pp::Var* exception) {
2710 return instance_->CallScriptableMethod(method, args, exception);
2713 } // namespace chrome_pdf