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/common/content_restriction.h"
21 #include "components/ui/zoom/page_zoom_constants.h"
22 #include "content/public/common/page_zoom.h"
23 #include "net/base/escape.h"
24 #include "pdf/draw_utils.h"
25 #include "pdf/number_image_generator.h"
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 PP_Bool
GetPrintPresetOptionsFromDocument(
220 PP_Instance instance
,
221 PP_PdfPrintPresetOptions_Dev
* options
) {
222 void* object
= pp::Instance::GetPerInstanceObject(instance
, kPPPPdfInterface
);
224 Instance
* obj_instance
= static_cast<Instance
*>(object
);
225 obj_instance
->GetPrintPresetOptionsFromDocument(options
);
230 const PPP_Pdf ppp_private
= {
233 &GetPrintPresetOptionsFromDocument
236 int ExtractPrintPreviewPageIndex(const std::string
& src_url
) {
237 // Sample |src_url| format: chrome://print/id/page_index/print.pdf
238 std::vector
<std::string
> url_substr
;
239 base::SplitString(src_url
.substr(strlen(kChromePrint
)), '/', &url_substr
);
240 if (url_substr
.size() != 3)
243 if (url_substr
[2] != "print.pdf")
247 if (!base::StringToInt(url_substr
[1], &page_index
))
252 bool IsPrintPreviewUrl(const std::string
& url
) {
253 return url
.substr(0, strlen(kChromePrint
)) == kChromePrint
;
256 void ScalePoint(float scale
, pp::Point
* point
) {
257 point
->set_x(static_cast<int>(point
->x() * scale
));
258 point
->set_y(static_cast<int>(point
->y() * scale
));
261 void ScaleRect(float scale
, pp::Rect
* rect
) {
262 int left
= static_cast<int>(floorf(rect
->x() * scale
));
263 int top
= static_cast<int>(floorf(rect
->y() * scale
));
264 int right
= static_cast<int>(ceilf((rect
->x() + rect
->width()) * scale
));
265 int bottom
= static_cast<int>(ceilf((rect
->y() + rect
->height()) * scale
));
266 rect
->SetRect(left
, top
, right
- left
, bottom
- top
);
270 T
ClipToRange(T value
, T lower_boundary
, T upper_boundary
) {
271 DCHECK(lower_boundary
<= upper_boundary
);
272 return std::max
<T
>(lower_boundary
, std::min
<T
>(value
, upper_boundary
));
277 Instance::Instance(PP_Instance instance
)
278 : pp::InstancePrivate(instance
),
279 pp::Find_Private(this),
280 pp::Printing_Dev(this),
281 pp::Selection_Dev(this),
282 pp::WidgetClient_Dev(this),
284 cursor_(PP_CURSORTYPE_POINTER
),
285 timer_pending_(false),
286 current_timer_id_(0),
289 printing_enabled_(true),
290 hidpi_enabled_(false),
291 full_(IsFullFrame()),
292 zoom_mode_(full_
? ZOOM_AUTO
: ZOOM_SCALE
),
293 did_call_start_loading_(false),
294 is_autoscroll_(false),
295 scrollbar_thickness_(-1),
296 scrollbar_reserved_thickness_(-1),
297 current_tb_info_(NULL
),
298 current_tb_info_size_(0),
299 paint_manager_(this, this, true),
300 delayed_progress_timer_id_(0),
302 painted_first_page_(false),
303 show_page_indicator_(false),
304 document_load_state_(LOAD_STATE_LOADING
),
305 preview_document_load_state_(LOAD_STATE_COMPLETE
),
306 told_browser_about_unsupported_feature_(false),
307 print_preview_page_count_(0) {
308 loader_factory_
.Initialize(this);
309 timer_factory_
.Initialize(this);
310 form_factory_
.Initialize(this);
311 callback_factory_
.Initialize(this);
312 engine_
.reset(PDFEngine::Create(this));
313 pp::Module::Get()->AddPluginInterface(kPPPPdfInterface
, &ppp_private
);
314 AddPerInstanceObject(kPPPPdfInterface
, this);
316 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_MOUSE
);
317 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_WHEEL
);
318 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_KEYBOARD
);
319 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_TOUCH
);
322 Instance::~Instance() {
323 if (timer_pending_
) {
324 timer_factory_
.CancelAll();
325 timer_pending_
= false;
327 // The engine may try to access this instance during its destruction.
328 // Make sure this happens early while the instance is still intact.
330 RemovePerInstanceObject(kPPPPdfInterface
, this);
333 bool Instance::Init(uint32_t argc
, const char* argn
[], const char* argv
[]) {
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 (!IsMouseOnScrollbar(event_device_res
) &&
438 toolbar_
->HandleEvent(event_device_res
))
441 #ifdef ENABLE_THUMBNAILS
442 if (v_scrollbar_
.get() && event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE
) {
443 pp::MouseInputEvent
mouse_event(event
);
444 pp::Point pt
= mouse_event
.GetPosition();
445 pp::Rect v_scrollbar_rc
;
446 v_scrollbar_
->GetLocation(&v_scrollbar_rc
);
447 // There is a bug (https://bugs.webkit.org/show_bug.cgi?id=45208)
448 // in the webkit that makes event.u.mouse.button
449 // equal to PP_INPUTEVENT_MOUSEBUTTON_LEFT, even when no button is pressed.
450 // To work around this issue we use modifier for now, and will switch
451 // to button once the bug is fixed and webkit got merged back to our tree.
452 if (v_scrollbar_rc
.Contains(pt
) &&
453 (event
.GetModifiers() & PP_INPUTEVENT_MODIFIER_LEFTBUTTONDOWN
)) {
454 thumbnails_
.SlideIn();
457 // When scrollbar is in the scrolling mode we should display thumbnails
458 // even the mouse is outside the thumbnail and scrollbar areas.
459 // If mouse is outside plugin area, we are still getting mouse move events
460 // while scrolling. See bug description for details:
461 // http://code.google.com/p/chromium/issues/detail?id=56444
462 if (!v_scrollbar_rc
.Contains(pt
) && thumbnails_
.visible() &&
463 !(event
.GetModifiers() & PP_INPUTEVENT_MODIFIER_LEFTBUTTONDOWN
) &&
464 !thumbnails_
.rect().Contains(pt
)) {
465 thumbnails_
.SlideOut();
470 // Need to pass the event to the engine first, since if we're over an edit
471 // control we want it to get keyboard events (like space) instead of the
473 // TODO: will have to offset the mouse coordinates once we support bidi and
474 // there could be scrollbars on the left.
475 pp::InputEvent
offset_event(event_device_res
);
476 bool try_engine_first
= true;
477 switch (offset_event
.GetType()) {
478 case PP_INPUTEVENT_TYPE_MOUSEDOWN
:
479 case PP_INPUTEVENT_TYPE_MOUSEUP
:
480 case PP_INPUTEVENT_TYPE_MOUSEMOVE
:
481 case PP_INPUTEVENT_TYPE_MOUSEENTER
:
482 case PP_INPUTEVENT_TYPE_MOUSELEAVE
: {
483 pp::MouseInputEvent
mouse_event(event_device_res
);
484 pp::MouseInputEvent
mouse_event_dip(event
);
485 pp::Point point
= mouse_event
.GetPosition();
486 point
.set_x(point
.x() - available_area_
.x());
487 offset_event
= pp::MouseInputEvent(
490 event
.GetTimeStamp(),
491 event
.GetModifiers(),
492 mouse_event
.GetButton(),
494 mouse_event
.GetClickCount(),
495 mouse_event
.GetMovement());
496 if (!engine_
->IsSelecting()) {
497 if (!IsOverlayScrollbar() &&
498 !available_area_
.Contains(mouse_event
.GetPosition())) {
499 try_engine_first
= false;
500 } else if (IsOverlayScrollbar() && IsMouseOnScrollbar(event
)) {
501 try_engine_first
= false;
509 if (try_engine_first
&& engine_
->HandleEvent(offset_event
))
512 // Left/Right arrows should scroll to the beginning of the Prev/Next page if
513 // there is no horizontal scroll bar.
514 // If fit-to-height, PgDown/PgUp should scroll to the beginning of the
515 // Prev/Next page. Spacebar / shift+spacebar should do the same.
516 if (v_scrollbar_
.get() && event
.GetType() == PP_INPUTEVENT_TYPE_KEYDOWN
) {
517 pp::KeyboardInputEvent
keyboard_event(event
);
518 bool no_h_scrollbar
= !h_scrollbar_
.get();
519 uint32_t key_code
= keyboard_event
.GetKeyCode();
520 bool has_modifiers
= keyboard_event
.GetModifiers() != 0;
522 no_h_scrollbar
&& !has_modifiers
&& key_code
== ui::VKEY_RIGHT
;
524 no_h_scrollbar
&& !has_modifiers
&& key_code
== ui::VKEY_LEFT
;
525 if (zoom_mode_
== ZOOM_FIT_TO_PAGE
) {
527 keyboard_event
.GetModifiers() & PP_INPUTEVENT_MODIFIER_SHIFTKEY
;
528 bool key_is_space
= key_code
== ui::VKEY_SPACE
;
529 page_down
|= key_is_space
|| key_code
== ui::VKEY_NEXT
;
530 page_up
|= (key_is_space
&& has_shift
) || (key_code
== ui::VKEY_PRIOR
);
533 int page
= engine_
->GetFirstVisiblePage();
536 // Engine calculates visible page including delimiter to the page size.
537 // We need to check here if the page itself is completely out of view and
538 // scroll to the next one in that case.
539 if (engine_
->GetPageRect(page
).bottom() * zoom_
<=
540 v_scrollbar_
->GetValue())
542 ScrollToPage(page
+ 1);
543 UpdateCursor(PP_CURSORTYPE_POINTER
);
545 } else if (page_up
) {
546 int page
= engine_
->GetFirstVisiblePage();
549 if (engine_
->GetPageRect(page
).y() * zoom_
>= v_scrollbar_
->GetValue())
552 UpdateCursor(PP_CURSORTYPE_POINTER
);
557 if (v_scrollbar_
.get() && v_scrollbar_
->HandleEvent(event
)) {
558 UpdateCursor(PP_CURSORTYPE_POINTER
);
562 if (h_scrollbar_
.get() && h_scrollbar_
->HandleEvent(event
)) {
563 UpdateCursor(PP_CURSORTYPE_POINTER
);
567 if (timer_pending_
&&
568 (event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEUP
||
569 event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE
)) {
570 timer_factory_
.CancelAll();
571 timer_pending_
= false;
572 } else if (event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE
&&
573 engine_
->IsSelecting()) {
574 bool set_timer
= false;
575 pp::MouseInputEvent
mouse_event(event
);
576 if (v_scrollbar_
.get() &&
577 (mouse_event
.GetPosition().y() <= 0 ||
578 mouse_event
.GetPosition().y() >= (plugin_dip_size_
.height() - 1))) {
579 v_scrollbar_
->ScrollBy(
580 PP_SCROLLBY_LINE
, mouse_event
.GetPosition().y() >= 0 ? 1: -1);
583 if (h_scrollbar_
.get() &&
584 (mouse_event
.GetPosition().x() <= 0 ||
585 mouse_event
.GetPosition().x() >= (plugin_dip_size_
.width() - 1))) {
586 h_scrollbar_
->ScrollBy(PP_SCROLLBY_LINE
,
587 mouse_event
.GetPosition().x() >= 0 ? 1: -1);
592 last_mouse_event_
= pp::MouseInputEvent(event
);
594 pp::CompletionCallback callback
=
595 timer_factory_
.NewCallback(&Instance::OnTimerFired
);
596 pp::Module::Get()->core()->CallOnMainThread(kDragTimerMs
, callback
);
597 timer_pending_
= true;
601 if (event
.GetType() == PP_INPUTEVENT_TYPE_KEYDOWN
) {
602 pp::KeyboardInputEvent
keyboard_event(event
);
603 const uint32 modifier
= event
.GetModifiers();
604 if (modifier
& kDefaultKeyModifier
) {
605 switch (keyboard_event
.GetKeyCode()) {
607 engine_
->SelectAll();
611 if (modifier
& PP_INPUTEVENT_MODIFIER_CONTROLKEY
) {
612 switch (keyboard_event
.GetKeyCode()) {
615 engine_
->RotateCounterclockwise();
619 engine_
->RotateClockwise();
625 // Return true for unhandled clicks so the plugin takes focus.
626 return (event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN
);
629 void Instance::DidChangeView(const pp::View
& view
) {
630 pp::Rect
view_rect(view
.GetRect());
631 float device_scale
= 1.0f
;
632 float old_device_scale
= device_scale_
;
634 device_scale
= view
.GetDeviceScale();
635 pp::Size
view_device_size(view_rect
.width() * device_scale
,
636 view_rect
.height() * device_scale
);
637 if (view_device_size
== plugin_size_
&& device_scale
== device_scale_
)
638 return; // We don't care about the position, only the size.
640 image_data_
= pp::ImageData();
641 device_scale_
= device_scale
;
642 plugin_dip_size_
= view_rect
.size();
643 plugin_size_
= view_device_size
;
645 paint_manager_
.SetSize(view_device_size
, device_scale_
);
647 image_data_
= pp::ImageData(this,
648 PP_IMAGEDATAFORMAT_BGRA_PREMUL
,
651 if (image_data_
.is_null()) {
652 DCHECK(plugin_size_
.IsEmpty());
656 // View dimensions changed, disable autoscroll (if it was enabled).
659 OnGeometryChanged(zoom_
, old_device_scale
);
662 pp::Var
Instance::GetInstanceObject() {
663 if (instance_object_
.is_undefined()) {
664 PDFScriptableObject
* object
= new PDFScriptableObject(this);
665 // The pp::Var takes ownership of object here.
666 instance_object_
= pp::VarPrivate(this, object
);
669 return instance_object_
;
672 void Instance::GetPrintPresetOptionsFromDocument(
673 PP_PdfPrintPresetOptions_Dev
* options
) {
674 options
->is_scaling_disabled
= PP_FromBool(IsPrintScalingDisabled());
675 options
->copies
= engine_
->GetCopiesToPrint();
678 pp::Var
Instance::GetLinkAtPosition(const pp::Point
& point
) {
679 pp::Point
offset_point(point
);
680 ScalePoint(device_scale_
, &offset_point
);
681 offset_point
.set_x(offset_point
.x() - available_area_
.x());
682 return engine_
->GetLinkAtPosition(offset_point
);
685 pp::Var
Instance::GetSelectedText(bool html
) {
688 return engine_
->GetSelectedText();
691 void Instance::InvalidateWidget(pp::Widget_Dev widget
,
692 const pp::Rect
& dirty_rect
) {
693 if (v_scrollbar_
.get() && *v_scrollbar_
== widget
) {
694 if (!image_data_
.is_null())
695 v_scrollbar_
->Paint(dirty_rect
.pp_rect(), &image_data_
);
696 } else if (h_scrollbar_
.get() && *h_scrollbar_
== widget
) {
697 if (!image_data_
.is_null())
698 h_scrollbar_
->Paint(dirty_rect
.pp_rect(), &image_data_
);
700 // Possible to hit this condition since sometimes the scrollbar codes posts
701 // a task to do something later, and we could have deleted our reference in
706 pp::Rect dirty_rect_scaled
= dirty_rect
;
707 ScaleRect(device_scale_
, &dirty_rect_scaled
);
708 paint_manager_
.InvalidateRect(dirty_rect_scaled
);
711 void Instance::ScrollbarValueChanged(pp::Scrollbar_Dev scrollbar
,
713 value
= GetScaled(value
);
714 if (v_scrollbar_
.get() && *v_scrollbar_
== scrollbar
) {
715 engine_
->ScrolledToYPosition(value
);
717 v_scrollbar_
->GetLocation(&rc
);
718 int32 doc_height
= GetDocumentPixelHeight();
719 doc_height
-= GetScaled(rc
.height());
720 #ifdef ENABLE_THUMBNAILS
721 if (thumbnails_
.visible()) {
722 thumbnails_
.SetPosition(value
, doc_height
, true);
726 plugin_size_
.width() - page_indicator_
.rect().width() -
727 GetScaled(GetScrollbarReservedThickness()),
728 page_indicator_
.GetYPosition(value
, doc_height
, plugin_size_
.height()));
729 page_indicator_
.MoveTo(origin
, page_indicator_
.visible());
730 } else if (h_scrollbar_
.get() && *h_scrollbar_
== scrollbar
) {
731 engine_
->ScrolledToXPosition(value
);
735 void Instance::ScrollbarOverlayChanged(pp::Scrollbar_Dev scrollbar
,
737 scrollbar_reserved_thickness_
= overlay
? 0 : scrollbar_thickness_
;
738 OnGeometryChanged(zoom_
, device_scale_
);
741 uint32_t Instance::QuerySupportedPrintOutputFormats() {
742 return engine_
->QuerySupportedPrintOutputFormats();
745 int32_t Instance::PrintBegin(const PP_PrintSettings_Dev
& print_settings
) {
746 // For us num_pages is always equal to the number of pages in the PDF
747 // document irrespective of the printable area.
748 int32_t ret
= engine_
->GetNumberOfPages();
752 uint32_t supported_formats
= engine_
->QuerySupportedPrintOutputFormats();
753 if ((print_settings
.format
& supported_formats
) == 0)
756 print_settings_
.is_printing
= true;
757 print_settings_
.pepper_print_settings
= print_settings
;
758 engine_
->PrintBegin();
762 pp::Resource
Instance::PrintPages(
763 const PP_PrintPageNumberRange_Dev
* page_ranges
,
764 uint32_t page_range_count
) {
765 if (!print_settings_
.is_printing
)
766 return pp::Resource();
768 print_settings_
.print_pages_called_
= true;
769 return engine_
->PrintPages(page_ranges
, page_range_count
,
770 print_settings_
.pepper_print_settings
);
773 void Instance::PrintEnd() {
774 if (print_settings_
.print_pages_called_
)
775 UserMetricsRecordAction("PDF.PrintPage");
776 print_settings_
.Clear();
780 bool Instance::IsPrintScalingDisabled() {
781 return !engine_
->GetPrintScaling();
784 bool Instance::StartFind(const std::string
& text
, bool case_sensitive
) {
785 engine_
->StartFind(text
.c_str(), case_sensitive
);
789 void Instance::SelectFindResult(bool forward
) {
790 engine_
->SelectFindResult(forward
);
793 void Instance::StopFind() {
797 void Instance::Zoom(double scale
, bool text_only
) {
798 UserMetricsRecordAction("PDF.ZoomFromBrowser");
800 // If the zoom level doesn't change it means that this zoom change might have
801 // been initiated by the plugin. In that case, we don't want to change the
802 // zoom mode to ZOOM_SCALE as it may have been intentionally set to
803 // ZOOM_FIT_TO_PAGE or some other value when the zoom was last changed.
807 SetZoom(ZOOM_SCALE
, scale
);
810 void Instance::ZoomChanged(double factor
) {
812 Zoom_Dev::ZoomChanged(factor
);
815 void Instance::OnPaint(const std::vector
<pp::Rect
>& paint_rects
,
816 std::vector
<PaintManager::ReadyRect
>* ready
,
817 std::vector
<pp::Rect
>* pending
) {
818 if (image_data_
.is_null()) {
819 DCHECK(plugin_size_
.IsEmpty());
823 first_paint_
= false;
824 pp::Rect rect
= pp::Rect(pp::Point(), plugin_size_
);
825 FillRect(rect
, kBackgroundColor
);
826 ready
->push_back(PaintManager::ReadyRect(rect
, image_data_
, true));
827 *pending
= paint_rects
;
833 for (size_t i
= 0; i
< paint_rects
.size(); i
++) {
834 // Intersect with plugin area since there could be pending invalidates from
835 // when the plugin area was larger.
837 paint_rects
[i
].Intersect(pp::Rect(pp::Point(), plugin_size_
));
841 pp::Rect pdf_rect
= available_area_
.Intersect(rect
);
842 if (!pdf_rect
.IsEmpty()) {
843 pdf_rect
.Offset(available_area_
.x() * -1, 0);
845 std::vector
<pp::Rect
> pdf_ready
;
846 std::vector
<pp::Rect
> pdf_pending
;
847 engine_
->Paint(pdf_rect
, &image_data_
, &pdf_ready
, &pdf_pending
);
848 for (size_t j
= 0; j
< pdf_ready
.size(); ++j
) {
849 pdf_ready
[j
].Offset(available_area_
.point());
851 PaintManager::ReadyRect(pdf_ready
[j
], image_data_
, false));
853 for (size_t j
= 0; j
< pdf_pending
.size(); ++j
) {
854 pdf_pending
[j
].Offset(available_area_
.point());
855 pending
->push_back(pdf_pending
[j
]);
859 for (size_t j
= 0; j
< background_parts_
.size(); ++j
) {
860 pp::Rect intersection
= background_parts_
[j
].location
.Intersect(rect
);
861 if (!intersection
.IsEmpty()) {
862 FillRect(intersection
, background_parts_
[j
].color
);
864 PaintManager::ReadyRect(intersection
, image_data_
, false));
868 if (document_load_state_
== LOAD_STATE_FAILED
) {
869 pp::Point top_center
;
870 top_center
.set_x(plugin_size_
.width() / 2);
871 top_center
.set_y(plugin_size_
.height() / 2);
872 DrawText(top_center
, PP_RESOURCESTRING_PDFLOAD_FAILED
);
875 #ifdef ENABLE_THUMBNAILS
876 thumbnails_
.Paint(&image_data_
, rect
);
880 engine_
->PostPaint();
882 // Must paint scrollbars after the background parts, in case we have an
883 // overlay scrollbar that's over the background. We also do this in a separate
884 // loop because the scrollbar painting logic uses the signal of whether there
885 // are pending paints or not to figure out if it should draw right away or
887 for (size_t i
= 0; i
< paint_rects
.size(); i
++) {
888 PaintIfWidgetIntersects(h_scrollbar_
.get(), paint_rects
[i
], ready
, pending
);
889 PaintIfWidgetIntersects(v_scrollbar_
.get(), paint_rects
[i
], ready
, pending
);
892 if (progress_bar_
.visible())
893 PaintOverlayControl(&progress_bar_
, &image_data_
, ready
);
895 if (page_indicator_
.visible())
896 PaintOverlayControl(&page_indicator_
, &image_data_
, ready
);
898 if (toolbar_
->current_transparency() != kTransparentAlpha
)
899 PaintOverlayControl(toolbar_
.get(), &image_data_
, ready
);
901 // Paint autoscroll anchor if needed.
902 if (is_autoscroll_
) {
903 size_t limit
= ready
->size();
904 for (size_t i
= 0; i
< limit
; i
++) {
905 pp::Rect anchor_rect
= autoscroll_rect_
.Intersect((*ready
)[i
].rect
);
906 if (!anchor_rect
.IsEmpty()) {
907 pp::Rect draw_rc
= pp::Rect(
908 pp::Point(anchor_rect
.x() - autoscroll_rect_
.x(),
909 anchor_rect
.y() - autoscroll_rect_
.y()),
911 // Paint autoscroll anchor.
912 AlphaBlend(autoscroll_anchor_
, draw_rc
,
913 &image_data_
, anchor_rect
.point(), kOpaqueAlpha
);
919 void Instance::PaintOverlayControl(
921 pp::ImageData
* image_data
,
922 std::vector
<PaintManager::ReadyRect
>* ready
) {
923 // Make sure that we only paint overlay controls over an area that's ready,
924 // i.e. not pending. Otherwise we'll mark the control rect as ready and
925 // it'll overwrite the pdf region.
926 std::list
<pp::Rect
> ctrl_rects
;
927 for (size_t i
= 0; i
< ready
->size(); i
++) {
928 pp::Rect rc
= ctrl
->rect().Intersect((*ready
)[i
].rect
);
930 ctrl_rects
.push_back(rc
);
933 if (!ctrl_rects
.empty()) {
934 ctrl
->PaintMultipleRects(image_data
, ctrl_rects
);
936 std::list
<pp::Rect
>::iterator iter
;
937 for (iter
= ctrl_rects
.begin(); iter
!= ctrl_rects
.end(); ++iter
) {
938 ready
->push_back(PaintManager::ReadyRect(*iter
, *image_data
, false));
943 void Instance::DidOpen(int32_t result
) {
944 if (result
== PP_OK
) {
945 engine_
->HandleDocumentLoad(embed_loader_
);
946 } else if (result
!= PP_ERROR_ABORTED
) { // Can happen in tests.
951 void Instance::DidOpenPreview(int32_t result
) {
952 if (result
== PP_OK
) {
953 preview_engine_
.reset(PDFEngine::Create(new PreviewModeClient(this)));
954 preview_engine_
->HandleDocumentLoad(embed_preview_loader_
);
960 void Instance::PaintIfWidgetIntersects(
961 pp::Widget_Dev
* widget
,
962 const pp::Rect
& rect
,
963 std::vector
<PaintManager::ReadyRect
>* ready
,
964 std::vector
<pp::Rect
>* pending
) {
969 if (!widget
->GetLocation(&location
))
972 ScaleRect(device_scale_
, &location
);
973 location
= location
.Intersect(rect
);
974 if (location
.IsEmpty())
977 if (IsOverlayScrollbar()) {
978 // If we're using overlay scrollbars, and there are pending paints under the
979 // scrollbar, don't update the scrollbar instantly. While it would be nice,
980 // we would need to double buffer the plugin area in order to make this
981 // work. This is because we'd need to always have a copy of what the pdf
982 // under the scrollbar looks like, and additionally we couldn't paint the
983 // pdf under the scrollbar if it's ready until we got the preceding flush.
984 // So in practice, it would make painting slower and introduce extra buffer
985 // copies for the general case.
986 for (size_t i
= 0; i
< pending
->size(); ++i
) {
987 if ((*pending
)[i
].Intersects(location
))
991 // Even if none of the pending paints are under the scrollbar, we never want
992 // to paint it if it's over the pdf if there are other pending paints.
993 // Otherwise different parts of the pdf plugin would display at different
995 if (!pending
->empty() && available_area_
.Intersects(rect
)) {
996 pending
->push_back(location
);
1001 pp::Rect location_dip
= location
;
1002 ScaleRect(1.0f
/ device_scale_
, &location_dip
);
1004 DCHECK(!image_data_
.is_null());
1005 widget
->Paint(location_dip
, &image_data_
);
1007 ready
->push_back(PaintManager::ReadyRect(location
, image_data_
, true));
1010 void Instance::OnTimerFired(int32_t) {
1011 HandleInputEvent(last_mouse_event_
);
1014 void Instance::OnClientTimerFired(int32_t id
) {
1015 engine_
->OnCallback(id
);
1018 void Instance::OnControlTimerFired(int32_t,
1019 const uint32
& control_id
,
1020 const uint32
& timer_id
) {
1021 if (control_id
== toolbar_
->id()) {
1022 toolbar_
->OnTimerFired(timer_id
);
1023 } else if (control_id
== progress_bar_
.id()) {
1024 if (timer_id
== delayed_progress_timer_id_
) {
1025 if (document_load_state_
== LOAD_STATE_LOADING
&&
1026 !progress_bar_
.visible()) {
1027 progress_bar_
.Fade(true, kProgressFadeTimeoutMs
);
1029 delayed_progress_timer_id_
= 0;
1031 progress_bar_
.OnTimerFired(timer_id
);
1033 } else if (control_id
== kAutoScrollId
) {
1034 if (is_autoscroll_
) {
1035 if (autoscroll_x_
!= 0 && h_scrollbar_
.get()) {
1036 h_scrollbar_
->ScrollBy(PP_SCROLLBY_PIXEL
, autoscroll_x_
);
1038 if (autoscroll_y_
!= 0 && v_scrollbar_
.get()) {
1039 v_scrollbar_
->ScrollBy(PP_SCROLLBY_PIXEL
, autoscroll_y_
);
1042 // Reschedule timer.
1043 ScheduleTimer(kAutoScrollId
, kAutoScrollTimeoutMs
);
1045 } else if (control_id
== kPageIndicatorId
) {
1046 page_indicator_
.OnTimerFired(timer_id
);
1048 #ifdef ENABLE_THUMBNAILS
1049 else if (control_id
== thumbnails_
.id()) {
1050 thumbnails_
.OnTimerFired(timer_id
);
1055 void Instance::CalculateBackgroundParts() {
1056 background_parts_
.clear();
1057 int v_scrollbar_thickness
=
1058 GetScaled(v_scrollbar_
.get() ? GetScrollbarReservedThickness() : 0);
1059 int h_scrollbar_thickness
=
1060 GetScaled(h_scrollbar_
.get() ? GetScrollbarReservedThickness() : 0);
1061 int width_without_scrollbar
= std::max(
1062 plugin_size_
.width() - v_scrollbar_thickness
, 0);
1063 int height_without_scrollbar
= std::max(
1064 plugin_size_
.height() - h_scrollbar_thickness
, 0);
1065 int left_width
= available_area_
.x();
1066 int right_start
= available_area_
.right();
1067 int right_width
= abs(width_without_scrollbar
- available_area_
.right());
1068 int bottom
= std::min(available_area_
.bottom(), height_without_scrollbar
);
1070 // Add the left, right, and bottom rectangles. Note: we assume only
1071 // horizontal centering.
1072 BackgroundPart part
= {
1073 pp::Rect(0, 0, left_width
, bottom
),
1076 if (!part
.location
.IsEmpty())
1077 background_parts_
.push_back(part
);
1078 part
.location
= pp::Rect(right_start
, 0, right_width
, bottom
);
1079 if (!part
.location
.IsEmpty())
1080 background_parts_
.push_back(part
);
1081 part
.location
= pp::Rect(
1082 0, bottom
, width_without_scrollbar
, height_without_scrollbar
- bottom
);
1083 if (!part
.location
.IsEmpty())
1084 background_parts_
.push_back(part
);
1086 if (h_scrollbar_thickness
1087 #if defined(OS_MACOSX)
1092 v_scrollbar_thickness
) {
1093 part
.color
= 0xFFFFFFFF;
1094 part
.location
= pp::Rect(plugin_size_
.width() - v_scrollbar_thickness
,
1095 plugin_size_
.height() - h_scrollbar_thickness
,
1096 h_scrollbar_thickness
,
1097 v_scrollbar_thickness
);
1098 background_parts_
.push_back(part
);
1102 int Instance::GetDocumentPixelWidth() const {
1103 return static_cast<int>(ceil(document_size_
.width() * zoom_
* device_scale_
));
1106 int Instance::GetDocumentPixelHeight() const {
1107 return static_cast<int>(ceil(document_size_
.height() *
1112 void Instance::FillRect(const pp::Rect
& rect
, uint32 color
) {
1113 DCHECK(!image_data_
.is_null() || rect
.IsEmpty());
1114 uint32
* buffer_start
= static_cast<uint32
*>(image_data_
.data());
1115 int stride
= image_data_
.stride();
1116 uint32
* ptr
= buffer_start
+ rect
.y() * stride
/ 4 + rect
.x();
1117 int height
= rect
.height();
1118 int width
= rect
.width();
1119 for (int y
= 0; y
< height
; ++y
) {
1120 for (int x
= 0; x
< width
; ++x
)
1126 void Instance::DocumentSizeUpdated(const pp::Size
& size
) {
1127 document_size_
= size
;
1129 OnGeometryChanged(zoom_
, device_scale_
);
1132 void Instance::Invalidate(const pp::Rect
& rect
) {
1133 pp::Rect
offset_rect(rect
);
1134 offset_rect
.Offset(available_area_
.point());
1135 paint_manager_
.InvalidateRect(offset_rect
);
1138 void Instance::Scroll(const pp::Point
& point
) {
1139 pp::Rect scroll_area
= available_area_
;
1140 if (IsOverlayScrollbar()) {
1142 if (h_scrollbar_
.get()) {
1143 h_scrollbar_
->GetLocation(&rc
);
1144 ScaleRect(device_scale_
, &rc
);
1145 if (scroll_area
.bottom() > rc
.y()) {
1146 scroll_area
.set_height(rc
.y() - scroll_area
.y());
1147 paint_manager_
.InvalidateRect(rc
);
1150 if (v_scrollbar_
.get()) {
1151 v_scrollbar_
->GetLocation(&rc
);
1152 ScaleRect(device_scale_
, &rc
);
1153 if (scroll_area
.right() > rc
.x()) {
1154 scroll_area
.set_width(rc
.x() - scroll_area
.x());
1155 paint_manager_
.InvalidateRect(rc
);
1159 paint_manager_
.ScrollRect(scroll_area
, point
);
1161 if (toolbar_
->current_transparency() != kTransparentAlpha
)
1162 paint_manager_
.InvalidateRect(toolbar_
->GetControlsRect());
1164 if (progress_bar_
.visible())
1165 paint_manager_
.InvalidateRect(progress_bar_
.rect());
1168 paint_manager_
.InvalidateRect(autoscroll_rect_
);
1170 if (show_page_indicator_
) {
1171 page_indicator_
.set_current_page(GetPageNumberToDisplay());
1172 page_indicator_
.Splash();
1175 if (page_indicator_
.visible())
1176 paint_manager_
.InvalidateRect(page_indicator_
.rect());
1178 // Run the scroll callback asynchronously. This function can be invoked by a
1179 // layout change which should not re-enter into JS synchronously.
1180 pp::CompletionCallback callback
=
1181 callback_factory_
.NewCallback(&Instance::RunCallback
,
1182 on_scroll_callback_
);
1183 pp::Module::Get()->core()->CallOnMainThread(0, callback
);
1186 void Instance::ScrollToX(int position
) {
1187 if (!h_scrollbar_
.get()) {
1191 int position_dip
= static_cast<int>(position
/ device_scale_
);
1192 h_scrollbar_
->SetValue(position_dip
);
1195 void Instance::ScrollToY(int position
) {
1196 if (!v_scrollbar_
.get()) {
1200 int position_dip
= static_cast<int>(position
/ device_scale_
);
1201 v_scrollbar_
->SetValue(ClipToRange(position_dip
, 0, valid_v_range_
));
1204 void Instance::ScrollToPage(int page
) {
1205 if (!v_scrollbar_
.get())
1208 if (engine_
->GetNumberOfPages() == 0)
1211 int index
= ClipToRange(page
, 0, engine_
->GetNumberOfPages() - 1);
1212 pp::Rect rect
= engine_
->GetPageRect(index
);
1213 // If we are trying to scroll pass the last page,
1214 // scroll to the end of the last page.
1215 int position
= index
< page
? rect
.bottom() : rect
.y();
1216 ScrollToY(position
* zoom_
* device_scale_
);
1219 void Instance::NavigateTo(const std::string
& url
, bool open_in_new_tab
) {
1220 std::string
url_copy(url
);
1222 // Empty |url_copy| is ok, and will effectively be a reload.
1223 // Skip the code below so an empty URL does not turn into "http://", which
1224 // will cause GURL to fail a DCHECK.
1225 if (!url_copy
.empty()) {
1226 // If |url_copy| starts with '#', then it's for the same URL with a
1227 // different URL fragment.
1228 if (url_copy
[0] == '#') {
1229 // if '#' is already present in |url_| then remove old fragment and add
1230 // new |url_copy| fragment.
1231 std::size_t index
= url_
.find('#');
1232 if (index
!= std::string::npos
)
1233 url_copy
= url_
.substr(0, index
) + url_copy
;
1235 url_copy
= url_
+ url_copy
;
1236 // Changing the href does not actually do anything when navigating in the
1237 // same tab, so do the actual page scroll here. Then fall through so the
1238 // href gets updated.
1239 if (!open_in_new_tab
) {
1240 int page_number
= GetInitialPage(url_copy
);
1241 if (page_number
>= 0)
1242 ScrollToPage(page_number
);
1245 // If there's no scheme, add http.
1246 if (url_copy
.find("://") == std::string::npos
&&
1247 url_copy
.find("mailto:") == std::string::npos
) {
1248 url_copy
= "http://" + url_copy
;
1250 // Make sure |url_copy| starts with a valid scheme.
1251 if (url_copy
.find("http://") != 0 &&
1252 url_copy
.find("https://") != 0 &&
1253 url_copy
.find("ftp://") != 0 &&
1254 url_copy
.find("file://") != 0 &&
1255 url_copy
.find("mailto:") != 0) {
1258 // Make sure |url_copy| is not only a scheme.
1259 if (url_copy
== "http://" ||
1260 url_copy
== "https://" ||
1261 url_copy
== "ftp://" ||
1262 url_copy
== "file://" ||
1263 url_copy
== "mailto:") {
1267 if (open_in_new_tab
) {
1268 GetWindowObject().Call("open", url_copy
);
1270 GetWindowObject().GetProperty("top").GetProperty("location").
1271 SetProperty("href", url_copy
);
1275 void Instance::UpdateCursor(PP_CursorType_Dev cursor
) {
1276 if (cursor
== cursor_
)
1280 const PPB_CursorControl_Dev
* cursor_interface
=
1281 reinterpret_cast<const PPB_CursorControl_Dev
*>(
1282 pp::Module::Get()->GetBrowserInterface(PPB_CURSOR_CONTROL_DEV_INTERFACE
));
1283 if (!cursor_interface
) {
1288 cursor_interface
->SetCursor(
1289 pp_instance(), cursor_
, pp::ImageData().pp_resource(), NULL
);
1292 void Instance::UpdateTickMarks(const std::vector
<pp::Rect
>& tickmarks
) {
1293 if (!v_scrollbar_
.get())
1296 float inverse_scale
= 1.0f
/ device_scale_
;
1297 std::vector
<pp::Rect
> scaled_tickmarks
= tickmarks
;
1298 for (size_t i
= 0; i
< scaled_tickmarks
.size(); i
++) {
1299 ScaleRect(inverse_scale
, &scaled_tickmarks
[i
]);
1302 v_scrollbar_
->SetTickMarks(
1303 scaled_tickmarks
.empty() ? NULL
: &scaled_tickmarks
[0], tickmarks
.size());
1306 void Instance::NotifyNumberOfFindResultsChanged(int total
, bool final_result
) {
1307 NumberOfFindResultsChanged(total
, final_result
);
1310 void Instance::NotifySelectedFindResultChanged(int current_find_index
) {
1311 DCHECK_GE(current_find_index
, 0);
1312 SelectedFindResultChanged(current_find_index
);
1315 void Instance::OnEvent(uint32 control_id
, uint32 event_id
, void* data
) {
1316 if (event_id
== Button::EVENT_ID_BUTTON_CLICKED
||
1317 event_id
== Button::EVENT_ID_BUTTON_STATE_CHANGED
) {
1318 switch (control_id
) {
1319 case kFitToPageButtonId
:
1320 UserMetricsRecordAction("PDF.FitToPageButton");
1321 SetZoom(ZOOM_FIT_TO_PAGE
, 0);
1324 case kFitToWidthButtonId
:
1325 UserMetricsRecordAction("PDF.FitToWidthButton");
1326 SetZoom(ZOOM_FIT_TO_WIDTH
, 0);
1329 case kZoomOutButtonId
:
1330 case kZoomInButtonId
:
1331 UserMetricsRecordAction(control_id
== kZoomOutButtonId
?
1332 "PDF.ZoomOutButton" : "PDF.ZoomInButton");
1333 SetZoom(ZOOM_SCALE
, CalculateZoom(control_id
));
1337 UserMetricsRecordAction("PDF.SaveButton");
1340 case kPrintButtonId
:
1341 UserMetricsRecordAction("PDF.PrintButton");
1346 if (control_id
== kThumbnailsId
&&
1347 event_id
== ThumbnailControl::EVENT_ID_THUMBNAIL_SELECTED
) {
1348 int page
= *static_cast<int*>(data
);
1349 pp::Rect
page_rc(engine_
->GetPageRect(page
));
1350 ScrollToY(static_cast<int>(page_rc
.y() * zoom_
* device_scale_
));
1354 void Instance::Invalidate(uint32 control_id
, const pp::Rect
& rc
) {
1355 paint_manager_
.InvalidateRect(rc
);
1358 uint32
Instance::ScheduleTimer(uint32 control_id
, uint32 timeout_ms
) {
1359 current_timer_id_
++;
1360 pp::CompletionCallback callback
=
1361 timer_factory_
.NewCallback(&Instance::OnControlTimerFired
,
1364 pp::Module::Get()->core()->CallOnMainThread(timeout_ms
, callback
);
1365 return current_timer_id_
;
1368 void Instance::SetEventCapture(uint32 control_id
, bool set_capture
) {
1369 // TODO(gene): set event capture here.
1372 void Instance::SetCursor(uint32 control_id
, PP_CursorType_Dev cursor_type
) {
1373 UpdateCursor(cursor_type
);
1376 pp::Instance
* Instance::GetInstance() {
1380 void Instance::GetDocumentPassword(
1381 pp::CompletionCallbackWithOutput
<pp::Var
> callback
) {
1382 std::string
message(GetLocalizedString(PP_RESOURCESTRING_PDFGETPASSWORD
));
1383 pp::Var result
= pp::PDF::ModalPromptForPassword(this, message
);
1384 *callback
.output() = result
.pp_var();
1385 callback
.Run(PP_OK
);
1388 void Instance::Alert(const std::string
& message
) {
1389 GetWindowObject().Call("alert", message
);
1392 bool Instance::Confirm(const std::string
& message
) {
1393 pp::Var result
= GetWindowObject().Call("confirm", message
);
1394 return result
.is_bool() ? result
.AsBool() : false;
1397 std::string
Instance::Prompt(const std::string
& question
,
1398 const std::string
& default_answer
) {
1399 pp::Var result
= GetWindowObject().Call("prompt", question
, default_answer
);
1400 return result
.is_string() ? result
.AsString() : std::string();
1403 std::string
Instance::GetURL() {
1407 void Instance::Email(const std::string
& to
,
1408 const std::string
& cc
,
1409 const std::string
& bcc
,
1410 const std::string
& subject
,
1411 const std::string
& body
) {
1412 std::string javascript
=
1413 "var href = 'mailto:" + net::EscapeUrlEncodedData(to
, false) +
1414 "?cc=" + net::EscapeUrlEncodedData(cc
, false) +
1415 "&bcc=" + net::EscapeUrlEncodedData(bcc
, false) +
1416 "&subject=" + net::EscapeUrlEncodedData(subject
, false) +
1417 "&body=" + net::EscapeUrlEncodedData(body
, false) +
1418 "';var temp = window.open(href, '_blank', " +
1419 "'width=1,height=1');if(temp) temp.close();";
1420 ExecuteScript(javascript
);
1423 void Instance::Print() {
1424 if (!printing_enabled_
||
1425 (!engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
) &&
1426 !engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY
))) {
1430 pp::CompletionCallback callback
=
1431 callback_factory_
.NewCallback(&Instance::OnPrint
);
1432 pp::Module::Get()->core()->CallOnMainThread(0, callback
);
1435 void Instance::OnPrint(int32_t) {
1436 pp::PDF::Print(this);
1439 void Instance::SaveAs() {
1440 pp::PDF::SaveAs(this);
1443 void Instance::SubmitForm(const std::string
& url
,
1446 pp::URLRequestInfo
request(this);
1447 request
.SetURL(url
);
1448 request
.SetMethod("POST");
1449 request
.AppendDataToBody(reinterpret_cast<const char*>(data
), length
);
1451 pp::CompletionCallback callback
=
1452 form_factory_
.NewCallback(&Instance::FormDidOpen
);
1453 form_loader_
= CreateURLLoaderInternal();
1454 int rv
= form_loader_
.Open(request
, callback
);
1455 if (rv
!= PP_OK_COMPLETIONPENDING
)
1459 void Instance::FormDidOpen(int32_t result
) {
1460 // TODO: inform the user of success/failure.
1461 if (result
!= PP_OK
) {
1466 std::string
Instance::ShowFileSelectionDialog() {
1467 // Seems like very low priority to implement, since the pdf has no way to get
1468 // the file data anyways. Javascript doesn't let you do this synchronously.
1470 return std::string();
1473 pp::URLLoader
Instance::CreateURLLoader() {
1475 if (!did_call_start_loading_
) {
1476 did_call_start_loading_
= true;
1477 pp::PDF::DidStartLoading(this);
1480 // Disable save and print until the document is fully loaded, since they
1481 // would generate an incomplete document. Need to do this each time we
1482 // call DidStartLoading since that resets the content restrictions.
1483 pp::PDF::SetContentRestriction(this, CONTENT_RESTRICTION_SAVE
|
1484 CONTENT_RESTRICTION_PRINT
);
1487 return CreateURLLoaderInternal();
1490 void Instance::ScheduleCallback(int id
, int delay_in_ms
) {
1491 pp::CompletionCallback callback
=
1492 timer_factory_
.NewCallback(&Instance::OnClientTimerFired
);
1493 pp::Module::Get()->core()->CallOnMainThread(delay_in_ms
, callback
, id
);
1496 void Instance::SearchString(const base::char16
* string
,
1497 const base::char16
* term
,
1498 bool case_sensitive
,
1499 std::vector
<SearchStringResult
>* results
) {
1500 if (!pp::PDF::IsAvailable()) {
1505 PP_PrivateFindResult
* pp_results
;
1507 pp::PDF::SearchString(
1509 reinterpret_cast<const unsigned short*>(string
),
1510 reinterpret_cast<const unsigned short*>(term
),
1515 results
->resize(count
);
1516 for (int i
= 0; i
< count
; ++i
) {
1517 (*results
)[i
].start_index
= pp_results
[i
].start_index
;
1518 (*results
)[i
].length
= pp_results
[i
].length
;
1521 pp::Memory_Dev memory
;
1522 memory
.MemFree(pp_results
);
1525 void Instance::DocumentPaintOccurred() {
1526 if (painted_first_page_
)
1529 painted_first_page_
= true;
1530 UpdateToolbarPosition(false);
1531 toolbar_
->Splash(kToolbarSplashTimeoutMs
);
1533 if (engine_
->GetNumberOfPages() > 1)
1534 show_page_indicator_
= true;
1536 show_page_indicator_
= false;
1538 if (v_scrollbar_
.get() && show_page_indicator_
) {
1539 page_indicator_
.set_current_page(GetPageNumberToDisplay());
1540 page_indicator_
.Splash(kToolbarSplashTimeoutMs
,
1541 kPageIndicatorInitialFadeTimeoutMs
);
1545 void Instance::DocumentLoadComplete(int page_count
) {
1546 // Clear focus state for OSK.
1547 FormTextFieldFocusChange(false);
1549 // Update progress control.
1550 if (progress_bar_
.visible())
1551 progress_bar_
.Fade(false, kProgressFadeTimeoutMs
);
1553 DCHECK(document_load_state_
== LOAD_STATE_LOADING
);
1554 document_load_state_
= LOAD_STATE_COMPLETE
;
1555 UserMetricsRecordAction("PDF.LoadSuccess");
1557 if (did_call_start_loading_
) {
1558 pp::PDF::DidStopLoading(this);
1559 did_call_start_loading_
= false;
1562 if (on_load_callback_
.is_string())
1563 ExecuteScript(on_load_callback_
);
1564 // Note: If we are in print preview mode on_load_callback_ might call
1565 // ScrollTo{X|Y}() and we don't want to scroll again and override it.
1566 // #page=N is not supported in Print Preview.
1567 if (!IsPrintPreview()) {
1568 int initial_page
= GetInitialPage(url_
);
1569 if (initial_page
>= 0)
1570 ScrollToPage(initial_page
);
1575 if (!pp::PDF::IsAvailable())
1578 int content_restrictions
=
1579 CONTENT_RESTRICTION_CUT
| CONTENT_RESTRICTION_PASTE
;
1580 if (!engine_
->HasPermission(PDFEngine::PERMISSION_COPY
))
1581 content_restrictions
|= CONTENT_RESTRICTION_COPY
;
1583 if (!engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
) &&
1584 !engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY
)) {
1585 printing_enabled_
= false;
1586 if (current_tb_info_
== kPDFToolbarButtons
) {
1587 // Remove Print button.
1588 CreateToolbar(kPDFNoPrintToolbarButtons
,
1589 arraysize(kPDFNoPrintToolbarButtons
));
1590 UpdateToolbarPosition(false);
1591 Invalidate(pp::Rect(plugin_size_
));
1595 pp::PDF::SetContentRestriction(this, content_restrictions
);
1597 pp::PDF::HistogramPDFPageCount(this, page_count
);
1600 void Instance::RotateClockwise() {
1601 engine_
->RotateClockwise();
1604 void Instance::RotateCounterclockwise() {
1605 engine_
->RotateCounterclockwise();
1608 bool Instance::IsMouseOnScrollbar(const pp::InputEvent
& event
) {
1609 pp::MouseInputEvent
mouse_event(event
);
1610 if (mouse_event
.is_null())
1613 pp::Point pt
= mouse_event
.GetPosition();
1615 if ((v_scrollbar_
.get() && v_scrollbar_
->GetLocation(&temp
) &&
1616 temp
.Contains(pt
)) ||
1617 (h_scrollbar_
.get() && h_scrollbar_
->GetLocation(&temp
) &&
1618 temp
.Contains(pt
))) {
1624 void Instance::PreviewDocumentLoadComplete() {
1625 if (preview_document_load_state_
!= LOAD_STATE_LOADING
||
1626 preview_pages_info_
.empty()) {
1630 preview_document_load_state_
= LOAD_STATE_COMPLETE
;
1632 int dest_page_index
= preview_pages_info_
.front().second
;
1633 int src_page_index
=
1634 ExtractPrintPreviewPageIndex(preview_pages_info_
.front().first
);
1635 if (src_page_index
> 0 && dest_page_index
> -1 && preview_engine_
.get())
1636 engine_
->AppendPage(preview_engine_
.get(), dest_page_index
);
1638 preview_pages_info_
.pop();
1639 // |print_preview_page_count_| is not updated yet. Do not load any
1640 // other preview pages till we get this information.
1641 if (print_preview_page_count_
== 0)
1644 if (preview_pages_info_
.size())
1645 LoadAvailablePreviewPage();
1648 void Instance::DocumentLoadFailed() {
1649 DCHECK(document_load_state_
== LOAD_STATE_LOADING
);
1650 UserMetricsRecordAction("PDF.LoadFailure");
1652 // Hide progress control.
1653 progress_bar_
.Fade(false, kProgressFadeTimeoutMs
);
1655 if (did_call_start_loading_
) {
1656 pp::PDF::DidStopLoading(this);
1657 did_call_start_loading_
= false;
1660 document_load_state_
= LOAD_STATE_FAILED
;
1661 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
1664 void Instance::PreviewDocumentLoadFailed() {
1665 UserMetricsRecordAction("PDF.PreviewDocumentLoadFailure");
1666 if (preview_document_load_state_
!= LOAD_STATE_LOADING
||
1667 preview_pages_info_
.empty()) {
1671 preview_document_load_state_
= LOAD_STATE_FAILED
;
1672 preview_pages_info_
.pop();
1674 if (preview_pages_info_
.size())
1675 LoadAvailablePreviewPage();
1678 pp::Instance
* Instance::GetPluginInstance() {
1679 return GetInstance();
1682 void Instance::DocumentHasUnsupportedFeature(const std::string
& feature
) {
1683 std::string
metric("PDF_Unsupported_");
1685 if (!unsupported_features_reported_
.count(metric
)) {
1686 unsupported_features_reported_
.insert(metric
);
1687 UserMetricsRecordAction(metric
);
1690 // Since we use an info bar, only do this for full frame plugins..
1694 if (told_browser_about_unsupported_feature_
)
1696 told_browser_about_unsupported_feature_
= true;
1698 pp::PDF::HasUnsupportedFeature(this);
1701 void Instance::DocumentLoadProgress(uint32 available
, uint32 doc_size
) {
1702 double progress
= 0.0;
1703 if (doc_size
== 0) {
1704 // Document size is unknown. Use heuristics.
1705 // We'll make progress logarithmic from 0 to 100M.
1706 static const double kFactor
= log(100000000.0) / 100.0;
1707 if (available
> 0) {
1708 progress
= log(static_cast<double>(available
)) / kFactor
;
1709 if (progress
> 100.0)
1713 progress
= 100.0 * static_cast<double>(available
) / doc_size
;
1715 progress_bar_
.SetProgress(progress
);
1718 void Instance::FormTextFieldFocusChange(bool in_focus
) {
1719 if (!text_input_
.get())
1722 text_input_
->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_TEXT
);
1724 text_input_
->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_NONE
);
1727 // Called by PDFScriptableObject.
1728 bool Instance::HasScriptableMethod(const pp::Var
& method
, pp::Var
* exception
) {
1729 std::string method_str
= method
.AsString();
1730 return (method_str
== kJSAccessibility
||
1731 method_str
== kJSDocumentLoadComplete
||
1732 method_str
== kJSGetHeight
||
1733 method_str
== kJSGetHorizontalScrollbarThickness
||
1734 method_str
== kJSGetPageLocationNormalized
||
1735 method_str
== kJSGetSelectedText
||
1736 method_str
== kJSGetVerticalScrollbarThickness
||
1737 method_str
== kJSGetWidth
||
1738 method_str
== kJSGetZoomLevel
||
1739 method_str
== kJSGoToPage
||
1740 method_str
== kJSGrayscale
||
1741 method_str
== kJSLoadPreviewPage
||
1742 method_str
== kJSOnLoad
||
1743 method_str
== kJSOnPluginSizeChanged
||
1744 method_str
== kJSOnScroll
||
1745 method_str
== kJSPageXOffset
||
1746 method_str
== kJSPageYOffset
||
1747 method_str
== kJSPrintPreviewPageCount
||
1748 method_str
== kJSReload
||
1749 method_str
== kJSRemovePrintButton
||
1750 method_str
== kJSResetPrintPreviewUrl
||
1751 method_str
== kJSSendKeyEvent
||
1752 method_str
== kJSSetPageNumbers
||
1753 method_str
== kJSSetPageXOffset
||
1754 method_str
== kJSSetPageYOffset
||
1755 method_str
== kJSSetZoomLevel
||
1756 method_str
== kJSZoomFitToHeight
||
1757 method_str
== kJSZoomFitToWidth
||
1758 method_str
== kJSZoomIn
||
1759 method_str
== kJSZoomOut
);
1762 pp::Var
Instance::CallScriptableMethod(const pp::Var
& method
,
1763 const std::vector
<pp::Var
>& args
,
1764 pp::Var
* exception
) {
1765 std::string method_str
= method
.AsString();
1766 if (method_str
== kJSGrayscale
) {
1767 if (args
.size() == 1 && args
[0].is_bool()) {
1768 engine_
->SetGrayscale(args
[0].AsBool());
1770 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
1771 #ifdef ENABLE_THUMBNAILS
1772 if (thumbnails_
.visible())
1773 thumbnails_
.Show(true, true);
1775 return pp::Var(true);
1777 return pp::Var(false);
1779 if (method_str
== kJSOnLoad
) {
1780 if (args
.size() == 1 && args
[0].is_string()) {
1781 on_load_callback_
= args
[0];
1782 return pp::Var(true);
1784 return pp::Var(false);
1786 if (method_str
== kJSOnScroll
) {
1787 if (args
.size() == 1 && args
[0].is_string()) {
1788 on_scroll_callback_
= args
[0];
1789 return pp::Var(true);
1791 return pp::Var(false);
1793 if (method_str
== kJSOnPluginSizeChanged
) {
1794 if (args
.size() == 1 && args
[0].is_string()) {
1795 on_plugin_size_changed_callback_
= args
[0];
1796 return pp::Var(true);
1798 return pp::Var(false);
1800 if (method_str
== kJSReload
) {
1801 document_load_state_
= LOAD_STATE_LOADING
;
1804 preview_engine_
.reset();
1805 print_preview_page_count_
= 0;
1806 engine_
.reset(PDFEngine::Create(this));
1807 engine_
->New(url_
.c_str());
1808 #ifdef ENABLE_THUMBNAILS
1809 thumbnails_
.ResetEngine(engine_
.get());
1813 if (method_str
== kJSResetPrintPreviewUrl
) {
1814 if (args
.size() == 1 && args
[0].is_string()) {
1815 url_
= args
[0].AsString();
1816 preview_pages_info_
= std::queue
<PreviewPageInfo
>();
1817 preview_document_load_state_
= LOAD_STATE_COMPLETE
;
1821 if (method_str
== kJSZoomFitToHeight
) {
1822 SetZoom(ZOOM_FIT_TO_PAGE
, 0);
1825 if (method_str
== kJSZoomFitToWidth
) {
1826 SetZoom(ZOOM_FIT_TO_WIDTH
, 0);
1829 if (method_str
== kJSZoomIn
) {
1830 SetZoom(ZOOM_SCALE
, CalculateZoom(kZoomInButtonId
));
1833 if (method_str
== kJSZoomOut
) {
1834 SetZoom(ZOOM_SCALE
, CalculateZoom(kZoomOutButtonId
));
1837 if (method_str
== kJSSetZoomLevel
) {
1838 if (args
.size() == 1 && args
[0].is_number())
1839 SetZoom(ZOOM_SCALE
, args
[0].AsDouble());
1842 if (method_str
== kJSGetZoomLevel
) {
1843 return pp::Var(zoom_
);
1845 if (method_str
== kJSGetHeight
) {
1846 return pp::Var(plugin_size_
.height());
1848 if (method_str
== kJSGetWidth
) {
1849 return pp::Var(plugin_size_
.width());
1851 if (method_str
== kJSGetHorizontalScrollbarThickness
) {
1853 h_scrollbar_
.get() ? GetScrollbarReservedThickness() : 0);
1855 if (method_str
== kJSGetVerticalScrollbarThickness
) {
1857 v_scrollbar_
.get() ? GetScrollbarReservedThickness() : 0);
1859 if (method_str
== kJSGetSelectedText
) {
1860 std::string selected_text
= engine_
->GetSelectedText();
1861 // Always return unix newlines to JS.
1862 base::ReplaceChars(selected_text
, "\r", std::string(), &selected_text
);
1863 return selected_text
;
1865 if (method_str
== kJSDocumentLoadComplete
) {
1866 return pp::Var((document_load_state_
!= LOAD_STATE_LOADING
));
1868 if (method_str
== kJSPageYOffset
) {
1869 return pp::Var(static_cast<int32_t>(
1870 v_scrollbar_
.get() ? v_scrollbar_
->GetValue() : 0));
1872 if (method_str
== kJSSetPageYOffset
) {
1873 if (args
.size() == 1 && args
[0].is_number() && v_scrollbar_
.get())
1874 ScrollToY(GetScaled(args
[0].AsInt()));
1877 if (method_str
== kJSPageXOffset
) {
1878 return pp::Var(static_cast<int32_t>(
1879 h_scrollbar_
.get() ? h_scrollbar_
->GetValue() : 0));
1881 if (method_str
== kJSSetPageXOffset
) {
1882 if (args
.size() == 1 && args
[0].is_number() && h_scrollbar_
.get())
1883 ScrollToX(GetScaled(args
[0].AsInt()));
1886 if (method_str
== kJSRemovePrintButton
) {
1887 CreateToolbar(kPrintPreviewToolbarButtons
,
1888 arraysize(kPrintPreviewToolbarButtons
));
1889 UpdateToolbarPosition(false);
1890 Invalidate(pp::Rect(plugin_size_
));
1893 if (method_str
== kJSGoToPage
) {
1894 if (args
.size() == 1 && args
[0].is_string()) {
1895 ScrollToPage(atoi(args
[0].AsString().c_str()));
1899 if (method_str
== kJSAccessibility
) {
1900 if (args
.size() == 0) {
1901 base::DictionaryValue node
;
1902 node
.SetInteger(kAccessibleNumberOfPages
, engine_
->GetNumberOfPages());
1903 node
.SetBoolean(kAccessibleLoaded
,
1904 document_load_state_
!= LOAD_STATE_LOADING
);
1905 bool has_permissions
=
1906 engine_
->HasPermission(PDFEngine::PERMISSION_COPY
) ||
1907 engine_
->HasPermission(PDFEngine::PERMISSION_COPY_ACCESSIBLE
);
1908 node
.SetBoolean(kAccessibleCopyable
, has_permissions
);
1910 base::JSONWriter::Write(&node
, &json
);
1911 return pp::Var(json
);
1912 } else if (args
[0].is_number()) {
1913 return pp::Var(engine_
->GetPageAsJSON(args
[0].AsInt()));
1916 if (method_str
== kJSPrintPreviewPageCount
) {
1917 if (args
.size() == 1 && args
[0].is_number())
1918 SetPrintPreviewMode(args
[0].AsInt());
1921 if (method_str
== kJSLoadPreviewPage
) {
1922 if (args
.size() == 2 && args
[0].is_string() && args
[1].is_number())
1923 ProcessPreviewPageInfo(args
[0].AsString(), args
[1].AsInt());
1926 if (method_str
== kJSGetPageLocationNormalized
) {
1927 const size_t kMaxLength
= 30;
1928 char location_info
[kMaxLength
];
1929 int page_idx
= engine_
->GetMostVisiblePage();
1931 return pp::Var(std::string());
1932 pp::Rect rect
= engine_
->GetPageContentsRect(page_idx
);
1933 int v_scrollbar_reserved_thickness
=
1934 v_scrollbar_
.get() ? GetScaled(GetScrollbarReservedThickness()) : 0;
1936 rect
.set_x(rect
.x() + ((plugin_size_
.width() -
1937 v_scrollbar_reserved_thickness
- available_area_
.width()) / 2));
1938 base::snprintf(location_info
,
1940 "%0.4f;%0.4f;%0.4f;%0.4f;",
1941 rect
.x() / static_cast<float>(plugin_size_
.width()),
1942 rect
.y() / static_cast<float>(plugin_size_
.height()),
1943 rect
.width() / static_cast<float>(plugin_size_
.width()),
1944 rect
.height()/ static_cast<float>(plugin_size_
.height()));
1945 return pp::Var(std::string(location_info
));
1947 if (method_str
== kJSSetPageNumbers
) {
1948 if (args
.size() != 1 || !args
[0].is_string())
1950 const int num_pages_signed
= engine_
->GetNumberOfPages();
1951 if (num_pages_signed
<= 0)
1953 scoped_ptr
<base::ListValue
> page_ranges(static_cast<base::ListValue
*>(
1954 base::JSONReader::Read(args
[0].AsString(), false)));
1955 const size_t num_pages
= static_cast<size_t>(num_pages_signed
);
1956 if (!page_ranges
.get() || page_ranges
->GetSize() != num_pages
)
1959 std::vector
<int> print_preview_page_numbers
;
1960 for (size_t index
= 0; index
< num_pages
; ++index
) {
1961 int page_number
= 0; // |page_number| is 1-based.
1962 if (!page_ranges
->GetInteger(index
, &page_number
) || page_number
< 1)
1964 print_preview_page_numbers
.push_back(page_number
);
1966 print_preview_page_numbers_
= print_preview_page_numbers
;
1967 page_indicator_
.set_current_page(GetPageNumberToDisplay());
1970 // This is here to work around https://bugs.webkit.org/show_bug.cgi?id=16735.
1971 // In JS, creating a synthetic keyboard event and dispatching it always
1972 // result in a keycode of 0.
1973 if (method_str
== kJSSendKeyEvent
) {
1974 if (args
.size() == 1 && args
[0].is_number()) {
1975 pp::KeyboardInputEvent
event(
1977 PP_INPUTEVENT_TYPE_KEYDOWN
, // HandleInputEvent only care about this.
1978 0, // timestamp, not used for kbd events.
1980 args
[0].AsInt(), // keycode.
1981 pp::Var()); // no char text needed.
1982 HandleInputEvent(event
);
1988 void Instance::OnGeometryChanged(double old_zoom
, float old_device_scale
) {
1989 bool force_no_horizontal_scrollbar
= false;
1990 int scrollbar_thickness
= GetScrollbarThickness();
1992 if (old_device_scale
!= device_scale_
) {
1993 // Change in device scale forces us to recreate resources
1994 ConfigureNumberImageGenerator();
1996 CreateToolbar(current_tb_info_
, current_tb_info_size_
);
1997 // Load autoscroll anchor image.
1998 autoscroll_anchor_
=
1999 CreateResourceImage(PP_RESOURCEIMAGE_PDF_PAN_SCROLL_ICON
);
2001 ConfigurePageIndicator();
2002 ConfigureProgressBar();
2004 pp::Point scroll_position
= engine_
->GetScrollPosition();
2005 ScalePoint(device_scale_
/ old_device_scale
, &scroll_position
);
2006 engine_
->SetScrollPosition(scroll_position
);
2010 if (zoom_
!= old_zoom
|| device_scale_
!= old_device_scale
)
2011 engine_
->ZoomUpdated(zoom_
* device_scale_
);
2012 if (zoom_
!= old_zoom
)
2015 available_area_
= pp::Rect(plugin_size_
);
2016 if (GetDocumentPixelHeight() > plugin_size_
.height()) {
2017 CreateVerticalScrollbar();
2019 DestroyVerticalScrollbar();
2022 int v_scrollbar_reserved_thickness
=
2023 v_scrollbar_
.get() ? GetScaled(GetScrollbarReservedThickness()) : 0;
2025 if (!force_no_horizontal_scrollbar
&&
2026 GetDocumentPixelWidth() >
2027 (plugin_size_
.width() - v_scrollbar_reserved_thickness
)) {
2028 CreateHorizontalScrollbar();
2030 // Adding the horizontal scrollbar now might cause us to need vertical
2032 if (GetDocumentPixelHeight() >
2033 plugin_size_
.height() - GetScaled(GetScrollbarReservedThickness())) {
2034 CreateVerticalScrollbar();
2038 DestroyHorizontalScrollbar();
2041 #ifdef ENABLE_THUMBNAILS
2042 int thumbnails_pos
= 0, thumbnails_total
= 0;
2044 if (v_scrollbar_
.get()) {
2045 v_scrollbar_
->SetScale(device_scale_
);
2046 available_area_
.set_width(
2047 std::max(0, plugin_size_
.width() - v_scrollbar_reserved_thickness
));
2049 #ifdef ENABLE_THUMBNAILS
2050 int height
= plugin_size_
.height();
2052 int height_dip
= plugin_dip_size_
.height();
2054 #if defined(OS_MACOSX)
2055 // Before Lion, Mac always had the resize at the bottom. After that, it
2057 if ((base::mac::IsOSSnowLeopard() && full_
) ||
2058 (base::mac::IsOSLionOrLater() && h_scrollbar_
.get())) {
2060 if (h_scrollbar_
.get()) {
2061 #endif // defined(OS_MACOSX)
2062 #ifdef ENABLE_THUMBNAILS
2063 height
-= GetScaled(GetScrollbarThickness());
2065 height_dip
-= GetScrollbarThickness();
2067 #ifdef ENABLE_THUMBNAILS
2068 int32 doc_height
= GetDocumentPixelHeight();
2070 int32 doc_height_dip
=
2071 static_cast<int32
>(GetDocumentPixelHeight() / device_scale_
);
2072 #if defined(OS_MACOSX)
2073 // On the Mac we always allow room for the resize button (whose width is
2074 // the same as that of the scrollbar) in full mode. However, if there is no
2075 // no horizontal scrollbar, the end of the scrollbar will scroll past the
2076 // end of the document. This is because the scrollbar assumes that its own
2077 // height (in the case of a vscroll bar) is the same as the height of the
2078 // viewport. Since the viewport is actually larger, we compensate by
2079 // adjusting the document height. Similar logic applies below for the
2080 // horizontal scrollbar.
2081 // For example, if the document size is 1000, and the viewport size is 200,
2082 // then the scrollbar position at the end will be 800. In this case the
2083 // viewport is actally 215 (assuming 15 as the scrollbar width) but the
2084 // scrollbar thinks it is 200. We want the scrollbar position at the end to
2085 // be 785. Making the document size 985 achieves this.
2086 if (full_
&& !h_scrollbar_
.get()) {
2087 #ifdef ENABLE_THUMBNAILS
2088 doc_height
-= GetScaled(GetScrollbarThickness());
2090 doc_height_dip
-= GetScrollbarThickness();
2092 #endif // defined(OS_MACOSX)
2095 position
= v_scrollbar_
->GetValue();
2096 position
= static_cast<int>(position
* zoom_
/ old_zoom
);
2097 valid_v_range_
= doc_height_dip
- height_dip
;
2098 if (position
> valid_v_range_
)
2099 position
= valid_v_range_
;
2101 v_scrollbar_
->SetValue(position
);
2104 loc
.point
.x
= static_cast<int>(available_area_
.right() / device_scale_
);
2105 if (IsOverlayScrollbar())
2106 loc
.point
.x
-= scrollbar_thickness
;
2108 loc
.size
.width
= scrollbar_thickness
;
2109 loc
.size
.height
= height_dip
;
2110 v_scrollbar_
->SetLocation(loc
);
2111 v_scrollbar_
->SetDocumentSize(doc_height_dip
);
2113 #ifdef ENABLE_THUMBNAILS
2114 thumbnails_pos
= position
;
2115 thumbnails_total
= doc_height
- height
;
2119 if (h_scrollbar_
.get()) {
2120 h_scrollbar_
->SetScale(device_scale_
);
2121 available_area_
.set_height(
2122 std::max(0, plugin_size_
.height() -
2123 GetScaled(GetScrollbarReservedThickness())));
2125 int width_dip
= plugin_dip_size_
.width();
2128 #if defined(OS_MACOSX)
2129 if ((base::mac::IsOSSnowLeopard() && full_
) ||
2130 (base::mac::IsOSLionOrLater() && v_scrollbar_
.get())) {
2132 if (v_scrollbar_
.get()) {
2134 width_dip
-= GetScrollbarThickness();
2136 int32 doc_width_dip
=
2137 static_cast<int32
>(GetDocumentPixelWidth() / device_scale_
);
2138 #if defined(OS_MACOSX)
2139 // See comment in the above if (v_scrollbar_.get()) block.
2140 if (full_
&& !v_scrollbar_
.get())
2141 doc_width_dip
-= GetScrollbarThickness();
2142 #endif // defined(OS_MACOSX)
2145 position
= h_scrollbar_
->GetValue();
2146 position
= static_cast<int>(position
* zoom_
/ old_zoom
);
2147 position
= std::min(position
, doc_width_dip
- width_dip
);
2149 h_scrollbar_
->SetValue(position
);
2153 loc
.point
.y
= static_cast<int>(available_area_
.bottom() / device_scale_
);
2154 if (IsOverlayScrollbar())
2155 loc
.point
.y
-= scrollbar_thickness
;
2156 loc
.size
.width
= width_dip
;
2157 loc
.size
.height
= scrollbar_thickness
;
2158 h_scrollbar_
->SetLocation(loc
);
2159 h_scrollbar_
->SetDocumentSize(doc_width_dip
);
2162 int doc_width
= GetDocumentPixelWidth();
2163 if (doc_width
< available_area_
.width()) {
2164 available_area_
.Offset((available_area_
.width() - doc_width
) / 2, 0);
2165 available_area_
.set_width(doc_width
);
2167 int doc_height
= GetDocumentPixelHeight();
2168 if (doc_height
< available_area_
.height()) {
2169 available_area_
.set_height(doc_height
);
2172 // We'll invalidate the entire plugin anyways.
2173 UpdateToolbarPosition(false);
2174 UpdateProgressBarPosition(false);
2175 UpdatePageIndicatorPosition(false);
2177 #ifdef ENABLE_THUMBNAILS
2178 // Update thumbnail control position.
2179 thumbnails_
.SetPosition(thumbnails_pos
, thumbnails_total
, false);
2180 pp::Rect
thumbnails_rc(plugin_size_
.width() - GetScaled(kThumbnailsWidth
), 0,
2181 GetScaled(kThumbnailsWidth
), plugin_size_
.height());
2182 if (v_scrollbar_
.get())
2183 thumbnails_rc
.Offset(-v_scrollbar_reserved_thickness
, 0);
2184 if (h_scrollbar_
.get())
2185 thumbnails_rc
.Inset(0, 0, 0, v_scrollbar_reserved_thickness
);
2186 thumbnails_
.SetRect(thumbnails_rc
, false);
2189 CalculateBackgroundParts();
2190 engine_
->PageOffsetUpdated(available_area_
.point());
2191 engine_
->PluginSizeUpdated(available_area_
.size());
2193 if (!document_size_
.GetArea())
2195 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
2197 // Run the plugin size change callback asynchronously. This function can be
2198 // invoked by a layout change which should not re-enter into JS synchronously.
2199 pp::CompletionCallback callback
=
2200 callback_factory_
.NewCallback(&Instance::RunCallback
,
2201 on_plugin_size_changed_callback_
);
2202 pp::Module::Get()->core()->CallOnMainThread(0, callback
);
2205 void Instance::RunCallback(int32_t, pp::Var callback
) {
2206 if (callback
.is_string())
2207 ExecuteScript(callback
);
2210 void Instance::CreateHorizontalScrollbar() {
2211 if (h_scrollbar_
.get())
2214 h_scrollbar_
.reset(new pp::Scrollbar_Dev(this, false));
2217 void Instance::CreateVerticalScrollbar() {
2218 if (v_scrollbar_
.get())
2221 v_scrollbar_
.reset(new pp::Scrollbar_Dev(this, true));
2224 void Instance::DestroyHorizontalScrollbar() {
2225 if (!h_scrollbar_
.get())
2227 if (h_scrollbar_
->GetValue())
2228 engine_
->ScrolledToXPosition(0);
2229 h_scrollbar_
.reset();
2232 void Instance::DestroyVerticalScrollbar() {
2233 if (!v_scrollbar_
.get())
2235 if (v_scrollbar_
->GetValue())
2236 engine_
->ScrolledToYPosition(0);
2237 v_scrollbar_
.reset();
2238 page_indicator_
.Show(false, true);
2241 int Instance::GetScrollbarThickness() {
2242 if (scrollbar_thickness_
== -1) {
2243 pp::Scrollbar_Dev
temp_scrollbar(this, false);
2244 scrollbar_thickness_
= temp_scrollbar
.GetThickness();
2245 scrollbar_reserved_thickness_
=
2246 temp_scrollbar
.IsOverlay() ? 0 : scrollbar_thickness_
;
2249 return scrollbar_thickness_
;
2252 int Instance::GetScrollbarReservedThickness() {
2253 GetScrollbarThickness();
2254 return scrollbar_reserved_thickness_
;
2257 bool Instance::IsOverlayScrollbar() {
2258 return GetScrollbarReservedThickness() == 0;
2261 void Instance::CreateToolbar(const ToolbarButtonInfo
* tb_info
, size_t size
) {
2262 toolbar_
.reset(new FadingControls());
2267 // Remember the current toolbar information in case we need to recreate the
2269 current_tb_info_
= tb_info
;
2270 current_tb_info_size_
= size
;
2273 pp::Point
origin(kToolbarFadingOffsetLeft
, kToolbarFadingOffsetTop
);
2274 ScalePoint(device_scale_
, &origin
);
2276 std::list
<Button
*> buttons
;
2277 for (size_t i
= 0; i
< size
; i
++) {
2278 Button
* btn
= new Button
;
2279 pp::ImageData normal_face
=
2280 CreateResourceImage(tb_info
[i
].normal
);
2281 btn
->CreateButton(tb_info
[i
].id
,
2287 CreateResourceImage(tb_info
[i
].highlighted
),
2288 CreateResourceImage(tb_info
[i
].pressed
));
2289 buttons
.push_back(btn
);
2291 origin
+= pp::Point(normal_face
.size().width(), 0);
2292 max_height
= std::max(max_height
, normal_face
.size().height());
2295 pp::Rect
rc_toolbar(0, 0,
2296 origin
.x() + GetToolbarRightOffset(),
2297 origin
.y() + max_height
+ GetToolbarBottomOffset());
2298 toolbar_
->CreateFadingControls(
2299 kToolbarId
, rc_toolbar
, false, this, kTransparentAlpha
);
2301 std::list
<Button
*>::iterator iter
;
2302 for (iter
= buttons
.begin(); iter
!= buttons
.end(); ++iter
) {
2303 toolbar_
->AddControl(*iter
);
2307 int Instance::GetToolbarRightOffset() {
2308 int scrollbar_thickness
= GetScrollbarThickness();
2309 return GetScaled(kToolbarFadingOffsetRight
) + 2 * scrollbar_thickness
;
2312 int Instance::GetToolbarBottomOffset() {
2313 int scrollbar_thickness
= GetScrollbarThickness();
2314 return GetScaled(kToolbarFadingOffsetBottom
) + scrollbar_thickness
;
2317 std::vector
<pp::ImageData
> Instance::GetThumbnailResources() {
2318 std::vector
<pp::ImageData
> num_images(10);
2319 num_images
[0] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_0
);
2320 num_images
[1] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_1
);
2321 num_images
[2] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_2
);
2322 num_images
[3] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_3
);
2323 num_images
[4] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_4
);
2324 num_images
[5] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_5
);
2325 num_images
[6] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_6
);
2326 num_images
[7] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_7
);
2327 num_images
[8] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_8
);
2328 num_images
[9] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_9
);
2332 std::vector
<pp::ImageData
> Instance::GetProgressBarResources(
2333 pp::ImageData
* background
) {
2334 std::vector
<pp::ImageData
> result(9);
2335 result
[0] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_0
);
2336 result
[1] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_1
);
2337 result
[2] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_2
);
2338 result
[3] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_3
);
2339 result
[4] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_4
);
2340 result
[5] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_5
);
2341 result
[6] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_6
);
2342 result
[7] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_7
);
2343 result
[8] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_8
);
2344 *background
= CreateResourceImage(
2345 PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_BACKGROUND
);
2349 void Instance::CreatePageIndicator(bool always_visible
) {
2350 page_indicator_
.CreatePageIndicator(kPageIndicatorId
, false, this,
2351 number_image_generator(), always_visible
);
2352 ConfigurePageIndicator();
2355 void Instance::ConfigurePageIndicator() {
2356 pp::ImageData background
=
2357 CreateResourceImage(PP_RESOURCEIMAGE_PDF_PAGE_INDICATOR_BACKGROUND
);
2358 page_indicator_
.Configure(pp::Point(), background
);
2361 void Instance::CreateProgressBar() {
2362 pp::ImageData background
;
2363 std::vector
<pp::ImageData
> images
= GetProgressBarResources(&background
);
2364 std::string text
= GetLocalizedString(PP_RESOURCESTRING_PDFPROGRESSLOADING
);
2365 progress_bar_
.CreateProgressControl(kProgressBarId
, false, this, 0.0,
2366 device_scale_
, images
, background
, text
);
2369 void Instance::ConfigureProgressBar() {
2370 pp::ImageData background
;
2371 std::vector
<pp::ImageData
> images
= GetProgressBarResources(&background
);
2372 progress_bar_
.Reconfigure(background
, images
, device_scale_
);
2375 void Instance::CreateThumbnails() {
2376 thumbnails_
.CreateThumbnailControl(
2377 kThumbnailsId
, pp::Rect(), false, this, engine_
.get(),
2378 number_image_generator());
2381 void Instance::LoadUrl(const std::string
& url
) {
2382 LoadUrlInternal(url
, &embed_loader_
, &Instance::DidOpen
);
2385 void Instance::LoadPreviewUrl(const std::string
& url
) {
2386 LoadUrlInternal(url
, &embed_preview_loader_
, &Instance::DidOpenPreview
);
2389 void Instance::LoadUrlInternal(const std::string
& url
, pp::URLLoader
* loader
,
2390 void (Instance::* method
)(int32_t)) {
2391 pp::URLRequestInfo
request(this);
2392 request
.SetURL(url
);
2393 request
.SetMethod("GET");
2395 *loader
= CreateURLLoaderInternal();
2396 pp::CompletionCallback callback
= loader_factory_
.NewCallback(method
);
2397 int rv
= loader
->Open(request
, callback
);
2398 if (rv
!= PP_OK_COMPLETIONPENDING
)
2402 pp::URLLoader
Instance::CreateURLLoaderInternal() {
2403 pp::URLLoader
loader(this);
2405 const PPB_URLLoaderTrusted
* trusted_interface
=
2406 reinterpret_cast<const PPB_URLLoaderTrusted
*>(
2407 pp::Module::Get()->GetBrowserInterface(
2408 PPB_URLLOADERTRUSTED_INTERFACE
));
2409 if (trusted_interface
)
2410 trusted_interface
->GrantUniversalAccess(loader
.pp_resource());
2414 int Instance::GetInitialPage(const std::string
& url
) {
2415 size_t found_idx
= url
.find('#');
2416 if (found_idx
== std::string::npos
)
2419 const std::string
& ref
= url
.substr(found_idx
+ 1);
2420 std::vector
<std::string
> fragments
;
2421 Tokenize(ref
, kDelimiters
, &fragments
);
2423 // Page number to return, zero-based.
2426 // Handle the case of http://foo.com/bar#NAMEDDEST. This is not explicitly
2427 // mentioned except by example in the Adobe "PDF Open Parameters" document.
2428 if ((fragments
.size() == 1) && (fragments
[0].find('=') == std::string::npos
))
2429 return engine_
->GetNamedDestinationPage(fragments
[0]);
2431 for (size_t i
= 0; i
< fragments
.size(); ++i
) {
2432 std::vector
<std::string
> key_value
;
2433 base::SplitString(fragments
[i
], '=', &key_value
);
2434 if (key_value
.size() != 2)
2436 const std::string
& key
= key_value
[0];
2437 const std::string
& value
= key_value
[1];
2439 if (base::strcasecmp(kPage
, key
.c_str()) == 0) {
2440 // |page_value| is 1-based.
2441 int page_value
= -1;
2442 if (base::StringToInt(value
, &page_value
) && page_value
> 0)
2443 page
= page_value
- 1;
2446 if (base::strcasecmp(kNamedDest
, key
.c_str()) == 0) {
2447 // |page_value| is 0-based.
2448 int page_value
= engine_
->GetNamedDestinationPage(value
);
2449 if (page_value
>= 0)
2457 void Instance::UpdateToolbarPosition(bool invalidate
) {
2458 pp::Rect ctrl_rc
= toolbar_
->GetControlsRect();
2459 int min_toolbar_width
= ctrl_rc
.width() + GetToolbarRightOffset() +
2460 GetScaled(kToolbarFadingOffsetLeft
);
2461 int min_toolbar_height
= ctrl_rc
.width() + GetToolbarBottomOffset() +
2462 GetScaled(kToolbarFadingOffsetBottom
);
2464 // Update toolbar position
2465 if (plugin_size_
.width() < min_toolbar_width
||
2466 plugin_size_
.height() < min_toolbar_height
) {
2467 // Disable toolbar if it does not fit on the screen.
2468 toolbar_
->Show(false, invalidate
);
2471 plugin_size_
.width() - GetToolbarRightOffset() - ctrl_rc
.right(),
2472 plugin_size_
.height() - GetToolbarBottomOffset() - ctrl_rc
.bottom());
2473 toolbar_
->MoveBy(offset
, invalidate
);
2475 int toolbar_width
= std::max(plugin_size_
.width() / 2, min_toolbar_width
);
2476 toolbar_
->ExpandLeft(toolbar_width
- toolbar_
->rect().width());
2477 toolbar_
->Show(painted_first_page_
, invalidate
);
2481 void Instance::UpdateProgressBarPosition(bool invalidate
) {
2482 // TODO(gene): verify we don't overlap with toolbar.
2483 int scrollbar_thickness
= GetScrollbarThickness();
2484 pp::Point
progress_origin(
2485 scrollbar_thickness
+ GetScaled(kProgressOffsetLeft
),
2486 plugin_size_
.height() - progress_bar_
.rect().height() -
2487 scrollbar_thickness
- GetScaled(kProgressOffsetBottom
));
2488 progress_bar_
.MoveTo(progress_origin
, invalidate
);
2491 void Instance::UpdatePageIndicatorPosition(bool invalidate
) {
2492 int32 doc_height
= static_cast<int>(document_size_
.height() * zoom_
);
2494 plugin_size_
.width() - page_indicator_
.rect().width() -
2495 GetScaled(GetScrollbarReservedThickness()),
2496 page_indicator_
.GetYPosition(engine_
->GetVerticalScrollbarYPosition(),
2497 doc_height
, plugin_size_
.height()));
2498 page_indicator_
.MoveTo(origin
, invalidate
);
2501 void Instance::SetZoom(ZoomMode zoom_mode
, double scale
) {
2502 double old_zoom
= zoom_
;
2504 zoom_mode_
= zoom_mode
;
2505 if (zoom_mode_
== ZOOM_SCALE
)
2509 engine_
->ZoomUpdated(zoom_
* device_scale_
);
2510 OnGeometryChanged(old_zoom
, device_scale_
);
2512 // If fit-to-height, snap to the beginning of the most visible page.
2513 if (zoom_mode_
== ZOOM_FIT_TO_PAGE
) {
2514 ScrollToPage(engine_
->GetMostVisiblePage());
2517 // Update sticky buttons to the current zoom style.
2518 Button
* ftp_btn
= static_cast<Button
*>(
2519 toolbar_
->GetControl(kFitToPageButtonId
));
2520 Button
* ftw_btn
= static_cast<Button
*>(
2521 toolbar_
->GetControl(kFitToWidthButtonId
));
2522 switch (zoom_mode_
) {
2523 case ZOOM_FIT_TO_PAGE
:
2524 ftp_btn
->SetPressedState(true);
2525 ftw_btn
->SetPressedState(false);
2527 case ZOOM_FIT_TO_WIDTH
:
2528 ftw_btn
->SetPressedState(true);
2529 ftp_btn
->SetPressedState(false);
2532 ftw_btn
->SetPressedState(false);
2533 ftp_btn
->SetPressedState(false);
2537 void Instance::UpdateZoomScale() {
2538 switch (zoom_mode_
) {
2540 break; // Keep current scale.
2541 case ZOOM_FIT_TO_PAGE
: {
2542 int page_num
= engine_
->GetFirstVisiblePage();
2545 pp::Rect rc
= engine_
->GetPageRect(page_num
);
2548 // Calculate fit to width zoom level.
2549 double ftw_zoom
= static_cast<double>(plugin_dip_size_
.width() -
2550 GetScrollbarReservedThickness()) / document_size_
.width();
2551 // Calculate fit to height zoom level. If document will not fit
2552 // horizontally, adjust zoom level to allow space for horizontal
2555 static_cast<double>(plugin_dip_size_
.height()) / rc
.height();
2556 if (fth_zoom
* document_size_
.width() >
2557 plugin_dip_size_
.width() - GetScrollbarReservedThickness())
2558 fth_zoom
= static_cast<double>(plugin_dip_size_
.height()
2559 - GetScrollbarReservedThickness()) / rc
.height();
2560 zoom_
= std::min(ftw_zoom
, fth_zoom
);
2562 case ZOOM_FIT_TO_WIDTH
:
2564 if (!document_size_
.width())
2566 zoom_
= static_cast<double>(plugin_dip_size_
.width() -
2567 GetScrollbarReservedThickness()) / document_size_
.width();
2568 if (zoom_mode_
== ZOOM_AUTO
&& zoom_
> 1.0)
2572 zoom_
= ClipToRange(zoom_
, kMinZoom
, kMaxZoom
);
2575 double Instance::CalculateZoom(uint32 control_id
) const {
2576 if (control_id
== kZoomInButtonId
) {
2577 for (size_t i
= 0; i
< ui_zoom::kPresetZoomFactorsSize
; ++i
) {
2578 double current_zoom
= ui_zoom::kPresetZoomFactors
[i
];
2579 if (current_zoom
- content::kEpsilon
> zoom_
)
2580 return current_zoom
;
2583 for (size_t i
= ui_zoom::kPresetZoomFactorsSize
; i
> 0; --i
) {
2584 double current_zoom
= ui_zoom::kPresetZoomFactors
[i
- 1];
2585 if (current_zoom
+ content::kEpsilon
< zoom_
)
2586 return current_zoom
;
2592 pp::ImageData
Instance::CreateResourceImage(PP_ResourceImage image_id
) {
2593 pp::ImageData resource_data
;
2594 if (hidpi_enabled_
) {
2596 pp::PDF::GetResourceImageForScale(this, image_id
, device_scale_
);
2599 return resource_data
.data() ? resource_data
2600 : pp::PDF::GetResourceImage(this, image_id
);
2603 std::string
Instance::GetLocalizedString(PP_ResourceString id
) {
2604 pp::Var
rv(pp::PDF::GetLocalizedString(this, id
));
2605 if (!rv
.is_string())
2606 return std::string();
2608 return rv
.AsString();
2611 void Instance::DrawText(const pp::Point
& top_center
, PP_ResourceString id
) {
2612 std::string
str(GetLocalizedString(id
));
2614 pp::FontDescription_Dev description
;
2615 description
.set_family(PP_FONTFAMILY_SANSSERIF
);
2616 description
.set_size(kMessageTextSize
* device_scale_
);
2617 pp::Font_Dev
font(this, description
);
2618 int length
= font
.MeasureSimpleText(str
);
2619 pp::Point
point(top_center
);
2620 point
.set_x(point
.x() - length
/ 2);
2621 DCHECK(!image_data_
.is_null());
2622 font
.DrawSimpleText(&image_data_
, str
, point
, kMessageTextColor
);
2625 void Instance::SetPrintPreviewMode(int page_count
) {
2626 if (!IsPrintPreview() || page_count
<= 0) {
2627 print_preview_page_count_
= 0;
2631 print_preview_page_count_
= page_count
;
2633 engine_
->AppendBlankPages(print_preview_page_count_
);
2634 if (preview_pages_info_
.size() > 0)
2635 LoadAvailablePreviewPage();
2638 bool Instance::IsPrintPreview() {
2639 return IsPrintPreviewUrl(url_
);
2642 int Instance::GetPageNumberToDisplay() {
2643 int page
= engine_
->GetMostVisiblePage();
2644 if (IsPrintPreview() && !print_preview_page_numbers_
.empty()) {
2645 page
= ClipToRange
<int>(page
, 0, print_preview_page_numbers_
.size() - 1);
2646 return print_preview_page_numbers_
[page
];
2651 void Instance::ProcessPreviewPageInfo(const std::string
& url
,
2652 int dst_page_index
) {
2653 if (!IsPrintPreview() || print_preview_page_count_
< 0)
2656 int src_page_index
= ExtractPrintPreviewPageIndex(url
);
2657 if (src_page_index
< 1)
2660 preview_pages_info_
.push(std::make_pair(url
, dst_page_index
));
2661 LoadAvailablePreviewPage();
2664 void Instance::LoadAvailablePreviewPage() {
2665 if (preview_pages_info_
.size() <= 0)
2668 std::string url
= preview_pages_info_
.front().first
;
2669 int dst_page_index
= preview_pages_info_
.front().second
;
2670 int src_page_index
= ExtractPrintPreviewPageIndex(url
);
2671 if (src_page_index
< 1 ||
2672 dst_page_index
>= print_preview_page_count_
||
2673 preview_document_load_state_
== LOAD_STATE_LOADING
) {
2677 preview_document_load_state_
= LOAD_STATE_LOADING
;
2678 LoadPreviewUrl(url
);
2681 void Instance::EnableAutoscroll(const pp::Point
& origin
) {
2685 pp::Size client_size
= plugin_size_
;
2686 if (v_scrollbar_
.get())
2687 client_size
.Enlarge(-GetScrollbarThickness(), 0);
2688 if (h_scrollbar_
.get())
2689 client_size
.Enlarge(0, -GetScrollbarThickness());
2691 // Do not allow autoscroll if client area is too small.
2692 if (autoscroll_anchor_
.size().width() > client_size
.width() ||
2693 autoscroll_anchor_
.size().height() > client_size
.height())
2696 autoscroll_rect_
= pp::Rect(
2697 pp::Point(origin
.x() - autoscroll_anchor_
.size().width() / 2,
2698 origin
.y() - autoscroll_anchor_
.size().height() / 2),
2699 autoscroll_anchor_
.size());
2701 // Make sure autoscroll anchor is in the client area.
2702 if (autoscroll_rect_
.right() > client_size
.width()) {
2703 autoscroll_rect_
.set_x(
2704 client_size
.width() - autoscroll_anchor_
.size().width());
2706 if (autoscroll_rect_
.bottom() > client_size
.height()) {
2707 autoscroll_rect_
.set_y(
2708 client_size
.height() - autoscroll_anchor_
.size().height());
2711 if (autoscroll_rect_
.x() < 0)
2712 autoscroll_rect_
.set_x(0);
2713 if (autoscroll_rect_
.y() < 0)
2714 autoscroll_rect_
.set_y(0);
2716 is_autoscroll_
= true;
2717 Invalidate(kAutoScrollId
, autoscroll_rect_
);
2719 ScheduleTimer(kAutoScrollId
, kAutoScrollTimeoutMs
);
2722 void Instance::DisableAutoscroll() {
2723 if (is_autoscroll_
) {
2724 is_autoscroll_
= false;
2725 Invalidate(kAutoScrollId
, autoscroll_rect_
);
2729 PP_CursorType_Dev
Instance::CalculateAutoscroll(const pp::Point
& mouse_pos
) {
2730 // Scroll only if mouse pointer is outside of the anchor area.
2731 if (autoscroll_rect_
.Contains(mouse_pos
)) {
2734 return PP_CURSORTYPE_MIDDLEPANNING
;
2737 // Relative position to the center of anchor area.
2738 pp::Point rel_pos
= mouse_pos
- autoscroll_rect_
.CenterPoint();
2740 // Calculate angle from the X axis. Angle is in range from -pi to pi.
2741 double angle
= atan2(static_cast<double>(rel_pos
.y()),
2742 static_cast<double>(rel_pos
.x()));
2744 autoscroll_x_
= rel_pos
.x() * kAutoScrollFactor
;
2745 autoscroll_y_
= rel_pos
.y() * kAutoScrollFactor
;
2747 // Angle is from -pi to pi. Screen Y is increasing toward bottom,
2748 // so negative angle represent north direction.
2749 if (angle
< - (M_PI
* 7.0 / 8.0)) {
2751 return PP_CURSORTYPE_WESTPANNING
;
2752 } else if (angle
< - (M_PI
* 5.0 / 8.0)) {
2754 return PP_CURSORTYPE_NORTHWESTPANNING
;
2755 } else if (angle
< - (M_PI
* 3.0 / 8.0)) {
2757 return PP_CURSORTYPE_NORTHPANNING
;
2758 } else if (angle
< - (M_PI
* 1.0 / 8.0)) {
2760 return PP_CURSORTYPE_NORTHEASTPANNING
;
2761 } else if (angle
< M_PI
* 1.0 / 8.0) {
2763 return PP_CURSORTYPE_EASTPANNING
;
2764 } else if (angle
< M_PI
* 3.0 / 8.0) {
2766 return PP_CURSORTYPE_SOUTHEASTPANNING
;
2767 } else if (angle
< M_PI
* 5.0 / 8.0) {
2769 return PP_CURSORTYPE_SOUTHPANNING
;
2770 } else if (angle
< M_PI
* 7.0 / 8.0) {
2772 return PP_CURSORTYPE_SOUTHWESTPANNING
;
2775 // went around the circle, going west again
2776 return PP_CURSORTYPE_WESTPANNING
;
2779 void Instance::ConfigureNumberImageGenerator() {
2780 std::vector
<pp::ImageData
> num_images
= GetThumbnailResources();
2781 pp::ImageData number_background
= CreateResourceImage(
2782 PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_NUM_BACKGROUND
);
2783 number_image_generator_
->Configure(number_background
,
2788 NumberImageGenerator
* Instance::number_image_generator() {
2789 if (!number_image_generator_
.get()) {
2790 number_image_generator_
.reset(new NumberImageGenerator(this));
2791 ConfigureNumberImageGenerator();
2793 return number_image_generator_
.get();
2796 int Instance::GetScaled(int x
) const {
2797 return static_cast<int>(x
* device_scale_
);
2800 void Instance::UserMetricsRecordAction(const std::string
& action
) {
2801 pp::PDF::UserMetricsRecordAction(this, pp::Var(action
));
2804 PDFScriptableObject::PDFScriptableObject(Instance
* instance
)
2805 : instance_(instance
) {
2808 PDFScriptableObject::~PDFScriptableObject() {
2811 bool PDFScriptableObject::HasMethod(const pp::Var
& name
, pp::Var
* exception
) {
2812 return instance_
->HasScriptableMethod(name
, exception
);
2815 pp::Var
PDFScriptableObject::Call(const pp::Var
& method
,
2816 const std::vector
<pp::Var
>& args
,
2817 pp::Var
* exception
) {
2818 return instance_
->CallScriptableMethod(method
, args
, exception
);
2821 } // namespace chrome_pdf