1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "pdf/instance.h"
7 #include <algorithm> // for min()
8 #define _USE_MATH_DEFINES // for M_PI
9 #include <cmath> // for log() and pow()
13 #include "base/json/json_reader.h"
14 #include "base/json/json_writer.h"
15 #include "base/logging.h"
16 #include "base/strings/string_number_conversions.h"
17 #include "base/strings/string_split.h"
18 #include "base/strings/string_util.h"
19 #include "base/values.h"
20 #include "chrome/common/content_restriction.h"
21 #include "components/ui/zoom/page_zoom_constants.h"
22 #include "content/public/common/page_zoom.h"
23 #include "net/base/escape.h"
24 #include "pdf/draw_utils.h"
25 #include "pdf/number_image_generator.h"
27 #include "pdf/resource_consts.h"
28 #include "ppapi/c/dev/ppb_cursor_control_dev.h"
29 #include "ppapi/c/pp_errors.h"
30 #include "ppapi/c/pp_rect.h"
31 #include "ppapi/c/private/ppp_pdf.h"
32 #include "ppapi/c/trusted/ppb_url_loader_trusted.h"
33 #include "ppapi/cpp/core.h"
34 #include "ppapi/cpp/dev/font_dev.h"
35 #include "ppapi/cpp/dev/memory_dev.h"
36 #include "ppapi/cpp/dev/text_input_dev.h"
37 #include "ppapi/cpp/module.h"
38 #include "ppapi/cpp/point.h"
39 #include "ppapi/cpp/private/pdf.h"
40 #include "ppapi/cpp/rect.h"
41 #include "ppapi/cpp/resource.h"
42 #include "ppapi/cpp/url_request_info.h"
43 #include "ui/events/keycodes/keyboard_codes.h"
45 #if defined(OS_MACOSX)
46 #include "base/mac/mac_util.h"
49 namespace chrome_pdf
{
51 struct ToolbarButtonInfo
{
53 Button::ButtonStyle style
;
54 PP_ResourceImage normal
;
55 PP_ResourceImage highlighted
;
56 PP_ResourceImage pressed
;
59 const uint32 kBackgroundColor
= 0xFFCCCCCC;
63 // Uncomment following #define to enable thumbnails.
64 // #define ENABLE_THUMBNAILS
66 const uint32 kToolbarSplashTimeoutMs
= 6000;
67 const uint32 kMessageTextColor
= 0xFF575757;
68 const uint32 kMessageTextSize
= 22;
69 const uint32 kProgressFadeTimeoutMs
= 250;
70 const uint32 kProgressDelayTimeoutMs
= 1000;
71 const uint32 kAutoScrollTimeoutMs
= 50;
72 const double kAutoScrollFactor
= 0.2;
74 // Javascript methods.
75 const char kJSAccessibility
[] = "accessibility";
76 const char kJSDocumentLoadComplete
[] = "documentLoadComplete";
77 const char kJSGetHeight
[] = "getHeight";
78 const char kJSGetHorizontalScrollbarThickness
[] =
79 "getHorizontalScrollbarThickness";
80 const char kJSGetPageLocationNormalized
[] = "getPageLocationNormalized";
81 const char kJSGetSelectedText
[] = "getSelectedText";
82 const char kJSGetVerticalScrollbarThickness
[] = "getVerticalScrollbarThickness";
83 const char kJSGetWidth
[] = "getWidth";
84 const char kJSGetZoomLevel
[] = "getZoomLevel";
85 const char kJSGoToPage
[] = "goToPage";
86 const char kJSGrayscale
[] = "grayscale";
87 const char kJSLoadPreviewPage
[] = "loadPreviewPage";
88 const char kJSOnLoad
[] = "onload";
89 const char kJSOnPluginSizeChanged
[] = "onPluginSizeChanged";
90 const char kJSOnScroll
[] = "onScroll";
91 const char kJSPageXOffset
[] = "pageXOffset";
92 const char kJSPageYOffset
[] = "pageYOffset";
93 const char kJSPrintPreviewPageCount
[] = "printPreviewPageCount";
94 const char kJSReload
[] = "reload";
95 const char kJSRemovePrintButton
[] = "removePrintButton";
96 const char kJSResetPrintPreviewUrl
[] = "resetPrintPreviewUrl";
97 const char kJSSendKeyEvent
[] = "sendKeyEvent";
98 const char kJSSetPageNumbers
[] = "setPageNumbers";
99 const char kJSSetPageXOffset
[] = "setPageXOffset";
100 const char kJSSetPageYOffset
[] = "setPageYOffset";
101 const char kJSSetZoomLevel
[] = "setZoomLevel";
102 const char kJSZoomFitToHeight
[] = "fitToHeight";
103 const char kJSZoomFitToWidth
[] = "fitToWidth";
104 const char kJSZoomIn
[] = "zoomIn";
105 const char kJSZoomOut
[] = "zoomOut";
107 // URL reference parameters.
108 // For more possible parameters, see RFC 3778 and the "PDF Open Parameters"
109 // document from Adobe.
110 const char kDelimiters
[] = "#&";
111 const char kNamedDest
[] = "nameddest";
112 const char kPage
[] = "page";
114 const char kChromePrint
[] = "chrome://print/";
116 // Dictionary Value key names for the document accessibility info
117 const char kAccessibleNumberOfPages
[] = "numberOfPages";
118 const char kAccessibleLoaded
[] = "loaded";
119 const char kAccessibleCopyable
[] = "copyable";
121 const ToolbarButtonInfo kPDFToolbarButtons
[] = {
122 { kFitToPageButtonId
, Button::BUTTON_STATE
,
123 PP_RESOURCEIMAGE_PDF_BUTTON_FTP
,
124 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_HOVER
,
125 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_PRESSED
},
126 { kFitToWidthButtonId
, Button::BUTTON_STATE
,
127 PP_RESOURCEIMAGE_PDF_BUTTON_FTW
,
128 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_HOVER
,
129 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_PRESSED
},
130 { kZoomOutButtonId
, Button::BUTTON_CLICKABLE
,
131 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT
,
132 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_HOVER
,
133 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_PRESSED
},
134 { kZoomInButtonId
, Button::BUTTON_CLICKABLE
,
135 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN
,
136 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_HOVER
,
137 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_PRESSED
},
138 { kSaveButtonId
, Button::BUTTON_CLICKABLE
,
139 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE
,
140 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE_HOVER
,
141 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE_PRESSED
},
142 { kPrintButtonId
, Button::BUTTON_CLICKABLE
,
143 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT
,
144 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_HOVER
,
145 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_PRESSED
},
148 const ToolbarButtonInfo kPDFNoPrintToolbarButtons
[] = {
149 { kFitToPageButtonId
, Button::BUTTON_STATE
,
150 PP_RESOURCEIMAGE_PDF_BUTTON_FTP
,
151 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_HOVER
,
152 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_PRESSED
},
153 { kFitToWidthButtonId
, Button::BUTTON_STATE
,
154 PP_RESOURCEIMAGE_PDF_BUTTON_FTW
,
155 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_HOVER
,
156 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_PRESSED
},
157 { kZoomOutButtonId
, Button::BUTTON_CLICKABLE
,
158 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT
,
159 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_HOVER
,
160 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_PRESSED
},
161 { kZoomInButtonId
, Button::BUTTON_CLICKABLE
,
162 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN
,
163 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_HOVER
,
164 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_PRESSED
},
165 { kSaveButtonId
, Button::BUTTON_CLICKABLE
,
166 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE
,
167 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE_HOVER
,
168 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE_PRESSED
},
169 { kPrintButtonId
, Button::BUTTON_CLICKABLE
,
170 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_DISABLED
,
171 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_DISABLED
,
172 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_DISABLED
}
175 const ToolbarButtonInfo kPrintPreviewToolbarButtons
[] = {
176 { kFitToPageButtonId
, Button::BUTTON_STATE
,
177 PP_RESOURCEIMAGE_PDF_BUTTON_FTP
,
178 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_HOVER
,
179 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_PRESSED
},
180 { kFitToWidthButtonId
, Button::BUTTON_STATE
,
181 PP_RESOURCEIMAGE_PDF_BUTTON_FTW
,
182 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_HOVER
,
183 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_PRESSED
},
184 { kZoomOutButtonId
, Button::BUTTON_CLICKABLE
,
185 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT
,
186 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_HOVER
,
187 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_PRESSED
},
188 { kZoomInButtonId
, Button::BUTTON_CLICKABLE
,
189 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_END
,
190 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_END_HOVER
,
191 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_END_PRESSED
},
194 static const char kPPPPdfInterface
[] = PPP_PDF_INTERFACE_1
;
196 PP_Var
GetLinkAtPosition(PP_Instance instance
, PP_Point point
) {
199 pp::Instance::GetPerInstanceObject(instance
, kPPPPdfInterface
);
201 var
= static_cast<Instance
*>(object
)->GetLinkAtPosition(pp::Point(point
));
205 void Transform(PP_Instance instance
, PP_PrivatePageTransformType type
) {
207 pp::Instance::GetPerInstanceObject(instance
, kPPPPdfInterface
);
209 Instance
* obj_instance
= static_cast<Instance
*>(object
);
211 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CW
:
212 obj_instance
->RotateClockwise();
214 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CCW
:
215 obj_instance
->RotateCounterclockwise();
221 PP_Bool
GetPrintPresetOptionsFromDocument(
222 PP_Instance instance
,
223 PP_PdfPrintPresetOptions_Dev
* options
) {
224 void* object
= pp::Instance::GetPerInstanceObject(instance
, kPPPPdfInterface
);
226 Instance
* obj_instance
= static_cast<Instance
*>(object
);
227 obj_instance
->GetPrintPresetOptionsFromDocument(options
);
232 const PPP_Pdf ppp_private
= {
235 &GetPrintPresetOptionsFromDocument
238 int ExtractPrintPreviewPageIndex(const std::string
& src_url
) {
239 // Sample |src_url| format: chrome://print/id/page_index/print.pdf
240 std::vector
<std::string
> url_substr
;
241 base::SplitString(src_url
.substr(strlen(kChromePrint
)), '/', &url_substr
);
242 if (url_substr
.size() != 3)
245 if (url_substr
[2] != "print.pdf")
249 if (!base::StringToInt(url_substr
[1], &page_index
))
254 bool IsPrintPreviewUrl(const std::string
& url
) {
255 return url
.substr(0, strlen(kChromePrint
)) == kChromePrint
;
258 void ScalePoint(float scale
, pp::Point
* point
) {
259 point
->set_x(static_cast<int>(point
->x() * scale
));
260 point
->set_y(static_cast<int>(point
->y() * scale
));
263 void ScaleRect(float scale
, pp::Rect
* rect
) {
264 int left
= static_cast<int>(floorf(rect
->x() * scale
));
265 int top
= static_cast<int>(floorf(rect
->y() * scale
));
266 int right
= static_cast<int>(ceilf((rect
->x() + rect
->width()) * scale
));
267 int bottom
= static_cast<int>(ceilf((rect
->y() + rect
->height()) * scale
));
268 rect
->SetRect(left
, top
, right
- left
, bottom
- top
);
272 T
ClipToRange(T value
, T lower_boundary
, T upper_boundary
) {
273 DCHECK(lower_boundary
<= upper_boundary
);
274 return std::max
<T
>(lower_boundary
, std::min
<T
>(value
, upper_boundary
));
279 Instance::Instance(PP_Instance instance
)
280 : pp::InstancePrivate(instance
),
281 pp::Find_Private(this),
282 pp::Printing_Dev(this),
283 pp::Selection_Dev(this),
284 pp::WidgetClient_Dev(this),
286 cursor_(PP_CURSORTYPE_POINTER
),
287 timer_pending_(false),
288 current_timer_id_(0),
291 printing_enabled_(true),
292 hidpi_enabled_(false),
293 full_(IsFullFrame()),
294 zoom_mode_(full_
? ZOOM_AUTO
: ZOOM_SCALE
),
295 did_call_start_loading_(false),
296 is_autoscroll_(false),
297 scrollbar_thickness_(-1),
298 scrollbar_reserved_thickness_(-1),
299 current_tb_info_(NULL
),
300 current_tb_info_size_(0),
301 paint_manager_(this, this, true),
302 delayed_progress_timer_id_(0),
304 painted_first_page_(false),
305 show_page_indicator_(false),
306 document_load_state_(LOAD_STATE_LOADING
),
307 preview_document_load_state_(LOAD_STATE_COMPLETE
),
308 told_browser_about_unsupported_feature_(false),
309 print_preview_page_count_(0) {
310 loader_factory_
.Initialize(this);
311 timer_factory_
.Initialize(this);
312 form_factory_
.Initialize(this);
313 callback_factory_
.Initialize(this);
314 engine_
.reset(PDFEngine::Create(this));
315 pp::Module::Get()->AddPluginInterface(kPPPPdfInterface
, &ppp_private
);
316 AddPerInstanceObject(kPPPPdfInterface
, this);
318 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_MOUSE
);
319 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_WHEEL
);
320 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_KEYBOARD
);
321 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_TOUCH
);
324 Instance::~Instance() {
325 if (timer_pending_
) {
326 timer_factory_
.CancelAll();
327 timer_pending_
= false;
329 // The engine may try to access this instance during its destruction.
330 // Make sure this happens early while the instance is still intact.
332 RemovePerInstanceObject(kPPPPdfInterface
, this);
335 bool Instance::Init(uint32_t argc
, const char* argn
[], const char* argv
[]) {
336 // For now, we hide HiDPI support behind a flag.
337 if (pp::PDF::IsFeatureEnabled(this, PP_PDFFEATURE_HIDPI
))
338 hidpi_enabled_
= true;
340 printing_enabled_
= pp::PDF::IsFeatureEnabled(this, PP_PDFFEATURE_PRINTING
);
341 if (printing_enabled_
) {
342 CreateToolbar(kPDFToolbarButtons
, arraysize(kPDFToolbarButtons
));
344 CreateToolbar(kPDFNoPrintToolbarButtons
,
345 arraysize(kPDFNoPrintToolbarButtons
));
350 // Load autoscroll anchor image.
352 CreateResourceImage(PP_RESOURCEIMAGE_PDF_PAN_SCROLL_ICON
);
354 #ifdef ENABLE_THUMBNAILS
357 const char* url
= NULL
;
358 for (uint32_t i
= 0; i
< argc
; ++i
) {
359 if (strcmp(argn
[i
], "src") == 0) {
368 CreatePageIndicator(IsPrintPreviewUrl(url
));
371 // For PDFs embedded in a frame, we don't get the data automatically like we
372 // do for full-frame loads. Start loading the data manually.
375 DCHECK(!did_call_start_loading_
);
376 pp::PDF::DidStartLoading(this);
377 did_call_start_loading_
= true;
380 ZoomLimitsChanged(kMinZoom
, kMaxZoom
);
382 text_input_
.reset(new pp::TextInput_Dev(this));
385 return engine_
->New(url
);
388 bool Instance::HandleDocumentLoad(const pp::URLLoader
& loader
) {
389 delayed_progress_timer_id_
= ScheduleTimer(kProgressBarId
,
390 kProgressDelayTimeoutMs
);
391 return engine_
->HandleDocumentLoad(loader
);
394 bool Instance::HandleInputEvent(const pp::InputEvent
& event
) {
395 // To simplify things, convert the event into device coordinates if it is
397 pp::InputEvent
event_device_res(event
);
399 pp::MouseInputEvent
mouse_event(event
);
400 if (!mouse_event
.is_null()) {
401 pp::Point point
= mouse_event
.GetPosition();
402 pp::Point movement
= mouse_event
.GetMovement();
403 ScalePoint(device_scale_
, &point
);
404 ScalePoint(device_scale_
, &movement
);
405 mouse_event
= pp::MouseInputEvent(
408 event
.GetTimeStamp(),
409 event
.GetModifiers(),
410 mouse_event
.GetButton(),
412 mouse_event
.GetClickCount(),
414 event_device_res
= mouse_event
;
418 // Check if we need to go to autoscroll mode.
419 if (event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE
&&
420 (event
.GetModifiers() & PP_INPUTEVENT_MODIFIER_MIDDLEBUTTONDOWN
)) {
421 pp::MouseInputEvent
mouse_event(event_device_res
);
422 pp::Point pos
= mouse_event
.GetPosition();
423 EnableAutoscroll(pos
);
424 UpdateCursor(CalculateAutoscroll(pos
));
427 // Quit autoscrolling on any other event.
431 #ifdef ENABLE_THUMBNAILS
432 if (event
.GetType() == PP_INPUTEVENT_TYPE_MOUSELEAVE
)
433 thumbnails_
.SlideOut();
435 if (thumbnails_
.HandleEvent(event_device_res
))
439 if (!IsMouseOnScrollbar(event_device_res
) &&
440 toolbar_
->HandleEvent(event_device_res
))
443 #ifdef ENABLE_THUMBNAILS
444 if (v_scrollbar_
.get() && event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE
) {
445 pp::MouseInputEvent
mouse_event(event
);
446 pp::Point pt
= mouse_event
.GetPosition();
447 pp::Rect v_scrollbar_rc
;
448 v_scrollbar_
->GetLocation(&v_scrollbar_rc
);
449 // There is a bug (https://bugs.webkit.org/show_bug.cgi?id=45208)
450 // in the webkit that makes event.u.mouse.button
451 // equal to PP_INPUTEVENT_MOUSEBUTTON_LEFT, even when no button is pressed.
452 // To work around this issue we use modifier for now, and will switch
453 // to button once the bug is fixed and webkit got merged back to our tree.
454 if (v_scrollbar_rc
.Contains(pt
) &&
455 (event
.GetModifiers() & PP_INPUTEVENT_MODIFIER_LEFTBUTTONDOWN
)) {
456 thumbnails_
.SlideIn();
459 // When scrollbar is in the scrolling mode we should display thumbnails
460 // even the mouse is outside the thumbnail and scrollbar areas.
461 // If mouse is outside plugin area, we are still getting mouse move events
462 // while scrolling. See bug description for details:
463 // http://code.google.com/p/chromium/issues/detail?id=56444
464 if (!v_scrollbar_rc
.Contains(pt
) && thumbnails_
.visible() &&
465 !(event
.GetModifiers() & PP_INPUTEVENT_MODIFIER_LEFTBUTTONDOWN
) &&
466 !thumbnails_
.rect().Contains(pt
)) {
467 thumbnails_
.SlideOut();
472 // Need to pass the event to the engine first, since if we're over an edit
473 // control we want it to get keyboard events (like space) instead of the
475 // TODO: will have to offset the mouse coordinates once we support bidi and
476 // there could be scrollbars on the left.
477 pp::InputEvent
offset_event(event_device_res
);
478 bool try_engine_first
= true;
479 switch (offset_event
.GetType()) {
480 case PP_INPUTEVENT_TYPE_MOUSEDOWN
:
481 case PP_INPUTEVENT_TYPE_MOUSEUP
:
482 case PP_INPUTEVENT_TYPE_MOUSEMOVE
:
483 case PP_INPUTEVENT_TYPE_MOUSEENTER
:
484 case PP_INPUTEVENT_TYPE_MOUSELEAVE
: {
485 pp::MouseInputEvent
mouse_event(event_device_res
);
486 pp::MouseInputEvent
mouse_event_dip(event
);
487 pp::Point point
= mouse_event
.GetPosition();
488 point
.set_x(point
.x() - available_area_
.x());
489 offset_event
= pp::MouseInputEvent(
492 event
.GetTimeStamp(),
493 event
.GetModifiers(),
494 mouse_event
.GetButton(),
496 mouse_event
.GetClickCount(),
497 mouse_event
.GetMovement());
498 if (!engine_
->IsSelecting()) {
499 if (!IsOverlayScrollbar() &&
500 !available_area_
.Contains(mouse_event
.GetPosition())) {
501 try_engine_first
= false;
502 } else if (IsOverlayScrollbar() && IsMouseOnScrollbar(event
)) {
503 try_engine_first
= false;
511 if (try_engine_first
&& engine_
->HandleEvent(offset_event
))
514 // Left/Right arrows should scroll to the beginning of the Prev/Next page if
515 // there is no horizontal scroll bar.
516 // If fit-to-height, PgDown/PgUp should scroll to the beginning of the
517 // Prev/Next page. Spacebar / shift+spacebar should do the same.
518 if (v_scrollbar_
.get() && event
.GetType() == PP_INPUTEVENT_TYPE_KEYDOWN
) {
519 pp::KeyboardInputEvent
keyboard_event(event
);
520 bool no_h_scrollbar
= !h_scrollbar_
.get();
521 uint32_t key_code
= keyboard_event
.GetKeyCode();
522 bool has_modifiers
= keyboard_event
.GetModifiers() != 0;
524 no_h_scrollbar
&& !has_modifiers
&& key_code
== ui::VKEY_RIGHT
;
526 no_h_scrollbar
&& !has_modifiers
&& key_code
== ui::VKEY_LEFT
;
527 if (zoom_mode_
== ZOOM_FIT_TO_PAGE
) {
529 keyboard_event
.GetModifiers() & PP_INPUTEVENT_MODIFIER_SHIFTKEY
;
530 bool key_is_space
= key_code
== ui::VKEY_SPACE
;
531 page_down
|= key_is_space
|| key_code
== ui::VKEY_NEXT
;
532 page_up
|= (key_is_space
&& has_shift
) || (key_code
== ui::VKEY_PRIOR
);
535 int page
= engine_
->GetFirstVisiblePage();
538 // Engine calculates visible page including delimiter to the page size.
539 // We need to check here if the page itself is completely out of view and
540 // scroll to the next one in that case.
541 if (engine_
->GetPageRect(page
).bottom() * zoom_
<=
542 v_scrollbar_
->GetValue())
544 ScrollToPage(page
+ 1);
545 UpdateCursor(PP_CURSORTYPE_POINTER
);
547 } else if (page_up
) {
548 int page
= engine_
->GetFirstVisiblePage();
551 if (engine_
->GetPageRect(page
).y() * zoom_
>= v_scrollbar_
->GetValue())
554 UpdateCursor(PP_CURSORTYPE_POINTER
);
559 if (v_scrollbar_
.get() && v_scrollbar_
->HandleEvent(event
)) {
560 UpdateCursor(PP_CURSORTYPE_POINTER
);
564 if (h_scrollbar_
.get() && h_scrollbar_
->HandleEvent(event
)) {
565 UpdateCursor(PP_CURSORTYPE_POINTER
);
569 if (timer_pending_
&&
570 (event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEUP
||
571 event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE
)) {
572 timer_factory_
.CancelAll();
573 timer_pending_
= false;
574 } else if (event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE
&&
575 engine_
->IsSelecting()) {
576 bool set_timer
= false;
577 pp::MouseInputEvent
mouse_event(event
);
578 if (v_scrollbar_
.get() &&
579 (mouse_event
.GetPosition().y() <= 0 ||
580 mouse_event
.GetPosition().y() >= (plugin_dip_size_
.height() - 1))) {
581 v_scrollbar_
->ScrollBy(
582 PP_SCROLLBY_LINE
, mouse_event
.GetPosition().y() >= 0 ? 1: -1);
585 if (h_scrollbar_
.get() &&
586 (mouse_event
.GetPosition().x() <= 0 ||
587 mouse_event
.GetPosition().x() >= (plugin_dip_size_
.width() - 1))) {
588 h_scrollbar_
->ScrollBy(PP_SCROLLBY_LINE
,
589 mouse_event
.GetPosition().x() >= 0 ? 1: -1);
594 last_mouse_event_
= pp::MouseInputEvent(event
);
596 pp::CompletionCallback callback
=
597 timer_factory_
.NewCallback(&Instance::OnTimerFired
);
598 pp::Module::Get()->core()->CallOnMainThread(kDragTimerMs
, callback
);
599 timer_pending_
= true;
603 if (event
.GetType() == PP_INPUTEVENT_TYPE_KEYDOWN
) {
604 pp::KeyboardInputEvent
keyboard_event(event
);
605 const uint32 modifier
= event
.GetModifiers();
606 if (modifier
& kDefaultKeyModifier
) {
607 switch (keyboard_event
.GetKeyCode()) {
609 engine_
->SelectAll();
613 if (modifier
& PP_INPUTEVENT_MODIFIER_CONTROLKEY
) {
614 switch (keyboard_event
.GetKeyCode()) {
617 engine_
->RotateCounterclockwise();
621 engine_
->RotateClockwise();
627 // Return true for unhandled clicks so the plugin takes focus.
628 return (event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN
);
631 void Instance::DidChangeView(const pp::View
& view
) {
632 pp::Rect
view_rect(view
.GetRect());
633 float device_scale
= 1.0f
;
634 float old_device_scale
= device_scale_
;
636 device_scale
= view
.GetDeviceScale();
637 pp::Size
view_device_size(view_rect
.width() * device_scale
,
638 view_rect
.height() * device_scale
);
639 if (view_device_size
== plugin_size_
&& device_scale
== device_scale_
)
640 return; // We don't care about the position, only the size.
642 image_data_
= pp::ImageData();
643 device_scale_
= device_scale
;
644 plugin_dip_size_
= view_rect
.size();
645 plugin_size_
= view_device_size
;
647 paint_manager_
.SetSize(view_device_size
, device_scale_
);
649 image_data_
= pp::ImageData(this,
650 PP_IMAGEDATAFORMAT_BGRA_PREMUL
,
653 if (image_data_
.is_null()) {
654 DCHECK(plugin_size_
.IsEmpty());
658 // View dimensions changed, disable autoscroll (if it was enabled).
661 OnGeometryChanged(zoom_
, old_device_scale
);
664 pp::Var
Instance::GetInstanceObject() {
665 if (instance_object_
.is_undefined()) {
666 PDFScriptableObject
* object
= new PDFScriptableObject(this);
667 // The pp::Var takes ownership of object here.
668 instance_object_
= pp::VarPrivate(this, object
);
671 return instance_object_
;
674 void Instance::GetPrintPresetOptionsFromDocument(
675 PP_PdfPrintPresetOptions_Dev
* options
) {
676 options
->is_scaling_disabled
= PP_FromBool(IsPrintScalingDisabled());
678 static_cast<PP_PrivateDuplexMode_Dev
>(engine_
->GetDuplexType());
679 options
->copies
= engine_
->GetCopiesToPrint();
680 pp::Size uniform_page_size
;
681 options
->is_page_size_uniform
=
682 PP_FromBool(engine_
->GetPageSizeAndUniformity(&uniform_page_size
));
683 options
->uniform_page_size
= PP_Size(uniform_page_size
);
686 pp::Var
Instance::GetLinkAtPosition(const pp::Point
& point
) {
687 pp::Point
offset_point(point
);
688 ScalePoint(device_scale_
, &offset_point
);
689 offset_point
.set_x(offset_point
.x() - available_area_
.x());
690 return engine_
->GetLinkAtPosition(offset_point
);
693 pp::Var
Instance::GetSelectedText(bool html
) {
696 return engine_
->GetSelectedText();
699 void Instance::InvalidateWidget(pp::Widget_Dev widget
,
700 const pp::Rect
& dirty_rect
) {
701 if (v_scrollbar_
.get() && *v_scrollbar_
== widget
) {
702 if (!image_data_
.is_null())
703 v_scrollbar_
->Paint(dirty_rect
.pp_rect(), &image_data_
);
704 } else if (h_scrollbar_
.get() && *h_scrollbar_
== widget
) {
705 if (!image_data_
.is_null())
706 h_scrollbar_
->Paint(dirty_rect
.pp_rect(), &image_data_
);
708 // Possible to hit this condition since sometimes the scrollbar codes posts
709 // a task to do something later, and we could have deleted our reference in
714 pp::Rect dirty_rect_scaled
= dirty_rect
;
715 ScaleRect(device_scale_
, &dirty_rect_scaled
);
716 paint_manager_
.InvalidateRect(dirty_rect_scaled
);
719 void Instance::ScrollbarValueChanged(pp::Scrollbar_Dev scrollbar
,
721 value
= GetScaled(value
);
722 if (v_scrollbar_
.get() && *v_scrollbar_
== scrollbar
) {
723 engine_
->ScrolledToYPosition(value
);
725 v_scrollbar_
->GetLocation(&rc
);
726 int32 doc_height
= GetDocumentPixelHeight();
727 doc_height
-= GetScaled(rc
.height());
728 #ifdef ENABLE_THUMBNAILS
729 if (thumbnails_
.visible()) {
730 thumbnails_
.SetPosition(value
, doc_height
, true);
734 plugin_size_
.width() - page_indicator_
.rect().width() -
735 GetScaled(GetScrollbarReservedThickness()),
736 page_indicator_
.GetYPosition(value
, doc_height
, plugin_size_
.height()));
737 page_indicator_
.MoveTo(origin
, page_indicator_
.visible());
738 } else if (h_scrollbar_
.get() && *h_scrollbar_
== scrollbar
) {
739 engine_
->ScrolledToXPosition(value
);
743 void Instance::ScrollbarOverlayChanged(pp::Scrollbar_Dev scrollbar
,
745 scrollbar_reserved_thickness_
= overlay
? 0 : scrollbar_thickness_
;
746 OnGeometryChanged(zoom_
, device_scale_
);
749 uint32_t Instance::QuerySupportedPrintOutputFormats() {
750 return engine_
->QuerySupportedPrintOutputFormats();
753 int32_t Instance::PrintBegin(const PP_PrintSettings_Dev
& print_settings
) {
754 // For us num_pages is always equal to the number of pages in the PDF
755 // document irrespective of the printable area.
756 int32_t ret
= engine_
->GetNumberOfPages();
760 uint32_t supported_formats
= engine_
->QuerySupportedPrintOutputFormats();
761 if ((print_settings
.format
& supported_formats
) == 0)
764 print_settings_
.is_printing
= true;
765 print_settings_
.pepper_print_settings
= print_settings
;
766 engine_
->PrintBegin();
770 pp::Resource
Instance::PrintPages(
771 const PP_PrintPageNumberRange_Dev
* page_ranges
,
772 uint32_t page_range_count
) {
773 if (!print_settings_
.is_printing
)
774 return pp::Resource();
776 print_settings_
.print_pages_called_
= true;
777 return engine_
->PrintPages(page_ranges
, page_range_count
,
778 print_settings_
.pepper_print_settings
);
781 void Instance::PrintEnd() {
782 if (print_settings_
.print_pages_called_
)
783 UserMetricsRecordAction("PDF.PrintPage");
784 print_settings_
.Clear();
788 bool Instance::IsPrintScalingDisabled() {
789 return !engine_
->GetPrintScaling();
792 bool Instance::StartFind(const std::string
& text
, bool case_sensitive
) {
793 engine_
->StartFind(text
.c_str(), case_sensitive
);
797 void Instance::SelectFindResult(bool forward
) {
798 engine_
->SelectFindResult(forward
);
801 void Instance::StopFind() {
805 void Instance::Zoom(double scale
, bool text_only
) {
806 UserMetricsRecordAction("PDF.ZoomFromBrowser");
808 // If the zoom level doesn't change it means that this zoom change might have
809 // been initiated by the plugin. In that case, we don't want to change the
810 // zoom mode to ZOOM_SCALE as it may have been intentionally set to
811 // ZOOM_FIT_TO_PAGE or some other value when the zoom was last changed.
815 SetZoom(ZOOM_SCALE
, scale
);
818 void Instance::ZoomChanged(double factor
) {
820 Zoom_Dev::ZoomChanged(factor
);
823 void Instance::OnPaint(const std::vector
<pp::Rect
>& paint_rects
,
824 std::vector
<PaintManager::ReadyRect
>* ready
,
825 std::vector
<pp::Rect
>* pending
) {
826 if (image_data_
.is_null()) {
827 DCHECK(plugin_size_
.IsEmpty());
831 first_paint_
= false;
832 pp::Rect rect
= pp::Rect(pp::Point(), plugin_size_
);
833 FillRect(rect
, kBackgroundColor
);
834 ready
->push_back(PaintManager::ReadyRect(rect
, image_data_
, true));
835 *pending
= paint_rects
;
841 for (size_t i
= 0; i
< paint_rects
.size(); i
++) {
842 // Intersect with plugin area since there could be pending invalidates from
843 // when the plugin area was larger.
845 paint_rects
[i
].Intersect(pp::Rect(pp::Point(), plugin_size_
));
849 pp::Rect pdf_rect
= available_area_
.Intersect(rect
);
850 if (!pdf_rect
.IsEmpty()) {
851 pdf_rect
.Offset(available_area_
.x() * -1, 0);
853 std::vector
<pp::Rect
> pdf_ready
;
854 std::vector
<pp::Rect
> pdf_pending
;
855 engine_
->Paint(pdf_rect
, &image_data_
, &pdf_ready
, &pdf_pending
);
856 for (size_t j
= 0; j
< pdf_ready
.size(); ++j
) {
857 pdf_ready
[j
].Offset(available_area_
.point());
859 PaintManager::ReadyRect(pdf_ready
[j
], image_data_
, false));
861 for (size_t j
= 0; j
< pdf_pending
.size(); ++j
) {
862 pdf_pending
[j
].Offset(available_area_
.point());
863 pending
->push_back(pdf_pending
[j
]);
867 for (size_t j
= 0; j
< background_parts_
.size(); ++j
) {
868 pp::Rect intersection
= background_parts_
[j
].location
.Intersect(rect
);
869 if (!intersection
.IsEmpty()) {
870 FillRect(intersection
, background_parts_
[j
].color
);
872 PaintManager::ReadyRect(intersection
, image_data_
, false));
876 if (document_load_state_
== LOAD_STATE_FAILED
) {
877 pp::Point top_center
;
878 top_center
.set_x(plugin_size_
.width() / 2);
879 top_center
.set_y(plugin_size_
.height() / 2);
880 DrawText(top_center
, PP_RESOURCESTRING_PDFLOAD_FAILED
);
883 #ifdef ENABLE_THUMBNAILS
884 thumbnails_
.Paint(&image_data_
, rect
);
888 engine_
->PostPaint();
890 // Must paint scrollbars after the background parts, in case we have an
891 // overlay scrollbar that's over the background. We also do this in a separate
892 // loop because the scrollbar painting logic uses the signal of whether there
893 // are pending paints or not to figure out if it should draw right away or
895 for (size_t i
= 0; i
< paint_rects
.size(); i
++) {
896 PaintIfWidgetIntersects(h_scrollbar_
.get(), paint_rects
[i
], ready
, pending
);
897 PaintIfWidgetIntersects(v_scrollbar_
.get(), paint_rects
[i
], ready
, pending
);
900 if (progress_bar_
.visible())
901 PaintOverlayControl(&progress_bar_
, &image_data_
, ready
);
903 if (page_indicator_
.visible())
904 PaintOverlayControl(&page_indicator_
, &image_data_
, ready
);
906 if (toolbar_
->current_transparency() != kTransparentAlpha
)
907 PaintOverlayControl(toolbar_
.get(), &image_data_
, ready
);
909 // Paint autoscroll anchor if needed.
910 if (is_autoscroll_
) {
911 size_t limit
= ready
->size();
912 for (size_t i
= 0; i
< limit
; i
++) {
913 pp::Rect anchor_rect
= autoscroll_rect_
.Intersect((*ready
)[i
].rect
);
914 if (!anchor_rect
.IsEmpty()) {
915 pp::Rect draw_rc
= pp::Rect(
916 pp::Point(anchor_rect
.x() - autoscroll_rect_
.x(),
917 anchor_rect
.y() - autoscroll_rect_
.y()),
919 // Paint autoscroll anchor.
920 AlphaBlend(autoscroll_anchor_
, draw_rc
,
921 &image_data_
, anchor_rect
.point(), kOpaqueAlpha
);
927 void Instance::PaintOverlayControl(
929 pp::ImageData
* image_data
,
930 std::vector
<PaintManager::ReadyRect
>* ready
) {
931 // Make sure that we only paint overlay controls over an area that's ready,
932 // i.e. not pending. Otherwise we'll mark the control rect as ready and
933 // it'll overwrite the pdf region.
934 std::list
<pp::Rect
> ctrl_rects
;
935 for (size_t i
= 0; i
< ready
->size(); i
++) {
936 pp::Rect rc
= ctrl
->rect().Intersect((*ready
)[i
].rect
);
938 ctrl_rects
.push_back(rc
);
941 if (!ctrl_rects
.empty()) {
942 ctrl
->PaintMultipleRects(image_data
, ctrl_rects
);
944 std::list
<pp::Rect
>::iterator iter
;
945 for (iter
= ctrl_rects
.begin(); iter
!= ctrl_rects
.end(); ++iter
) {
946 ready
->push_back(PaintManager::ReadyRect(*iter
, *image_data
, false));
951 void Instance::DidOpen(int32_t result
) {
952 if (result
== PP_OK
) {
953 engine_
->HandleDocumentLoad(embed_loader_
);
954 } else if (result
!= PP_ERROR_ABORTED
) { // Can happen in tests.
959 void Instance::DidOpenPreview(int32_t result
) {
960 if (result
== PP_OK
) {
961 preview_engine_
.reset(PDFEngine::Create(new PreviewModeClient(this)));
962 preview_engine_
->HandleDocumentLoad(embed_preview_loader_
);
968 void Instance::PaintIfWidgetIntersects(
969 pp::Widget_Dev
* widget
,
970 const pp::Rect
& rect
,
971 std::vector
<PaintManager::ReadyRect
>* ready
,
972 std::vector
<pp::Rect
>* pending
) {
977 if (!widget
->GetLocation(&location
))
980 ScaleRect(device_scale_
, &location
);
981 location
= location
.Intersect(rect
);
982 if (location
.IsEmpty())
985 if (IsOverlayScrollbar()) {
986 // If we're using overlay scrollbars, and there are pending paints under the
987 // scrollbar, don't update the scrollbar instantly. While it would be nice,
988 // we would need to double buffer the plugin area in order to make this
989 // work. This is because we'd need to always have a copy of what the pdf
990 // under the scrollbar looks like, and additionally we couldn't paint the
991 // pdf under the scrollbar if it's ready until we got the preceding flush.
992 // So in practice, it would make painting slower and introduce extra buffer
993 // copies for the general case.
994 for (size_t i
= 0; i
< pending
->size(); ++i
) {
995 if ((*pending
)[i
].Intersects(location
))
999 // Even if none of the pending paints are under the scrollbar, we never want
1000 // to paint it if it's over the pdf if there are other pending paints.
1001 // Otherwise different parts of the pdf plugin would display at different
1003 if (!pending
->empty() && available_area_
.Intersects(rect
)) {
1004 pending
->push_back(location
);
1009 pp::Rect location_dip
= location
;
1010 ScaleRect(1.0f
/ device_scale_
, &location_dip
);
1012 DCHECK(!image_data_
.is_null());
1013 widget
->Paint(location_dip
, &image_data_
);
1015 ready
->push_back(PaintManager::ReadyRect(location
, image_data_
, true));
1018 void Instance::OnTimerFired(int32_t) {
1019 HandleInputEvent(last_mouse_event_
);
1022 void Instance::OnClientTimerFired(int32_t id
) {
1023 engine_
->OnCallback(id
);
1026 void Instance::OnControlTimerFired(int32_t,
1027 const uint32
& control_id
,
1028 const uint32
& timer_id
) {
1029 if (control_id
== toolbar_
->id()) {
1030 toolbar_
->OnTimerFired(timer_id
);
1031 } else if (control_id
== progress_bar_
.id()) {
1032 if (timer_id
== delayed_progress_timer_id_
) {
1033 if (document_load_state_
== LOAD_STATE_LOADING
&&
1034 !progress_bar_
.visible()) {
1035 progress_bar_
.Fade(true, kProgressFadeTimeoutMs
);
1037 delayed_progress_timer_id_
= 0;
1039 progress_bar_
.OnTimerFired(timer_id
);
1041 } else if (control_id
== kAutoScrollId
) {
1042 if (is_autoscroll_
) {
1043 if (autoscroll_x_
!= 0 && h_scrollbar_
.get()) {
1044 h_scrollbar_
->ScrollBy(PP_SCROLLBY_PIXEL
, autoscroll_x_
);
1046 if (autoscroll_y_
!= 0 && v_scrollbar_
.get()) {
1047 v_scrollbar_
->ScrollBy(PP_SCROLLBY_PIXEL
, autoscroll_y_
);
1050 // Reschedule timer.
1051 ScheduleTimer(kAutoScrollId
, kAutoScrollTimeoutMs
);
1053 } else if (control_id
== kPageIndicatorId
) {
1054 page_indicator_
.OnTimerFired(timer_id
);
1056 #ifdef ENABLE_THUMBNAILS
1057 else if (control_id
== thumbnails_
.id()) {
1058 thumbnails_
.OnTimerFired(timer_id
);
1063 void Instance::CalculateBackgroundParts() {
1064 background_parts_
.clear();
1065 int v_scrollbar_thickness
=
1066 GetScaled(v_scrollbar_
.get() ? GetScrollbarReservedThickness() : 0);
1067 int h_scrollbar_thickness
=
1068 GetScaled(h_scrollbar_
.get() ? GetScrollbarReservedThickness() : 0);
1069 int width_without_scrollbar
= std::max(
1070 plugin_size_
.width() - v_scrollbar_thickness
, 0);
1071 int height_without_scrollbar
= std::max(
1072 plugin_size_
.height() - h_scrollbar_thickness
, 0);
1073 int left_width
= available_area_
.x();
1074 int right_start
= available_area_
.right();
1075 int right_width
= abs(width_without_scrollbar
- available_area_
.right());
1076 int bottom
= std::min(available_area_
.bottom(), height_without_scrollbar
);
1078 // Add the left, right, and bottom rectangles. Note: we assume only
1079 // horizontal centering.
1080 BackgroundPart part
= {
1081 pp::Rect(0, 0, left_width
, bottom
),
1084 if (!part
.location
.IsEmpty())
1085 background_parts_
.push_back(part
);
1086 part
.location
= pp::Rect(right_start
, 0, right_width
, bottom
);
1087 if (!part
.location
.IsEmpty())
1088 background_parts_
.push_back(part
);
1089 part
.location
= pp::Rect(
1090 0, bottom
, width_without_scrollbar
, height_without_scrollbar
- bottom
);
1091 if (!part
.location
.IsEmpty())
1092 background_parts_
.push_back(part
);
1094 if (h_scrollbar_thickness
1095 #if defined(OS_MACOSX)
1100 v_scrollbar_thickness
) {
1101 part
.color
= 0xFFFFFFFF;
1102 part
.location
= pp::Rect(plugin_size_
.width() - v_scrollbar_thickness
,
1103 plugin_size_
.height() - h_scrollbar_thickness
,
1104 h_scrollbar_thickness
,
1105 v_scrollbar_thickness
);
1106 background_parts_
.push_back(part
);
1110 int Instance::GetDocumentPixelWidth() const {
1111 return static_cast<int>(ceil(document_size_
.width() * zoom_
* device_scale_
));
1114 int Instance::GetDocumentPixelHeight() const {
1115 return static_cast<int>(ceil(document_size_
.height() *
1120 void Instance::FillRect(const pp::Rect
& rect
, uint32 color
) {
1121 DCHECK(!image_data_
.is_null() || rect
.IsEmpty());
1122 uint32
* buffer_start
= static_cast<uint32
*>(image_data_
.data());
1123 int stride
= image_data_
.stride();
1124 uint32
* ptr
= buffer_start
+ rect
.y() * stride
/ 4 + rect
.x();
1125 int height
= rect
.height();
1126 int width
= rect
.width();
1127 for (int y
= 0; y
< height
; ++y
) {
1128 for (int x
= 0; x
< width
; ++x
)
1134 void Instance::DocumentSizeUpdated(const pp::Size
& size
) {
1135 document_size_
= size
;
1137 OnGeometryChanged(zoom_
, device_scale_
);
1140 void Instance::Invalidate(const pp::Rect
& rect
) {
1141 pp::Rect
offset_rect(rect
);
1142 offset_rect
.Offset(available_area_
.point());
1143 paint_manager_
.InvalidateRect(offset_rect
);
1146 void Instance::Scroll(const pp::Point
& point
) {
1147 pp::Rect scroll_area
= available_area_
;
1148 if (IsOverlayScrollbar()) {
1150 if (h_scrollbar_
.get()) {
1151 h_scrollbar_
->GetLocation(&rc
);
1152 ScaleRect(device_scale_
, &rc
);
1153 if (scroll_area
.bottom() > rc
.y()) {
1154 scroll_area
.set_height(rc
.y() - scroll_area
.y());
1155 paint_manager_
.InvalidateRect(rc
);
1158 if (v_scrollbar_
.get()) {
1159 v_scrollbar_
->GetLocation(&rc
);
1160 ScaleRect(device_scale_
, &rc
);
1161 if (scroll_area
.right() > rc
.x()) {
1162 scroll_area
.set_width(rc
.x() - scroll_area
.x());
1163 paint_manager_
.InvalidateRect(rc
);
1167 paint_manager_
.ScrollRect(scroll_area
, point
);
1169 if (toolbar_
->current_transparency() != kTransparentAlpha
)
1170 paint_manager_
.InvalidateRect(toolbar_
->GetControlsRect());
1172 if (progress_bar_
.visible())
1173 paint_manager_
.InvalidateRect(progress_bar_
.rect());
1176 paint_manager_
.InvalidateRect(autoscroll_rect_
);
1178 if (show_page_indicator_
) {
1179 page_indicator_
.set_current_page(GetPageNumberToDisplay());
1180 page_indicator_
.Splash();
1183 if (page_indicator_
.visible())
1184 paint_manager_
.InvalidateRect(page_indicator_
.rect());
1186 // Run the scroll callback asynchronously. This function can be invoked by a
1187 // layout change which should not re-enter into JS synchronously.
1188 pp::CompletionCallback callback
=
1189 callback_factory_
.NewCallback(&Instance::RunCallback
,
1190 on_scroll_callback_
);
1191 pp::Module::Get()->core()->CallOnMainThread(0, callback
);
1194 void Instance::ScrollToX(int position
) {
1195 if (!h_scrollbar_
.get()) {
1199 int position_dip
= static_cast<int>(position
/ device_scale_
);
1200 h_scrollbar_
->SetValue(position_dip
);
1203 void Instance::ScrollToY(int position
) {
1204 if (!v_scrollbar_
.get()) {
1208 int position_dip
= static_cast<int>(position
/ device_scale_
);
1209 v_scrollbar_
->SetValue(ClipToRange(position_dip
, 0, valid_v_range_
));
1212 void Instance::ScrollToPage(int page
) {
1213 if (!v_scrollbar_
.get())
1216 if (engine_
->GetNumberOfPages() == 0)
1219 int index
= ClipToRange(page
, 0, engine_
->GetNumberOfPages() - 1);
1220 pp::Rect rect
= engine_
->GetPageRect(index
);
1221 // If we are trying to scroll pass the last page,
1222 // scroll to the end of the last page.
1223 int position
= index
< page
? rect
.bottom() : rect
.y();
1224 ScrollToY(position
* zoom_
* device_scale_
);
1227 void Instance::NavigateTo(const std::string
& url
, bool open_in_new_tab
) {
1228 std::string
url_copy(url
);
1230 // Empty |url_copy| is ok, and will effectively be a reload.
1231 // Skip the code below so an empty URL does not turn into "http://", which
1232 // will cause GURL to fail a DCHECK.
1233 if (!url_copy
.empty()) {
1234 // If |url_copy| starts with '#', then it's for the same URL with a
1235 // different URL fragment.
1236 if (url_copy
[0] == '#') {
1237 // if '#' is already present in |url_| then remove old fragment and add
1238 // new |url_copy| fragment.
1239 std::size_t index
= url_
.find('#');
1240 if (index
!= std::string::npos
)
1241 url_copy
= url_
.substr(0, index
) + url_copy
;
1243 url_copy
= url_
+ url_copy
;
1244 // Changing the href does not actually do anything when navigating in the
1245 // same tab, so do the actual page scroll here. Then fall through so the
1246 // href gets updated.
1247 if (!open_in_new_tab
) {
1248 int page_number
= GetInitialPage(url_copy
);
1249 if (page_number
>= 0)
1250 ScrollToPage(page_number
);
1253 // If there's no scheme, add http.
1254 if (url_copy
.find("://") == std::string::npos
&&
1255 url_copy
.find("mailto:") == std::string::npos
) {
1256 url_copy
= "http://" + url_copy
;
1258 // Make sure |url_copy| starts with a valid scheme.
1259 if (url_copy
.find("http://") != 0 &&
1260 url_copy
.find("https://") != 0 &&
1261 url_copy
.find("ftp://") != 0 &&
1262 url_copy
.find("file://") != 0 &&
1263 url_copy
.find("mailto:") != 0) {
1266 // Make sure |url_copy| is not only a scheme.
1267 if (url_copy
== "http://" ||
1268 url_copy
== "https://" ||
1269 url_copy
== "ftp://" ||
1270 url_copy
== "file://" ||
1271 url_copy
== "mailto:") {
1275 if (open_in_new_tab
) {
1276 GetWindowObject().Call("open", url_copy
);
1278 GetWindowObject().GetProperty("top").GetProperty("location").
1279 SetProperty("href", url_copy
);
1283 void Instance::UpdateCursor(PP_CursorType_Dev cursor
) {
1284 if (cursor
== cursor_
)
1288 const PPB_CursorControl_Dev
* cursor_interface
=
1289 reinterpret_cast<const PPB_CursorControl_Dev
*>(
1290 pp::Module::Get()->GetBrowserInterface(PPB_CURSOR_CONTROL_DEV_INTERFACE
));
1291 if (!cursor_interface
) {
1296 cursor_interface
->SetCursor(
1297 pp_instance(), cursor_
, pp::ImageData().pp_resource(), NULL
);
1300 void Instance::UpdateTickMarks(const std::vector
<pp::Rect
>& tickmarks
) {
1301 if (!v_scrollbar_
.get())
1304 float inverse_scale
= 1.0f
/ device_scale_
;
1305 std::vector
<pp::Rect
> scaled_tickmarks
= tickmarks
;
1306 for (size_t i
= 0; i
< scaled_tickmarks
.size(); i
++) {
1307 ScaleRect(inverse_scale
, &scaled_tickmarks
[i
]);
1310 v_scrollbar_
->SetTickMarks(
1311 scaled_tickmarks
.empty() ? NULL
: &scaled_tickmarks
[0], tickmarks
.size());
1314 void Instance::NotifyNumberOfFindResultsChanged(int total
, bool final_result
) {
1315 NumberOfFindResultsChanged(total
, final_result
);
1318 void Instance::NotifySelectedFindResultChanged(int current_find_index
) {
1319 DCHECK_GE(current_find_index
, 0);
1320 SelectedFindResultChanged(current_find_index
);
1323 void Instance::OnEvent(uint32 control_id
, uint32 event_id
, void* data
) {
1324 if (event_id
== Button::EVENT_ID_BUTTON_CLICKED
||
1325 event_id
== Button::EVENT_ID_BUTTON_STATE_CHANGED
) {
1326 switch (control_id
) {
1327 case kFitToPageButtonId
:
1328 UserMetricsRecordAction("PDF.FitToPageButton");
1329 SetZoom(ZOOM_FIT_TO_PAGE
, 0);
1332 case kFitToWidthButtonId
:
1333 UserMetricsRecordAction("PDF.FitToWidthButton");
1334 SetZoom(ZOOM_FIT_TO_WIDTH
, 0);
1337 case kZoomOutButtonId
:
1338 case kZoomInButtonId
:
1339 UserMetricsRecordAction(control_id
== kZoomOutButtonId
?
1340 "PDF.ZoomOutButton" : "PDF.ZoomInButton");
1341 SetZoom(ZOOM_SCALE
, CalculateZoom(control_id
));
1345 UserMetricsRecordAction("PDF.SaveButton");
1348 case kPrintButtonId
:
1349 UserMetricsRecordAction("PDF.PrintButton");
1354 if (control_id
== kThumbnailsId
&&
1355 event_id
== ThumbnailControl::EVENT_ID_THUMBNAIL_SELECTED
) {
1356 int page
= *static_cast<int*>(data
);
1357 pp::Rect
page_rc(engine_
->GetPageRect(page
));
1358 ScrollToY(static_cast<int>(page_rc
.y() * zoom_
* device_scale_
));
1362 void Instance::Invalidate(uint32 control_id
, const pp::Rect
& rc
) {
1363 paint_manager_
.InvalidateRect(rc
);
1366 uint32
Instance::ScheduleTimer(uint32 control_id
, uint32 timeout_ms
) {
1367 current_timer_id_
++;
1368 pp::CompletionCallback callback
=
1369 timer_factory_
.NewCallback(&Instance::OnControlTimerFired
,
1372 pp::Module::Get()->core()->CallOnMainThread(timeout_ms
, callback
);
1373 return current_timer_id_
;
1376 void Instance::SetEventCapture(uint32 control_id
, bool set_capture
) {
1377 // TODO(gene): set event capture here.
1380 void Instance::SetCursor(uint32 control_id
, PP_CursorType_Dev cursor_type
) {
1381 UpdateCursor(cursor_type
);
1384 pp::Instance
* Instance::GetInstance() {
1388 void Instance::GetDocumentPassword(
1389 pp::CompletionCallbackWithOutput
<pp::Var
> callback
) {
1390 std::string
message(GetLocalizedString(PP_RESOURCESTRING_PDFGETPASSWORD
));
1391 pp::Var result
= pp::PDF::ModalPromptForPassword(this, message
);
1392 *callback
.output() = result
.pp_var();
1393 callback
.Run(PP_OK
);
1396 void Instance::Alert(const std::string
& message
) {
1397 GetWindowObject().Call("alert", message
);
1400 bool Instance::Confirm(const std::string
& message
) {
1401 pp::Var result
= GetWindowObject().Call("confirm", message
);
1402 return result
.is_bool() ? result
.AsBool() : false;
1405 std::string
Instance::Prompt(const std::string
& question
,
1406 const std::string
& default_answer
) {
1407 pp::Var result
= GetWindowObject().Call("prompt", question
, default_answer
);
1408 return result
.is_string() ? result
.AsString() : std::string();
1411 std::string
Instance::GetURL() {
1415 void Instance::Email(const std::string
& to
,
1416 const std::string
& cc
,
1417 const std::string
& bcc
,
1418 const std::string
& subject
,
1419 const std::string
& body
) {
1420 std::string javascript
=
1421 "var href = 'mailto:" + net::EscapeUrlEncodedData(to
, false) +
1422 "?cc=" + net::EscapeUrlEncodedData(cc
, false) +
1423 "&bcc=" + net::EscapeUrlEncodedData(bcc
, false) +
1424 "&subject=" + net::EscapeUrlEncodedData(subject
, false) +
1425 "&body=" + net::EscapeUrlEncodedData(body
, false) +
1426 "';var temp = window.open(href, '_blank', " +
1427 "'width=1,height=1');if(temp) temp.close();";
1428 ExecuteScript(javascript
);
1431 void Instance::Print() {
1432 if (!printing_enabled_
||
1433 (!engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
) &&
1434 !engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY
))) {
1438 pp::CompletionCallback callback
=
1439 callback_factory_
.NewCallback(&Instance::OnPrint
);
1440 pp::Module::Get()->core()->CallOnMainThread(0, callback
);
1443 void Instance::OnPrint(int32_t) {
1444 pp::PDF::Print(this);
1447 void Instance::SaveAs() {
1448 pp::PDF::SaveAs(this);
1451 void Instance::SubmitForm(const std::string
& url
,
1454 pp::URLRequestInfo
request(this);
1455 request
.SetURL(url
);
1456 request
.SetMethod("POST");
1457 request
.AppendDataToBody(reinterpret_cast<const char*>(data
), length
);
1459 pp::CompletionCallback callback
=
1460 form_factory_
.NewCallback(&Instance::FormDidOpen
);
1461 form_loader_
= CreateURLLoaderInternal();
1462 int rv
= form_loader_
.Open(request
, callback
);
1463 if (rv
!= PP_OK_COMPLETIONPENDING
)
1467 void Instance::FormDidOpen(int32_t result
) {
1468 // TODO: inform the user of success/failure.
1469 if (result
!= PP_OK
) {
1474 std::string
Instance::ShowFileSelectionDialog() {
1475 // Seems like very low priority to implement, since the pdf has no way to get
1476 // the file data anyways. Javascript doesn't let you do this synchronously.
1478 return std::string();
1481 pp::URLLoader
Instance::CreateURLLoader() {
1483 if (!did_call_start_loading_
) {
1484 did_call_start_loading_
= true;
1485 pp::PDF::DidStartLoading(this);
1488 // Disable save and print until the document is fully loaded, since they
1489 // would generate an incomplete document. Need to do this each time we
1490 // call DidStartLoading since that resets the content restrictions.
1491 pp::PDF::SetContentRestriction(this, CONTENT_RESTRICTION_SAVE
|
1492 CONTENT_RESTRICTION_PRINT
);
1495 return CreateURLLoaderInternal();
1498 void Instance::ScheduleCallback(int id
, int delay_in_ms
) {
1499 pp::CompletionCallback callback
=
1500 timer_factory_
.NewCallback(&Instance::OnClientTimerFired
);
1501 pp::Module::Get()->core()->CallOnMainThread(delay_in_ms
, callback
, id
);
1504 void Instance::SearchString(const base::char16
* string
,
1505 const base::char16
* term
,
1506 bool case_sensitive
,
1507 std::vector
<SearchStringResult
>* results
) {
1508 if (!pp::PDF::IsAvailable()) {
1513 PP_PrivateFindResult
* pp_results
;
1515 pp::PDF::SearchString(
1517 reinterpret_cast<const unsigned short*>(string
),
1518 reinterpret_cast<const unsigned short*>(term
),
1523 results
->resize(count
);
1524 for (int i
= 0; i
< count
; ++i
) {
1525 (*results
)[i
].start_index
= pp_results
[i
].start_index
;
1526 (*results
)[i
].length
= pp_results
[i
].length
;
1529 pp::Memory_Dev memory
;
1530 memory
.MemFree(pp_results
);
1533 void Instance::DocumentPaintOccurred() {
1534 if (painted_first_page_
)
1537 painted_first_page_
= true;
1538 UpdateToolbarPosition(false);
1539 toolbar_
->Splash(kToolbarSplashTimeoutMs
);
1541 if (engine_
->GetNumberOfPages() > 1)
1542 show_page_indicator_
= true;
1544 show_page_indicator_
= false;
1546 if (v_scrollbar_
.get() && show_page_indicator_
) {
1547 page_indicator_
.set_current_page(GetPageNumberToDisplay());
1548 page_indicator_
.Splash(kToolbarSplashTimeoutMs
,
1549 kPageIndicatorInitialFadeTimeoutMs
);
1553 void Instance::DocumentLoadComplete(int page_count
) {
1554 // Clear focus state for OSK.
1555 FormTextFieldFocusChange(false);
1557 // Update progress control.
1558 if (progress_bar_
.visible())
1559 progress_bar_
.Fade(false, kProgressFadeTimeoutMs
);
1561 DCHECK(document_load_state_
== LOAD_STATE_LOADING
);
1562 document_load_state_
= LOAD_STATE_COMPLETE
;
1563 UserMetricsRecordAction("PDF.LoadSuccess");
1565 if (did_call_start_loading_
) {
1566 pp::PDF::DidStopLoading(this);
1567 did_call_start_loading_
= false;
1570 if (on_load_callback_
.is_string())
1571 ExecuteScript(on_load_callback_
);
1572 // Note: If we are in print preview mode on_load_callback_ might call
1573 // ScrollTo{X|Y}() and we don't want to scroll again and override it.
1574 // #page=N is not supported in Print Preview.
1575 if (!IsPrintPreview()) {
1576 int initial_page
= GetInitialPage(url_
);
1577 if (initial_page
>= 0)
1578 ScrollToPage(initial_page
);
1583 if (!pp::PDF::IsAvailable())
1586 int content_restrictions
=
1587 CONTENT_RESTRICTION_CUT
| CONTENT_RESTRICTION_PASTE
;
1588 if (!engine_
->HasPermission(PDFEngine::PERMISSION_COPY
))
1589 content_restrictions
|= CONTENT_RESTRICTION_COPY
;
1591 if (!engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
) &&
1592 !engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY
)) {
1593 printing_enabled_
= false;
1594 if (current_tb_info_
== kPDFToolbarButtons
) {
1595 // Remove Print button.
1596 CreateToolbar(kPDFNoPrintToolbarButtons
,
1597 arraysize(kPDFNoPrintToolbarButtons
));
1598 UpdateToolbarPosition(false);
1599 Invalidate(pp::Rect(plugin_size_
));
1603 pp::PDF::SetContentRestriction(this, content_restrictions
);
1605 pp::PDF::HistogramPDFPageCount(this, page_count
);
1608 void Instance::RotateClockwise() {
1609 engine_
->RotateClockwise();
1612 void Instance::RotateCounterclockwise() {
1613 engine_
->RotateCounterclockwise();
1616 bool Instance::IsMouseOnScrollbar(const pp::InputEvent
& event
) {
1617 pp::MouseInputEvent
mouse_event(event
);
1618 if (mouse_event
.is_null())
1621 pp::Point pt
= mouse_event
.GetPosition();
1623 if ((v_scrollbar_
.get() && v_scrollbar_
->GetLocation(&temp
) &&
1624 temp
.Contains(pt
)) ||
1625 (h_scrollbar_
.get() && h_scrollbar_
->GetLocation(&temp
) &&
1626 temp
.Contains(pt
))) {
1632 void Instance::PreviewDocumentLoadComplete() {
1633 if (preview_document_load_state_
!= LOAD_STATE_LOADING
||
1634 preview_pages_info_
.empty()) {
1638 preview_document_load_state_
= LOAD_STATE_COMPLETE
;
1640 int dest_page_index
= preview_pages_info_
.front().second
;
1641 int src_page_index
=
1642 ExtractPrintPreviewPageIndex(preview_pages_info_
.front().first
);
1643 if (src_page_index
> 0 && dest_page_index
> -1 && preview_engine_
.get())
1644 engine_
->AppendPage(preview_engine_
.get(), dest_page_index
);
1646 preview_pages_info_
.pop();
1647 // |print_preview_page_count_| is not updated yet. Do not load any
1648 // other preview pages till we get this information.
1649 if (print_preview_page_count_
== 0)
1652 if (preview_pages_info_
.size())
1653 LoadAvailablePreviewPage();
1656 void Instance::DocumentLoadFailed() {
1657 DCHECK(document_load_state_
== LOAD_STATE_LOADING
);
1658 UserMetricsRecordAction("PDF.LoadFailure");
1660 // Hide progress control.
1661 progress_bar_
.Fade(false, kProgressFadeTimeoutMs
);
1663 if (did_call_start_loading_
) {
1664 pp::PDF::DidStopLoading(this);
1665 did_call_start_loading_
= false;
1668 document_load_state_
= LOAD_STATE_FAILED
;
1669 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
1672 void Instance::PreviewDocumentLoadFailed() {
1673 UserMetricsRecordAction("PDF.PreviewDocumentLoadFailure");
1674 if (preview_document_load_state_
!= LOAD_STATE_LOADING
||
1675 preview_pages_info_
.empty()) {
1679 preview_document_load_state_
= LOAD_STATE_FAILED
;
1680 preview_pages_info_
.pop();
1682 if (preview_pages_info_
.size())
1683 LoadAvailablePreviewPage();
1686 pp::Instance
* Instance::GetPluginInstance() {
1687 return GetInstance();
1690 void Instance::DocumentHasUnsupportedFeature(const std::string
& feature
) {
1691 std::string
metric("PDF_Unsupported_");
1693 if (!unsupported_features_reported_
.count(metric
)) {
1694 unsupported_features_reported_
.insert(metric
);
1695 UserMetricsRecordAction(metric
);
1698 // Since we use an info bar, only do this for full frame plugins..
1702 if (told_browser_about_unsupported_feature_
)
1704 told_browser_about_unsupported_feature_
= true;
1706 pp::PDF::HasUnsupportedFeature(this);
1709 void Instance::DocumentLoadProgress(uint32 available
, uint32 doc_size
) {
1710 double progress
= 0.0;
1711 if (doc_size
== 0) {
1712 // Document size is unknown. Use heuristics.
1713 // We'll make progress logarithmic from 0 to 100M.
1714 static const double kFactor
= log(100000000.0) / 100.0;
1715 if (available
> 0) {
1716 progress
= log(static_cast<double>(available
)) / kFactor
;
1717 if (progress
> 100.0)
1721 progress
= 100.0 * static_cast<double>(available
) / doc_size
;
1723 progress_bar_
.SetProgress(progress
);
1726 void Instance::FormTextFieldFocusChange(bool in_focus
) {
1727 if (!text_input_
.get())
1730 text_input_
->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_TEXT
);
1732 text_input_
->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_NONE
);
1735 // Called by PDFScriptableObject.
1736 bool Instance::HasScriptableMethod(const pp::Var
& method
, pp::Var
* exception
) {
1737 std::string method_str
= method
.AsString();
1738 return (method_str
== kJSAccessibility
||
1739 method_str
== kJSDocumentLoadComplete
||
1740 method_str
== kJSGetHeight
||
1741 method_str
== kJSGetHorizontalScrollbarThickness
||
1742 method_str
== kJSGetPageLocationNormalized
||
1743 method_str
== kJSGetSelectedText
||
1744 method_str
== kJSGetVerticalScrollbarThickness
||
1745 method_str
== kJSGetWidth
||
1746 method_str
== kJSGetZoomLevel
||
1747 method_str
== kJSGoToPage
||
1748 method_str
== kJSGrayscale
||
1749 method_str
== kJSLoadPreviewPage
||
1750 method_str
== kJSOnLoad
||
1751 method_str
== kJSOnPluginSizeChanged
||
1752 method_str
== kJSOnScroll
||
1753 method_str
== kJSPageXOffset
||
1754 method_str
== kJSPageYOffset
||
1755 method_str
== kJSPrintPreviewPageCount
||
1756 method_str
== kJSReload
||
1757 method_str
== kJSRemovePrintButton
||
1758 method_str
== kJSResetPrintPreviewUrl
||
1759 method_str
== kJSSendKeyEvent
||
1760 method_str
== kJSSetPageNumbers
||
1761 method_str
== kJSSetPageXOffset
||
1762 method_str
== kJSSetPageYOffset
||
1763 method_str
== kJSSetZoomLevel
||
1764 method_str
== kJSZoomFitToHeight
||
1765 method_str
== kJSZoomFitToWidth
||
1766 method_str
== kJSZoomIn
||
1767 method_str
== kJSZoomOut
);
1770 pp::Var
Instance::CallScriptableMethod(const pp::Var
& method
,
1771 const std::vector
<pp::Var
>& args
,
1772 pp::Var
* exception
) {
1773 std::string method_str
= method
.AsString();
1774 if (method_str
== kJSGrayscale
) {
1775 if (args
.size() == 1 && args
[0].is_bool()) {
1776 engine_
->SetGrayscale(args
[0].AsBool());
1778 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
1779 #ifdef ENABLE_THUMBNAILS
1780 if (thumbnails_
.visible())
1781 thumbnails_
.Show(true, true);
1783 return pp::Var(true);
1785 return pp::Var(false);
1787 if (method_str
== kJSOnLoad
) {
1788 if (args
.size() == 1 && args
[0].is_string()) {
1789 on_load_callback_
= args
[0];
1790 return pp::Var(true);
1792 return pp::Var(false);
1794 if (method_str
== kJSOnScroll
) {
1795 if (args
.size() == 1 && args
[0].is_string()) {
1796 on_scroll_callback_
= args
[0];
1797 return pp::Var(true);
1799 return pp::Var(false);
1801 if (method_str
== kJSOnPluginSizeChanged
) {
1802 if (args
.size() == 1 && args
[0].is_string()) {
1803 on_plugin_size_changed_callback_
= args
[0];
1804 return pp::Var(true);
1806 return pp::Var(false);
1808 if (method_str
== kJSReload
) {
1809 document_load_state_
= LOAD_STATE_LOADING
;
1812 preview_engine_
.reset();
1813 print_preview_page_count_
= 0;
1814 engine_
.reset(PDFEngine::Create(this));
1815 engine_
->New(url_
.c_str());
1816 #ifdef ENABLE_THUMBNAILS
1817 thumbnails_
.ResetEngine(engine_
.get());
1821 if (method_str
== kJSResetPrintPreviewUrl
) {
1822 if (args
.size() == 1 && args
[0].is_string()) {
1823 url_
= args
[0].AsString();
1824 preview_pages_info_
= std::queue
<PreviewPageInfo
>();
1825 preview_document_load_state_
= LOAD_STATE_COMPLETE
;
1829 if (method_str
== kJSZoomFitToHeight
) {
1830 SetZoom(ZOOM_FIT_TO_PAGE
, 0);
1833 if (method_str
== kJSZoomFitToWidth
) {
1834 SetZoom(ZOOM_FIT_TO_WIDTH
, 0);
1837 if (method_str
== kJSZoomIn
) {
1838 SetZoom(ZOOM_SCALE
, CalculateZoom(kZoomInButtonId
));
1841 if (method_str
== kJSZoomOut
) {
1842 SetZoom(ZOOM_SCALE
, CalculateZoom(kZoomOutButtonId
));
1845 if (method_str
== kJSSetZoomLevel
) {
1846 if (args
.size() == 1 && args
[0].is_number())
1847 SetZoom(ZOOM_SCALE
, args
[0].AsDouble());
1850 if (method_str
== kJSGetZoomLevel
) {
1851 return pp::Var(zoom_
);
1853 if (method_str
== kJSGetHeight
) {
1854 return pp::Var(plugin_size_
.height());
1856 if (method_str
== kJSGetWidth
) {
1857 return pp::Var(plugin_size_
.width());
1859 if (method_str
== kJSGetHorizontalScrollbarThickness
) {
1861 h_scrollbar_
.get() ? GetScrollbarReservedThickness() : 0);
1863 if (method_str
== kJSGetVerticalScrollbarThickness
) {
1865 v_scrollbar_
.get() ? GetScrollbarReservedThickness() : 0);
1867 if (method_str
== kJSGetSelectedText
) {
1868 std::string selected_text
= engine_
->GetSelectedText();
1869 // Always return unix newlines to JS.
1870 base::ReplaceChars(selected_text
, "\r", std::string(), &selected_text
);
1871 return selected_text
;
1873 if (method_str
== kJSDocumentLoadComplete
) {
1874 return pp::Var((document_load_state_
!= LOAD_STATE_LOADING
));
1876 if (method_str
== kJSPageYOffset
) {
1877 return pp::Var(static_cast<int32_t>(
1878 v_scrollbar_
.get() ? v_scrollbar_
->GetValue() : 0));
1880 if (method_str
== kJSSetPageYOffset
) {
1881 if (args
.size() == 1 && args
[0].is_number() && v_scrollbar_
.get())
1882 ScrollToY(GetScaled(args
[0].AsInt()));
1885 if (method_str
== kJSPageXOffset
) {
1886 return pp::Var(static_cast<int32_t>(
1887 h_scrollbar_
.get() ? h_scrollbar_
->GetValue() : 0));
1889 if (method_str
== kJSSetPageXOffset
) {
1890 if (args
.size() == 1 && args
[0].is_number() && h_scrollbar_
.get())
1891 ScrollToX(GetScaled(args
[0].AsInt()));
1894 if (method_str
== kJSRemovePrintButton
) {
1895 CreateToolbar(kPrintPreviewToolbarButtons
,
1896 arraysize(kPrintPreviewToolbarButtons
));
1897 UpdateToolbarPosition(false);
1898 Invalidate(pp::Rect(plugin_size_
));
1901 if (method_str
== kJSGoToPage
) {
1902 if (args
.size() == 1 && args
[0].is_string()) {
1903 ScrollToPage(atoi(args
[0].AsString().c_str()));
1907 if (method_str
== kJSAccessibility
) {
1908 if (args
.size() == 0) {
1909 base::DictionaryValue node
;
1910 node
.SetInteger(kAccessibleNumberOfPages
, engine_
->GetNumberOfPages());
1911 node
.SetBoolean(kAccessibleLoaded
,
1912 document_load_state_
!= LOAD_STATE_LOADING
);
1913 bool has_permissions
=
1914 engine_
->HasPermission(PDFEngine::PERMISSION_COPY
) ||
1915 engine_
->HasPermission(PDFEngine::PERMISSION_COPY_ACCESSIBLE
);
1916 node
.SetBoolean(kAccessibleCopyable
, has_permissions
);
1918 base::JSONWriter::Write(&node
, &json
);
1919 return pp::Var(json
);
1920 } else if (args
[0].is_number()) {
1921 return pp::Var(engine_
->GetPageAsJSON(args
[0].AsInt()));
1924 if (method_str
== kJSPrintPreviewPageCount
) {
1925 if (args
.size() == 1 && args
[0].is_number())
1926 SetPrintPreviewMode(args
[0].AsInt());
1929 if (method_str
== kJSLoadPreviewPage
) {
1930 if (args
.size() == 2 && args
[0].is_string() && args
[1].is_number())
1931 ProcessPreviewPageInfo(args
[0].AsString(), args
[1].AsInt());
1934 if (method_str
== kJSGetPageLocationNormalized
) {
1935 const size_t kMaxLength
= 30;
1936 char location_info
[kMaxLength
];
1937 int page_idx
= engine_
->GetMostVisiblePage();
1939 return pp::Var(std::string());
1940 pp::Rect rect
= engine_
->GetPageContentsRect(page_idx
);
1941 int v_scrollbar_reserved_thickness
=
1942 v_scrollbar_
.get() ? GetScaled(GetScrollbarReservedThickness()) : 0;
1944 rect
.set_x(rect
.x() + ((plugin_size_
.width() -
1945 v_scrollbar_reserved_thickness
- available_area_
.width()) / 2));
1946 base::snprintf(location_info
,
1948 "%0.4f;%0.4f;%0.4f;%0.4f;",
1949 rect
.x() / static_cast<float>(plugin_size_
.width()),
1950 rect
.y() / static_cast<float>(plugin_size_
.height()),
1951 rect
.width() / static_cast<float>(plugin_size_
.width()),
1952 rect
.height()/ static_cast<float>(plugin_size_
.height()));
1953 return pp::Var(std::string(location_info
));
1955 if (method_str
== kJSSetPageNumbers
) {
1956 if (args
.size() != 1 || !args
[0].is_string())
1958 const int num_pages_signed
= engine_
->GetNumberOfPages();
1959 if (num_pages_signed
<= 0)
1961 scoped_ptr
<base::ListValue
> page_ranges(static_cast<base::ListValue
*>(
1962 base::JSONReader::Read(args
[0].AsString(), false)));
1963 const size_t num_pages
= static_cast<size_t>(num_pages_signed
);
1964 if (!page_ranges
.get() || page_ranges
->GetSize() != num_pages
)
1967 std::vector
<int> print_preview_page_numbers
;
1968 for (size_t index
= 0; index
< num_pages
; ++index
) {
1969 int page_number
= 0; // |page_number| is 1-based.
1970 if (!page_ranges
->GetInteger(index
, &page_number
) || page_number
< 1)
1972 print_preview_page_numbers
.push_back(page_number
);
1974 print_preview_page_numbers_
= print_preview_page_numbers
;
1975 page_indicator_
.set_current_page(GetPageNumberToDisplay());
1978 // This is here to work around https://bugs.webkit.org/show_bug.cgi?id=16735.
1979 // In JS, creating a synthetic keyboard event and dispatching it always
1980 // result in a keycode of 0.
1981 if (method_str
== kJSSendKeyEvent
) {
1982 if (args
.size() == 1 && args
[0].is_number()) {
1983 pp::KeyboardInputEvent
event(
1985 PP_INPUTEVENT_TYPE_KEYDOWN
, // HandleInputEvent only care about this.
1986 0, // timestamp, not used for kbd events.
1988 args
[0].AsInt(), // keycode.
1989 pp::Var()); // no char text needed.
1990 HandleInputEvent(event
);
1996 void Instance::OnGeometryChanged(double old_zoom
, float old_device_scale
) {
1997 bool force_no_horizontal_scrollbar
= false;
1998 int scrollbar_thickness
= GetScrollbarThickness();
2000 if (old_device_scale
!= device_scale_
) {
2001 // Change in device scale forces us to recreate resources
2002 ConfigureNumberImageGenerator();
2004 CreateToolbar(current_tb_info_
, current_tb_info_size_
);
2005 // Load autoscroll anchor image.
2006 autoscroll_anchor_
=
2007 CreateResourceImage(PP_RESOURCEIMAGE_PDF_PAN_SCROLL_ICON
);
2009 ConfigurePageIndicator();
2010 ConfigureProgressBar();
2012 pp::Point scroll_position
= engine_
->GetScrollPosition();
2013 ScalePoint(device_scale_
/ old_device_scale
, &scroll_position
);
2014 engine_
->SetScrollPosition(scroll_position
);
2018 if (zoom_
!= old_zoom
|| device_scale_
!= old_device_scale
)
2019 engine_
->ZoomUpdated(zoom_
* device_scale_
);
2020 if (zoom_
!= old_zoom
)
2023 available_area_
= pp::Rect(plugin_size_
);
2024 if (GetDocumentPixelHeight() > plugin_size_
.height()) {
2025 CreateVerticalScrollbar();
2027 DestroyVerticalScrollbar();
2030 int v_scrollbar_reserved_thickness
=
2031 v_scrollbar_
.get() ? GetScaled(GetScrollbarReservedThickness()) : 0;
2033 if (!force_no_horizontal_scrollbar
&&
2034 GetDocumentPixelWidth() >
2035 (plugin_size_
.width() - v_scrollbar_reserved_thickness
)) {
2036 CreateHorizontalScrollbar();
2038 // Adding the horizontal scrollbar now might cause us to need vertical
2040 if (GetDocumentPixelHeight() >
2041 plugin_size_
.height() - GetScaled(GetScrollbarReservedThickness())) {
2042 CreateVerticalScrollbar();
2046 DestroyHorizontalScrollbar();
2049 #ifdef ENABLE_THUMBNAILS
2050 int thumbnails_pos
= 0, thumbnails_total
= 0;
2052 if (v_scrollbar_
.get()) {
2053 v_scrollbar_
->SetScale(device_scale_
);
2054 available_area_
.set_width(
2055 std::max(0, plugin_size_
.width() - v_scrollbar_reserved_thickness
));
2057 #ifdef ENABLE_THUMBNAILS
2058 int height
= plugin_size_
.height();
2060 int height_dip
= plugin_dip_size_
.height();
2062 #if defined(OS_MACOSX)
2063 // Before Lion, Mac always had the resize at the bottom. After that, it
2065 if ((base::mac::IsOSSnowLeopard() && full_
) ||
2066 (base::mac::IsOSLionOrLater() && h_scrollbar_
.get())) {
2068 if (h_scrollbar_
.get()) {
2069 #endif // defined(OS_MACOSX)
2070 #ifdef ENABLE_THUMBNAILS
2071 height
-= GetScaled(GetScrollbarThickness());
2073 height_dip
-= GetScrollbarThickness();
2075 #ifdef ENABLE_THUMBNAILS
2076 int32 doc_height
= GetDocumentPixelHeight();
2078 int32 doc_height_dip
=
2079 static_cast<int32
>(GetDocumentPixelHeight() / device_scale_
);
2080 #if defined(OS_MACOSX)
2081 // On the Mac we always allow room for the resize button (whose width is
2082 // the same as that of the scrollbar) in full mode. However, if there is no
2083 // no horizontal scrollbar, the end of the scrollbar will scroll past the
2084 // end of the document. This is because the scrollbar assumes that its own
2085 // height (in the case of a vscroll bar) is the same as the height of the
2086 // viewport. Since the viewport is actually larger, we compensate by
2087 // adjusting the document height. Similar logic applies below for the
2088 // horizontal scrollbar.
2089 // For example, if the document size is 1000, and the viewport size is 200,
2090 // then the scrollbar position at the end will be 800. In this case the
2091 // viewport is actally 215 (assuming 15 as the scrollbar width) but the
2092 // scrollbar thinks it is 200. We want the scrollbar position at the end to
2093 // be 785. Making the document size 985 achieves this.
2094 if (full_
&& !h_scrollbar_
.get()) {
2095 #ifdef ENABLE_THUMBNAILS
2096 doc_height
-= GetScaled(GetScrollbarThickness());
2098 doc_height_dip
-= GetScrollbarThickness();
2100 #endif // defined(OS_MACOSX)
2103 position
= v_scrollbar_
->GetValue();
2104 position
= static_cast<int>(position
* zoom_
/ old_zoom
);
2105 valid_v_range_
= doc_height_dip
- height_dip
;
2106 if (position
> valid_v_range_
)
2107 position
= valid_v_range_
;
2109 v_scrollbar_
->SetValue(position
);
2112 loc
.point
.x
= static_cast<int>(available_area_
.right() / device_scale_
);
2113 if (IsOverlayScrollbar())
2114 loc
.point
.x
-= scrollbar_thickness
;
2116 loc
.size
.width
= scrollbar_thickness
;
2117 loc
.size
.height
= height_dip
;
2118 v_scrollbar_
->SetLocation(loc
);
2119 v_scrollbar_
->SetDocumentSize(doc_height_dip
);
2121 #ifdef ENABLE_THUMBNAILS
2122 thumbnails_pos
= position
;
2123 thumbnails_total
= doc_height
- height
;
2127 if (h_scrollbar_
.get()) {
2128 h_scrollbar_
->SetScale(device_scale_
);
2129 available_area_
.set_height(
2130 std::max(0, plugin_size_
.height() -
2131 GetScaled(GetScrollbarReservedThickness())));
2133 int width_dip
= plugin_dip_size_
.width();
2136 #if defined(OS_MACOSX)
2137 if ((base::mac::IsOSSnowLeopard() && full_
) ||
2138 (base::mac::IsOSLionOrLater() && v_scrollbar_
.get())) {
2140 if (v_scrollbar_
.get()) {
2142 width_dip
-= GetScrollbarThickness();
2144 int32 doc_width_dip
=
2145 static_cast<int32
>(GetDocumentPixelWidth() / device_scale_
);
2146 #if defined(OS_MACOSX)
2147 // See comment in the above if (v_scrollbar_.get()) block.
2148 if (full_
&& !v_scrollbar_
.get())
2149 doc_width_dip
-= GetScrollbarThickness();
2150 #endif // defined(OS_MACOSX)
2153 position
= h_scrollbar_
->GetValue();
2154 position
= static_cast<int>(position
* zoom_
/ old_zoom
);
2155 position
= std::min(position
, doc_width_dip
- width_dip
);
2157 h_scrollbar_
->SetValue(position
);
2161 loc
.point
.y
= static_cast<int>(available_area_
.bottom() / device_scale_
);
2162 if (IsOverlayScrollbar())
2163 loc
.point
.y
-= scrollbar_thickness
;
2164 loc
.size
.width
= width_dip
;
2165 loc
.size
.height
= scrollbar_thickness
;
2166 h_scrollbar_
->SetLocation(loc
);
2167 h_scrollbar_
->SetDocumentSize(doc_width_dip
);
2170 int doc_width
= GetDocumentPixelWidth();
2171 if (doc_width
< available_area_
.width()) {
2172 available_area_
.Offset((available_area_
.width() - doc_width
) / 2, 0);
2173 available_area_
.set_width(doc_width
);
2175 int doc_height
= GetDocumentPixelHeight();
2176 if (doc_height
< available_area_
.height()) {
2177 available_area_
.set_height(doc_height
);
2180 // We'll invalidate the entire plugin anyways.
2181 UpdateToolbarPosition(false);
2182 UpdateProgressBarPosition(false);
2183 UpdatePageIndicatorPosition(false);
2185 #ifdef ENABLE_THUMBNAILS
2186 // Update thumbnail control position.
2187 thumbnails_
.SetPosition(thumbnails_pos
, thumbnails_total
, false);
2188 pp::Rect
thumbnails_rc(plugin_size_
.width() - GetScaled(kThumbnailsWidth
), 0,
2189 GetScaled(kThumbnailsWidth
), plugin_size_
.height());
2190 if (v_scrollbar_
.get())
2191 thumbnails_rc
.Offset(-v_scrollbar_reserved_thickness
, 0);
2192 if (h_scrollbar_
.get())
2193 thumbnails_rc
.Inset(0, 0, 0, v_scrollbar_reserved_thickness
);
2194 thumbnails_
.SetRect(thumbnails_rc
, false);
2197 CalculateBackgroundParts();
2198 engine_
->PageOffsetUpdated(available_area_
.point());
2199 engine_
->PluginSizeUpdated(available_area_
.size());
2201 if (!document_size_
.GetArea())
2203 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
2205 // Run the plugin size change callback asynchronously. This function can be
2206 // invoked by a layout change which should not re-enter into JS synchronously.
2207 pp::CompletionCallback callback
=
2208 callback_factory_
.NewCallback(&Instance::RunCallback
,
2209 on_plugin_size_changed_callback_
);
2210 pp::Module::Get()->core()->CallOnMainThread(0, callback
);
2213 void Instance::RunCallback(int32_t, pp::Var callback
) {
2214 if (callback
.is_string())
2215 ExecuteScript(callback
);
2218 void Instance::CreateHorizontalScrollbar() {
2219 if (h_scrollbar_
.get())
2222 h_scrollbar_
.reset(new pp::Scrollbar_Dev(this, false));
2225 void Instance::CreateVerticalScrollbar() {
2226 if (v_scrollbar_
.get())
2229 v_scrollbar_
.reset(new pp::Scrollbar_Dev(this, true));
2232 void Instance::DestroyHorizontalScrollbar() {
2233 if (!h_scrollbar_
.get())
2235 if (h_scrollbar_
->GetValue())
2236 engine_
->ScrolledToXPosition(0);
2237 h_scrollbar_
.reset();
2240 void Instance::DestroyVerticalScrollbar() {
2241 if (!v_scrollbar_
.get())
2243 if (v_scrollbar_
->GetValue())
2244 engine_
->ScrolledToYPosition(0);
2245 v_scrollbar_
.reset();
2246 page_indicator_
.Show(false, true);
2249 int Instance::GetScrollbarThickness() {
2250 if (scrollbar_thickness_
== -1) {
2251 pp::Scrollbar_Dev
temp_scrollbar(this, false);
2252 scrollbar_thickness_
= temp_scrollbar
.GetThickness();
2253 scrollbar_reserved_thickness_
=
2254 temp_scrollbar
.IsOverlay() ? 0 : scrollbar_thickness_
;
2257 return scrollbar_thickness_
;
2260 int Instance::GetScrollbarReservedThickness() {
2261 GetScrollbarThickness();
2262 return scrollbar_reserved_thickness_
;
2265 bool Instance::IsOverlayScrollbar() {
2266 return GetScrollbarReservedThickness() == 0;
2269 void Instance::CreateToolbar(const ToolbarButtonInfo
* tb_info
, size_t size
) {
2270 toolbar_
.reset(new FadingControls());
2275 // Remember the current toolbar information in case we need to recreate the
2277 current_tb_info_
= tb_info
;
2278 current_tb_info_size_
= size
;
2281 pp::Point
origin(kToolbarFadingOffsetLeft
, kToolbarFadingOffsetTop
);
2282 ScalePoint(device_scale_
, &origin
);
2284 std::list
<Button
*> buttons
;
2285 for (size_t i
= 0; i
< size
; i
++) {
2286 Button
* btn
= new Button
;
2287 pp::ImageData normal_face
=
2288 CreateResourceImage(tb_info
[i
].normal
);
2289 btn
->CreateButton(tb_info
[i
].id
,
2295 CreateResourceImage(tb_info
[i
].highlighted
),
2296 CreateResourceImage(tb_info
[i
].pressed
));
2297 buttons
.push_back(btn
);
2299 origin
+= pp::Point(normal_face
.size().width(), 0);
2300 max_height
= std::max(max_height
, normal_face
.size().height());
2303 pp::Rect
rc_toolbar(0, 0,
2304 origin
.x() + GetToolbarRightOffset(),
2305 origin
.y() + max_height
+ GetToolbarBottomOffset());
2306 toolbar_
->CreateFadingControls(
2307 kToolbarId
, rc_toolbar
, false, this, kTransparentAlpha
);
2309 std::list
<Button
*>::iterator iter
;
2310 for (iter
= buttons
.begin(); iter
!= buttons
.end(); ++iter
) {
2311 toolbar_
->AddControl(*iter
);
2315 int Instance::GetToolbarRightOffset() {
2316 int scrollbar_thickness
= GetScrollbarThickness();
2317 return GetScaled(kToolbarFadingOffsetRight
) + 2 * scrollbar_thickness
;
2320 int Instance::GetToolbarBottomOffset() {
2321 int scrollbar_thickness
= GetScrollbarThickness();
2322 return GetScaled(kToolbarFadingOffsetBottom
) + scrollbar_thickness
;
2325 std::vector
<pp::ImageData
> Instance::GetThumbnailResources() {
2326 std::vector
<pp::ImageData
> num_images(10);
2327 num_images
[0] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_0
);
2328 num_images
[1] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_1
);
2329 num_images
[2] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_2
);
2330 num_images
[3] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_3
);
2331 num_images
[4] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_4
);
2332 num_images
[5] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_5
);
2333 num_images
[6] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_6
);
2334 num_images
[7] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_7
);
2335 num_images
[8] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_8
);
2336 num_images
[9] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_9
);
2340 std::vector
<pp::ImageData
> Instance::GetProgressBarResources(
2341 pp::ImageData
* background
) {
2342 std::vector
<pp::ImageData
> result(9);
2343 result
[0] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_0
);
2344 result
[1] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_1
);
2345 result
[2] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_2
);
2346 result
[3] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_3
);
2347 result
[4] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_4
);
2348 result
[5] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_5
);
2349 result
[6] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_6
);
2350 result
[7] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_7
);
2351 result
[8] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_8
);
2352 *background
= CreateResourceImage(
2353 PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_BACKGROUND
);
2357 void Instance::CreatePageIndicator(bool always_visible
) {
2358 page_indicator_
.CreatePageIndicator(kPageIndicatorId
, false, this,
2359 number_image_generator(), always_visible
);
2360 ConfigurePageIndicator();
2363 void Instance::ConfigurePageIndicator() {
2364 pp::ImageData background
=
2365 CreateResourceImage(PP_RESOURCEIMAGE_PDF_PAGE_INDICATOR_BACKGROUND
);
2366 page_indicator_
.Configure(pp::Point(), background
);
2369 void Instance::CreateProgressBar() {
2370 pp::ImageData background
;
2371 std::vector
<pp::ImageData
> images
= GetProgressBarResources(&background
);
2372 std::string text
= GetLocalizedString(PP_RESOURCESTRING_PDFPROGRESSLOADING
);
2373 progress_bar_
.CreateProgressControl(kProgressBarId
, false, this, 0.0,
2374 device_scale_
, images
, background
, text
);
2377 void Instance::ConfigureProgressBar() {
2378 pp::ImageData background
;
2379 std::vector
<pp::ImageData
> images
= GetProgressBarResources(&background
);
2380 progress_bar_
.Reconfigure(background
, images
, device_scale_
);
2383 void Instance::CreateThumbnails() {
2384 thumbnails_
.CreateThumbnailControl(
2385 kThumbnailsId
, pp::Rect(), false, this, engine_
.get(),
2386 number_image_generator());
2389 void Instance::LoadUrl(const std::string
& url
) {
2390 LoadUrlInternal(url
, &embed_loader_
, &Instance::DidOpen
);
2393 void Instance::LoadPreviewUrl(const std::string
& url
) {
2394 LoadUrlInternal(url
, &embed_preview_loader_
, &Instance::DidOpenPreview
);
2397 void Instance::LoadUrlInternal(const std::string
& url
, pp::URLLoader
* loader
,
2398 void (Instance::* method
)(int32_t)) {
2399 pp::URLRequestInfo
request(this);
2400 request
.SetURL(url
);
2401 request
.SetMethod("GET");
2403 *loader
= CreateURLLoaderInternal();
2404 pp::CompletionCallback callback
= loader_factory_
.NewCallback(method
);
2405 int rv
= loader
->Open(request
, callback
);
2406 if (rv
!= PP_OK_COMPLETIONPENDING
)
2410 pp::URLLoader
Instance::CreateURLLoaderInternal() {
2411 pp::URLLoader
loader(this);
2413 const PPB_URLLoaderTrusted
* trusted_interface
=
2414 reinterpret_cast<const PPB_URLLoaderTrusted
*>(
2415 pp::Module::Get()->GetBrowserInterface(
2416 PPB_URLLOADERTRUSTED_INTERFACE
));
2417 if (trusted_interface
)
2418 trusted_interface
->GrantUniversalAccess(loader
.pp_resource());
2422 int Instance::GetInitialPage(const std::string
& url
) {
2423 size_t found_idx
= url
.find('#');
2424 if (found_idx
== std::string::npos
)
2427 const std::string
& ref
= url
.substr(found_idx
+ 1);
2428 std::vector
<std::string
> fragments
;
2429 Tokenize(ref
, kDelimiters
, &fragments
);
2431 // Page number to return, zero-based.
2434 // Handle the case of http://foo.com/bar#NAMEDDEST. This is not explicitly
2435 // mentioned except by example in the Adobe "PDF Open Parameters" document.
2436 if ((fragments
.size() == 1) && (fragments
[0].find('=') == std::string::npos
))
2437 return engine_
->GetNamedDestinationPage(fragments
[0]);
2439 for (size_t i
= 0; i
< fragments
.size(); ++i
) {
2440 std::vector
<std::string
> key_value
;
2441 base::SplitString(fragments
[i
], '=', &key_value
);
2442 if (key_value
.size() != 2)
2444 const std::string
& key
= key_value
[0];
2445 const std::string
& value
= key_value
[1];
2447 if (base::strcasecmp(kPage
, key
.c_str()) == 0) {
2448 // |page_value| is 1-based.
2449 int page_value
= -1;
2450 if (base::StringToInt(value
, &page_value
) && page_value
> 0)
2451 page
= page_value
- 1;
2454 if (base::strcasecmp(kNamedDest
, key
.c_str()) == 0) {
2455 // |page_value| is 0-based.
2456 int page_value
= engine_
->GetNamedDestinationPage(value
);
2457 if (page_value
>= 0)
2465 void Instance::UpdateToolbarPosition(bool invalidate
) {
2466 pp::Rect ctrl_rc
= toolbar_
->GetControlsRect();
2467 int min_toolbar_width
= ctrl_rc
.width() + GetToolbarRightOffset() +
2468 GetScaled(kToolbarFadingOffsetLeft
);
2469 int min_toolbar_height
= ctrl_rc
.width() + GetToolbarBottomOffset() +
2470 GetScaled(kToolbarFadingOffsetBottom
);
2472 // Update toolbar position
2473 if (plugin_size_
.width() < min_toolbar_width
||
2474 plugin_size_
.height() < min_toolbar_height
) {
2475 // Disable toolbar if it does not fit on the screen.
2476 toolbar_
->Show(false, invalidate
);
2479 plugin_size_
.width() - GetToolbarRightOffset() - ctrl_rc
.right(),
2480 plugin_size_
.height() - GetToolbarBottomOffset() - ctrl_rc
.bottom());
2481 toolbar_
->MoveBy(offset
, invalidate
);
2483 int toolbar_width
= std::max(plugin_size_
.width() / 2, min_toolbar_width
);
2484 toolbar_
->ExpandLeft(toolbar_width
- toolbar_
->rect().width());
2485 toolbar_
->Show(painted_first_page_
, invalidate
);
2489 void Instance::UpdateProgressBarPosition(bool invalidate
) {
2490 // TODO(gene): verify we don't overlap with toolbar.
2491 int scrollbar_thickness
= GetScrollbarThickness();
2492 pp::Point
progress_origin(
2493 scrollbar_thickness
+ GetScaled(kProgressOffsetLeft
),
2494 plugin_size_
.height() - progress_bar_
.rect().height() -
2495 scrollbar_thickness
- GetScaled(kProgressOffsetBottom
));
2496 progress_bar_
.MoveTo(progress_origin
, invalidate
);
2499 void Instance::UpdatePageIndicatorPosition(bool invalidate
) {
2500 int32 doc_height
= static_cast<int>(document_size_
.height() * zoom_
);
2502 plugin_size_
.width() - page_indicator_
.rect().width() -
2503 GetScaled(GetScrollbarReservedThickness()),
2504 page_indicator_
.GetYPosition(engine_
->GetVerticalScrollbarYPosition(),
2505 doc_height
, plugin_size_
.height()));
2506 page_indicator_
.MoveTo(origin
, invalidate
);
2509 void Instance::SetZoom(ZoomMode zoom_mode
, double scale
) {
2510 double old_zoom
= zoom_
;
2512 zoom_mode_
= zoom_mode
;
2513 if (zoom_mode_
== ZOOM_SCALE
)
2517 engine_
->ZoomUpdated(zoom_
* device_scale_
);
2518 OnGeometryChanged(old_zoom
, device_scale_
);
2520 // If fit-to-height, snap to the beginning of the most visible page.
2521 if (zoom_mode_
== ZOOM_FIT_TO_PAGE
) {
2522 ScrollToPage(engine_
->GetMostVisiblePage());
2525 // Update sticky buttons to the current zoom style.
2526 Button
* ftp_btn
= static_cast<Button
*>(
2527 toolbar_
->GetControl(kFitToPageButtonId
));
2528 Button
* ftw_btn
= static_cast<Button
*>(
2529 toolbar_
->GetControl(kFitToWidthButtonId
));
2530 switch (zoom_mode_
) {
2531 case ZOOM_FIT_TO_PAGE
:
2532 ftp_btn
->SetPressedState(true);
2533 ftw_btn
->SetPressedState(false);
2535 case ZOOM_FIT_TO_WIDTH
:
2536 ftw_btn
->SetPressedState(true);
2537 ftp_btn
->SetPressedState(false);
2540 ftw_btn
->SetPressedState(false);
2541 ftp_btn
->SetPressedState(false);
2545 void Instance::UpdateZoomScale() {
2546 switch (zoom_mode_
) {
2548 break; // Keep current scale.
2549 case ZOOM_FIT_TO_PAGE
: {
2550 int page_num
= engine_
->GetFirstVisiblePage();
2553 pp::Rect rc
= engine_
->GetPageRect(page_num
);
2556 // Calculate fit to width zoom level.
2557 double ftw_zoom
= static_cast<double>(plugin_dip_size_
.width() -
2558 GetScrollbarReservedThickness()) / document_size_
.width();
2559 // Calculate fit to height zoom level. If document will not fit
2560 // horizontally, adjust zoom level to allow space for horizontal
2563 static_cast<double>(plugin_dip_size_
.height()) / rc
.height();
2564 if (fth_zoom
* document_size_
.width() >
2565 plugin_dip_size_
.width() - GetScrollbarReservedThickness())
2566 fth_zoom
= static_cast<double>(plugin_dip_size_
.height()
2567 - GetScrollbarReservedThickness()) / rc
.height();
2568 zoom_
= std::min(ftw_zoom
, fth_zoom
);
2570 case ZOOM_FIT_TO_WIDTH
:
2572 if (!document_size_
.width())
2574 zoom_
= static_cast<double>(plugin_dip_size_
.width() -
2575 GetScrollbarReservedThickness()) / document_size_
.width();
2576 if (zoom_mode_
== ZOOM_AUTO
&& zoom_
> 1.0)
2580 zoom_
= ClipToRange(zoom_
, kMinZoom
, kMaxZoom
);
2583 double Instance::CalculateZoom(uint32 control_id
) const {
2584 if (control_id
== kZoomInButtonId
) {
2585 for (size_t i
= 0; i
< ui_zoom::kPresetZoomFactorsSize
; ++i
) {
2586 double current_zoom
= ui_zoom::kPresetZoomFactors
[i
];
2587 if (current_zoom
- content::kEpsilon
> zoom_
)
2588 return current_zoom
;
2591 for (size_t i
= ui_zoom::kPresetZoomFactorsSize
; i
> 0; --i
) {
2592 double current_zoom
= ui_zoom::kPresetZoomFactors
[i
- 1];
2593 if (current_zoom
+ content::kEpsilon
< zoom_
)
2594 return current_zoom
;
2600 pp::ImageData
Instance::CreateResourceImage(PP_ResourceImage image_id
) {
2601 pp::ImageData resource_data
;
2602 if (hidpi_enabled_
) {
2604 pp::PDF::GetResourceImageForScale(this, image_id
, device_scale_
);
2607 return resource_data
.data() ? resource_data
2608 : pp::PDF::GetResourceImage(this, image_id
);
2611 std::string
Instance::GetLocalizedString(PP_ResourceString id
) {
2612 pp::Var
rv(pp::PDF::GetLocalizedString(this, id
));
2613 if (!rv
.is_string())
2614 return std::string();
2616 return rv
.AsString();
2619 void Instance::DrawText(const pp::Point
& top_center
, PP_ResourceString id
) {
2620 std::string
str(GetLocalizedString(id
));
2622 pp::FontDescription_Dev description
;
2623 description
.set_family(PP_FONTFAMILY_SANSSERIF
);
2624 description
.set_size(kMessageTextSize
* device_scale_
);
2625 pp::Font_Dev
font(this, description
);
2626 int length
= font
.MeasureSimpleText(str
);
2627 pp::Point
point(top_center
);
2628 point
.set_x(point
.x() - length
/ 2);
2629 DCHECK(!image_data_
.is_null());
2630 font
.DrawSimpleText(&image_data_
, str
, point
, kMessageTextColor
);
2633 void Instance::SetPrintPreviewMode(int page_count
) {
2634 if (!IsPrintPreview() || page_count
<= 0) {
2635 print_preview_page_count_
= 0;
2639 print_preview_page_count_
= page_count
;
2641 engine_
->AppendBlankPages(print_preview_page_count_
);
2642 if (preview_pages_info_
.size() > 0)
2643 LoadAvailablePreviewPage();
2646 bool Instance::IsPrintPreview() {
2647 return IsPrintPreviewUrl(url_
);
2650 uint32
Instance::GetBackgroundColor() {
2651 return kBackgroundColor
;
2654 int Instance::GetPageNumberToDisplay() {
2655 int page
= engine_
->GetMostVisiblePage();
2656 if (IsPrintPreview() && !print_preview_page_numbers_
.empty()) {
2657 page
= ClipToRange
<int>(page
, 0, print_preview_page_numbers_
.size() - 1);
2658 return print_preview_page_numbers_
[page
];
2663 void Instance::ProcessPreviewPageInfo(const std::string
& url
,
2664 int dst_page_index
) {
2665 if (!IsPrintPreview() || print_preview_page_count_
< 0)
2668 int src_page_index
= ExtractPrintPreviewPageIndex(url
);
2669 if (src_page_index
< 1)
2672 preview_pages_info_
.push(std::make_pair(url
, dst_page_index
));
2673 LoadAvailablePreviewPage();
2676 void Instance::LoadAvailablePreviewPage() {
2677 if (preview_pages_info_
.size() <= 0)
2680 std::string url
= preview_pages_info_
.front().first
;
2681 int dst_page_index
= preview_pages_info_
.front().second
;
2682 int src_page_index
= ExtractPrintPreviewPageIndex(url
);
2683 if (src_page_index
< 1 ||
2684 dst_page_index
>= print_preview_page_count_
||
2685 preview_document_load_state_
== LOAD_STATE_LOADING
) {
2689 preview_document_load_state_
= LOAD_STATE_LOADING
;
2690 LoadPreviewUrl(url
);
2693 void Instance::EnableAutoscroll(const pp::Point
& origin
) {
2697 pp::Size client_size
= plugin_size_
;
2698 if (v_scrollbar_
.get())
2699 client_size
.Enlarge(-GetScrollbarThickness(), 0);
2700 if (h_scrollbar_
.get())
2701 client_size
.Enlarge(0, -GetScrollbarThickness());
2703 // Do not allow autoscroll if client area is too small.
2704 if (autoscroll_anchor_
.size().width() > client_size
.width() ||
2705 autoscroll_anchor_
.size().height() > client_size
.height())
2708 autoscroll_rect_
= pp::Rect(
2709 pp::Point(origin
.x() - autoscroll_anchor_
.size().width() / 2,
2710 origin
.y() - autoscroll_anchor_
.size().height() / 2),
2711 autoscroll_anchor_
.size());
2713 // Make sure autoscroll anchor is in the client area.
2714 if (autoscroll_rect_
.right() > client_size
.width()) {
2715 autoscroll_rect_
.set_x(
2716 client_size
.width() - autoscroll_anchor_
.size().width());
2718 if (autoscroll_rect_
.bottom() > client_size
.height()) {
2719 autoscroll_rect_
.set_y(
2720 client_size
.height() - autoscroll_anchor_
.size().height());
2723 if (autoscroll_rect_
.x() < 0)
2724 autoscroll_rect_
.set_x(0);
2725 if (autoscroll_rect_
.y() < 0)
2726 autoscroll_rect_
.set_y(0);
2728 is_autoscroll_
= true;
2729 Invalidate(kAutoScrollId
, autoscroll_rect_
);
2731 ScheduleTimer(kAutoScrollId
, kAutoScrollTimeoutMs
);
2734 void Instance::DisableAutoscroll() {
2735 if (is_autoscroll_
) {
2736 is_autoscroll_
= false;
2737 Invalidate(kAutoScrollId
, autoscroll_rect_
);
2741 PP_CursorType_Dev
Instance::CalculateAutoscroll(const pp::Point
& mouse_pos
) {
2742 // Scroll only if mouse pointer is outside of the anchor area.
2743 if (autoscroll_rect_
.Contains(mouse_pos
)) {
2746 return PP_CURSORTYPE_MIDDLEPANNING
;
2749 // Relative position to the center of anchor area.
2750 pp::Point rel_pos
= mouse_pos
- autoscroll_rect_
.CenterPoint();
2752 // Calculate angle from the X axis. Angle is in range from -pi to pi.
2753 double angle
= atan2(static_cast<double>(rel_pos
.y()),
2754 static_cast<double>(rel_pos
.x()));
2756 autoscroll_x_
= rel_pos
.x() * kAutoScrollFactor
;
2757 autoscroll_y_
= rel_pos
.y() * kAutoScrollFactor
;
2759 // Angle is from -pi to pi. Screen Y is increasing toward bottom,
2760 // so negative angle represent north direction.
2761 if (angle
< - (M_PI
* 7.0 / 8.0)) {
2763 return PP_CURSORTYPE_WESTPANNING
;
2764 } else if (angle
< - (M_PI
* 5.0 / 8.0)) {
2766 return PP_CURSORTYPE_NORTHWESTPANNING
;
2767 } else if (angle
< - (M_PI
* 3.0 / 8.0)) {
2769 return PP_CURSORTYPE_NORTHPANNING
;
2770 } else if (angle
< - (M_PI
* 1.0 / 8.0)) {
2772 return PP_CURSORTYPE_NORTHEASTPANNING
;
2773 } else if (angle
< M_PI
* 1.0 / 8.0) {
2775 return PP_CURSORTYPE_EASTPANNING
;
2776 } else if (angle
< M_PI
* 3.0 / 8.0) {
2778 return PP_CURSORTYPE_SOUTHEASTPANNING
;
2779 } else if (angle
< M_PI
* 5.0 / 8.0) {
2781 return PP_CURSORTYPE_SOUTHPANNING
;
2782 } else if (angle
< M_PI
* 7.0 / 8.0) {
2784 return PP_CURSORTYPE_SOUTHWESTPANNING
;
2787 // went around the circle, going west again
2788 return PP_CURSORTYPE_WESTPANNING
;
2791 void Instance::ConfigureNumberImageGenerator() {
2792 std::vector
<pp::ImageData
> num_images
= GetThumbnailResources();
2793 pp::ImageData number_background
= CreateResourceImage(
2794 PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_NUM_BACKGROUND
);
2795 number_image_generator_
->Configure(number_background
,
2800 NumberImageGenerator
* Instance::number_image_generator() {
2801 if (!number_image_generator_
.get()) {
2802 number_image_generator_
.reset(new NumberImageGenerator(this));
2803 ConfigureNumberImageGenerator();
2805 return number_image_generator_
.get();
2808 int Instance::GetScaled(int x
) const {
2809 return static_cast<int>(x
* device_scale_
);
2812 void Instance::UserMetricsRecordAction(const std::string
& action
) {
2813 pp::PDF::UserMetricsRecordAction(this, pp::Var(action
));
2816 PDFScriptableObject::PDFScriptableObject(Instance
* instance
)
2817 : instance_(instance
) {
2820 PDFScriptableObject::~PDFScriptableObject() {
2823 bool PDFScriptableObject::HasMethod(const pp::Var
& name
, pp::Var
* exception
) {
2824 return instance_
->HasScriptableMethod(name
, exception
);
2827 pp::Var
PDFScriptableObject::Call(const pp::Var
& method
,
2828 const std::vector
<pp::Var
>& args
,
2829 pp::Var
* exception
) {
2830 return instance_
->CallScriptableMethod(method
, args
, exception
);
2833 } // namespace chrome_pdf