1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "pdf/instance.h"
7 #include <algorithm> // for min()
8 #define _USE_MATH_DEFINES // for M_PI
9 #include <cmath> // for log() and pow()
13 #include "base/json/json_reader.h"
14 #include "base/json/json_writer.h"
15 #include "base/logging.h"
16 #include "base/strings/string_number_conversions.h"
17 #include "base/strings/string_split.h"
18 #include "base/strings/string_util.h"
19 #include "base/values.h"
20 #include "chrome/browser/chrome_page_zoom_constants.h"
21 #include "chrome/common/content_restriction.h"
22 #include "content/public/common/page_zoom.h"
23 #include "net/base/escape.h"
24 #include "pdf/draw_utils.h"
25 #include "pdf/number_image_generator.h"
27 #include "pdf/resource_consts.h"
28 #include "ppapi/c/dev/ppb_cursor_control_dev.h"
29 #include "ppapi/c/pp_errors.h"
30 #include "ppapi/c/pp_rect.h"
31 #include "ppapi/c/private/ppp_pdf.h"
32 #include "ppapi/c/trusted/ppb_url_loader_trusted.h"
33 #include "ppapi/cpp/core.h"
34 #include "ppapi/cpp/dev/font_dev.h"
35 #include "ppapi/cpp/dev/memory_dev.h"
36 #include "ppapi/cpp/dev/text_input_dev.h"
37 #include "ppapi/cpp/module.h"
38 #include "ppapi/cpp/point.h"
39 #include "ppapi/cpp/private/pdf.h"
40 #include "ppapi/cpp/rect.h"
41 #include "ppapi/cpp/resource.h"
42 #include "ppapi/cpp/url_request_info.h"
43 #include "ui/events/keycodes/keyboard_codes.h"
45 #if defined(OS_MACOSX)
46 #include "base/mac/mac_util.h"
49 namespace chrome_pdf
{
51 struct ToolbarButtonInfo
{
53 Button::ButtonStyle style
;
54 PP_ResourceImage normal
;
55 PP_ResourceImage highlighted
;
56 PP_ResourceImage pressed
;
61 // Uncomment following #define to enable thumbnails.
62 // #define ENABLE_THUMBNAILS
64 const uint32 kToolbarSplashTimeoutMs
= 6000;
65 const uint32 kMessageTextColor
= 0xFF575757;
66 const uint32 kMessageTextSize
= 22;
67 const uint32 kProgressFadeTimeoutMs
= 250;
68 const uint32 kProgressDelayTimeoutMs
= 1000;
69 const uint32 kAutoScrollTimeoutMs
= 50;
70 const double kAutoScrollFactor
= 0.2;
72 // Javascript methods.
73 const char kJSAccessibility
[] = "accessibility";
74 const char kJSDocumentLoadComplete
[] = "documentLoadComplete";
75 const char kJSGetHeight
[] = "getHeight";
76 const char kJSGetHorizontalScrollbarThickness
[] =
77 "getHorizontalScrollbarThickness";
78 const char kJSGetPageLocationNormalized
[] = "getPageLocationNormalized";
79 const char kJSGetVerticalScrollbarThickness
[] = "getVerticalScrollbarThickness";
80 const char kJSGetWidth
[] = "getWidth";
81 const char kJSGetZoomLevel
[] = "getZoomLevel";
82 const char kJSGoToPage
[] = "goToPage";
83 const char kJSGrayscale
[] = "grayscale";
84 const char kJSLoadPreviewPage
[] = "loadPreviewPage";
85 const char kJSOnLoad
[] = "onload";
86 const char kJSOnPluginSizeChanged
[] = "onPluginSizeChanged";
87 const char kJSOnScroll
[] = "onScroll";
88 const char kJSPageXOffset
[] = "pageXOffset";
89 const char kJSPageYOffset
[] = "pageYOffset";
90 const char kJSPrintPreviewPageCount
[] = "printPreviewPageCount";
91 const char kJSReload
[] = "reload";
92 const char kJSRemovePrintButton
[] = "removePrintButton";
93 const char kJSResetPrintPreviewUrl
[] = "resetPrintPreviewUrl";
94 const char kJSSendKeyEvent
[] = "sendKeyEvent";
95 const char kJSSetPageNumbers
[] = "setPageNumbers";
96 const char kJSSetPageXOffset
[] = "setPageXOffset";
97 const char kJSSetPageYOffset
[] = "setPageYOffset";
98 const char kJSSetZoomLevel
[] = "setZoomLevel";
99 const char kJSZoomFitToHeight
[] = "fitToHeight";
100 const char kJSZoomFitToWidth
[] = "fitToWidth";
101 const char kJSZoomIn
[] = "zoomIn";
102 const char kJSZoomOut
[] = "zoomOut";
104 // URL reference parameters.
105 // For more possible parameters, see RFC 3778 and the "PDF Open Parameters"
106 // document from Adobe.
107 const char kDelimiters
[] = "#&";
108 const char kNamedDest
[] = "nameddest";
109 const char kPage
[] = "page";
111 const char kChromePrint
[] = "chrome://print/";
113 // Dictionary Value key names for the document accessibility info
114 const char kAccessibleNumberOfPages
[] = "numberOfPages";
115 const char kAccessibleLoaded
[] = "loaded";
116 const char kAccessibleCopyable
[] = "copyable";
118 const ToolbarButtonInfo kPDFToolbarButtons
[] = {
119 { kFitToPageButtonId
, Button::BUTTON_STATE
,
120 PP_RESOURCEIMAGE_PDF_BUTTON_FTP
,
121 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_HOVER
,
122 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_PRESSED
},
123 { kFitToWidthButtonId
, Button::BUTTON_STATE
,
124 PP_RESOURCEIMAGE_PDF_BUTTON_FTW
,
125 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_HOVER
,
126 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_PRESSED
},
127 { kZoomOutButtonId
, Button::BUTTON_CLICKABLE
,
128 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT
,
129 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_HOVER
,
130 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_PRESSED
},
131 { kZoomInButtonId
, Button::BUTTON_CLICKABLE
,
132 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN
,
133 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_HOVER
,
134 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_PRESSED
},
135 { kSaveButtonId
, Button::BUTTON_CLICKABLE
,
136 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE
,
137 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE_HOVER
,
138 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE_PRESSED
},
139 { kPrintButtonId
, Button::BUTTON_CLICKABLE
,
140 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT
,
141 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_HOVER
,
142 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_PRESSED
},
145 const ToolbarButtonInfo kPDFNoPrintToolbarButtons
[] = {
146 { kFitToPageButtonId
, Button::BUTTON_STATE
,
147 PP_RESOURCEIMAGE_PDF_BUTTON_FTP
,
148 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_HOVER
,
149 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_PRESSED
},
150 { kFitToWidthButtonId
, Button::BUTTON_STATE
,
151 PP_RESOURCEIMAGE_PDF_BUTTON_FTW
,
152 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_HOVER
,
153 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_PRESSED
},
154 { kZoomOutButtonId
, Button::BUTTON_CLICKABLE
,
155 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT
,
156 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_HOVER
,
157 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_PRESSED
},
158 { kZoomInButtonId
, Button::BUTTON_CLICKABLE
,
159 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN
,
160 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_HOVER
,
161 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_PRESSED
},
162 { kSaveButtonId
, Button::BUTTON_CLICKABLE
,
163 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE
,
164 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE_HOVER
,
165 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE_PRESSED
},
166 { kPrintButtonId
, Button::BUTTON_CLICKABLE
,
167 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_DISABLED
,
168 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_DISABLED
,
169 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_DISABLED
}
172 const ToolbarButtonInfo kPrintPreviewToolbarButtons
[] = {
173 { kFitToPageButtonId
, Button::BUTTON_STATE
,
174 PP_RESOURCEIMAGE_PDF_BUTTON_FTP
,
175 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_HOVER
,
176 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_PRESSED
},
177 { kFitToWidthButtonId
, Button::BUTTON_STATE
,
178 PP_RESOURCEIMAGE_PDF_BUTTON_FTW
,
179 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_HOVER
,
180 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_PRESSED
},
181 { kZoomOutButtonId
, Button::BUTTON_CLICKABLE
,
182 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT
,
183 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_HOVER
,
184 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_PRESSED
},
185 { kZoomInButtonId
, Button::BUTTON_CLICKABLE
,
186 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_END
,
187 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_END_HOVER
,
188 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_END_PRESSED
},
191 static const char kPPPPdfInterface
[] = PPP_PDF_INTERFACE_1
;
193 PP_Var
GetLinkAtPosition(PP_Instance instance
, PP_Point point
) {
196 pp::Instance::GetPerInstanceObject(instance
, kPPPPdfInterface
);
198 var
= static_cast<Instance
*>(object
)->GetLinkAtPosition(pp::Point(point
));
202 void Transform(PP_Instance instance
, PP_PrivatePageTransformType type
) {
204 pp::Instance::GetPerInstanceObject(instance
, kPPPPdfInterface
);
206 Instance
* obj_instance
= static_cast<Instance
*>(object
);
208 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CW
:
209 obj_instance
->RotateClockwise();
211 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CCW
:
212 obj_instance
->RotateCounterclockwise();
218 const PPP_Pdf ppp_private
= {
223 int ExtractPrintPreviewPageIndex(const std::string
& src_url
) {
224 // Sample |src_url| format: chrome://print/id/page_index/print.pdf
225 std::vector
<std::string
> url_substr
;
226 base::SplitString(src_url
.substr(strlen(kChromePrint
)), '/', &url_substr
);
227 if (url_substr
.size() != 3)
230 if (url_substr
[2] != "print.pdf")
234 if (!base::StringToInt(url_substr
[1], &page_index
))
239 bool IsPrintPreviewUrl(const std::string
& url
) {
240 return url
.substr(0, strlen(kChromePrint
)) == kChromePrint
;
243 void ScalePoint(float scale
, pp::Point
* point
) {
244 point
->set_x(static_cast<int>(point
->x() * scale
));
245 point
->set_y(static_cast<int>(point
->y() * scale
));
248 void ScaleRect(float scale
, pp::Rect
* rect
) {
249 int left
= static_cast<int>(floorf(rect
->x() * scale
));
250 int top
= static_cast<int>(floorf(rect
->y() * scale
));
251 int right
= static_cast<int>(ceilf((rect
->x() + rect
->width()) * scale
));
252 int bottom
= static_cast<int>(ceilf((rect
->y() + rect
->height()) * scale
));
253 rect
->SetRect(left
, top
, right
- left
, bottom
- top
);
257 T
ClipToRange(T value
, T lower_boundary
, T upper_boundary
) {
258 DCHECK(lower_boundary
<= upper_boundary
);
259 return std::max
<T
>(lower_boundary
, std::min
<T
>(value
, upper_boundary
));
264 Instance::Instance(PP_Instance instance
)
265 : pp::InstancePrivate(instance
),
266 pp::Find_Private(this),
267 pp::Printing_Dev(this),
268 pp::Selection_Dev(this),
269 pp::WidgetClient_Dev(this),
271 cursor_(PP_CURSORTYPE_POINTER
),
272 timer_pending_(false),
273 current_timer_id_(0),
276 printing_enabled_(true),
277 hidpi_enabled_(false),
278 full_(IsFullFrame()),
279 zoom_mode_(full_
? ZOOM_AUTO
: ZOOM_SCALE
),
280 did_call_start_loading_(false),
281 is_autoscroll_(false),
282 scrollbar_thickness_(-1),
283 scrollbar_reserved_thickness_(-1),
284 current_tb_info_(NULL
),
285 current_tb_info_size_(0),
286 paint_manager_(this, this, true),
287 delayed_progress_timer_id_(0),
289 painted_first_page_(false),
290 show_page_indicator_(false),
291 document_load_state_(LOAD_STATE_LOADING
),
292 preview_document_load_state_(LOAD_STATE_COMPLETE
),
293 told_browser_about_unsupported_feature_(false),
294 print_preview_page_count_(0) {
295 loader_factory_
.Initialize(this);
296 timer_factory_
.Initialize(this);
297 form_factory_
.Initialize(this);
298 callback_factory_
.Initialize(this);
299 engine_
.reset(PDFEngine::Create(this));
300 pp::Module::Get()->AddPluginInterface(kPPPPdfInterface
, &ppp_private
);
301 AddPerInstanceObject(kPPPPdfInterface
, this);
303 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_MOUSE
);
304 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_WHEEL
);
305 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_KEYBOARD
);
306 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_TOUCH
);
309 Instance::~Instance() {
310 if (timer_pending_
) {
311 timer_factory_
.CancelAll();
312 timer_pending_
= false;
314 // The engine may try to access this instance during its destruction.
315 // Make sure this happens early while the instance is still intact.
317 RemovePerInstanceObject(kPPPPdfInterface
, this);
320 bool Instance::Init(uint32_t argc
, const char* argn
[], const char* argv
[]) {
321 // For now, we hide HiDPI support behind a flag.
322 if (pp::PDF::IsFeatureEnabled(this, PP_PDFFEATURE_HIDPI
))
323 hidpi_enabled_
= true;
325 printing_enabled_
= pp::PDF::IsFeatureEnabled(this, PP_PDFFEATURE_PRINTING
);
326 if (printing_enabled_
) {
327 CreateToolbar(kPDFToolbarButtons
, arraysize(kPDFToolbarButtons
));
329 CreateToolbar(kPDFNoPrintToolbarButtons
,
330 arraysize(kPDFNoPrintToolbarButtons
));
335 // Load autoscroll anchor image.
337 CreateResourceImage(PP_RESOURCEIMAGE_PDF_PAN_SCROLL_ICON
);
339 #ifdef ENABLE_THUMBNAILS
342 const char* url
= NULL
;
343 for (uint32_t i
= 0; i
< argc
; ++i
) {
344 if (strcmp(argn
[i
], "src") == 0) {
353 CreatePageIndicator(IsPrintPreviewUrl(url
));
356 // For PDFs embedded in a frame, we don't get the data automatically like we
357 // do for full-frame loads. Start loading the data manually.
360 DCHECK(!did_call_start_loading_
);
361 pp::PDF::DidStartLoading(this);
362 did_call_start_loading_
= true;
365 ZoomLimitsChanged(kMinZoom
, kMaxZoom
);
367 text_input_
.reset(new pp::TextInput_Dev(this));
370 return engine_
->New(url
);
373 bool Instance::HandleDocumentLoad(const pp::URLLoader
& loader
) {
374 delayed_progress_timer_id_
= ScheduleTimer(kProgressBarId
,
375 kProgressDelayTimeoutMs
);
376 return engine_
->HandleDocumentLoad(loader
);
379 bool Instance::HandleInputEvent(const pp::InputEvent
& event
) {
380 // To simplify things, convert the event into device coordinates if it is
382 pp::InputEvent
event_device_res(event
);
384 pp::MouseInputEvent
mouse_event(event
);
385 if (!mouse_event
.is_null()) {
386 pp::Point point
= mouse_event
.GetPosition();
387 pp::Point movement
= mouse_event
.GetMovement();
388 ScalePoint(device_scale_
, &point
);
389 ScalePoint(device_scale_
, &movement
);
390 mouse_event
= pp::MouseInputEvent(
393 event
.GetTimeStamp(),
394 event
.GetModifiers(),
395 mouse_event
.GetButton(),
397 mouse_event
.GetClickCount(),
399 event_device_res
= mouse_event
;
403 // Check if we need to go to autoscroll mode.
404 if (event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE
&&
405 (event
.GetModifiers() & PP_INPUTEVENT_MODIFIER_MIDDLEBUTTONDOWN
)) {
406 pp::MouseInputEvent
mouse_event(event_device_res
);
407 pp::Point pos
= mouse_event
.GetPosition();
408 EnableAutoscroll(pos
);
409 UpdateCursor(CalculateAutoscroll(pos
));
412 // Quit autoscrolling on any other event.
416 #ifdef ENABLE_THUMBNAILS
417 if (event
.GetType() == PP_INPUTEVENT_TYPE_MOUSELEAVE
)
418 thumbnails_
.SlideOut();
420 if (thumbnails_
.HandleEvent(event_device_res
))
424 if (toolbar_
->HandleEvent(event_device_res
))
427 #ifdef ENABLE_THUMBNAILS
428 if (v_scrollbar_
.get() && event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE
) {
429 pp::MouseInputEvent
mouse_event(event
);
430 pp::Point pt
= mouse_event
.GetPosition();
431 pp::Rect v_scrollbar_rc
;
432 v_scrollbar_
->GetLocation(&v_scrollbar_rc
);
433 // There is a bug (https://bugs.webkit.org/show_bug.cgi?id=45208)
434 // in the webkit that makes event.u.mouse.button
435 // equal to PP_INPUTEVENT_MOUSEBUTTON_LEFT, even when no button is pressed.
436 // To work around this issue we use modifier for now, and will switch
437 // to button once the bug is fixed and webkit got merged back to our tree.
438 if (v_scrollbar_rc
.Contains(pt
) &&
439 (event
.GetModifiers() & PP_INPUTEVENT_MODIFIER_LEFTBUTTONDOWN
)) {
440 thumbnails_
.SlideIn();
443 // When scrollbar is in the scrolling mode we should display thumbnails
444 // even the mouse is outside the thumbnail and scrollbar areas.
445 // If mouse is outside plugin area, we are still getting mouse move events
446 // while scrolling. See bug description for details:
447 // http://code.google.com/p/chromium/issues/detail?id=56444
448 if (!v_scrollbar_rc
.Contains(pt
) && thumbnails_
.visible() &&
449 !(event
.GetModifiers() & PP_INPUTEVENT_MODIFIER_LEFTBUTTONDOWN
) &&
450 !thumbnails_
.rect().Contains(pt
)) {
451 thumbnails_
.SlideOut();
456 // Need to pass the event to the engine first, since if we're over an edit
457 // control we want it to get keyboard events (like space) instead of the
459 // TODO: will have to offset the mouse coordinates once we support bidi and
460 // there could be scrollbars on the left.
461 pp::InputEvent
offset_event(event_device_res
);
462 bool try_engine_first
= true;
463 switch (offset_event
.GetType()) {
464 case PP_INPUTEVENT_TYPE_MOUSEDOWN
:
465 case PP_INPUTEVENT_TYPE_MOUSEUP
:
466 case PP_INPUTEVENT_TYPE_MOUSEMOVE
:
467 case PP_INPUTEVENT_TYPE_MOUSEENTER
:
468 case PP_INPUTEVENT_TYPE_MOUSELEAVE
: {
469 pp::MouseInputEvent
mouse_event(event_device_res
);
470 pp::MouseInputEvent
mouse_event_dip(event
);
471 pp::Point point
= mouse_event
.GetPosition();
472 point
.set_x(point
.x() - available_area_
.x());
473 offset_event
= pp::MouseInputEvent(
476 event
.GetTimeStamp(),
477 event
.GetModifiers(),
478 mouse_event
.GetButton(),
480 mouse_event
.GetClickCount(),
481 mouse_event
.GetMovement());
482 if (!engine_
->IsSelecting()) {
483 if (!IsOverlayScrollbar() &&
484 !available_area_
.Contains(mouse_event
.GetPosition())) {
485 try_engine_first
= false;
486 } else if (IsOverlayScrollbar()) {
488 if ((v_scrollbar_
.get() && v_scrollbar_
->GetLocation(&temp
) &&
489 temp
.Contains(mouse_event_dip
.GetPosition())) ||
490 (h_scrollbar_
.get() && h_scrollbar_
->GetLocation(&temp
) &&
491 temp
.Contains(mouse_event_dip
.GetPosition()))) {
492 try_engine_first
= false;
501 if (try_engine_first
&& engine_
->HandleEvent(offset_event
))
504 // Left/Right arrows should scroll to the beginning of the Prev/Next page if
505 // there is no horizontal scroll bar.
506 // If fit-to-height, PgDown/PgUp should scroll to the beginning of the
507 // Prev/Next page. Spacebar / shift+spacebar should do the same.
508 if (v_scrollbar_
.get() && event
.GetType() == PP_INPUTEVENT_TYPE_KEYDOWN
) {
509 pp::KeyboardInputEvent
keyboard_event(event
);
510 bool no_h_scrollbar
= !h_scrollbar_
.get();
511 uint32_t key_code
= keyboard_event
.GetKeyCode();
512 bool page_down
= no_h_scrollbar
&& key_code
== ui::VKEY_RIGHT
;
513 bool page_up
= no_h_scrollbar
&& key_code
== ui::VKEY_LEFT
;
514 if (zoom_mode_
== ZOOM_FIT_TO_PAGE
) {
516 keyboard_event
.GetModifiers() & PP_INPUTEVENT_MODIFIER_SHIFTKEY
;
517 bool key_is_space
= key_code
== ui::VKEY_SPACE
;
518 page_down
|= key_is_space
|| key_code
== ui::VKEY_NEXT
;
519 page_up
|= (key_is_space
&& has_shift
) || (key_code
== ui::VKEY_PRIOR
);
522 int page
= engine_
->GetFirstVisiblePage();
525 // Engine calculates visible page including delimiter to the page size.
526 // We need to check here if the page itself is completely out of view and
527 // scroll to the next one in that case.
528 if (engine_
->GetPageRect(page
).bottom() * zoom_
<=
529 v_scrollbar_
->GetValue())
531 ScrollToPage(page
+ 1);
532 UpdateCursor(PP_CURSORTYPE_POINTER
);
534 } else if (page_up
) {
535 int page
= engine_
->GetFirstVisiblePage();
538 if (engine_
->GetPageRect(page
).y() * zoom_
>= v_scrollbar_
->GetValue())
541 UpdateCursor(PP_CURSORTYPE_POINTER
);
546 if (v_scrollbar_
.get() && v_scrollbar_
->HandleEvent(event
)) {
547 UpdateCursor(PP_CURSORTYPE_POINTER
);
551 if (h_scrollbar_
.get() && h_scrollbar_
->HandleEvent(event
)) {
552 UpdateCursor(PP_CURSORTYPE_POINTER
);
556 if (timer_pending_
&&
557 (event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEUP
||
558 event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE
)) {
559 timer_factory_
.CancelAll();
560 timer_pending_
= false;
561 } else if (event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE
&&
562 engine_
->IsSelecting()) {
563 bool set_timer
= false;
564 pp::MouseInputEvent
mouse_event(event
);
565 if (v_scrollbar_
.get() &&
566 (mouse_event
.GetPosition().y() <= 0 ||
567 mouse_event
.GetPosition().y() >= (plugin_dip_size_
.height() - 1))) {
568 v_scrollbar_
->ScrollBy(
569 PP_SCROLLBY_LINE
, mouse_event
.GetPosition().y() >= 0 ? 1: -1);
572 if (h_scrollbar_
.get() &&
573 (mouse_event
.GetPosition().x() <= 0 ||
574 mouse_event
.GetPosition().x() >= (plugin_dip_size_
.width() - 1))) {
575 h_scrollbar_
->ScrollBy(PP_SCROLLBY_LINE
,
576 mouse_event
.GetPosition().x() >= 0 ? 1: -1);
581 last_mouse_event_
= pp::MouseInputEvent(event
);
583 pp::CompletionCallback callback
=
584 timer_factory_
.NewCallback(&Instance::OnTimerFired
);
585 pp::Module::Get()->core()->CallOnMainThread(kDragTimerMs
, callback
);
586 timer_pending_
= true;
590 if (event
.GetType() == PP_INPUTEVENT_TYPE_KEYDOWN
) {
591 pp::KeyboardInputEvent
keyboard_event(event
);
592 const uint32 modifier
= event
.GetModifiers();
593 if (modifier
& kDefaultKeyModifier
) {
594 switch (keyboard_event
.GetKeyCode()) {
596 engine_
->SelectAll();
599 } else if (modifier
& PP_INPUTEVENT_MODIFIER_CONTROLKEY
) {
600 switch (keyboard_event
.GetKeyCode()) {
603 engine_
->RotateCounterclockwise();
607 engine_
->RotateClockwise();
613 // Return true for unhandled clicks so the plugin takes focus.
614 return (event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN
);
617 void Instance::DidChangeView(const pp::View
& view
) {
618 pp::Rect
view_rect(view
.GetRect());
619 float device_scale
= 1.0f
;
620 float old_device_scale
= device_scale_
;
622 device_scale
= view
.GetDeviceScale();
623 pp::Size
view_device_size(view_rect
.width() * device_scale
,
624 view_rect
.height() * device_scale
);
625 if (view_device_size
== plugin_size_
&& device_scale
== device_scale_
)
626 return; // We don't care about the position, only the size.
628 image_data_
= pp::ImageData();
629 device_scale_
= device_scale
;
630 plugin_dip_size_
= view_rect
.size();
631 plugin_size_
= view_device_size
;
633 paint_manager_
.SetSize(view_device_size
, device_scale_
);
635 image_data_
= pp::ImageData(this,
636 PP_IMAGEDATAFORMAT_BGRA_PREMUL
,
639 if (image_data_
.is_null()) {
640 DCHECK(plugin_size_
.IsEmpty());
644 // View dimensions changed, disable autoscroll (if it was enabled).
647 OnGeometryChanged(zoom_
, old_device_scale
);
650 pp::Var
Instance::GetInstanceObject() {
651 if (instance_object_
.is_undefined()) {
652 PDFScriptableObject
* object
= new PDFScriptableObject(this);
653 // The pp::Var takes ownership of object here.
654 instance_object_
= pp::VarPrivate(this, object
);
657 return instance_object_
;
660 pp::Var
Instance::GetLinkAtPosition(const pp::Point
& point
) {
661 pp::Point
offset_point(point
);
662 ScalePoint(device_scale_
, &offset_point
);
663 offset_point
.set_x(offset_point
.x() - available_area_
.x());
664 return engine_
->GetLinkAtPosition(offset_point
);
667 pp::Var
Instance::GetSelectedText(bool html
) {
668 if (html
|| !engine_
->HasPermission(PDFEngine::PERMISSION_COPY
))
670 return engine_
->GetSelectedText();
673 void Instance::InvalidateWidget(pp::Widget_Dev widget
,
674 const pp::Rect
& dirty_rect
) {
675 if (v_scrollbar_
.get() && *v_scrollbar_
== widget
) {
676 if (!image_data_
.is_null())
677 v_scrollbar_
->Paint(dirty_rect
.pp_rect(), &image_data_
);
678 } else if (h_scrollbar_
.get() && *h_scrollbar_
== widget
) {
679 if (!image_data_
.is_null())
680 h_scrollbar_
->Paint(dirty_rect
.pp_rect(), &image_data_
);
682 // Possible to hit this condition since sometimes the scrollbar codes posts
683 // a task to do something later, and we could have deleted our reference in
688 pp::Rect dirty_rect_scaled
= dirty_rect
;
689 ScaleRect(device_scale_
, &dirty_rect_scaled
);
690 paint_manager_
.InvalidateRect(dirty_rect_scaled
);
693 void Instance::ScrollbarValueChanged(pp::Scrollbar_Dev scrollbar
,
695 value
= GetScaled(value
);
696 if (v_scrollbar_
.get() && *v_scrollbar_
== scrollbar
) {
697 engine_
->ScrolledToYPosition(value
);
699 v_scrollbar_
->GetLocation(&rc
);
700 int32 doc_height
= GetDocumentPixelHeight();
701 doc_height
-= GetScaled(rc
.height());
702 #ifdef ENABLE_THUMBNAILS
703 if (thumbnails_
.visible()) {
704 thumbnails_
.SetPosition(value
, doc_height
, true);
708 plugin_size_
.width() - page_indicator_
.rect().width() -
709 GetScaled(GetScrollbarReservedThickness()),
710 page_indicator_
.GetYPosition(value
, doc_height
, plugin_size_
.height()));
711 page_indicator_
.MoveTo(origin
, page_indicator_
.visible());
712 } else if (h_scrollbar_
.get() && *h_scrollbar_
== scrollbar
) {
713 engine_
->ScrolledToXPosition(value
);
717 void Instance::ScrollbarOverlayChanged(pp::Scrollbar_Dev scrollbar
,
719 scrollbar_reserved_thickness_
= overlay
? 0 : scrollbar_thickness_
;
720 OnGeometryChanged(zoom_
, device_scale_
);
723 uint32_t Instance::QuerySupportedPrintOutputFormats() {
724 return engine_
->QuerySupportedPrintOutputFormats();
727 int32_t Instance::PrintBegin(const PP_PrintSettings_Dev
& print_settings
) {
728 // For us num_pages is always equal to the number of pages in the PDF
729 // document irrespective of the printable area.
730 int32_t ret
= engine_
->GetNumberOfPages();
734 uint32_t supported_formats
= engine_
->QuerySupportedPrintOutputFormats();
735 if ((print_settings
.format
& supported_formats
) == 0)
738 print_settings_
.is_printing
= true;
739 print_settings_
.pepper_print_settings
= print_settings
;
740 engine_
->PrintBegin();
744 pp::Resource
Instance::PrintPages(
745 const PP_PrintPageNumberRange_Dev
* page_ranges
,
746 uint32_t page_range_count
) {
747 if (!print_settings_
.is_printing
)
748 return pp::Resource();
750 print_settings_
.print_pages_called_
= true;
751 return engine_
->PrintPages(page_ranges
, page_range_count
,
752 print_settings_
.pepper_print_settings
);
755 void Instance::PrintEnd() {
756 if (print_settings_
.print_pages_called_
)
757 UserMetricsRecordAction("PDF.PrintPage");
758 print_settings_
.Clear();
762 bool Instance::IsPrintScalingDisabled() {
763 return !engine_
->GetPrintScaling();
766 bool Instance::StartFind(const std::string
& text
, bool case_sensitive
) {
767 engine_
->StartFind(text
.c_str(), case_sensitive
);
771 void Instance::SelectFindResult(bool forward
) {
772 engine_
->SelectFindResult(forward
);
775 void Instance::StopFind() {
779 void Instance::Zoom(double scale
, bool text_only
) {
780 UserMetricsRecordAction("PDF.ZoomFromBrowser");
781 SetZoom(ZOOM_SCALE
, scale
);
784 void Instance::ZoomChanged(double factor
) {
786 Zoom_Dev::ZoomChanged(factor
);
789 void Instance::OnPaint(const std::vector
<pp::Rect
>& paint_rects
,
790 std::vector
<PaintManager::ReadyRect
>* ready
,
791 std::vector
<pp::Rect
>* pending
) {
792 if (image_data_
.is_null()) {
793 DCHECK(plugin_size_
.IsEmpty());
797 first_paint_
= false;
798 pp::Rect rect
= pp::Rect(pp::Point(), plugin_size_
);
799 FillRect(rect
, kBackgroundColor
);
800 ready
->push_back(PaintManager::ReadyRect(rect
, image_data_
, true));
801 *pending
= paint_rects
;
807 for (size_t i
= 0; i
< paint_rects
.size(); i
++) {
808 // Intersect with plugin area since there could be pending invalidates from
809 // when the plugin area was larger.
811 paint_rects
[i
].Intersect(pp::Rect(pp::Point(), plugin_size_
));
815 pp::Rect pdf_rect
= available_area_
.Intersect(rect
);
816 if (!pdf_rect
.IsEmpty()) {
817 pdf_rect
.Offset(available_area_
.x() * -1, 0);
819 std::vector
<pp::Rect
> pdf_ready
;
820 std::vector
<pp::Rect
> pdf_pending
;
821 engine_
->Paint(pdf_rect
, &image_data_
, &pdf_ready
, &pdf_pending
);
822 for (size_t j
= 0; j
< pdf_ready
.size(); ++j
) {
823 pdf_ready
[j
].Offset(available_area_
.point());
825 PaintManager::ReadyRect(pdf_ready
[j
], image_data_
, false));
827 for (size_t j
= 0; j
< pdf_pending
.size(); ++j
) {
828 pdf_pending
[j
].Offset(available_area_
.point());
829 pending
->push_back(pdf_pending
[j
]);
833 for (size_t j
= 0; j
< background_parts_
.size(); ++j
) {
834 pp::Rect intersection
= background_parts_
[j
].location
.Intersect(rect
);
835 if (!intersection
.IsEmpty()) {
836 FillRect(intersection
, background_parts_
[j
].color
);
838 PaintManager::ReadyRect(intersection
, image_data_
, false));
842 if (document_load_state_
== LOAD_STATE_FAILED
) {
843 pp::Point top_center
;
844 top_center
.set_x(plugin_size_
.width() / 2);
845 top_center
.set_y(plugin_size_
.height() / 2);
846 DrawText(top_center
, PP_RESOURCESTRING_PDFLOAD_FAILED
);
849 #ifdef ENABLE_THUMBNAILS
850 thumbnails_
.Paint(&image_data_
, rect
);
854 engine_
->PostPaint();
856 // Must paint scrollbars after the background parts, in case we have an
857 // overlay scrollbar that's over the background. We also do this in a separate
858 // loop because the scrollbar painting logic uses the signal of whether there
859 // are pending paints or not to figure out if it should draw right away or
861 for (size_t i
= 0; i
< paint_rects
.size(); i
++) {
862 PaintIfWidgetIntersects(h_scrollbar_
.get(), paint_rects
[i
], ready
, pending
);
863 PaintIfWidgetIntersects(v_scrollbar_
.get(), paint_rects
[i
], ready
, pending
);
866 if (progress_bar_
.visible())
867 PaintOverlayControl(&progress_bar_
, &image_data_
, ready
);
869 if (page_indicator_
.visible())
870 PaintOverlayControl(&page_indicator_
, &image_data_
, ready
);
872 if (toolbar_
->current_transparency() != kTransparentAlpha
)
873 PaintOverlayControl(toolbar_
.get(), &image_data_
, ready
);
875 // Paint autoscroll anchor if needed.
876 if (is_autoscroll_
) {
877 size_t limit
= ready
->size();
878 for (size_t i
= 0; i
< limit
; i
++) {
879 pp::Rect anchor_rect
= autoscroll_rect_
.Intersect((*ready
)[i
].rect
);
880 if (!anchor_rect
.IsEmpty()) {
881 pp::Rect draw_rc
= pp::Rect(
882 pp::Point(anchor_rect
.x() - autoscroll_rect_
.x(),
883 anchor_rect
.y() - autoscroll_rect_
.y()),
885 // Paint autoscroll anchor.
886 AlphaBlend(autoscroll_anchor_
, draw_rc
,
887 &image_data_
, anchor_rect
.point(), kOpaqueAlpha
);
893 void Instance::PaintOverlayControl(
895 pp::ImageData
* image_data
,
896 std::vector
<PaintManager::ReadyRect
>* ready
) {
897 // Make sure that we only paint overlay controls over an area that's ready,
898 // i.e. not pending. Otherwise we'll mark the control rect as ready and
899 // it'll overwrite the pdf region.
900 std::list
<pp::Rect
> ctrl_rects
;
901 for (size_t i
= 0; i
< ready
->size(); i
++) {
902 pp::Rect rc
= ctrl
->rect().Intersect((*ready
)[i
].rect
);
904 ctrl_rects
.push_back(rc
);
907 if (!ctrl_rects
.empty()) {
908 ctrl
->PaintMultipleRects(image_data
, ctrl_rects
);
910 std::list
<pp::Rect
>::iterator iter
;
911 for (iter
= ctrl_rects
.begin(); iter
!= ctrl_rects
.end(); ++iter
) {
912 ready
->push_back(PaintManager::ReadyRect(*iter
, *image_data
, false));
917 void Instance::DidOpen(int32_t result
) {
918 if (result
== PP_OK
) {
919 engine_
->HandleDocumentLoad(embed_loader_
);
920 } else if (result
!= PP_ERROR_ABORTED
) { // Can happen in tests.
925 void Instance::DidOpenPreview(int32_t result
) {
926 if (result
== PP_OK
) {
927 preview_engine_
.reset(PDFEngine::Create(new PreviewModeClient(this)));
928 preview_engine_
->HandleDocumentLoad(embed_preview_loader_
);
934 void Instance::PaintIfWidgetIntersects(
935 pp::Widget_Dev
* widget
,
936 const pp::Rect
& rect
,
937 std::vector
<PaintManager::ReadyRect
>* ready
,
938 std::vector
<pp::Rect
>* pending
) {
943 if (!widget
->GetLocation(&location
))
946 ScaleRect(device_scale_
, &location
);
947 location
= location
.Intersect(rect
);
948 if (location
.IsEmpty())
951 if (IsOverlayScrollbar()) {
952 // If we're using overlay scrollbars, and there are pending paints under the
953 // scrollbar, don't update the scrollbar instantly. While it would be nice,
954 // we would need to double buffer the plugin area in order to make this
955 // work. This is because we'd need to always have a copy of what the pdf
956 // under the scrollbar looks like, and additionally we couldn't paint the
957 // pdf under the scrollbar if it's ready until we got the preceding flush.
958 // So in practice, it would make painting slower and introduce extra buffer
959 // copies for the general case.
960 for (size_t i
= 0; i
< pending
->size(); ++i
) {
961 if ((*pending
)[i
].Intersects(location
))
965 // Even if none of the pending paints are under the scrollbar, we never want
966 // to paint it if it's over the pdf if there are other pending paints.
967 // Otherwise different parts of the pdf plugin would display at different
969 if (!pending
->empty() && available_area_
.Intersects(rect
)) {
970 pending
->push_back(location
);
975 pp::Rect location_dip
= location
;
976 ScaleRect(1.0f
/ device_scale_
, &location_dip
);
978 DCHECK(!image_data_
.is_null());
979 widget
->Paint(location_dip
, &image_data_
);
981 ready
->push_back(PaintManager::ReadyRect(location
, image_data_
, true));
984 void Instance::OnTimerFired(int32_t) {
985 HandleInputEvent(last_mouse_event_
);
988 void Instance::OnClientTimerFired(int32_t id
) {
989 engine_
->OnCallback(id
);
992 void Instance::OnControlTimerFired(int32_t,
993 const uint32
& control_id
,
994 const uint32
& timer_id
) {
995 if (control_id
== toolbar_
->id()) {
996 toolbar_
->OnTimerFired(timer_id
);
997 } else if (control_id
== progress_bar_
.id()) {
998 if (timer_id
== delayed_progress_timer_id_
) {
999 if (document_load_state_
== LOAD_STATE_LOADING
&&
1000 !progress_bar_
.visible()) {
1001 progress_bar_
.Fade(true, kProgressFadeTimeoutMs
);
1003 delayed_progress_timer_id_
= 0;
1005 progress_bar_
.OnTimerFired(timer_id
);
1007 } else if (control_id
== kAutoScrollId
) {
1008 if (is_autoscroll_
) {
1009 if (autoscroll_x_
!= 0 && h_scrollbar_
.get()) {
1010 h_scrollbar_
->ScrollBy(PP_SCROLLBY_PIXEL
, autoscroll_x_
);
1012 if (autoscroll_y_
!= 0 && v_scrollbar_
.get()) {
1013 v_scrollbar_
->ScrollBy(PP_SCROLLBY_PIXEL
, autoscroll_y_
);
1016 // Reschedule timer.
1017 ScheduleTimer(kAutoScrollId
, kAutoScrollTimeoutMs
);
1019 } else if (control_id
== kPageIndicatorId
) {
1020 page_indicator_
.OnTimerFired(timer_id
);
1022 #ifdef ENABLE_THUMBNAILS
1023 else if (control_id
== thumbnails_
.id()) {
1024 thumbnails_
.OnTimerFired(timer_id
);
1029 void Instance::CalculateBackgroundParts() {
1030 background_parts_
.clear();
1031 int v_scrollbar_thickness
=
1032 GetScaled(v_scrollbar_
.get() ? GetScrollbarReservedThickness() : 0);
1033 int h_scrollbar_thickness
=
1034 GetScaled(h_scrollbar_
.get() ? GetScrollbarReservedThickness() : 0);
1035 int width_without_scrollbar
= std::max(
1036 plugin_size_
.width() - v_scrollbar_thickness
, 0);
1037 int height_without_scrollbar
= std::max(
1038 plugin_size_
.height() - h_scrollbar_thickness
, 0);
1039 int left_width
= available_area_
.x();
1040 int right_start
= available_area_
.right();
1041 int right_width
= abs(width_without_scrollbar
- available_area_
.right());
1042 int bottom
= std::min(available_area_
.bottom(), height_without_scrollbar
);
1044 // Add the left, right, and bottom rectangles. Note: we assume only
1045 // horizontal centering.
1046 BackgroundPart part
= {
1047 pp::Rect(0, 0, left_width
, bottom
),
1050 if (!part
.location
.IsEmpty())
1051 background_parts_
.push_back(part
);
1052 part
.location
= pp::Rect(right_start
, 0, right_width
, bottom
);
1053 if (!part
.location
.IsEmpty())
1054 background_parts_
.push_back(part
);
1055 part
.location
= pp::Rect(
1056 0, bottom
, width_without_scrollbar
, height_without_scrollbar
- bottom
);
1057 if (!part
.location
.IsEmpty())
1058 background_parts_
.push_back(part
);
1060 if (h_scrollbar_thickness
1061 #if defined(OS_MACOSX)
1066 v_scrollbar_thickness
) {
1067 part
.color
= 0xFFFFFFFF;
1068 part
.location
= pp::Rect(plugin_size_
.width() - v_scrollbar_thickness
,
1069 plugin_size_
.height() - h_scrollbar_thickness
,
1070 h_scrollbar_thickness
,
1071 v_scrollbar_thickness
);
1072 background_parts_
.push_back(part
);
1076 int Instance::GetDocumentPixelWidth() const {
1077 return static_cast<int>(ceil(document_size_
.width() * zoom_
* device_scale_
));
1080 int Instance::GetDocumentPixelHeight() const {
1081 return static_cast<int>(ceil(document_size_
.height() *
1086 void Instance::FillRect(const pp::Rect
& rect
, uint32 color
) {
1087 DCHECK(!image_data_
.is_null() || rect
.IsEmpty());
1088 uint32
* buffer_start
= static_cast<uint32
*>(image_data_
.data());
1089 int stride
= image_data_
.stride();
1090 uint32
* ptr
= buffer_start
+ rect
.y() * stride
/ 4 + rect
.x();
1091 int height
= rect
.height();
1092 int width
= rect
.width();
1093 for (int y
= 0; y
< height
; ++y
) {
1094 for (int x
= 0; x
< width
; ++x
)
1100 void Instance::DocumentSizeUpdated(const pp::Size
& size
) {
1101 document_size_
= size
;
1103 OnGeometryChanged(zoom_
, device_scale_
);
1106 void Instance::Invalidate(const pp::Rect
& rect
) {
1107 pp::Rect
offset_rect(rect
);
1108 offset_rect
.Offset(available_area_
.point());
1109 paint_manager_
.InvalidateRect(offset_rect
);
1112 void Instance::Scroll(const pp::Point
& point
) {
1113 pp::Rect scroll_area
= available_area_
;
1114 if (IsOverlayScrollbar()) {
1116 if (h_scrollbar_
.get()) {
1117 h_scrollbar_
->GetLocation(&rc
);
1118 ScaleRect(device_scale_
, &rc
);
1119 if (scroll_area
.bottom() > rc
.y()) {
1120 scroll_area
.set_height(rc
.y() - scroll_area
.y());
1121 paint_manager_
.InvalidateRect(rc
);
1124 if (v_scrollbar_
.get()) {
1125 v_scrollbar_
->GetLocation(&rc
);
1126 ScaleRect(device_scale_
, &rc
);
1127 if (scroll_area
.right() > rc
.x()) {
1128 scroll_area
.set_width(rc
.x() - scroll_area
.x());
1129 paint_manager_
.InvalidateRect(rc
);
1133 paint_manager_
.ScrollRect(scroll_area
, point
);
1135 if (toolbar_
->current_transparency() != kTransparentAlpha
)
1136 paint_manager_
.InvalidateRect(toolbar_
->GetControlsRect());
1138 if (progress_bar_
.visible())
1139 paint_manager_
.InvalidateRect(progress_bar_
.rect());
1142 paint_manager_
.InvalidateRect(autoscroll_rect_
);
1144 if (show_page_indicator_
) {
1145 page_indicator_
.set_current_page(GetPageNumberToDisplay());
1146 page_indicator_
.Splash();
1149 if (page_indicator_
.visible())
1150 paint_manager_
.InvalidateRect(page_indicator_
.rect());
1152 // Run the scroll callback asynchronously. This function can be invoked by a
1153 // layout change which should not re-enter into JS synchronously.
1154 pp::CompletionCallback callback
=
1155 callback_factory_
.NewCallback(&Instance::RunCallback
,
1156 on_scroll_callback_
);
1157 pp::Module::Get()->core()->CallOnMainThread(0, callback
);
1160 void Instance::ScrollToX(int position
) {
1161 if (!h_scrollbar_
.get()) {
1165 int position_dip
= static_cast<int>(position
/ device_scale_
);
1166 h_scrollbar_
->SetValue(position_dip
);
1169 void Instance::ScrollToY(int position
) {
1170 if (!v_scrollbar_
.get()) {
1174 int position_dip
= static_cast<int>(position
/ device_scale_
);
1175 v_scrollbar_
->SetValue(ClipToRange(position_dip
, 0, valid_v_range_
));
1178 void Instance::ScrollToPage(int page
) {
1179 if (!v_scrollbar_
.get())
1182 if (engine_
->GetNumberOfPages() == 0)
1185 int index
= ClipToRange(page
, 0, engine_
->GetNumberOfPages() - 1);
1186 pp::Rect rect
= engine_
->GetPageRect(index
);
1187 // If we are trying to scroll pass the last page,
1188 // scroll to the end of the last page.
1189 int position
= index
< page
? rect
.bottom() : rect
.y();
1190 ScrollToY(position
* zoom_
* device_scale_
);
1193 void Instance::NavigateTo(const std::string
& url
, bool open_in_new_tab
) {
1194 std::string
url_copy(url
);
1196 // Empty |url_copy| is ok, and will effectively be a reload.
1197 // Skip the code below so an empty URL does not turn into "http://", which
1198 // will cause GURL to fail a DCHECK.
1199 if (!url_copy
.empty()) {
1200 // If |url_copy| starts with '#', then it's for the same URL with a
1201 // different URL fragment.
1202 if (url_copy
[0] == '#') {
1203 url_copy
= url_
+ url_copy
;
1204 // Changing the href does not actually do anything when navigating in the
1205 // same tab, so do the actual page scroll here. Then fall through so the
1206 // href gets updated.
1207 if (!open_in_new_tab
) {
1208 int page_number
= GetInitialPage(url_copy
);
1209 if (page_number
>= 0)
1210 ScrollToPage(page_number
);
1213 // If there's no scheme, add http.
1214 if (url_copy
.find("://") == std::string::npos
&&
1215 url_copy
.find("mailto:") == std::string::npos
) {
1216 url_copy
= "http://" + url_copy
;
1218 // Make sure |url_copy| starts with a valid scheme.
1219 if (url_copy
.find("http://") != 0 &&
1220 url_copy
.find("https://") != 0 &&
1221 url_copy
.find("ftp://") != 0 &&
1222 url_copy
.find("file://") != 0 &&
1223 url_copy
.find("mailto:") != 0) {
1226 // Make sure |url_copy| is not only a scheme.
1227 if (url_copy
== "http://" ||
1228 url_copy
== "https://" ||
1229 url_copy
== "ftp://" ||
1230 url_copy
== "file://" ||
1231 url_copy
== "mailto:") {
1235 if (open_in_new_tab
) {
1236 GetWindowObject().Call("open", url_copy
);
1238 GetWindowObject().GetProperty("top").GetProperty("location").
1239 SetProperty("href", url_copy
);
1243 void Instance::UpdateCursor(PP_CursorType_Dev cursor
) {
1244 if (cursor
== cursor_
)
1248 const PPB_CursorControl_Dev
* cursor_interface
=
1249 reinterpret_cast<const PPB_CursorControl_Dev
*>(
1250 pp::Module::Get()->GetBrowserInterface(PPB_CURSOR_CONTROL_DEV_INTERFACE
));
1251 if (!cursor_interface
) {
1256 cursor_interface
->SetCursor(
1257 pp_instance(), cursor_
, pp::ImageData().pp_resource(), NULL
);
1260 void Instance::UpdateTickMarks(const std::vector
<pp::Rect
>& tickmarks
) {
1261 if (!v_scrollbar_
.get())
1264 float inverse_scale
= 1.0f
/ device_scale_
;
1265 std::vector
<pp::Rect
> scaled_tickmarks
= tickmarks
;
1266 for (size_t i
= 0; i
< scaled_tickmarks
.size(); i
++) {
1267 ScaleRect(inverse_scale
, &scaled_tickmarks
[i
]);
1270 v_scrollbar_
->SetTickMarks(
1271 scaled_tickmarks
.empty() ? NULL
: &scaled_tickmarks
[0], tickmarks
.size());
1274 void Instance::NotifyNumberOfFindResultsChanged(int total
, bool final_result
) {
1275 NumberOfFindResultsChanged(total
, final_result
);
1278 void Instance::NotifySelectedFindResultChanged(int current_find_index
) {
1279 SelectedFindResultChanged(current_find_index
);
1282 void Instance::OnEvent(uint32 control_id
, uint32 event_id
, void* data
) {
1283 if (event_id
== Button::EVENT_ID_BUTTON_CLICKED
||
1284 event_id
== Button::EVENT_ID_BUTTON_STATE_CHANGED
) {
1285 switch (control_id
) {
1286 case kFitToPageButtonId
:
1287 UserMetricsRecordAction("PDF.FitToPageButton");
1288 SetZoom(ZOOM_FIT_TO_PAGE
, 0);
1291 case kFitToWidthButtonId
:
1292 UserMetricsRecordAction("PDF.FitToWidthButton");
1293 SetZoom(ZOOM_FIT_TO_WIDTH
, 0);
1296 case kZoomOutButtonId
:
1297 case kZoomInButtonId
:
1298 UserMetricsRecordAction(control_id
== kZoomOutButtonId
?
1299 "PDF.ZoomOutButton" : "PDF.ZoomInButton");
1300 SetZoom(ZOOM_SCALE
, CalculateZoom(control_id
));
1304 UserMetricsRecordAction("PDF.SaveButton");
1307 case kPrintButtonId
:
1308 UserMetricsRecordAction("PDF.PrintButton");
1313 if (control_id
== kThumbnailsId
&&
1314 event_id
== ThumbnailControl::EVENT_ID_THUMBNAIL_SELECTED
) {
1315 int page
= *static_cast<int*>(data
);
1316 pp::Rect
page_rc(engine_
->GetPageRect(page
));
1317 ScrollToY(static_cast<int>(page_rc
.y() * zoom_
* device_scale_
));
1321 void Instance::Invalidate(uint32 control_id
, const pp::Rect
& rc
) {
1322 paint_manager_
.InvalidateRect(rc
);
1325 uint32
Instance::ScheduleTimer(uint32 control_id
, uint32 timeout_ms
) {
1326 current_timer_id_
++;
1327 pp::CompletionCallback callback
=
1328 timer_factory_
.NewCallback(&Instance::OnControlTimerFired
,
1331 pp::Module::Get()->core()->CallOnMainThread(timeout_ms
, callback
);
1332 return current_timer_id_
;
1335 void Instance::SetEventCapture(uint32 control_id
, bool set_capture
) {
1336 // TODO(gene): set event capture here.
1339 void Instance::SetCursor(uint32 control_id
, PP_CursorType_Dev cursor_type
) {
1340 UpdateCursor(cursor_type
);
1343 pp::Instance
* Instance::GetInstance() {
1347 void Instance::GetDocumentPassword(
1348 pp::CompletionCallbackWithOutput
<pp::Var
> callback
) {
1349 std::string
message(GetLocalizedString(PP_RESOURCESTRING_PDFGETPASSWORD
));
1350 pp::Var result
= pp::PDF::ModalPromptForPassword(this, message
);
1351 *callback
.output() = result
.pp_var();
1352 callback
.Run(PP_OK
);
1355 void Instance::Alert(const std::string
& message
) {
1356 GetWindowObject().Call("alert", message
);
1359 bool Instance::Confirm(const std::string
& message
) {
1360 pp::Var result
= GetWindowObject().Call("confirm", message
);
1361 return result
.is_bool() ? result
.AsBool() : false;
1364 std::string
Instance::Prompt(const std::string
& question
,
1365 const std::string
& default_answer
) {
1366 pp::Var result
= GetWindowObject().Call("prompt", question
, default_answer
);
1367 return result
.is_string() ? result
.AsString() : std::string();
1370 std::string
Instance::GetURL() {
1374 void Instance::Email(const std::string
& to
,
1375 const std::string
& cc
,
1376 const std::string
& bcc
,
1377 const std::string
& subject
,
1378 const std::string
& body
) {
1379 std::string javascript
=
1380 "var href = 'mailto:" + net::EscapeUrlEncodedData(to
, false) +
1381 "?cc=" + net::EscapeUrlEncodedData(cc
, false) +
1382 "&bcc=" + net::EscapeUrlEncodedData(bcc
, false) +
1383 "&subject=" + net::EscapeUrlEncodedData(subject
, false) +
1384 "&body=" + net::EscapeUrlEncodedData(body
, false) +
1385 "';var temp = window.open(href, '_blank', " +
1386 "'width=1,height=1');if(temp) temp.close();";
1387 ExecuteScript(javascript
);
1390 void Instance::Print() {
1391 if (!printing_enabled_
||
1392 (!engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
) &&
1393 !engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY
))) {
1397 pp::CompletionCallback callback
=
1398 callback_factory_
.NewCallback(&Instance::OnPrint
);
1399 pp::Module::Get()->core()->CallOnMainThread(0, callback
);
1402 void Instance::OnPrint(int32_t) {
1403 pp::PDF::Print(this);
1406 void Instance::SaveAs() {
1407 pp::PDF::SaveAs(this);
1410 void Instance::SubmitForm(const std::string
& url
,
1413 pp::URLRequestInfo
request(this);
1414 request
.SetURL(url
);
1415 request
.SetMethod("POST");
1416 request
.AppendDataToBody(reinterpret_cast<const char*>(data
), length
);
1418 pp::CompletionCallback callback
=
1419 form_factory_
.NewCallback(&Instance::FormDidOpen
);
1420 form_loader_
= CreateURLLoaderInternal();
1421 int rv
= form_loader_
.Open(request
, callback
);
1422 if (rv
!= PP_OK_COMPLETIONPENDING
)
1426 void Instance::FormDidOpen(int32_t result
) {
1427 // TODO: inform the user of success/failure.
1428 if (result
!= PP_OK
) {
1433 std::string
Instance::ShowFileSelectionDialog() {
1434 // Seems like very low priority to implement, since the pdf has no way to get
1435 // the file data anyways. Javascript doesn't let you do this synchronously.
1437 return std::string();
1440 pp::URLLoader
Instance::CreateURLLoader() {
1442 if (!did_call_start_loading_
) {
1443 did_call_start_loading_
= true;
1444 pp::PDF::DidStartLoading(this);
1447 // Disable save and print until the document is fully loaded, since they
1448 // would generate an incomplete document. Need to do this each time we
1449 // call DidStartLoading since that resets the content restrictions.
1450 pp::PDF::SetContentRestriction(this, CONTENT_RESTRICTION_SAVE
|
1451 CONTENT_RESTRICTION_PRINT
);
1454 return CreateURLLoaderInternal();
1457 void Instance::ScheduleCallback(int id
, int delay_in_ms
) {
1458 pp::CompletionCallback callback
=
1459 timer_factory_
.NewCallback(&Instance::OnClientTimerFired
);
1460 pp::Module::Get()->core()->CallOnMainThread(delay_in_ms
, callback
, id
);
1463 void Instance::SearchString(const base::char16
* string
,
1464 const base::char16
* term
,
1465 bool case_sensitive
,
1466 std::vector
<SearchStringResult
>* results
) {
1467 if (!pp::PDF::IsAvailable()) {
1472 PP_PrivateFindResult
* pp_results
;
1474 pp::PDF::SearchString(
1476 reinterpret_cast<const unsigned short*>(string
),
1477 reinterpret_cast<const unsigned short*>(term
),
1482 results
->resize(count
);
1483 for (int i
= 0; i
< count
; ++i
) {
1484 (*results
)[i
].start_index
= pp_results
[i
].start_index
;
1485 (*results
)[i
].length
= pp_results
[i
].length
;
1488 pp::Memory_Dev memory
;
1489 memory
.MemFree(pp_results
);
1492 void Instance::DocumentPaintOccurred() {
1493 if (painted_first_page_
)
1496 painted_first_page_
= true;
1497 UpdateToolbarPosition(false);
1498 toolbar_
->Splash(kToolbarSplashTimeoutMs
);
1500 if (engine_
->GetNumberOfPages() > 1)
1501 show_page_indicator_
= true;
1503 show_page_indicator_
= false;
1505 if (v_scrollbar_
.get() && show_page_indicator_
) {
1506 page_indicator_
.set_current_page(GetPageNumberToDisplay());
1507 page_indicator_
.Splash(kToolbarSplashTimeoutMs
,
1508 kPageIndicatorInitialFadeTimeoutMs
);
1512 void Instance::DocumentLoadComplete(int page_count
) {
1513 // Clear focus state for OSK.
1514 FormTextFieldFocusChange(false);
1516 // Update progress control.
1517 if (progress_bar_
.visible())
1518 progress_bar_
.Fade(false, kProgressFadeTimeoutMs
);
1520 DCHECK(document_load_state_
== LOAD_STATE_LOADING
);
1521 document_load_state_
= LOAD_STATE_COMPLETE
;
1522 UserMetricsRecordAction("PDF.LoadSuccess");
1524 if (did_call_start_loading_
) {
1525 pp::PDF::DidStopLoading(this);
1526 did_call_start_loading_
= false;
1529 if (on_load_callback_
.is_string())
1530 ExecuteScript(on_load_callback_
);
1531 // Note: If we are in print preview mode on_load_callback_ might call
1532 // ScrollTo{X|Y}() and we don't want to scroll again and override it.
1533 // #page=N is not supported in Print Preview.
1534 if (!IsPrintPreview()) {
1535 int initial_page
= GetInitialPage(url_
);
1536 if (initial_page
>= 0)
1537 ScrollToPage(initial_page
);
1542 if (!pp::PDF::IsAvailable())
1545 int content_restrictions
=
1546 CONTENT_RESTRICTION_CUT
| CONTENT_RESTRICTION_PASTE
;
1547 if (!engine_
->HasPermission(PDFEngine::PERMISSION_COPY
))
1548 content_restrictions
|= CONTENT_RESTRICTION_COPY
;
1550 if (!engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
) &&
1551 !engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY
)) {
1552 printing_enabled_
= false;
1553 if (current_tb_info_
== kPDFToolbarButtons
) {
1554 // Remove Print button.
1555 CreateToolbar(kPDFNoPrintToolbarButtons
,
1556 arraysize(kPDFNoPrintToolbarButtons
));
1557 UpdateToolbarPosition(false);
1558 Invalidate(pp::Rect(plugin_size_
));
1562 pp::PDF::SetContentRestriction(this, content_restrictions
);
1564 pp::PDF::HistogramPDFPageCount(this, page_count
);
1567 void Instance::RotateClockwise() {
1568 engine_
->RotateClockwise();
1571 void Instance::RotateCounterclockwise() {
1572 engine_
->RotateCounterclockwise();
1575 void Instance::PreviewDocumentLoadComplete() {
1576 if (preview_document_load_state_
!= LOAD_STATE_LOADING
||
1577 preview_pages_info_
.empty()) {
1581 preview_document_load_state_
= LOAD_STATE_COMPLETE
;
1583 int dest_page_index
= preview_pages_info_
.front().second
;
1584 int src_page_index
=
1585 ExtractPrintPreviewPageIndex(preview_pages_info_
.front().first
);
1586 if (src_page_index
> 0 && dest_page_index
> -1 && preview_engine_
.get())
1587 engine_
->AppendPage(preview_engine_
.get(), dest_page_index
);
1589 preview_pages_info_
.pop();
1590 // |print_preview_page_count_| is not updated yet. Do not load any
1591 // other preview pages till we get this information.
1592 if (print_preview_page_count_
== 0)
1595 if (preview_pages_info_
.size())
1596 LoadAvailablePreviewPage();
1599 void Instance::DocumentLoadFailed() {
1600 DCHECK(document_load_state_
== LOAD_STATE_LOADING
);
1601 UserMetricsRecordAction("PDF.LoadFailure");
1603 // Hide progress control.
1604 progress_bar_
.Fade(false, kProgressFadeTimeoutMs
);
1606 if (did_call_start_loading_
) {
1607 pp::PDF::DidStopLoading(this);
1608 did_call_start_loading_
= false;
1611 document_load_state_
= LOAD_STATE_FAILED
;
1612 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
1615 void Instance::PreviewDocumentLoadFailed() {
1616 UserMetricsRecordAction("PDF.PreviewDocumentLoadFailure");
1617 if (preview_document_load_state_
!= LOAD_STATE_LOADING
||
1618 preview_pages_info_
.empty()) {
1622 preview_document_load_state_
= LOAD_STATE_FAILED
;
1623 preview_pages_info_
.pop();
1625 if (preview_pages_info_
.size())
1626 LoadAvailablePreviewPage();
1629 pp::Instance
* Instance::GetPluginInstance() {
1630 return GetInstance();
1633 void Instance::DocumentHasUnsupportedFeature(const std::string
& feature
) {
1634 std::string
metric("PDF_Unsupported_");
1636 if (!unsupported_features_reported_
.count(metric
)) {
1637 unsupported_features_reported_
.insert(metric
);
1638 UserMetricsRecordAction(metric
);
1641 // Since we use an info bar, only do this for full frame plugins..
1645 if (told_browser_about_unsupported_feature_
)
1647 told_browser_about_unsupported_feature_
= true;
1649 pp::PDF::HasUnsupportedFeature(this);
1652 void Instance::DocumentLoadProgress(uint32 available
, uint32 doc_size
) {
1653 double progress
= 0.0;
1654 if (doc_size
== 0) {
1655 // Document size is unknown. Use heuristics.
1656 // We'll make progress logarithmic from 0 to 100M.
1657 static const double kFactor
= log(100000000.0) / 100.0;
1658 if (available
> 0) {
1659 progress
= log(static_cast<double>(available
)) / kFactor
;
1660 if (progress
> 100.0)
1664 progress
= 100.0 * static_cast<double>(available
) / doc_size
;
1666 progress_bar_
.SetProgress(progress
);
1669 void Instance::FormTextFieldFocusChange(bool in_focus
) {
1670 if (!text_input_
.get())
1673 text_input_
->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_TEXT
);
1675 text_input_
->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_NONE
);
1678 // Called by PDFScriptableObject.
1679 bool Instance::HasScriptableMethod(const pp::Var
& method
, pp::Var
* exception
) {
1680 std::string method_str
= method
.AsString();
1681 return (method_str
== kJSAccessibility
||
1682 method_str
== kJSDocumentLoadComplete
||
1683 method_str
== kJSGetHeight
||
1684 method_str
== kJSGetHorizontalScrollbarThickness
||
1685 method_str
== kJSGetPageLocationNormalized
||
1686 method_str
== kJSGetVerticalScrollbarThickness
||
1687 method_str
== kJSGetWidth
||
1688 method_str
== kJSGetZoomLevel
||
1689 method_str
== kJSGoToPage
||
1690 method_str
== kJSGrayscale
||
1691 method_str
== kJSLoadPreviewPage
||
1692 method_str
== kJSOnLoad
||
1693 method_str
== kJSOnPluginSizeChanged
||
1694 method_str
== kJSOnScroll
||
1695 method_str
== kJSPageXOffset
||
1696 method_str
== kJSPageYOffset
||
1697 method_str
== kJSPrintPreviewPageCount
||
1698 method_str
== kJSReload
||
1699 method_str
== kJSRemovePrintButton
||
1700 method_str
== kJSResetPrintPreviewUrl
||
1701 method_str
== kJSSendKeyEvent
||
1702 method_str
== kJSSetPageNumbers
||
1703 method_str
== kJSSetPageXOffset
||
1704 method_str
== kJSSetPageYOffset
||
1705 method_str
== kJSSetZoomLevel
||
1706 method_str
== kJSZoomFitToHeight
||
1707 method_str
== kJSZoomFitToWidth
||
1708 method_str
== kJSZoomIn
||
1709 method_str
== kJSZoomOut
);
1712 pp::Var
Instance::CallScriptableMethod(const pp::Var
& method
,
1713 const std::vector
<pp::Var
>& args
,
1714 pp::Var
* exception
) {
1715 std::string method_str
= method
.AsString();
1716 if (method_str
== kJSGrayscale
) {
1717 if (args
.size() == 1 && args
[0].is_bool()) {
1718 engine_
->SetGrayscale(args
[0].AsBool());
1720 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
1721 #ifdef ENABLE_THUMBNAILS
1722 if (thumbnails_
.visible())
1723 thumbnails_
.Show(true, true);
1725 return pp::Var(true);
1727 return pp::Var(false);
1729 if (method_str
== kJSOnLoad
) {
1730 if (args
.size() == 1 && args
[0].is_string()) {
1731 on_load_callback_
= args
[0];
1732 return pp::Var(true);
1734 return pp::Var(false);
1736 if (method_str
== kJSOnScroll
) {
1737 if (args
.size() == 1 && args
[0].is_string()) {
1738 on_scroll_callback_
= args
[0];
1739 return pp::Var(true);
1741 return pp::Var(false);
1743 if (method_str
== kJSOnPluginSizeChanged
) {
1744 if (args
.size() == 1 && args
[0].is_string()) {
1745 on_plugin_size_changed_callback_
= args
[0];
1746 return pp::Var(true);
1748 return pp::Var(false);
1750 if (method_str
== kJSReload
) {
1751 document_load_state_
= LOAD_STATE_LOADING
;
1754 preview_engine_
.reset();
1755 print_preview_page_count_
= 0;
1756 engine_
.reset(PDFEngine::Create(this));
1757 engine_
->New(url_
.c_str());
1758 #ifdef ENABLE_THUMBNAILS
1759 thumbnails_
.ResetEngine(engine_
.get());
1763 if (method_str
== kJSResetPrintPreviewUrl
) {
1764 if (args
.size() == 1 && args
[0].is_string()) {
1765 url_
= args
[0].AsString();
1766 preview_pages_info_
= std::queue
<PreviewPageInfo
>();
1767 preview_document_load_state_
= LOAD_STATE_COMPLETE
;
1771 if (method_str
== kJSZoomFitToHeight
) {
1772 SetZoom(ZOOM_FIT_TO_PAGE
, 0);
1775 if (method_str
== kJSZoomFitToWidth
) {
1776 SetZoom(ZOOM_FIT_TO_WIDTH
, 0);
1779 if (method_str
== kJSZoomIn
) {
1780 SetZoom(ZOOM_SCALE
, CalculateZoom(kZoomInButtonId
));
1783 if (method_str
== kJSZoomOut
) {
1784 SetZoom(ZOOM_SCALE
, CalculateZoom(kZoomOutButtonId
));
1787 if (method_str
== kJSSetZoomLevel
) {
1788 if (args
.size() == 1 && args
[0].is_number())
1789 SetZoom(ZOOM_SCALE
, args
[0].AsDouble());
1792 if (method_str
== kJSGetZoomLevel
) {
1793 return pp::Var(zoom_
);
1795 if (method_str
== kJSGetHeight
) {
1796 return pp::Var(plugin_size_
.height());
1798 if (method_str
== kJSGetWidth
) {
1799 return pp::Var(plugin_size_
.width());
1801 if (method_str
== kJSGetHorizontalScrollbarThickness
) {
1803 h_scrollbar_
.get() ? GetScrollbarReservedThickness() : 0);
1805 if (method_str
== kJSGetVerticalScrollbarThickness
) {
1807 v_scrollbar_
.get() ? GetScrollbarReservedThickness() : 0);
1809 if (method_str
== kJSDocumentLoadComplete
) {
1810 return pp::Var((document_load_state_
!= LOAD_STATE_LOADING
));
1812 if (method_str
== kJSPageYOffset
) {
1813 return pp::Var(static_cast<int32_t>(
1814 v_scrollbar_
.get() ? v_scrollbar_
->GetValue() : 0));
1816 if (method_str
== kJSSetPageYOffset
) {
1817 if (args
.size() == 1 && args
[0].is_number() && v_scrollbar_
.get())
1818 ScrollToY(GetScaled(args
[0].AsInt()));
1821 if (method_str
== kJSPageXOffset
) {
1822 return pp::Var(static_cast<int32_t>(
1823 h_scrollbar_
.get() ? h_scrollbar_
->GetValue() : 0));
1825 if (method_str
== kJSSetPageXOffset
) {
1826 if (args
.size() == 1 && args
[0].is_number() && h_scrollbar_
.get())
1827 ScrollToX(GetScaled(args
[0].AsInt()));
1830 if (method_str
== kJSRemovePrintButton
) {
1831 CreateToolbar(kPrintPreviewToolbarButtons
,
1832 arraysize(kPrintPreviewToolbarButtons
));
1833 UpdateToolbarPosition(false);
1834 Invalidate(pp::Rect(plugin_size_
));
1837 if (method_str
== kJSGoToPage
) {
1838 if (args
.size() == 1 && args
[0].is_string()) {
1839 ScrollToPage(atoi(args
[0].AsString().c_str()));
1843 if (method_str
== kJSAccessibility
) {
1844 if (args
.size() == 0) {
1845 base::DictionaryValue node
;
1846 node
.SetInteger(kAccessibleNumberOfPages
, engine_
->GetNumberOfPages());
1847 node
.SetBoolean(kAccessibleLoaded
,
1848 document_load_state_
!= LOAD_STATE_LOADING
);
1849 bool has_permissions
=
1850 engine_
->HasPermission(PDFEngine::PERMISSION_COPY
) ||
1851 engine_
->HasPermission(PDFEngine::PERMISSION_COPY_ACCESSIBLE
);
1852 node
.SetBoolean(kAccessibleCopyable
, has_permissions
);
1854 base::JSONWriter::Write(&node
, &json
);
1855 return pp::Var(json
);
1856 } else if (args
[0].is_number()) {
1857 return pp::Var(engine_
->GetPageAsJSON(args
[0].AsInt()));
1860 if (method_str
== kJSPrintPreviewPageCount
) {
1861 if (args
.size() == 1 && args
[0].is_number())
1862 SetPrintPreviewMode(args
[0].AsInt());
1865 if (method_str
== kJSLoadPreviewPage
) {
1866 if (args
.size() == 2 && args
[0].is_string() && args
[1].is_number())
1867 ProcessPreviewPageInfo(args
[0].AsString(), args
[1].AsInt());
1870 if (method_str
== kJSGetPageLocationNormalized
) {
1871 const size_t kMaxLength
= 30;
1872 char location_info
[kMaxLength
];
1873 int page_idx
= engine_
->GetMostVisiblePage();
1875 return pp::Var(std::string());
1876 pp::Rect rect
= engine_
->GetPageContentsRect(page_idx
);
1877 int v_scrollbar_reserved_thickness
=
1878 v_scrollbar_
.get() ? GetScaled(GetScrollbarReservedThickness()) : 0;
1880 rect
.set_x(rect
.x() + ((plugin_size_
.width() -
1881 v_scrollbar_reserved_thickness
- available_area_
.width()) / 2));
1882 base::snprintf(location_info
,
1884 "%0.4f;%0.4f;%0.4f;%0.4f;",
1885 rect
.x() / static_cast<float>(plugin_size_
.width()),
1886 rect
.y() / static_cast<float>(plugin_size_
.height()),
1887 rect
.width() / static_cast<float>(plugin_size_
.width()),
1888 rect
.height()/ static_cast<float>(plugin_size_
.height()));
1889 return pp::Var(std::string(location_info
));
1891 if (method_str
== kJSSetPageNumbers
) {
1892 if (args
.size() != 1 || !args
[0].is_string())
1894 const int num_pages_signed
= engine_
->GetNumberOfPages();
1895 if (num_pages_signed
<= 0)
1897 scoped_ptr
<base::ListValue
> page_ranges(static_cast<base::ListValue
*>(
1898 base::JSONReader::Read(args
[0].AsString(), false)));
1899 const size_t num_pages
= static_cast<size_t>(num_pages_signed
);
1900 if (!page_ranges
.get() || page_ranges
->GetSize() != num_pages
)
1903 std::vector
<int> print_preview_page_numbers
;
1904 for (size_t index
= 0; index
< num_pages
; ++index
) {
1905 int page_number
= 0; // |page_number| is 1-based.
1906 if (!page_ranges
->GetInteger(index
, &page_number
) || page_number
< 1)
1908 print_preview_page_numbers
.push_back(page_number
);
1910 print_preview_page_numbers_
= print_preview_page_numbers
;
1911 page_indicator_
.set_current_page(GetPageNumberToDisplay());
1914 // This is here to work around https://bugs.webkit.org/show_bug.cgi?id=16735.
1915 // In JS, creating a synthetic keyboard event and dispatching it always
1916 // result in a keycode of 0.
1917 if (method_str
== kJSSendKeyEvent
) {
1918 if (args
.size() == 1 && args
[0].is_number()) {
1919 pp::KeyboardInputEvent
event(
1921 PP_INPUTEVENT_TYPE_KEYDOWN
, // HandleInputEvent only care about this.
1922 0, // timestamp, not used for kbd events.
1924 args
[0].AsInt(), // keycode.
1925 pp::Var()); // no char text needed.
1926 HandleInputEvent(event
);
1932 void Instance::OnGeometryChanged(double old_zoom
, float old_device_scale
) {
1933 bool force_no_horizontal_scrollbar
= false;
1934 int scrollbar_thickness
= GetScrollbarThickness();
1936 if (old_device_scale
!= device_scale_
) {
1937 // Change in device scale forces us to recreate resources
1938 ConfigureNumberImageGenerator();
1940 CreateToolbar(current_tb_info_
, current_tb_info_size_
);
1941 // Load autoscroll anchor image.
1942 autoscroll_anchor_
=
1943 CreateResourceImage(PP_RESOURCEIMAGE_PDF_PAN_SCROLL_ICON
);
1945 ConfigurePageIndicator();
1946 ConfigureProgressBar();
1948 pp::Point scroll_position
= engine_
->GetScrollPosition();
1949 ScalePoint(device_scale_
/ old_device_scale
, &scroll_position
);
1950 engine_
->SetScrollPosition(scroll_position
);
1954 if (zoom_
!= old_zoom
|| device_scale_
!= old_device_scale
)
1955 engine_
->ZoomUpdated(zoom_
* device_scale_
);
1956 if (zoom_
!= old_zoom
)
1959 available_area_
= pp::Rect(plugin_size_
);
1960 if (GetDocumentPixelHeight() > plugin_size_
.height()) {
1961 CreateVerticalScrollbar();
1963 DestroyVerticalScrollbar();
1966 int v_scrollbar_reserved_thickness
=
1967 v_scrollbar_
.get() ? GetScaled(GetScrollbarReservedThickness()) : 0;
1969 if (!force_no_horizontal_scrollbar
&&
1970 GetDocumentPixelWidth() >
1971 (plugin_size_
.width() - v_scrollbar_reserved_thickness
)) {
1972 CreateHorizontalScrollbar();
1974 // Adding the horizontal scrollbar now might cause us to need vertical
1976 if (GetDocumentPixelHeight() >
1977 plugin_size_
.height() - GetScaled(GetScrollbarReservedThickness())) {
1978 CreateVerticalScrollbar();
1982 DestroyHorizontalScrollbar();
1985 #ifdef ENABLE_THUMBNAILS
1986 int thumbnails_pos
= 0, thumbnails_total
= 0;
1988 if (v_scrollbar_
.get()) {
1989 v_scrollbar_
->SetScale(device_scale_
);
1990 available_area_
.set_width(
1991 std::max(0, plugin_size_
.width() - v_scrollbar_reserved_thickness
));
1993 #ifdef ENABLE_THUMBNAILS
1994 int height
= plugin_size_
.height();
1996 int height_dip
= plugin_dip_size_
.height();
1998 #if defined(OS_MACOSX)
1999 // Before Lion, Mac always had the resize at the bottom. After that, it
2001 if ((base::mac::IsOSSnowLeopard() && full_
) ||
2002 (base::mac::IsOSLionOrLater() && h_scrollbar_
.get())) {
2004 if (h_scrollbar_
.get()) {
2005 #endif // defined(OS_MACOSX)
2006 #ifdef ENABLE_THUMBNAILS
2007 height
-= GetScaled(GetScrollbarThickness());
2009 height_dip
-= GetScrollbarThickness();
2011 #ifdef ENABLE_THUMBNAILS
2012 int32 doc_height
= GetDocumentPixelHeight();
2014 int32 doc_height_dip
=
2015 static_cast<int32
>(GetDocumentPixelHeight() / device_scale_
);
2016 #if defined(OS_MACOSX)
2017 // On the Mac we always allow room for the resize button (whose width is
2018 // the same as that of the scrollbar) in full mode. However, if there is no
2019 // no horizontal scrollbar, the end of the scrollbar will scroll past the
2020 // end of the document. This is because the scrollbar assumes that its own
2021 // height (in the case of a vscroll bar) is the same as the height of the
2022 // viewport. Since the viewport is actually larger, we compensate by
2023 // adjusting the document height. Similar logic applies below for the
2024 // horizontal scrollbar.
2025 // For example, if the document size is 1000, and the viewport size is 200,
2026 // then the scrollbar position at the end will be 800. In this case the
2027 // viewport is actally 215 (assuming 15 as the scrollbar width) but the
2028 // scrollbar thinks it is 200. We want the scrollbar position at the end to
2029 // be 785. Making the document size 985 achieves this.
2030 if (full_
&& !h_scrollbar_
.get()) {
2031 #ifdef ENABLE_THUMBNAILS
2032 doc_height
-= GetScaled(GetScrollbarThickness());
2034 doc_height_dip
-= GetScrollbarThickness();
2036 #endif // defined(OS_MACOSX)
2039 position
= v_scrollbar_
->GetValue();
2040 position
= static_cast<int>(position
* zoom_
/ old_zoom
);
2041 valid_v_range_
= doc_height_dip
- height_dip
;
2042 if (position
> valid_v_range_
)
2043 position
= valid_v_range_
;
2045 v_scrollbar_
->SetValue(position
);
2048 loc
.point
.x
= static_cast<int>(available_area_
.right() / device_scale_
);
2049 if (IsOverlayScrollbar())
2050 loc
.point
.x
-= scrollbar_thickness
;
2052 loc
.size
.width
= scrollbar_thickness
;
2053 loc
.size
.height
= height_dip
;
2054 v_scrollbar_
->SetLocation(loc
);
2055 v_scrollbar_
->SetDocumentSize(doc_height_dip
);
2057 #ifdef ENABLE_THUMBNAILS
2058 thumbnails_pos
= position
;
2059 thumbnails_total
= doc_height
- height
;
2063 if (h_scrollbar_
.get()) {
2064 h_scrollbar_
->SetScale(device_scale_
);
2065 available_area_
.set_height(
2066 std::max(0, plugin_size_
.height() -
2067 GetScaled(GetScrollbarReservedThickness())));
2069 int width_dip
= plugin_dip_size_
.width();
2072 #if defined(OS_MACOSX)
2073 if ((base::mac::IsOSSnowLeopard() && full_
) ||
2074 (base::mac::IsOSLionOrLater() && v_scrollbar_
.get())) {
2076 if (v_scrollbar_
.get()) {
2078 width_dip
-= GetScrollbarThickness();
2080 int32 doc_width_dip
=
2081 static_cast<int32
>(GetDocumentPixelWidth() / device_scale_
);
2082 #if defined(OS_MACOSX)
2083 // See comment in the above if (v_scrollbar_.get()) block.
2084 if (full_
&& !v_scrollbar_
.get())
2085 doc_width_dip
-= GetScrollbarThickness();
2086 #endif // defined(OS_MACOSX)
2089 position
= h_scrollbar_
->GetValue();
2090 position
= static_cast<int>(position
* zoom_
/ old_zoom
);
2091 position
= std::min(position
, doc_width_dip
- width_dip
);
2093 h_scrollbar_
->SetValue(position
);
2097 loc
.point
.y
= static_cast<int>(available_area_
.bottom() / device_scale_
);
2098 if (IsOverlayScrollbar())
2099 loc
.point
.y
-= scrollbar_thickness
;
2100 loc
.size
.width
= width_dip
;
2101 loc
.size
.height
= scrollbar_thickness
;
2102 h_scrollbar_
->SetLocation(loc
);
2103 h_scrollbar_
->SetDocumentSize(doc_width_dip
);
2106 int doc_width
= GetDocumentPixelWidth();
2107 if (doc_width
< available_area_
.width()) {
2108 available_area_
.Offset((available_area_
.width() - doc_width
) / 2, 0);
2109 available_area_
.set_width(doc_width
);
2111 int doc_height
= GetDocumentPixelHeight();
2112 if (doc_height
< available_area_
.height()) {
2113 available_area_
.set_height(doc_height
);
2116 // We'll invalidate the entire plugin anyways.
2117 UpdateToolbarPosition(false);
2118 UpdateProgressBarPosition(false);
2119 UpdatePageIndicatorPosition(false);
2121 #ifdef ENABLE_THUMBNAILS
2122 // Update thumbnail control position.
2123 thumbnails_
.SetPosition(thumbnails_pos
, thumbnails_total
, false);
2124 pp::Rect
thumbnails_rc(plugin_size_
.width() - GetScaled(kThumbnailsWidth
), 0,
2125 GetScaled(kThumbnailsWidth
), plugin_size_
.height());
2126 if (v_scrollbar_
.get())
2127 thumbnails_rc
.Offset(-v_scrollbar_reserved_thickness
, 0);
2128 if (h_scrollbar_
.get())
2129 thumbnails_rc
.Inset(0, 0, 0, v_scrollbar_reserved_thickness
);
2130 thumbnails_
.SetRect(thumbnails_rc
, false);
2133 CalculateBackgroundParts();
2134 engine_
->PageOffsetUpdated(available_area_
.point());
2135 engine_
->PluginSizeUpdated(available_area_
.size());
2137 if (!document_size_
.GetArea())
2139 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
2141 // Run the plugin size change callback asynchronously. This function can be
2142 // invoked by a layout change which should not re-enter into JS synchronously.
2143 pp::CompletionCallback callback
=
2144 callback_factory_
.NewCallback(&Instance::RunCallback
,
2145 on_plugin_size_changed_callback_
);
2146 pp::Module::Get()->core()->CallOnMainThread(0, callback
);
2149 void Instance::RunCallback(int32_t, pp::Var callback
) {
2150 if (callback
.is_string())
2151 ExecuteScript(callback
);
2154 void Instance::CreateHorizontalScrollbar() {
2155 if (h_scrollbar_
.get())
2158 h_scrollbar_
.reset(new pp::Scrollbar_Dev(this, false));
2161 void Instance::CreateVerticalScrollbar() {
2162 if (v_scrollbar_
.get())
2165 v_scrollbar_
.reset(new pp::Scrollbar_Dev(this, true));
2168 void Instance::DestroyHorizontalScrollbar() {
2169 if (!h_scrollbar_
.get())
2171 if (h_scrollbar_
->GetValue())
2172 engine_
->ScrolledToXPosition(0);
2173 h_scrollbar_
.reset();
2176 void Instance::DestroyVerticalScrollbar() {
2177 if (!v_scrollbar_
.get())
2179 if (v_scrollbar_
->GetValue())
2180 engine_
->ScrolledToYPosition(0);
2181 v_scrollbar_
.reset();
2182 page_indicator_
.Show(false, true);
2185 int Instance::GetScrollbarThickness() {
2186 if (scrollbar_thickness_
== -1) {
2187 pp::Scrollbar_Dev
temp_scrollbar(this, false);
2188 scrollbar_thickness_
= temp_scrollbar
.GetThickness();
2189 scrollbar_reserved_thickness_
=
2190 temp_scrollbar
.IsOverlay() ? 0 : scrollbar_thickness_
;
2193 return scrollbar_thickness_
;
2196 int Instance::GetScrollbarReservedThickness() {
2197 GetScrollbarThickness();
2198 return scrollbar_reserved_thickness_
;
2201 bool Instance::IsOverlayScrollbar() {
2202 return GetScrollbarReservedThickness() == 0;
2205 void Instance::CreateToolbar(const ToolbarButtonInfo
* tb_info
, size_t size
) {
2206 toolbar_
.reset(new FadingControls());
2211 // Remember the current toolbar information in case we need to recreate the
2213 current_tb_info_
= tb_info
;
2214 current_tb_info_size_
= size
;
2217 pp::Point
origin(kToolbarFadingOffsetLeft
, kToolbarFadingOffsetTop
);
2218 ScalePoint(device_scale_
, &origin
);
2220 std::list
<Button
*> buttons
;
2221 for (size_t i
= 0; i
< size
; i
++) {
2222 Button
* btn
= new Button
;
2223 pp::ImageData normal_face
=
2224 CreateResourceImage(tb_info
[i
].normal
);
2225 btn
->CreateButton(tb_info
[i
].id
,
2231 CreateResourceImage(tb_info
[i
].highlighted
),
2232 CreateResourceImage(tb_info
[i
].pressed
));
2233 buttons
.push_back(btn
);
2235 origin
+= pp::Point(normal_face
.size().width(), 0);
2236 max_height
= std::max(max_height
, normal_face
.size().height());
2239 pp::Rect
rc_toolbar(0, 0,
2240 origin
.x() + GetToolbarRightOffset(),
2241 origin
.y() + max_height
+ GetToolbarBottomOffset());
2242 toolbar_
->CreateFadingControls(
2243 kToolbarId
, rc_toolbar
, false, this, kTransparentAlpha
);
2245 std::list
<Button
*>::iterator iter
;
2246 for (iter
= buttons
.begin(); iter
!= buttons
.end(); ++iter
) {
2247 toolbar_
->AddControl(*iter
);
2251 int Instance::GetToolbarRightOffset() {
2252 int scrollbar_thickness
= GetScrollbarThickness();
2253 return GetScaled(kToolbarFadingOffsetRight
) + 2 * scrollbar_thickness
;
2256 int Instance::GetToolbarBottomOffset() {
2257 int scrollbar_thickness
= GetScrollbarThickness();
2258 return GetScaled(kToolbarFadingOffsetBottom
) + scrollbar_thickness
;
2261 std::vector
<pp::ImageData
> Instance::GetThumbnailResources() {
2262 std::vector
<pp::ImageData
> num_images(10);
2263 num_images
[0] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_0
);
2264 num_images
[1] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_1
);
2265 num_images
[2] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_2
);
2266 num_images
[3] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_3
);
2267 num_images
[4] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_4
);
2268 num_images
[5] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_5
);
2269 num_images
[6] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_6
);
2270 num_images
[7] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_7
);
2271 num_images
[8] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_8
);
2272 num_images
[9] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_9
);
2276 std::vector
<pp::ImageData
> Instance::GetProgressBarResources(
2277 pp::ImageData
* background
) {
2278 std::vector
<pp::ImageData
> result(9);
2279 result
[0] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_0
);
2280 result
[1] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_1
);
2281 result
[2] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_2
);
2282 result
[3] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_3
);
2283 result
[4] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_4
);
2284 result
[5] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_5
);
2285 result
[6] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_6
);
2286 result
[7] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_7
);
2287 result
[8] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_8
);
2288 *background
= CreateResourceImage(
2289 PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_BACKGROUND
);
2293 void Instance::CreatePageIndicator(bool always_visible
) {
2294 page_indicator_
.CreatePageIndicator(kPageIndicatorId
, false, this,
2295 number_image_generator(), always_visible
);
2296 ConfigurePageIndicator();
2299 void Instance::ConfigurePageIndicator() {
2300 pp::ImageData background
=
2301 CreateResourceImage(PP_RESOURCEIMAGE_PDF_PAGE_INDICATOR_BACKGROUND
);
2302 page_indicator_
.Configure(pp::Point(), background
);
2305 void Instance::CreateProgressBar() {
2306 pp::ImageData background
;
2307 std::vector
<pp::ImageData
> images
= GetProgressBarResources(&background
);
2308 std::string text
= GetLocalizedString(PP_RESOURCESTRING_PDFPROGRESSLOADING
);
2309 progress_bar_
.CreateProgressControl(kProgressBarId
, false, this, 0.0,
2310 device_scale_
, images
, background
, text
);
2313 void Instance::ConfigureProgressBar() {
2314 pp::ImageData background
;
2315 std::vector
<pp::ImageData
> images
= GetProgressBarResources(&background
);
2316 progress_bar_
.Reconfigure(background
, images
, device_scale_
);
2319 void Instance::CreateThumbnails() {
2320 thumbnails_
.CreateThumbnailControl(
2321 kThumbnailsId
, pp::Rect(), false, this, engine_
.get(),
2322 number_image_generator());
2325 void Instance::LoadUrl(const std::string
& url
) {
2326 LoadUrlInternal(url
, &embed_loader_
, &Instance::DidOpen
);
2329 void Instance::LoadPreviewUrl(const std::string
& url
) {
2330 LoadUrlInternal(url
, &embed_preview_loader_
, &Instance::DidOpenPreview
);
2333 void Instance::LoadUrlInternal(const std::string
& url
, pp::URLLoader
* loader
,
2334 void (Instance::* method
)(int32_t)) {
2335 pp::URLRequestInfo
request(this);
2336 request
.SetURL(url
);
2337 request
.SetMethod("GET");
2339 *loader
= CreateURLLoaderInternal();
2340 pp::CompletionCallback callback
= loader_factory_
.NewCallback(method
);
2341 int rv
= loader
->Open(request
, callback
);
2342 if (rv
!= PP_OK_COMPLETIONPENDING
)
2346 pp::URLLoader
Instance::CreateURLLoaderInternal() {
2347 pp::URLLoader
loader(this);
2349 const PPB_URLLoaderTrusted
* trusted_interface
=
2350 reinterpret_cast<const PPB_URLLoaderTrusted
*>(
2351 pp::Module::Get()->GetBrowserInterface(
2352 PPB_URLLOADERTRUSTED_INTERFACE
));
2353 if (trusted_interface
)
2354 trusted_interface
->GrantUniversalAccess(loader
.pp_resource());
2358 int Instance::GetInitialPage(const std::string
& url
) {
2359 size_t found_idx
= url
.find('#');
2360 if (found_idx
== std::string::npos
)
2363 const std::string
& ref
= url
.substr(found_idx
+ 1);
2364 std::vector
<std::string
> fragments
;
2365 Tokenize(ref
, kDelimiters
, &fragments
);
2367 // Page number to return, zero-based.
2370 // Handle the case of http://foo.com/bar#NAMEDDEST. This is not explicitly
2371 // mentioned except by example in the Adobe "PDF Open Parameters" document.
2372 if ((fragments
.size() == 1) && (fragments
[0].find('=') == std::string::npos
))
2373 return engine_
->GetNamedDestinationPage(fragments
[0]);
2375 for (size_t i
= 0; i
< fragments
.size(); ++i
) {
2376 std::vector
<std::string
> key_value
;
2377 base::SplitString(fragments
[i
], '=', &key_value
);
2378 if (key_value
.size() != 2)
2380 const std::string
& key
= key_value
[0];
2381 const std::string
& value
= key_value
[1];
2383 if (base::strcasecmp(kPage
, key
.c_str()) == 0) {
2384 // |page_value| is 1-based.
2385 int page_value
= -1;
2386 if (base::StringToInt(value
, &page_value
) && page_value
> 0)
2387 page
= page_value
- 1;
2390 if (base::strcasecmp(kNamedDest
, key
.c_str()) == 0) {
2391 // |page_value| is 0-based.
2392 int page_value
= engine_
->GetNamedDestinationPage(value
);
2393 if (page_value
>= 0)
2401 void Instance::UpdateToolbarPosition(bool invalidate
) {
2402 pp::Rect ctrl_rc
= toolbar_
->GetControlsRect();
2403 int min_toolbar_width
= ctrl_rc
.width() + GetToolbarRightOffset() +
2404 GetScaled(kToolbarFadingOffsetLeft
);
2405 int min_toolbar_height
= ctrl_rc
.width() + GetToolbarBottomOffset() +
2406 GetScaled(kToolbarFadingOffsetBottom
);
2408 // Update toolbar position
2409 if (plugin_size_
.width() < min_toolbar_width
||
2410 plugin_size_
.height() < min_toolbar_height
) {
2411 // Disable toolbar if it does not fit on the screen.
2412 toolbar_
->Show(false, invalidate
);
2415 plugin_size_
.width() - GetToolbarRightOffset() - ctrl_rc
.right(),
2416 plugin_size_
.height() - GetToolbarBottomOffset() - ctrl_rc
.bottom());
2417 toolbar_
->MoveBy(offset
, invalidate
);
2419 int toolbar_width
= std::max(plugin_size_
.width() / 2, min_toolbar_width
);
2420 toolbar_
->ExpandLeft(toolbar_width
- toolbar_
->rect().width());
2421 toolbar_
->Show(painted_first_page_
, invalidate
);
2425 void Instance::UpdateProgressBarPosition(bool invalidate
) {
2426 // TODO(gene): verify we don't overlap with toolbar.
2427 int scrollbar_thickness
= GetScrollbarThickness();
2428 pp::Point
progress_origin(
2429 scrollbar_thickness
+ GetScaled(kProgressOffsetLeft
),
2430 plugin_size_
.height() - progress_bar_
.rect().height() -
2431 scrollbar_thickness
- GetScaled(kProgressOffsetBottom
));
2432 progress_bar_
.MoveTo(progress_origin
, invalidate
);
2435 void Instance::UpdatePageIndicatorPosition(bool invalidate
) {
2436 int32 doc_height
= static_cast<int>(document_size_
.height() * zoom_
);
2438 plugin_size_
.width() - page_indicator_
.rect().width() -
2439 GetScaled(GetScrollbarReservedThickness()),
2440 page_indicator_
.GetYPosition(engine_
->GetVerticalScrollbarYPosition(),
2441 doc_height
, plugin_size_
.height()));
2442 page_indicator_
.MoveTo(origin
, invalidate
);
2445 void Instance::SetZoom(ZoomMode zoom_mode
, double scale
) {
2446 double old_zoom
= zoom_
;
2448 zoom_mode_
= zoom_mode
;
2449 if (zoom_mode_
== ZOOM_SCALE
)
2453 engine_
->ZoomUpdated(zoom_
* device_scale_
);
2454 OnGeometryChanged(old_zoom
, device_scale_
);
2456 // If fit-to-height, snap to the beginning of the most visible page.
2457 if (zoom_mode_
== ZOOM_FIT_TO_PAGE
) {
2458 ScrollToPage(engine_
->GetMostVisiblePage());
2461 // Update sticky buttons to the current zoom style.
2462 Button
* ftp_btn
= static_cast<Button
*>(
2463 toolbar_
->GetControl(kFitToPageButtonId
));
2464 Button
* ftw_btn
= static_cast<Button
*>(
2465 toolbar_
->GetControl(kFitToWidthButtonId
));
2466 switch (zoom_mode_
) {
2467 case ZOOM_FIT_TO_PAGE
:
2468 ftp_btn
->SetPressedState(true);
2469 ftw_btn
->SetPressedState(false);
2471 case ZOOM_FIT_TO_WIDTH
:
2472 ftw_btn
->SetPressedState(true);
2473 ftp_btn
->SetPressedState(false);
2476 ftw_btn
->SetPressedState(false);
2477 ftp_btn
->SetPressedState(false);
2481 void Instance::UpdateZoomScale() {
2482 switch (zoom_mode_
) {
2484 break; // Keep current scale.
2485 case ZOOM_FIT_TO_PAGE
: {
2486 int page_num
= engine_
->GetFirstVisiblePage();
2489 pp::Rect rc
= engine_
->GetPageRect(page_num
);
2492 // Calculate fit to width zoom level.
2493 double ftw_zoom
= static_cast<double>(plugin_dip_size_
.width() -
2494 GetScrollbarReservedThickness()) / document_size_
.width();
2495 // Calculate fit to height zoom level. If document will not fit
2496 // horizontally, adjust zoom level to allow space for horizontal
2499 static_cast<double>(plugin_dip_size_
.height()) / rc
.height();
2500 if (fth_zoom
* document_size_
.width() >
2501 plugin_dip_size_
.width() - GetScrollbarReservedThickness())
2502 fth_zoom
= static_cast<double>(plugin_dip_size_
.height()
2503 - GetScrollbarReservedThickness()) / rc
.height();
2504 zoom_
= std::min(ftw_zoom
, fth_zoom
);
2506 case ZOOM_FIT_TO_WIDTH
:
2508 if (!document_size_
.width())
2510 zoom_
= static_cast<double>(plugin_dip_size_
.width() -
2511 GetScrollbarReservedThickness()) / document_size_
.width();
2512 if (zoom_mode_
== ZOOM_AUTO
&& zoom_
> 1.0)
2516 zoom_
= ClipToRange(zoom_
, kMinZoom
, kMaxZoom
);
2519 double Instance::CalculateZoom(uint32 control_id
) const {
2520 if (control_id
== kZoomInButtonId
) {
2521 for (size_t i
= 0; i
< chrome_page_zoom::kPresetZoomFactorsSize
; ++i
) {
2522 double current_zoom
= chrome_page_zoom::kPresetZoomFactors
[i
];
2523 if (current_zoom
- content::kEpsilon
> zoom_
)
2524 return current_zoom
;
2527 for (size_t i
= chrome_page_zoom::kPresetZoomFactorsSize
; i
> 0; --i
) {
2528 double current_zoom
= chrome_page_zoom::kPresetZoomFactors
[i
- 1];
2529 if (current_zoom
+ content::kEpsilon
< zoom_
)
2530 return current_zoom
;
2536 pp::ImageData
Instance::CreateResourceImage(PP_ResourceImage image_id
) {
2537 pp::ImageData resource_data
;
2538 if (hidpi_enabled_
) {
2540 pp::PDF::GetResourceImageForScale(this, image_id
, device_scale_
);
2543 return resource_data
.data() ? resource_data
2544 : pp::PDF::GetResourceImage(this, image_id
);
2547 std::string
Instance::GetLocalizedString(PP_ResourceString id
) {
2548 pp::Var
rv(pp::PDF::GetLocalizedString(this, id
));
2549 if (!rv
.is_string())
2550 return std::string();
2552 return rv
.AsString();
2555 void Instance::DrawText(const pp::Point
& top_center
, PP_ResourceString id
) {
2556 std::string
str(GetLocalizedString(id
));
2558 pp::FontDescription_Dev description
;
2559 description
.set_family(PP_FONTFAMILY_SANSSERIF
);
2560 description
.set_size(kMessageTextSize
* device_scale_
);
2561 pp::Font_Dev
font(this, description
);
2562 int length
= font
.MeasureSimpleText(str
);
2563 pp::Point
point(top_center
);
2564 point
.set_x(point
.x() - length
/ 2);
2565 DCHECK(!image_data_
.is_null());
2566 font
.DrawSimpleText(&image_data_
, str
, point
, kMessageTextColor
);
2569 void Instance::SetPrintPreviewMode(int page_count
) {
2570 if (!IsPrintPreview() || page_count
<= 0) {
2571 print_preview_page_count_
= 0;
2575 print_preview_page_count_
= page_count
;
2577 engine_
->AppendBlankPages(print_preview_page_count_
);
2578 if (preview_pages_info_
.size() > 0)
2579 LoadAvailablePreviewPage();
2582 bool Instance::IsPrintPreview() {
2583 return IsPrintPreviewUrl(url_
);
2586 int Instance::GetPageNumberToDisplay() {
2587 int page
= engine_
->GetMostVisiblePage();
2588 if (IsPrintPreview() && !print_preview_page_numbers_
.empty()) {
2589 page
= ClipToRange
<int>(page
, 0, print_preview_page_numbers_
.size() - 1);
2590 return print_preview_page_numbers_
[page
];
2595 void Instance::ProcessPreviewPageInfo(const std::string
& url
,
2596 int dst_page_index
) {
2597 if (!IsPrintPreview() || print_preview_page_count_
< 0)
2600 int src_page_index
= ExtractPrintPreviewPageIndex(url
);
2601 if (src_page_index
< 1)
2604 preview_pages_info_
.push(std::make_pair(url
, dst_page_index
));
2605 LoadAvailablePreviewPage();
2608 void Instance::LoadAvailablePreviewPage() {
2609 if (preview_pages_info_
.size() <= 0)
2612 std::string url
= preview_pages_info_
.front().first
;
2613 int dst_page_index
= preview_pages_info_
.front().second
;
2614 int src_page_index
= ExtractPrintPreviewPageIndex(url
);
2615 if (src_page_index
< 1 ||
2616 dst_page_index
>= print_preview_page_count_
||
2617 preview_document_load_state_
== LOAD_STATE_LOADING
) {
2621 preview_document_load_state_
= LOAD_STATE_LOADING
;
2622 LoadPreviewUrl(url
);
2625 void Instance::EnableAutoscroll(const pp::Point
& origin
) {
2629 pp::Size client_size
= plugin_size_
;
2630 if (v_scrollbar_
.get())
2631 client_size
.Enlarge(-GetScrollbarThickness(), 0);
2632 if (h_scrollbar_
.get())
2633 client_size
.Enlarge(0, -GetScrollbarThickness());
2635 // Do not allow autoscroll if client area is too small.
2636 if (autoscroll_anchor_
.size().width() > client_size
.width() ||
2637 autoscroll_anchor_
.size().height() > client_size
.height())
2640 autoscroll_rect_
= pp::Rect(
2641 pp::Point(origin
.x() - autoscroll_anchor_
.size().width() / 2,
2642 origin
.y() - autoscroll_anchor_
.size().height() / 2),
2643 autoscroll_anchor_
.size());
2645 // Make sure autoscroll anchor is in the client area.
2646 if (autoscroll_rect_
.right() > client_size
.width()) {
2647 autoscroll_rect_
.set_x(
2648 client_size
.width() - autoscroll_anchor_
.size().width());
2650 if (autoscroll_rect_
.bottom() > client_size
.height()) {
2651 autoscroll_rect_
.set_y(
2652 client_size
.height() - autoscroll_anchor_
.size().height());
2655 if (autoscroll_rect_
.x() < 0)
2656 autoscroll_rect_
.set_x(0);
2657 if (autoscroll_rect_
.y() < 0)
2658 autoscroll_rect_
.set_y(0);
2660 is_autoscroll_
= true;
2661 Invalidate(kAutoScrollId
, autoscroll_rect_
);
2663 ScheduleTimer(kAutoScrollId
, kAutoScrollTimeoutMs
);
2666 void Instance::DisableAutoscroll() {
2667 if (is_autoscroll_
) {
2668 is_autoscroll_
= false;
2669 Invalidate(kAutoScrollId
, autoscroll_rect_
);
2673 PP_CursorType_Dev
Instance::CalculateAutoscroll(const pp::Point
& mouse_pos
) {
2674 // Scroll only if mouse pointer is outside of the anchor area.
2675 if (autoscroll_rect_
.Contains(mouse_pos
)) {
2678 return PP_CURSORTYPE_MIDDLEPANNING
;
2681 // Relative position to the center of anchor area.
2682 pp::Point rel_pos
= mouse_pos
- autoscroll_rect_
.CenterPoint();
2684 // Calculate angle from the X axis. Angle is in range from -pi to pi.
2685 double angle
= atan2(static_cast<double>(rel_pos
.y()),
2686 static_cast<double>(rel_pos
.x()));
2688 autoscroll_x_
= rel_pos
.x() * kAutoScrollFactor
;
2689 autoscroll_y_
= rel_pos
.y() * kAutoScrollFactor
;
2691 // Angle is from -pi to pi. Screen Y is increasing toward bottom,
2692 // so negative angle represent north direction.
2693 if (angle
< - (M_PI
* 7.0 / 8.0)) {
2695 return PP_CURSORTYPE_WESTPANNING
;
2696 } else if (angle
< - (M_PI
* 5.0 / 8.0)) {
2698 return PP_CURSORTYPE_NORTHWESTPANNING
;
2699 } else if (angle
< - (M_PI
* 3.0 / 8.0)) {
2701 return PP_CURSORTYPE_NORTHPANNING
;
2702 } else if (angle
< - (M_PI
* 1.0 / 8.0)) {
2704 return PP_CURSORTYPE_NORTHEASTPANNING
;
2705 } else if (angle
< M_PI
* 1.0 / 8.0) {
2707 return PP_CURSORTYPE_EASTPANNING
;
2708 } else if (angle
< M_PI
* 3.0 / 8.0) {
2710 return PP_CURSORTYPE_SOUTHEASTPANNING
;
2711 } else if (angle
< M_PI
* 5.0 / 8.0) {
2713 return PP_CURSORTYPE_SOUTHPANNING
;
2714 } else if (angle
< M_PI
* 7.0 / 8.0) {
2716 return PP_CURSORTYPE_SOUTHWESTPANNING
;
2719 // went around the circle, going west again
2720 return PP_CURSORTYPE_WESTPANNING
;
2723 void Instance::ConfigureNumberImageGenerator() {
2724 std::vector
<pp::ImageData
> num_images
= GetThumbnailResources();
2725 pp::ImageData number_background
= CreateResourceImage(
2726 PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_NUM_BACKGROUND
);
2727 number_image_generator_
->Configure(number_background
,
2732 NumberImageGenerator
* Instance::number_image_generator() {
2733 if (!number_image_generator_
.get()) {
2734 number_image_generator_
.reset(new NumberImageGenerator(this));
2735 ConfigureNumberImageGenerator();
2737 return number_image_generator_
.get();
2740 int Instance::GetScaled(int x
) const {
2741 return static_cast<int>(x
* device_scale_
);
2744 void Instance::UserMetricsRecordAction(const std::string
& action
) {
2745 pp::PDF::UserMetricsRecordAction(this, pp::Var(action
));
2748 PDFScriptableObject::PDFScriptableObject(Instance
* instance
)
2749 : instance_(instance
) {
2752 PDFScriptableObject::~PDFScriptableObject() {
2755 bool PDFScriptableObject::HasMethod(const pp::Var
& name
, pp::Var
* exception
) {
2756 return instance_
->HasScriptableMethod(name
, exception
);
2759 pp::Var
PDFScriptableObject::Call(const pp::Var
& method
,
2760 const std::vector
<pp::Var
>& args
,
2761 pp::Var
* exception
) {
2762 return instance_
->CallScriptableMethod(method
, args
, exception
);
2765 } // namespace chrome_pdf