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 print_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();
523 // Engine calculates visible page including delimiter to the page size.
524 // We need to check here if the page itself is completely out of view and
525 // scroll to the next one in that case.
526 if (engine_
->GetPageRect(page
).bottom() * zoom_
<=
527 v_scrollbar_
->GetValue())
529 ScrollToPage(page
+ 1);
530 UpdateCursor(PP_CURSORTYPE_POINTER
);
532 } else if (page_up
) {
533 int page
= engine_
->GetFirstVisiblePage();
534 if (engine_
->GetPageRect(page
).y() * zoom_
>= v_scrollbar_
->GetValue())
537 UpdateCursor(PP_CURSORTYPE_POINTER
);
542 if (v_scrollbar_
.get() && v_scrollbar_
->HandleEvent(event
)) {
543 UpdateCursor(PP_CURSORTYPE_POINTER
);
547 if (h_scrollbar_
.get() && h_scrollbar_
->HandleEvent(event
)) {
548 UpdateCursor(PP_CURSORTYPE_POINTER
);
552 if (timer_pending_
&&
553 (event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEUP
||
554 event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE
)) {
555 timer_factory_
.CancelAll();
556 timer_pending_
= false;
557 } else if (event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE
&&
558 engine_
->IsSelecting()) {
559 bool set_timer
= false;
560 pp::MouseInputEvent
mouse_event(event
);
561 if (v_scrollbar_
.get() &&
562 (mouse_event
.GetPosition().y() <= 0 ||
563 mouse_event
.GetPosition().y() >= (plugin_dip_size_
.height() - 1))) {
564 v_scrollbar_
->ScrollBy(
565 PP_SCROLLBY_LINE
, mouse_event
.GetPosition().y() >= 0 ? 1: -1);
568 if (h_scrollbar_
.get() &&
569 (mouse_event
.GetPosition().x() <= 0 ||
570 mouse_event
.GetPosition().x() >= (plugin_dip_size_
.width() - 1))) {
571 h_scrollbar_
->ScrollBy(PP_SCROLLBY_LINE
,
572 mouse_event
.GetPosition().x() >= 0 ? 1: -1);
577 last_mouse_event_
= pp::MouseInputEvent(event
);
579 pp::CompletionCallback callback
=
580 timer_factory_
.NewCallback(&Instance::OnTimerFired
);
581 pp::Module::Get()->core()->CallOnMainThread(kDragTimerMs
, callback
);
582 timer_pending_
= true;
586 if (event
.GetType() == PP_INPUTEVENT_TYPE_KEYDOWN
&&
587 event
.GetModifiers() & kDefaultKeyModifier
) {
588 pp::KeyboardInputEvent
keyboard_event(event
);
589 switch (keyboard_event
.GetKeyCode()) {
591 engine_
->SelectAll();
596 // Return true for unhandled clicks so the plugin takes focus.
597 return (event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN
);
600 void Instance::DidChangeView(const pp::View
& view
) {
601 pp::Rect
view_rect(view
.GetRect());
602 float device_scale
= 1.0f
;
603 float old_device_scale
= device_scale_
;
605 device_scale
= view
.GetDeviceScale();
606 pp::Size
view_device_size(view_rect
.width() * device_scale
,
607 view_rect
.height() * device_scale
);
608 if (view_device_size
== plugin_size_
&& device_scale
== device_scale_
)
609 return; // We don't care about the position, only the size.
611 image_data_
= pp::ImageData();
612 device_scale_
= device_scale
;
613 plugin_dip_size_
= view_rect
.size();
614 plugin_size_
= view_device_size
;
616 paint_manager_
.SetSize(view_device_size
, device_scale_
);
618 image_data_
= pp::ImageData(this,
619 PP_IMAGEDATAFORMAT_BGRA_PREMUL
,
622 if (image_data_
.is_null()) {
623 DCHECK(plugin_size_
.IsEmpty());
627 // View dimensions changed, disable autoscroll (if it was enabled).
630 OnGeometryChanged(zoom_
, old_device_scale
);
633 pp::Var
Instance::GetInstanceObject() {
634 if (instance_object_
.is_undefined()) {
635 PDFScriptableObject
* object
= new PDFScriptableObject(this);
636 // The pp::Var takes ownership of object here.
637 instance_object_
= pp::VarPrivate(this, object
);
640 return instance_object_
;
643 pp::Var
Instance::GetLinkAtPosition(const pp::Point
& point
) {
644 pp::Point
offset_point(point
);
645 ScalePoint(device_scale_
, &offset_point
);
646 offset_point
.set_x(offset_point
.x() - available_area_
.x());
647 return engine_
->GetLinkAtPosition(offset_point
);
650 pp::Var
Instance::GetSelectedText(bool html
) {
651 if (html
|| !engine_
->HasPermission(PDFEngine::PERMISSION_COPY
))
653 return engine_
->GetSelectedText();
656 void Instance::InvalidateWidget(pp::Widget_Dev widget
,
657 const pp::Rect
& dirty_rect
) {
658 if (v_scrollbar_
.get() && *v_scrollbar_
== widget
) {
659 if (!image_data_
.is_null())
660 v_scrollbar_
->Paint(dirty_rect
.pp_rect(), &image_data_
);
661 } else if (h_scrollbar_
.get() && *h_scrollbar_
== widget
) {
662 if (!image_data_
.is_null())
663 h_scrollbar_
->Paint(dirty_rect
.pp_rect(), &image_data_
);
665 // Possible to hit this condition since sometimes the scrollbar codes posts
666 // a task to do something later, and we could have deleted our reference in
671 pp::Rect dirty_rect_scaled
= dirty_rect
;
672 ScaleRect(device_scale_
, &dirty_rect_scaled
);
673 paint_manager_
.InvalidateRect(dirty_rect_scaled
);
676 void Instance::ScrollbarValueChanged(pp::Scrollbar_Dev scrollbar
,
678 value
= GetScaled(value
);
679 if (v_scrollbar_
.get() && *v_scrollbar_
== scrollbar
) {
680 engine_
->ScrolledToYPosition(value
);
682 v_scrollbar_
->GetLocation(&rc
);
683 int32 doc_height
= GetDocumentPixelHeight();
684 doc_height
-= GetScaled(rc
.height());
685 #ifdef ENABLE_THUMBNAILS
686 if (thumbnails_
.visible()) {
687 thumbnails_
.SetPosition(value
, doc_height
, true);
691 plugin_size_
.width() - page_indicator_
.rect().width() -
692 GetScaled(GetScrollbarReservedThickness()),
693 page_indicator_
.GetYPosition(value
, doc_height
, plugin_size_
.height()));
694 page_indicator_
.MoveTo(origin
, page_indicator_
.visible());
695 } else if (h_scrollbar_
.get() && *h_scrollbar_
== scrollbar
) {
696 engine_
->ScrolledToXPosition(value
);
700 void Instance::ScrollbarOverlayChanged(pp::Scrollbar_Dev scrollbar
,
702 scrollbar_reserved_thickness_
= overlay
? 0 : scrollbar_thickness_
;
703 OnGeometryChanged(zoom_
, device_scale_
);
706 uint32_t Instance::QuerySupportedPrintOutputFormats() {
707 return engine_
->QuerySupportedPrintOutputFormats();
710 int32_t Instance::PrintBegin(const PP_PrintSettings_Dev
& print_settings
) {
711 // For us num_pages is always equal to the number of pages in the PDF
712 // document irrespective of the printable area.
713 int32_t ret
= engine_
->GetNumberOfPages();
717 uint32_t supported_formats
= engine_
->QuerySupportedPrintOutputFormats();
718 if ((print_settings
.format
& supported_formats
) == 0)
721 print_settings_
.is_printing
= true;
722 print_settings_
.pepper_print_settings
= print_settings
;
723 engine_
->PrintBegin();
727 pp::Resource
Instance::PrintPages(
728 const PP_PrintPageNumberRange_Dev
* page_ranges
,
729 uint32_t page_range_count
) {
730 if (!print_settings_
.is_printing
)
731 return pp::Resource();
733 print_settings_
.print_pages_called_
= true;
734 return engine_
->PrintPages(page_ranges
, page_range_count
,
735 print_settings_
.pepper_print_settings
);
738 void Instance::PrintEnd() {
739 if (print_settings_
.print_pages_called_
)
740 UserMetricsRecordAction("PDF.PrintPage");
741 print_settings_
.Clear();
745 bool Instance::IsPrintScalingDisabled() {
746 return !engine_
->GetPrintScaling();
749 bool Instance::StartFind(const std::string
& text
, bool case_sensitive
) {
750 engine_
->StartFind(text
.c_str(), case_sensitive
);
754 void Instance::SelectFindResult(bool forward
) {
755 engine_
->SelectFindResult(forward
);
758 void Instance::StopFind() {
762 void Instance::Zoom(double scale
, bool text_only
) {
763 UserMetricsRecordAction("PDF.ZoomFromBrowser");
764 SetZoom(ZOOM_SCALE
, scale
);
767 void Instance::ZoomChanged(double factor
) {
769 Zoom_Dev::ZoomChanged(factor
);
772 void Instance::OnPaint(const std::vector
<pp::Rect
>& paint_rects
,
773 std::vector
<PaintManager::ReadyRect
>* ready
,
774 std::vector
<pp::Rect
>* pending
) {
775 if (image_data_
.is_null()) {
776 DCHECK(plugin_size_
.IsEmpty());
780 first_paint_
= false;
781 pp::Rect rect
= pp::Rect(pp::Point(), plugin_size_
);
782 FillRect(rect
, kBackgroundColor
);
783 ready
->push_back(PaintManager::ReadyRect(rect
, image_data_
, true));
784 *pending
= paint_rects
;
790 for (size_t i
= 0; i
< paint_rects
.size(); i
++) {
791 // Intersect with plugin area since there could be pending invalidates from
792 // when the plugin area was larger.
794 paint_rects
[i
].Intersect(pp::Rect(pp::Point(), plugin_size_
));
798 pp::Rect pdf_rect
= available_area_
.Intersect(rect
);
799 if (!pdf_rect
.IsEmpty()) {
800 pdf_rect
.Offset(available_area_
.x() * -1, 0);
802 std::vector
<pp::Rect
> pdf_ready
;
803 std::vector
<pp::Rect
> pdf_pending
;
804 engine_
->Paint(pdf_rect
, &image_data_
, &pdf_ready
, &pdf_pending
);
805 for (size_t j
= 0; j
< pdf_ready
.size(); ++j
) {
806 pdf_ready
[j
].Offset(available_area_
.point());
808 PaintManager::ReadyRect(pdf_ready
[j
], image_data_
, false));
810 for (size_t j
= 0; j
< pdf_pending
.size(); ++j
) {
811 pdf_pending
[j
].Offset(available_area_
.point());
812 pending
->push_back(pdf_pending
[j
]);
816 for (size_t j
= 0; j
< background_parts_
.size(); ++j
) {
817 pp::Rect intersection
= background_parts_
[j
].location
.Intersect(rect
);
818 if (!intersection
.IsEmpty()) {
819 FillRect(intersection
, background_parts_
[j
].color
);
821 PaintManager::ReadyRect(intersection
, image_data_
, false));
825 if (document_load_state_
== LOAD_STATE_FAILED
) {
826 pp::Point top_center
;
827 top_center
.set_x(plugin_size_
.width() / 2);
828 top_center
.set_y(plugin_size_
.height() / 2);
829 DrawText(top_center
, PP_RESOURCESTRING_PDFLOAD_FAILED
);
832 #ifdef ENABLE_THUMBNAILS
833 thumbnails_
.Paint(&image_data_
, rect
);
837 engine_
->PostPaint();
839 // Must paint scrollbars after the background parts, in case we have an
840 // overlay scrollbar that's over the background. We also do this in a separate
841 // loop because the scrollbar painting logic uses the signal of whether there
842 // are pending paints or not to figure out if it should draw right away or
844 for (size_t i
= 0; i
< paint_rects
.size(); i
++) {
845 PaintIfWidgetIntersects(h_scrollbar_
.get(), paint_rects
[i
], ready
, pending
);
846 PaintIfWidgetIntersects(v_scrollbar_
.get(), paint_rects
[i
], ready
, pending
);
849 if (progress_bar_
.visible())
850 PaintOverlayControl(&progress_bar_
, &image_data_
, ready
);
852 if (page_indicator_
.visible())
853 PaintOverlayControl(&page_indicator_
, &image_data_
, ready
);
855 if (toolbar_
->current_transparency() != kTransparentAlpha
)
856 PaintOverlayControl(toolbar_
.get(), &image_data_
, ready
);
858 // Paint autoscroll anchor if needed.
859 if (is_autoscroll_
) {
860 size_t limit
= ready
->size();
861 for (size_t i
= 0; i
< limit
; i
++) {
862 pp::Rect anchor_rect
= autoscroll_rect_
.Intersect((*ready
)[i
].rect
);
863 if (!anchor_rect
.IsEmpty()) {
864 pp::Rect draw_rc
= pp::Rect(
865 pp::Point(anchor_rect
.x() - autoscroll_rect_
.x(),
866 anchor_rect
.y() - autoscroll_rect_
.y()),
868 // Paint autoscroll anchor.
869 AlphaBlend(autoscroll_anchor_
, draw_rc
,
870 &image_data_
, anchor_rect
.point(), kOpaqueAlpha
);
876 void Instance::PaintOverlayControl(
878 pp::ImageData
* image_data
,
879 std::vector
<PaintManager::ReadyRect
>* ready
) {
880 // Make sure that we only paint overlay controls over an area that's ready,
881 // i.e. not pending. Otherwise we'll mark the control rect as ready and
882 // it'll overwrite the pdf region.
883 std::list
<pp::Rect
> ctrl_rects
;
884 for (size_t i
= 0; i
< ready
->size(); i
++) {
885 pp::Rect rc
= ctrl
->rect().Intersect((*ready
)[i
].rect
);
887 ctrl_rects
.push_back(rc
);
890 if (!ctrl_rects
.empty()) {
891 ctrl
->PaintMultipleRects(image_data
, ctrl_rects
);
893 std::list
<pp::Rect
>::iterator iter
;
894 for (iter
= ctrl_rects
.begin(); iter
!= ctrl_rects
.end(); ++iter
) {
895 ready
->push_back(PaintManager::ReadyRect(*iter
, *image_data
, false));
900 void Instance::DidOpen(int32_t result
) {
901 if (result
== PP_OK
) {
902 engine_
->HandleDocumentLoad(embed_loader_
);
903 } else if (result
!= PP_ERROR_ABORTED
) { // Can happen in tests.
908 void Instance::DidOpenPreview(int32_t result
) {
909 if (result
== PP_OK
) {
910 preview_engine_
.reset(PDFEngine::Create(new PreviewModeClient(this)));
911 preview_engine_
->HandleDocumentLoad(embed_preview_loader_
);
917 void Instance::PaintIfWidgetIntersects(
918 pp::Widget_Dev
* widget
,
919 const pp::Rect
& rect
,
920 std::vector
<PaintManager::ReadyRect
>* ready
,
921 std::vector
<pp::Rect
>* pending
) {
926 if (!widget
->GetLocation(&location
))
929 ScaleRect(device_scale_
, &location
);
930 location
= location
.Intersect(rect
);
931 if (location
.IsEmpty())
934 if (IsOverlayScrollbar()) {
935 // If we're using overlay scrollbars, and there are pending paints under the
936 // scrollbar, don't update the scrollbar instantly. While it would be nice,
937 // we would need to double buffer the plugin area in order to make this
938 // work. This is because we'd need to always have a copy of what the pdf
939 // under the scrollbar looks like, and additionally we couldn't paint the
940 // pdf under the scrollbar if it's ready until we got the preceding flush.
941 // So in practice, it would make painting slower and introduce extra buffer
942 // copies for the general case.
943 for (size_t i
= 0; i
< pending
->size(); ++i
) {
944 if ((*pending
)[i
].Intersects(location
))
948 // Even if none of the pending paints are under the scrollbar, we never want
949 // to paint it if it's over the pdf if there are other pending paints.
950 // Otherwise different parts of the pdf plugin would display at different
952 if (!pending
->empty() && available_area_
.Intersects(rect
)) {
953 pending
->push_back(location
);
958 pp::Rect location_dip
= location
;
959 ScaleRect(1.0f
/ device_scale_
, &location_dip
);
961 DCHECK(!image_data_
.is_null());
962 widget
->Paint(location_dip
, &image_data_
);
964 ready
->push_back(PaintManager::ReadyRect(location
, image_data_
, true));
967 void Instance::OnTimerFired(int32_t) {
968 HandleInputEvent(last_mouse_event_
);
971 void Instance::OnClientTimerFired(int32_t id
) {
972 engine_
->OnCallback(id
);
975 void Instance::OnControlTimerFired(int32_t,
976 const uint32
& control_id
,
977 const uint32
& timer_id
) {
978 if (control_id
== toolbar_
->id()) {
979 toolbar_
->OnTimerFired(timer_id
);
980 } else if (control_id
== progress_bar_
.id()) {
981 if (timer_id
== delayed_progress_timer_id_
) {
982 if (document_load_state_
== LOAD_STATE_LOADING
&&
983 !progress_bar_
.visible()) {
984 progress_bar_
.Fade(true, kProgressFadeTimeoutMs
);
986 delayed_progress_timer_id_
= 0;
988 progress_bar_
.OnTimerFired(timer_id
);
990 } else if (control_id
== kAutoScrollId
) {
991 if (is_autoscroll_
) {
992 if (autoscroll_x_
!= 0 && h_scrollbar_
.get()) {
993 h_scrollbar_
->ScrollBy(PP_SCROLLBY_PIXEL
, autoscroll_x_
);
995 if (autoscroll_y_
!= 0 && v_scrollbar_
.get()) {
996 v_scrollbar_
->ScrollBy(PP_SCROLLBY_PIXEL
, autoscroll_y_
);
1000 ScheduleTimer(kAutoScrollId
, kAutoScrollTimeoutMs
);
1002 } else if (control_id
== kPageIndicatorId
) {
1003 page_indicator_
.OnTimerFired(timer_id
);
1005 #ifdef ENABLE_THUMBNAILS
1006 else if (control_id
== thumbnails_
.id()) {
1007 thumbnails_
.OnTimerFired(timer_id
);
1012 void Instance::CalculateBackgroundParts() {
1013 background_parts_
.clear();
1014 int v_scrollbar_thickness
=
1015 GetScaled(v_scrollbar_
.get() ? GetScrollbarReservedThickness() : 0);
1016 int h_scrollbar_thickness
=
1017 GetScaled(h_scrollbar_
.get() ? GetScrollbarReservedThickness() : 0);
1018 int width_without_scrollbar
= std::max(
1019 plugin_size_
.width() - v_scrollbar_thickness
, 0);
1020 int height_without_scrollbar
= std::max(
1021 plugin_size_
.height() - h_scrollbar_thickness
, 0);
1022 int left_width
= available_area_
.x();
1023 int right_start
= available_area_
.right();
1024 int right_width
= abs(width_without_scrollbar
- available_area_
.right());
1025 int bottom
= std::min(available_area_
.bottom(), height_without_scrollbar
);
1027 // Add the left, right, and bottom rectangles. Note: we assume only
1028 // horizontal centering.
1029 BackgroundPart part
= {
1030 pp::Rect(0, 0, left_width
, bottom
),
1033 if (!part
.location
.IsEmpty())
1034 background_parts_
.push_back(part
);
1035 part
.location
= pp::Rect(right_start
, 0, right_width
, bottom
);
1036 if (!part
.location
.IsEmpty())
1037 background_parts_
.push_back(part
);
1038 part
.location
= pp::Rect(
1039 0, bottom
, width_without_scrollbar
, height_without_scrollbar
- bottom
);
1040 if (!part
.location
.IsEmpty())
1041 background_parts_
.push_back(part
);
1043 if (h_scrollbar_thickness
1044 #if defined(OS_MACOSX)
1049 v_scrollbar_thickness
) {
1050 part
.color
= 0xFFFFFFFF;
1051 part
.location
= pp::Rect(plugin_size_
.width() - v_scrollbar_thickness
,
1052 plugin_size_
.height() - h_scrollbar_thickness
,
1053 h_scrollbar_thickness
,
1054 v_scrollbar_thickness
);
1055 background_parts_
.push_back(part
);
1059 int Instance::GetDocumentPixelWidth() const {
1060 return static_cast<int>(ceil(document_size_
.width() * zoom_
* device_scale_
));
1063 int Instance::GetDocumentPixelHeight() const {
1064 return static_cast<int>(ceil(document_size_
.height() *
1069 void Instance::FillRect(const pp::Rect
& rect
, uint32 color
) {
1070 DCHECK(!image_data_
.is_null() || rect
.IsEmpty());
1071 uint32
* buffer_start
= static_cast<uint32
*>(image_data_
.data());
1072 int stride
= image_data_
.stride();
1073 uint32
* ptr
= buffer_start
+ rect
.y() * stride
/ 4 + rect
.x();
1074 int height
= rect
.height();
1075 int width
= rect
.width();
1076 for (int y
= 0; y
< height
; ++y
) {
1077 for (int x
= 0; x
< width
; ++x
)
1083 void Instance::DocumentSizeUpdated(const pp::Size
& size
) {
1084 document_size_
= size
;
1086 OnGeometryChanged(zoom_
, device_scale_
);
1089 void Instance::Invalidate(const pp::Rect
& rect
) {
1090 pp::Rect
offset_rect(rect
);
1091 offset_rect
.Offset(available_area_
.point());
1092 paint_manager_
.InvalidateRect(offset_rect
);
1095 void Instance::Scroll(const pp::Point
& point
) {
1096 pp::Rect scroll_area
= available_area_
;
1097 if (IsOverlayScrollbar()) {
1099 if (h_scrollbar_
.get()) {
1100 h_scrollbar_
->GetLocation(&rc
);
1101 ScaleRect(device_scale_
, &rc
);
1102 if (scroll_area
.bottom() > rc
.y()) {
1103 scroll_area
.set_height(rc
.y() - scroll_area
.y());
1104 paint_manager_
.InvalidateRect(rc
);
1107 if (v_scrollbar_
.get()) {
1108 v_scrollbar_
->GetLocation(&rc
);
1109 ScaleRect(device_scale_
, &rc
);
1110 if (scroll_area
.right() > rc
.x()) {
1111 scroll_area
.set_width(rc
.x() - scroll_area
.x());
1112 paint_manager_
.InvalidateRect(rc
);
1116 paint_manager_
.ScrollRect(scroll_area
, point
);
1118 if (toolbar_
->current_transparency() != kTransparentAlpha
)
1119 paint_manager_
.InvalidateRect(toolbar_
->GetControlsRect());
1121 if (progress_bar_
.visible())
1122 paint_manager_
.InvalidateRect(progress_bar_
.rect());
1125 paint_manager_
.InvalidateRect(autoscroll_rect_
);
1127 if (show_page_indicator_
) {
1128 page_indicator_
.set_current_page(GetPageNumberToDisplay());
1129 page_indicator_
.Splash();
1132 if (page_indicator_
.visible())
1133 paint_manager_
.InvalidateRect(page_indicator_
.rect());
1135 if (on_scroll_callback_
.is_string())
1136 ExecuteScript(on_scroll_callback_
);
1139 void Instance::ScrollToX(int position
) {
1140 if (!h_scrollbar_
.get()) {
1144 int position_dip
= static_cast<int>(position
/ device_scale_
);
1145 h_scrollbar_
->SetValue(position_dip
);
1148 void Instance::ScrollToY(int position
) {
1149 if (!v_scrollbar_
.get()) {
1153 int position_dip
= static_cast<int>(position
/ device_scale_
);
1154 v_scrollbar_
->SetValue(ClipToRange(position_dip
, 0, valid_v_range_
));
1157 void Instance::ScrollToPage(int page
) {
1158 if (!v_scrollbar_
.get())
1161 if (engine_
->GetNumberOfPages() == 0)
1164 int index
= ClipToRange(page
, 0, engine_
->GetNumberOfPages() - 1);
1165 pp::Rect rect
= engine_
->GetPageRect(index
);
1166 // If we are trying to scroll pass the last page,
1167 // scroll to the end of the last page.
1168 int position
= index
< page
? rect
.bottom() : rect
.y();
1169 ScrollToY(position
* zoom_
* device_scale_
);
1172 void Instance::NavigateTo(const std::string
& url
, bool open_in_new_tab
) {
1173 std::string
url_copy(url
);
1175 // Empty |url_copy| is ok, and will effectively be a reload.
1176 // Skip the code below so an empty URL does not turn into "http://", which
1177 // will cause GURL to fail a DCHECK.
1178 if (!url_copy
.empty()) {
1179 // If |url_copy| starts with '#', then it's for the same URL with a
1180 // different URL fragment.
1181 if (url_copy
[0] == '#') {
1182 url_copy
= url_
+ url_copy
;
1183 // Changing the href does not actually do anything when navigating in the
1184 // same tab, so do the actual page scroll here. Then fall through so the
1185 // href gets updated.
1186 if (!open_in_new_tab
) {
1187 int page_number
= GetInitialPage(url_copy
);
1188 if (page_number
>= 0)
1189 ScrollToPage(page_number
);
1192 // If there's no scheme, add http.
1193 if (url_copy
.find("://") == std::string::npos
&&
1194 url_copy
.find("mailto:") == std::string::npos
) {
1195 url_copy
= "http://" + url_copy
;
1197 // Make sure |url_copy| starts with a valid scheme.
1198 if (url_copy
.find("http://") != 0 &&
1199 url_copy
.find("https://") != 0 &&
1200 url_copy
.find("ftp://") != 0 &&
1201 url_copy
.find("file://") != 0 &&
1202 url_copy
.find("mailto:") != 0) {
1205 // Make sure |url_copy| is not only a scheme.
1206 if (url_copy
== "http://" ||
1207 url_copy
== "https://" ||
1208 url_copy
== "ftp://" ||
1209 url_copy
== "file://" ||
1210 url_copy
== "mailto:") {
1214 if (open_in_new_tab
) {
1215 GetWindowObject().Call("open", url_copy
);
1217 GetWindowObject().GetProperty("top").GetProperty("location").
1218 SetProperty("href", url_copy
);
1222 void Instance::UpdateCursor(PP_CursorType_Dev cursor
) {
1223 if (cursor
== cursor_
)
1227 const PPB_CursorControl_Dev
* cursor_interface
=
1228 reinterpret_cast<const PPB_CursorControl_Dev
*>(
1229 pp::Module::Get()->GetBrowserInterface(PPB_CURSOR_CONTROL_DEV_INTERFACE
));
1230 if (!cursor_interface
) {
1235 cursor_interface
->SetCursor(
1236 pp_instance(), cursor_
, pp::ImageData().pp_resource(), NULL
);
1239 void Instance::UpdateTickMarks(const std::vector
<pp::Rect
>& tickmarks
) {
1240 if (!v_scrollbar_
.get())
1243 float inverse_scale
= 1.0f
/ device_scale_
;
1244 std::vector
<pp::Rect
> scaled_tickmarks
= tickmarks
;
1245 for (size_t i
= 0; i
< scaled_tickmarks
.size(); i
++) {
1246 ScaleRect(inverse_scale
, &scaled_tickmarks
[i
]);
1249 v_scrollbar_
->SetTickMarks(
1250 scaled_tickmarks
.empty() ? NULL
: &scaled_tickmarks
[0], tickmarks
.size());
1253 void Instance::NotifyNumberOfFindResultsChanged(int total
, bool final_result
) {
1254 NumberOfFindResultsChanged(total
, final_result
);
1257 void Instance::NotifySelectedFindResultChanged(int current_find_index
) {
1258 SelectedFindResultChanged(current_find_index
);
1261 void Instance::OnEvent(uint32 control_id
, uint32 event_id
, void* data
) {
1262 if (event_id
== Button::EVENT_ID_BUTTON_CLICKED
||
1263 event_id
== Button::EVENT_ID_BUTTON_STATE_CHANGED
) {
1264 switch (control_id
) {
1265 case kFitToPageButtonId
:
1266 UserMetricsRecordAction("PDF.FitToPageButton");
1267 SetZoom(ZOOM_FIT_TO_PAGE
, 0);
1270 case kFitToWidthButtonId
:
1271 UserMetricsRecordAction("PDF.FitToWidthButton");
1272 SetZoom(ZOOM_FIT_TO_WIDTH
, 0);
1275 case kZoomOutButtonId
:
1276 case kZoomInButtonId
:
1277 UserMetricsRecordAction(control_id
== kZoomOutButtonId
?
1278 "PDF.ZoomOutButton" : "PDF.ZoomInButton");
1279 SetZoom(ZOOM_SCALE
, CalculateZoom(control_id
));
1283 UserMetricsRecordAction("PDF.SaveButton");
1286 case kPrintButtonId
:
1287 UserMetricsRecordAction("PDF.PrintButton");
1292 if (control_id
== kThumbnailsId
&&
1293 event_id
== ThumbnailControl::EVENT_ID_THUMBNAIL_SELECTED
) {
1294 int page
= *static_cast<int*>(data
);
1295 pp::Rect
page_rc(engine_
->GetPageRect(page
));
1296 ScrollToY(static_cast<int>(page_rc
.y() * zoom_
* device_scale_
));
1300 void Instance::Invalidate(uint32 control_id
, const pp::Rect
& rc
) {
1301 paint_manager_
.InvalidateRect(rc
);
1304 uint32
Instance::ScheduleTimer(uint32 control_id
, uint32 timeout_ms
) {
1305 current_timer_id_
++;
1306 pp::CompletionCallback callback
=
1307 timer_factory_
.NewCallback(&Instance::OnControlTimerFired
,
1310 pp::Module::Get()->core()->CallOnMainThread(timeout_ms
, callback
);
1311 return current_timer_id_
;
1314 void Instance::SetEventCapture(uint32 control_id
, bool set_capture
) {
1315 // TODO(gene): set event capture here.
1318 void Instance::SetCursor(uint32 control_id
, PP_CursorType_Dev cursor_type
) {
1319 UpdateCursor(cursor_type
);
1322 pp::Instance
* Instance::GetInstance() {
1326 void Instance::GetDocumentPassword(
1327 pp::CompletionCallbackWithOutput
<pp::Var
> callback
) {
1328 std::string
message(GetLocalizedString(PP_RESOURCESTRING_PDFGETPASSWORD
));
1329 pp::Var result
= pp::PDF::ModalPromptForPassword(this, message
);
1330 *callback
.output() = result
.pp_var();
1331 callback
.Run(PP_OK
);
1334 void Instance::Alert(const std::string
& message
) {
1335 GetWindowObject().Call("alert", message
);
1338 bool Instance::Confirm(const std::string
& message
) {
1339 pp::Var result
= GetWindowObject().Call("confirm", message
);
1340 return result
.is_bool() ? result
.AsBool() : false;
1343 std::string
Instance::Prompt(const std::string
& question
,
1344 const std::string
& default_answer
) {
1345 pp::Var result
= GetWindowObject().Call("prompt", question
, default_answer
);
1346 return result
.is_string() ? result
.AsString() : std::string();
1349 std::string
Instance::GetURL() {
1353 void Instance::Email(const std::string
& to
,
1354 const std::string
& cc
,
1355 const std::string
& bcc
,
1356 const std::string
& subject
,
1357 const std::string
& body
) {
1358 std::string javascript
=
1359 "var href = 'mailto:" + net::EscapeUrlEncodedData(to
, false) +
1360 "?cc=" + net::EscapeUrlEncodedData(cc
, false) +
1361 "&bcc=" + net::EscapeUrlEncodedData(bcc
, false) +
1362 "&subject=" + net::EscapeUrlEncodedData(subject
, false) +
1363 "&body=" + net::EscapeUrlEncodedData(body
, false) +
1364 "';var temp = window.open(href, '_blank', " +
1365 "'width=1,height=1');if(temp) temp.close();";
1366 ExecuteScript(javascript
);
1369 void Instance::Print() {
1370 if (!printing_enabled_
||
1371 (!engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
) &&
1372 !engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY
))) {
1376 pp::CompletionCallback callback
=
1377 print_callback_factory_
.NewCallback(&Instance::OnPrint
);
1378 pp::Module::Get()->core()->CallOnMainThread(0, callback
);
1381 void Instance::OnPrint(int32_t) {
1382 pp::PDF::Print(this);
1385 void Instance::SaveAs() {
1386 pp::PDF::SaveAs(this);
1389 void Instance::SubmitForm(const std::string
& url
,
1392 pp::URLRequestInfo
request(this);
1393 request
.SetURL(url
);
1394 request
.SetMethod("POST");
1395 request
.AppendDataToBody(reinterpret_cast<const char*>(data
), length
);
1397 pp::CompletionCallback callback
=
1398 form_factory_
.NewCallback(&Instance::FormDidOpen
);
1399 form_loader_
= CreateURLLoaderInternal();
1400 int rv
= form_loader_
.Open(request
, callback
);
1401 if (rv
!= PP_OK_COMPLETIONPENDING
)
1405 void Instance::FormDidOpen(int32_t result
) {
1406 // TODO: inform the user of success/failure.
1407 if (result
!= PP_OK
) {
1412 std::string
Instance::ShowFileSelectionDialog() {
1413 // Seems like very low priority to implement, since the pdf has no way to get
1414 // the file data anyways. Javascript doesn't let you do this synchronously.
1416 return std::string();
1419 pp::URLLoader
Instance::CreateURLLoader() {
1421 if (!did_call_start_loading_
) {
1422 did_call_start_loading_
= true;
1423 pp::PDF::DidStartLoading(this);
1426 // Disable save and print until the document is fully loaded, since they
1427 // would generate an incomplete document. Need to do this each time we
1428 // call DidStartLoading since that resets the content restrictions.
1429 pp::PDF::SetContentRestriction(this, CONTENT_RESTRICTION_SAVE
|
1430 CONTENT_RESTRICTION_PRINT
);
1433 return CreateURLLoaderInternal();
1436 void Instance::ScheduleCallback(int id
, int delay_in_ms
) {
1437 pp::CompletionCallback callback
=
1438 timer_factory_
.NewCallback(&Instance::OnClientTimerFired
);
1439 pp::Module::Get()->core()->CallOnMainThread(delay_in_ms
, callback
, id
);
1442 void Instance::SearchString(const base::char16
* string
,
1443 const base::char16
* term
,
1444 bool case_sensitive
,
1445 std::vector
<SearchStringResult
>* results
) {
1446 if (!pp::PDF::IsAvailable()) {
1451 PP_PrivateFindResult
* pp_results
;
1453 pp::PDF::SearchString(
1455 reinterpret_cast<const unsigned short*>(string
),
1456 reinterpret_cast<const unsigned short*>(term
),
1461 results
->resize(count
);
1462 for (int i
= 0; i
< count
; ++i
) {
1463 (*results
)[i
].start_index
= pp_results
[i
].start_index
;
1464 (*results
)[i
].length
= pp_results
[i
].length
;
1467 pp::Memory_Dev memory
;
1468 memory
.MemFree(pp_results
);
1471 void Instance::DocumentPaintOccurred() {
1472 if (painted_first_page_
)
1475 painted_first_page_
= true;
1476 UpdateToolbarPosition(false);
1477 toolbar_
->Splash(kToolbarSplashTimeoutMs
);
1479 if (engine_
->GetNumberOfPages() > 1)
1480 show_page_indicator_
= true;
1482 show_page_indicator_
= false;
1484 if (v_scrollbar_
.get() && show_page_indicator_
) {
1485 page_indicator_
.set_current_page(GetPageNumberToDisplay());
1486 page_indicator_
.Splash(kToolbarSplashTimeoutMs
,
1487 kPageIndicatorInitialFadeTimeoutMs
);
1491 void Instance::DocumentLoadComplete(int page_count
) {
1492 // Clear focus state for OSK.
1493 FormTextFieldFocusChange(false);
1495 // Update progress control.
1496 if (progress_bar_
.visible())
1497 progress_bar_
.Fade(false, kProgressFadeTimeoutMs
);
1499 DCHECK(document_load_state_
== LOAD_STATE_LOADING
);
1500 document_load_state_
= LOAD_STATE_COMPLETE
;
1501 UserMetricsRecordAction("PDF.LoadSuccess");
1502 if (on_load_callback_
.is_string())
1503 ExecuteScript(on_load_callback_
);
1504 // Note: If we are in print preview mode on_load_callback_ might call
1505 // ScrollTo{X|Y}() and we don't want to scroll again and override it.
1506 // #page=N is not supported in Print Preview.
1507 if (!IsPrintPreview()) {
1508 int initial_page
= GetInitialPage(url_
);
1509 if (initial_page
>= 0)
1510 ScrollToPage(initial_page
);
1515 if (!pp::PDF::IsAvailable())
1518 if (did_call_start_loading_
) {
1519 pp::PDF::DidStopLoading(this);
1520 did_call_start_loading_
= false;
1523 int content_restrictions
=
1524 CONTENT_RESTRICTION_CUT
| CONTENT_RESTRICTION_PASTE
;
1525 if (!engine_
->HasPermission(PDFEngine::PERMISSION_COPY
))
1526 content_restrictions
|= CONTENT_RESTRICTION_COPY
;
1528 if (!engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
) &&
1529 !engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY
)) {
1530 printing_enabled_
= false;
1531 if (current_tb_info_
== kPDFToolbarButtons
) {
1532 // Remove Print button.
1533 CreateToolbar(kPDFNoPrintToolbarButtons
,
1534 arraysize(kPDFNoPrintToolbarButtons
));
1535 UpdateToolbarPosition(false);
1536 Invalidate(pp::Rect(plugin_size_
));
1540 pp::PDF::SetContentRestriction(this, content_restrictions
);
1542 pp::PDF::HistogramPDFPageCount(this, page_count
);
1545 void Instance::RotateClockwise() {
1546 engine_
->RotateClockwise();
1549 void Instance::RotateCounterclockwise() {
1550 engine_
->RotateCounterclockwise();
1553 void Instance::PreviewDocumentLoadComplete() {
1554 if (preview_document_load_state_
!= LOAD_STATE_LOADING
||
1555 preview_pages_info_
.empty()) {
1559 preview_document_load_state_
= LOAD_STATE_COMPLETE
;
1561 int dest_page_index
= preview_pages_info_
.front().second
;
1562 int src_page_index
=
1563 ExtractPrintPreviewPageIndex(preview_pages_info_
.front().first
);
1564 if (src_page_index
> 0 && dest_page_index
> -1 && preview_engine_
.get())
1565 engine_
->AppendPage(preview_engine_
.get(), dest_page_index
);
1567 preview_pages_info_
.pop();
1568 // |print_preview_page_count_| is not updated yet. Do not load any
1569 // other preview pages till we get this information.
1570 if (print_preview_page_count_
== 0)
1573 if (preview_pages_info_
.size())
1574 LoadAvailablePreviewPage();
1577 void Instance::DocumentLoadFailed() {
1578 DCHECK(document_load_state_
== LOAD_STATE_LOADING
);
1579 UserMetricsRecordAction("PDF.LoadFailure");
1581 // Hide progress control.
1582 progress_bar_
.Fade(false, kProgressFadeTimeoutMs
);
1584 if (did_call_start_loading_
) {
1585 pp::PDF::DidStopLoading(this);
1586 did_call_start_loading_
= false;
1589 document_load_state_
= LOAD_STATE_FAILED
;
1590 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
1593 void Instance::PreviewDocumentLoadFailed() {
1594 UserMetricsRecordAction("PDF.PreviewDocumentLoadFailure");
1595 if (preview_document_load_state_
!= LOAD_STATE_LOADING
||
1596 preview_pages_info_
.empty()) {
1600 preview_document_load_state_
= LOAD_STATE_FAILED
;
1601 preview_pages_info_
.pop();
1603 if (preview_pages_info_
.size())
1604 LoadAvailablePreviewPage();
1607 pp::Instance
* Instance::GetPluginInstance() {
1608 return GetInstance();
1611 void Instance::DocumentHasUnsupportedFeature(const std::string
& feature
) {
1612 std::string
metric("PDF_Unsupported_");
1614 if (!unsupported_features_reported_
.count(metric
)) {
1615 unsupported_features_reported_
.insert(metric
);
1616 UserMetricsRecordAction(metric
);
1619 // Since we use an info bar, only do this for full frame plugins..
1623 if (told_browser_about_unsupported_feature_
)
1625 told_browser_about_unsupported_feature_
= true;
1627 pp::PDF::HasUnsupportedFeature(this);
1630 void Instance::DocumentLoadProgress(uint32 available
, uint32 doc_size
) {
1631 double progress
= 0.0;
1632 if (doc_size
== 0) {
1633 // Document size is unknown. Use heuristics.
1634 // We'll make progress logarithmic from 0 to 100M.
1635 static const double kFactor
= log(100000000.0) / 100.0;
1636 if (available
> 0) {
1637 progress
= log(static_cast<double>(available
)) / kFactor
;
1638 if (progress
> 100.0)
1642 progress
= 100.0 * static_cast<double>(available
) / doc_size
;
1644 progress_bar_
.SetProgress(progress
);
1647 void Instance::FormTextFieldFocusChange(bool in_focus
) {
1648 if (!text_input_
.get())
1651 text_input_
->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_TEXT
);
1653 text_input_
->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_NONE
);
1656 // Called by PDFScriptableObject.
1657 bool Instance::HasScriptableMethod(const pp::Var
& method
, pp::Var
* exception
) {
1658 std::string method_str
= method
.AsString();
1659 return (method_str
== kJSAccessibility
||
1660 method_str
== kJSDocumentLoadComplete
||
1661 method_str
== kJSGetHeight
||
1662 method_str
== kJSGetHorizontalScrollbarThickness
||
1663 method_str
== kJSGetPageLocationNormalized
||
1664 method_str
== kJSGetVerticalScrollbarThickness
||
1665 method_str
== kJSGetWidth
||
1666 method_str
== kJSGetZoomLevel
||
1667 method_str
== kJSGoToPage
||
1668 method_str
== kJSGrayscale
||
1669 method_str
== kJSLoadPreviewPage
||
1670 method_str
== kJSOnLoad
||
1671 method_str
== kJSOnPluginSizeChanged
||
1672 method_str
== kJSOnScroll
||
1673 method_str
== kJSPageXOffset
||
1674 method_str
== kJSPageYOffset
||
1675 method_str
== kJSPrintPreviewPageCount
||
1676 method_str
== kJSReload
||
1677 method_str
== kJSRemovePrintButton
||
1678 method_str
== kJSResetPrintPreviewUrl
||
1679 method_str
== kJSSendKeyEvent
||
1680 method_str
== kJSSetPageNumbers
||
1681 method_str
== kJSSetPageXOffset
||
1682 method_str
== kJSSetPageYOffset
||
1683 method_str
== kJSSetZoomLevel
||
1684 method_str
== kJSZoomFitToHeight
||
1685 method_str
== kJSZoomFitToWidth
||
1686 method_str
== kJSZoomIn
||
1687 method_str
== kJSZoomOut
);
1690 pp::Var
Instance::CallScriptableMethod(const pp::Var
& method
,
1691 const std::vector
<pp::Var
>& args
,
1692 pp::Var
* exception
) {
1693 std::string method_str
= method
.AsString();
1694 if (method_str
== kJSGrayscale
) {
1695 if (args
.size() == 1 && args
[0].is_bool()) {
1696 engine_
->SetGrayscale(args
[0].AsBool());
1698 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
1699 #ifdef ENABLE_THUMBNAILS
1700 if (thumbnails_
.visible())
1701 thumbnails_
.Show(true, true);
1703 return pp::Var(true);
1705 return pp::Var(false);
1707 if (method_str
== kJSOnLoad
) {
1708 if (args
.size() == 1 && args
[0].is_string()) {
1709 on_load_callback_
= args
[0];
1710 return pp::Var(true);
1712 return pp::Var(false);
1714 if (method_str
== kJSOnScroll
) {
1715 if (args
.size() == 1 && args
[0].is_string()) {
1716 on_scroll_callback_
= args
[0];
1717 return pp::Var(true);
1719 return pp::Var(false);
1721 if (method_str
== kJSOnPluginSizeChanged
) {
1722 if (args
.size() == 1 && args
[0].is_string()) {
1723 on_plugin_size_changed_callback_
= args
[0];
1724 return pp::Var(true);
1726 return pp::Var(false);
1728 if (method_str
== kJSReload
) {
1729 document_load_state_
= LOAD_STATE_LOADING
;
1732 preview_engine_
.reset();
1733 print_preview_page_count_
= 0;
1734 engine_
.reset(PDFEngine::Create(this));
1735 engine_
->New(url_
.c_str());
1736 #ifdef ENABLE_THUMBNAILS
1737 thumbnails_
.ResetEngine(engine_
.get());
1741 if (method_str
== kJSResetPrintPreviewUrl
) {
1742 if (args
.size() == 1 && args
[0].is_string()) {
1743 url_
= args
[0].AsString();
1744 preview_pages_info_
= std::queue
<PreviewPageInfo
>();
1745 preview_document_load_state_
= LOAD_STATE_COMPLETE
;
1749 if (method_str
== kJSZoomFitToHeight
) {
1750 SetZoom(ZOOM_FIT_TO_PAGE
, 0);
1753 if (method_str
== kJSZoomFitToWidth
) {
1754 SetZoom(ZOOM_FIT_TO_WIDTH
, 0);
1757 if (method_str
== kJSZoomIn
) {
1758 SetZoom(ZOOM_SCALE
, CalculateZoom(kZoomInButtonId
));
1761 if (method_str
== kJSZoomOut
) {
1762 SetZoom(ZOOM_SCALE
, CalculateZoom(kZoomOutButtonId
));
1765 if (method_str
== kJSSetZoomLevel
) {
1766 if (args
.size() == 1 && args
[0].is_double())
1767 SetZoom(ZOOM_SCALE
, args
[0].AsDouble());
1770 if (method_str
== kJSGetZoomLevel
) {
1771 return pp::Var(zoom_
);
1773 if (method_str
== kJSGetHeight
) {
1774 return pp::Var(plugin_size_
.height());
1776 if (method_str
== kJSGetWidth
) {
1777 return pp::Var(plugin_size_
.width());
1779 if (method_str
== kJSGetHorizontalScrollbarThickness
) {
1781 h_scrollbar_
.get() ? GetScrollbarReservedThickness() : 0);
1783 if (method_str
== kJSGetVerticalScrollbarThickness
) {
1785 v_scrollbar_
.get() ? GetScrollbarReservedThickness() : 0);
1787 if (method_str
== kJSDocumentLoadComplete
) {
1788 return pp::Var((document_load_state_
!= LOAD_STATE_LOADING
));
1790 if (method_str
== kJSPageYOffset
) {
1791 return pp::Var(static_cast<int32_t>(
1792 v_scrollbar_
.get() ? v_scrollbar_
->GetValue() : 0));
1794 if (method_str
== kJSSetPageYOffset
) {
1795 if (args
.size() == 1 && args
[0].is_number() && v_scrollbar_
.get())
1796 ScrollToY(GetScaled(args
[0].AsInt()));
1799 if (method_str
== kJSPageXOffset
) {
1800 return pp::Var(static_cast<int32_t>(
1801 h_scrollbar_
.get() ? h_scrollbar_
->GetValue() : 0));
1803 if (method_str
== kJSSetPageXOffset
) {
1804 if (args
.size() == 1 && args
[0].is_number() && h_scrollbar_
.get())
1805 ScrollToX(GetScaled(args
[0].AsInt()));
1808 if (method_str
== kJSRemovePrintButton
) {
1809 CreateToolbar(kPrintPreviewToolbarButtons
,
1810 arraysize(kPrintPreviewToolbarButtons
));
1811 UpdateToolbarPosition(false);
1812 Invalidate(pp::Rect(plugin_size_
));
1815 if (method_str
== kJSGoToPage
) {
1816 if (args
.size() == 1 && args
[0].is_string()) {
1817 ScrollToPage(atoi(args
[0].AsString().c_str()));
1821 if (method_str
== kJSAccessibility
) {
1822 if (args
.size() == 0) {
1823 base::DictionaryValue node
;
1824 node
.SetInteger(kAccessibleNumberOfPages
, engine_
->GetNumberOfPages());
1825 node
.SetBoolean(kAccessibleLoaded
,
1826 document_load_state_
!= LOAD_STATE_LOADING
);
1827 bool has_permissions
=
1828 engine_
->HasPermission(PDFEngine::PERMISSION_COPY
) ||
1829 engine_
->HasPermission(PDFEngine::PERMISSION_COPY_ACCESSIBLE
);
1830 node
.SetBoolean(kAccessibleCopyable
, has_permissions
);
1832 base::JSONWriter::Write(&node
, &json
);
1833 return pp::Var(json
);
1834 } else if (args
[0].is_number()) {
1835 return pp::Var(engine_
->GetPageAsJSON(args
[0].AsInt()));
1838 if (method_str
== kJSPrintPreviewPageCount
) {
1839 if (args
.size() == 1 && args
[0].is_number())
1840 SetPrintPreviewMode(args
[0].AsInt());
1843 if (method_str
== kJSLoadPreviewPage
) {
1844 if (args
.size() == 2 && args
[0].is_string() && args
[1].is_number())
1845 ProcessPreviewPageInfo(args
[0].AsString(), args
[1].AsInt());
1848 if (method_str
== kJSGetPageLocationNormalized
) {
1849 const size_t kMaxLength
= 30;
1850 char location_info
[kMaxLength
];
1851 int page_idx
= engine_
->GetMostVisiblePage();
1853 return pp::Var(std::string());
1854 pp::Rect rect
= engine_
->GetPageContentsRect(page_idx
);
1855 int v_scrollbar_reserved_thickness
=
1856 v_scrollbar_
.get() ? GetScaled(GetScrollbarReservedThickness()) : 0;
1858 rect
.set_x(rect
.x() + ((plugin_size_
.width() -
1859 v_scrollbar_reserved_thickness
- available_area_
.width()) / 2));
1860 base::snprintf(location_info
,
1862 "%0.4f;%0.4f;%0.4f;%0.4f;",
1863 rect
.x() / static_cast<float>(plugin_size_
.width()),
1864 rect
.y() / static_cast<float>(plugin_size_
.height()),
1865 rect
.width() / static_cast<float>(plugin_size_
.width()),
1866 rect
.height()/ static_cast<float>(plugin_size_
.height()));
1867 return pp::Var(std::string(location_info
));
1869 if (method_str
== kJSSetPageNumbers
) {
1870 if (args
.size() != 1 || !args
[0].is_string())
1872 const int num_pages_signed
= engine_
->GetNumberOfPages();
1873 if (num_pages_signed
<= 0)
1875 scoped_ptr
<base::ListValue
> page_ranges(static_cast<base::ListValue
*>(
1876 base::JSONReader::Read(args
[0].AsString(), false)));
1877 const size_t num_pages
= static_cast<size_t>(num_pages_signed
);
1878 if (!page_ranges
.get() || page_ranges
->GetSize() != num_pages
)
1881 std::vector
<int> print_preview_page_numbers
;
1882 for (size_t index
= 0; index
< num_pages
; ++index
) {
1883 int page_number
= 0; // |page_number| is 1-based.
1884 if (!page_ranges
->GetInteger(index
, &page_number
) || page_number
< 1)
1886 print_preview_page_numbers
.push_back(page_number
);
1888 print_preview_page_numbers_
= print_preview_page_numbers
;
1889 page_indicator_
.set_current_page(GetPageNumberToDisplay());
1892 // This is here to work around https://bugs.webkit.org/show_bug.cgi?id=16735.
1893 // In JS, creating a synthetic keyboard event and dispatching it always
1894 // result in a keycode of 0.
1895 if (method_str
== kJSSendKeyEvent
) {
1896 if (args
.size() == 1 && args
[0].is_number()) {
1897 pp::KeyboardInputEvent
event(
1899 PP_INPUTEVENT_TYPE_KEYDOWN
, // HandleInputEvent only care about this.
1900 0, // timestamp, not used for kbd events.
1902 args
[0].AsInt(), // keycode.
1903 pp::Var()); // no char text needed.
1904 HandleInputEvent(event
);
1910 void Instance::OnGeometryChanged(double old_zoom
, float old_device_scale
) {
1911 bool force_no_horizontal_scrollbar
= false;
1912 int scrollbar_thickness
= GetScrollbarThickness();
1914 if (old_device_scale
!= device_scale_
) {
1915 // Change in device scale forces us to recreate resources
1916 ConfigureNumberImageGenerator();
1918 CreateToolbar(current_tb_info_
, current_tb_info_size_
);
1919 // Load autoscroll anchor image.
1920 autoscroll_anchor_
=
1921 CreateResourceImage(PP_RESOURCEIMAGE_PDF_PAN_SCROLL_ICON
);
1923 ConfigurePageIndicator();
1924 ConfigureProgressBar();
1926 pp::Point scroll_position
= engine_
->GetScrollPosition();
1927 ScalePoint(device_scale_
/ old_device_scale
, &scroll_position
);
1928 engine_
->SetScrollPosition(scroll_position
);
1932 if (zoom_
!= old_zoom
|| device_scale_
!= old_device_scale
)
1933 engine_
->ZoomUpdated(zoom_
* device_scale_
);
1934 if (zoom_
!= old_zoom
)
1937 available_area_
= pp::Rect(plugin_size_
);
1938 if (GetDocumentPixelHeight() > plugin_size_
.height()) {
1939 CreateVerticalScrollbar();
1941 DestroyVerticalScrollbar();
1944 int v_scrollbar_reserved_thickness
=
1945 v_scrollbar_
.get() ? GetScaled(GetScrollbarReservedThickness()) : 0;
1947 if (!force_no_horizontal_scrollbar
&&
1948 GetDocumentPixelWidth() >
1949 (plugin_size_
.width() - v_scrollbar_reserved_thickness
)) {
1950 CreateHorizontalScrollbar();
1952 // Adding the horizontal scrollbar now might cause us to need vertical
1954 if (GetDocumentPixelHeight() >
1955 plugin_size_
.height() - GetScaled(GetScrollbarReservedThickness())) {
1956 CreateVerticalScrollbar();
1960 DestroyHorizontalScrollbar();
1963 #ifdef ENABLE_THUMBNAILS
1964 int thumbnails_pos
= 0, thumbnails_total
= 0;
1966 if (v_scrollbar_
.get()) {
1967 v_scrollbar_
->SetScale(device_scale_
);
1968 available_area_
.set_width(
1969 std::max(0, plugin_size_
.width() - v_scrollbar_reserved_thickness
));
1971 #ifdef ENABLE_THUMBNAILS
1972 int height
= plugin_size_
.height();
1974 int height_dip
= plugin_dip_size_
.height();
1976 #if defined(OS_MACOSX)
1977 // Before Lion, Mac always had the resize at the bottom. After that, it
1979 if ((base::mac::IsOSSnowLeopard() && full_
) ||
1980 (base::mac::IsOSLionOrLater() && h_scrollbar_
.get())) {
1982 if (h_scrollbar_
.get()) {
1983 #endif // defined(OS_MACOSX)
1984 #ifdef ENABLE_THUMBNAILS
1985 height
-= GetScaled(GetScrollbarThickness());
1987 height_dip
-= GetScrollbarThickness();
1989 #ifdef ENABLE_THUMBNAILS
1990 int32 doc_height
= GetDocumentPixelHeight();
1992 int32 doc_height_dip
=
1993 static_cast<int32
>(GetDocumentPixelHeight() / device_scale_
);
1994 #if defined(OS_MACOSX)
1995 // On the Mac we always allow room for the resize button (whose width is
1996 // the same as that of the scrollbar) in full mode. However, if there is no
1997 // no horizontal scrollbar, the end of the scrollbar will scroll past the
1998 // end of the document. This is because the scrollbar assumes that its own
1999 // height (in the case of a vscroll bar) is the same as the height of the
2000 // viewport. Since the viewport is actually larger, we compensate by
2001 // adjusting the document height. Similar logic applies below for the
2002 // horizontal scrollbar.
2003 // For example, if the document size is 1000, and the viewport size is 200,
2004 // then the scrollbar position at the end will be 800. In this case the
2005 // viewport is actally 215 (assuming 15 as the scrollbar width) but the
2006 // scrollbar thinks it is 200. We want the scrollbar position at the end to
2007 // be 785. Making the document size 985 achieves this.
2008 if (full_
&& !h_scrollbar_
.get()) {
2009 #ifdef ENABLE_THUMBNAILS
2010 doc_height
-= GetScaled(GetScrollbarThickness());
2012 doc_height_dip
-= GetScrollbarThickness();
2014 #endif // defined(OS_MACOSX)
2017 position
= v_scrollbar_
->GetValue();
2018 position
= static_cast<int>(position
* zoom_
/ old_zoom
);
2019 valid_v_range_
= doc_height_dip
- height_dip
;
2020 if (position
> valid_v_range_
)
2021 position
= valid_v_range_
;
2023 v_scrollbar_
->SetValue(position
);
2026 loc
.point
.x
= static_cast<int>(available_area_
.right() / device_scale_
);
2027 if (IsOverlayScrollbar())
2028 loc
.point
.x
-= scrollbar_thickness
;
2030 loc
.size
.width
= scrollbar_thickness
;
2031 loc
.size
.height
= height_dip
;
2032 v_scrollbar_
->SetLocation(loc
);
2033 v_scrollbar_
->SetDocumentSize(doc_height_dip
);
2035 #ifdef ENABLE_THUMBNAILS
2036 thumbnails_pos
= position
;
2037 thumbnails_total
= doc_height
- height
;
2041 if (h_scrollbar_
.get()) {
2042 h_scrollbar_
->SetScale(device_scale_
);
2043 available_area_
.set_height(
2044 std::max(0, plugin_size_
.height() -
2045 GetScaled(GetScrollbarReservedThickness())));
2047 int width_dip
= plugin_dip_size_
.width();
2050 #if defined(OS_MACOSX)
2051 if ((base::mac::IsOSSnowLeopard() && full_
) ||
2052 (base::mac::IsOSLionOrLater() && v_scrollbar_
.get())) {
2054 if (v_scrollbar_
.get()) {
2056 width_dip
-= GetScrollbarThickness();
2058 int32 doc_width_dip
=
2059 static_cast<int32
>(GetDocumentPixelWidth() / device_scale_
);
2060 #if defined(OS_MACOSX)
2061 // See comment in the above if (v_scrollbar_.get()) block.
2062 if (full_
&& !v_scrollbar_
.get())
2063 doc_width_dip
-= GetScrollbarThickness();
2064 #endif // defined(OS_MACOSX)
2067 position
= h_scrollbar_
->GetValue();
2068 position
= static_cast<int>(position
* zoom_
/ old_zoom
);
2069 position
= std::min(position
, doc_width_dip
- width_dip
);
2071 h_scrollbar_
->SetValue(position
);
2075 loc
.point
.y
= static_cast<int>(available_area_
.bottom() / device_scale_
);
2076 if (IsOverlayScrollbar())
2077 loc
.point
.y
-= scrollbar_thickness
;
2078 loc
.size
.width
= width_dip
;
2079 loc
.size
.height
= scrollbar_thickness
;
2080 h_scrollbar_
->SetLocation(loc
);
2081 h_scrollbar_
->SetDocumentSize(doc_width_dip
);
2084 int doc_width
= GetDocumentPixelWidth();
2085 if (doc_width
< available_area_
.width()) {
2086 available_area_
.Offset((available_area_
.width() - doc_width
) / 2, 0);
2087 available_area_
.set_width(doc_width
);
2089 int doc_height
= GetDocumentPixelHeight();
2090 if (doc_height
< available_area_
.height()) {
2091 available_area_
.set_height(doc_height
);
2094 // We'll invalidate the entire plugin anyways.
2095 UpdateToolbarPosition(false);
2096 UpdateProgressBarPosition(false);
2097 UpdatePageIndicatorPosition(false);
2099 #ifdef ENABLE_THUMBNAILS
2100 // Update thumbnail control position.
2101 thumbnails_
.SetPosition(thumbnails_pos
, thumbnails_total
, false);
2102 pp::Rect
thumbnails_rc(plugin_size_
.width() - GetScaled(kThumbnailsWidth
), 0,
2103 GetScaled(kThumbnailsWidth
), plugin_size_
.height());
2104 if (v_scrollbar_
.get())
2105 thumbnails_rc
.Offset(-v_scrollbar_reserved_thickness
, 0);
2106 if (h_scrollbar_
.get())
2107 thumbnails_rc
.Inset(0, 0, 0, v_scrollbar_reserved_thickness
);
2108 thumbnails_
.SetRect(thumbnails_rc
, false);
2111 CalculateBackgroundParts();
2112 engine_
->PageOffsetUpdated(available_area_
.point());
2113 engine_
->PluginSizeUpdated(available_area_
.size());
2115 if (!document_size_
.GetArea())
2117 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
2119 if (on_plugin_size_changed_callback_
.is_string())
2120 ExecuteScript(on_plugin_size_changed_callback_
);
2123 void Instance::CreateHorizontalScrollbar() {
2124 if (h_scrollbar_
.get())
2127 h_scrollbar_
.reset(new pp::Scrollbar_Dev(this, false));
2130 void Instance::CreateVerticalScrollbar() {
2131 if (v_scrollbar_
.get())
2134 v_scrollbar_
.reset(new pp::Scrollbar_Dev(this, true));
2137 void Instance::DestroyHorizontalScrollbar() {
2138 if (!h_scrollbar_
.get())
2140 if (h_scrollbar_
->GetValue())
2141 engine_
->ScrolledToXPosition(0);
2142 h_scrollbar_
.reset();
2145 void Instance::DestroyVerticalScrollbar() {
2146 if (!v_scrollbar_
.get())
2148 if (v_scrollbar_
->GetValue())
2149 engine_
->ScrolledToYPosition(0);
2150 v_scrollbar_
.reset();
2151 page_indicator_
.Show(false, true);
2154 int Instance::GetScrollbarThickness() {
2155 if (scrollbar_thickness_
== -1) {
2156 pp::Scrollbar_Dev
temp_scrollbar(this, false);
2157 scrollbar_thickness_
= temp_scrollbar
.GetThickness();
2158 scrollbar_reserved_thickness_
=
2159 temp_scrollbar
.IsOverlay() ? 0 : scrollbar_thickness_
;
2162 return scrollbar_thickness_
;
2165 int Instance::GetScrollbarReservedThickness() {
2166 GetScrollbarThickness();
2167 return scrollbar_reserved_thickness_
;
2170 bool Instance::IsOverlayScrollbar() {
2171 return GetScrollbarReservedThickness() == 0;
2174 void Instance::CreateToolbar(const ToolbarButtonInfo
* tb_info
, size_t size
) {
2175 toolbar_
.reset(new FadingControls());
2180 // Remember the current toolbar information in case we need to recreate the
2182 current_tb_info_
= tb_info
;
2183 current_tb_info_size_
= size
;
2186 pp::Point
origin(kToolbarFadingOffsetLeft
, kToolbarFadingOffsetTop
);
2187 ScalePoint(device_scale_
, &origin
);
2189 std::list
<Button
*> buttons
;
2190 for (size_t i
= 0; i
< size
; i
++) {
2191 Button
* btn
= new Button
;
2192 pp::ImageData normal_face
=
2193 CreateResourceImage(tb_info
[i
].normal
);
2194 btn
->CreateButton(tb_info
[i
].id
,
2200 CreateResourceImage(tb_info
[i
].highlighted
),
2201 CreateResourceImage(tb_info
[i
].pressed
));
2202 buttons
.push_back(btn
);
2204 origin
+= pp::Point(normal_face
.size().width(), 0);
2205 max_height
= std::max(max_height
, normal_face
.size().height());
2208 pp::Rect
rc_toolbar(0, 0,
2209 origin
.x() + GetToolbarRightOffset(),
2210 origin
.y() + max_height
+ GetToolbarBottomOffset());
2211 toolbar_
->CreateFadingControls(
2212 kToolbarId
, rc_toolbar
, false, this, kTransparentAlpha
);
2214 std::list
<Button
*>::iterator iter
;
2215 for (iter
= buttons
.begin(); iter
!= buttons
.end(); ++iter
) {
2216 toolbar_
->AddControl(*iter
);
2220 int Instance::GetToolbarRightOffset() {
2221 int scrollbar_thickness
= GetScrollbarThickness();
2222 return GetScaled(kToolbarFadingOffsetRight
) + 2 * scrollbar_thickness
;
2225 int Instance::GetToolbarBottomOffset() {
2226 int scrollbar_thickness
= GetScrollbarThickness();
2227 return GetScaled(kToolbarFadingOffsetBottom
) + scrollbar_thickness
;
2230 std::vector
<pp::ImageData
> Instance::GetThumbnailResources() {
2231 std::vector
<pp::ImageData
> num_images(10);
2232 num_images
[0] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_0
);
2233 num_images
[1] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_1
);
2234 num_images
[2] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_2
);
2235 num_images
[3] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_3
);
2236 num_images
[4] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_4
);
2237 num_images
[5] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_5
);
2238 num_images
[6] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_6
);
2239 num_images
[7] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_7
);
2240 num_images
[8] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_8
);
2241 num_images
[9] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_9
);
2245 std::vector
<pp::ImageData
> Instance::GetProgressBarResources(
2246 pp::ImageData
* background
) {
2247 std::vector
<pp::ImageData
> result(9);
2248 result
[0] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_0
);
2249 result
[1] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_1
);
2250 result
[2] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_2
);
2251 result
[3] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_3
);
2252 result
[4] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_4
);
2253 result
[5] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_5
);
2254 result
[6] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_6
);
2255 result
[7] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_7
);
2256 result
[8] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_8
);
2257 *background
= CreateResourceImage(
2258 PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_BACKGROUND
);
2262 void Instance::CreatePageIndicator(bool always_visible
) {
2263 page_indicator_
.CreatePageIndicator(kPageIndicatorId
, false, this,
2264 number_image_generator(), always_visible
);
2265 ConfigurePageIndicator();
2268 void Instance::ConfigurePageIndicator() {
2269 pp::ImageData background
=
2270 CreateResourceImage(PP_RESOURCEIMAGE_PDF_PAGE_INDICATOR_BACKGROUND
);
2271 page_indicator_
.Configure(pp::Point(), background
);
2274 void Instance::CreateProgressBar() {
2275 pp::ImageData background
;
2276 std::vector
<pp::ImageData
> images
= GetProgressBarResources(&background
);
2277 std::string text
= GetLocalizedString(PP_RESOURCESTRING_PDFPROGRESSLOADING
);
2278 progress_bar_
.CreateProgressControl(kProgressBarId
, false, this, 0.0,
2279 device_scale_
, images
, background
, text
);
2282 void Instance::ConfigureProgressBar() {
2283 pp::ImageData background
;
2284 std::vector
<pp::ImageData
> images
= GetProgressBarResources(&background
);
2285 progress_bar_
.Reconfigure(background
, images
, device_scale_
);
2288 void Instance::CreateThumbnails() {
2289 thumbnails_
.CreateThumbnailControl(
2290 kThumbnailsId
, pp::Rect(), false, this, engine_
.get(),
2291 number_image_generator());
2294 void Instance::LoadUrl(const std::string
& url
) {
2295 LoadUrlInternal(url
, &embed_loader_
, &Instance::DidOpen
);
2298 void Instance::LoadPreviewUrl(const std::string
& url
) {
2299 LoadUrlInternal(url
, &embed_preview_loader_
, &Instance::DidOpenPreview
);
2302 void Instance::LoadUrlInternal(const std::string
& url
, pp::URLLoader
* loader
,
2303 void (Instance::* method
)(int32_t)) {
2304 pp::URLRequestInfo
request(this);
2305 request
.SetURL(url
);
2306 request
.SetMethod("GET");
2308 *loader
= CreateURLLoaderInternal();
2309 pp::CompletionCallback callback
= loader_factory_
.NewCallback(method
);
2310 int rv
= loader
->Open(request
, callback
);
2311 if (rv
!= PP_OK_COMPLETIONPENDING
)
2315 pp::URLLoader
Instance::CreateURLLoaderInternal() {
2316 pp::URLLoader
loader(this);
2318 const PPB_URLLoaderTrusted
* trusted_interface
=
2319 reinterpret_cast<const PPB_URLLoaderTrusted
*>(
2320 pp::Module::Get()->GetBrowserInterface(
2321 PPB_URLLOADERTRUSTED_INTERFACE
));
2322 if (trusted_interface
)
2323 trusted_interface
->GrantUniversalAccess(loader
.pp_resource());
2327 int Instance::GetInitialPage(const std::string
& url
) {
2328 size_t found_idx
= url
.find('#');
2329 if (found_idx
== std::string::npos
)
2332 const std::string
& ref
= url
.substr(found_idx
+ 1);
2333 std::vector
<std::string
> fragments
;
2334 Tokenize(ref
, kDelimiters
, &fragments
);
2336 // Page number to return, zero-based.
2339 // Handle the case of http://foo.com/bar#NAMEDDEST. This is not explicitly
2340 // mentioned except by example in the Adobe "PDF Open Parameters" document.
2341 if ((fragments
.size() == 1) && (fragments
[0].find('=') == std::string::npos
))
2342 return engine_
->GetNamedDestinationPage(fragments
[0]);
2344 for (size_t i
= 0; i
< fragments
.size(); ++i
) {
2345 std::vector
<std::string
> key_value
;
2346 base::SplitString(fragments
[i
], '=', &key_value
);
2347 if (key_value
.size() != 2)
2349 const std::string
& key
= key_value
[0];
2350 const std::string
& value
= key_value
[1];
2352 if (base::strcasecmp(kPage
, key
.c_str()) == 0) {
2353 // |page_value| is 1-based.
2354 int page_value
= -1;
2355 if (base::StringToInt(value
, &page_value
) && page_value
> 0)
2356 page
= page_value
- 1;
2359 if (base::strcasecmp(kNamedDest
, key
.c_str()) == 0) {
2360 // |page_value| is 0-based.
2361 int page_value
= engine_
->GetNamedDestinationPage(value
);
2362 if (page_value
>= 0)
2370 void Instance::UpdateToolbarPosition(bool invalidate
) {
2371 pp::Rect ctrl_rc
= toolbar_
->GetControlsRect();
2372 int min_toolbar_width
= ctrl_rc
.width() + GetToolbarRightOffset() +
2373 GetScaled(kToolbarFadingOffsetLeft
);
2374 int min_toolbar_height
= ctrl_rc
.width() + GetToolbarBottomOffset() +
2375 GetScaled(kToolbarFadingOffsetBottom
);
2377 // Update toolbar position
2378 if (plugin_size_
.width() < min_toolbar_width
||
2379 plugin_size_
.height() < min_toolbar_height
) {
2380 // Disable toolbar if it does not fit on the screen.
2381 toolbar_
->Show(false, invalidate
);
2384 plugin_size_
.width() - GetToolbarRightOffset() - ctrl_rc
.right(),
2385 plugin_size_
.height() - GetToolbarBottomOffset() - ctrl_rc
.bottom());
2386 toolbar_
->MoveBy(offset
, invalidate
);
2388 int toolbar_width
= std::max(plugin_size_
.width() / 2, min_toolbar_width
);
2389 toolbar_
->ExpandLeft(toolbar_width
- toolbar_
->rect().width());
2390 toolbar_
->Show(painted_first_page_
, invalidate
);
2394 void Instance::UpdateProgressBarPosition(bool invalidate
) {
2395 // TODO(gene): verify we don't overlap with toolbar.
2396 int scrollbar_thickness
= GetScrollbarThickness();
2397 pp::Point
progress_origin(
2398 scrollbar_thickness
+ GetScaled(kProgressOffsetLeft
),
2399 plugin_size_
.height() - progress_bar_
.rect().height() -
2400 scrollbar_thickness
- GetScaled(kProgressOffsetBottom
));
2401 progress_bar_
.MoveTo(progress_origin
, invalidate
);
2404 void Instance::UpdatePageIndicatorPosition(bool invalidate
) {
2405 int32 doc_height
= static_cast<int>(document_size_
.height() * zoom_
);
2407 plugin_size_
.width() - page_indicator_
.rect().width() -
2408 GetScaled(GetScrollbarReservedThickness()),
2409 page_indicator_
.GetYPosition(engine_
->GetVerticalScrollbarYPosition(),
2410 doc_height
, plugin_size_
.height()));
2411 page_indicator_
.MoveTo(origin
, invalidate
);
2414 void Instance::SetZoom(ZoomMode zoom_mode
, double scale
) {
2415 double old_zoom
= zoom_
;
2417 zoom_mode_
= zoom_mode
;
2418 if (zoom_mode_
== ZOOM_SCALE
)
2422 engine_
->ZoomUpdated(zoom_
* device_scale_
);
2423 OnGeometryChanged(old_zoom
, device_scale_
);
2425 // If fit-to-height, snap to the beginning of the most visible page.
2426 if (zoom_mode_
== ZOOM_FIT_TO_PAGE
) {
2427 ScrollToPage(engine_
->GetMostVisiblePage());
2430 // Update sticky buttons to the current zoom style.
2431 Button
* ftp_btn
= static_cast<Button
*>(
2432 toolbar_
->GetControl(kFitToPageButtonId
));
2433 Button
* ftw_btn
= static_cast<Button
*>(
2434 toolbar_
->GetControl(kFitToWidthButtonId
));
2435 switch (zoom_mode_
) {
2436 case ZOOM_FIT_TO_PAGE
:
2437 ftp_btn
->SetPressedState(true);
2438 ftw_btn
->SetPressedState(false);
2440 case ZOOM_FIT_TO_WIDTH
:
2441 ftw_btn
->SetPressedState(true);
2442 ftp_btn
->SetPressedState(false);
2445 ftw_btn
->SetPressedState(false);
2446 ftp_btn
->SetPressedState(false);
2450 void Instance::UpdateZoomScale() {
2451 switch (zoom_mode_
) {
2453 break; // Keep current scale.
2454 case ZOOM_FIT_TO_PAGE
: {
2455 int page_num
= engine_
->GetFirstVisiblePage();
2458 pp::Rect rc
= engine_
->GetPageRect(page_num
);
2461 // Calculate fit to width zoom level.
2462 double ftw_zoom
= static_cast<double>(plugin_dip_size_
.width() -
2463 GetScrollbarReservedThickness()) / document_size_
.width();
2464 // Calculate fit to height zoom level. If document will not fit
2465 // horizontally, adjust zoom level to allow space for horizontal
2468 static_cast<double>(plugin_dip_size_
.height()) / rc
.height();
2469 if (fth_zoom
* document_size_
.width() >
2470 plugin_dip_size_
.width() - GetScrollbarReservedThickness())
2471 fth_zoom
= static_cast<double>(plugin_dip_size_
.height()
2472 - GetScrollbarReservedThickness()) / rc
.height();
2473 zoom_
= std::min(ftw_zoom
, fth_zoom
);
2475 case ZOOM_FIT_TO_WIDTH
:
2477 if (!document_size_
.width())
2479 zoom_
= static_cast<double>(plugin_dip_size_
.width() -
2480 GetScrollbarReservedThickness()) / document_size_
.width();
2481 if (zoom_mode_
== ZOOM_AUTO
&& zoom_
> 1.0)
2485 zoom_
= ClipToRange(zoom_
, kMinZoom
, kMaxZoom
);
2488 double Instance::CalculateZoom(uint32 control_id
) const {
2489 if (control_id
== kZoomInButtonId
) {
2490 for (size_t i
= 0; i
< chrome_page_zoom::kPresetZoomFactorsSize
; ++i
) {
2491 double current_zoom
= chrome_page_zoom::kPresetZoomFactors
[i
];
2492 if (current_zoom
- content::kEpsilon
> zoom_
)
2493 return current_zoom
;
2496 for (size_t i
= chrome_page_zoom::kPresetZoomFactorsSize
; i
> 0; --i
) {
2497 double current_zoom
= chrome_page_zoom::kPresetZoomFactors
[i
- 1];
2498 if (current_zoom
+ content::kEpsilon
< zoom_
)
2499 return current_zoom
;
2505 pp::ImageData
Instance::CreateResourceImage(PP_ResourceImage image_id
) {
2507 return pp::PDF::GetResourceImageForScale(this, image_id
, device_scale_
);
2509 return pp::PDF::GetResourceImage(this, image_id
);
2512 std::string
Instance::GetLocalizedString(PP_ResourceString id
) {
2513 pp::Var
rv(pp::PDF::GetLocalizedString(this, id
));
2514 if (!rv
.is_string())
2515 return std::string();
2517 return rv
.AsString();
2520 void Instance::DrawText(const pp::Point
& top_center
, PP_ResourceString id
) {
2521 std::string
str(GetLocalizedString(id
));
2523 pp::FontDescription_Dev description
;
2524 description
.set_family(PP_FONTFAMILY_SANSSERIF
);
2525 description
.set_size(kMessageTextSize
* device_scale_
);
2526 pp::Font_Dev
font(this, description
);
2527 int length
= font
.MeasureSimpleText(str
);
2528 pp::Point
point(top_center
);
2529 point
.set_x(point
.x() - length
/ 2);
2530 DCHECK(!image_data_
.is_null());
2531 font
.DrawSimpleText(&image_data_
, str
, point
, kMessageTextColor
);
2534 void Instance::SetPrintPreviewMode(int page_count
) {
2535 if (!IsPrintPreview() || page_count
<= 0) {
2536 print_preview_page_count_
= 0;
2540 print_preview_page_count_
= page_count
;
2542 engine_
->AppendBlankPages(print_preview_page_count_
);
2543 if (preview_pages_info_
.size() > 0)
2544 LoadAvailablePreviewPage();
2547 bool Instance::IsPrintPreview() {
2548 return IsPrintPreviewUrl(url_
);
2551 int Instance::GetPageNumberToDisplay() {
2552 int page
= engine_
->GetMostVisiblePage();
2553 if (IsPrintPreview() && !print_preview_page_numbers_
.empty()) {
2554 page
= ClipToRange
<int>(page
, 0, print_preview_page_numbers_
.size() - 1);
2555 return print_preview_page_numbers_
[page
];
2560 void Instance::ProcessPreviewPageInfo(const std::string
& url
,
2561 int dst_page_index
) {
2562 if (!IsPrintPreview() || print_preview_page_count_
< 0)
2565 int src_page_index
= ExtractPrintPreviewPageIndex(url
);
2566 if (src_page_index
< 1)
2569 preview_pages_info_
.push(std::make_pair(url
, dst_page_index
));
2570 LoadAvailablePreviewPage();
2573 void Instance::LoadAvailablePreviewPage() {
2574 if (preview_pages_info_
.size() <= 0)
2577 std::string url
= preview_pages_info_
.front().first
;
2578 int dst_page_index
= preview_pages_info_
.front().second
;
2579 int src_page_index
= ExtractPrintPreviewPageIndex(url
);
2580 if (src_page_index
< 1 ||
2581 dst_page_index
>= print_preview_page_count_
||
2582 preview_document_load_state_
== LOAD_STATE_LOADING
) {
2586 preview_document_load_state_
= LOAD_STATE_LOADING
;
2587 LoadPreviewUrl(url
);
2590 void Instance::EnableAutoscroll(const pp::Point
& origin
) {
2594 pp::Size client_size
= plugin_size_
;
2595 if (v_scrollbar_
.get())
2596 client_size
.Enlarge(-GetScrollbarThickness(), 0);
2597 if (h_scrollbar_
.get())
2598 client_size
.Enlarge(0, -GetScrollbarThickness());
2600 // Do not allow autoscroll if client area is too small.
2601 if (autoscroll_anchor_
.size().width() > client_size
.width() ||
2602 autoscroll_anchor_
.size().height() > client_size
.height())
2605 autoscroll_rect_
= pp::Rect(
2606 pp::Point(origin
.x() - autoscroll_anchor_
.size().width() / 2,
2607 origin
.y() - autoscroll_anchor_
.size().height() / 2),
2608 autoscroll_anchor_
.size());
2610 // Make sure autoscroll anchor is in the client area.
2611 if (autoscroll_rect_
.right() > client_size
.width()) {
2612 autoscroll_rect_
.set_x(
2613 client_size
.width() - autoscroll_anchor_
.size().width());
2615 if (autoscroll_rect_
.bottom() > client_size
.height()) {
2616 autoscroll_rect_
.set_y(
2617 client_size
.height() - autoscroll_anchor_
.size().height());
2620 if (autoscroll_rect_
.x() < 0)
2621 autoscroll_rect_
.set_x(0);
2622 if (autoscroll_rect_
.y() < 0)
2623 autoscroll_rect_
.set_y(0);
2625 is_autoscroll_
= true;
2626 Invalidate(kAutoScrollId
, autoscroll_rect_
);
2628 ScheduleTimer(kAutoScrollId
, kAutoScrollTimeoutMs
);
2631 void Instance::DisableAutoscroll() {
2632 if (is_autoscroll_
) {
2633 is_autoscroll_
= false;
2634 Invalidate(kAutoScrollId
, autoscroll_rect_
);
2638 PP_CursorType_Dev
Instance::CalculateAutoscroll(const pp::Point
& mouse_pos
) {
2639 // Scroll only if mouse pointer is outside of the anchor area.
2640 if (autoscroll_rect_
.Contains(mouse_pos
)) {
2643 return PP_CURSORTYPE_MIDDLEPANNING
;
2646 // Relative position to the center of anchor area.
2647 pp::Point rel_pos
= mouse_pos
- autoscroll_rect_
.CenterPoint();
2649 // Calculate angle from the X axis. Angle is in range from -pi to pi.
2650 double angle
= atan2(static_cast<double>(rel_pos
.y()),
2651 static_cast<double>(rel_pos
.x()));
2653 autoscroll_x_
= rel_pos
.x() * kAutoScrollFactor
;
2654 autoscroll_y_
= rel_pos
.y() * kAutoScrollFactor
;
2656 // Angle is from -pi to pi. Screen Y is increasing toward bottom,
2657 // so negative angle represent north direction.
2658 if (angle
< - (M_PI
* 7.0 / 8.0)) {
2660 return PP_CURSORTYPE_WESTPANNING
;
2661 } else if (angle
< - (M_PI
* 5.0 / 8.0)) {
2663 return PP_CURSORTYPE_NORTHWESTPANNING
;
2664 } else if (angle
< - (M_PI
* 3.0 / 8.0)) {
2666 return PP_CURSORTYPE_NORTHPANNING
;
2667 } else if (angle
< - (M_PI
* 1.0 / 8.0)) {
2669 return PP_CURSORTYPE_NORTHEASTPANNING
;
2670 } else if (angle
< M_PI
* 1.0 / 8.0) {
2672 return PP_CURSORTYPE_EASTPANNING
;
2673 } else if (angle
< M_PI
* 3.0 / 8.0) {
2675 return PP_CURSORTYPE_SOUTHEASTPANNING
;
2676 } else if (angle
< M_PI
* 5.0 / 8.0) {
2678 return PP_CURSORTYPE_SOUTHPANNING
;
2679 } else if (angle
< M_PI
* 7.0 / 8.0) {
2681 return PP_CURSORTYPE_SOUTHWESTPANNING
;
2684 // went around the circle, going west again
2685 return PP_CURSORTYPE_WESTPANNING
;
2688 void Instance::ConfigureNumberImageGenerator() {
2689 std::vector
<pp::ImageData
> num_images
= GetThumbnailResources();
2690 pp::ImageData number_background
= CreateResourceImage(
2691 PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_NUM_BACKGROUND
);
2692 number_image_generator_
->Configure(number_background
,
2697 NumberImageGenerator
* Instance::number_image_generator() {
2698 if (!number_image_generator_
.get()) {
2699 number_image_generator_
.reset(new NumberImageGenerator(this));
2700 ConfigureNumberImageGenerator();
2702 return number_image_generator_
.get();
2705 int Instance::GetScaled(int x
) const {
2706 return static_cast<int>(x
* device_scale_
);
2709 void Instance::UserMetricsRecordAction(const std::string
& action
) {
2710 pp::PDF::UserMetricsRecordAction(this, pp::Var(action
));
2713 PDFScriptableObject::PDFScriptableObject(Instance
* instance
)
2714 : instance_(instance
) {
2717 PDFScriptableObject::~PDFScriptableObject() {
2720 bool PDFScriptableObject::HasMethod(const pp::Var
& name
, pp::Var
* exception
) {
2721 return instance_
->HasScriptableMethod(name
, exception
);
2724 pp::Var
PDFScriptableObject::Call(const pp::Var
& method
,
2725 const std::vector
<pp::Var
>& args
,
2726 pp::Var
* exception
) {
2727 return instance_
->CallScriptableMethod(method
, args
, exception
);
2730 } // namespace chrome_pdf