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()
13 #include "base/json/json_reader.h"
14 #include "base/json/json_writer.h"
15 #include "base/logging.h"
16 #include "base/strings/string_number_conversions.h"
17 #include "base/strings/string_split.h"
18 #include "base/strings/string_util.h"
19 #include "base/values.h"
20 #include "chrome/browser/chrome_page_zoom_constants.h"
21 #include "chrome/common/content_restriction.h"
22 #include "content/public/common/page_zoom.h"
23 #include "net/base/escape.h"
24 #include "pdf/draw_utils.h"
25 #include "pdf/number_image_generator.h"
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"
49 namespace chrome_pdf
{
51 struct ToolbarButtonInfo
{
53 Button::ButtonStyle style
;
54 PP_ResourceImage normal
;
55 PP_ResourceImage highlighted
;
56 PP_ResourceImage pressed
;
61 // Uncomment following #define to enable thumbnails.
62 // #define ENABLE_THUMBNAILS
64 const uint32 kToolbarSplashTimeoutMs
= 6000;
65 const uint32 kMessageTextColor
= 0xFF575757;
66 const uint32 kMessageTextSize
= 22;
67 const uint32 kProgressFadeTimeoutMs
= 250;
68 const uint32 kProgressDelayTimeoutMs
= 1000;
69 const uint32 kAutoScrollTimeoutMs
= 50;
70 const double kAutoScrollFactor
= 0.2;
72 // Javascript methods.
73 const char kJSAccessibility
[] = "accessibility";
74 const char kJSDocumentLoadComplete
[] = "documentLoadComplete";
75 const char kJSGetHeight
[] = "getHeight";
76 const char kJSGetHorizontalScrollbarThickness
[] =
77 "getHorizontalScrollbarThickness";
78 const char kJSGetPageLocationNormalized
[] = "getPageLocationNormalized";
79 const char kJSGetSelectedText
[] = "getSelectedText";
80 const char kJSGetVerticalScrollbarThickness
[] = "getVerticalScrollbarThickness";
81 const char kJSGetWidth
[] = "getWidth";
82 const char kJSGetZoomLevel
[] = "getZoomLevel";
83 const char kJSGoToPage
[] = "goToPage";
84 const char kJSGrayscale
[] = "grayscale";
85 const char kJSLoadPreviewPage
[] = "loadPreviewPage";
86 const char kJSOnLoad
[] = "onload";
87 const char kJSOnPluginSizeChanged
[] = "onPluginSizeChanged";
88 const char kJSOnScroll
[] = "onScroll";
89 const char kJSPageXOffset
[] = "pageXOffset";
90 const char kJSPageYOffset
[] = "pageYOffset";
91 const char kJSPrintPreviewPageCount
[] = "printPreviewPageCount";
92 const char kJSReload
[] = "reload";
93 const char kJSRemovePrintButton
[] = "removePrintButton";
94 const char kJSResetPrintPreviewUrl
[] = "resetPrintPreviewUrl";
95 const char kJSSendKeyEvent
[] = "sendKeyEvent";
96 const char kJSSetPageNumbers
[] = "setPageNumbers";
97 const char kJSSetPageXOffset
[] = "setPageXOffset";
98 const char kJSSetPageYOffset
[] = "setPageYOffset";
99 const char kJSSetZoomLevel
[] = "setZoomLevel";
100 const char kJSZoomFitToHeight
[] = "fitToHeight";
101 const char kJSZoomFitToWidth
[] = "fitToWidth";
102 const char kJSZoomIn
[] = "zoomIn";
103 const char kJSZoomOut
[] = "zoomOut";
105 // URL reference parameters.
106 // For more possible parameters, see RFC 3778 and the "PDF Open Parameters"
107 // document from Adobe.
108 const char kDelimiters
[] = "#&";
109 const char kNamedDest
[] = "nameddest";
110 const char kPage
[] = "page";
112 const char kChromePrint
[] = "chrome://print/";
114 // Dictionary Value key names for the document accessibility info
115 const char kAccessibleNumberOfPages
[] = "numberOfPages";
116 const char kAccessibleLoaded
[] = "loaded";
117 const char kAccessibleCopyable
[] = "copyable";
119 const ToolbarButtonInfo kPDFToolbarButtons
[] = {
120 { kFitToPageButtonId
, Button::BUTTON_STATE
,
121 PP_RESOURCEIMAGE_PDF_BUTTON_FTP
,
122 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_HOVER
,
123 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_PRESSED
},
124 { kFitToWidthButtonId
, Button::BUTTON_STATE
,
125 PP_RESOURCEIMAGE_PDF_BUTTON_FTW
,
126 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_HOVER
,
127 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_PRESSED
},
128 { kZoomOutButtonId
, Button::BUTTON_CLICKABLE
,
129 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT
,
130 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_HOVER
,
131 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_PRESSED
},
132 { kZoomInButtonId
, Button::BUTTON_CLICKABLE
,
133 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN
,
134 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_HOVER
,
135 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_PRESSED
},
136 { kSaveButtonId
, Button::BUTTON_CLICKABLE
,
137 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE
,
138 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE_HOVER
,
139 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE_PRESSED
},
140 { kPrintButtonId
, Button::BUTTON_CLICKABLE
,
141 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT
,
142 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_HOVER
,
143 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_PRESSED
},
146 const ToolbarButtonInfo kPDFNoPrintToolbarButtons
[] = {
147 { kFitToPageButtonId
, Button::BUTTON_STATE
,
148 PP_RESOURCEIMAGE_PDF_BUTTON_FTP
,
149 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_HOVER
,
150 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_PRESSED
},
151 { kFitToWidthButtonId
, Button::BUTTON_STATE
,
152 PP_RESOURCEIMAGE_PDF_BUTTON_FTW
,
153 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_HOVER
,
154 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_PRESSED
},
155 { kZoomOutButtonId
, Button::BUTTON_CLICKABLE
,
156 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT
,
157 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_HOVER
,
158 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_PRESSED
},
159 { kZoomInButtonId
, Button::BUTTON_CLICKABLE
,
160 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN
,
161 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_HOVER
,
162 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_PRESSED
},
163 { kSaveButtonId
, Button::BUTTON_CLICKABLE
,
164 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE
,
165 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE_HOVER
,
166 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE_PRESSED
},
167 { kPrintButtonId
, Button::BUTTON_CLICKABLE
,
168 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_DISABLED
,
169 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_DISABLED
,
170 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_DISABLED
}
173 const ToolbarButtonInfo kPrintPreviewToolbarButtons
[] = {
174 { kFitToPageButtonId
, Button::BUTTON_STATE
,
175 PP_RESOURCEIMAGE_PDF_BUTTON_FTP
,
176 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_HOVER
,
177 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_PRESSED
},
178 { kFitToWidthButtonId
, Button::BUTTON_STATE
,
179 PP_RESOURCEIMAGE_PDF_BUTTON_FTW
,
180 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_HOVER
,
181 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_PRESSED
},
182 { kZoomOutButtonId
, Button::BUTTON_CLICKABLE
,
183 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT
,
184 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_HOVER
,
185 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_PRESSED
},
186 { kZoomInButtonId
, Button::BUTTON_CLICKABLE
,
187 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_END
,
188 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_END_HOVER
,
189 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_END_PRESSED
},
192 static const char kPPPPdfInterface
[] = PPP_PDF_INTERFACE_1
;
194 PP_Var
GetLinkAtPosition(PP_Instance instance
, PP_Point point
) {
197 pp::Instance::GetPerInstanceObject(instance
, kPPPPdfInterface
);
199 var
= static_cast<Instance
*>(object
)->GetLinkAtPosition(pp::Point(point
));
203 void Transform(PP_Instance instance
, PP_PrivatePageTransformType type
) {
205 pp::Instance::GetPerInstanceObject(instance
, kPPPPdfInterface
);
207 Instance
* obj_instance
= static_cast<Instance
*>(object
);
209 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CW
:
210 obj_instance
->RotateClockwise();
212 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CCW
:
213 obj_instance
->RotateCounterclockwise();
219 const PPP_Pdf ppp_private
= {
224 int ExtractPrintPreviewPageIndex(const std::string
& src_url
) {
225 // Sample |src_url| format: chrome://print/id/page_index/print.pdf
226 std::vector
<std::string
> url_substr
;
227 base::SplitString(src_url
.substr(strlen(kChromePrint
)), '/', &url_substr
);
228 if (url_substr
.size() != 3)
231 if (url_substr
[2] != "print.pdf")
235 if (!base::StringToInt(url_substr
[1], &page_index
))
240 bool IsPrintPreviewUrl(const std::string
& url
) {
241 return url
.substr(0, strlen(kChromePrint
)) == kChromePrint
;
244 void ScalePoint(float scale
, pp::Point
* point
) {
245 point
->set_x(static_cast<int>(point
->x() * scale
));
246 point
->set_y(static_cast<int>(point
->y() * scale
));
249 void ScaleRect(float scale
, pp::Rect
* rect
) {
250 int left
= static_cast<int>(floorf(rect
->x() * scale
));
251 int top
= static_cast<int>(floorf(rect
->y() * scale
));
252 int right
= static_cast<int>(ceilf((rect
->x() + rect
->width()) * scale
));
253 int bottom
= static_cast<int>(ceilf((rect
->y() + rect
->height()) * scale
));
254 rect
->SetRect(left
, top
, right
- left
, bottom
- top
);
258 T
ClipToRange(T value
, T lower_boundary
, T upper_boundary
) {
259 DCHECK(lower_boundary
<= upper_boundary
);
260 return std::max
<T
>(lower_boundary
, std::min
<T
>(value
, upper_boundary
));
265 Instance::Instance(PP_Instance instance
)
266 : pp::InstancePrivate(instance
),
267 pp::Find_Private(this),
268 pp::Printing_Dev(this),
269 pp::Selection_Dev(this),
270 pp::WidgetClient_Dev(this),
272 cursor_(PP_CURSORTYPE_POINTER
),
273 timer_pending_(false),
274 current_timer_id_(0),
277 printing_enabled_(true),
278 hidpi_enabled_(false),
279 full_(IsFullFrame()),
280 zoom_mode_(full_
? ZOOM_AUTO
: ZOOM_SCALE
),
281 did_call_start_loading_(false),
282 is_autoscroll_(false),
283 scrollbar_thickness_(-1),
284 scrollbar_reserved_thickness_(-1),
285 current_tb_info_(NULL
),
286 current_tb_info_size_(0),
287 paint_manager_(this, this, true),
288 delayed_progress_timer_id_(0),
290 painted_first_page_(false),
291 show_page_indicator_(false),
292 document_load_state_(LOAD_STATE_LOADING
),
293 preview_document_load_state_(LOAD_STATE_COMPLETE
),
294 told_browser_about_unsupported_feature_(false),
295 print_preview_page_count_(0) {
296 loader_factory_
.Initialize(this);
297 timer_factory_
.Initialize(this);
298 form_factory_
.Initialize(this);
299 callback_factory_
.Initialize(this);
300 engine_
.reset(PDFEngine::Create(this));
301 pp::Module::Get()->AddPluginInterface(kPPPPdfInterface
, &ppp_private
);
302 AddPerInstanceObject(kPPPPdfInterface
, this);
304 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_MOUSE
);
305 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_WHEEL
);
306 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_KEYBOARD
);
307 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_TOUCH
);
310 Instance::~Instance() {
311 if (timer_pending_
) {
312 timer_factory_
.CancelAll();
313 timer_pending_
= false;
315 // The engine may try to access this instance during its destruction.
316 // Make sure this happens early while the instance is still intact.
318 RemovePerInstanceObject(kPPPPdfInterface
, this);
321 bool Instance::Init(uint32_t argc
, const char* argn
[], const char* argv
[]) {
322 // For now, we hide HiDPI support behind a flag.
323 if (pp::PDF::IsFeatureEnabled(this, PP_PDFFEATURE_HIDPI
))
324 hidpi_enabled_
= true;
326 printing_enabled_
= pp::PDF::IsFeatureEnabled(this, PP_PDFFEATURE_PRINTING
);
327 if (printing_enabled_
) {
328 CreateToolbar(kPDFToolbarButtons
, arraysize(kPDFToolbarButtons
));
330 CreateToolbar(kPDFNoPrintToolbarButtons
,
331 arraysize(kPDFNoPrintToolbarButtons
));
336 // Load autoscroll anchor image.
338 CreateResourceImage(PP_RESOURCEIMAGE_PDF_PAN_SCROLL_ICON
);
340 #ifdef ENABLE_THUMBNAILS
343 const char* url
= NULL
;
344 for (uint32_t i
= 0; i
< argc
; ++i
) {
345 if (strcmp(argn
[i
], "src") == 0) {
354 CreatePageIndicator(IsPrintPreviewUrl(url
));
357 // For PDFs embedded in a frame, we don't get the data automatically like we
358 // do for full-frame loads. Start loading the data manually.
361 DCHECK(!did_call_start_loading_
);
362 pp::PDF::DidStartLoading(this);
363 did_call_start_loading_
= true;
366 ZoomLimitsChanged(kMinZoom
, kMaxZoom
);
368 text_input_
.reset(new pp::TextInput_Dev(this));
371 return engine_
->New(url
);
374 bool Instance::HandleDocumentLoad(const pp::URLLoader
& loader
) {
375 delayed_progress_timer_id_
= ScheduleTimer(kProgressBarId
,
376 kProgressDelayTimeoutMs
);
377 return engine_
->HandleDocumentLoad(loader
);
380 bool Instance::HandleInputEvent(const pp::InputEvent
& event
) {
381 // To simplify things, convert the event into device coordinates if it is
383 pp::InputEvent
event_device_res(event
);
385 pp::MouseInputEvent
mouse_event(event
);
386 if (!mouse_event
.is_null()) {
387 pp::Point point
= mouse_event
.GetPosition();
388 pp::Point movement
= mouse_event
.GetMovement();
389 ScalePoint(device_scale_
, &point
);
390 ScalePoint(device_scale_
, &movement
);
391 mouse_event
= pp::MouseInputEvent(
394 event
.GetTimeStamp(),
395 event
.GetModifiers(),
396 mouse_event
.GetButton(),
398 mouse_event
.GetClickCount(),
400 event_device_res
= mouse_event
;
404 // Check if we need to go to autoscroll mode.
405 if (event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE
&&
406 (event
.GetModifiers() & PP_INPUTEVENT_MODIFIER_MIDDLEBUTTONDOWN
)) {
407 pp::MouseInputEvent
mouse_event(event_device_res
);
408 pp::Point pos
= mouse_event
.GetPosition();
409 EnableAutoscroll(pos
);
410 UpdateCursor(CalculateAutoscroll(pos
));
413 // Quit autoscrolling on any other event.
417 #ifdef ENABLE_THUMBNAILS
418 if (event
.GetType() == PP_INPUTEVENT_TYPE_MOUSELEAVE
)
419 thumbnails_
.SlideOut();
421 if (thumbnails_
.HandleEvent(event_device_res
))
425 if (toolbar_
->HandleEvent(event_device_res
))
428 #ifdef ENABLE_THUMBNAILS
429 if (v_scrollbar_
.get() && event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE
) {
430 pp::MouseInputEvent
mouse_event(event
);
431 pp::Point pt
= mouse_event
.GetPosition();
432 pp::Rect v_scrollbar_rc
;
433 v_scrollbar_
->GetLocation(&v_scrollbar_rc
);
434 // There is a bug (https://bugs.webkit.org/show_bug.cgi?id=45208)
435 // in the webkit that makes event.u.mouse.button
436 // equal to PP_INPUTEVENT_MOUSEBUTTON_LEFT, even when no button is pressed.
437 // To work around this issue we use modifier for now, and will switch
438 // to button once the bug is fixed and webkit got merged back to our tree.
439 if (v_scrollbar_rc
.Contains(pt
) &&
440 (event
.GetModifiers() & PP_INPUTEVENT_MODIFIER_LEFTBUTTONDOWN
)) {
441 thumbnails_
.SlideIn();
444 // When scrollbar is in the scrolling mode we should display thumbnails
445 // even the mouse is outside the thumbnail and scrollbar areas.
446 // If mouse is outside plugin area, we are still getting mouse move events
447 // while scrolling. See bug description for details:
448 // http://code.google.com/p/chromium/issues/detail?id=56444
449 if (!v_scrollbar_rc
.Contains(pt
) && thumbnails_
.visible() &&
450 !(event
.GetModifiers() & PP_INPUTEVENT_MODIFIER_LEFTBUTTONDOWN
) &&
451 !thumbnails_
.rect().Contains(pt
)) {
452 thumbnails_
.SlideOut();
457 // Need to pass the event to the engine first, since if we're over an edit
458 // control we want it to get keyboard events (like space) instead of the
460 // TODO: will have to offset the mouse coordinates once we support bidi and
461 // there could be scrollbars on the left.
462 pp::InputEvent
offset_event(event_device_res
);
463 bool try_engine_first
= true;
464 switch (offset_event
.GetType()) {
465 case PP_INPUTEVENT_TYPE_MOUSEDOWN
:
466 case PP_INPUTEVENT_TYPE_MOUSEUP
:
467 case PP_INPUTEVENT_TYPE_MOUSEMOVE
:
468 case PP_INPUTEVENT_TYPE_MOUSEENTER
:
469 case PP_INPUTEVENT_TYPE_MOUSELEAVE
: {
470 pp::MouseInputEvent
mouse_event(event_device_res
);
471 pp::MouseInputEvent
mouse_event_dip(event
);
472 pp::Point point
= mouse_event
.GetPosition();
473 point
.set_x(point
.x() - available_area_
.x());
474 offset_event
= pp::MouseInputEvent(
477 event
.GetTimeStamp(),
478 event
.GetModifiers(),
479 mouse_event
.GetButton(),
481 mouse_event
.GetClickCount(),
482 mouse_event
.GetMovement());
483 if (!engine_
->IsSelecting()) {
484 if (!IsOverlayScrollbar() &&
485 !available_area_
.Contains(mouse_event
.GetPosition())) {
486 try_engine_first
= false;
487 } else if (IsOverlayScrollbar()) {
489 if ((v_scrollbar_
.get() && v_scrollbar_
->GetLocation(&temp
) &&
490 temp
.Contains(mouse_event_dip
.GetPosition())) ||
491 (h_scrollbar_
.get() && h_scrollbar_
->GetLocation(&temp
) &&
492 temp
.Contains(mouse_event_dip
.GetPosition()))) {
493 try_engine_first
= false;
502 if (try_engine_first
&& engine_
->HandleEvent(offset_event
))
505 // Left/Right arrows should scroll to the beginning of the Prev/Next page if
506 // there is no horizontal scroll bar.
507 // If fit-to-height, PgDown/PgUp should scroll to the beginning of the
508 // Prev/Next page. Spacebar / shift+spacebar should do the same.
509 if (v_scrollbar_
.get() && event
.GetType() == PP_INPUTEVENT_TYPE_KEYDOWN
) {
510 pp::KeyboardInputEvent
keyboard_event(event
);
511 bool no_h_scrollbar
= !h_scrollbar_
.get();
512 uint32_t key_code
= keyboard_event
.GetKeyCode();
513 bool page_down
= no_h_scrollbar
&& key_code
== ui::VKEY_RIGHT
;
514 bool page_up
= no_h_scrollbar
&& key_code
== ui::VKEY_LEFT
;
515 if (zoom_mode_
== ZOOM_FIT_TO_PAGE
) {
517 keyboard_event
.GetModifiers() & PP_INPUTEVENT_MODIFIER_SHIFTKEY
;
518 bool key_is_space
= key_code
== ui::VKEY_SPACE
;
519 page_down
|= key_is_space
|| key_code
== ui::VKEY_NEXT
;
520 page_up
|= (key_is_space
&& has_shift
) || (key_code
== ui::VKEY_PRIOR
);
523 int page
= engine_
->GetFirstVisiblePage();
526 // Engine calculates visible page including delimiter to the page size.
527 // We need to check here if the page itself is completely out of view and
528 // scroll to the next one in that case.
529 if (engine_
->GetPageRect(page
).bottom() * zoom_
<=
530 v_scrollbar_
->GetValue())
532 ScrollToPage(page
+ 1);
533 UpdateCursor(PP_CURSORTYPE_POINTER
);
535 } else if (page_up
) {
536 int page
= engine_
->GetFirstVisiblePage();
539 if (engine_
->GetPageRect(page
).y() * zoom_
>= v_scrollbar_
->GetValue())
542 UpdateCursor(PP_CURSORTYPE_POINTER
);
547 if (v_scrollbar_
.get() && v_scrollbar_
->HandleEvent(event
)) {
548 UpdateCursor(PP_CURSORTYPE_POINTER
);
552 if (h_scrollbar_
.get() && h_scrollbar_
->HandleEvent(event
)) {
553 UpdateCursor(PP_CURSORTYPE_POINTER
);
557 if (timer_pending_
&&
558 (event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEUP
||
559 event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE
)) {
560 timer_factory_
.CancelAll();
561 timer_pending_
= false;
562 } else if (event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE
&&
563 engine_
->IsSelecting()) {
564 bool set_timer
= false;
565 pp::MouseInputEvent
mouse_event(event
);
566 if (v_scrollbar_
.get() &&
567 (mouse_event
.GetPosition().y() <= 0 ||
568 mouse_event
.GetPosition().y() >= (plugin_dip_size_
.height() - 1))) {
569 v_scrollbar_
->ScrollBy(
570 PP_SCROLLBY_LINE
, mouse_event
.GetPosition().y() >= 0 ? 1: -1);
573 if (h_scrollbar_
.get() &&
574 (mouse_event
.GetPosition().x() <= 0 ||
575 mouse_event
.GetPosition().x() >= (plugin_dip_size_
.width() - 1))) {
576 h_scrollbar_
->ScrollBy(PP_SCROLLBY_LINE
,
577 mouse_event
.GetPosition().x() >= 0 ? 1: -1);
582 last_mouse_event_
= pp::MouseInputEvent(event
);
584 pp::CompletionCallback callback
=
585 timer_factory_
.NewCallback(&Instance::OnTimerFired
);
586 pp::Module::Get()->core()->CallOnMainThread(kDragTimerMs
, callback
);
587 timer_pending_
= true;
591 if (event
.GetType() == PP_INPUTEVENT_TYPE_KEYDOWN
) {
592 pp::KeyboardInputEvent
keyboard_event(event
);
593 const uint32 modifier
= event
.GetModifiers();
594 if (modifier
& kDefaultKeyModifier
) {
595 switch (keyboard_event
.GetKeyCode()) {
597 engine_
->SelectAll();
601 if (modifier
& PP_INPUTEVENT_MODIFIER_CONTROLKEY
) {
602 switch (keyboard_event
.GetKeyCode()) {
605 engine_
->RotateCounterclockwise();
609 engine_
->RotateClockwise();
615 // Return true for unhandled clicks so the plugin takes focus.
616 return (event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN
);
619 void Instance::DidChangeView(const pp::View
& view
) {
620 pp::Rect
view_rect(view
.GetRect());
621 float device_scale
= 1.0f
;
622 float old_device_scale
= device_scale_
;
624 device_scale
= view
.GetDeviceScale();
625 pp::Size
view_device_size(view_rect
.width() * device_scale
,
626 view_rect
.height() * device_scale
);
627 if (view_device_size
== plugin_size_
&& device_scale
== device_scale_
)
628 return; // We don't care about the position, only the size.
630 image_data_
= pp::ImageData();
631 device_scale_
= device_scale
;
632 plugin_dip_size_
= view_rect
.size();
633 plugin_size_
= view_device_size
;
635 paint_manager_
.SetSize(view_device_size
, device_scale_
);
637 image_data_
= pp::ImageData(this,
638 PP_IMAGEDATAFORMAT_BGRA_PREMUL
,
641 if (image_data_
.is_null()) {
642 DCHECK(plugin_size_
.IsEmpty());
646 // View dimensions changed, disable autoscroll (if it was enabled).
649 OnGeometryChanged(zoom_
, old_device_scale
);
652 pp::Var
Instance::GetInstanceObject() {
653 if (instance_object_
.is_undefined()) {
654 PDFScriptableObject
* object
= new PDFScriptableObject(this);
655 // The pp::Var takes ownership of object here.
656 instance_object_
= pp::VarPrivate(this, object
);
659 return instance_object_
;
662 pp::Var
Instance::GetLinkAtPosition(const pp::Point
& point
) {
663 pp::Point
offset_point(point
);
664 ScalePoint(device_scale_
, &offset_point
);
665 offset_point
.set_x(offset_point
.x() - available_area_
.x());
666 return engine_
->GetLinkAtPosition(offset_point
);
669 pp::Var
Instance::GetSelectedText(bool html
) {
670 if (html
|| !engine_
->HasPermission(PDFEngine::PERMISSION_COPY
))
672 return engine_
->GetSelectedText();
675 void Instance::InvalidateWidget(pp::Widget_Dev widget
,
676 const pp::Rect
& dirty_rect
) {
677 if (v_scrollbar_
.get() && *v_scrollbar_
== widget
) {
678 if (!image_data_
.is_null())
679 v_scrollbar_
->Paint(dirty_rect
.pp_rect(), &image_data_
);
680 } else if (h_scrollbar_
.get() && *h_scrollbar_
== widget
) {
681 if (!image_data_
.is_null())
682 h_scrollbar_
->Paint(dirty_rect
.pp_rect(), &image_data_
);
684 // Possible to hit this condition since sometimes the scrollbar codes posts
685 // a task to do something later, and we could have deleted our reference in
690 pp::Rect dirty_rect_scaled
= dirty_rect
;
691 ScaleRect(device_scale_
, &dirty_rect_scaled
);
692 paint_manager_
.InvalidateRect(dirty_rect_scaled
);
695 void Instance::ScrollbarValueChanged(pp::Scrollbar_Dev scrollbar
,
697 value
= GetScaled(value
);
698 if (v_scrollbar_
.get() && *v_scrollbar_
== scrollbar
) {
699 engine_
->ScrolledToYPosition(value
);
701 v_scrollbar_
->GetLocation(&rc
);
702 int32 doc_height
= GetDocumentPixelHeight();
703 doc_height
-= GetScaled(rc
.height());
704 #ifdef ENABLE_THUMBNAILS
705 if (thumbnails_
.visible()) {
706 thumbnails_
.SetPosition(value
, doc_height
, true);
710 plugin_size_
.width() - page_indicator_
.rect().width() -
711 GetScaled(GetScrollbarReservedThickness()),
712 page_indicator_
.GetYPosition(value
, doc_height
, plugin_size_
.height()));
713 page_indicator_
.MoveTo(origin
, page_indicator_
.visible());
714 } else if (h_scrollbar_
.get() && *h_scrollbar_
== scrollbar
) {
715 engine_
->ScrolledToXPosition(value
);
719 void Instance::ScrollbarOverlayChanged(pp::Scrollbar_Dev scrollbar
,
721 scrollbar_reserved_thickness_
= overlay
? 0 : scrollbar_thickness_
;
722 OnGeometryChanged(zoom_
, device_scale_
);
725 uint32_t Instance::QuerySupportedPrintOutputFormats() {
726 return engine_
->QuerySupportedPrintOutputFormats();
729 int32_t Instance::PrintBegin(const PP_PrintSettings_Dev
& print_settings
) {
730 // For us num_pages is always equal to the number of pages in the PDF
731 // document irrespective of the printable area.
732 int32_t ret
= engine_
->GetNumberOfPages();
736 uint32_t supported_formats
= engine_
->QuerySupportedPrintOutputFormats();
737 if ((print_settings
.format
& supported_formats
) == 0)
740 print_settings_
.is_printing
= true;
741 print_settings_
.pepper_print_settings
= print_settings
;
742 engine_
->PrintBegin();
746 pp::Resource
Instance::PrintPages(
747 const PP_PrintPageNumberRange_Dev
* page_ranges
,
748 uint32_t page_range_count
) {
749 if (!print_settings_
.is_printing
)
750 return pp::Resource();
752 print_settings_
.print_pages_called_
= true;
753 return engine_
->PrintPages(page_ranges
, page_range_count
,
754 print_settings_
.pepper_print_settings
);
757 void Instance::PrintEnd() {
758 if (print_settings_
.print_pages_called_
)
759 UserMetricsRecordAction("PDF.PrintPage");
760 print_settings_
.Clear();
764 bool Instance::IsPrintScalingDisabled() {
765 return !engine_
->GetPrintScaling();
768 bool Instance::StartFind(const std::string
& text
, bool case_sensitive
) {
769 engine_
->StartFind(text
.c_str(), case_sensitive
);
773 void Instance::SelectFindResult(bool forward
) {
774 engine_
->SelectFindResult(forward
);
777 void Instance::StopFind() {
781 void Instance::Zoom(double scale
, bool text_only
) {
782 UserMetricsRecordAction("PDF.ZoomFromBrowser");
784 // If the zoom level doesn't change it means that this zoom change might have
785 // been initiated by the plugin. In that case, we don't want to change the
786 // zoom mode to ZOOM_SCALE as it may have been intentionally set to
787 // ZOOM_FIT_TO_PAGE or some other value when the zoom was last changed.
791 SetZoom(ZOOM_SCALE
, scale
);
794 void Instance::ZoomChanged(double factor
) {
796 Zoom_Dev::ZoomChanged(factor
);
799 void Instance::OnPaint(const std::vector
<pp::Rect
>& paint_rects
,
800 std::vector
<PaintManager::ReadyRect
>* ready
,
801 std::vector
<pp::Rect
>* pending
) {
802 if (image_data_
.is_null()) {
803 DCHECK(plugin_size_
.IsEmpty());
807 first_paint_
= false;
808 pp::Rect rect
= pp::Rect(pp::Point(), plugin_size_
);
809 FillRect(rect
, kBackgroundColor
);
810 ready
->push_back(PaintManager::ReadyRect(rect
, image_data_
, true));
811 *pending
= paint_rects
;
817 for (size_t i
= 0; i
< paint_rects
.size(); i
++) {
818 // Intersect with plugin area since there could be pending invalidates from
819 // when the plugin area was larger.
821 paint_rects
[i
].Intersect(pp::Rect(pp::Point(), plugin_size_
));
825 pp::Rect pdf_rect
= available_area_
.Intersect(rect
);
826 if (!pdf_rect
.IsEmpty()) {
827 pdf_rect
.Offset(available_area_
.x() * -1, 0);
829 std::vector
<pp::Rect
> pdf_ready
;
830 std::vector
<pp::Rect
> pdf_pending
;
831 engine_
->Paint(pdf_rect
, &image_data_
, &pdf_ready
, &pdf_pending
);
832 for (size_t j
= 0; j
< pdf_ready
.size(); ++j
) {
833 pdf_ready
[j
].Offset(available_area_
.point());
835 PaintManager::ReadyRect(pdf_ready
[j
], image_data_
, false));
837 for (size_t j
= 0; j
< pdf_pending
.size(); ++j
) {
838 pdf_pending
[j
].Offset(available_area_
.point());
839 pending
->push_back(pdf_pending
[j
]);
843 for (size_t j
= 0; j
< background_parts_
.size(); ++j
) {
844 pp::Rect intersection
= background_parts_
[j
].location
.Intersect(rect
);
845 if (!intersection
.IsEmpty()) {
846 FillRect(intersection
, background_parts_
[j
].color
);
848 PaintManager::ReadyRect(intersection
, image_data_
, false));
852 if (document_load_state_
== LOAD_STATE_FAILED
) {
853 pp::Point top_center
;
854 top_center
.set_x(plugin_size_
.width() / 2);
855 top_center
.set_y(plugin_size_
.height() / 2);
856 DrawText(top_center
, PP_RESOURCESTRING_PDFLOAD_FAILED
);
859 #ifdef ENABLE_THUMBNAILS
860 thumbnails_
.Paint(&image_data_
, rect
);
864 engine_
->PostPaint();
866 // Must paint scrollbars after the background parts, in case we have an
867 // overlay scrollbar that's over the background. We also do this in a separate
868 // loop because the scrollbar painting logic uses the signal of whether there
869 // are pending paints or not to figure out if it should draw right away or
871 for (size_t i
= 0; i
< paint_rects
.size(); i
++) {
872 PaintIfWidgetIntersects(h_scrollbar_
.get(), paint_rects
[i
], ready
, pending
);
873 PaintIfWidgetIntersects(v_scrollbar_
.get(), paint_rects
[i
], ready
, pending
);
876 if (progress_bar_
.visible())
877 PaintOverlayControl(&progress_bar_
, &image_data_
, ready
);
879 if (page_indicator_
.visible())
880 PaintOverlayControl(&page_indicator_
, &image_data_
, ready
);
882 if (toolbar_
->current_transparency() != kTransparentAlpha
)
883 PaintOverlayControl(toolbar_
.get(), &image_data_
, ready
);
885 // Paint autoscroll anchor if needed.
886 if (is_autoscroll_
) {
887 size_t limit
= ready
->size();
888 for (size_t i
= 0; i
< limit
; i
++) {
889 pp::Rect anchor_rect
= autoscroll_rect_
.Intersect((*ready
)[i
].rect
);
890 if (!anchor_rect
.IsEmpty()) {
891 pp::Rect draw_rc
= pp::Rect(
892 pp::Point(anchor_rect
.x() - autoscroll_rect_
.x(),
893 anchor_rect
.y() - autoscroll_rect_
.y()),
895 // Paint autoscroll anchor.
896 AlphaBlend(autoscroll_anchor_
, draw_rc
,
897 &image_data_
, anchor_rect
.point(), kOpaqueAlpha
);
903 void Instance::PaintOverlayControl(
905 pp::ImageData
* image_data
,
906 std::vector
<PaintManager::ReadyRect
>* ready
) {
907 // Make sure that we only paint overlay controls over an area that's ready,
908 // i.e. not pending. Otherwise we'll mark the control rect as ready and
909 // it'll overwrite the pdf region.
910 std::list
<pp::Rect
> ctrl_rects
;
911 for (size_t i
= 0; i
< ready
->size(); i
++) {
912 pp::Rect rc
= ctrl
->rect().Intersect((*ready
)[i
].rect
);
914 ctrl_rects
.push_back(rc
);
917 if (!ctrl_rects
.empty()) {
918 ctrl
->PaintMultipleRects(image_data
, ctrl_rects
);
920 std::list
<pp::Rect
>::iterator iter
;
921 for (iter
= ctrl_rects
.begin(); iter
!= ctrl_rects
.end(); ++iter
) {
922 ready
->push_back(PaintManager::ReadyRect(*iter
, *image_data
, false));
927 void Instance::DidOpen(int32_t result
) {
928 if (result
== PP_OK
) {
929 engine_
->HandleDocumentLoad(embed_loader_
);
930 } else if (result
!= PP_ERROR_ABORTED
) { // Can happen in tests.
935 void Instance::DidOpenPreview(int32_t result
) {
936 if (result
== PP_OK
) {
937 preview_engine_
.reset(PDFEngine::Create(new PreviewModeClient(this)));
938 preview_engine_
->HandleDocumentLoad(embed_preview_loader_
);
944 void Instance::PaintIfWidgetIntersects(
945 pp::Widget_Dev
* widget
,
946 const pp::Rect
& rect
,
947 std::vector
<PaintManager::ReadyRect
>* ready
,
948 std::vector
<pp::Rect
>* pending
) {
953 if (!widget
->GetLocation(&location
))
956 ScaleRect(device_scale_
, &location
);
957 location
= location
.Intersect(rect
);
958 if (location
.IsEmpty())
961 if (IsOverlayScrollbar()) {
962 // If we're using overlay scrollbars, and there are pending paints under the
963 // scrollbar, don't update the scrollbar instantly. While it would be nice,
964 // we would need to double buffer the plugin area in order to make this
965 // work. This is because we'd need to always have a copy of what the pdf
966 // under the scrollbar looks like, and additionally we couldn't paint the
967 // pdf under the scrollbar if it's ready until we got the preceding flush.
968 // So in practice, it would make painting slower and introduce extra buffer
969 // copies for the general case.
970 for (size_t i
= 0; i
< pending
->size(); ++i
) {
971 if ((*pending
)[i
].Intersects(location
))
975 // Even if none of the pending paints are under the scrollbar, we never want
976 // to paint it if it's over the pdf if there are other pending paints.
977 // Otherwise different parts of the pdf plugin would display at different
979 if (!pending
->empty() && available_area_
.Intersects(rect
)) {
980 pending
->push_back(location
);
985 pp::Rect location_dip
= location
;
986 ScaleRect(1.0f
/ device_scale_
, &location_dip
);
988 DCHECK(!image_data_
.is_null());
989 widget
->Paint(location_dip
, &image_data_
);
991 ready
->push_back(PaintManager::ReadyRect(location
, image_data_
, true));
994 void Instance::OnTimerFired(int32_t) {
995 HandleInputEvent(last_mouse_event_
);
998 void Instance::OnClientTimerFired(int32_t id
) {
999 engine_
->OnCallback(id
);
1002 void Instance::OnControlTimerFired(int32_t,
1003 const uint32
& control_id
,
1004 const uint32
& timer_id
) {
1005 if (control_id
== toolbar_
->id()) {
1006 toolbar_
->OnTimerFired(timer_id
);
1007 } else if (control_id
== progress_bar_
.id()) {
1008 if (timer_id
== delayed_progress_timer_id_
) {
1009 if (document_load_state_
== LOAD_STATE_LOADING
&&
1010 !progress_bar_
.visible()) {
1011 progress_bar_
.Fade(true, kProgressFadeTimeoutMs
);
1013 delayed_progress_timer_id_
= 0;
1015 progress_bar_
.OnTimerFired(timer_id
);
1017 } else if (control_id
== kAutoScrollId
) {
1018 if (is_autoscroll_
) {
1019 if (autoscroll_x_
!= 0 && h_scrollbar_
.get()) {
1020 h_scrollbar_
->ScrollBy(PP_SCROLLBY_PIXEL
, autoscroll_x_
);
1022 if (autoscroll_y_
!= 0 && v_scrollbar_
.get()) {
1023 v_scrollbar_
->ScrollBy(PP_SCROLLBY_PIXEL
, autoscroll_y_
);
1026 // Reschedule timer.
1027 ScheduleTimer(kAutoScrollId
, kAutoScrollTimeoutMs
);
1029 } else if (control_id
== kPageIndicatorId
) {
1030 page_indicator_
.OnTimerFired(timer_id
);
1032 #ifdef ENABLE_THUMBNAILS
1033 else if (control_id
== thumbnails_
.id()) {
1034 thumbnails_
.OnTimerFired(timer_id
);
1039 void Instance::CalculateBackgroundParts() {
1040 background_parts_
.clear();
1041 int v_scrollbar_thickness
=
1042 GetScaled(v_scrollbar_
.get() ? GetScrollbarReservedThickness() : 0);
1043 int h_scrollbar_thickness
=
1044 GetScaled(h_scrollbar_
.get() ? GetScrollbarReservedThickness() : 0);
1045 int width_without_scrollbar
= std::max(
1046 plugin_size_
.width() - v_scrollbar_thickness
, 0);
1047 int height_without_scrollbar
= std::max(
1048 plugin_size_
.height() - h_scrollbar_thickness
, 0);
1049 int left_width
= available_area_
.x();
1050 int right_start
= available_area_
.right();
1051 int right_width
= abs(width_without_scrollbar
- available_area_
.right());
1052 int bottom
= std::min(available_area_
.bottom(), height_without_scrollbar
);
1054 // Add the left, right, and bottom rectangles. Note: we assume only
1055 // horizontal centering.
1056 BackgroundPart part
= {
1057 pp::Rect(0, 0, left_width
, bottom
),
1060 if (!part
.location
.IsEmpty())
1061 background_parts_
.push_back(part
);
1062 part
.location
= pp::Rect(right_start
, 0, right_width
, bottom
);
1063 if (!part
.location
.IsEmpty())
1064 background_parts_
.push_back(part
);
1065 part
.location
= pp::Rect(
1066 0, bottom
, width_without_scrollbar
, height_without_scrollbar
- bottom
);
1067 if (!part
.location
.IsEmpty())
1068 background_parts_
.push_back(part
);
1070 if (h_scrollbar_thickness
1071 #if defined(OS_MACOSX)
1076 v_scrollbar_thickness
) {
1077 part
.color
= 0xFFFFFFFF;
1078 part
.location
= pp::Rect(plugin_size_
.width() - v_scrollbar_thickness
,
1079 plugin_size_
.height() - h_scrollbar_thickness
,
1080 h_scrollbar_thickness
,
1081 v_scrollbar_thickness
);
1082 background_parts_
.push_back(part
);
1086 int Instance::GetDocumentPixelWidth() const {
1087 return static_cast<int>(ceil(document_size_
.width() * zoom_
* device_scale_
));
1090 int Instance::GetDocumentPixelHeight() const {
1091 return static_cast<int>(ceil(document_size_
.height() *
1096 void Instance::FillRect(const pp::Rect
& rect
, uint32 color
) {
1097 DCHECK(!image_data_
.is_null() || rect
.IsEmpty());
1098 uint32
* buffer_start
= static_cast<uint32
*>(image_data_
.data());
1099 int stride
= image_data_
.stride();
1100 uint32
* ptr
= buffer_start
+ rect
.y() * stride
/ 4 + rect
.x();
1101 int height
= rect
.height();
1102 int width
= rect
.width();
1103 for (int y
= 0; y
< height
; ++y
) {
1104 for (int x
= 0; x
< width
; ++x
)
1110 void Instance::DocumentSizeUpdated(const pp::Size
& size
) {
1111 document_size_
= size
;
1113 OnGeometryChanged(zoom_
, device_scale_
);
1116 void Instance::Invalidate(const pp::Rect
& rect
) {
1117 pp::Rect
offset_rect(rect
);
1118 offset_rect
.Offset(available_area_
.point());
1119 paint_manager_
.InvalidateRect(offset_rect
);
1122 void Instance::Scroll(const pp::Point
& point
) {
1123 pp::Rect scroll_area
= available_area_
;
1124 if (IsOverlayScrollbar()) {
1126 if (h_scrollbar_
.get()) {
1127 h_scrollbar_
->GetLocation(&rc
);
1128 ScaleRect(device_scale_
, &rc
);
1129 if (scroll_area
.bottom() > rc
.y()) {
1130 scroll_area
.set_height(rc
.y() - scroll_area
.y());
1131 paint_manager_
.InvalidateRect(rc
);
1134 if (v_scrollbar_
.get()) {
1135 v_scrollbar_
->GetLocation(&rc
);
1136 ScaleRect(device_scale_
, &rc
);
1137 if (scroll_area
.right() > rc
.x()) {
1138 scroll_area
.set_width(rc
.x() - scroll_area
.x());
1139 paint_manager_
.InvalidateRect(rc
);
1143 paint_manager_
.ScrollRect(scroll_area
, point
);
1145 if (toolbar_
->current_transparency() != kTransparentAlpha
)
1146 paint_manager_
.InvalidateRect(toolbar_
->GetControlsRect());
1148 if (progress_bar_
.visible())
1149 paint_manager_
.InvalidateRect(progress_bar_
.rect());
1152 paint_manager_
.InvalidateRect(autoscroll_rect_
);
1154 if (show_page_indicator_
) {
1155 page_indicator_
.set_current_page(GetPageNumberToDisplay());
1156 page_indicator_
.Splash();
1159 if (page_indicator_
.visible())
1160 paint_manager_
.InvalidateRect(page_indicator_
.rect());
1162 // Run the scroll callback asynchronously. This function can be invoked by a
1163 // layout change which should not re-enter into JS synchronously.
1164 pp::CompletionCallback callback
=
1165 callback_factory_
.NewCallback(&Instance::RunCallback
,
1166 on_scroll_callback_
);
1167 pp::Module::Get()->core()->CallOnMainThread(0, callback
);
1170 void Instance::ScrollToX(int position
) {
1171 if (!h_scrollbar_
.get()) {
1175 int position_dip
= static_cast<int>(position
/ device_scale_
);
1176 h_scrollbar_
->SetValue(position_dip
);
1179 void Instance::ScrollToY(int position
) {
1180 if (!v_scrollbar_
.get()) {
1184 int position_dip
= static_cast<int>(position
/ device_scale_
);
1185 v_scrollbar_
->SetValue(ClipToRange(position_dip
, 0, valid_v_range_
));
1188 void Instance::ScrollToPage(int page
) {
1189 if (!v_scrollbar_
.get())
1192 if (engine_
->GetNumberOfPages() == 0)
1195 int index
= ClipToRange(page
, 0, engine_
->GetNumberOfPages() - 1);
1196 pp::Rect rect
= engine_
->GetPageRect(index
);
1197 // If we are trying to scroll pass the last page,
1198 // scroll to the end of the last page.
1199 int position
= index
< page
? rect
.bottom() : rect
.y();
1200 ScrollToY(position
* zoom_
* device_scale_
);
1203 void Instance::NavigateTo(const std::string
& url
, bool open_in_new_tab
) {
1204 std::string
url_copy(url
);
1206 // Empty |url_copy| is ok, and will effectively be a reload.
1207 // Skip the code below so an empty URL does not turn into "http://", which
1208 // will cause GURL to fail a DCHECK.
1209 if (!url_copy
.empty()) {
1210 // If |url_copy| starts with '#', then it's for the same URL with a
1211 // different URL fragment.
1212 if (url_copy
[0] == '#') {
1213 url_copy
= url_
+ url_copy
;
1214 // Changing the href does not actually do anything when navigating in the
1215 // same tab, so do the actual page scroll here. Then fall through so the
1216 // href gets updated.
1217 if (!open_in_new_tab
) {
1218 int page_number
= GetInitialPage(url_copy
);
1219 if (page_number
>= 0)
1220 ScrollToPage(page_number
);
1223 // If there's no scheme, add http.
1224 if (url_copy
.find("://") == std::string::npos
&&
1225 url_copy
.find("mailto:") == std::string::npos
) {
1226 url_copy
= "http://" + url_copy
;
1228 // Make sure |url_copy| starts with a valid scheme.
1229 if (url_copy
.find("http://") != 0 &&
1230 url_copy
.find("https://") != 0 &&
1231 url_copy
.find("ftp://") != 0 &&
1232 url_copy
.find("file://") != 0 &&
1233 url_copy
.find("mailto:") != 0) {
1236 // Make sure |url_copy| is not only a scheme.
1237 if (url_copy
== "http://" ||
1238 url_copy
== "https://" ||
1239 url_copy
== "ftp://" ||
1240 url_copy
== "file://" ||
1241 url_copy
== "mailto:") {
1245 if (open_in_new_tab
) {
1246 GetWindowObject().Call("open", url_copy
);
1248 GetWindowObject().GetProperty("top").GetProperty("location").
1249 SetProperty("href", url_copy
);
1253 void Instance::UpdateCursor(PP_CursorType_Dev cursor
) {
1254 if (cursor
== cursor_
)
1258 const PPB_CursorControl_Dev
* cursor_interface
=
1259 reinterpret_cast<const PPB_CursorControl_Dev
*>(
1260 pp::Module::Get()->GetBrowserInterface(PPB_CURSOR_CONTROL_DEV_INTERFACE
));
1261 if (!cursor_interface
) {
1266 cursor_interface
->SetCursor(
1267 pp_instance(), cursor_
, pp::ImageData().pp_resource(), NULL
);
1270 void Instance::UpdateTickMarks(const std::vector
<pp::Rect
>& tickmarks
) {
1271 if (!v_scrollbar_
.get())
1274 float inverse_scale
= 1.0f
/ device_scale_
;
1275 std::vector
<pp::Rect
> scaled_tickmarks
= tickmarks
;
1276 for (size_t i
= 0; i
< scaled_tickmarks
.size(); i
++) {
1277 ScaleRect(inverse_scale
, &scaled_tickmarks
[i
]);
1280 v_scrollbar_
->SetTickMarks(
1281 scaled_tickmarks
.empty() ? NULL
: &scaled_tickmarks
[0], tickmarks
.size());
1284 void Instance::NotifyNumberOfFindResultsChanged(int total
, bool final_result
) {
1285 NumberOfFindResultsChanged(total
, final_result
);
1288 void Instance::NotifySelectedFindResultChanged(int current_find_index
) {
1289 SelectedFindResultChanged(current_find_index
);
1292 void Instance::OnEvent(uint32 control_id
, uint32 event_id
, void* data
) {
1293 if (event_id
== Button::EVENT_ID_BUTTON_CLICKED
||
1294 event_id
== Button::EVENT_ID_BUTTON_STATE_CHANGED
) {
1295 switch (control_id
) {
1296 case kFitToPageButtonId
:
1297 UserMetricsRecordAction("PDF.FitToPageButton");
1298 SetZoom(ZOOM_FIT_TO_PAGE
, 0);
1301 case kFitToWidthButtonId
:
1302 UserMetricsRecordAction("PDF.FitToWidthButton");
1303 SetZoom(ZOOM_FIT_TO_WIDTH
, 0);
1306 case kZoomOutButtonId
:
1307 case kZoomInButtonId
:
1308 UserMetricsRecordAction(control_id
== kZoomOutButtonId
?
1309 "PDF.ZoomOutButton" : "PDF.ZoomInButton");
1310 SetZoom(ZOOM_SCALE
, CalculateZoom(control_id
));
1314 UserMetricsRecordAction("PDF.SaveButton");
1317 case kPrintButtonId
:
1318 UserMetricsRecordAction("PDF.PrintButton");
1323 if (control_id
== kThumbnailsId
&&
1324 event_id
== ThumbnailControl::EVENT_ID_THUMBNAIL_SELECTED
) {
1325 int page
= *static_cast<int*>(data
);
1326 pp::Rect
page_rc(engine_
->GetPageRect(page
));
1327 ScrollToY(static_cast<int>(page_rc
.y() * zoom_
* device_scale_
));
1331 void Instance::Invalidate(uint32 control_id
, const pp::Rect
& rc
) {
1332 paint_manager_
.InvalidateRect(rc
);
1335 uint32
Instance::ScheduleTimer(uint32 control_id
, uint32 timeout_ms
) {
1336 current_timer_id_
++;
1337 pp::CompletionCallback callback
=
1338 timer_factory_
.NewCallback(&Instance::OnControlTimerFired
,
1341 pp::Module::Get()->core()->CallOnMainThread(timeout_ms
, callback
);
1342 return current_timer_id_
;
1345 void Instance::SetEventCapture(uint32 control_id
, bool set_capture
) {
1346 // TODO(gene): set event capture here.
1349 void Instance::SetCursor(uint32 control_id
, PP_CursorType_Dev cursor_type
) {
1350 UpdateCursor(cursor_type
);
1353 pp::Instance
* Instance::GetInstance() {
1357 void Instance::GetDocumentPassword(
1358 pp::CompletionCallbackWithOutput
<pp::Var
> callback
) {
1359 std::string
message(GetLocalizedString(PP_RESOURCESTRING_PDFGETPASSWORD
));
1360 pp::Var result
= pp::PDF::ModalPromptForPassword(this, message
);
1361 *callback
.output() = result
.pp_var();
1362 callback
.Run(PP_OK
);
1365 void Instance::Alert(const std::string
& message
) {
1366 GetWindowObject().Call("alert", message
);
1369 bool Instance::Confirm(const std::string
& message
) {
1370 pp::Var result
= GetWindowObject().Call("confirm", message
);
1371 return result
.is_bool() ? result
.AsBool() : false;
1374 std::string
Instance::Prompt(const std::string
& question
,
1375 const std::string
& default_answer
) {
1376 pp::Var result
= GetWindowObject().Call("prompt", question
, default_answer
);
1377 return result
.is_string() ? result
.AsString() : std::string();
1380 std::string
Instance::GetURL() {
1384 void Instance::Email(const std::string
& to
,
1385 const std::string
& cc
,
1386 const std::string
& bcc
,
1387 const std::string
& subject
,
1388 const std::string
& body
) {
1389 std::string javascript
=
1390 "var href = 'mailto:" + net::EscapeUrlEncodedData(to
, false) +
1391 "?cc=" + net::EscapeUrlEncodedData(cc
, false) +
1392 "&bcc=" + net::EscapeUrlEncodedData(bcc
, false) +
1393 "&subject=" + net::EscapeUrlEncodedData(subject
, false) +
1394 "&body=" + net::EscapeUrlEncodedData(body
, false) +
1395 "';var temp = window.open(href, '_blank', " +
1396 "'width=1,height=1');if(temp) temp.close();";
1397 ExecuteScript(javascript
);
1400 void Instance::Print() {
1401 if (!printing_enabled_
||
1402 (!engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
) &&
1403 !engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY
))) {
1407 pp::CompletionCallback callback
=
1408 callback_factory_
.NewCallback(&Instance::OnPrint
);
1409 pp::Module::Get()->core()->CallOnMainThread(0, callback
);
1412 void Instance::OnPrint(int32_t) {
1413 pp::PDF::Print(this);
1416 void Instance::SaveAs() {
1417 pp::PDF::SaveAs(this);
1420 void Instance::SubmitForm(const std::string
& url
,
1423 pp::URLRequestInfo
request(this);
1424 request
.SetURL(url
);
1425 request
.SetMethod("POST");
1426 request
.AppendDataToBody(reinterpret_cast<const char*>(data
), length
);
1428 pp::CompletionCallback callback
=
1429 form_factory_
.NewCallback(&Instance::FormDidOpen
);
1430 form_loader_
= CreateURLLoaderInternal();
1431 int rv
= form_loader_
.Open(request
, callback
);
1432 if (rv
!= PP_OK_COMPLETIONPENDING
)
1436 void Instance::FormDidOpen(int32_t result
) {
1437 // TODO: inform the user of success/failure.
1438 if (result
!= PP_OK
) {
1443 std::string
Instance::ShowFileSelectionDialog() {
1444 // Seems like very low priority to implement, since the pdf has no way to get
1445 // the file data anyways. Javascript doesn't let you do this synchronously.
1447 return std::string();
1450 pp::URLLoader
Instance::CreateURLLoader() {
1452 if (!did_call_start_loading_
) {
1453 did_call_start_loading_
= true;
1454 pp::PDF::DidStartLoading(this);
1457 // Disable save and print until the document is fully loaded, since they
1458 // would generate an incomplete document. Need to do this each time we
1459 // call DidStartLoading since that resets the content restrictions.
1460 pp::PDF::SetContentRestriction(this, CONTENT_RESTRICTION_SAVE
|
1461 CONTENT_RESTRICTION_PRINT
);
1464 return CreateURLLoaderInternal();
1467 void Instance::ScheduleCallback(int id
, int delay_in_ms
) {
1468 pp::CompletionCallback callback
=
1469 timer_factory_
.NewCallback(&Instance::OnClientTimerFired
);
1470 pp::Module::Get()->core()->CallOnMainThread(delay_in_ms
, callback
, id
);
1473 void Instance::SearchString(const base::char16
* string
,
1474 const base::char16
* term
,
1475 bool case_sensitive
,
1476 std::vector
<SearchStringResult
>* results
) {
1477 if (!pp::PDF::IsAvailable()) {
1482 PP_PrivateFindResult
* pp_results
;
1484 pp::PDF::SearchString(
1486 reinterpret_cast<const unsigned short*>(string
),
1487 reinterpret_cast<const unsigned short*>(term
),
1492 results
->resize(count
);
1493 for (int i
= 0; i
< count
; ++i
) {
1494 (*results
)[i
].start_index
= pp_results
[i
].start_index
;
1495 (*results
)[i
].length
= pp_results
[i
].length
;
1498 pp::Memory_Dev memory
;
1499 memory
.MemFree(pp_results
);
1502 void Instance::DocumentPaintOccurred() {
1503 if (painted_first_page_
)
1506 painted_first_page_
= true;
1507 UpdateToolbarPosition(false);
1508 toolbar_
->Splash(kToolbarSplashTimeoutMs
);
1510 if (engine_
->GetNumberOfPages() > 1)
1511 show_page_indicator_
= true;
1513 show_page_indicator_
= false;
1515 if (v_scrollbar_
.get() && show_page_indicator_
) {
1516 page_indicator_
.set_current_page(GetPageNumberToDisplay());
1517 page_indicator_
.Splash(kToolbarSplashTimeoutMs
,
1518 kPageIndicatorInitialFadeTimeoutMs
);
1522 void Instance::DocumentLoadComplete(int page_count
) {
1523 // Clear focus state for OSK.
1524 FormTextFieldFocusChange(false);
1526 // Update progress control.
1527 if (progress_bar_
.visible())
1528 progress_bar_
.Fade(false, kProgressFadeTimeoutMs
);
1530 DCHECK(document_load_state_
== LOAD_STATE_LOADING
);
1531 document_load_state_
= LOAD_STATE_COMPLETE
;
1532 UserMetricsRecordAction("PDF.LoadSuccess");
1534 if (did_call_start_loading_
) {
1535 pp::PDF::DidStopLoading(this);
1536 did_call_start_loading_
= false;
1539 if (on_load_callback_
.is_string())
1540 ExecuteScript(on_load_callback_
);
1541 // Note: If we are in print preview mode on_load_callback_ might call
1542 // ScrollTo{X|Y}() and we don't want to scroll again and override it.
1543 // #page=N is not supported in Print Preview.
1544 if (!IsPrintPreview()) {
1545 int initial_page
= GetInitialPage(url_
);
1546 if (initial_page
>= 0)
1547 ScrollToPage(initial_page
);
1552 if (!pp::PDF::IsAvailable())
1555 int content_restrictions
=
1556 CONTENT_RESTRICTION_CUT
| CONTENT_RESTRICTION_PASTE
;
1557 if (!engine_
->HasPermission(PDFEngine::PERMISSION_COPY
))
1558 content_restrictions
|= CONTENT_RESTRICTION_COPY
;
1560 if (!engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
) &&
1561 !engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY
)) {
1562 printing_enabled_
= false;
1563 if (current_tb_info_
== kPDFToolbarButtons
) {
1564 // Remove Print button.
1565 CreateToolbar(kPDFNoPrintToolbarButtons
,
1566 arraysize(kPDFNoPrintToolbarButtons
));
1567 UpdateToolbarPosition(false);
1568 Invalidate(pp::Rect(plugin_size_
));
1572 pp::PDF::SetContentRestriction(this, content_restrictions
);
1574 pp::PDF::HistogramPDFPageCount(this, page_count
);
1577 void Instance::RotateClockwise() {
1578 engine_
->RotateClockwise();
1581 void Instance::RotateCounterclockwise() {
1582 engine_
->RotateCounterclockwise();
1585 void Instance::PreviewDocumentLoadComplete() {
1586 if (preview_document_load_state_
!= LOAD_STATE_LOADING
||
1587 preview_pages_info_
.empty()) {
1591 preview_document_load_state_
= LOAD_STATE_COMPLETE
;
1593 int dest_page_index
= preview_pages_info_
.front().second
;
1594 int src_page_index
=
1595 ExtractPrintPreviewPageIndex(preview_pages_info_
.front().first
);
1596 if (src_page_index
> 0 && dest_page_index
> -1 && preview_engine_
.get())
1597 engine_
->AppendPage(preview_engine_
.get(), dest_page_index
);
1599 preview_pages_info_
.pop();
1600 // |print_preview_page_count_| is not updated yet. Do not load any
1601 // other preview pages till we get this information.
1602 if (print_preview_page_count_
== 0)
1605 if (preview_pages_info_
.size())
1606 LoadAvailablePreviewPage();
1609 void Instance::DocumentLoadFailed() {
1610 DCHECK(document_load_state_
== LOAD_STATE_LOADING
);
1611 UserMetricsRecordAction("PDF.LoadFailure");
1613 // Hide progress control.
1614 progress_bar_
.Fade(false, kProgressFadeTimeoutMs
);
1616 if (did_call_start_loading_
) {
1617 pp::PDF::DidStopLoading(this);
1618 did_call_start_loading_
= false;
1621 document_load_state_
= LOAD_STATE_FAILED
;
1622 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
1625 void Instance::PreviewDocumentLoadFailed() {
1626 UserMetricsRecordAction("PDF.PreviewDocumentLoadFailure");
1627 if (preview_document_load_state_
!= LOAD_STATE_LOADING
||
1628 preview_pages_info_
.empty()) {
1632 preview_document_load_state_
= LOAD_STATE_FAILED
;
1633 preview_pages_info_
.pop();
1635 if (preview_pages_info_
.size())
1636 LoadAvailablePreviewPage();
1639 pp::Instance
* Instance::GetPluginInstance() {
1640 return GetInstance();
1643 void Instance::DocumentHasUnsupportedFeature(const std::string
& feature
) {
1644 std::string
metric("PDF_Unsupported_");
1646 if (!unsupported_features_reported_
.count(metric
)) {
1647 unsupported_features_reported_
.insert(metric
);
1648 UserMetricsRecordAction(metric
);
1651 // Since we use an info bar, only do this for full frame plugins..
1655 if (told_browser_about_unsupported_feature_
)
1657 told_browser_about_unsupported_feature_
= true;
1659 pp::PDF::HasUnsupportedFeature(this);
1662 void Instance::DocumentLoadProgress(uint32 available
, uint32 doc_size
) {
1663 double progress
= 0.0;
1664 if (doc_size
== 0) {
1665 // Document size is unknown. Use heuristics.
1666 // We'll make progress logarithmic from 0 to 100M.
1667 static const double kFactor
= log(100000000.0) / 100.0;
1668 if (available
> 0) {
1669 progress
= log(static_cast<double>(available
)) / kFactor
;
1670 if (progress
> 100.0)
1674 progress
= 100.0 * static_cast<double>(available
) / doc_size
;
1676 progress_bar_
.SetProgress(progress
);
1679 void Instance::FormTextFieldFocusChange(bool in_focus
) {
1680 if (!text_input_
.get())
1683 text_input_
->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_TEXT
);
1685 text_input_
->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_NONE
);
1688 // Called by PDFScriptableObject.
1689 bool Instance::HasScriptableMethod(const pp::Var
& method
, pp::Var
* exception
) {
1690 std::string method_str
= method
.AsString();
1691 return (method_str
== kJSAccessibility
||
1692 method_str
== kJSDocumentLoadComplete
||
1693 method_str
== kJSGetHeight
||
1694 method_str
== kJSGetHorizontalScrollbarThickness
||
1695 method_str
== kJSGetPageLocationNormalized
||
1696 method_str
== kJSGetSelectedText
||
1697 method_str
== kJSGetVerticalScrollbarThickness
||
1698 method_str
== kJSGetWidth
||
1699 method_str
== kJSGetZoomLevel
||
1700 method_str
== kJSGoToPage
||
1701 method_str
== kJSGrayscale
||
1702 method_str
== kJSLoadPreviewPage
||
1703 method_str
== kJSOnLoad
||
1704 method_str
== kJSOnPluginSizeChanged
||
1705 method_str
== kJSOnScroll
||
1706 method_str
== kJSPageXOffset
||
1707 method_str
== kJSPageYOffset
||
1708 method_str
== kJSPrintPreviewPageCount
||
1709 method_str
== kJSReload
||
1710 method_str
== kJSRemovePrintButton
||
1711 method_str
== kJSResetPrintPreviewUrl
||
1712 method_str
== kJSSendKeyEvent
||
1713 method_str
== kJSSetPageNumbers
||
1714 method_str
== kJSSetPageXOffset
||
1715 method_str
== kJSSetPageYOffset
||
1716 method_str
== kJSSetZoomLevel
||
1717 method_str
== kJSZoomFitToHeight
||
1718 method_str
== kJSZoomFitToWidth
||
1719 method_str
== kJSZoomIn
||
1720 method_str
== kJSZoomOut
);
1723 pp::Var
Instance::CallScriptableMethod(const pp::Var
& method
,
1724 const std::vector
<pp::Var
>& args
,
1725 pp::Var
* exception
) {
1726 std::string method_str
= method
.AsString();
1727 if (method_str
== kJSGrayscale
) {
1728 if (args
.size() == 1 && args
[0].is_bool()) {
1729 engine_
->SetGrayscale(args
[0].AsBool());
1731 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
1732 #ifdef ENABLE_THUMBNAILS
1733 if (thumbnails_
.visible())
1734 thumbnails_
.Show(true, true);
1736 return pp::Var(true);
1738 return pp::Var(false);
1740 if (method_str
== kJSOnLoad
) {
1741 if (args
.size() == 1 && args
[0].is_string()) {
1742 on_load_callback_
= args
[0];
1743 return pp::Var(true);
1745 return pp::Var(false);
1747 if (method_str
== kJSOnScroll
) {
1748 if (args
.size() == 1 && args
[0].is_string()) {
1749 on_scroll_callback_
= args
[0];
1750 return pp::Var(true);
1752 return pp::Var(false);
1754 if (method_str
== kJSOnPluginSizeChanged
) {
1755 if (args
.size() == 1 && args
[0].is_string()) {
1756 on_plugin_size_changed_callback_
= args
[0];
1757 return pp::Var(true);
1759 return pp::Var(false);
1761 if (method_str
== kJSReload
) {
1762 document_load_state_
= LOAD_STATE_LOADING
;
1765 preview_engine_
.reset();
1766 print_preview_page_count_
= 0;
1767 engine_
.reset(PDFEngine::Create(this));
1768 engine_
->New(url_
.c_str());
1769 #ifdef ENABLE_THUMBNAILS
1770 thumbnails_
.ResetEngine(engine_
.get());
1774 if (method_str
== kJSResetPrintPreviewUrl
) {
1775 if (args
.size() == 1 && args
[0].is_string()) {
1776 url_
= args
[0].AsString();
1777 preview_pages_info_
= std::queue
<PreviewPageInfo
>();
1778 preview_document_load_state_
= LOAD_STATE_COMPLETE
;
1782 if (method_str
== kJSZoomFitToHeight
) {
1783 SetZoom(ZOOM_FIT_TO_PAGE
, 0);
1786 if (method_str
== kJSZoomFitToWidth
) {
1787 SetZoom(ZOOM_FIT_TO_WIDTH
, 0);
1790 if (method_str
== kJSZoomIn
) {
1791 SetZoom(ZOOM_SCALE
, CalculateZoom(kZoomInButtonId
));
1794 if (method_str
== kJSZoomOut
) {
1795 SetZoom(ZOOM_SCALE
, CalculateZoom(kZoomOutButtonId
));
1798 if (method_str
== kJSSetZoomLevel
) {
1799 if (args
.size() == 1 && args
[0].is_number())
1800 SetZoom(ZOOM_SCALE
, args
[0].AsDouble());
1803 if (method_str
== kJSGetZoomLevel
) {
1804 return pp::Var(zoom_
);
1806 if (method_str
== kJSGetHeight
) {
1807 return pp::Var(plugin_size_
.height());
1809 if (method_str
== kJSGetWidth
) {
1810 return pp::Var(plugin_size_
.width());
1812 if (method_str
== kJSGetHorizontalScrollbarThickness
) {
1814 h_scrollbar_
.get() ? GetScrollbarReservedThickness() : 0);
1816 if (method_str
== kJSGetVerticalScrollbarThickness
) {
1818 v_scrollbar_
.get() ? GetScrollbarReservedThickness() : 0);
1820 if (method_str
== kJSGetSelectedText
) {
1821 return GetSelectedText(false);
1823 if (method_str
== kJSDocumentLoadComplete
) {
1824 return pp::Var((document_load_state_
!= LOAD_STATE_LOADING
));
1826 if (method_str
== kJSPageYOffset
) {
1827 return pp::Var(static_cast<int32_t>(
1828 v_scrollbar_
.get() ? v_scrollbar_
->GetValue() : 0));
1830 if (method_str
== kJSSetPageYOffset
) {
1831 if (args
.size() == 1 && args
[0].is_number() && v_scrollbar_
.get())
1832 ScrollToY(GetScaled(args
[0].AsInt()));
1835 if (method_str
== kJSPageXOffset
) {
1836 return pp::Var(static_cast<int32_t>(
1837 h_scrollbar_
.get() ? h_scrollbar_
->GetValue() : 0));
1839 if (method_str
== kJSSetPageXOffset
) {
1840 if (args
.size() == 1 && args
[0].is_number() && h_scrollbar_
.get())
1841 ScrollToX(GetScaled(args
[0].AsInt()));
1844 if (method_str
== kJSRemovePrintButton
) {
1845 CreateToolbar(kPrintPreviewToolbarButtons
,
1846 arraysize(kPrintPreviewToolbarButtons
));
1847 UpdateToolbarPosition(false);
1848 Invalidate(pp::Rect(plugin_size_
));
1851 if (method_str
== kJSGoToPage
) {
1852 if (args
.size() == 1 && args
[0].is_string()) {
1853 ScrollToPage(atoi(args
[0].AsString().c_str()));
1857 if (method_str
== kJSAccessibility
) {
1858 if (args
.size() == 0) {
1859 base::DictionaryValue node
;
1860 node
.SetInteger(kAccessibleNumberOfPages
, engine_
->GetNumberOfPages());
1861 node
.SetBoolean(kAccessibleLoaded
,
1862 document_load_state_
!= LOAD_STATE_LOADING
);
1863 bool has_permissions
=
1864 engine_
->HasPermission(PDFEngine::PERMISSION_COPY
) ||
1865 engine_
->HasPermission(PDFEngine::PERMISSION_COPY_ACCESSIBLE
);
1866 node
.SetBoolean(kAccessibleCopyable
, has_permissions
);
1868 base::JSONWriter::Write(&node
, &json
);
1869 return pp::Var(json
);
1870 } else if (args
[0].is_number()) {
1871 return pp::Var(engine_
->GetPageAsJSON(args
[0].AsInt()));
1874 if (method_str
== kJSPrintPreviewPageCount
) {
1875 if (args
.size() == 1 && args
[0].is_number())
1876 SetPrintPreviewMode(args
[0].AsInt());
1879 if (method_str
== kJSLoadPreviewPage
) {
1880 if (args
.size() == 2 && args
[0].is_string() && args
[1].is_number())
1881 ProcessPreviewPageInfo(args
[0].AsString(), args
[1].AsInt());
1884 if (method_str
== kJSGetPageLocationNormalized
) {
1885 const size_t kMaxLength
= 30;
1886 char location_info
[kMaxLength
];
1887 int page_idx
= engine_
->GetMostVisiblePage();
1889 return pp::Var(std::string());
1890 pp::Rect rect
= engine_
->GetPageContentsRect(page_idx
);
1891 int v_scrollbar_reserved_thickness
=
1892 v_scrollbar_
.get() ? GetScaled(GetScrollbarReservedThickness()) : 0;
1894 rect
.set_x(rect
.x() + ((plugin_size_
.width() -
1895 v_scrollbar_reserved_thickness
- available_area_
.width()) / 2));
1896 base::snprintf(location_info
,
1898 "%0.4f;%0.4f;%0.4f;%0.4f;",
1899 rect
.x() / static_cast<float>(plugin_size_
.width()),
1900 rect
.y() / static_cast<float>(plugin_size_
.height()),
1901 rect
.width() / static_cast<float>(plugin_size_
.width()),
1902 rect
.height()/ static_cast<float>(plugin_size_
.height()));
1903 return pp::Var(std::string(location_info
));
1905 if (method_str
== kJSSetPageNumbers
) {
1906 if (args
.size() != 1 || !args
[0].is_string())
1908 const int num_pages_signed
= engine_
->GetNumberOfPages();
1909 if (num_pages_signed
<= 0)
1911 scoped_ptr
<base::ListValue
> page_ranges(static_cast<base::ListValue
*>(
1912 base::JSONReader::Read(args
[0].AsString(), false)));
1913 const size_t num_pages
= static_cast<size_t>(num_pages_signed
);
1914 if (!page_ranges
.get() || page_ranges
->GetSize() != num_pages
)
1917 std::vector
<int> print_preview_page_numbers
;
1918 for (size_t index
= 0; index
< num_pages
; ++index
) {
1919 int page_number
= 0; // |page_number| is 1-based.
1920 if (!page_ranges
->GetInteger(index
, &page_number
) || page_number
< 1)
1922 print_preview_page_numbers
.push_back(page_number
);
1924 print_preview_page_numbers_
= print_preview_page_numbers
;
1925 page_indicator_
.set_current_page(GetPageNumberToDisplay());
1928 // This is here to work around https://bugs.webkit.org/show_bug.cgi?id=16735.
1929 // In JS, creating a synthetic keyboard event and dispatching it always
1930 // result in a keycode of 0.
1931 if (method_str
== kJSSendKeyEvent
) {
1932 if (args
.size() == 1 && args
[0].is_number()) {
1933 pp::KeyboardInputEvent
event(
1935 PP_INPUTEVENT_TYPE_KEYDOWN
, // HandleInputEvent only care about this.
1936 0, // timestamp, not used for kbd events.
1938 args
[0].AsInt(), // keycode.
1939 pp::Var()); // no char text needed.
1940 HandleInputEvent(event
);
1946 void Instance::OnGeometryChanged(double old_zoom
, float old_device_scale
) {
1947 bool force_no_horizontal_scrollbar
= false;
1948 int scrollbar_thickness
= GetScrollbarThickness();
1950 if (old_device_scale
!= device_scale_
) {
1951 // Change in device scale forces us to recreate resources
1952 ConfigureNumberImageGenerator();
1954 CreateToolbar(current_tb_info_
, current_tb_info_size_
);
1955 // Load autoscroll anchor image.
1956 autoscroll_anchor_
=
1957 CreateResourceImage(PP_RESOURCEIMAGE_PDF_PAN_SCROLL_ICON
);
1959 ConfigurePageIndicator();
1960 ConfigureProgressBar();
1962 pp::Point scroll_position
= engine_
->GetScrollPosition();
1963 ScalePoint(device_scale_
/ old_device_scale
, &scroll_position
);
1964 engine_
->SetScrollPosition(scroll_position
);
1968 if (zoom_
!= old_zoom
|| device_scale_
!= old_device_scale
)
1969 engine_
->ZoomUpdated(zoom_
* device_scale_
);
1970 if (zoom_
!= old_zoom
)
1973 available_area_
= pp::Rect(plugin_size_
);
1974 if (GetDocumentPixelHeight() > plugin_size_
.height()) {
1975 CreateVerticalScrollbar();
1977 DestroyVerticalScrollbar();
1980 int v_scrollbar_reserved_thickness
=
1981 v_scrollbar_
.get() ? GetScaled(GetScrollbarReservedThickness()) : 0;
1983 if (!force_no_horizontal_scrollbar
&&
1984 GetDocumentPixelWidth() >
1985 (plugin_size_
.width() - v_scrollbar_reserved_thickness
)) {
1986 CreateHorizontalScrollbar();
1988 // Adding the horizontal scrollbar now might cause us to need vertical
1990 if (GetDocumentPixelHeight() >
1991 plugin_size_
.height() - GetScaled(GetScrollbarReservedThickness())) {
1992 CreateVerticalScrollbar();
1996 DestroyHorizontalScrollbar();
1999 #ifdef ENABLE_THUMBNAILS
2000 int thumbnails_pos
= 0, thumbnails_total
= 0;
2002 if (v_scrollbar_
.get()) {
2003 v_scrollbar_
->SetScale(device_scale_
);
2004 available_area_
.set_width(
2005 std::max(0, plugin_size_
.width() - v_scrollbar_reserved_thickness
));
2007 #ifdef ENABLE_THUMBNAILS
2008 int height
= plugin_size_
.height();
2010 int height_dip
= plugin_dip_size_
.height();
2012 #if defined(OS_MACOSX)
2013 // Before Lion, Mac always had the resize at the bottom. After that, it
2015 if ((base::mac::IsOSSnowLeopard() && full_
) ||
2016 (base::mac::IsOSLionOrLater() && h_scrollbar_
.get())) {
2018 if (h_scrollbar_
.get()) {
2019 #endif // defined(OS_MACOSX)
2020 #ifdef ENABLE_THUMBNAILS
2021 height
-= GetScaled(GetScrollbarThickness());
2023 height_dip
-= GetScrollbarThickness();
2025 #ifdef ENABLE_THUMBNAILS
2026 int32 doc_height
= GetDocumentPixelHeight();
2028 int32 doc_height_dip
=
2029 static_cast<int32
>(GetDocumentPixelHeight() / device_scale_
);
2030 #if defined(OS_MACOSX)
2031 // On the Mac we always allow room for the resize button (whose width is
2032 // the same as that of the scrollbar) in full mode. However, if there is no
2033 // no horizontal scrollbar, the end of the scrollbar will scroll past the
2034 // end of the document. This is because the scrollbar assumes that its own
2035 // height (in the case of a vscroll bar) is the same as the height of the
2036 // viewport. Since the viewport is actually larger, we compensate by
2037 // adjusting the document height. Similar logic applies below for the
2038 // horizontal scrollbar.
2039 // For example, if the document size is 1000, and the viewport size is 200,
2040 // then the scrollbar position at the end will be 800. In this case the
2041 // viewport is actally 215 (assuming 15 as the scrollbar width) but the
2042 // scrollbar thinks it is 200. We want the scrollbar position at the end to
2043 // be 785. Making the document size 985 achieves this.
2044 if (full_
&& !h_scrollbar_
.get()) {
2045 #ifdef ENABLE_THUMBNAILS
2046 doc_height
-= GetScaled(GetScrollbarThickness());
2048 doc_height_dip
-= GetScrollbarThickness();
2050 #endif // defined(OS_MACOSX)
2053 position
= v_scrollbar_
->GetValue();
2054 position
= static_cast<int>(position
* zoom_
/ old_zoom
);
2055 valid_v_range_
= doc_height_dip
- height_dip
;
2056 if (position
> valid_v_range_
)
2057 position
= valid_v_range_
;
2059 v_scrollbar_
->SetValue(position
);
2062 loc
.point
.x
= static_cast<int>(available_area_
.right() / device_scale_
);
2063 if (IsOverlayScrollbar())
2064 loc
.point
.x
-= scrollbar_thickness
;
2066 loc
.size
.width
= scrollbar_thickness
;
2067 loc
.size
.height
= height_dip
;
2068 v_scrollbar_
->SetLocation(loc
);
2069 v_scrollbar_
->SetDocumentSize(doc_height_dip
);
2071 #ifdef ENABLE_THUMBNAILS
2072 thumbnails_pos
= position
;
2073 thumbnails_total
= doc_height
- height
;
2077 if (h_scrollbar_
.get()) {
2078 h_scrollbar_
->SetScale(device_scale_
);
2079 available_area_
.set_height(
2080 std::max(0, plugin_size_
.height() -
2081 GetScaled(GetScrollbarReservedThickness())));
2083 int width_dip
= plugin_dip_size_
.width();
2086 #if defined(OS_MACOSX)
2087 if ((base::mac::IsOSSnowLeopard() && full_
) ||
2088 (base::mac::IsOSLionOrLater() && v_scrollbar_
.get())) {
2090 if (v_scrollbar_
.get()) {
2092 width_dip
-= GetScrollbarThickness();
2094 int32 doc_width_dip
=
2095 static_cast<int32
>(GetDocumentPixelWidth() / device_scale_
);
2096 #if defined(OS_MACOSX)
2097 // See comment in the above if (v_scrollbar_.get()) block.
2098 if (full_
&& !v_scrollbar_
.get())
2099 doc_width_dip
-= GetScrollbarThickness();
2100 #endif // defined(OS_MACOSX)
2103 position
= h_scrollbar_
->GetValue();
2104 position
= static_cast<int>(position
* zoom_
/ old_zoom
);
2105 position
= std::min(position
, doc_width_dip
- width_dip
);
2107 h_scrollbar_
->SetValue(position
);
2111 loc
.point
.y
= static_cast<int>(available_area_
.bottom() / device_scale_
);
2112 if (IsOverlayScrollbar())
2113 loc
.point
.y
-= scrollbar_thickness
;
2114 loc
.size
.width
= width_dip
;
2115 loc
.size
.height
= scrollbar_thickness
;
2116 h_scrollbar_
->SetLocation(loc
);
2117 h_scrollbar_
->SetDocumentSize(doc_width_dip
);
2120 int doc_width
= GetDocumentPixelWidth();
2121 if (doc_width
< available_area_
.width()) {
2122 available_area_
.Offset((available_area_
.width() - doc_width
) / 2, 0);
2123 available_area_
.set_width(doc_width
);
2125 int doc_height
= GetDocumentPixelHeight();
2126 if (doc_height
< available_area_
.height()) {
2127 available_area_
.set_height(doc_height
);
2130 // We'll invalidate the entire plugin anyways.
2131 UpdateToolbarPosition(false);
2132 UpdateProgressBarPosition(false);
2133 UpdatePageIndicatorPosition(false);
2135 #ifdef ENABLE_THUMBNAILS
2136 // Update thumbnail control position.
2137 thumbnails_
.SetPosition(thumbnails_pos
, thumbnails_total
, false);
2138 pp::Rect
thumbnails_rc(plugin_size_
.width() - GetScaled(kThumbnailsWidth
), 0,
2139 GetScaled(kThumbnailsWidth
), plugin_size_
.height());
2140 if (v_scrollbar_
.get())
2141 thumbnails_rc
.Offset(-v_scrollbar_reserved_thickness
, 0);
2142 if (h_scrollbar_
.get())
2143 thumbnails_rc
.Inset(0, 0, 0, v_scrollbar_reserved_thickness
);
2144 thumbnails_
.SetRect(thumbnails_rc
, false);
2147 CalculateBackgroundParts();
2148 engine_
->PageOffsetUpdated(available_area_
.point());
2149 engine_
->PluginSizeUpdated(available_area_
.size());
2151 if (!document_size_
.GetArea())
2153 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
2155 // Run the plugin size change callback asynchronously. This function can be
2156 // invoked by a layout change which should not re-enter into JS synchronously.
2157 pp::CompletionCallback callback
=
2158 callback_factory_
.NewCallback(&Instance::RunCallback
,
2159 on_plugin_size_changed_callback_
);
2160 pp::Module::Get()->core()->CallOnMainThread(0, callback
);
2163 void Instance::RunCallback(int32_t, pp::Var callback
) {
2164 if (callback
.is_string())
2165 ExecuteScript(callback
);
2168 void Instance::CreateHorizontalScrollbar() {
2169 if (h_scrollbar_
.get())
2172 h_scrollbar_
.reset(new pp::Scrollbar_Dev(this, false));
2175 void Instance::CreateVerticalScrollbar() {
2176 if (v_scrollbar_
.get())
2179 v_scrollbar_
.reset(new pp::Scrollbar_Dev(this, true));
2182 void Instance::DestroyHorizontalScrollbar() {
2183 if (!h_scrollbar_
.get())
2185 if (h_scrollbar_
->GetValue())
2186 engine_
->ScrolledToXPosition(0);
2187 h_scrollbar_
.reset();
2190 void Instance::DestroyVerticalScrollbar() {
2191 if (!v_scrollbar_
.get())
2193 if (v_scrollbar_
->GetValue())
2194 engine_
->ScrolledToYPosition(0);
2195 v_scrollbar_
.reset();
2196 page_indicator_
.Show(false, true);
2199 int Instance::GetScrollbarThickness() {
2200 if (scrollbar_thickness_
== -1) {
2201 pp::Scrollbar_Dev
temp_scrollbar(this, false);
2202 scrollbar_thickness_
= temp_scrollbar
.GetThickness();
2203 scrollbar_reserved_thickness_
=
2204 temp_scrollbar
.IsOverlay() ? 0 : scrollbar_thickness_
;
2207 return scrollbar_thickness_
;
2210 int Instance::GetScrollbarReservedThickness() {
2211 GetScrollbarThickness();
2212 return scrollbar_reserved_thickness_
;
2215 bool Instance::IsOverlayScrollbar() {
2216 return GetScrollbarReservedThickness() == 0;
2219 void Instance::CreateToolbar(const ToolbarButtonInfo
* tb_info
, size_t size
) {
2220 toolbar_
.reset(new FadingControls());
2225 // Remember the current toolbar information in case we need to recreate the
2227 current_tb_info_
= tb_info
;
2228 current_tb_info_size_
= size
;
2231 pp::Point
origin(kToolbarFadingOffsetLeft
, kToolbarFadingOffsetTop
);
2232 ScalePoint(device_scale_
, &origin
);
2234 std::list
<Button
*> buttons
;
2235 for (size_t i
= 0; i
< size
; i
++) {
2236 Button
* btn
= new Button
;
2237 pp::ImageData normal_face
=
2238 CreateResourceImage(tb_info
[i
].normal
);
2239 btn
->CreateButton(tb_info
[i
].id
,
2245 CreateResourceImage(tb_info
[i
].highlighted
),
2246 CreateResourceImage(tb_info
[i
].pressed
));
2247 buttons
.push_back(btn
);
2249 origin
+= pp::Point(normal_face
.size().width(), 0);
2250 max_height
= std::max(max_height
, normal_face
.size().height());
2253 pp::Rect
rc_toolbar(0, 0,
2254 origin
.x() + GetToolbarRightOffset(),
2255 origin
.y() + max_height
+ GetToolbarBottomOffset());
2256 toolbar_
->CreateFadingControls(
2257 kToolbarId
, rc_toolbar
, false, this, kTransparentAlpha
);
2259 std::list
<Button
*>::iterator iter
;
2260 for (iter
= buttons
.begin(); iter
!= buttons
.end(); ++iter
) {
2261 toolbar_
->AddControl(*iter
);
2265 int Instance::GetToolbarRightOffset() {
2266 int scrollbar_thickness
= GetScrollbarThickness();
2267 return GetScaled(kToolbarFadingOffsetRight
) + 2 * scrollbar_thickness
;
2270 int Instance::GetToolbarBottomOffset() {
2271 int scrollbar_thickness
= GetScrollbarThickness();
2272 return GetScaled(kToolbarFadingOffsetBottom
) + scrollbar_thickness
;
2275 std::vector
<pp::ImageData
> Instance::GetThumbnailResources() {
2276 std::vector
<pp::ImageData
> num_images(10);
2277 num_images
[0] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_0
);
2278 num_images
[1] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_1
);
2279 num_images
[2] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_2
);
2280 num_images
[3] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_3
);
2281 num_images
[4] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_4
);
2282 num_images
[5] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_5
);
2283 num_images
[6] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_6
);
2284 num_images
[7] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_7
);
2285 num_images
[8] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_8
);
2286 num_images
[9] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_9
);
2290 std::vector
<pp::ImageData
> Instance::GetProgressBarResources(
2291 pp::ImageData
* background
) {
2292 std::vector
<pp::ImageData
> result(9);
2293 result
[0] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_0
);
2294 result
[1] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_1
);
2295 result
[2] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_2
);
2296 result
[3] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_3
);
2297 result
[4] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_4
);
2298 result
[5] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_5
);
2299 result
[6] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_6
);
2300 result
[7] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_7
);
2301 result
[8] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_8
);
2302 *background
= CreateResourceImage(
2303 PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_BACKGROUND
);
2307 void Instance::CreatePageIndicator(bool always_visible
) {
2308 page_indicator_
.CreatePageIndicator(kPageIndicatorId
, false, this,
2309 number_image_generator(), always_visible
);
2310 ConfigurePageIndicator();
2313 void Instance::ConfigurePageIndicator() {
2314 pp::ImageData background
=
2315 CreateResourceImage(PP_RESOURCEIMAGE_PDF_PAGE_INDICATOR_BACKGROUND
);
2316 page_indicator_
.Configure(pp::Point(), background
);
2319 void Instance::CreateProgressBar() {
2320 pp::ImageData background
;
2321 std::vector
<pp::ImageData
> images
= GetProgressBarResources(&background
);
2322 std::string text
= GetLocalizedString(PP_RESOURCESTRING_PDFPROGRESSLOADING
);
2323 progress_bar_
.CreateProgressControl(kProgressBarId
, false, this, 0.0,
2324 device_scale_
, images
, background
, text
);
2327 void Instance::ConfigureProgressBar() {
2328 pp::ImageData background
;
2329 std::vector
<pp::ImageData
> images
= GetProgressBarResources(&background
);
2330 progress_bar_
.Reconfigure(background
, images
, device_scale_
);
2333 void Instance::CreateThumbnails() {
2334 thumbnails_
.CreateThumbnailControl(
2335 kThumbnailsId
, pp::Rect(), false, this, engine_
.get(),
2336 number_image_generator());
2339 void Instance::LoadUrl(const std::string
& url
) {
2340 LoadUrlInternal(url
, &embed_loader_
, &Instance::DidOpen
);
2343 void Instance::LoadPreviewUrl(const std::string
& url
) {
2344 LoadUrlInternal(url
, &embed_preview_loader_
, &Instance::DidOpenPreview
);
2347 void Instance::LoadUrlInternal(const std::string
& url
, pp::URLLoader
* loader
,
2348 void (Instance::* method
)(int32_t)) {
2349 pp::URLRequestInfo
request(this);
2350 request
.SetURL(url
);
2351 request
.SetMethod("GET");
2353 *loader
= CreateURLLoaderInternal();
2354 pp::CompletionCallback callback
= loader_factory_
.NewCallback(method
);
2355 int rv
= loader
->Open(request
, callback
);
2356 if (rv
!= PP_OK_COMPLETIONPENDING
)
2360 pp::URLLoader
Instance::CreateURLLoaderInternal() {
2361 pp::URLLoader
loader(this);
2363 const PPB_URLLoaderTrusted
* trusted_interface
=
2364 reinterpret_cast<const PPB_URLLoaderTrusted
*>(
2365 pp::Module::Get()->GetBrowserInterface(
2366 PPB_URLLOADERTRUSTED_INTERFACE
));
2367 if (trusted_interface
)
2368 trusted_interface
->GrantUniversalAccess(loader
.pp_resource());
2372 int Instance::GetInitialPage(const std::string
& url
) {
2373 size_t found_idx
= url
.find('#');
2374 if (found_idx
== std::string::npos
)
2377 const std::string
& ref
= url
.substr(found_idx
+ 1);
2378 std::vector
<std::string
> fragments
;
2379 Tokenize(ref
, kDelimiters
, &fragments
);
2381 // Page number to return, zero-based.
2384 // Handle the case of http://foo.com/bar#NAMEDDEST. This is not explicitly
2385 // mentioned except by example in the Adobe "PDF Open Parameters" document.
2386 if ((fragments
.size() == 1) && (fragments
[0].find('=') == std::string::npos
))
2387 return engine_
->GetNamedDestinationPage(fragments
[0]);
2389 for (size_t i
= 0; i
< fragments
.size(); ++i
) {
2390 std::vector
<std::string
> key_value
;
2391 base::SplitString(fragments
[i
], '=', &key_value
);
2392 if (key_value
.size() != 2)
2394 const std::string
& key
= key_value
[0];
2395 const std::string
& value
= key_value
[1];
2397 if (base::strcasecmp(kPage
, key
.c_str()) == 0) {
2398 // |page_value| is 1-based.
2399 int page_value
= -1;
2400 if (base::StringToInt(value
, &page_value
) && page_value
> 0)
2401 page
= page_value
- 1;
2404 if (base::strcasecmp(kNamedDest
, key
.c_str()) == 0) {
2405 // |page_value| is 0-based.
2406 int page_value
= engine_
->GetNamedDestinationPage(value
);
2407 if (page_value
>= 0)
2415 void Instance::UpdateToolbarPosition(bool invalidate
) {
2416 pp::Rect ctrl_rc
= toolbar_
->GetControlsRect();
2417 int min_toolbar_width
= ctrl_rc
.width() + GetToolbarRightOffset() +
2418 GetScaled(kToolbarFadingOffsetLeft
);
2419 int min_toolbar_height
= ctrl_rc
.width() + GetToolbarBottomOffset() +
2420 GetScaled(kToolbarFadingOffsetBottom
);
2422 // Update toolbar position
2423 if (plugin_size_
.width() < min_toolbar_width
||
2424 plugin_size_
.height() < min_toolbar_height
) {
2425 // Disable toolbar if it does not fit on the screen.
2426 toolbar_
->Show(false, invalidate
);
2429 plugin_size_
.width() - GetToolbarRightOffset() - ctrl_rc
.right(),
2430 plugin_size_
.height() - GetToolbarBottomOffset() - ctrl_rc
.bottom());
2431 toolbar_
->MoveBy(offset
, invalidate
);
2433 int toolbar_width
= std::max(plugin_size_
.width() / 2, min_toolbar_width
);
2434 toolbar_
->ExpandLeft(toolbar_width
- toolbar_
->rect().width());
2435 toolbar_
->Show(painted_first_page_
, invalidate
);
2439 void Instance::UpdateProgressBarPosition(bool invalidate
) {
2440 // TODO(gene): verify we don't overlap with toolbar.
2441 int scrollbar_thickness
= GetScrollbarThickness();
2442 pp::Point
progress_origin(
2443 scrollbar_thickness
+ GetScaled(kProgressOffsetLeft
),
2444 plugin_size_
.height() - progress_bar_
.rect().height() -
2445 scrollbar_thickness
- GetScaled(kProgressOffsetBottom
));
2446 progress_bar_
.MoveTo(progress_origin
, invalidate
);
2449 void Instance::UpdatePageIndicatorPosition(bool invalidate
) {
2450 int32 doc_height
= static_cast<int>(document_size_
.height() * zoom_
);
2452 plugin_size_
.width() - page_indicator_
.rect().width() -
2453 GetScaled(GetScrollbarReservedThickness()),
2454 page_indicator_
.GetYPosition(engine_
->GetVerticalScrollbarYPosition(),
2455 doc_height
, plugin_size_
.height()));
2456 page_indicator_
.MoveTo(origin
, invalidate
);
2459 void Instance::SetZoom(ZoomMode zoom_mode
, double scale
) {
2460 double old_zoom
= zoom_
;
2462 zoom_mode_
= zoom_mode
;
2463 if (zoom_mode_
== ZOOM_SCALE
)
2467 engine_
->ZoomUpdated(zoom_
* device_scale_
);
2468 OnGeometryChanged(old_zoom
, device_scale_
);
2470 // If fit-to-height, snap to the beginning of the most visible page.
2471 if (zoom_mode_
== ZOOM_FIT_TO_PAGE
) {
2472 ScrollToPage(engine_
->GetMostVisiblePage());
2475 // Update sticky buttons to the current zoom style.
2476 Button
* ftp_btn
= static_cast<Button
*>(
2477 toolbar_
->GetControl(kFitToPageButtonId
));
2478 Button
* ftw_btn
= static_cast<Button
*>(
2479 toolbar_
->GetControl(kFitToWidthButtonId
));
2480 switch (zoom_mode_
) {
2481 case ZOOM_FIT_TO_PAGE
:
2482 ftp_btn
->SetPressedState(true);
2483 ftw_btn
->SetPressedState(false);
2485 case ZOOM_FIT_TO_WIDTH
:
2486 ftw_btn
->SetPressedState(true);
2487 ftp_btn
->SetPressedState(false);
2490 ftw_btn
->SetPressedState(false);
2491 ftp_btn
->SetPressedState(false);
2495 void Instance::UpdateZoomScale() {
2496 switch (zoom_mode_
) {
2498 break; // Keep current scale.
2499 case ZOOM_FIT_TO_PAGE
: {
2500 int page_num
= engine_
->GetFirstVisiblePage();
2503 pp::Rect rc
= engine_
->GetPageRect(page_num
);
2506 // Calculate fit to width zoom level.
2507 double ftw_zoom
= static_cast<double>(plugin_dip_size_
.width() -
2508 GetScrollbarReservedThickness()) / document_size_
.width();
2509 // Calculate fit to height zoom level. If document will not fit
2510 // horizontally, adjust zoom level to allow space for horizontal
2513 static_cast<double>(plugin_dip_size_
.height()) / rc
.height();
2514 if (fth_zoom
* document_size_
.width() >
2515 plugin_dip_size_
.width() - GetScrollbarReservedThickness())
2516 fth_zoom
= static_cast<double>(plugin_dip_size_
.height()
2517 - GetScrollbarReservedThickness()) / rc
.height();
2518 zoom_
= std::min(ftw_zoom
, fth_zoom
);
2520 case ZOOM_FIT_TO_WIDTH
:
2522 if (!document_size_
.width())
2524 zoom_
= static_cast<double>(plugin_dip_size_
.width() -
2525 GetScrollbarReservedThickness()) / document_size_
.width();
2526 if (zoom_mode_
== ZOOM_AUTO
&& zoom_
> 1.0)
2530 zoom_
= ClipToRange(zoom_
, kMinZoom
, kMaxZoom
);
2533 double Instance::CalculateZoom(uint32 control_id
) const {
2534 if (control_id
== kZoomInButtonId
) {
2535 for (size_t i
= 0; i
< chrome_page_zoom::kPresetZoomFactorsSize
; ++i
) {
2536 double current_zoom
= chrome_page_zoom::kPresetZoomFactors
[i
];
2537 if (current_zoom
- content::kEpsilon
> zoom_
)
2538 return current_zoom
;
2541 for (size_t i
= chrome_page_zoom::kPresetZoomFactorsSize
; i
> 0; --i
) {
2542 double current_zoom
= chrome_page_zoom::kPresetZoomFactors
[i
- 1];
2543 if (current_zoom
+ content::kEpsilon
< zoom_
)
2544 return current_zoom
;
2550 pp::ImageData
Instance::CreateResourceImage(PP_ResourceImage image_id
) {
2551 pp::ImageData resource_data
;
2552 if (hidpi_enabled_
) {
2554 pp::PDF::GetResourceImageForScale(this, image_id
, device_scale_
);
2557 return resource_data
.data() ? resource_data
2558 : pp::PDF::GetResourceImage(this, image_id
);
2561 std::string
Instance::GetLocalizedString(PP_ResourceString id
) {
2562 pp::Var
rv(pp::PDF::GetLocalizedString(this, id
));
2563 if (!rv
.is_string())
2564 return std::string();
2566 return rv
.AsString();
2569 void Instance::DrawText(const pp::Point
& top_center
, PP_ResourceString id
) {
2570 std::string
str(GetLocalizedString(id
));
2572 pp::FontDescription_Dev description
;
2573 description
.set_family(PP_FONTFAMILY_SANSSERIF
);
2574 description
.set_size(kMessageTextSize
* device_scale_
);
2575 pp::Font_Dev
font(this, description
);
2576 int length
= font
.MeasureSimpleText(str
);
2577 pp::Point
point(top_center
);
2578 point
.set_x(point
.x() - length
/ 2);
2579 DCHECK(!image_data_
.is_null());
2580 font
.DrawSimpleText(&image_data_
, str
, point
, kMessageTextColor
);
2583 void Instance::SetPrintPreviewMode(int page_count
) {
2584 if (!IsPrintPreview() || page_count
<= 0) {
2585 print_preview_page_count_
= 0;
2589 print_preview_page_count_
= page_count
;
2591 engine_
->AppendBlankPages(print_preview_page_count_
);
2592 if (preview_pages_info_
.size() > 0)
2593 LoadAvailablePreviewPage();
2596 bool Instance::IsPrintPreview() {
2597 return IsPrintPreviewUrl(url_
);
2600 int Instance::GetPageNumberToDisplay() {
2601 int page
= engine_
->GetMostVisiblePage();
2602 if (IsPrintPreview() && !print_preview_page_numbers_
.empty()) {
2603 page
= ClipToRange
<int>(page
, 0, print_preview_page_numbers_
.size() - 1);
2604 return print_preview_page_numbers_
[page
];
2609 void Instance::ProcessPreviewPageInfo(const std::string
& url
,
2610 int dst_page_index
) {
2611 if (!IsPrintPreview() || print_preview_page_count_
< 0)
2614 int src_page_index
= ExtractPrintPreviewPageIndex(url
);
2615 if (src_page_index
< 1)
2618 preview_pages_info_
.push(std::make_pair(url
, dst_page_index
));
2619 LoadAvailablePreviewPage();
2622 void Instance::LoadAvailablePreviewPage() {
2623 if (preview_pages_info_
.size() <= 0)
2626 std::string url
= preview_pages_info_
.front().first
;
2627 int dst_page_index
= preview_pages_info_
.front().second
;
2628 int src_page_index
= ExtractPrintPreviewPageIndex(url
);
2629 if (src_page_index
< 1 ||
2630 dst_page_index
>= print_preview_page_count_
||
2631 preview_document_load_state_
== LOAD_STATE_LOADING
) {
2635 preview_document_load_state_
= LOAD_STATE_LOADING
;
2636 LoadPreviewUrl(url
);
2639 void Instance::EnableAutoscroll(const pp::Point
& origin
) {
2643 pp::Size client_size
= plugin_size_
;
2644 if (v_scrollbar_
.get())
2645 client_size
.Enlarge(-GetScrollbarThickness(), 0);
2646 if (h_scrollbar_
.get())
2647 client_size
.Enlarge(0, -GetScrollbarThickness());
2649 // Do not allow autoscroll if client area is too small.
2650 if (autoscroll_anchor_
.size().width() > client_size
.width() ||
2651 autoscroll_anchor_
.size().height() > client_size
.height())
2654 autoscroll_rect_
= pp::Rect(
2655 pp::Point(origin
.x() - autoscroll_anchor_
.size().width() / 2,
2656 origin
.y() - autoscroll_anchor_
.size().height() / 2),
2657 autoscroll_anchor_
.size());
2659 // Make sure autoscroll anchor is in the client area.
2660 if (autoscroll_rect_
.right() > client_size
.width()) {
2661 autoscroll_rect_
.set_x(
2662 client_size
.width() - autoscroll_anchor_
.size().width());
2664 if (autoscroll_rect_
.bottom() > client_size
.height()) {
2665 autoscroll_rect_
.set_y(
2666 client_size
.height() - autoscroll_anchor_
.size().height());
2669 if (autoscroll_rect_
.x() < 0)
2670 autoscroll_rect_
.set_x(0);
2671 if (autoscroll_rect_
.y() < 0)
2672 autoscroll_rect_
.set_y(0);
2674 is_autoscroll_
= true;
2675 Invalidate(kAutoScrollId
, autoscroll_rect_
);
2677 ScheduleTimer(kAutoScrollId
, kAutoScrollTimeoutMs
);
2680 void Instance::DisableAutoscroll() {
2681 if (is_autoscroll_
) {
2682 is_autoscroll_
= false;
2683 Invalidate(kAutoScrollId
, autoscroll_rect_
);
2687 PP_CursorType_Dev
Instance::CalculateAutoscroll(const pp::Point
& mouse_pos
) {
2688 // Scroll only if mouse pointer is outside of the anchor area.
2689 if (autoscroll_rect_
.Contains(mouse_pos
)) {
2692 return PP_CURSORTYPE_MIDDLEPANNING
;
2695 // Relative position to the center of anchor area.
2696 pp::Point rel_pos
= mouse_pos
- autoscroll_rect_
.CenterPoint();
2698 // Calculate angle from the X axis. Angle is in range from -pi to pi.
2699 double angle
= atan2(static_cast<double>(rel_pos
.y()),
2700 static_cast<double>(rel_pos
.x()));
2702 autoscroll_x_
= rel_pos
.x() * kAutoScrollFactor
;
2703 autoscroll_y_
= rel_pos
.y() * kAutoScrollFactor
;
2705 // Angle is from -pi to pi. Screen Y is increasing toward bottom,
2706 // so negative angle represent north direction.
2707 if (angle
< - (M_PI
* 7.0 / 8.0)) {
2709 return PP_CURSORTYPE_WESTPANNING
;
2710 } else if (angle
< - (M_PI
* 5.0 / 8.0)) {
2712 return PP_CURSORTYPE_NORTHWESTPANNING
;
2713 } else if (angle
< - (M_PI
* 3.0 / 8.0)) {
2715 return PP_CURSORTYPE_NORTHPANNING
;
2716 } else if (angle
< - (M_PI
* 1.0 / 8.0)) {
2718 return PP_CURSORTYPE_NORTHEASTPANNING
;
2719 } else if (angle
< M_PI
* 1.0 / 8.0) {
2721 return PP_CURSORTYPE_EASTPANNING
;
2722 } else if (angle
< M_PI
* 3.0 / 8.0) {
2724 return PP_CURSORTYPE_SOUTHEASTPANNING
;
2725 } else if (angle
< M_PI
* 5.0 / 8.0) {
2727 return PP_CURSORTYPE_SOUTHPANNING
;
2728 } else if (angle
< M_PI
* 7.0 / 8.0) {
2730 return PP_CURSORTYPE_SOUTHWESTPANNING
;
2733 // went around the circle, going west again
2734 return PP_CURSORTYPE_WESTPANNING
;
2737 void Instance::ConfigureNumberImageGenerator() {
2738 std::vector
<pp::ImageData
> num_images
= GetThumbnailResources();
2739 pp::ImageData number_background
= CreateResourceImage(
2740 PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_NUM_BACKGROUND
);
2741 number_image_generator_
->Configure(number_background
,
2746 NumberImageGenerator
* Instance::number_image_generator() {
2747 if (!number_image_generator_
.get()) {
2748 number_image_generator_
.reset(new NumberImageGenerator(this));
2749 ConfigureNumberImageGenerator();
2751 return number_image_generator_
.get();
2754 int Instance::GetScaled(int x
) const {
2755 return static_cast<int>(x
* device_scale_
);
2758 void Instance::UserMetricsRecordAction(const std::string
& action
) {
2759 pp::PDF::UserMetricsRecordAction(this, pp::Var(action
));
2762 PDFScriptableObject::PDFScriptableObject(Instance
* instance
)
2763 : instance_(instance
) {
2766 PDFScriptableObject::~PDFScriptableObject() {
2769 bool PDFScriptableObject::HasMethod(const pp::Var
& name
, pp::Var
* exception
) {
2770 return instance_
->HasScriptableMethod(name
, exception
);
2773 pp::Var
PDFScriptableObject::Call(const pp::Var
& method
,
2774 const std::vector
<pp::Var
>& args
,
2775 pp::Var
* exception
) {
2776 return instance_
->CallScriptableMethod(method
, args
, exception
);
2779 } // namespace chrome_pdf