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