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();
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 // Run the scroll callback asynchronously. This function can be invoked by a
1136 // layout change which should not re-enter into JS synchronously.
1137 pp::CompletionCallback callback
=
1138 callback_factory_
.NewCallback(&Instance::RunCallback
,
1139 on_scroll_callback_
);
1140 pp::Module::Get()->core()->CallOnMainThread(0, callback
);
1143 void Instance::ScrollToX(int position
) {
1144 if (!h_scrollbar_
.get()) {
1148 int position_dip
= static_cast<int>(position
/ device_scale_
);
1149 h_scrollbar_
->SetValue(position_dip
);
1152 void Instance::ScrollToY(int position
) {
1153 if (!v_scrollbar_
.get()) {
1157 int position_dip
= static_cast<int>(position
/ device_scale_
);
1158 v_scrollbar_
->SetValue(ClipToRange(position_dip
, 0, valid_v_range_
));
1161 void Instance::ScrollToPage(int page
) {
1162 if (!v_scrollbar_
.get())
1165 if (engine_
->GetNumberOfPages() == 0)
1168 int index
= ClipToRange(page
, 0, engine_
->GetNumberOfPages() - 1);
1169 pp::Rect rect
= engine_
->GetPageRect(index
);
1170 // If we are trying to scroll pass the last page,
1171 // scroll to the end of the last page.
1172 int position
= index
< page
? rect
.bottom() : rect
.y();
1173 ScrollToY(position
* zoom_
* device_scale_
);
1176 void Instance::NavigateTo(const std::string
& url
, bool open_in_new_tab
) {
1177 std::string
url_copy(url
);
1179 // Empty |url_copy| is ok, and will effectively be a reload.
1180 // Skip the code below so an empty URL does not turn into "http://", which
1181 // will cause GURL to fail a DCHECK.
1182 if (!url_copy
.empty()) {
1183 // If |url_copy| starts with '#', then it's for the same URL with a
1184 // different URL fragment.
1185 if (url_copy
[0] == '#') {
1186 url_copy
= url_
+ url_copy
;
1187 // Changing the href does not actually do anything when navigating in the
1188 // same tab, so do the actual page scroll here. Then fall through so the
1189 // href gets updated.
1190 if (!open_in_new_tab
) {
1191 int page_number
= GetInitialPage(url_copy
);
1192 if (page_number
>= 0)
1193 ScrollToPage(page_number
);
1196 // If there's no scheme, add http.
1197 if (url_copy
.find("://") == std::string::npos
&&
1198 url_copy
.find("mailto:") == std::string::npos
) {
1199 url_copy
= "http://" + url_copy
;
1201 // Make sure |url_copy| starts with a valid scheme.
1202 if (url_copy
.find("http://") != 0 &&
1203 url_copy
.find("https://") != 0 &&
1204 url_copy
.find("ftp://") != 0 &&
1205 url_copy
.find("file://") != 0 &&
1206 url_copy
.find("mailto:") != 0) {
1209 // Make sure |url_copy| is not only a scheme.
1210 if (url_copy
== "http://" ||
1211 url_copy
== "https://" ||
1212 url_copy
== "ftp://" ||
1213 url_copy
== "file://" ||
1214 url_copy
== "mailto:") {
1218 if (open_in_new_tab
) {
1219 GetWindowObject().Call("open", url_copy
);
1221 GetWindowObject().GetProperty("top").GetProperty("location").
1222 SetProperty("href", url_copy
);
1226 void Instance::UpdateCursor(PP_CursorType_Dev cursor
) {
1227 if (cursor
== cursor_
)
1231 const PPB_CursorControl_Dev
* cursor_interface
=
1232 reinterpret_cast<const PPB_CursorControl_Dev
*>(
1233 pp::Module::Get()->GetBrowserInterface(PPB_CURSOR_CONTROL_DEV_INTERFACE
));
1234 if (!cursor_interface
) {
1239 cursor_interface
->SetCursor(
1240 pp_instance(), cursor_
, pp::ImageData().pp_resource(), NULL
);
1243 void Instance::UpdateTickMarks(const std::vector
<pp::Rect
>& tickmarks
) {
1244 if (!v_scrollbar_
.get())
1247 float inverse_scale
= 1.0f
/ device_scale_
;
1248 std::vector
<pp::Rect
> scaled_tickmarks
= tickmarks
;
1249 for (size_t i
= 0; i
< scaled_tickmarks
.size(); i
++) {
1250 ScaleRect(inverse_scale
, &scaled_tickmarks
[i
]);
1253 v_scrollbar_
->SetTickMarks(
1254 scaled_tickmarks
.empty() ? NULL
: &scaled_tickmarks
[0], tickmarks
.size());
1257 void Instance::NotifyNumberOfFindResultsChanged(int total
, bool final_result
) {
1258 NumberOfFindResultsChanged(total
, final_result
);
1261 void Instance::NotifySelectedFindResultChanged(int current_find_index
) {
1262 SelectedFindResultChanged(current_find_index
);
1265 void Instance::OnEvent(uint32 control_id
, uint32 event_id
, void* data
) {
1266 if (event_id
== Button::EVENT_ID_BUTTON_CLICKED
||
1267 event_id
== Button::EVENT_ID_BUTTON_STATE_CHANGED
) {
1268 switch (control_id
) {
1269 case kFitToPageButtonId
:
1270 UserMetricsRecordAction("PDF.FitToPageButton");
1271 SetZoom(ZOOM_FIT_TO_PAGE
, 0);
1274 case kFitToWidthButtonId
:
1275 UserMetricsRecordAction("PDF.FitToWidthButton");
1276 SetZoom(ZOOM_FIT_TO_WIDTH
, 0);
1279 case kZoomOutButtonId
:
1280 case kZoomInButtonId
:
1281 UserMetricsRecordAction(control_id
== kZoomOutButtonId
?
1282 "PDF.ZoomOutButton" : "PDF.ZoomInButton");
1283 SetZoom(ZOOM_SCALE
, CalculateZoom(control_id
));
1287 UserMetricsRecordAction("PDF.SaveButton");
1290 case kPrintButtonId
:
1291 UserMetricsRecordAction("PDF.PrintButton");
1296 if (control_id
== kThumbnailsId
&&
1297 event_id
== ThumbnailControl::EVENT_ID_THUMBNAIL_SELECTED
) {
1298 int page
= *static_cast<int*>(data
);
1299 pp::Rect
page_rc(engine_
->GetPageRect(page
));
1300 ScrollToY(static_cast<int>(page_rc
.y() * zoom_
* device_scale_
));
1304 void Instance::Invalidate(uint32 control_id
, const pp::Rect
& rc
) {
1305 paint_manager_
.InvalidateRect(rc
);
1308 uint32
Instance::ScheduleTimer(uint32 control_id
, uint32 timeout_ms
) {
1309 current_timer_id_
++;
1310 pp::CompletionCallback callback
=
1311 timer_factory_
.NewCallback(&Instance::OnControlTimerFired
,
1314 pp::Module::Get()->core()->CallOnMainThread(timeout_ms
, callback
);
1315 return current_timer_id_
;
1318 void Instance::SetEventCapture(uint32 control_id
, bool set_capture
) {
1319 // TODO(gene): set event capture here.
1322 void Instance::SetCursor(uint32 control_id
, PP_CursorType_Dev cursor_type
) {
1323 UpdateCursor(cursor_type
);
1326 pp::Instance
* Instance::GetInstance() {
1330 void Instance::GetDocumentPassword(
1331 pp::CompletionCallbackWithOutput
<pp::Var
> callback
) {
1332 std::string
message(GetLocalizedString(PP_RESOURCESTRING_PDFGETPASSWORD
));
1333 pp::Var result
= pp::PDF::ModalPromptForPassword(this, message
);
1334 *callback
.output() = result
.pp_var();
1335 callback
.Run(PP_OK
);
1338 void Instance::Alert(const std::string
& message
) {
1339 GetWindowObject().Call("alert", message
);
1342 bool Instance::Confirm(const std::string
& message
) {
1343 pp::Var result
= GetWindowObject().Call("confirm", message
);
1344 return result
.is_bool() ? result
.AsBool() : false;
1347 std::string
Instance::Prompt(const std::string
& question
,
1348 const std::string
& default_answer
) {
1349 pp::Var result
= GetWindowObject().Call("prompt", question
, default_answer
);
1350 return result
.is_string() ? result
.AsString() : std::string();
1353 std::string
Instance::GetURL() {
1357 void Instance::Email(const std::string
& to
,
1358 const std::string
& cc
,
1359 const std::string
& bcc
,
1360 const std::string
& subject
,
1361 const std::string
& body
) {
1362 std::string javascript
=
1363 "var href = 'mailto:" + net::EscapeUrlEncodedData(to
, false) +
1364 "?cc=" + net::EscapeUrlEncodedData(cc
, false) +
1365 "&bcc=" + net::EscapeUrlEncodedData(bcc
, false) +
1366 "&subject=" + net::EscapeUrlEncodedData(subject
, false) +
1367 "&body=" + net::EscapeUrlEncodedData(body
, false) +
1368 "';var temp = window.open(href, '_blank', " +
1369 "'width=1,height=1');if(temp) temp.close();";
1370 ExecuteScript(javascript
);
1373 void Instance::Print() {
1374 if (!printing_enabled_
||
1375 (!engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
) &&
1376 !engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY
))) {
1380 pp::CompletionCallback callback
=
1381 callback_factory_
.NewCallback(&Instance::OnPrint
);
1382 pp::Module::Get()->core()->CallOnMainThread(0, callback
);
1385 void Instance::OnPrint(int32_t) {
1386 pp::PDF::Print(this);
1389 void Instance::SaveAs() {
1390 pp::PDF::SaveAs(this);
1393 void Instance::SubmitForm(const std::string
& url
,
1396 pp::URLRequestInfo
request(this);
1397 request
.SetURL(url
);
1398 request
.SetMethod("POST");
1399 request
.AppendDataToBody(reinterpret_cast<const char*>(data
), length
);
1401 pp::CompletionCallback callback
=
1402 form_factory_
.NewCallback(&Instance::FormDidOpen
);
1403 form_loader_
= CreateURLLoaderInternal();
1404 int rv
= form_loader_
.Open(request
, callback
);
1405 if (rv
!= PP_OK_COMPLETIONPENDING
)
1409 void Instance::FormDidOpen(int32_t result
) {
1410 // TODO: inform the user of success/failure.
1411 if (result
!= PP_OK
) {
1416 std::string
Instance::ShowFileSelectionDialog() {
1417 // Seems like very low priority to implement, since the pdf has no way to get
1418 // the file data anyways. Javascript doesn't let you do this synchronously.
1420 return std::string();
1423 pp::URLLoader
Instance::CreateURLLoader() {
1425 if (!did_call_start_loading_
) {
1426 did_call_start_loading_
= true;
1427 pp::PDF::DidStartLoading(this);
1430 // Disable save and print until the document is fully loaded, since they
1431 // would generate an incomplete document. Need to do this each time we
1432 // call DidStartLoading since that resets the content restrictions.
1433 pp::PDF::SetContentRestriction(this, CONTENT_RESTRICTION_SAVE
|
1434 CONTENT_RESTRICTION_PRINT
);
1437 return CreateURLLoaderInternal();
1440 void Instance::ScheduleCallback(int id
, int delay_in_ms
) {
1441 pp::CompletionCallback callback
=
1442 timer_factory_
.NewCallback(&Instance::OnClientTimerFired
);
1443 pp::Module::Get()->core()->CallOnMainThread(delay_in_ms
, callback
, id
);
1446 void Instance::SearchString(const base::char16
* string
,
1447 const base::char16
* term
,
1448 bool case_sensitive
,
1449 std::vector
<SearchStringResult
>* results
) {
1450 if (!pp::PDF::IsAvailable()) {
1455 PP_PrivateFindResult
* pp_results
;
1457 pp::PDF::SearchString(
1459 reinterpret_cast<const unsigned short*>(string
),
1460 reinterpret_cast<const unsigned short*>(term
),
1465 results
->resize(count
);
1466 for (int i
= 0; i
< count
; ++i
) {
1467 (*results
)[i
].start_index
= pp_results
[i
].start_index
;
1468 (*results
)[i
].length
= pp_results
[i
].length
;
1471 pp::Memory_Dev memory
;
1472 memory
.MemFree(pp_results
);
1475 void Instance::DocumentPaintOccurred() {
1476 if (painted_first_page_
)
1479 painted_first_page_
= true;
1480 UpdateToolbarPosition(false);
1481 toolbar_
->Splash(kToolbarSplashTimeoutMs
);
1483 if (engine_
->GetNumberOfPages() > 1)
1484 show_page_indicator_
= true;
1486 show_page_indicator_
= false;
1488 if (v_scrollbar_
.get() && show_page_indicator_
) {
1489 page_indicator_
.set_current_page(GetPageNumberToDisplay());
1490 page_indicator_
.Splash(kToolbarSplashTimeoutMs
,
1491 kPageIndicatorInitialFadeTimeoutMs
);
1495 void Instance::DocumentLoadComplete(int page_count
) {
1496 // Clear focus state for OSK.
1497 FormTextFieldFocusChange(false);
1499 // Update progress control.
1500 if (progress_bar_
.visible())
1501 progress_bar_
.Fade(false, kProgressFadeTimeoutMs
);
1503 DCHECK(document_load_state_
== LOAD_STATE_LOADING
);
1504 document_load_state_
= LOAD_STATE_COMPLETE
;
1505 UserMetricsRecordAction("PDF.LoadSuccess");
1507 if (did_call_start_loading_
) {
1508 pp::PDF::DidStopLoading(this);
1509 did_call_start_loading_
= false;
1512 if (on_load_callback_
.is_string())
1513 ExecuteScript(on_load_callback_
);
1514 // Note: If we are in print preview mode on_load_callback_ might call
1515 // ScrollTo{X|Y}() and we don't want to scroll again and override it.
1516 // #page=N is not supported in Print Preview.
1517 if (!IsPrintPreview()) {
1518 int initial_page
= GetInitialPage(url_
);
1519 if (initial_page
>= 0)
1520 ScrollToPage(initial_page
);
1525 if (!pp::PDF::IsAvailable())
1528 int content_restrictions
=
1529 CONTENT_RESTRICTION_CUT
| CONTENT_RESTRICTION_PASTE
;
1530 if (!engine_
->HasPermission(PDFEngine::PERMISSION_COPY
))
1531 content_restrictions
|= CONTENT_RESTRICTION_COPY
;
1533 if (!engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
) &&
1534 !engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY
)) {
1535 printing_enabled_
= false;
1536 if (current_tb_info_
== kPDFToolbarButtons
) {
1537 // Remove Print button.
1538 CreateToolbar(kPDFNoPrintToolbarButtons
,
1539 arraysize(kPDFNoPrintToolbarButtons
));
1540 UpdateToolbarPosition(false);
1541 Invalidate(pp::Rect(plugin_size_
));
1545 pp::PDF::SetContentRestriction(this, content_restrictions
);
1547 pp::PDF::HistogramPDFPageCount(this, page_count
);
1550 void Instance::RotateClockwise() {
1551 engine_
->RotateClockwise();
1554 void Instance::RotateCounterclockwise() {
1555 engine_
->RotateCounterclockwise();
1558 void Instance::PreviewDocumentLoadComplete() {
1559 if (preview_document_load_state_
!= LOAD_STATE_LOADING
||
1560 preview_pages_info_
.empty()) {
1564 preview_document_load_state_
= LOAD_STATE_COMPLETE
;
1566 int dest_page_index
= preview_pages_info_
.front().second
;
1567 int src_page_index
=
1568 ExtractPrintPreviewPageIndex(preview_pages_info_
.front().first
);
1569 if (src_page_index
> 0 && dest_page_index
> -1 && preview_engine_
.get())
1570 engine_
->AppendPage(preview_engine_
.get(), dest_page_index
);
1572 preview_pages_info_
.pop();
1573 // |print_preview_page_count_| is not updated yet. Do not load any
1574 // other preview pages till we get this information.
1575 if (print_preview_page_count_
== 0)
1578 if (preview_pages_info_
.size())
1579 LoadAvailablePreviewPage();
1582 void Instance::DocumentLoadFailed() {
1583 DCHECK(document_load_state_
== LOAD_STATE_LOADING
);
1584 UserMetricsRecordAction("PDF.LoadFailure");
1586 // Hide progress control.
1587 progress_bar_
.Fade(false, kProgressFadeTimeoutMs
);
1589 if (did_call_start_loading_
) {
1590 pp::PDF::DidStopLoading(this);
1591 did_call_start_loading_
= false;
1594 document_load_state_
= LOAD_STATE_FAILED
;
1595 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
1598 void Instance::PreviewDocumentLoadFailed() {
1599 UserMetricsRecordAction("PDF.PreviewDocumentLoadFailure");
1600 if (preview_document_load_state_
!= LOAD_STATE_LOADING
||
1601 preview_pages_info_
.empty()) {
1605 preview_document_load_state_
= LOAD_STATE_FAILED
;
1606 preview_pages_info_
.pop();
1608 if (preview_pages_info_
.size())
1609 LoadAvailablePreviewPage();
1612 pp::Instance
* Instance::GetPluginInstance() {
1613 return GetInstance();
1616 void Instance::DocumentHasUnsupportedFeature(const std::string
& feature
) {
1617 std::string
metric("PDF_Unsupported_");
1619 if (!unsupported_features_reported_
.count(metric
)) {
1620 unsupported_features_reported_
.insert(metric
);
1621 UserMetricsRecordAction(metric
);
1624 // Since we use an info bar, only do this for full frame plugins..
1628 if (told_browser_about_unsupported_feature_
)
1630 told_browser_about_unsupported_feature_
= true;
1632 pp::PDF::HasUnsupportedFeature(this);
1635 void Instance::DocumentLoadProgress(uint32 available
, uint32 doc_size
) {
1636 double progress
= 0.0;
1637 if (doc_size
== 0) {
1638 // Document size is unknown. Use heuristics.
1639 // We'll make progress logarithmic from 0 to 100M.
1640 static const double kFactor
= log(100000000.0) / 100.0;
1641 if (available
> 0) {
1642 progress
= log(static_cast<double>(available
)) / kFactor
;
1643 if (progress
> 100.0)
1647 progress
= 100.0 * static_cast<double>(available
) / doc_size
;
1649 progress_bar_
.SetProgress(progress
);
1652 void Instance::FormTextFieldFocusChange(bool in_focus
) {
1653 if (!text_input_
.get())
1656 text_input_
->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_TEXT
);
1658 text_input_
->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_NONE
);
1661 // Called by PDFScriptableObject.
1662 bool Instance::HasScriptableMethod(const pp::Var
& method
, pp::Var
* exception
) {
1663 std::string method_str
= method
.AsString();
1664 return (method_str
== kJSAccessibility
||
1665 method_str
== kJSDocumentLoadComplete
||
1666 method_str
== kJSGetHeight
||
1667 method_str
== kJSGetHorizontalScrollbarThickness
||
1668 method_str
== kJSGetPageLocationNormalized
||
1669 method_str
== kJSGetVerticalScrollbarThickness
||
1670 method_str
== kJSGetWidth
||
1671 method_str
== kJSGetZoomLevel
||
1672 method_str
== kJSGoToPage
||
1673 method_str
== kJSGrayscale
||
1674 method_str
== kJSLoadPreviewPage
||
1675 method_str
== kJSOnLoad
||
1676 method_str
== kJSOnPluginSizeChanged
||
1677 method_str
== kJSOnScroll
||
1678 method_str
== kJSPageXOffset
||
1679 method_str
== kJSPageYOffset
||
1680 method_str
== kJSPrintPreviewPageCount
||
1681 method_str
== kJSReload
||
1682 method_str
== kJSRemovePrintButton
||
1683 method_str
== kJSResetPrintPreviewUrl
||
1684 method_str
== kJSSendKeyEvent
||
1685 method_str
== kJSSetPageNumbers
||
1686 method_str
== kJSSetPageXOffset
||
1687 method_str
== kJSSetPageYOffset
||
1688 method_str
== kJSSetZoomLevel
||
1689 method_str
== kJSZoomFitToHeight
||
1690 method_str
== kJSZoomFitToWidth
||
1691 method_str
== kJSZoomIn
||
1692 method_str
== kJSZoomOut
);
1695 pp::Var
Instance::CallScriptableMethod(const pp::Var
& method
,
1696 const std::vector
<pp::Var
>& args
,
1697 pp::Var
* exception
) {
1698 std::string method_str
= method
.AsString();
1699 if (method_str
== kJSGrayscale
) {
1700 if (args
.size() == 1 && args
[0].is_bool()) {
1701 engine_
->SetGrayscale(args
[0].AsBool());
1703 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
1704 #ifdef ENABLE_THUMBNAILS
1705 if (thumbnails_
.visible())
1706 thumbnails_
.Show(true, true);
1708 return pp::Var(true);
1710 return pp::Var(false);
1712 if (method_str
== kJSOnLoad
) {
1713 if (args
.size() == 1 && args
[0].is_string()) {
1714 on_load_callback_
= args
[0];
1715 return pp::Var(true);
1717 return pp::Var(false);
1719 if (method_str
== kJSOnScroll
) {
1720 if (args
.size() == 1 && args
[0].is_string()) {
1721 on_scroll_callback_
= args
[0];
1722 return pp::Var(true);
1724 return pp::Var(false);
1726 if (method_str
== kJSOnPluginSizeChanged
) {
1727 if (args
.size() == 1 && args
[0].is_string()) {
1728 on_plugin_size_changed_callback_
= args
[0];
1729 return pp::Var(true);
1731 return pp::Var(false);
1733 if (method_str
== kJSReload
) {
1734 document_load_state_
= LOAD_STATE_LOADING
;
1737 preview_engine_
.reset();
1738 print_preview_page_count_
= 0;
1739 engine_
.reset(PDFEngine::Create(this));
1740 engine_
->New(url_
.c_str());
1741 #ifdef ENABLE_THUMBNAILS
1742 thumbnails_
.ResetEngine(engine_
.get());
1746 if (method_str
== kJSResetPrintPreviewUrl
) {
1747 if (args
.size() == 1 && args
[0].is_string()) {
1748 url_
= args
[0].AsString();
1749 preview_pages_info_
= std::queue
<PreviewPageInfo
>();
1750 preview_document_load_state_
= LOAD_STATE_COMPLETE
;
1754 if (method_str
== kJSZoomFitToHeight
) {
1755 SetZoom(ZOOM_FIT_TO_PAGE
, 0);
1758 if (method_str
== kJSZoomFitToWidth
) {
1759 SetZoom(ZOOM_FIT_TO_WIDTH
, 0);
1762 if (method_str
== kJSZoomIn
) {
1763 SetZoom(ZOOM_SCALE
, CalculateZoom(kZoomInButtonId
));
1766 if (method_str
== kJSZoomOut
) {
1767 SetZoom(ZOOM_SCALE
, CalculateZoom(kZoomOutButtonId
));
1770 if (method_str
== kJSSetZoomLevel
) {
1771 if (args
.size() == 1 && args
[0].is_number())
1772 SetZoom(ZOOM_SCALE
, args
[0].AsDouble());
1775 if (method_str
== kJSGetZoomLevel
) {
1776 return pp::Var(zoom_
);
1778 if (method_str
== kJSGetHeight
) {
1779 return pp::Var(plugin_size_
.height());
1781 if (method_str
== kJSGetWidth
) {
1782 return pp::Var(plugin_size_
.width());
1784 if (method_str
== kJSGetHorizontalScrollbarThickness
) {
1786 h_scrollbar_
.get() ? GetScrollbarReservedThickness() : 0);
1788 if (method_str
== kJSGetVerticalScrollbarThickness
) {
1790 v_scrollbar_
.get() ? GetScrollbarReservedThickness() : 0);
1792 if (method_str
== kJSDocumentLoadComplete
) {
1793 return pp::Var((document_load_state_
!= LOAD_STATE_LOADING
));
1795 if (method_str
== kJSPageYOffset
) {
1796 return pp::Var(static_cast<int32_t>(
1797 v_scrollbar_
.get() ? v_scrollbar_
->GetValue() : 0));
1799 if (method_str
== kJSSetPageYOffset
) {
1800 if (args
.size() == 1 && args
[0].is_number() && v_scrollbar_
.get())
1801 ScrollToY(GetScaled(args
[0].AsInt()));
1804 if (method_str
== kJSPageXOffset
) {
1805 return pp::Var(static_cast<int32_t>(
1806 h_scrollbar_
.get() ? h_scrollbar_
->GetValue() : 0));
1808 if (method_str
== kJSSetPageXOffset
) {
1809 if (args
.size() == 1 && args
[0].is_number() && h_scrollbar_
.get())
1810 ScrollToX(GetScaled(args
[0].AsInt()));
1813 if (method_str
== kJSRemovePrintButton
) {
1814 CreateToolbar(kPrintPreviewToolbarButtons
,
1815 arraysize(kPrintPreviewToolbarButtons
));
1816 UpdateToolbarPosition(false);
1817 Invalidate(pp::Rect(plugin_size_
));
1820 if (method_str
== kJSGoToPage
) {
1821 if (args
.size() == 1 && args
[0].is_string()) {
1822 ScrollToPage(atoi(args
[0].AsString().c_str()));
1826 if (method_str
== kJSAccessibility
) {
1827 if (args
.size() == 0) {
1828 base::DictionaryValue node
;
1829 node
.SetInteger(kAccessibleNumberOfPages
, engine_
->GetNumberOfPages());
1830 node
.SetBoolean(kAccessibleLoaded
,
1831 document_load_state_
!= LOAD_STATE_LOADING
);
1832 bool has_permissions
=
1833 engine_
->HasPermission(PDFEngine::PERMISSION_COPY
) ||
1834 engine_
->HasPermission(PDFEngine::PERMISSION_COPY_ACCESSIBLE
);
1835 node
.SetBoolean(kAccessibleCopyable
, has_permissions
);
1837 base::JSONWriter::Write(&node
, &json
);
1838 return pp::Var(json
);
1839 } else if (args
[0].is_number()) {
1840 return pp::Var(engine_
->GetPageAsJSON(args
[0].AsInt()));
1843 if (method_str
== kJSPrintPreviewPageCount
) {
1844 if (args
.size() == 1 && args
[0].is_number())
1845 SetPrintPreviewMode(args
[0].AsInt());
1848 if (method_str
== kJSLoadPreviewPage
) {
1849 if (args
.size() == 2 && args
[0].is_string() && args
[1].is_number())
1850 ProcessPreviewPageInfo(args
[0].AsString(), args
[1].AsInt());
1853 if (method_str
== kJSGetPageLocationNormalized
) {
1854 const size_t kMaxLength
= 30;
1855 char location_info
[kMaxLength
];
1856 int page_idx
= engine_
->GetMostVisiblePage();
1858 return pp::Var(std::string());
1859 pp::Rect rect
= engine_
->GetPageContentsRect(page_idx
);
1860 int v_scrollbar_reserved_thickness
=
1861 v_scrollbar_
.get() ? GetScaled(GetScrollbarReservedThickness()) : 0;
1863 rect
.set_x(rect
.x() + ((plugin_size_
.width() -
1864 v_scrollbar_reserved_thickness
- available_area_
.width()) / 2));
1865 base::snprintf(location_info
,
1867 "%0.4f;%0.4f;%0.4f;%0.4f;",
1868 rect
.x() / static_cast<float>(plugin_size_
.width()),
1869 rect
.y() / static_cast<float>(plugin_size_
.height()),
1870 rect
.width() / static_cast<float>(plugin_size_
.width()),
1871 rect
.height()/ static_cast<float>(plugin_size_
.height()));
1872 return pp::Var(std::string(location_info
));
1874 if (method_str
== kJSSetPageNumbers
) {
1875 if (args
.size() != 1 || !args
[0].is_string())
1877 const int num_pages_signed
= engine_
->GetNumberOfPages();
1878 if (num_pages_signed
<= 0)
1880 scoped_ptr
<base::ListValue
> page_ranges(static_cast<base::ListValue
*>(
1881 base::JSONReader::Read(args
[0].AsString(), false)));
1882 const size_t num_pages
= static_cast<size_t>(num_pages_signed
);
1883 if (!page_ranges
.get() || page_ranges
->GetSize() != num_pages
)
1886 std::vector
<int> print_preview_page_numbers
;
1887 for (size_t index
= 0; index
< num_pages
; ++index
) {
1888 int page_number
= 0; // |page_number| is 1-based.
1889 if (!page_ranges
->GetInteger(index
, &page_number
) || page_number
< 1)
1891 print_preview_page_numbers
.push_back(page_number
);
1893 print_preview_page_numbers_
= print_preview_page_numbers
;
1894 page_indicator_
.set_current_page(GetPageNumberToDisplay());
1897 // This is here to work around https://bugs.webkit.org/show_bug.cgi?id=16735.
1898 // In JS, creating a synthetic keyboard event and dispatching it always
1899 // result in a keycode of 0.
1900 if (method_str
== kJSSendKeyEvent
) {
1901 if (args
.size() == 1 && args
[0].is_number()) {
1902 pp::KeyboardInputEvent
event(
1904 PP_INPUTEVENT_TYPE_KEYDOWN
, // HandleInputEvent only care about this.
1905 0, // timestamp, not used for kbd events.
1907 args
[0].AsInt(), // keycode.
1908 pp::Var()); // no char text needed.
1909 HandleInputEvent(event
);
1915 void Instance::OnGeometryChanged(double old_zoom
, float old_device_scale
) {
1916 bool force_no_horizontal_scrollbar
= false;
1917 int scrollbar_thickness
= GetScrollbarThickness();
1919 if (old_device_scale
!= device_scale_
) {
1920 // Change in device scale forces us to recreate resources
1921 ConfigureNumberImageGenerator();
1923 CreateToolbar(current_tb_info_
, current_tb_info_size_
);
1924 // Load autoscroll anchor image.
1925 autoscroll_anchor_
=
1926 CreateResourceImage(PP_RESOURCEIMAGE_PDF_PAN_SCROLL_ICON
);
1928 ConfigurePageIndicator();
1929 ConfigureProgressBar();
1931 pp::Point scroll_position
= engine_
->GetScrollPosition();
1932 ScalePoint(device_scale_
/ old_device_scale
, &scroll_position
);
1933 engine_
->SetScrollPosition(scroll_position
);
1937 if (zoom_
!= old_zoom
|| device_scale_
!= old_device_scale
)
1938 engine_
->ZoomUpdated(zoom_
* device_scale_
);
1939 if (zoom_
!= old_zoom
)
1942 available_area_
= pp::Rect(plugin_size_
);
1943 if (GetDocumentPixelHeight() > plugin_size_
.height()) {
1944 CreateVerticalScrollbar();
1946 DestroyVerticalScrollbar();
1949 int v_scrollbar_reserved_thickness
=
1950 v_scrollbar_
.get() ? GetScaled(GetScrollbarReservedThickness()) : 0;
1952 if (!force_no_horizontal_scrollbar
&&
1953 GetDocumentPixelWidth() >
1954 (plugin_size_
.width() - v_scrollbar_reserved_thickness
)) {
1955 CreateHorizontalScrollbar();
1957 // Adding the horizontal scrollbar now might cause us to need vertical
1959 if (GetDocumentPixelHeight() >
1960 plugin_size_
.height() - GetScaled(GetScrollbarReservedThickness())) {
1961 CreateVerticalScrollbar();
1965 DestroyHorizontalScrollbar();
1968 #ifdef ENABLE_THUMBNAILS
1969 int thumbnails_pos
= 0, thumbnails_total
= 0;
1971 if (v_scrollbar_
.get()) {
1972 v_scrollbar_
->SetScale(device_scale_
);
1973 available_area_
.set_width(
1974 std::max(0, plugin_size_
.width() - v_scrollbar_reserved_thickness
));
1976 #ifdef ENABLE_THUMBNAILS
1977 int height
= plugin_size_
.height();
1979 int height_dip
= plugin_dip_size_
.height();
1981 #if defined(OS_MACOSX)
1982 // Before Lion, Mac always had the resize at the bottom. After that, it
1984 if ((base::mac::IsOSSnowLeopard() && full_
) ||
1985 (base::mac::IsOSLionOrLater() && h_scrollbar_
.get())) {
1987 if (h_scrollbar_
.get()) {
1988 #endif // defined(OS_MACOSX)
1989 #ifdef ENABLE_THUMBNAILS
1990 height
-= GetScaled(GetScrollbarThickness());
1992 height_dip
-= GetScrollbarThickness();
1994 #ifdef ENABLE_THUMBNAILS
1995 int32 doc_height
= GetDocumentPixelHeight();
1997 int32 doc_height_dip
=
1998 static_cast<int32
>(GetDocumentPixelHeight() / device_scale_
);
1999 #if defined(OS_MACOSX)
2000 // On the Mac we always allow room for the resize button (whose width is
2001 // the same as that of the scrollbar) in full mode. However, if there is no
2002 // no horizontal scrollbar, the end of the scrollbar will scroll past the
2003 // end of the document. This is because the scrollbar assumes that its own
2004 // height (in the case of a vscroll bar) is the same as the height of the
2005 // viewport. Since the viewport is actually larger, we compensate by
2006 // adjusting the document height. Similar logic applies below for the
2007 // horizontal scrollbar.
2008 // For example, if the document size is 1000, and the viewport size is 200,
2009 // then the scrollbar position at the end will be 800. In this case the
2010 // viewport is actally 215 (assuming 15 as the scrollbar width) but the
2011 // scrollbar thinks it is 200. We want the scrollbar position at the end to
2012 // be 785. Making the document size 985 achieves this.
2013 if (full_
&& !h_scrollbar_
.get()) {
2014 #ifdef ENABLE_THUMBNAILS
2015 doc_height
-= GetScaled(GetScrollbarThickness());
2017 doc_height_dip
-= GetScrollbarThickness();
2019 #endif // defined(OS_MACOSX)
2022 position
= v_scrollbar_
->GetValue();
2023 position
= static_cast<int>(position
* zoom_
/ old_zoom
);
2024 valid_v_range_
= doc_height_dip
- height_dip
;
2025 if (position
> valid_v_range_
)
2026 position
= valid_v_range_
;
2028 v_scrollbar_
->SetValue(position
);
2031 loc
.point
.x
= static_cast<int>(available_area_
.right() / device_scale_
);
2032 if (IsOverlayScrollbar())
2033 loc
.point
.x
-= scrollbar_thickness
;
2035 loc
.size
.width
= scrollbar_thickness
;
2036 loc
.size
.height
= height_dip
;
2037 v_scrollbar_
->SetLocation(loc
);
2038 v_scrollbar_
->SetDocumentSize(doc_height_dip
);
2040 #ifdef ENABLE_THUMBNAILS
2041 thumbnails_pos
= position
;
2042 thumbnails_total
= doc_height
- height
;
2046 if (h_scrollbar_
.get()) {
2047 h_scrollbar_
->SetScale(device_scale_
);
2048 available_area_
.set_height(
2049 std::max(0, plugin_size_
.height() -
2050 GetScaled(GetScrollbarReservedThickness())));
2052 int width_dip
= plugin_dip_size_
.width();
2055 #if defined(OS_MACOSX)
2056 if ((base::mac::IsOSSnowLeopard() && full_
) ||
2057 (base::mac::IsOSLionOrLater() && v_scrollbar_
.get())) {
2059 if (v_scrollbar_
.get()) {
2061 width_dip
-= GetScrollbarThickness();
2063 int32 doc_width_dip
=
2064 static_cast<int32
>(GetDocumentPixelWidth() / device_scale_
);
2065 #if defined(OS_MACOSX)
2066 // See comment in the above if (v_scrollbar_.get()) block.
2067 if (full_
&& !v_scrollbar_
.get())
2068 doc_width_dip
-= GetScrollbarThickness();
2069 #endif // defined(OS_MACOSX)
2072 position
= h_scrollbar_
->GetValue();
2073 position
= static_cast<int>(position
* zoom_
/ old_zoom
);
2074 position
= std::min(position
, doc_width_dip
- width_dip
);
2076 h_scrollbar_
->SetValue(position
);
2080 loc
.point
.y
= static_cast<int>(available_area_
.bottom() / device_scale_
);
2081 if (IsOverlayScrollbar())
2082 loc
.point
.y
-= scrollbar_thickness
;
2083 loc
.size
.width
= width_dip
;
2084 loc
.size
.height
= scrollbar_thickness
;
2085 h_scrollbar_
->SetLocation(loc
);
2086 h_scrollbar_
->SetDocumentSize(doc_width_dip
);
2089 int doc_width
= GetDocumentPixelWidth();
2090 if (doc_width
< available_area_
.width()) {
2091 available_area_
.Offset((available_area_
.width() - doc_width
) / 2, 0);
2092 available_area_
.set_width(doc_width
);
2094 int doc_height
= GetDocumentPixelHeight();
2095 if (doc_height
< available_area_
.height()) {
2096 available_area_
.set_height(doc_height
);
2099 // We'll invalidate the entire plugin anyways.
2100 UpdateToolbarPosition(false);
2101 UpdateProgressBarPosition(false);
2102 UpdatePageIndicatorPosition(false);
2104 #ifdef ENABLE_THUMBNAILS
2105 // Update thumbnail control position.
2106 thumbnails_
.SetPosition(thumbnails_pos
, thumbnails_total
, false);
2107 pp::Rect
thumbnails_rc(plugin_size_
.width() - GetScaled(kThumbnailsWidth
), 0,
2108 GetScaled(kThumbnailsWidth
), plugin_size_
.height());
2109 if (v_scrollbar_
.get())
2110 thumbnails_rc
.Offset(-v_scrollbar_reserved_thickness
, 0);
2111 if (h_scrollbar_
.get())
2112 thumbnails_rc
.Inset(0, 0, 0, v_scrollbar_reserved_thickness
);
2113 thumbnails_
.SetRect(thumbnails_rc
, false);
2116 CalculateBackgroundParts();
2117 engine_
->PageOffsetUpdated(available_area_
.point());
2118 engine_
->PluginSizeUpdated(available_area_
.size());
2120 if (!document_size_
.GetArea())
2122 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
2124 // Run the plugin size change callback asynchronously. This function can be
2125 // invoked by a layout change which should not re-enter into JS synchronously.
2126 pp::CompletionCallback callback
=
2127 callback_factory_
.NewCallback(&Instance::RunCallback
,
2128 on_plugin_size_changed_callback_
);
2129 pp::Module::Get()->core()->CallOnMainThread(0, callback
);
2132 void Instance::RunCallback(int32_t, pp::Var callback
) {
2133 if (callback
.is_string())
2134 ExecuteScript(callback
);
2137 void Instance::CreateHorizontalScrollbar() {
2138 if (h_scrollbar_
.get())
2141 h_scrollbar_
.reset(new pp::Scrollbar_Dev(this, false));
2144 void Instance::CreateVerticalScrollbar() {
2145 if (v_scrollbar_
.get())
2148 v_scrollbar_
.reset(new pp::Scrollbar_Dev(this, true));
2151 void Instance::DestroyHorizontalScrollbar() {
2152 if (!h_scrollbar_
.get())
2154 if (h_scrollbar_
->GetValue())
2155 engine_
->ScrolledToXPosition(0);
2156 h_scrollbar_
.reset();
2159 void Instance::DestroyVerticalScrollbar() {
2160 if (!v_scrollbar_
.get())
2162 if (v_scrollbar_
->GetValue())
2163 engine_
->ScrolledToYPosition(0);
2164 v_scrollbar_
.reset();
2165 page_indicator_
.Show(false, true);
2168 int Instance::GetScrollbarThickness() {
2169 if (scrollbar_thickness_
== -1) {
2170 pp::Scrollbar_Dev
temp_scrollbar(this, false);
2171 scrollbar_thickness_
= temp_scrollbar
.GetThickness();
2172 scrollbar_reserved_thickness_
=
2173 temp_scrollbar
.IsOverlay() ? 0 : scrollbar_thickness_
;
2176 return scrollbar_thickness_
;
2179 int Instance::GetScrollbarReservedThickness() {
2180 GetScrollbarThickness();
2181 return scrollbar_reserved_thickness_
;
2184 bool Instance::IsOverlayScrollbar() {
2185 return GetScrollbarReservedThickness() == 0;
2188 void Instance::CreateToolbar(const ToolbarButtonInfo
* tb_info
, size_t size
) {
2189 toolbar_
.reset(new FadingControls());
2194 // Remember the current toolbar information in case we need to recreate the
2196 current_tb_info_
= tb_info
;
2197 current_tb_info_size_
= size
;
2200 pp::Point
origin(kToolbarFadingOffsetLeft
, kToolbarFadingOffsetTop
);
2201 ScalePoint(device_scale_
, &origin
);
2203 std::list
<Button
*> buttons
;
2204 for (size_t i
= 0; i
< size
; i
++) {
2205 Button
* btn
= new Button
;
2206 pp::ImageData normal_face
=
2207 CreateResourceImage(tb_info
[i
].normal
);
2208 btn
->CreateButton(tb_info
[i
].id
,
2214 CreateResourceImage(tb_info
[i
].highlighted
),
2215 CreateResourceImage(tb_info
[i
].pressed
));
2216 buttons
.push_back(btn
);
2218 origin
+= pp::Point(normal_face
.size().width(), 0);
2219 max_height
= std::max(max_height
, normal_face
.size().height());
2222 pp::Rect
rc_toolbar(0, 0,
2223 origin
.x() + GetToolbarRightOffset(),
2224 origin
.y() + max_height
+ GetToolbarBottomOffset());
2225 toolbar_
->CreateFadingControls(
2226 kToolbarId
, rc_toolbar
, false, this, kTransparentAlpha
);
2228 std::list
<Button
*>::iterator iter
;
2229 for (iter
= buttons
.begin(); iter
!= buttons
.end(); ++iter
) {
2230 toolbar_
->AddControl(*iter
);
2234 int Instance::GetToolbarRightOffset() {
2235 int scrollbar_thickness
= GetScrollbarThickness();
2236 return GetScaled(kToolbarFadingOffsetRight
) + 2 * scrollbar_thickness
;
2239 int Instance::GetToolbarBottomOffset() {
2240 int scrollbar_thickness
= GetScrollbarThickness();
2241 return GetScaled(kToolbarFadingOffsetBottom
) + scrollbar_thickness
;
2244 std::vector
<pp::ImageData
> Instance::GetThumbnailResources() {
2245 std::vector
<pp::ImageData
> num_images(10);
2246 num_images
[0] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_0
);
2247 num_images
[1] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_1
);
2248 num_images
[2] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_2
);
2249 num_images
[3] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_3
);
2250 num_images
[4] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_4
);
2251 num_images
[5] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_5
);
2252 num_images
[6] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_6
);
2253 num_images
[7] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_7
);
2254 num_images
[8] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_8
);
2255 num_images
[9] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_9
);
2259 std::vector
<pp::ImageData
> Instance::GetProgressBarResources(
2260 pp::ImageData
* background
) {
2261 std::vector
<pp::ImageData
> result(9);
2262 result
[0] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_0
);
2263 result
[1] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_1
);
2264 result
[2] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_2
);
2265 result
[3] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_3
);
2266 result
[4] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_4
);
2267 result
[5] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_5
);
2268 result
[6] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_6
);
2269 result
[7] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_7
);
2270 result
[8] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_8
);
2271 *background
= CreateResourceImage(
2272 PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_BACKGROUND
);
2276 void Instance::CreatePageIndicator(bool always_visible
) {
2277 page_indicator_
.CreatePageIndicator(kPageIndicatorId
, false, this,
2278 number_image_generator(), always_visible
);
2279 ConfigurePageIndicator();
2282 void Instance::ConfigurePageIndicator() {
2283 pp::ImageData background
=
2284 CreateResourceImage(PP_RESOURCEIMAGE_PDF_PAGE_INDICATOR_BACKGROUND
);
2285 page_indicator_
.Configure(pp::Point(), background
);
2288 void Instance::CreateProgressBar() {
2289 pp::ImageData background
;
2290 std::vector
<pp::ImageData
> images
= GetProgressBarResources(&background
);
2291 std::string text
= GetLocalizedString(PP_RESOURCESTRING_PDFPROGRESSLOADING
);
2292 progress_bar_
.CreateProgressControl(kProgressBarId
, false, this, 0.0,
2293 device_scale_
, images
, background
, text
);
2296 void Instance::ConfigureProgressBar() {
2297 pp::ImageData background
;
2298 std::vector
<pp::ImageData
> images
= GetProgressBarResources(&background
);
2299 progress_bar_
.Reconfigure(background
, images
, device_scale_
);
2302 void Instance::CreateThumbnails() {
2303 thumbnails_
.CreateThumbnailControl(
2304 kThumbnailsId
, pp::Rect(), false, this, engine_
.get(),
2305 number_image_generator());
2308 void Instance::LoadUrl(const std::string
& url
) {
2309 LoadUrlInternal(url
, &embed_loader_
, &Instance::DidOpen
);
2312 void Instance::LoadPreviewUrl(const std::string
& url
) {
2313 LoadUrlInternal(url
, &embed_preview_loader_
, &Instance::DidOpenPreview
);
2316 void Instance::LoadUrlInternal(const std::string
& url
, pp::URLLoader
* loader
,
2317 void (Instance::* method
)(int32_t)) {
2318 pp::URLRequestInfo
request(this);
2319 request
.SetURL(url
);
2320 request
.SetMethod("GET");
2322 *loader
= CreateURLLoaderInternal();
2323 pp::CompletionCallback callback
= loader_factory_
.NewCallback(method
);
2324 int rv
= loader
->Open(request
, callback
);
2325 if (rv
!= PP_OK_COMPLETIONPENDING
)
2329 pp::URLLoader
Instance::CreateURLLoaderInternal() {
2330 pp::URLLoader
loader(this);
2332 const PPB_URLLoaderTrusted
* trusted_interface
=
2333 reinterpret_cast<const PPB_URLLoaderTrusted
*>(
2334 pp::Module::Get()->GetBrowserInterface(
2335 PPB_URLLOADERTRUSTED_INTERFACE
));
2336 if (trusted_interface
)
2337 trusted_interface
->GrantUniversalAccess(loader
.pp_resource());
2341 int Instance::GetInitialPage(const std::string
& url
) {
2342 size_t found_idx
= url
.find('#');
2343 if (found_idx
== std::string::npos
)
2346 const std::string
& ref
= url
.substr(found_idx
+ 1);
2347 std::vector
<std::string
> fragments
;
2348 Tokenize(ref
, kDelimiters
, &fragments
);
2350 // Page number to return, zero-based.
2353 // Handle the case of http://foo.com/bar#NAMEDDEST. This is not explicitly
2354 // mentioned except by example in the Adobe "PDF Open Parameters" document.
2355 if ((fragments
.size() == 1) && (fragments
[0].find('=') == std::string::npos
))
2356 return engine_
->GetNamedDestinationPage(fragments
[0]);
2358 for (size_t i
= 0; i
< fragments
.size(); ++i
) {
2359 std::vector
<std::string
> key_value
;
2360 base::SplitString(fragments
[i
], '=', &key_value
);
2361 if (key_value
.size() != 2)
2363 const std::string
& key
= key_value
[0];
2364 const std::string
& value
= key_value
[1];
2366 if (base::strcasecmp(kPage
, key
.c_str()) == 0) {
2367 // |page_value| is 1-based.
2368 int page_value
= -1;
2369 if (base::StringToInt(value
, &page_value
) && page_value
> 0)
2370 page
= page_value
- 1;
2373 if (base::strcasecmp(kNamedDest
, key
.c_str()) == 0) {
2374 // |page_value| is 0-based.
2375 int page_value
= engine_
->GetNamedDestinationPage(value
);
2376 if (page_value
>= 0)
2384 void Instance::UpdateToolbarPosition(bool invalidate
) {
2385 pp::Rect ctrl_rc
= toolbar_
->GetControlsRect();
2386 int min_toolbar_width
= ctrl_rc
.width() + GetToolbarRightOffset() +
2387 GetScaled(kToolbarFadingOffsetLeft
);
2388 int min_toolbar_height
= ctrl_rc
.width() + GetToolbarBottomOffset() +
2389 GetScaled(kToolbarFadingOffsetBottom
);
2391 // Update toolbar position
2392 if (plugin_size_
.width() < min_toolbar_width
||
2393 plugin_size_
.height() < min_toolbar_height
) {
2394 // Disable toolbar if it does not fit on the screen.
2395 toolbar_
->Show(false, invalidate
);
2398 plugin_size_
.width() - GetToolbarRightOffset() - ctrl_rc
.right(),
2399 plugin_size_
.height() - GetToolbarBottomOffset() - ctrl_rc
.bottom());
2400 toolbar_
->MoveBy(offset
, invalidate
);
2402 int toolbar_width
= std::max(plugin_size_
.width() / 2, min_toolbar_width
);
2403 toolbar_
->ExpandLeft(toolbar_width
- toolbar_
->rect().width());
2404 toolbar_
->Show(painted_first_page_
, invalidate
);
2408 void Instance::UpdateProgressBarPosition(bool invalidate
) {
2409 // TODO(gene): verify we don't overlap with toolbar.
2410 int scrollbar_thickness
= GetScrollbarThickness();
2411 pp::Point
progress_origin(
2412 scrollbar_thickness
+ GetScaled(kProgressOffsetLeft
),
2413 plugin_size_
.height() - progress_bar_
.rect().height() -
2414 scrollbar_thickness
- GetScaled(kProgressOffsetBottom
));
2415 progress_bar_
.MoveTo(progress_origin
, invalidate
);
2418 void Instance::UpdatePageIndicatorPosition(bool invalidate
) {
2419 int32 doc_height
= static_cast<int>(document_size_
.height() * zoom_
);
2421 plugin_size_
.width() - page_indicator_
.rect().width() -
2422 GetScaled(GetScrollbarReservedThickness()),
2423 page_indicator_
.GetYPosition(engine_
->GetVerticalScrollbarYPosition(),
2424 doc_height
, plugin_size_
.height()));
2425 page_indicator_
.MoveTo(origin
, invalidate
);
2428 void Instance::SetZoom(ZoomMode zoom_mode
, double scale
) {
2429 double old_zoom
= zoom_
;
2431 zoom_mode_
= zoom_mode
;
2432 if (zoom_mode_
== ZOOM_SCALE
)
2436 engine_
->ZoomUpdated(zoom_
* device_scale_
);
2437 OnGeometryChanged(old_zoom
, device_scale_
);
2439 // If fit-to-height, snap to the beginning of the most visible page.
2440 if (zoom_mode_
== ZOOM_FIT_TO_PAGE
) {
2441 ScrollToPage(engine_
->GetMostVisiblePage());
2444 // Update sticky buttons to the current zoom style.
2445 Button
* ftp_btn
= static_cast<Button
*>(
2446 toolbar_
->GetControl(kFitToPageButtonId
));
2447 Button
* ftw_btn
= static_cast<Button
*>(
2448 toolbar_
->GetControl(kFitToWidthButtonId
));
2449 switch (zoom_mode_
) {
2450 case ZOOM_FIT_TO_PAGE
:
2451 ftp_btn
->SetPressedState(true);
2452 ftw_btn
->SetPressedState(false);
2454 case ZOOM_FIT_TO_WIDTH
:
2455 ftw_btn
->SetPressedState(true);
2456 ftp_btn
->SetPressedState(false);
2459 ftw_btn
->SetPressedState(false);
2460 ftp_btn
->SetPressedState(false);
2464 void Instance::UpdateZoomScale() {
2465 switch (zoom_mode_
) {
2467 break; // Keep current scale.
2468 case ZOOM_FIT_TO_PAGE
: {
2469 int page_num
= engine_
->GetFirstVisiblePage();
2472 pp::Rect rc
= engine_
->GetPageRect(page_num
);
2475 // Calculate fit to width zoom level.
2476 double ftw_zoom
= static_cast<double>(plugin_dip_size_
.width() -
2477 GetScrollbarReservedThickness()) / document_size_
.width();
2478 // Calculate fit to height zoom level. If document will not fit
2479 // horizontally, adjust zoom level to allow space for horizontal
2482 static_cast<double>(plugin_dip_size_
.height()) / rc
.height();
2483 if (fth_zoom
* document_size_
.width() >
2484 plugin_dip_size_
.width() - GetScrollbarReservedThickness())
2485 fth_zoom
= static_cast<double>(plugin_dip_size_
.height()
2486 - GetScrollbarReservedThickness()) / rc
.height();
2487 zoom_
= std::min(ftw_zoom
, fth_zoom
);
2489 case ZOOM_FIT_TO_WIDTH
:
2491 if (!document_size_
.width())
2493 zoom_
= static_cast<double>(plugin_dip_size_
.width() -
2494 GetScrollbarReservedThickness()) / document_size_
.width();
2495 if (zoom_mode_
== ZOOM_AUTO
&& zoom_
> 1.0)
2499 zoom_
= ClipToRange(zoom_
, kMinZoom
, kMaxZoom
);
2502 double Instance::CalculateZoom(uint32 control_id
) const {
2503 if (control_id
== kZoomInButtonId
) {
2504 for (size_t i
= 0; i
< chrome_page_zoom::kPresetZoomFactorsSize
; ++i
) {
2505 double current_zoom
= chrome_page_zoom::kPresetZoomFactors
[i
];
2506 if (current_zoom
- content::kEpsilon
> zoom_
)
2507 return current_zoom
;
2510 for (size_t i
= chrome_page_zoom::kPresetZoomFactorsSize
; i
> 0; --i
) {
2511 double current_zoom
= chrome_page_zoom::kPresetZoomFactors
[i
- 1];
2512 if (current_zoom
+ content::kEpsilon
< zoom_
)
2513 return current_zoom
;
2519 pp::ImageData
Instance::CreateResourceImage(PP_ResourceImage image_id
) {
2520 pp::ImageData resource_data
;
2521 if (hidpi_enabled_
) {
2523 pp::PDF::GetResourceImageForScale(this, image_id
, device_scale_
);
2526 return resource_data
.data() ? resource_data
2527 : pp::PDF::GetResourceImage(this, image_id
);
2530 std::string
Instance::GetLocalizedString(PP_ResourceString id
) {
2531 pp::Var
rv(pp::PDF::GetLocalizedString(this, id
));
2532 if (!rv
.is_string())
2533 return std::string();
2535 return rv
.AsString();
2538 void Instance::DrawText(const pp::Point
& top_center
, PP_ResourceString id
) {
2539 std::string
str(GetLocalizedString(id
));
2541 pp::FontDescription_Dev description
;
2542 description
.set_family(PP_FONTFAMILY_SANSSERIF
);
2543 description
.set_size(kMessageTextSize
* device_scale_
);
2544 pp::Font_Dev
font(this, description
);
2545 int length
= font
.MeasureSimpleText(str
);
2546 pp::Point
point(top_center
);
2547 point
.set_x(point
.x() - length
/ 2);
2548 DCHECK(!image_data_
.is_null());
2549 font
.DrawSimpleText(&image_data_
, str
, point
, kMessageTextColor
);
2552 void Instance::SetPrintPreviewMode(int page_count
) {
2553 if (!IsPrintPreview() || page_count
<= 0) {
2554 print_preview_page_count_
= 0;
2558 print_preview_page_count_
= page_count
;
2560 engine_
->AppendBlankPages(print_preview_page_count_
);
2561 if (preview_pages_info_
.size() > 0)
2562 LoadAvailablePreviewPage();
2565 bool Instance::IsPrintPreview() {
2566 return IsPrintPreviewUrl(url_
);
2569 int Instance::GetPageNumberToDisplay() {
2570 int page
= engine_
->GetMostVisiblePage();
2571 if (IsPrintPreview() && !print_preview_page_numbers_
.empty()) {
2572 page
= ClipToRange
<int>(page
, 0, print_preview_page_numbers_
.size() - 1);
2573 return print_preview_page_numbers_
[page
];
2578 void Instance::ProcessPreviewPageInfo(const std::string
& url
,
2579 int dst_page_index
) {
2580 if (!IsPrintPreview() || print_preview_page_count_
< 0)
2583 int src_page_index
= ExtractPrintPreviewPageIndex(url
);
2584 if (src_page_index
< 1)
2587 preview_pages_info_
.push(std::make_pair(url
, dst_page_index
));
2588 LoadAvailablePreviewPage();
2591 void Instance::LoadAvailablePreviewPage() {
2592 if (preview_pages_info_
.size() <= 0)
2595 std::string url
= preview_pages_info_
.front().first
;
2596 int dst_page_index
= preview_pages_info_
.front().second
;
2597 int src_page_index
= ExtractPrintPreviewPageIndex(url
);
2598 if (src_page_index
< 1 ||
2599 dst_page_index
>= print_preview_page_count_
||
2600 preview_document_load_state_
== LOAD_STATE_LOADING
) {
2604 preview_document_load_state_
= LOAD_STATE_LOADING
;
2605 LoadPreviewUrl(url
);
2608 void Instance::EnableAutoscroll(const pp::Point
& origin
) {
2612 pp::Size client_size
= plugin_size_
;
2613 if (v_scrollbar_
.get())
2614 client_size
.Enlarge(-GetScrollbarThickness(), 0);
2615 if (h_scrollbar_
.get())
2616 client_size
.Enlarge(0, -GetScrollbarThickness());
2618 // Do not allow autoscroll if client area is too small.
2619 if (autoscroll_anchor_
.size().width() > client_size
.width() ||
2620 autoscroll_anchor_
.size().height() > client_size
.height())
2623 autoscroll_rect_
= pp::Rect(
2624 pp::Point(origin
.x() - autoscroll_anchor_
.size().width() / 2,
2625 origin
.y() - autoscroll_anchor_
.size().height() / 2),
2626 autoscroll_anchor_
.size());
2628 // Make sure autoscroll anchor is in the client area.
2629 if (autoscroll_rect_
.right() > client_size
.width()) {
2630 autoscroll_rect_
.set_x(
2631 client_size
.width() - autoscroll_anchor_
.size().width());
2633 if (autoscroll_rect_
.bottom() > client_size
.height()) {
2634 autoscroll_rect_
.set_y(
2635 client_size
.height() - autoscroll_anchor_
.size().height());
2638 if (autoscroll_rect_
.x() < 0)
2639 autoscroll_rect_
.set_x(0);
2640 if (autoscroll_rect_
.y() < 0)
2641 autoscroll_rect_
.set_y(0);
2643 is_autoscroll_
= true;
2644 Invalidate(kAutoScrollId
, autoscroll_rect_
);
2646 ScheduleTimer(kAutoScrollId
, kAutoScrollTimeoutMs
);
2649 void Instance::DisableAutoscroll() {
2650 if (is_autoscroll_
) {
2651 is_autoscroll_
= false;
2652 Invalidate(kAutoScrollId
, autoscroll_rect_
);
2656 PP_CursorType_Dev
Instance::CalculateAutoscroll(const pp::Point
& mouse_pos
) {
2657 // Scroll only if mouse pointer is outside of the anchor area.
2658 if (autoscroll_rect_
.Contains(mouse_pos
)) {
2661 return PP_CURSORTYPE_MIDDLEPANNING
;
2664 // Relative position to the center of anchor area.
2665 pp::Point rel_pos
= mouse_pos
- autoscroll_rect_
.CenterPoint();
2667 // Calculate angle from the X axis. Angle is in range from -pi to pi.
2668 double angle
= atan2(static_cast<double>(rel_pos
.y()),
2669 static_cast<double>(rel_pos
.x()));
2671 autoscroll_x_
= rel_pos
.x() * kAutoScrollFactor
;
2672 autoscroll_y_
= rel_pos
.y() * kAutoScrollFactor
;
2674 // Angle is from -pi to pi. Screen Y is increasing toward bottom,
2675 // so negative angle represent north direction.
2676 if (angle
< - (M_PI
* 7.0 / 8.0)) {
2678 return PP_CURSORTYPE_WESTPANNING
;
2679 } else if (angle
< - (M_PI
* 5.0 / 8.0)) {
2681 return PP_CURSORTYPE_NORTHWESTPANNING
;
2682 } else if (angle
< - (M_PI
* 3.0 / 8.0)) {
2684 return PP_CURSORTYPE_NORTHPANNING
;
2685 } else if (angle
< - (M_PI
* 1.0 / 8.0)) {
2687 return PP_CURSORTYPE_NORTHEASTPANNING
;
2688 } else if (angle
< M_PI
* 1.0 / 8.0) {
2690 return PP_CURSORTYPE_EASTPANNING
;
2691 } else if (angle
< M_PI
* 3.0 / 8.0) {
2693 return PP_CURSORTYPE_SOUTHEASTPANNING
;
2694 } else if (angle
< M_PI
* 5.0 / 8.0) {
2696 return PP_CURSORTYPE_SOUTHPANNING
;
2697 } else if (angle
< M_PI
* 7.0 / 8.0) {
2699 return PP_CURSORTYPE_SOUTHWESTPANNING
;
2702 // went around the circle, going west again
2703 return PP_CURSORTYPE_WESTPANNING
;
2706 void Instance::ConfigureNumberImageGenerator() {
2707 std::vector
<pp::ImageData
> num_images
= GetThumbnailResources();
2708 pp::ImageData number_background
= CreateResourceImage(
2709 PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_NUM_BACKGROUND
);
2710 number_image_generator_
->Configure(number_background
,
2715 NumberImageGenerator
* Instance::number_image_generator() {
2716 if (!number_image_generator_
.get()) {
2717 number_image_generator_
.reset(new NumberImageGenerator(this));
2718 ConfigureNumberImageGenerator();
2720 return number_image_generator_
.get();
2723 int Instance::GetScaled(int x
) const {
2724 return static_cast<int>(x
* device_scale_
);
2727 void Instance::UserMetricsRecordAction(const std::string
& action
) {
2728 pp::PDF::UserMetricsRecordAction(this, pp::Var(action
));
2731 PDFScriptableObject::PDFScriptableObject(Instance
* instance
)
2732 : instance_(instance
) {
2735 PDFScriptableObject::~PDFScriptableObject() {
2738 bool PDFScriptableObject::HasMethod(const pp::Var
& name
, pp::Var
* exception
) {
2739 return instance_
->HasScriptableMethod(name
, exception
);
2742 pp::Var
PDFScriptableObject::Call(const pp::Var
& method
,
2743 const std::vector
<pp::Var
>& args
,
2744 pp::Var
* exception
) {
2745 return instance_
->CallScriptableMethod(method
, args
, exception
);
2748 } // namespace chrome_pdf