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