Linux Sandbox: make sure Credentials test pass on TSAN
[chromium-blink-merge.git] / pdf / instance.cc
blob93daf6f163901ebb2ff18f0d69cd93442ebe14af
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/common/content_restriction.h"
21 #include "components/ui/zoom/page_zoom_constants.h"
22 #include "content/public/common/page_zoom.h"
23 #include "net/base/escape.h"
24 #include "pdf/draw_utils.h"
25 #include "pdf/number_image_generator.h"
26 #include "pdf/pdf.h"
27 #include "pdf/resource_consts.h"
28 #include "ppapi/c/dev/ppb_cursor_control_dev.h"
29 #include "ppapi/c/pp_errors.h"
30 #include "ppapi/c/pp_rect.h"
31 #include "ppapi/c/private/ppp_pdf.h"
32 #include "ppapi/c/trusted/ppb_url_loader_trusted.h"
33 #include "ppapi/cpp/core.h"
34 #include "ppapi/cpp/dev/font_dev.h"
35 #include "ppapi/cpp/dev/memory_dev.h"
36 #include "ppapi/cpp/dev/text_input_dev.h"
37 #include "ppapi/cpp/module.h"
38 #include "ppapi/cpp/point.h"
39 #include "ppapi/cpp/private/pdf.h"
40 #include "ppapi/cpp/rect.h"
41 #include "ppapi/cpp/resource.h"
42 #include "ppapi/cpp/url_request_info.h"
43 #include "ui/events/keycodes/keyboard_codes.h"
45 #if defined(OS_MACOSX)
46 #include "base/mac/mac_util.h"
47 #endif
49 namespace chrome_pdf {
51 struct ToolbarButtonInfo {
52 uint32 id;
53 Button::ButtonStyle style;
54 PP_ResourceImage normal;
55 PP_ResourceImage highlighted;
56 PP_ResourceImage pressed;
59 const uint32 kBackgroundColor = 0xFFCCCCCC;
61 namespace {
63 // Uncomment following #define to enable thumbnails.
64 // #define ENABLE_THUMBNAILS
66 const uint32 kToolbarSplashTimeoutMs = 6000;
67 const uint32 kMessageTextColor = 0xFF575757;
68 const uint32 kMessageTextSize = 22;
69 const uint32 kProgressFadeTimeoutMs = 250;
70 const uint32 kProgressDelayTimeoutMs = 1000;
71 const uint32 kAutoScrollTimeoutMs = 50;
72 const double kAutoScrollFactor = 0.2;
74 // Javascript methods.
75 const char kJSAccessibility[] = "accessibility";
76 const char kJSDocumentLoadComplete[] = "documentLoadComplete";
77 const char kJSGetHeight[] = "getHeight";
78 const char kJSGetHorizontalScrollbarThickness[] =
79 "getHorizontalScrollbarThickness";
80 const char kJSGetPageLocationNormalized[] = "getPageLocationNormalized";
81 const char kJSGetSelectedText[] = "getSelectedText";
82 const char kJSGetVerticalScrollbarThickness[] = "getVerticalScrollbarThickness";
83 const char kJSGetWidth[] = "getWidth";
84 const char kJSGetZoomLevel[] = "getZoomLevel";
85 const char kJSGoToPage[] = "goToPage";
86 const char kJSGrayscale[] = "grayscale";
87 const char kJSLoadPreviewPage[] = "loadPreviewPage";
88 const char kJSOnLoad[] = "onload";
89 const char kJSOnPluginSizeChanged[] = "onPluginSizeChanged";
90 const char kJSOnScroll[] = "onScroll";
91 const char kJSPageXOffset[] = "pageXOffset";
92 const char kJSPageYOffset[] = "pageYOffset";
93 const char kJSPrintPreviewPageCount[] = "printPreviewPageCount";
94 const char kJSReload[] = "reload";
95 const char kJSRemovePrintButton[] = "removePrintButton";
96 const char kJSResetPrintPreviewUrl[] = "resetPrintPreviewUrl";
97 const char kJSSendKeyEvent[] = "sendKeyEvent";
98 const char kJSSetPageNumbers[] = "setPageNumbers";
99 const char kJSSetPageXOffset[] = "setPageXOffset";
100 const char kJSSetPageYOffset[] = "setPageYOffset";
101 const char kJSSetZoomLevel[] = "setZoomLevel";
102 const char kJSZoomFitToHeight[] = "fitToHeight";
103 const char kJSZoomFitToWidth[] = "fitToWidth";
104 const char kJSZoomIn[] = "zoomIn";
105 const char kJSZoomOut[] = "zoomOut";
107 // URL reference parameters.
108 // For more possible parameters, see RFC 3778 and the "PDF Open Parameters"
109 // document from Adobe.
110 const char kDelimiters[] = "#&";
111 const char kNamedDest[] = "nameddest";
112 const char kPage[] = "page";
114 const char kChromePrint[] = "chrome://print/";
116 // Dictionary Value key names for the document accessibility info
117 const char kAccessibleNumberOfPages[] = "numberOfPages";
118 const char kAccessibleLoaded[] = "loaded";
119 const char kAccessibleCopyable[] = "copyable";
121 const ToolbarButtonInfo kPDFToolbarButtons[] = {
122 { kFitToPageButtonId, Button::BUTTON_STATE,
123 PP_RESOURCEIMAGE_PDF_BUTTON_FTP,
124 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_HOVER,
125 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_PRESSED },
126 { kFitToWidthButtonId, Button::BUTTON_STATE,
127 PP_RESOURCEIMAGE_PDF_BUTTON_FTW,
128 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_HOVER,
129 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_PRESSED },
130 { kZoomOutButtonId, Button::BUTTON_CLICKABLE,
131 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT,
132 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_HOVER,
133 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_PRESSED },
134 { kZoomInButtonId, Button::BUTTON_CLICKABLE,
135 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN,
136 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_HOVER,
137 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_PRESSED },
138 { kSaveButtonId, Button::BUTTON_CLICKABLE,
139 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE,
140 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE_HOVER,
141 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE_PRESSED },
142 { kPrintButtonId, Button::BUTTON_CLICKABLE,
143 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT,
144 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_HOVER,
145 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_PRESSED },
148 const ToolbarButtonInfo kPDFNoPrintToolbarButtons[] = {
149 { kFitToPageButtonId, Button::BUTTON_STATE,
150 PP_RESOURCEIMAGE_PDF_BUTTON_FTP,
151 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_HOVER,
152 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_PRESSED },
153 { kFitToWidthButtonId, Button::BUTTON_STATE,
154 PP_RESOURCEIMAGE_PDF_BUTTON_FTW,
155 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_HOVER,
156 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_PRESSED },
157 { kZoomOutButtonId, Button::BUTTON_CLICKABLE,
158 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT,
159 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_HOVER,
160 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_PRESSED },
161 { kZoomInButtonId, Button::BUTTON_CLICKABLE,
162 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN,
163 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_HOVER,
164 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_PRESSED },
165 { kSaveButtonId, Button::BUTTON_CLICKABLE,
166 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE,
167 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE_HOVER,
168 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE_PRESSED },
169 { kPrintButtonId, Button::BUTTON_CLICKABLE,
170 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_DISABLED,
171 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_DISABLED,
172 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_DISABLED }
175 const ToolbarButtonInfo kPrintPreviewToolbarButtons[] = {
176 { kFitToPageButtonId, Button::BUTTON_STATE,
177 PP_RESOURCEIMAGE_PDF_BUTTON_FTP,
178 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_HOVER,
179 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_PRESSED },
180 { kFitToWidthButtonId, Button::BUTTON_STATE,
181 PP_RESOURCEIMAGE_PDF_BUTTON_FTW,
182 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_HOVER,
183 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_PRESSED },
184 { kZoomOutButtonId, Button::BUTTON_CLICKABLE,
185 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT,
186 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_HOVER,
187 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_PRESSED },
188 { kZoomInButtonId, Button::BUTTON_CLICKABLE,
189 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_END,
190 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_END_HOVER,
191 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_END_PRESSED },
194 static const char kPPPPdfInterface[] = PPP_PDF_INTERFACE_1;
196 PP_Var GetLinkAtPosition(PP_Instance instance, PP_Point point) {
197 pp::Var var;
198 void* object =
199 pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
200 if (object)
201 var = static_cast<Instance*>(object)->GetLinkAtPosition(pp::Point(point));
202 return var.Detach();
205 void Transform(PP_Instance instance, PP_PrivatePageTransformType type) {
206 void* object =
207 pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
208 if (object) {
209 Instance* obj_instance = static_cast<Instance*>(object);
210 switch (type) {
211 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CW:
212 obj_instance->RotateClockwise();
213 break;
214 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CCW:
215 obj_instance->RotateCounterclockwise();
216 break;
221 PP_Bool GetPrintPresetOptionsFromDocument(
222 PP_Instance instance,
223 PP_PdfPrintPresetOptions_Dev* options) {
224 void* object = pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
225 if (object) {
226 Instance* obj_instance = static_cast<Instance*>(object);
227 obj_instance->GetPrintPresetOptionsFromDocument(options);
229 return PP_TRUE;
232 const PPP_Pdf ppp_private = {
233 &GetLinkAtPosition,
234 &Transform,
235 &GetPrintPresetOptionsFromDocument
238 int ExtractPrintPreviewPageIndex(const std::string& src_url) {
239 // Sample |src_url| format: chrome://print/id/page_index/print.pdf
240 std::vector<std::string> url_substr;
241 base::SplitString(src_url.substr(strlen(kChromePrint)), '/', &url_substr);
242 if (url_substr.size() != 3)
243 return -1;
245 if (url_substr[2] != "print.pdf")
246 return -1;
248 int page_index = 0;
249 if (!base::StringToInt(url_substr[1], &page_index))
250 return -1;
251 return page_index;
254 bool IsPrintPreviewUrl(const std::string& url) {
255 return url.substr(0, strlen(kChromePrint)) == kChromePrint;
258 void ScalePoint(float scale, pp::Point* point) {
259 point->set_x(static_cast<int>(point->x() * scale));
260 point->set_y(static_cast<int>(point->y() * scale));
263 void ScaleRect(float scale, pp::Rect* rect) {
264 int left = static_cast<int>(floorf(rect->x() * scale));
265 int top = static_cast<int>(floorf(rect->y() * scale));
266 int right = static_cast<int>(ceilf((rect->x() + rect->width()) * scale));
267 int bottom = static_cast<int>(ceilf((rect->y() + rect->height()) * scale));
268 rect->SetRect(left, top, right - left, bottom - top);
271 template<class T>
272 T ClipToRange(T value, T lower_boundary, T upper_boundary) {
273 DCHECK(lower_boundary <= upper_boundary);
274 return std::max<T>(lower_boundary, std::min<T>(value, upper_boundary));
277 } // namespace
279 Instance::Instance(PP_Instance instance)
280 : pp::InstancePrivate(instance),
281 pp::Find_Private(this),
282 pp::Printing_Dev(this),
283 pp::Selection_Dev(this),
284 pp::WidgetClient_Dev(this),
285 pp::Zoom_Dev(this),
286 cursor_(PP_CURSORTYPE_POINTER),
287 timer_pending_(false),
288 current_timer_id_(0),
289 zoom_(1.0),
290 device_scale_(1.0),
291 printing_enabled_(true),
292 hidpi_enabled_(false),
293 full_(IsFullFrame()),
294 zoom_mode_(full_ ? ZOOM_AUTO : ZOOM_SCALE),
295 did_call_start_loading_(false),
296 is_autoscroll_(false),
297 scrollbar_thickness_(-1),
298 scrollbar_reserved_thickness_(-1),
299 current_tb_info_(NULL),
300 current_tb_info_size_(0),
301 paint_manager_(this, this, true),
302 delayed_progress_timer_id_(0),
303 first_paint_(true),
304 painted_first_page_(false),
305 show_page_indicator_(false),
306 document_load_state_(LOAD_STATE_LOADING),
307 preview_document_load_state_(LOAD_STATE_COMPLETE),
308 told_browser_about_unsupported_feature_(false),
309 print_preview_page_count_(0) {
310 loader_factory_.Initialize(this);
311 timer_factory_.Initialize(this);
312 form_factory_.Initialize(this);
313 callback_factory_.Initialize(this);
314 engine_.reset(PDFEngine::Create(this));
315 pp::Module::Get()->AddPluginInterface(kPPPPdfInterface, &ppp_private);
316 AddPerInstanceObject(kPPPPdfInterface, this);
318 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_MOUSE);
319 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_WHEEL);
320 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_KEYBOARD);
321 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_TOUCH);
324 Instance::~Instance() {
325 if (timer_pending_) {
326 timer_factory_.CancelAll();
327 timer_pending_ = false;
329 // The engine may try to access this instance during its destruction.
330 // Make sure this happens early while the instance is still intact.
331 engine_.reset();
332 RemovePerInstanceObject(kPPPPdfInterface, this);
335 bool Instance::Init(uint32_t argc, const char* argn[], const char* argv[]) {
336 // For now, we hide HiDPI support behind a flag.
337 if (pp::PDF::IsFeatureEnabled(this, PP_PDFFEATURE_HIDPI))
338 hidpi_enabled_ = true;
340 printing_enabled_ = pp::PDF::IsFeatureEnabled(this, PP_PDFFEATURE_PRINTING);
341 if (printing_enabled_) {
342 CreateToolbar(kPDFToolbarButtons, arraysize(kPDFToolbarButtons));
343 } else {
344 CreateToolbar(kPDFNoPrintToolbarButtons,
345 arraysize(kPDFNoPrintToolbarButtons));
348 CreateProgressBar();
350 // Load autoscroll anchor image.
351 autoscroll_anchor_ =
352 CreateResourceImage(PP_RESOURCEIMAGE_PDF_PAN_SCROLL_ICON);
354 #ifdef ENABLE_THUMBNAILS
355 CreateThumbnails();
356 #endif
357 const char* url = NULL;
358 for (uint32_t i = 0; i < argc; ++i) {
359 if (strcmp(argn[i], "src") == 0) {
360 url = argv[i];
361 break;
365 if (!url)
366 return false;
368 CreatePageIndicator(IsPrintPreviewUrl(url));
370 if (!full_) {
371 // For PDFs embedded in a frame, we don't get the data automatically like we
372 // do for full-frame loads. Start loading the data manually.
373 LoadUrl(url);
374 } else {
375 DCHECK(!did_call_start_loading_);
376 pp::PDF::DidStartLoading(this);
377 did_call_start_loading_ = true;
380 ZoomLimitsChanged(kMinZoom, kMaxZoom);
382 text_input_.reset(new pp::TextInput_Dev(this));
384 url_ = url;
385 return engine_->New(url);
388 bool Instance::HandleDocumentLoad(const pp::URLLoader& loader) {
389 delayed_progress_timer_id_ = ScheduleTimer(kProgressBarId,
390 kProgressDelayTimeoutMs);
391 return engine_->HandleDocumentLoad(loader);
394 bool Instance::HandleInputEvent(const pp::InputEvent& event) {
395 // To simplify things, convert the event into device coordinates if it is
396 // a mouse event.
397 pp::InputEvent event_device_res(event);
399 pp::MouseInputEvent mouse_event(event);
400 if (!mouse_event.is_null()) {
401 pp::Point point = mouse_event.GetPosition();
402 pp::Point movement = mouse_event.GetMovement();
403 ScalePoint(device_scale_, &point);
404 ScalePoint(device_scale_, &movement);
405 mouse_event = pp::MouseInputEvent(
406 this,
407 event.GetType(),
408 event.GetTimeStamp(),
409 event.GetModifiers(),
410 mouse_event.GetButton(),
411 point,
412 mouse_event.GetClickCount(),
413 movement);
414 event_device_res = mouse_event;
418 // Check if we need to go to autoscroll mode.
419 if (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE &&
420 (event.GetModifiers() & PP_INPUTEVENT_MODIFIER_MIDDLEBUTTONDOWN)) {
421 pp::MouseInputEvent mouse_event(event_device_res);
422 pp::Point pos = mouse_event.GetPosition();
423 EnableAutoscroll(pos);
424 UpdateCursor(CalculateAutoscroll(pos));
425 return true;
426 } else {
427 // Quit autoscrolling on any other event.
428 DisableAutoscroll();
431 #ifdef ENABLE_THUMBNAILS
432 if (event.GetType() == PP_INPUTEVENT_TYPE_MOUSELEAVE)
433 thumbnails_.SlideOut();
435 if (thumbnails_.HandleEvent(event_device_res))
436 return true;
437 #endif
439 if (!IsMouseOnScrollbar(event_device_res) &&
440 toolbar_->HandleEvent(event_device_res))
441 return true;
443 #ifdef ENABLE_THUMBNAILS
444 if (v_scrollbar_.get() && event.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE) {
445 pp::MouseInputEvent mouse_event(event);
446 pp::Point pt = mouse_event.GetPosition();
447 pp::Rect v_scrollbar_rc;
448 v_scrollbar_->GetLocation(&v_scrollbar_rc);
449 // There is a bug (https://bugs.webkit.org/show_bug.cgi?id=45208)
450 // in the webkit that makes event.u.mouse.button
451 // equal to PP_INPUTEVENT_MOUSEBUTTON_LEFT, even when no button is pressed.
452 // To work around this issue we use modifier for now, and will switch
453 // to button once the bug is fixed and webkit got merged back to our tree.
454 if (v_scrollbar_rc.Contains(pt) &&
455 (event.GetModifiers() & PP_INPUTEVENT_MODIFIER_LEFTBUTTONDOWN)) {
456 thumbnails_.SlideIn();
459 // When scrollbar is in the scrolling mode we should display thumbnails
460 // even the mouse is outside the thumbnail and scrollbar areas.
461 // If mouse is outside plugin area, we are still getting mouse move events
462 // while scrolling. See bug description for details:
463 // http://code.google.com/p/chromium/issues/detail?id=56444
464 if (!v_scrollbar_rc.Contains(pt) && thumbnails_.visible() &&
465 !(event.GetModifiers() & PP_INPUTEVENT_MODIFIER_LEFTBUTTONDOWN) &&
466 !thumbnails_.rect().Contains(pt)) {
467 thumbnails_.SlideOut();
470 #endif
472 // Need to pass the event to the engine first, since if we're over an edit
473 // control we want it to get keyboard events (like space) instead of the
474 // scrollbar.
475 // TODO: will have to offset the mouse coordinates once we support bidi and
476 // there could be scrollbars on the left.
477 pp::InputEvent offset_event(event_device_res);
478 bool try_engine_first = true;
479 switch (offset_event.GetType()) {
480 case PP_INPUTEVENT_TYPE_MOUSEDOWN:
481 case PP_INPUTEVENT_TYPE_MOUSEUP:
482 case PP_INPUTEVENT_TYPE_MOUSEMOVE:
483 case PP_INPUTEVENT_TYPE_MOUSEENTER:
484 case PP_INPUTEVENT_TYPE_MOUSELEAVE: {
485 pp::MouseInputEvent mouse_event(event_device_res);
486 pp::MouseInputEvent mouse_event_dip(event);
487 pp::Point point = mouse_event.GetPosition();
488 point.set_x(point.x() - available_area_.x());
489 offset_event = pp::MouseInputEvent(
490 this,
491 event.GetType(),
492 event.GetTimeStamp(),
493 event.GetModifiers(),
494 mouse_event.GetButton(),
495 point,
496 mouse_event.GetClickCount(),
497 mouse_event.GetMovement());
498 if (!engine_->IsSelecting()) {
499 if (!IsOverlayScrollbar() &&
500 !available_area_.Contains(mouse_event.GetPosition())) {
501 try_engine_first = false;
502 } else if (IsOverlayScrollbar() && IsMouseOnScrollbar(event)) {
503 try_engine_first = false;
506 break;
508 default:
509 break;
511 if (try_engine_first && engine_->HandleEvent(offset_event))
512 return true;
514 // Left/Right arrows should scroll to the beginning of the Prev/Next page if
515 // there is no horizontal scroll bar.
516 // If fit-to-height, PgDown/PgUp should scroll to the beginning of the
517 // Prev/Next page. Spacebar / shift+spacebar should do the same.
518 if (v_scrollbar_.get() && event.GetType() == PP_INPUTEVENT_TYPE_KEYDOWN) {
519 pp::KeyboardInputEvent keyboard_event(event);
520 bool no_h_scrollbar = !h_scrollbar_.get();
521 uint32_t key_code = keyboard_event.GetKeyCode();
522 bool has_modifiers = keyboard_event.GetModifiers() != 0;
523 bool page_down =
524 no_h_scrollbar && !has_modifiers && key_code == ui::VKEY_RIGHT;
525 bool page_up =
526 no_h_scrollbar && !has_modifiers && 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 void Instance::GetPrintPresetOptionsFromDocument(
675 PP_PdfPrintPresetOptions_Dev* options) {
676 options->is_scaling_disabled = PP_FromBool(IsPrintScalingDisabled());
677 options->copies = engine_->GetCopiesToPrint();
680 pp::Var Instance::GetLinkAtPosition(const pp::Point& point) {
681 pp::Point offset_point(point);
682 ScalePoint(device_scale_, &offset_point);
683 offset_point.set_x(offset_point.x() - available_area_.x());
684 return engine_->GetLinkAtPosition(offset_point);
687 pp::Var Instance::GetSelectedText(bool html) {
688 if (html)
689 return pp::Var();
690 return engine_->GetSelectedText();
693 void Instance::InvalidateWidget(pp::Widget_Dev widget,
694 const pp::Rect& dirty_rect) {
695 if (v_scrollbar_.get() && *v_scrollbar_ == widget) {
696 if (!image_data_.is_null())
697 v_scrollbar_->Paint(dirty_rect.pp_rect(), &image_data_);
698 } else if (h_scrollbar_.get() && *h_scrollbar_ == widget) {
699 if (!image_data_.is_null())
700 h_scrollbar_->Paint(dirty_rect.pp_rect(), &image_data_);
701 } else {
702 // Possible to hit this condition since sometimes the scrollbar codes posts
703 // a task to do something later, and we could have deleted our reference in
704 // the meantime.
705 return;
708 pp::Rect dirty_rect_scaled = dirty_rect;
709 ScaleRect(device_scale_, &dirty_rect_scaled);
710 paint_manager_.InvalidateRect(dirty_rect_scaled);
713 void Instance::ScrollbarValueChanged(pp::Scrollbar_Dev scrollbar,
714 uint32_t value) {
715 value = GetScaled(value);
716 if (v_scrollbar_.get() && *v_scrollbar_ == scrollbar) {
717 engine_->ScrolledToYPosition(value);
718 pp::Rect rc;
719 v_scrollbar_->GetLocation(&rc);
720 int32 doc_height = GetDocumentPixelHeight();
721 doc_height -= GetScaled(rc.height());
722 #ifdef ENABLE_THUMBNAILS
723 if (thumbnails_.visible()) {
724 thumbnails_.SetPosition(value, doc_height, true);
726 #endif
727 pp::Point origin(
728 plugin_size_.width() - page_indicator_.rect().width() -
729 GetScaled(GetScrollbarReservedThickness()),
730 page_indicator_.GetYPosition(value, doc_height, plugin_size_.height()));
731 page_indicator_.MoveTo(origin, page_indicator_.visible());
732 } else if (h_scrollbar_.get() && *h_scrollbar_ == scrollbar) {
733 engine_->ScrolledToXPosition(value);
737 void Instance::ScrollbarOverlayChanged(pp::Scrollbar_Dev scrollbar,
738 bool overlay) {
739 scrollbar_reserved_thickness_ = overlay ? 0 : scrollbar_thickness_;
740 OnGeometryChanged(zoom_, device_scale_);
743 uint32_t Instance::QuerySupportedPrintOutputFormats() {
744 return engine_->QuerySupportedPrintOutputFormats();
747 int32_t Instance::PrintBegin(const PP_PrintSettings_Dev& print_settings) {
748 // For us num_pages is always equal to the number of pages in the PDF
749 // document irrespective of the printable area.
750 int32_t ret = engine_->GetNumberOfPages();
751 if (!ret)
752 return 0;
754 uint32_t supported_formats = engine_->QuerySupportedPrintOutputFormats();
755 if ((print_settings.format & supported_formats) == 0)
756 return 0;
758 print_settings_.is_printing = true;
759 print_settings_.pepper_print_settings = print_settings;
760 engine_->PrintBegin();
761 return ret;
764 pp::Resource Instance::PrintPages(
765 const PP_PrintPageNumberRange_Dev* page_ranges,
766 uint32_t page_range_count) {
767 if (!print_settings_.is_printing)
768 return pp::Resource();
770 print_settings_.print_pages_called_ = true;
771 return engine_->PrintPages(page_ranges, page_range_count,
772 print_settings_.pepper_print_settings);
775 void Instance::PrintEnd() {
776 if (print_settings_.print_pages_called_)
777 UserMetricsRecordAction("PDF.PrintPage");
778 print_settings_.Clear();
779 engine_->PrintEnd();
782 bool Instance::IsPrintScalingDisabled() {
783 return !engine_->GetPrintScaling();
786 bool Instance::StartFind(const std::string& text, bool case_sensitive) {
787 engine_->StartFind(text.c_str(), case_sensitive);
788 return true;
791 void Instance::SelectFindResult(bool forward) {
792 engine_->SelectFindResult(forward);
795 void Instance::StopFind() {
796 engine_->StopFind();
799 void Instance::Zoom(double scale, bool text_only) {
800 UserMetricsRecordAction("PDF.ZoomFromBrowser");
802 // If the zoom level doesn't change it means that this zoom change might have
803 // been initiated by the plugin. In that case, we don't want to change the
804 // zoom mode to ZOOM_SCALE as it may have been intentionally set to
805 // ZOOM_FIT_TO_PAGE or some other value when the zoom was last changed.
806 if (scale == zoom_)
807 return;
809 SetZoom(ZOOM_SCALE, scale);
812 void Instance::ZoomChanged(double factor) {
813 if (full_)
814 Zoom_Dev::ZoomChanged(factor);
817 void Instance::OnPaint(const std::vector<pp::Rect>& paint_rects,
818 std::vector<PaintManager::ReadyRect>* ready,
819 std::vector<pp::Rect>* pending) {
820 if (image_data_.is_null()) {
821 DCHECK(plugin_size_.IsEmpty());
822 return;
824 if (first_paint_) {
825 first_paint_ = false;
826 pp::Rect rect = pp::Rect(pp::Point(), plugin_size_);
827 FillRect(rect, kBackgroundColor);
828 ready->push_back(PaintManager::ReadyRect(rect, image_data_, true));
829 *pending = paint_rects;
830 return;
833 engine_->PrePaint();
835 for (size_t i = 0; i < paint_rects.size(); i++) {
836 // Intersect with plugin area since there could be pending invalidates from
837 // when the plugin area was larger.
838 pp::Rect rect =
839 paint_rects[i].Intersect(pp::Rect(pp::Point(), plugin_size_));
840 if (rect.IsEmpty())
841 continue;
843 pp::Rect pdf_rect = available_area_.Intersect(rect);
844 if (!pdf_rect.IsEmpty()) {
845 pdf_rect.Offset(available_area_.x() * -1, 0);
847 std::vector<pp::Rect> pdf_ready;
848 std::vector<pp::Rect> pdf_pending;
849 engine_->Paint(pdf_rect, &image_data_, &pdf_ready, &pdf_pending);
850 for (size_t j = 0; j < pdf_ready.size(); ++j) {
851 pdf_ready[j].Offset(available_area_.point());
852 ready->push_back(
853 PaintManager::ReadyRect(pdf_ready[j], image_data_, false));
855 for (size_t j = 0; j < pdf_pending.size(); ++j) {
856 pdf_pending[j].Offset(available_area_.point());
857 pending->push_back(pdf_pending[j]);
861 for (size_t j = 0; j < background_parts_.size(); ++j) {
862 pp::Rect intersection = background_parts_[j].location.Intersect(rect);
863 if (!intersection.IsEmpty()) {
864 FillRect(intersection, background_parts_[j].color);
865 ready->push_back(
866 PaintManager::ReadyRect(intersection, image_data_, false));
870 if (document_load_state_ == LOAD_STATE_FAILED) {
871 pp::Point top_center;
872 top_center.set_x(plugin_size_.width() / 2);
873 top_center.set_y(plugin_size_.height() / 2);
874 DrawText(top_center, PP_RESOURCESTRING_PDFLOAD_FAILED);
877 #ifdef ENABLE_THUMBNAILS
878 thumbnails_.Paint(&image_data_, rect);
879 #endif
882 engine_->PostPaint();
884 // Must paint scrollbars after the background parts, in case we have an
885 // overlay scrollbar that's over the background. We also do this in a separate
886 // loop because the scrollbar painting logic uses the signal of whether there
887 // are pending paints or not to figure out if it should draw right away or
888 // not.
889 for (size_t i = 0; i < paint_rects.size(); i++) {
890 PaintIfWidgetIntersects(h_scrollbar_.get(), paint_rects[i], ready, pending);
891 PaintIfWidgetIntersects(v_scrollbar_.get(), paint_rects[i], ready, pending);
894 if (progress_bar_.visible())
895 PaintOverlayControl(&progress_bar_, &image_data_, ready);
897 if (page_indicator_.visible())
898 PaintOverlayControl(&page_indicator_, &image_data_, ready);
900 if (toolbar_->current_transparency() != kTransparentAlpha)
901 PaintOverlayControl(toolbar_.get(), &image_data_, ready);
903 // Paint autoscroll anchor if needed.
904 if (is_autoscroll_) {
905 size_t limit = ready->size();
906 for (size_t i = 0; i < limit; i++) {
907 pp::Rect anchor_rect = autoscroll_rect_.Intersect((*ready)[i].rect);
908 if (!anchor_rect.IsEmpty()) {
909 pp::Rect draw_rc = pp::Rect(
910 pp::Point(anchor_rect.x() - autoscroll_rect_.x(),
911 anchor_rect.y() - autoscroll_rect_.y()),
912 anchor_rect.size());
913 // Paint autoscroll anchor.
914 AlphaBlend(autoscroll_anchor_, draw_rc,
915 &image_data_, anchor_rect.point(), kOpaqueAlpha);
921 void Instance::PaintOverlayControl(
922 Control* ctrl,
923 pp::ImageData* image_data,
924 std::vector<PaintManager::ReadyRect>* ready) {
925 // Make sure that we only paint overlay controls over an area that's ready,
926 // i.e. not pending. Otherwise we'll mark the control rect as ready and
927 // it'll overwrite the pdf region.
928 std::list<pp::Rect> ctrl_rects;
929 for (size_t i = 0; i < ready->size(); i++) {
930 pp::Rect rc = ctrl->rect().Intersect((*ready)[i].rect);
931 if (!rc.IsEmpty())
932 ctrl_rects.push_back(rc);
935 if (!ctrl_rects.empty()) {
936 ctrl->PaintMultipleRects(image_data, ctrl_rects);
938 std::list<pp::Rect>::iterator iter;
939 for (iter = ctrl_rects.begin(); iter != ctrl_rects.end(); ++iter) {
940 ready->push_back(PaintManager::ReadyRect(*iter, *image_data, false));
945 void Instance::DidOpen(int32_t result) {
946 if (result == PP_OK) {
947 engine_->HandleDocumentLoad(embed_loader_);
948 } else if (result != PP_ERROR_ABORTED) { // Can happen in tests.
949 NOTREACHED();
953 void Instance::DidOpenPreview(int32_t result) {
954 if (result == PP_OK) {
955 preview_engine_.reset(PDFEngine::Create(new PreviewModeClient(this)));
956 preview_engine_->HandleDocumentLoad(embed_preview_loader_);
957 } else {
958 NOTREACHED();
962 void Instance::PaintIfWidgetIntersects(
963 pp::Widget_Dev* widget,
964 const pp::Rect& rect,
965 std::vector<PaintManager::ReadyRect>* ready,
966 std::vector<pp::Rect>* pending) {
967 if (!widget)
968 return;
970 pp::Rect location;
971 if (!widget->GetLocation(&location))
972 return;
974 ScaleRect(device_scale_, &location);
975 location = location.Intersect(rect);
976 if (location.IsEmpty())
977 return;
979 if (IsOverlayScrollbar()) {
980 // If we're using overlay scrollbars, and there are pending paints under the
981 // scrollbar, don't update the scrollbar instantly. While it would be nice,
982 // we would need to double buffer the plugin area in order to make this
983 // work. This is because we'd need to always have a copy of what the pdf
984 // under the scrollbar looks like, and additionally we couldn't paint the
985 // pdf under the scrollbar if it's ready until we got the preceding flush.
986 // So in practice, it would make painting slower and introduce extra buffer
987 // copies for the general case.
988 for (size_t i = 0; i < pending->size(); ++i) {
989 if ((*pending)[i].Intersects(location))
990 return;
993 // Even if none of the pending paints are under the scrollbar, we never want
994 // to paint it if it's over the pdf if there are other pending paints.
995 // Otherwise different parts of the pdf plugin would display at different
996 // scroll offsets.
997 if (!pending->empty() && available_area_.Intersects(rect)) {
998 pending->push_back(location);
999 return;
1003 pp::Rect location_dip = location;
1004 ScaleRect(1.0f / device_scale_, &location_dip);
1006 DCHECK(!image_data_.is_null());
1007 widget->Paint(location_dip, &image_data_);
1009 ready->push_back(PaintManager::ReadyRect(location, image_data_, true));
1012 void Instance::OnTimerFired(int32_t) {
1013 HandleInputEvent(last_mouse_event_);
1016 void Instance::OnClientTimerFired(int32_t id) {
1017 engine_->OnCallback(id);
1020 void Instance::OnControlTimerFired(int32_t,
1021 const uint32& control_id,
1022 const uint32& timer_id) {
1023 if (control_id == toolbar_->id()) {
1024 toolbar_->OnTimerFired(timer_id);
1025 } else if (control_id == progress_bar_.id()) {
1026 if (timer_id == delayed_progress_timer_id_) {
1027 if (document_load_state_ == LOAD_STATE_LOADING &&
1028 !progress_bar_.visible()) {
1029 progress_bar_.Fade(true, kProgressFadeTimeoutMs);
1031 delayed_progress_timer_id_ = 0;
1032 } else {
1033 progress_bar_.OnTimerFired(timer_id);
1035 } else if (control_id == kAutoScrollId) {
1036 if (is_autoscroll_) {
1037 if (autoscroll_x_ != 0 && h_scrollbar_.get()) {
1038 h_scrollbar_->ScrollBy(PP_SCROLLBY_PIXEL, autoscroll_x_);
1040 if (autoscroll_y_ != 0 && v_scrollbar_.get()) {
1041 v_scrollbar_->ScrollBy(PP_SCROLLBY_PIXEL, autoscroll_y_);
1044 // Reschedule timer.
1045 ScheduleTimer(kAutoScrollId, kAutoScrollTimeoutMs);
1047 } else if (control_id == kPageIndicatorId) {
1048 page_indicator_.OnTimerFired(timer_id);
1050 #ifdef ENABLE_THUMBNAILS
1051 else if (control_id == thumbnails_.id()) {
1052 thumbnails_.OnTimerFired(timer_id);
1054 #endif
1057 void Instance::CalculateBackgroundParts() {
1058 background_parts_.clear();
1059 int v_scrollbar_thickness =
1060 GetScaled(v_scrollbar_.get() ? GetScrollbarReservedThickness() : 0);
1061 int h_scrollbar_thickness =
1062 GetScaled(h_scrollbar_.get() ? GetScrollbarReservedThickness() : 0);
1063 int width_without_scrollbar = std::max(
1064 plugin_size_.width() - v_scrollbar_thickness, 0);
1065 int height_without_scrollbar = std::max(
1066 plugin_size_.height() - h_scrollbar_thickness, 0);
1067 int left_width = available_area_.x();
1068 int right_start = available_area_.right();
1069 int right_width = abs(width_without_scrollbar - available_area_.right());
1070 int bottom = std::min(available_area_.bottom(), height_without_scrollbar);
1072 // Add the left, right, and bottom rectangles. Note: we assume only
1073 // horizontal centering.
1074 BackgroundPart part = {
1075 pp::Rect(0, 0, left_width, bottom),
1076 kBackgroundColor
1078 if (!part.location.IsEmpty())
1079 background_parts_.push_back(part);
1080 part.location = pp::Rect(right_start, 0, right_width, bottom);
1081 if (!part.location.IsEmpty())
1082 background_parts_.push_back(part);
1083 part.location = pp::Rect(
1084 0, bottom, width_without_scrollbar, height_without_scrollbar - bottom);
1085 if (!part.location.IsEmpty())
1086 background_parts_.push_back(part);
1088 if (h_scrollbar_thickness
1089 #if defined(OS_MACOSX)
1091 #else
1093 #endif
1094 v_scrollbar_thickness) {
1095 part.color = 0xFFFFFFFF;
1096 part.location = pp::Rect(plugin_size_.width() - v_scrollbar_thickness,
1097 plugin_size_.height() - h_scrollbar_thickness,
1098 h_scrollbar_thickness,
1099 v_scrollbar_thickness);
1100 background_parts_.push_back(part);
1104 int Instance::GetDocumentPixelWidth() const {
1105 return static_cast<int>(ceil(document_size_.width() * zoom_ * device_scale_));
1108 int Instance::GetDocumentPixelHeight() const {
1109 return static_cast<int>(ceil(document_size_.height() *
1110 zoom_ *
1111 device_scale_));
1114 void Instance::FillRect(const pp::Rect& rect, uint32 color) {
1115 DCHECK(!image_data_.is_null() || rect.IsEmpty());
1116 uint32* buffer_start = static_cast<uint32*>(image_data_.data());
1117 int stride = image_data_.stride();
1118 uint32* ptr = buffer_start + rect.y() * stride / 4 + rect.x();
1119 int height = rect.height();
1120 int width = rect.width();
1121 for (int y = 0; y < height; ++y) {
1122 for (int x = 0; x < width; ++x)
1123 *(ptr + x) = color;
1124 ptr += stride / 4;
1128 void Instance::DocumentSizeUpdated(const pp::Size& size) {
1129 document_size_ = size;
1131 OnGeometryChanged(zoom_, device_scale_);
1134 void Instance::Invalidate(const pp::Rect& rect) {
1135 pp::Rect offset_rect(rect);
1136 offset_rect.Offset(available_area_.point());
1137 paint_manager_.InvalidateRect(offset_rect);
1140 void Instance::Scroll(const pp::Point& point) {
1141 pp::Rect scroll_area = available_area_;
1142 if (IsOverlayScrollbar()) {
1143 pp::Rect rc;
1144 if (h_scrollbar_.get()) {
1145 h_scrollbar_->GetLocation(&rc);
1146 ScaleRect(device_scale_, &rc);
1147 if (scroll_area.bottom() > rc.y()) {
1148 scroll_area.set_height(rc.y() - scroll_area.y());
1149 paint_manager_.InvalidateRect(rc);
1152 if (v_scrollbar_.get()) {
1153 v_scrollbar_->GetLocation(&rc);
1154 ScaleRect(device_scale_, &rc);
1155 if (scroll_area.right() > rc.x()) {
1156 scroll_area.set_width(rc.x() - scroll_area.x());
1157 paint_manager_.InvalidateRect(rc);
1161 paint_manager_.ScrollRect(scroll_area, point);
1163 if (toolbar_->current_transparency() != kTransparentAlpha)
1164 paint_manager_.InvalidateRect(toolbar_->GetControlsRect());
1166 if (progress_bar_.visible())
1167 paint_manager_.InvalidateRect(progress_bar_.rect());
1169 if (is_autoscroll_)
1170 paint_manager_.InvalidateRect(autoscroll_rect_);
1172 if (show_page_indicator_) {
1173 page_indicator_.set_current_page(GetPageNumberToDisplay());
1174 page_indicator_.Splash();
1177 if (page_indicator_.visible())
1178 paint_manager_.InvalidateRect(page_indicator_.rect());
1180 // Run the scroll callback asynchronously. This function can be invoked by a
1181 // layout change which should not re-enter into JS synchronously.
1182 pp::CompletionCallback callback =
1183 callback_factory_.NewCallback(&Instance::RunCallback,
1184 on_scroll_callback_);
1185 pp::Module::Get()->core()->CallOnMainThread(0, callback);
1188 void Instance::ScrollToX(int position) {
1189 if (!h_scrollbar_.get()) {
1190 NOTREACHED();
1191 return;
1193 int position_dip = static_cast<int>(position / device_scale_);
1194 h_scrollbar_->SetValue(position_dip);
1197 void Instance::ScrollToY(int position) {
1198 if (!v_scrollbar_.get()) {
1199 NOTREACHED();
1200 return;
1202 int position_dip = static_cast<int>(position / device_scale_);
1203 v_scrollbar_->SetValue(ClipToRange(position_dip, 0, valid_v_range_));
1206 void Instance::ScrollToPage(int page) {
1207 if (!v_scrollbar_.get())
1208 return;
1210 if (engine_->GetNumberOfPages() == 0)
1211 return;
1213 int index = ClipToRange(page, 0, engine_->GetNumberOfPages() - 1);
1214 pp::Rect rect = engine_->GetPageRect(index);
1215 // If we are trying to scroll pass the last page,
1216 // scroll to the end of the last page.
1217 int position = index < page ? rect.bottom() : rect.y();
1218 ScrollToY(position * zoom_ * device_scale_);
1221 void Instance::NavigateTo(const std::string& url, bool open_in_new_tab) {
1222 std::string url_copy(url);
1224 // Empty |url_copy| is ok, and will effectively be a reload.
1225 // Skip the code below so an empty URL does not turn into "http://", which
1226 // will cause GURL to fail a DCHECK.
1227 if (!url_copy.empty()) {
1228 // If |url_copy| starts with '#', then it's for the same URL with a
1229 // different URL fragment.
1230 if (url_copy[0] == '#') {
1231 // if '#' is already present in |url_| then remove old fragment and add
1232 // new |url_copy| fragment.
1233 std::size_t index = url_.find('#');
1234 if (index != std::string::npos)
1235 url_copy = url_.substr(0, index) + url_copy;
1236 else
1237 url_copy = url_ + url_copy;
1238 // Changing the href does not actually do anything when navigating in the
1239 // same tab, so do the actual page scroll here. Then fall through so the
1240 // href gets updated.
1241 if (!open_in_new_tab) {
1242 int page_number = GetInitialPage(url_copy);
1243 if (page_number >= 0)
1244 ScrollToPage(page_number);
1247 // If there's no scheme, add http.
1248 if (url_copy.find("://") == std::string::npos &&
1249 url_copy.find("mailto:") == std::string::npos) {
1250 url_copy = "http://" + url_copy;
1252 // Make sure |url_copy| starts with a valid scheme.
1253 if (url_copy.find("http://") != 0 &&
1254 url_copy.find("https://") != 0 &&
1255 url_copy.find("ftp://") != 0 &&
1256 url_copy.find("file://") != 0 &&
1257 url_copy.find("mailto:") != 0) {
1258 return;
1260 // Make sure |url_copy| is not only a scheme.
1261 if (url_copy == "http://" ||
1262 url_copy == "https://" ||
1263 url_copy == "ftp://" ||
1264 url_copy == "file://" ||
1265 url_copy == "mailto:") {
1266 return;
1269 if (open_in_new_tab) {
1270 GetWindowObject().Call("open", url_copy);
1271 } else {
1272 GetWindowObject().GetProperty("top").GetProperty("location").
1273 SetProperty("href", url_copy);
1277 void Instance::UpdateCursor(PP_CursorType_Dev cursor) {
1278 if (cursor == cursor_)
1279 return;
1280 cursor_ = cursor;
1282 const PPB_CursorControl_Dev* cursor_interface =
1283 reinterpret_cast<const PPB_CursorControl_Dev*>(
1284 pp::Module::Get()->GetBrowserInterface(PPB_CURSOR_CONTROL_DEV_INTERFACE));
1285 if (!cursor_interface) {
1286 NOTREACHED();
1287 return;
1290 cursor_interface->SetCursor(
1291 pp_instance(), cursor_, pp::ImageData().pp_resource(), NULL);
1294 void Instance::UpdateTickMarks(const std::vector<pp::Rect>& tickmarks) {
1295 if (!v_scrollbar_.get())
1296 return;
1298 float inverse_scale = 1.0f / device_scale_;
1299 std::vector<pp::Rect> scaled_tickmarks = tickmarks;
1300 for (size_t i = 0; i < scaled_tickmarks.size(); i++) {
1301 ScaleRect(inverse_scale, &scaled_tickmarks[i]);
1304 v_scrollbar_->SetTickMarks(
1305 scaled_tickmarks.empty() ? NULL : &scaled_tickmarks[0], tickmarks.size());
1308 void Instance::NotifyNumberOfFindResultsChanged(int total, bool final_result) {
1309 NumberOfFindResultsChanged(total, final_result);
1312 void Instance::NotifySelectedFindResultChanged(int current_find_index) {
1313 DCHECK_GE(current_find_index, 0);
1314 SelectedFindResultChanged(current_find_index);
1317 void Instance::OnEvent(uint32 control_id, uint32 event_id, void* data) {
1318 if (event_id == Button::EVENT_ID_BUTTON_CLICKED ||
1319 event_id == Button::EVENT_ID_BUTTON_STATE_CHANGED) {
1320 switch (control_id) {
1321 case kFitToPageButtonId:
1322 UserMetricsRecordAction("PDF.FitToPageButton");
1323 SetZoom(ZOOM_FIT_TO_PAGE, 0);
1324 ZoomChanged(zoom_);
1325 break;
1326 case kFitToWidthButtonId:
1327 UserMetricsRecordAction("PDF.FitToWidthButton");
1328 SetZoom(ZOOM_FIT_TO_WIDTH, 0);
1329 ZoomChanged(zoom_);
1330 break;
1331 case kZoomOutButtonId:
1332 case kZoomInButtonId:
1333 UserMetricsRecordAction(control_id == kZoomOutButtonId ?
1334 "PDF.ZoomOutButton" : "PDF.ZoomInButton");
1335 SetZoom(ZOOM_SCALE, CalculateZoom(control_id));
1336 ZoomChanged(zoom_);
1337 break;
1338 case kSaveButtonId:
1339 UserMetricsRecordAction("PDF.SaveButton");
1340 SaveAs();
1341 break;
1342 case kPrintButtonId:
1343 UserMetricsRecordAction("PDF.PrintButton");
1344 Print();
1345 break;
1348 if (control_id == kThumbnailsId &&
1349 event_id == ThumbnailControl::EVENT_ID_THUMBNAIL_SELECTED) {
1350 int page = *static_cast<int*>(data);
1351 pp::Rect page_rc(engine_->GetPageRect(page));
1352 ScrollToY(static_cast<int>(page_rc.y() * zoom_ * device_scale_));
1356 void Instance::Invalidate(uint32 control_id, const pp::Rect& rc) {
1357 paint_manager_.InvalidateRect(rc);
1360 uint32 Instance::ScheduleTimer(uint32 control_id, uint32 timeout_ms) {
1361 current_timer_id_++;
1362 pp::CompletionCallback callback =
1363 timer_factory_.NewCallback(&Instance::OnControlTimerFired,
1364 control_id,
1365 current_timer_id_);
1366 pp::Module::Get()->core()->CallOnMainThread(timeout_ms, callback);
1367 return current_timer_id_;
1370 void Instance::SetEventCapture(uint32 control_id, bool set_capture) {
1371 // TODO(gene): set event capture here.
1374 void Instance::SetCursor(uint32 control_id, PP_CursorType_Dev cursor_type) {
1375 UpdateCursor(cursor_type);
1378 pp::Instance* Instance::GetInstance() {
1379 return this;
1382 void Instance::GetDocumentPassword(
1383 pp::CompletionCallbackWithOutput<pp::Var> callback) {
1384 std::string message(GetLocalizedString(PP_RESOURCESTRING_PDFGETPASSWORD));
1385 pp::Var result = pp::PDF::ModalPromptForPassword(this, message);
1386 *callback.output() = result.pp_var();
1387 callback.Run(PP_OK);
1390 void Instance::Alert(const std::string& message) {
1391 GetWindowObject().Call("alert", message);
1394 bool Instance::Confirm(const std::string& message) {
1395 pp::Var result = GetWindowObject().Call("confirm", message);
1396 return result.is_bool() ? result.AsBool() : false;
1399 std::string Instance::Prompt(const std::string& question,
1400 const std::string& default_answer) {
1401 pp::Var result = GetWindowObject().Call("prompt", question, default_answer);
1402 return result.is_string() ? result.AsString() : std::string();
1405 std::string Instance::GetURL() {
1406 return url_;
1409 void Instance::Email(const std::string& to,
1410 const std::string& cc,
1411 const std::string& bcc,
1412 const std::string& subject,
1413 const std::string& body) {
1414 std::string javascript =
1415 "var href = 'mailto:" + net::EscapeUrlEncodedData(to, false) +
1416 "?cc=" + net::EscapeUrlEncodedData(cc, false) +
1417 "&bcc=" + net::EscapeUrlEncodedData(bcc, false) +
1418 "&subject=" + net::EscapeUrlEncodedData(subject, false) +
1419 "&body=" + net::EscapeUrlEncodedData(body, false) +
1420 "';var temp = window.open(href, '_blank', " +
1421 "'width=1,height=1');if(temp) temp.close();";
1422 ExecuteScript(javascript);
1425 void Instance::Print() {
1426 if (!printing_enabled_ ||
1427 (!engine_->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY) &&
1428 !engine_->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY))) {
1429 return;
1432 pp::CompletionCallback callback =
1433 callback_factory_.NewCallback(&Instance::OnPrint);
1434 pp::Module::Get()->core()->CallOnMainThread(0, callback);
1437 void Instance::OnPrint(int32_t) {
1438 pp::PDF::Print(this);
1441 void Instance::SaveAs() {
1442 pp::PDF::SaveAs(this);
1445 void Instance::SubmitForm(const std::string& url,
1446 const void* data,
1447 int length) {
1448 pp::URLRequestInfo request(this);
1449 request.SetURL(url);
1450 request.SetMethod("POST");
1451 request.AppendDataToBody(reinterpret_cast<const char*>(data), length);
1453 pp::CompletionCallback callback =
1454 form_factory_.NewCallback(&Instance::FormDidOpen);
1455 form_loader_ = CreateURLLoaderInternal();
1456 int rv = form_loader_.Open(request, callback);
1457 if (rv != PP_OK_COMPLETIONPENDING)
1458 callback.Run(rv);
1461 void Instance::FormDidOpen(int32_t result) {
1462 // TODO: inform the user of success/failure.
1463 if (result != PP_OK) {
1464 NOTREACHED();
1468 std::string Instance::ShowFileSelectionDialog() {
1469 // Seems like very low priority to implement, since the pdf has no way to get
1470 // the file data anyways. Javascript doesn't let you do this synchronously.
1471 NOTREACHED();
1472 return std::string();
1475 pp::URLLoader Instance::CreateURLLoader() {
1476 if (full_) {
1477 if (!did_call_start_loading_) {
1478 did_call_start_loading_ = true;
1479 pp::PDF::DidStartLoading(this);
1482 // Disable save and print until the document is fully loaded, since they
1483 // would generate an incomplete document. Need to do this each time we
1484 // call DidStartLoading since that resets the content restrictions.
1485 pp::PDF::SetContentRestriction(this, CONTENT_RESTRICTION_SAVE |
1486 CONTENT_RESTRICTION_PRINT);
1489 return CreateURLLoaderInternal();
1492 void Instance::ScheduleCallback(int id, int delay_in_ms) {
1493 pp::CompletionCallback callback =
1494 timer_factory_.NewCallback(&Instance::OnClientTimerFired);
1495 pp::Module::Get()->core()->CallOnMainThread(delay_in_ms, callback, id);
1498 void Instance::SearchString(const base::char16* string,
1499 const base::char16* term,
1500 bool case_sensitive,
1501 std::vector<SearchStringResult>* results) {
1502 if (!pp::PDF::IsAvailable()) {
1503 NOTREACHED();
1504 return;
1507 PP_PrivateFindResult* pp_results;
1508 int count = 0;
1509 pp::PDF::SearchString(
1510 this,
1511 reinterpret_cast<const unsigned short*>(string),
1512 reinterpret_cast<const unsigned short*>(term),
1513 case_sensitive,
1514 &pp_results,
1515 &count);
1517 results->resize(count);
1518 for (int i = 0; i < count; ++i) {
1519 (*results)[i].start_index = pp_results[i].start_index;
1520 (*results)[i].length = pp_results[i].length;
1523 pp::Memory_Dev memory;
1524 memory.MemFree(pp_results);
1527 void Instance::DocumentPaintOccurred() {
1528 if (painted_first_page_)
1529 return;
1531 painted_first_page_ = true;
1532 UpdateToolbarPosition(false);
1533 toolbar_->Splash(kToolbarSplashTimeoutMs);
1535 if (engine_->GetNumberOfPages() > 1)
1536 show_page_indicator_ = true;
1537 else
1538 show_page_indicator_ = false;
1540 if (v_scrollbar_.get() && show_page_indicator_) {
1541 page_indicator_.set_current_page(GetPageNumberToDisplay());
1542 page_indicator_.Splash(kToolbarSplashTimeoutMs,
1543 kPageIndicatorInitialFadeTimeoutMs);
1547 void Instance::DocumentLoadComplete(int page_count) {
1548 // Clear focus state for OSK.
1549 FormTextFieldFocusChange(false);
1551 // Update progress control.
1552 if (progress_bar_.visible())
1553 progress_bar_.Fade(false, kProgressFadeTimeoutMs);
1555 DCHECK(document_load_state_ == LOAD_STATE_LOADING);
1556 document_load_state_ = LOAD_STATE_COMPLETE;
1557 UserMetricsRecordAction("PDF.LoadSuccess");
1559 if (did_call_start_loading_) {
1560 pp::PDF::DidStopLoading(this);
1561 did_call_start_loading_ = false;
1564 if (on_load_callback_.is_string())
1565 ExecuteScript(on_load_callback_);
1566 // Note: If we are in print preview mode on_load_callback_ might call
1567 // ScrollTo{X|Y}() and we don't want to scroll again and override it.
1568 // #page=N is not supported in Print Preview.
1569 if (!IsPrintPreview()) {
1570 int initial_page = GetInitialPage(url_);
1571 if (initial_page >= 0)
1572 ScrollToPage(initial_page);
1575 if (!full_)
1576 return;
1577 if (!pp::PDF::IsAvailable())
1578 return;
1580 int content_restrictions =
1581 CONTENT_RESTRICTION_CUT | CONTENT_RESTRICTION_PASTE;
1582 if (!engine_->HasPermission(PDFEngine::PERMISSION_COPY))
1583 content_restrictions |= CONTENT_RESTRICTION_COPY;
1585 if (!engine_->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY) &&
1586 !engine_->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY)) {
1587 printing_enabled_ = false;
1588 if (current_tb_info_ == kPDFToolbarButtons) {
1589 // Remove Print button.
1590 CreateToolbar(kPDFNoPrintToolbarButtons,
1591 arraysize(kPDFNoPrintToolbarButtons));
1592 UpdateToolbarPosition(false);
1593 Invalidate(pp::Rect(plugin_size_));
1597 pp::PDF::SetContentRestriction(this, content_restrictions);
1599 pp::PDF::HistogramPDFPageCount(this, page_count);
1602 void Instance::RotateClockwise() {
1603 engine_->RotateClockwise();
1606 void Instance::RotateCounterclockwise() {
1607 engine_->RotateCounterclockwise();
1610 bool Instance::IsMouseOnScrollbar(const pp::InputEvent& event) {
1611 pp::MouseInputEvent mouse_event(event);
1612 if (mouse_event.is_null())
1613 return false;
1615 pp::Point pt = mouse_event.GetPosition();
1616 pp::Rect temp;
1617 if ((v_scrollbar_.get() && v_scrollbar_->GetLocation(&temp) &&
1618 temp.Contains(pt)) ||
1619 (h_scrollbar_.get() && h_scrollbar_->GetLocation(&temp) &&
1620 temp.Contains(pt))) {
1621 return true;
1623 return false;
1626 void Instance::PreviewDocumentLoadComplete() {
1627 if (preview_document_load_state_ != LOAD_STATE_LOADING ||
1628 preview_pages_info_.empty()) {
1629 return;
1632 preview_document_load_state_ = LOAD_STATE_COMPLETE;
1634 int dest_page_index = preview_pages_info_.front().second;
1635 int src_page_index =
1636 ExtractPrintPreviewPageIndex(preview_pages_info_.front().first);
1637 if (src_page_index > 0 && dest_page_index > -1 && preview_engine_.get())
1638 engine_->AppendPage(preview_engine_.get(), dest_page_index);
1640 preview_pages_info_.pop();
1641 // |print_preview_page_count_| is not updated yet. Do not load any
1642 // other preview pages till we get this information.
1643 if (print_preview_page_count_ == 0)
1644 return;
1646 if (preview_pages_info_.size())
1647 LoadAvailablePreviewPage();
1650 void Instance::DocumentLoadFailed() {
1651 DCHECK(document_load_state_ == LOAD_STATE_LOADING);
1652 UserMetricsRecordAction("PDF.LoadFailure");
1654 // Hide progress control.
1655 progress_bar_.Fade(false, kProgressFadeTimeoutMs);
1657 if (did_call_start_loading_) {
1658 pp::PDF::DidStopLoading(this);
1659 did_call_start_loading_ = false;
1662 document_load_state_ = LOAD_STATE_FAILED;
1663 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
1666 void Instance::PreviewDocumentLoadFailed() {
1667 UserMetricsRecordAction("PDF.PreviewDocumentLoadFailure");
1668 if (preview_document_load_state_ != LOAD_STATE_LOADING ||
1669 preview_pages_info_.empty()) {
1670 return;
1673 preview_document_load_state_ = LOAD_STATE_FAILED;
1674 preview_pages_info_.pop();
1676 if (preview_pages_info_.size())
1677 LoadAvailablePreviewPage();
1680 pp::Instance* Instance::GetPluginInstance() {
1681 return GetInstance();
1684 void Instance::DocumentHasUnsupportedFeature(const std::string& feature) {
1685 std::string metric("PDF_Unsupported_");
1686 metric += feature;
1687 if (!unsupported_features_reported_.count(metric)) {
1688 unsupported_features_reported_.insert(metric);
1689 UserMetricsRecordAction(metric);
1692 // Since we use an info bar, only do this for full frame plugins..
1693 if (!full_)
1694 return;
1696 if (told_browser_about_unsupported_feature_)
1697 return;
1698 told_browser_about_unsupported_feature_ = true;
1700 pp::PDF::HasUnsupportedFeature(this);
1703 void Instance::DocumentLoadProgress(uint32 available, uint32 doc_size) {
1704 double progress = 0.0;
1705 if (doc_size == 0) {
1706 // Document size is unknown. Use heuristics.
1707 // We'll make progress logarithmic from 0 to 100M.
1708 static const double kFactor = log(100000000.0) / 100.0;
1709 if (available > 0) {
1710 progress = log(static_cast<double>(available)) / kFactor;
1711 if (progress > 100.0)
1712 progress = 100.0;
1714 } else {
1715 progress = 100.0 * static_cast<double>(available) / doc_size;
1717 progress_bar_.SetProgress(progress);
1720 void Instance::FormTextFieldFocusChange(bool in_focus) {
1721 if (!text_input_.get())
1722 return;
1723 if (in_focus)
1724 text_input_->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_TEXT);
1725 else
1726 text_input_->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_NONE);
1729 // Called by PDFScriptableObject.
1730 bool Instance::HasScriptableMethod(const pp::Var& method, pp::Var* exception) {
1731 std::string method_str = method.AsString();
1732 return (method_str == kJSAccessibility ||
1733 method_str == kJSDocumentLoadComplete ||
1734 method_str == kJSGetHeight ||
1735 method_str == kJSGetHorizontalScrollbarThickness ||
1736 method_str == kJSGetPageLocationNormalized ||
1737 method_str == kJSGetSelectedText ||
1738 method_str == kJSGetVerticalScrollbarThickness ||
1739 method_str == kJSGetWidth ||
1740 method_str == kJSGetZoomLevel ||
1741 method_str == kJSGoToPage ||
1742 method_str == kJSGrayscale ||
1743 method_str == kJSLoadPreviewPage ||
1744 method_str == kJSOnLoad ||
1745 method_str == kJSOnPluginSizeChanged ||
1746 method_str == kJSOnScroll ||
1747 method_str == kJSPageXOffset ||
1748 method_str == kJSPageYOffset ||
1749 method_str == kJSPrintPreviewPageCount ||
1750 method_str == kJSReload ||
1751 method_str == kJSRemovePrintButton ||
1752 method_str == kJSResetPrintPreviewUrl ||
1753 method_str == kJSSendKeyEvent ||
1754 method_str == kJSSetPageNumbers ||
1755 method_str == kJSSetPageXOffset ||
1756 method_str == kJSSetPageYOffset ||
1757 method_str == kJSSetZoomLevel ||
1758 method_str == kJSZoomFitToHeight ||
1759 method_str == kJSZoomFitToWidth ||
1760 method_str == kJSZoomIn ||
1761 method_str == kJSZoomOut);
1764 pp::Var Instance::CallScriptableMethod(const pp::Var& method,
1765 const std::vector<pp::Var>& args,
1766 pp::Var* exception) {
1767 std::string method_str = method.AsString();
1768 if (method_str == kJSGrayscale) {
1769 if (args.size() == 1 && args[0].is_bool()) {
1770 engine_->SetGrayscale(args[0].AsBool());
1771 // Redraw
1772 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
1773 #ifdef ENABLE_THUMBNAILS
1774 if (thumbnails_.visible())
1775 thumbnails_.Show(true, true);
1776 #endif
1777 return pp::Var(true);
1779 return pp::Var(false);
1781 if (method_str == kJSOnLoad) {
1782 if (args.size() == 1 && args[0].is_string()) {
1783 on_load_callback_ = args[0];
1784 return pp::Var(true);
1786 return pp::Var(false);
1788 if (method_str == kJSOnScroll) {
1789 if (args.size() == 1 && args[0].is_string()) {
1790 on_scroll_callback_ = args[0];
1791 return pp::Var(true);
1793 return pp::Var(false);
1795 if (method_str == kJSOnPluginSizeChanged) {
1796 if (args.size() == 1 && args[0].is_string()) {
1797 on_plugin_size_changed_callback_ = args[0];
1798 return pp::Var(true);
1800 return pp::Var(false);
1802 if (method_str == kJSReload) {
1803 document_load_state_ = LOAD_STATE_LOADING;
1804 if (!full_)
1805 LoadUrl(url_);
1806 preview_engine_.reset();
1807 print_preview_page_count_ = 0;
1808 engine_.reset(PDFEngine::Create(this));
1809 engine_->New(url_.c_str());
1810 #ifdef ENABLE_THUMBNAILS
1811 thumbnails_.ResetEngine(engine_.get());
1812 #endif
1813 return pp::Var();
1815 if (method_str == kJSResetPrintPreviewUrl) {
1816 if (args.size() == 1 && args[0].is_string()) {
1817 url_ = args[0].AsString();
1818 preview_pages_info_ = std::queue<PreviewPageInfo>();
1819 preview_document_load_state_ = LOAD_STATE_COMPLETE;
1821 return pp::Var();
1823 if (method_str == kJSZoomFitToHeight) {
1824 SetZoom(ZOOM_FIT_TO_PAGE, 0);
1825 return pp::Var();
1827 if (method_str == kJSZoomFitToWidth) {
1828 SetZoom(ZOOM_FIT_TO_WIDTH, 0);
1829 return pp::Var();
1831 if (method_str == kJSZoomIn) {
1832 SetZoom(ZOOM_SCALE, CalculateZoom(kZoomInButtonId));
1833 return pp::Var();
1835 if (method_str == kJSZoomOut) {
1836 SetZoom(ZOOM_SCALE, CalculateZoom(kZoomOutButtonId));
1837 return pp::Var();
1839 if (method_str == kJSSetZoomLevel) {
1840 if (args.size() == 1 && args[0].is_number())
1841 SetZoom(ZOOM_SCALE, args[0].AsDouble());
1842 return pp::Var();
1844 if (method_str == kJSGetZoomLevel) {
1845 return pp::Var(zoom_);
1847 if (method_str == kJSGetHeight) {
1848 return pp::Var(plugin_size_.height());
1850 if (method_str == kJSGetWidth) {
1851 return pp::Var(plugin_size_.width());
1853 if (method_str == kJSGetHorizontalScrollbarThickness) {
1854 return pp::Var(
1855 h_scrollbar_.get() ? GetScrollbarReservedThickness() : 0);
1857 if (method_str == kJSGetVerticalScrollbarThickness) {
1858 return pp::Var(
1859 v_scrollbar_.get() ? GetScrollbarReservedThickness() : 0);
1861 if (method_str == kJSGetSelectedText) {
1862 std::string selected_text = engine_->GetSelectedText();
1863 // Always return unix newlines to JS.
1864 base::ReplaceChars(selected_text, "\r", std::string(), &selected_text);
1865 return selected_text;
1867 if (method_str == kJSDocumentLoadComplete) {
1868 return pp::Var((document_load_state_ != LOAD_STATE_LOADING));
1870 if (method_str == kJSPageYOffset) {
1871 return pp::Var(static_cast<int32_t>(
1872 v_scrollbar_.get() ? v_scrollbar_->GetValue() : 0));
1874 if (method_str == kJSSetPageYOffset) {
1875 if (args.size() == 1 && args[0].is_number() && v_scrollbar_.get())
1876 ScrollToY(GetScaled(args[0].AsInt()));
1877 return pp::Var();
1879 if (method_str == kJSPageXOffset) {
1880 return pp::Var(static_cast<int32_t>(
1881 h_scrollbar_.get() ? h_scrollbar_->GetValue() : 0));
1883 if (method_str == kJSSetPageXOffset) {
1884 if (args.size() == 1 && args[0].is_number() && h_scrollbar_.get())
1885 ScrollToX(GetScaled(args[0].AsInt()));
1886 return pp::Var();
1888 if (method_str == kJSRemovePrintButton) {
1889 CreateToolbar(kPrintPreviewToolbarButtons,
1890 arraysize(kPrintPreviewToolbarButtons));
1891 UpdateToolbarPosition(false);
1892 Invalidate(pp::Rect(plugin_size_));
1893 return pp::Var();
1895 if (method_str == kJSGoToPage) {
1896 if (args.size() == 1 && args[0].is_string()) {
1897 ScrollToPage(atoi(args[0].AsString().c_str()));
1899 return pp::Var();
1901 if (method_str == kJSAccessibility) {
1902 if (args.size() == 0) {
1903 base::DictionaryValue node;
1904 node.SetInteger(kAccessibleNumberOfPages, engine_->GetNumberOfPages());
1905 node.SetBoolean(kAccessibleLoaded,
1906 document_load_state_ != LOAD_STATE_LOADING);
1907 bool has_permissions =
1908 engine_->HasPermission(PDFEngine::PERMISSION_COPY) ||
1909 engine_->HasPermission(PDFEngine::PERMISSION_COPY_ACCESSIBLE);
1910 node.SetBoolean(kAccessibleCopyable, has_permissions);
1911 std::string json;
1912 base::JSONWriter::Write(&node, &json);
1913 return pp::Var(json);
1914 } else if (args[0].is_number()) {
1915 return pp::Var(engine_->GetPageAsJSON(args[0].AsInt()));
1918 if (method_str == kJSPrintPreviewPageCount) {
1919 if (args.size() == 1 && args[0].is_number())
1920 SetPrintPreviewMode(args[0].AsInt());
1921 return pp::Var();
1923 if (method_str == kJSLoadPreviewPage) {
1924 if (args.size() == 2 && args[0].is_string() && args[1].is_number())
1925 ProcessPreviewPageInfo(args[0].AsString(), args[1].AsInt());
1926 return pp::Var();
1928 if (method_str == kJSGetPageLocationNormalized) {
1929 const size_t kMaxLength = 30;
1930 char location_info[kMaxLength];
1931 int page_idx = engine_->GetMostVisiblePage();
1932 if (page_idx < 0)
1933 return pp::Var(std::string());
1934 pp::Rect rect = engine_->GetPageContentsRect(page_idx);
1935 int v_scrollbar_reserved_thickness =
1936 v_scrollbar_.get() ? GetScaled(GetScrollbarReservedThickness()) : 0;
1938 rect.set_x(rect.x() + ((plugin_size_.width() -
1939 v_scrollbar_reserved_thickness - available_area_.width()) / 2));
1940 base::snprintf(location_info,
1941 kMaxLength,
1942 "%0.4f;%0.4f;%0.4f;%0.4f;",
1943 rect.x() / static_cast<float>(plugin_size_.width()),
1944 rect.y() / static_cast<float>(plugin_size_.height()),
1945 rect.width() / static_cast<float>(plugin_size_.width()),
1946 rect.height()/ static_cast<float>(plugin_size_.height()));
1947 return pp::Var(std::string(location_info));
1949 if (method_str == kJSSetPageNumbers) {
1950 if (args.size() != 1 || !args[0].is_string())
1951 return pp::Var();
1952 const int num_pages_signed = engine_->GetNumberOfPages();
1953 if (num_pages_signed <= 0)
1954 return pp::Var();
1955 scoped_ptr<base::ListValue> page_ranges(static_cast<base::ListValue*>(
1956 base::JSONReader::Read(args[0].AsString(), false)));
1957 const size_t num_pages = static_cast<size_t>(num_pages_signed);
1958 if (!page_ranges.get() || page_ranges->GetSize() != num_pages)
1959 return pp::Var();
1961 std::vector<int> print_preview_page_numbers;
1962 for (size_t index = 0; index < num_pages; ++index) {
1963 int page_number = 0; // |page_number| is 1-based.
1964 if (!page_ranges->GetInteger(index, &page_number) || page_number < 1)
1965 return pp::Var();
1966 print_preview_page_numbers.push_back(page_number);
1968 print_preview_page_numbers_ = print_preview_page_numbers;
1969 page_indicator_.set_current_page(GetPageNumberToDisplay());
1970 return pp::Var();
1972 // This is here to work around https://bugs.webkit.org/show_bug.cgi?id=16735.
1973 // In JS, creating a synthetic keyboard event and dispatching it always
1974 // result in a keycode of 0.
1975 if (method_str == kJSSendKeyEvent) {
1976 if (args.size() == 1 && args[0].is_number()) {
1977 pp::KeyboardInputEvent event(
1978 this, // instance
1979 PP_INPUTEVENT_TYPE_KEYDOWN, // HandleInputEvent only care about this.
1980 0, // timestamp, not used for kbd events.
1981 0, // no modifiers.
1982 args[0].AsInt(), // keycode.
1983 pp::Var()); // no char text needed.
1984 HandleInputEvent(event);
1987 return pp::Var();
1990 void Instance::OnGeometryChanged(double old_zoom, float old_device_scale) {
1991 bool force_no_horizontal_scrollbar = false;
1992 int scrollbar_thickness = GetScrollbarThickness();
1994 if (old_device_scale != device_scale_) {
1995 // Change in device scale forces us to recreate resources
1996 ConfigureNumberImageGenerator();
1998 CreateToolbar(current_tb_info_, current_tb_info_size_);
1999 // Load autoscroll anchor image.
2000 autoscroll_anchor_ =
2001 CreateResourceImage(PP_RESOURCEIMAGE_PDF_PAN_SCROLL_ICON);
2003 ConfigurePageIndicator();
2004 ConfigureProgressBar();
2006 pp::Point scroll_position = engine_->GetScrollPosition();
2007 ScalePoint(device_scale_ / old_device_scale, &scroll_position);
2008 engine_->SetScrollPosition(scroll_position);
2011 UpdateZoomScale();
2012 if (zoom_ != old_zoom || device_scale_ != old_device_scale)
2013 engine_->ZoomUpdated(zoom_ * device_scale_);
2014 if (zoom_ != old_zoom)
2015 ZoomChanged(zoom_);
2017 available_area_ = pp::Rect(plugin_size_);
2018 if (GetDocumentPixelHeight() > plugin_size_.height()) {
2019 CreateVerticalScrollbar();
2020 } else {
2021 DestroyVerticalScrollbar();
2024 int v_scrollbar_reserved_thickness =
2025 v_scrollbar_.get() ? GetScaled(GetScrollbarReservedThickness()) : 0;
2027 if (!force_no_horizontal_scrollbar &&
2028 GetDocumentPixelWidth() >
2029 (plugin_size_.width() - v_scrollbar_reserved_thickness)) {
2030 CreateHorizontalScrollbar();
2032 // Adding the horizontal scrollbar now might cause us to need vertical
2033 // scrollbars.
2034 if (GetDocumentPixelHeight() >
2035 plugin_size_.height() - GetScaled(GetScrollbarReservedThickness())) {
2036 CreateVerticalScrollbar();
2039 } else {
2040 DestroyHorizontalScrollbar();
2043 #ifdef ENABLE_THUMBNAILS
2044 int thumbnails_pos = 0, thumbnails_total = 0;
2045 #endif
2046 if (v_scrollbar_.get()) {
2047 v_scrollbar_->SetScale(device_scale_);
2048 available_area_.set_width(
2049 std::max(0, plugin_size_.width() - v_scrollbar_reserved_thickness));
2051 #ifdef ENABLE_THUMBNAILS
2052 int height = plugin_size_.height();
2053 #endif
2054 int height_dip = plugin_dip_size_.height();
2056 #if defined(OS_MACOSX)
2057 // Before Lion, Mac always had the resize at the bottom. After that, it
2058 // never did.
2059 if ((base::mac::IsOSSnowLeopard() && full_) ||
2060 (base::mac::IsOSLionOrLater() && h_scrollbar_.get())) {
2061 #else
2062 if (h_scrollbar_.get()) {
2063 #endif // defined(OS_MACOSX)
2064 #ifdef ENABLE_THUMBNAILS
2065 height -= GetScaled(GetScrollbarThickness());
2066 #endif
2067 height_dip -= GetScrollbarThickness();
2069 #ifdef ENABLE_THUMBNAILS
2070 int32 doc_height = GetDocumentPixelHeight();
2071 #endif
2072 int32 doc_height_dip =
2073 static_cast<int32>(GetDocumentPixelHeight() / device_scale_);
2074 #if defined(OS_MACOSX)
2075 // On the Mac we always allow room for the resize button (whose width is
2076 // the same as that of the scrollbar) in full mode. However, if there is no
2077 // no horizontal scrollbar, the end of the scrollbar will scroll past the
2078 // end of the document. This is because the scrollbar assumes that its own
2079 // height (in the case of a vscroll bar) is the same as the height of the
2080 // viewport. Since the viewport is actually larger, we compensate by
2081 // adjusting the document height. Similar logic applies below for the
2082 // horizontal scrollbar.
2083 // For example, if the document size is 1000, and the viewport size is 200,
2084 // then the scrollbar position at the end will be 800. In this case the
2085 // viewport is actally 215 (assuming 15 as the scrollbar width) but the
2086 // scrollbar thinks it is 200. We want the scrollbar position at the end to
2087 // be 785. Making the document size 985 achieves this.
2088 if (full_ && !h_scrollbar_.get()) {
2089 #ifdef ENABLE_THUMBNAILS
2090 doc_height -= GetScaled(GetScrollbarThickness());
2091 #endif
2092 doc_height_dip -= GetScrollbarThickness();
2094 #endif // defined(OS_MACOSX)
2096 int32 position;
2097 position = v_scrollbar_->GetValue();
2098 position = static_cast<int>(position * zoom_ / old_zoom);
2099 valid_v_range_ = doc_height_dip - height_dip;
2100 if (position > valid_v_range_)
2101 position = valid_v_range_;
2103 v_scrollbar_->SetValue(position);
2105 PP_Rect loc;
2106 loc.point.x = static_cast<int>(available_area_.right() / device_scale_);
2107 if (IsOverlayScrollbar())
2108 loc.point.x -= scrollbar_thickness;
2109 loc.point.y = 0;
2110 loc.size.width = scrollbar_thickness;
2111 loc.size.height = height_dip;
2112 v_scrollbar_->SetLocation(loc);
2113 v_scrollbar_->SetDocumentSize(doc_height_dip);
2115 #ifdef ENABLE_THUMBNAILS
2116 thumbnails_pos = position;
2117 thumbnails_total = doc_height - height;
2118 #endif
2121 if (h_scrollbar_.get()) {
2122 h_scrollbar_->SetScale(device_scale_);
2123 available_area_.set_height(
2124 std::max(0, plugin_size_.height() -
2125 GetScaled(GetScrollbarReservedThickness())));
2127 int width_dip = plugin_dip_size_.width();
2129 // See note above.
2130 #if defined(OS_MACOSX)
2131 if ((base::mac::IsOSSnowLeopard() && full_) ||
2132 (base::mac::IsOSLionOrLater() && v_scrollbar_.get())) {
2133 #else
2134 if (v_scrollbar_.get()) {
2135 #endif
2136 width_dip -= GetScrollbarThickness();
2138 int32 doc_width_dip =
2139 static_cast<int32>(GetDocumentPixelWidth() / device_scale_);
2140 #if defined(OS_MACOSX)
2141 // See comment in the above if (v_scrollbar_.get()) block.
2142 if (full_ && !v_scrollbar_.get())
2143 doc_width_dip -= GetScrollbarThickness();
2144 #endif // defined(OS_MACOSX)
2146 int32 position;
2147 position = h_scrollbar_->GetValue();
2148 position = static_cast<int>(position * zoom_ / old_zoom);
2149 position = std::min(position, doc_width_dip - width_dip);
2151 h_scrollbar_->SetValue(position);
2153 PP_Rect loc;
2154 loc.point.x = 0;
2155 loc.point.y = static_cast<int>(available_area_.bottom() / device_scale_);
2156 if (IsOverlayScrollbar())
2157 loc.point.y -= scrollbar_thickness;
2158 loc.size.width = width_dip;
2159 loc.size.height = scrollbar_thickness;
2160 h_scrollbar_->SetLocation(loc);
2161 h_scrollbar_->SetDocumentSize(doc_width_dip);
2164 int doc_width = GetDocumentPixelWidth();
2165 if (doc_width < available_area_.width()) {
2166 available_area_.Offset((available_area_.width() - doc_width) / 2, 0);
2167 available_area_.set_width(doc_width);
2169 int doc_height = GetDocumentPixelHeight();
2170 if (doc_height < available_area_.height()) {
2171 available_area_.set_height(doc_height);
2174 // We'll invalidate the entire plugin anyways.
2175 UpdateToolbarPosition(false);
2176 UpdateProgressBarPosition(false);
2177 UpdatePageIndicatorPosition(false);
2179 #ifdef ENABLE_THUMBNAILS
2180 // Update thumbnail control position.
2181 thumbnails_.SetPosition(thumbnails_pos, thumbnails_total, false);
2182 pp::Rect thumbnails_rc(plugin_size_.width() - GetScaled(kThumbnailsWidth), 0,
2183 GetScaled(kThumbnailsWidth), plugin_size_.height());
2184 if (v_scrollbar_.get())
2185 thumbnails_rc.Offset(-v_scrollbar_reserved_thickness, 0);
2186 if (h_scrollbar_.get())
2187 thumbnails_rc.Inset(0, 0, 0, v_scrollbar_reserved_thickness);
2188 thumbnails_.SetRect(thumbnails_rc, false);
2189 #endif
2191 CalculateBackgroundParts();
2192 engine_->PageOffsetUpdated(available_area_.point());
2193 engine_->PluginSizeUpdated(available_area_.size());
2195 if (!document_size_.GetArea())
2196 return;
2197 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
2199 // Run the plugin size change callback asynchronously. This function can be
2200 // invoked by a layout change which should not re-enter into JS synchronously.
2201 pp::CompletionCallback callback =
2202 callback_factory_.NewCallback(&Instance::RunCallback,
2203 on_plugin_size_changed_callback_);
2204 pp::Module::Get()->core()->CallOnMainThread(0, callback);
2207 void Instance::RunCallback(int32_t, pp::Var callback) {
2208 if (callback.is_string())
2209 ExecuteScript(callback);
2212 void Instance::CreateHorizontalScrollbar() {
2213 if (h_scrollbar_.get())
2214 return;
2216 h_scrollbar_.reset(new pp::Scrollbar_Dev(this, false));
2219 void Instance::CreateVerticalScrollbar() {
2220 if (v_scrollbar_.get())
2221 return;
2223 v_scrollbar_.reset(new pp::Scrollbar_Dev(this, true));
2226 void Instance::DestroyHorizontalScrollbar() {
2227 if (!h_scrollbar_.get())
2228 return;
2229 if (h_scrollbar_->GetValue())
2230 engine_->ScrolledToXPosition(0);
2231 h_scrollbar_.reset();
2234 void Instance::DestroyVerticalScrollbar() {
2235 if (!v_scrollbar_.get())
2236 return;
2237 if (v_scrollbar_->GetValue())
2238 engine_->ScrolledToYPosition(0);
2239 v_scrollbar_.reset();
2240 page_indicator_.Show(false, true);
2243 int Instance::GetScrollbarThickness() {
2244 if (scrollbar_thickness_ == -1) {
2245 pp::Scrollbar_Dev temp_scrollbar(this, false);
2246 scrollbar_thickness_ = temp_scrollbar.GetThickness();
2247 scrollbar_reserved_thickness_ =
2248 temp_scrollbar.IsOverlay() ? 0 : scrollbar_thickness_;
2251 return scrollbar_thickness_;
2254 int Instance::GetScrollbarReservedThickness() {
2255 GetScrollbarThickness();
2256 return scrollbar_reserved_thickness_;
2259 bool Instance::IsOverlayScrollbar() {
2260 return GetScrollbarReservedThickness() == 0;
2263 void Instance::CreateToolbar(const ToolbarButtonInfo* tb_info, size_t size) {
2264 toolbar_.reset(new FadingControls());
2266 DCHECK(tb_info);
2267 DCHECK(size >= 0);
2269 // Remember the current toolbar information in case we need to recreate the
2270 // images later.
2271 current_tb_info_ = tb_info;
2272 current_tb_info_size_ = size;
2274 int max_height = 0;
2275 pp::Point origin(kToolbarFadingOffsetLeft, kToolbarFadingOffsetTop);
2276 ScalePoint(device_scale_, &origin);
2278 std::list<Button*> buttons;
2279 for (size_t i = 0; i < size; i++) {
2280 Button* btn = new Button;
2281 pp::ImageData normal_face =
2282 CreateResourceImage(tb_info[i].normal);
2283 btn->CreateButton(tb_info[i].id,
2284 origin,
2285 true,
2286 toolbar_.get(),
2287 tb_info[i].style,
2288 normal_face,
2289 CreateResourceImage(tb_info[i].highlighted),
2290 CreateResourceImage(tb_info[i].pressed));
2291 buttons.push_back(btn);
2293 origin += pp::Point(normal_face.size().width(), 0);
2294 max_height = std::max(max_height, normal_face.size().height());
2297 pp::Rect rc_toolbar(0, 0,
2298 origin.x() + GetToolbarRightOffset(),
2299 origin.y() + max_height + GetToolbarBottomOffset());
2300 toolbar_->CreateFadingControls(
2301 kToolbarId, rc_toolbar, false, this, kTransparentAlpha);
2303 std::list<Button*>::iterator iter;
2304 for (iter = buttons.begin(); iter != buttons.end(); ++iter) {
2305 toolbar_->AddControl(*iter);
2309 int Instance::GetToolbarRightOffset() {
2310 int scrollbar_thickness = GetScrollbarThickness();
2311 return GetScaled(kToolbarFadingOffsetRight) + 2 * scrollbar_thickness;
2314 int Instance::GetToolbarBottomOffset() {
2315 int scrollbar_thickness = GetScrollbarThickness();
2316 return GetScaled(kToolbarFadingOffsetBottom) + scrollbar_thickness;
2319 std::vector<pp::ImageData> Instance::GetThumbnailResources() {
2320 std::vector<pp::ImageData> num_images(10);
2321 num_images[0] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_0);
2322 num_images[1] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_1);
2323 num_images[2] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_2);
2324 num_images[3] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_3);
2325 num_images[4] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_4);
2326 num_images[5] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_5);
2327 num_images[6] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_6);
2328 num_images[7] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_7);
2329 num_images[8] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_8);
2330 num_images[9] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_9);
2331 return num_images;
2334 std::vector<pp::ImageData> Instance::GetProgressBarResources(
2335 pp::ImageData* background) {
2336 std::vector<pp::ImageData> result(9);
2337 result[0] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_0);
2338 result[1] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_1);
2339 result[2] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_2);
2340 result[3] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_3);
2341 result[4] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_4);
2342 result[5] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_5);
2343 result[6] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_6);
2344 result[7] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_7);
2345 result[8] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_8);
2346 *background = CreateResourceImage(
2347 PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_BACKGROUND);
2348 return result;
2351 void Instance::CreatePageIndicator(bool always_visible) {
2352 page_indicator_.CreatePageIndicator(kPageIndicatorId, false, this,
2353 number_image_generator(), always_visible);
2354 ConfigurePageIndicator();
2357 void Instance::ConfigurePageIndicator() {
2358 pp::ImageData background =
2359 CreateResourceImage(PP_RESOURCEIMAGE_PDF_PAGE_INDICATOR_BACKGROUND);
2360 page_indicator_.Configure(pp::Point(), background);
2363 void Instance::CreateProgressBar() {
2364 pp::ImageData background;
2365 std::vector<pp::ImageData> images = GetProgressBarResources(&background);
2366 std::string text = GetLocalizedString(PP_RESOURCESTRING_PDFPROGRESSLOADING);
2367 progress_bar_.CreateProgressControl(kProgressBarId, false, this, 0.0,
2368 device_scale_, images, background, text);
2371 void Instance::ConfigureProgressBar() {
2372 pp::ImageData background;
2373 std::vector<pp::ImageData> images = GetProgressBarResources(&background);
2374 progress_bar_.Reconfigure(background, images, device_scale_);
2377 void Instance::CreateThumbnails() {
2378 thumbnails_.CreateThumbnailControl(
2379 kThumbnailsId, pp::Rect(), false, this, engine_.get(),
2380 number_image_generator());
2383 void Instance::LoadUrl(const std::string& url) {
2384 LoadUrlInternal(url, &embed_loader_, &Instance::DidOpen);
2387 void Instance::LoadPreviewUrl(const std::string& url) {
2388 LoadUrlInternal(url, &embed_preview_loader_, &Instance::DidOpenPreview);
2391 void Instance::LoadUrlInternal(const std::string& url, pp::URLLoader* loader,
2392 void (Instance::* method)(int32_t)) {
2393 pp::URLRequestInfo request(this);
2394 request.SetURL(url);
2395 request.SetMethod("GET");
2397 *loader = CreateURLLoaderInternal();
2398 pp::CompletionCallback callback = loader_factory_.NewCallback(method);
2399 int rv = loader->Open(request, callback);
2400 if (rv != PP_OK_COMPLETIONPENDING)
2401 callback.Run(rv);
2404 pp::URLLoader Instance::CreateURLLoaderInternal() {
2405 pp::URLLoader loader(this);
2407 const PPB_URLLoaderTrusted* trusted_interface =
2408 reinterpret_cast<const PPB_URLLoaderTrusted*>(
2409 pp::Module::Get()->GetBrowserInterface(
2410 PPB_URLLOADERTRUSTED_INTERFACE));
2411 if (trusted_interface)
2412 trusted_interface->GrantUniversalAccess(loader.pp_resource());
2413 return loader;
2416 int Instance::GetInitialPage(const std::string& url) {
2417 size_t found_idx = url.find('#');
2418 if (found_idx == std::string::npos)
2419 return -1;
2421 const std::string& ref = url.substr(found_idx + 1);
2422 std::vector<std::string> fragments;
2423 Tokenize(ref, kDelimiters, &fragments);
2425 // Page number to return, zero-based.
2426 int page = -1;
2428 // Handle the case of http://foo.com/bar#NAMEDDEST. This is not explicitly
2429 // mentioned except by example in the Adobe "PDF Open Parameters" document.
2430 if ((fragments.size() == 1) && (fragments[0].find('=') == std::string::npos))
2431 return engine_->GetNamedDestinationPage(fragments[0]);
2433 for (size_t i = 0; i < fragments.size(); ++i) {
2434 std::vector<std::string> key_value;
2435 base::SplitString(fragments[i], '=', &key_value);
2436 if (key_value.size() != 2)
2437 continue;
2438 const std::string& key = key_value[0];
2439 const std::string& value = key_value[1];
2441 if (base::strcasecmp(kPage, key.c_str()) == 0) {
2442 // |page_value| is 1-based.
2443 int page_value = -1;
2444 if (base::StringToInt(value, &page_value) && page_value > 0)
2445 page = page_value - 1;
2446 continue;
2448 if (base::strcasecmp(kNamedDest, key.c_str()) == 0) {
2449 // |page_value| is 0-based.
2450 int page_value = engine_->GetNamedDestinationPage(value);
2451 if (page_value >= 0)
2452 page = page_value;
2453 continue;
2456 return page;
2459 void Instance::UpdateToolbarPosition(bool invalidate) {
2460 pp::Rect ctrl_rc = toolbar_->GetControlsRect();
2461 int min_toolbar_width = ctrl_rc.width() + GetToolbarRightOffset() +
2462 GetScaled(kToolbarFadingOffsetLeft);
2463 int min_toolbar_height = ctrl_rc.width() + GetToolbarBottomOffset() +
2464 GetScaled(kToolbarFadingOffsetBottom);
2466 // Update toolbar position
2467 if (plugin_size_.width() < min_toolbar_width ||
2468 plugin_size_.height() < min_toolbar_height) {
2469 // Disable toolbar if it does not fit on the screen.
2470 toolbar_->Show(false, invalidate);
2471 } else {
2472 pp::Point offset(
2473 plugin_size_.width() - GetToolbarRightOffset() - ctrl_rc.right(),
2474 plugin_size_.height() - GetToolbarBottomOffset() - ctrl_rc.bottom());
2475 toolbar_->MoveBy(offset, invalidate);
2477 int toolbar_width = std::max(plugin_size_.width() / 2, min_toolbar_width);
2478 toolbar_->ExpandLeft(toolbar_width - toolbar_->rect().width());
2479 toolbar_->Show(painted_first_page_, invalidate);
2483 void Instance::UpdateProgressBarPosition(bool invalidate) {
2484 // TODO(gene): verify we don't overlap with toolbar.
2485 int scrollbar_thickness = GetScrollbarThickness();
2486 pp::Point progress_origin(
2487 scrollbar_thickness + GetScaled(kProgressOffsetLeft),
2488 plugin_size_.height() - progress_bar_.rect().height() -
2489 scrollbar_thickness - GetScaled(kProgressOffsetBottom));
2490 progress_bar_.MoveTo(progress_origin, invalidate);
2493 void Instance::UpdatePageIndicatorPosition(bool invalidate) {
2494 int32 doc_height = static_cast<int>(document_size_.height() * zoom_);
2495 pp::Point origin(
2496 plugin_size_.width() - page_indicator_.rect().width() -
2497 GetScaled(GetScrollbarReservedThickness()),
2498 page_indicator_.GetYPosition(engine_->GetVerticalScrollbarYPosition(),
2499 doc_height, plugin_size_.height()));
2500 page_indicator_.MoveTo(origin, invalidate);
2503 void Instance::SetZoom(ZoomMode zoom_mode, double scale) {
2504 double old_zoom = zoom_;
2506 zoom_mode_ = zoom_mode;
2507 if (zoom_mode_ == ZOOM_SCALE)
2508 zoom_ = scale;
2509 UpdateZoomScale();
2511 engine_->ZoomUpdated(zoom_ * device_scale_);
2512 OnGeometryChanged(old_zoom, device_scale_);
2514 // If fit-to-height, snap to the beginning of the most visible page.
2515 if (zoom_mode_ == ZOOM_FIT_TO_PAGE) {
2516 ScrollToPage(engine_->GetMostVisiblePage());
2519 // Update sticky buttons to the current zoom style.
2520 Button* ftp_btn = static_cast<Button*>(
2521 toolbar_->GetControl(kFitToPageButtonId));
2522 Button* ftw_btn = static_cast<Button*>(
2523 toolbar_->GetControl(kFitToWidthButtonId));
2524 switch (zoom_mode_) {
2525 case ZOOM_FIT_TO_PAGE:
2526 ftp_btn->SetPressedState(true);
2527 ftw_btn->SetPressedState(false);
2528 break;
2529 case ZOOM_FIT_TO_WIDTH:
2530 ftw_btn->SetPressedState(true);
2531 ftp_btn->SetPressedState(false);
2532 break;
2533 default:
2534 ftw_btn->SetPressedState(false);
2535 ftp_btn->SetPressedState(false);
2539 void Instance::UpdateZoomScale() {
2540 switch (zoom_mode_) {
2541 case ZOOM_SCALE:
2542 break; // Keep current scale.
2543 case ZOOM_FIT_TO_PAGE: {
2544 int page_num = engine_->GetFirstVisiblePage();
2545 if (page_num == -1)
2546 break;
2547 pp::Rect rc = engine_->GetPageRect(page_num);
2548 if (!rc.height())
2549 break;
2550 // Calculate fit to width zoom level.
2551 double ftw_zoom = static_cast<double>(plugin_dip_size_.width() -
2552 GetScrollbarReservedThickness()) / document_size_.width();
2553 // Calculate fit to height zoom level. If document will not fit
2554 // horizontally, adjust zoom level to allow space for horizontal
2555 // scrollbar.
2556 double fth_zoom =
2557 static_cast<double>(plugin_dip_size_.height()) / rc.height();
2558 if (fth_zoom * document_size_.width() >
2559 plugin_dip_size_.width() - GetScrollbarReservedThickness())
2560 fth_zoom = static_cast<double>(plugin_dip_size_.height()
2561 - GetScrollbarReservedThickness()) / rc.height();
2562 zoom_ = std::min(ftw_zoom, fth_zoom);
2563 } break;
2564 case ZOOM_FIT_TO_WIDTH:
2565 case ZOOM_AUTO:
2566 if (!document_size_.width())
2567 break;
2568 zoom_ = static_cast<double>(plugin_dip_size_.width() -
2569 GetScrollbarReservedThickness()) / document_size_.width();
2570 if (zoom_mode_ == ZOOM_AUTO && zoom_ > 1.0)
2571 zoom_ = 1.0;
2572 break;
2574 zoom_ = ClipToRange(zoom_, kMinZoom, kMaxZoom);
2577 double Instance::CalculateZoom(uint32 control_id) const {
2578 if (control_id == kZoomInButtonId) {
2579 for (size_t i = 0; i < ui_zoom::kPresetZoomFactorsSize; ++i) {
2580 double current_zoom = ui_zoom::kPresetZoomFactors[i];
2581 if (current_zoom - content::kEpsilon > zoom_)
2582 return current_zoom;
2584 } else {
2585 for (size_t i = ui_zoom::kPresetZoomFactorsSize; i > 0; --i) {
2586 double current_zoom = ui_zoom::kPresetZoomFactors[i - 1];
2587 if (current_zoom + content::kEpsilon < zoom_)
2588 return current_zoom;
2591 return zoom_;
2594 pp::ImageData Instance::CreateResourceImage(PP_ResourceImage image_id) {
2595 pp::ImageData resource_data;
2596 if (hidpi_enabled_) {
2597 resource_data =
2598 pp::PDF::GetResourceImageForScale(this, image_id, device_scale_);
2601 return resource_data.data() ? resource_data
2602 : pp::PDF::GetResourceImage(this, image_id);
2605 std::string Instance::GetLocalizedString(PP_ResourceString id) {
2606 pp::Var rv(pp::PDF::GetLocalizedString(this, id));
2607 if (!rv.is_string())
2608 return std::string();
2610 return rv.AsString();
2613 void Instance::DrawText(const pp::Point& top_center, PP_ResourceString id) {
2614 std::string str(GetLocalizedString(id));
2616 pp::FontDescription_Dev description;
2617 description.set_family(PP_FONTFAMILY_SANSSERIF);
2618 description.set_size(kMessageTextSize * device_scale_);
2619 pp::Font_Dev font(this, description);
2620 int length = font.MeasureSimpleText(str);
2621 pp::Point point(top_center);
2622 point.set_x(point.x() - length / 2);
2623 DCHECK(!image_data_.is_null());
2624 font.DrawSimpleText(&image_data_, str, point, kMessageTextColor);
2627 void Instance::SetPrintPreviewMode(int page_count) {
2628 if (!IsPrintPreview() || page_count <= 0) {
2629 print_preview_page_count_ = 0;
2630 return;
2633 print_preview_page_count_ = page_count;
2634 ScrollToPage(0);
2635 engine_->AppendBlankPages(print_preview_page_count_);
2636 if (preview_pages_info_.size() > 0)
2637 LoadAvailablePreviewPage();
2640 bool Instance::IsPrintPreview() {
2641 return IsPrintPreviewUrl(url_);
2644 uint32 Instance::GetBackgroundColor() {
2645 return kBackgroundColor;
2648 int Instance::GetPageNumberToDisplay() {
2649 int page = engine_->GetMostVisiblePage();
2650 if (IsPrintPreview() && !print_preview_page_numbers_.empty()) {
2651 page = ClipToRange<int>(page, 0, print_preview_page_numbers_.size() - 1);
2652 return print_preview_page_numbers_[page];
2654 return page + 1;
2657 void Instance::ProcessPreviewPageInfo(const std::string& url,
2658 int dst_page_index) {
2659 if (!IsPrintPreview() || print_preview_page_count_ < 0)
2660 return;
2662 int src_page_index = ExtractPrintPreviewPageIndex(url);
2663 if (src_page_index < 1)
2664 return;
2666 preview_pages_info_.push(std::make_pair(url, dst_page_index));
2667 LoadAvailablePreviewPage();
2670 void Instance::LoadAvailablePreviewPage() {
2671 if (preview_pages_info_.size() <= 0)
2672 return;
2674 std::string url = preview_pages_info_.front().first;
2675 int dst_page_index = preview_pages_info_.front().second;
2676 int src_page_index = ExtractPrintPreviewPageIndex(url);
2677 if (src_page_index < 1 ||
2678 dst_page_index >= print_preview_page_count_ ||
2679 preview_document_load_state_ == LOAD_STATE_LOADING) {
2680 return;
2683 preview_document_load_state_ = LOAD_STATE_LOADING;
2684 LoadPreviewUrl(url);
2687 void Instance::EnableAutoscroll(const pp::Point& origin) {
2688 if (is_autoscroll_)
2689 return;
2691 pp::Size client_size = plugin_size_;
2692 if (v_scrollbar_.get())
2693 client_size.Enlarge(-GetScrollbarThickness(), 0);
2694 if (h_scrollbar_.get())
2695 client_size.Enlarge(0, -GetScrollbarThickness());
2697 // Do not allow autoscroll if client area is too small.
2698 if (autoscroll_anchor_.size().width() > client_size.width() ||
2699 autoscroll_anchor_.size().height() > client_size.height())
2700 return;
2702 autoscroll_rect_ = pp::Rect(
2703 pp::Point(origin.x() - autoscroll_anchor_.size().width() / 2,
2704 origin.y() - autoscroll_anchor_.size().height() / 2),
2705 autoscroll_anchor_.size());
2707 // Make sure autoscroll anchor is in the client area.
2708 if (autoscroll_rect_.right() > client_size.width()) {
2709 autoscroll_rect_.set_x(
2710 client_size.width() - autoscroll_anchor_.size().width());
2712 if (autoscroll_rect_.bottom() > client_size.height()) {
2713 autoscroll_rect_.set_y(
2714 client_size.height() - autoscroll_anchor_.size().height());
2717 if (autoscroll_rect_.x() < 0)
2718 autoscroll_rect_.set_x(0);
2719 if (autoscroll_rect_.y() < 0)
2720 autoscroll_rect_.set_y(0);
2722 is_autoscroll_ = true;
2723 Invalidate(kAutoScrollId, autoscroll_rect_);
2725 ScheduleTimer(kAutoScrollId, kAutoScrollTimeoutMs);
2728 void Instance::DisableAutoscroll() {
2729 if (is_autoscroll_) {
2730 is_autoscroll_ = false;
2731 Invalidate(kAutoScrollId, autoscroll_rect_);
2735 PP_CursorType_Dev Instance::CalculateAutoscroll(const pp::Point& mouse_pos) {
2736 // Scroll only if mouse pointer is outside of the anchor area.
2737 if (autoscroll_rect_.Contains(mouse_pos)) {
2738 autoscroll_x_ = 0;
2739 autoscroll_y_ = 0;
2740 return PP_CURSORTYPE_MIDDLEPANNING;
2743 // Relative position to the center of anchor area.
2744 pp::Point rel_pos = mouse_pos - autoscroll_rect_.CenterPoint();
2746 // Calculate angle from the X axis. Angle is in range from -pi to pi.
2747 double angle = atan2(static_cast<double>(rel_pos.y()),
2748 static_cast<double>(rel_pos.x()));
2750 autoscroll_x_ = rel_pos.x() * kAutoScrollFactor;
2751 autoscroll_y_ = rel_pos.y() * kAutoScrollFactor;
2753 // Angle is from -pi to pi. Screen Y is increasing toward bottom,
2754 // so negative angle represent north direction.
2755 if (angle < - (M_PI * 7.0 / 8.0)) {
2756 // going west
2757 return PP_CURSORTYPE_WESTPANNING;
2758 } else if (angle < - (M_PI * 5.0 / 8.0)) {
2759 // going north-west
2760 return PP_CURSORTYPE_NORTHWESTPANNING;
2761 } else if (angle < - (M_PI * 3.0 / 8.0)) {
2762 // going north.
2763 return PP_CURSORTYPE_NORTHPANNING;
2764 } else if (angle < - (M_PI * 1.0 / 8.0)) {
2765 // going north-east
2766 return PP_CURSORTYPE_NORTHEASTPANNING;
2767 } else if (angle < M_PI * 1.0 / 8.0) {
2768 // going east.
2769 return PP_CURSORTYPE_EASTPANNING;
2770 } else if (angle < M_PI * 3.0 / 8.0) {
2771 // going south-east
2772 return PP_CURSORTYPE_SOUTHEASTPANNING;
2773 } else if (angle < M_PI * 5.0 / 8.0) {
2774 // going south.
2775 return PP_CURSORTYPE_SOUTHPANNING;
2776 } else if (angle < M_PI * 7.0 / 8.0) {
2777 // going south-west
2778 return PP_CURSORTYPE_SOUTHWESTPANNING;
2781 // went around the circle, going west again
2782 return PP_CURSORTYPE_WESTPANNING;
2785 void Instance::ConfigureNumberImageGenerator() {
2786 std::vector<pp::ImageData> num_images = GetThumbnailResources();
2787 pp::ImageData number_background = CreateResourceImage(
2788 PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_NUM_BACKGROUND);
2789 number_image_generator_->Configure(number_background,
2790 num_images,
2791 device_scale_);
2794 NumberImageGenerator* Instance::number_image_generator() {
2795 if (!number_image_generator_.get()) {
2796 number_image_generator_.reset(new NumberImageGenerator(this));
2797 ConfigureNumberImageGenerator();
2799 return number_image_generator_.get();
2802 int Instance::GetScaled(int x) const {
2803 return static_cast<int>(x * device_scale_);
2806 void Instance::UserMetricsRecordAction(const std::string& action) {
2807 pp::PDF::UserMetricsRecordAction(this, pp::Var(action));
2810 PDFScriptableObject::PDFScriptableObject(Instance* instance)
2811 : instance_(instance) {
2814 PDFScriptableObject::~PDFScriptableObject() {
2817 bool PDFScriptableObject::HasMethod(const pp::Var& name, pp::Var* exception) {
2818 return instance_->HasScriptableMethod(name, exception);
2821 pp::Var PDFScriptableObject::Call(const pp::Var& method,
2822 const std::vector<pp::Var>& args,
2823 pp::Var* exception) {
2824 return instance_->CallScriptableMethod(method, args, exception);
2827 } // namespace chrome_pdf