1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "pdf/instance.h"
7 #include <algorithm> // for min()
8 #define _USE_MATH_DEFINES // for M_PI
9 #include <cmath> // for log() and pow()
13 #include "base/json/json_reader.h"
14 #include "base/json/json_writer.h"
15 #include "base/logging.h"
16 #include "base/strings/string_number_conversions.h"
17 #include "base/strings/string_split.h"
18 #include "base/strings/string_util.h"
19 #include "base/values.h"
20 #include "chrome/browser/chrome_page_zoom_constants.h"
21 #include "chrome/common/content_restriction.h"
22 #include "content/public/common/page_zoom.h"
23 #include "net/base/escape.h"
24 #include "pdf/draw_utils.h"
25 #include "pdf/number_image_generator.h"
27 #include "pdf/resource_consts.h"
28 #include "ppapi/c/dev/ppb_cursor_control_dev.h"
29 #include "ppapi/c/pp_errors.h"
30 #include "ppapi/c/pp_rect.h"
31 #include "ppapi/c/private/ppp_pdf.h"
32 #include "ppapi/c/trusted/ppb_url_loader_trusted.h"
33 #include "ppapi/cpp/core.h"
34 #include "ppapi/cpp/dev/font_dev.h"
35 #include "ppapi/cpp/dev/memory_dev.h"
36 #include "ppapi/cpp/dev/text_input_dev.h"
37 #include "ppapi/cpp/module.h"
38 #include "ppapi/cpp/point.h"
39 #include "ppapi/cpp/private/pdf.h"
40 #include "ppapi/cpp/rect.h"
41 #include "ppapi/cpp/resource.h"
42 #include "ppapi/cpp/url_request_info.h"
43 #include "ui/events/keycodes/keyboard_codes.h"
45 #if defined(OS_MACOSX)
46 #include "base/mac/mac_util.h"
49 namespace chrome_pdf
{
51 struct ToolbarButtonInfo
{
53 Button::ButtonStyle style
;
54 PP_ResourceImage normal
;
55 PP_ResourceImage highlighted
;
56 PP_ResourceImage pressed
;
61 // Uncomment following #define to enable thumbnails.
62 // #define ENABLE_THUMBNAILS
64 const uint32 kToolbarSplashTimeoutMs
= 6000;
65 const uint32 kMessageTextColor
= 0xFF575757;
66 const uint32 kMessageTextSize
= 22;
67 const uint32 kProgressFadeTimeoutMs
= 250;
68 const uint32 kProgressDelayTimeoutMs
= 1000;
69 const uint32 kAutoScrollTimeoutMs
= 50;
70 const double kAutoScrollFactor
= 0.2;
72 // Javascript methods.
73 const char* kJSAccessibility
= "accessibility";
74 const char* kJSDocumentLoadComplete
= "documentLoadComplete";
75 const char* kJSGetHeight
= "getHeight";
76 const char* kJSGetHorizontalScrollbarThickness
=
77 "getHorizontalScrollbarThickness";
78 const char* kJSGetPageLocationNormalized
= "getPageLocationNormalized";
79 const char* kJSGetVerticalScrollbarThickness
= "getVerticalScrollbarThickness";
80 const char* kJSGetWidth
= "getWidth";
81 const char* kJSGetZoomLevel
= "getZoomLevel";
82 const char* kJSGoToPage
= "goToPage";
83 const char* kJSGrayscale
= "grayscale";
84 const char* kJSLoadPreviewPage
= "loadPreviewPage";
85 const char* kJSOnLoad
= "onload";
86 const char* kJSOnPluginSizeChanged
= "onPluginSizeChanged";
87 const char* kJSOnScroll
= "onScroll";
88 const char* kJSPageXOffset
= "pageXOffset";
89 const char* kJSPageYOffset
= "pageYOffset";
90 const char* kJSPrintPreviewPageCount
= "printPreviewPageCount";
91 const char* kJSReload
= "reload";
92 const char* kJSRemovePrintButton
= "removePrintButton";
93 const char* kJSResetPrintPreviewUrl
= "resetPrintPreviewUrl";
94 const char* kJSSendKeyEvent
= "sendKeyEvent";
95 const char* kJSSetPageNumbers
= "setPageNumbers";
96 const char* kJSSetPageXOffset
= "setPageXOffset";
97 const char* kJSSetPageYOffset
= "setPageYOffset";
98 const char* kJSSetZoomLevel
= "setZoomLevel";
99 const char* kJSZoomFitToHeight
= "fitToHeight";
100 const char* kJSZoomFitToWidth
= "fitToWidth";
101 const char* kJSZoomIn
= "zoomIn";
102 const char* kJSZoomOut
= "zoomOut";
104 // URL reference parameters.
105 // For more possible parameters, see RFC 3778 and the "PDF Open Parameters"
106 // document from Adobe.
107 const char kDelimiters
[] = "#&";
108 const char kNamedDest
[] = "nameddest";
109 const char kPage
[] = "page";
111 const char kChromePrint
[] = "chrome://print/";
113 // Dictionary Value key names for the document accessibility info
114 const char kAccessibleNumberOfPages
[] = "numberOfPages";
115 const char kAccessibleLoaded
[] = "loaded";
116 const char kAccessibleCopyable
[] = "copyable";
118 const ToolbarButtonInfo kPDFToolbarButtons
[] = {
119 { kFitToPageButtonId
, Button::BUTTON_STATE
,
120 PP_RESOURCEIMAGE_PDF_BUTTON_FTP
,
121 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_HOVER
,
122 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_PRESSED
},
123 { kFitToWidthButtonId
, Button::BUTTON_STATE
,
124 PP_RESOURCEIMAGE_PDF_BUTTON_FTW
,
125 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_HOVER
,
126 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_PRESSED
},
127 { kZoomOutButtonId
, Button::BUTTON_CLICKABLE
,
128 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT
,
129 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_HOVER
,
130 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_PRESSED
},
131 { kZoomInButtonId
, Button::BUTTON_CLICKABLE
,
132 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN
,
133 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_HOVER
,
134 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_PRESSED
},
135 { kSaveButtonId
, Button::BUTTON_CLICKABLE
,
136 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE
,
137 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE_HOVER
,
138 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE_PRESSED
},
139 { kPrintButtonId
, Button::BUTTON_CLICKABLE
,
140 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT
,
141 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_HOVER
,
142 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_PRESSED
},
145 const ToolbarButtonInfo kPDFNoPrintToolbarButtons
[] = {
146 { kFitToPageButtonId
, Button::BUTTON_STATE
,
147 PP_RESOURCEIMAGE_PDF_BUTTON_FTP
,
148 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_HOVER
,
149 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_PRESSED
},
150 { kFitToWidthButtonId
, Button::BUTTON_STATE
,
151 PP_RESOURCEIMAGE_PDF_BUTTON_FTW
,
152 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_HOVER
,
153 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_PRESSED
},
154 { kZoomOutButtonId
, Button::BUTTON_CLICKABLE
,
155 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT
,
156 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_HOVER
,
157 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_PRESSED
},
158 { kZoomInButtonId
, Button::BUTTON_CLICKABLE
,
159 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN
,
160 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_HOVER
,
161 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_PRESSED
},
162 { kSaveButtonId
, Button::BUTTON_CLICKABLE
,
163 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE
,
164 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE_HOVER
,
165 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE_PRESSED
},
166 { kPrintButtonId
, Button::BUTTON_CLICKABLE
,
167 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_DISABLED
,
168 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_DISABLED
,
169 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_DISABLED
}
172 const ToolbarButtonInfo kPrintPreviewToolbarButtons
[] = {
173 { kFitToPageButtonId
, Button::BUTTON_STATE
,
174 PP_RESOURCEIMAGE_PDF_BUTTON_FTP
,
175 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_HOVER
,
176 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_PRESSED
},
177 { kFitToWidthButtonId
, Button::BUTTON_STATE
,
178 PP_RESOURCEIMAGE_PDF_BUTTON_FTW
,
179 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_HOVER
,
180 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_PRESSED
},
181 { kZoomOutButtonId
, Button::BUTTON_CLICKABLE
,
182 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT
,
183 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_HOVER
,
184 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_PRESSED
},
185 { kZoomInButtonId
, Button::BUTTON_CLICKABLE
,
186 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_END
,
187 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_END_HOVER
,
188 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_END_PRESSED
},
191 static const char kPPPPdfInterface
[] = PPP_PDF_INTERFACE_1
;
193 PP_Var
GetLinkAtPosition(PP_Instance instance
, PP_Point point
) {
196 pp::Instance::GetPerInstanceObject(instance
, kPPPPdfInterface
);
198 var
= static_cast<Instance
*>(object
)->GetLinkAtPosition(pp::Point(point
));
202 void Transform(PP_Instance instance
, PP_PrivatePageTransformType type
) {
204 pp::Instance::GetPerInstanceObject(instance
, kPPPPdfInterface
);
206 Instance
* obj_instance
= static_cast<Instance
*>(object
);
208 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CW
:
209 obj_instance
->RotateClockwise();
211 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CCW
:
212 obj_instance
->RotateCounterclockwise();
218 const PPP_Pdf ppp_private
= {
223 int ExtractPrintPreviewPageIndex(const std::string
& src_url
) {
224 // Sample |src_url| format: chrome://print/id/page_index/print.pdf
225 std::vector
<std::string
> url_substr
;
226 base::SplitString(src_url
.substr(strlen(kChromePrint
)), '/', &url_substr
);
227 if (url_substr
.size() != 3)
230 if (url_substr
[2] != "print.pdf")
234 if (!base::StringToInt(url_substr
[1], &page_index
))
239 bool IsPrintPreviewUrl(const std::string
& url
) {
240 return url
.substr(0, strlen(kChromePrint
)) == kChromePrint
;
243 void ScalePoint(float scale
, pp::Point
* point
) {
244 point
->set_x(static_cast<int>(point
->x() * scale
));
245 point
->set_y(static_cast<int>(point
->y() * scale
));
248 void ScaleRect(float scale
, pp::Rect
* rect
) {
249 int left
= static_cast<int>(floorf(rect
->x() * scale
));
250 int top
= static_cast<int>(floorf(rect
->y() * scale
));
251 int right
= static_cast<int>(ceilf((rect
->x() + rect
->width()) * scale
));
252 int bottom
= static_cast<int>(ceilf((rect
->y() + rect
->height()) * scale
));
253 rect
->SetRect(left
, top
, right
- left
, bottom
- top
);
257 T
ClipToRange(T value
, T lower_boundary
, T upper_boundary
) {
258 DCHECK(lower_boundary
<= upper_boundary
);
259 return std::max
<T
>(lower_boundary
, std::min
<T
>(value
, upper_boundary
));
264 Instance::Instance(PP_Instance instance
)
265 : pp::InstancePrivate(instance
),
266 pp::Find_Private(this),
267 pp::Printing_Dev(this),
268 pp::Selection_Dev(this),
269 pp::WidgetClient_Dev(this),
271 cursor_(PP_CURSORTYPE_POINTER
),
272 timer_pending_(false),
273 current_timer_id_(0),
276 printing_enabled_(true),
277 hidpi_enabled_(false),
278 full_(IsFullFrame()),
279 zoom_mode_(full_
? ZOOM_AUTO
: ZOOM_SCALE
),
280 did_call_start_loading_(false),
281 is_autoscroll_(false),
282 scrollbar_thickness_(-1),
283 scrollbar_reserved_thickness_(-1),
284 current_tb_info_(NULL
),
285 current_tb_info_size_(0),
286 paint_manager_(this, this, true),
287 delayed_progress_timer_id_(0),
289 painted_first_page_(false),
290 show_page_indicator_(false),
291 document_load_state_(LOAD_STATE_LOADING
),
292 preview_document_load_state_(LOAD_STATE_COMPLETE
),
293 told_browser_about_unsupported_feature_(false),
294 print_preview_page_count_(0) {
295 loader_factory_
.Initialize(this);
296 timer_factory_
.Initialize(this);
297 form_factory_
.Initialize(this);
298 print_callback_factory_
.Initialize(this);
299 engine_
.reset(PDFEngine::Create(this));
300 pp::Module::Get()->AddPluginInterface(kPPPPdfInterface
, &ppp_private
);
301 AddPerInstanceObject(kPPPPdfInterface
, this);
303 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_MOUSE
);
304 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_WHEEL
);
305 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_KEYBOARD
);
306 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_TOUCH
);
309 Instance::~Instance() {
310 RemovePerInstanceObject(kPPPPdfInterface
, this);
313 bool Instance::Init(uint32_t argc
, const char* argn
[], const char* argv
[]) {
314 // For now, we hide HiDPI support behind a flag.
315 if (pp::PDF::IsFeatureEnabled(this, PP_PDFFEATURE_HIDPI
))
316 hidpi_enabled_
= true;
318 printing_enabled_
= pp::PDF::IsFeatureEnabled(this, PP_PDFFEATURE_PRINTING
);
319 if (printing_enabled_
) {
320 CreateToolbar(kPDFToolbarButtons
, arraysize(kPDFToolbarButtons
));
322 CreateToolbar(kPDFNoPrintToolbarButtons
,
323 arraysize(kPDFNoPrintToolbarButtons
));
328 // Load autoscroll anchor image.
330 CreateResourceImage(PP_RESOURCEIMAGE_PDF_PAN_SCROLL_ICON
);
332 #ifdef ENABLE_THUMBNAILS
335 const char* url
= NULL
;
336 for (uint32_t i
= 0; i
< argc
; ++i
) {
337 if (strcmp(argn
[i
], "src") == 0) {
346 CreatePageIndicator(IsPrintPreviewUrl(url
));
349 // For PDFs embedded in a frame, we don't get the data automatically like we
350 // do for full-frame loads. Start loading the data manually.
354 ZoomLimitsChanged(kMinZoom
, kMaxZoom
);
356 text_input_
.reset(new pp::TextInput_Dev(this));
359 return engine_
->New(url
);
362 bool Instance::HandleDocumentLoad(const pp::URLLoader
& loader
) {
363 delayed_progress_timer_id_
= ScheduleTimer(kProgressBarId
,
364 kProgressDelayTimeoutMs
);
365 return engine_
->HandleDocumentLoad(loader
);
368 bool Instance::HandleInputEvent(const pp::InputEvent
& event
) {
369 // To simplify things, convert the event into device coordinates if it is
371 pp::InputEvent
event_device_res(event
);
373 pp::MouseInputEvent
mouse_event(event
);
374 if (!mouse_event
.is_null()) {
375 pp::Point point
= mouse_event
.GetPosition();
376 pp::Point movement
= mouse_event
.GetMovement();
377 ScalePoint(device_scale_
, &point
);
378 ScalePoint(device_scale_
, &movement
);
379 mouse_event
= pp::MouseInputEvent(
382 event
.GetTimeStamp(),
383 event
.GetModifiers(),
384 mouse_event
.GetButton(),
386 mouse_event
.GetClickCount(),
388 event_device_res
= mouse_event
;
392 // Check if we need to go to autoscroll mode.
393 if (event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE
&&
394 (event
.GetModifiers() & PP_INPUTEVENT_MODIFIER_MIDDLEBUTTONDOWN
)) {
395 pp::MouseInputEvent
mouse_event(event_device_res
);
396 pp::Point pos
= mouse_event
.GetPosition();
397 EnableAutoscroll(pos
);
398 UpdateCursor(CalculateAutoscroll(pos
));
401 // Quit autoscrolling on any other event.
405 #ifdef ENABLE_THUMBNAILS
406 if (event
.GetType() == PP_INPUTEVENT_TYPE_MOUSELEAVE
)
407 thumbnails_
.SlideOut();
409 if (thumbnails_
.HandleEvent(event_device_res
))
413 if (toolbar_
->HandleEvent(event_device_res
))
416 #ifdef ENABLE_THUMBNAILS
417 if (v_scrollbar_
.get() && event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE
) {
418 pp::MouseInputEvent
mouse_event(event
);
419 pp::Point pt
= mouse_event
.GetPosition();
420 pp::Rect v_scrollbar_rc
;
421 v_scrollbar_
->GetLocation(&v_scrollbar_rc
);
422 // There is a bug (https://bugs.webkit.org/show_bug.cgi?id=45208)
423 // in the webkit that makes event.u.mouse.button
424 // equal to PP_INPUTEVENT_MOUSEBUTTON_LEFT, even when no button is pressed.
425 // To work around this issue we use modifier for now, and will switch
426 // to button once the bug is fixed and webkit got merged back to our tree.
427 if (v_scrollbar_rc
.Contains(pt
) &&
428 (event
.GetModifiers() & PP_INPUTEVENT_MODIFIER_LEFTBUTTONDOWN
)) {
429 thumbnails_
.SlideIn();
432 // When scrollbar is in the scrolling mode we should display thumbnails
433 // even the mouse is outside the thumbnail and scrollbar areas.
434 // If mouse is outside plugin area, we are still getting mouse move events
435 // while scrolling. See bug description for details:
436 // http://code.google.com/p/chromium/issues/detail?id=56444
437 if (!v_scrollbar_rc
.Contains(pt
) && thumbnails_
.visible() &&
438 !(event
.GetModifiers() & PP_INPUTEVENT_MODIFIER_LEFTBUTTONDOWN
) &&
439 !thumbnails_
.rect().Contains(pt
)) {
440 thumbnails_
.SlideOut();
445 // Need to pass the event to the engine first, since if we're over an edit
446 // control we want it to get keyboard events (like space) instead of the
448 // TODO: will have to offset the mouse coordinates once we support bidi and
449 // there could be scrollbars on the left.
450 pp::InputEvent
offset_event(event_device_res
);
451 bool try_engine_first
= true;
452 switch (offset_event
.GetType()) {
453 case PP_INPUTEVENT_TYPE_MOUSEDOWN
:
454 case PP_INPUTEVENT_TYPE_MOUSEUP
:
455 case PP_INPUTEVENT_TYPE_MOUSEMOVE
:
456 case PP_INPUTEVENT_TYPE_MOUSEENTER
:
457 case PP_INPUTEVENT_TYPE_MOUSELEAVE
: {
458 pp::MouseInputEvent
mouse_event(event_device_res
);
459 pp::MouseInputEvent
mouse_event_dip(event
);
460 pp::Point point
= mouse_event
.GetPosition();
461 point
.set_x(point
.x() - available_area_
.x());
462 offset_event
= pp::MouseInputEvent(
465 event
.GetTimeStamp(),
466 event
.GetModifiers(),
467 mouse_event
.GetButton(),
469 mouse_event
.GetClickCount(),
470 mouse_event
.GetMovement());
471 if (!engine_
->IsSelecting()) {
472 if (!IsOverlayScrollbar() &&
473 !available_area_
.Contains(mouse_event
.GetPosition())) {
474 try_engine_first
= false;
475 } else if (IsOverlayScrollbar()) {
477 if ((v_scrollbar_
.get() && v_scrollbar_
->GetLocation(&temp
) &&
478 temp
.Contains(mouse_event_dip
.GetPosition())) ||
479 (h_scrollbar_
.get() && h_scrollbar_
->GetLocation(&temp
) &&
480 temp
.Contains(mouse_event_dip
.GetPosition()))) {
481 try_engine_first
= false;
490 if (try_engine_first
&& engine_
->HandleEvent(offset_event
))
493 // Left/Right arrows should scroll to the beginning of the Prev/Next page if
494 // there is no horizontal scroll bar.
495 // If fit-to-height, PgDown/PgUp should scroll to the beginning of the
497 if (v_scrollbar_
.get() && event
.GetType() == PP_INPUTEVENT_TYPE_KEYDOWN
) {
498 pp::KeyboardInputEvent
keyboard_event(event
);
500 (!h_scrollbar_
.get() &&
501 keyboard_event
.GetKeyCode() == ui::VKEY_RIGHT
) ||
502 (zoom_mode_
== ZOOM_FIT_TO_PAGE
&&
503 keyboard_event
.GetKeyCode() == ui::VKEY_NEXT
);
505 (!h_scrollbar_
.get() &&
506 keyboard_event
.GetKeyCode() == ui::VKEY_LEFT
) ||
507 (zoom_mode_
== ZOOM_FIT_TO_PAGE
&&
508 keyboard_event
.GetKeyCode() == ui::VKEY_PRIOR
);
511 int page
= engine_
->GetFirstVisiblePage();
512 // Engine calculates visible page including delimiter to the page size.
513 // We need to check here if the page itself is completely out of view and
514 // scroll to the next one in that case.
515 if (engine_
->GetPageRect(page
).bottom() * zoom_
<=
516 v_scrollbar_
->GetValue())
518 ScrollToPage(page
+ 1);
519 UpdateCursor(PP_CURSORTYPE_POINTER
);
521 } else if (page_up
) {
522 int page
= engine_
->GetFirstVisiblePage();
523 if (engine_
->GetPageRect(page
).y() * zoom_
>= v_scrollbar_
->GetValue())
526 UpdateCursor(PP_CURSORTYPE_POINTER
);
531 if (v_scrollbar_
.get() && v_scrollbar_
->HandleEvent(event
)) {
532 UpdateCursor(PP_CURSORTYPE_POINTER
);
536 if (h_scrollbar_
.get() && h_scrollbar_
->HandleEvent(event
)) {
537 UpdateCursor(PP_CURSORTYPE_POINTER
);
541 if (timer_pending_
&&
542 (event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEUP
||
543 event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE
)) {
544 timer_factory_
.CancelAll();
545 timer_pending_
= false;
546 } else if (event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE
&&
547 engine_
->IsSelecting()) {
548 bool set_timer
= false;
549 pp::MouseInputEvent
mouse_event(event
);
550 if (v_scrollbar_
.get() &&
551 (mouse_event
.GetPosition().y() <= 0 ||
552 mouse_event
.GetPosition().y() >= (plugin_dip_size_
.height() - 1))) {
553 v_scrollbar_
->ScrollBy(
554 PP_SCROLLBY_LINE
, mouse_event
.GetPosition().y() >= 0 ? 1: -1);
557 if (h_scrollbar_
.get() &&
558 (mouse_event
.GetPosition().x() <= 0 ||
559 mouse_event
.GetPosition().x() >= (plugin_dip_size_
.width() - 1))) {
560 h_scrollbar_
->ScrollBy(PP_SCROLLBY_LINE
,
561 mouse_event
.GetPosition().x() >= 0 ? 1: -1);
566 last_mouse_event_
= pp::MouseInputEvent(event
);
568 pp::CompletionCallback callback
=
569 timer_factory_
.NewCallback(&Instance::OnTimerFired
);
570 pp::Module::Get()->core()->CallOnMainThread(kDragTimerMs
, callback
);
571 timer_pending_
= true;
575 if (event
.GetType() == PP_INPUTEVENT_TYPE_KEYDOWN
&&
576 event
.GetModifiers() & kDefaultKeyModifier
) {
577 pp::KeyboardInputEvent
keyboard_event(event
);
578 switch (keyboard_event
.GetKeyCode()) {
580 engine_
->SelectAll();
585 // Return true for unhandled clicks so the plugin takes focus.
586 return (event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN
);
589 void Instance::DidChangeView(const pp::View
& view
) {
590 pp::Rect
view_rect(view
.GetRect());
591 float device_scale
= 1.0f
;
592 float old_device_scale
= device_scale_
;
594 device_scale
= view
.GetDeviceScale();
595 pp::Size
view_device_size(view_rect
.width() * device_scale
,
596 view_rect
.height() * device_scale
);
597 if (view_device_size
== plugin_size_
&& device_scale
== device_scale_
)
598 return; // We don't care about the position, only the size.
600 image_data_
= pp::ImageData();
601 device_scale_
= device_scale
;
602 plugin_dip_size_
= view_rect
.size();
603 plugin_size_
= view_device_size
;
605 paint_manager_
.SetSize(view_device_size
, device_scale_
);
607 image_data_
= pp::ImageData(this,
608 PP_IMAGEDATAFORMAT_BGRA_PREMUL
,
611 if (image_data_
.is_null()) {
612 DCHECK(plugin_size_
.IsEmpty());
616 // View dimensions changed, disable autoscroll (if it was enabled).
619 OnGeometryChanged(zoom_
, old_device_scale
);
622 pp::Var
Instance::GetInstanceObject() {
623 if (instance_object_
.is_undefined()) {
624 PDFScriptableObject
* object
= new PDFScriptableObject(this);
625 // The pp::Var takes ownership of object here.
626 instance_object_
= pp::VarPrivate(this, object
);
629 return instance_object_
;
632 pp::Var
Instance::GetLinkAtPosition(const pp::Point
& point
) {
633 pp::Point
offset_point(point
);
634 ScalePoint(device_scale_
, &offset_point
);
635 offset_point
.set_x(offset_point
.x() - available_area_
.x());
636 return engine_
->GetLinkAtPosition(offset_point
);
639 pp::Var
Instance::GetSelectedText(bool html
) {
640 if (html
|| !engine_
->HasPermission(PDFEngine::PERMISSION_COPY
))
642 return engine_
->GetSelectedText();
645 void Instance::InvalidateWidget(pp::Widget_Dev widget
,
646 const pp::Rect
& dirty_rect
) {
647 if (v_scrollbar_
.get() && *v_scrollbar_
== widget
) {
648 if (!image_data_
.is_null())
649 v_scrollbar_
->Paint(dirty_rect
.pp_rect(), &image_data_
);
650 } else if (h_scrollbar_
.get() && *h_scrollbar_
== widget
) {
651 if (!image_data_
.is_null())
652 h_scrollbar_
->Paint(dirty_rect
.pp_rect(), &image_data_
);
654 // Possible to hit this condition since sometimes the scrollbar codes posts
655 // a task to do something later, and we could have deleted our reference in
660 pp::Rect dirty_rect_scaled
= dirty_rect
;
661 ScaleRect(device_scale_
, &dirty_rect_scaled
);
662 paint_manager_
.InvalidateRect(dirty_rect_scaled
);
665 void Instance::ScrollbarValueChanged(pp::Scrollbar_Dev scrollbar
,
667 value
= GetScaled(value
);
668 if (v_scrollbar_
.get() && *v_scrollbar_
== scrollbar
) {
669 engine_
->ScrolledToYPosition(value
);
671 v_scrollbar_
->GetLocation(&rc
);
672 int32 doc_height
= GetDocumentPixelHeight();
673 doc_height
-= GetScaled(rc
.height());
674 #ifdef ENABLE_THUMBNAILS
675 if (thumbnails_
.visible()) {
676 thumbnails_
.SetPosition(value
, doc_height
, true);
680 plugin_size_
.width() - page_indicator_
.rect().width() -
681 GetScaled(GetScrollbarReservedThickness()),
682 page_indicator_
.GetYPosition(value
, doc_height
, plugin_size_
.height()));
683 page_indicator_
.MoveTo(origin
, page_indicator_
.visible());
684 } else if (h_scrollbar_
.get() && *h_scrollbar_
== scrollbar
) {
685 engine_
->ScrolledToXPosition(value
);
689 void Instance::ScrollbarOverlayChanged(pp::Scrollbar_Dev scrollbar
,
691 scrollbar_reserved_thickness_
= overlay
? 0 : scrollbar_thickness_
;
692 OnGeometryChanged(zoom_
, device_scale_
);
695 uint32_t Instance::QuerySupportedPrintOutputFormats() {
696 return engine_
->QuerySupportedPrintOutputFormats();
699 int32_t Instance::PrintBegin(const PP_PrintSettings_Dev
& print_settings
) {
700 // For us num_pages is always equal to the number of pages in the PDF
701 // document irrespective of the printable area.
702 int32_t ret
= engine_
->GetNumberOfPages();
706 uint32_t supported_formats
= engine_
->QuerySupportedPrintOutputFormats();
707 if ((print_settings
.format
& supported_formats
) == 0)
710 print_settings_
.is_printing
= true;
711 print_settings_
.pepper_print_settings
= print_settings
;
712 engine_
->PrintBegin();
716 pp::Resource
Instance::PrintPages(
717 const PP_PrintPageNumberRange_Dev
* page_ranges
,
718 uint32_t page_range_count
) {
719 if (!print_settings_
.is_printing
)
720 return pp::Resource();
722 print_settings_
.print_pages_called_
= true;
723 return engine_
->PrintPages(page_ranges
, page_range_count
,
724 print_settings_
.pepper_print_settings
);
727 void Instance::PrintEnd() {
728 if (print_settings_
.print_pages_called_
)
729 UserMetricsRecordAction("PDF.PrintPage");
730 print_settings_
.Clear();
734 bool Instance::IsPrintScalingDisabled() {
735 return !engine_
->GetPrintScaling();
738 bool Instance::StartFind(const std::string
& text
, bool case_sensitive
) {
739 engine_
->StartFind(text
.c_str(), case_sensitive
);
743 void Instance::SelectFindResult(bool forward
) {
744 engine_
->SelectFindResult(forward
);
747 void Instance::StopFind() {
751 void Instance::Zoom(double scale
, bool text_only
) {
752 UserMetricsRecordAction("PDF.ZoomFromBrowser");
753 SetZoom(ZOOM_SCALE
, scale
);
756 void Instance::ZoomChanged(double factor
) {
758 Zoom_Dev::ZoomChanged(factor
);
761 void Instance::OnPaint(const std::vector
<pp::Rect
>& paint_rects
,
762 std::vector
<PaintManager::ReadyRect
>* ready
,
763 std::vector
<pp::Rect
>* pending
) {
764 if (image_data_
.is_null()) {
765 DCHECK(plugin_size_
.IsEmpty());
769 first_paint_
= false;
770 pp::Rect rect
= pp::Rect(pp::Point(), plugin_size_
);
771 unsigned int color
= kBackgroundColorA
<< 24 |
772 kBackgroundColorR
<< 16 |
773 kBackgroundColorG
<< 8 |
775 FillRect(rect
, color
);
776 ready
->push_back(PaintManager::ReadyRect(rect
, image_data_
, true));
777 *pending
= paint_rects
;
783 for (size_t i
= 0; i
< paint_rects
.size(); i
++) {
784 // Intersect with plugin area since there could be pending invalidates from
785 // when the plugin area was larger.
787 paint_rects
[i
].Intersect(pp::Rect(pp::Point(), plugin_size_
));
791 pp::Rect pdf_rect
= available_area_
.Intersect(rect
);
792 if (!pdf_rect
.IsEmpty()) {
793 pdf_rect
.Offset(available_area_
.x() * -1, 0);
795 std::vector
<pp::Rect
> pdf_ready
;
796 std::vector
<pp::Rect
> pdf_pending
;
797 engine_
->Paint(pdf_rect
, &image_data_
, &pdf_ready
, &pdf_pending
);
798 for (size_t j
= 0; j
< pdf_ready
.size(); ++j
) {
799 pdf_ready
[j
].Offset(available_area_
.point());
801 PaintManager::ReadyRect(pdf_ready
[j
], image_data_
, false));
803 for (size_t j
= 0; j
< pdf_pending
.size(); ++j
) {
804 pdf_pending
[j
].Offset(available_area_
.point());
805 pending
->push_back(pdf_pending
[j
]);
809 for (size_t j
= 0; j
< background_parts_
.size(); ++j
) {
810 pp::Rect intersection
= background_parts_
[j
].location
.Intersect(rect
);
811 if (!intersection
.IsEmpty()) {
812 FillRect(intersection
, background_parts_
[j
].color
);
814 PaintManager::ReadyRect(intersection
, image_data_
, false));
818 if (document_load_state_
== LOAD_STATE_FAILED
) {
819 pp::Point top_center
;
820 top_center
.set_x(plugin_size_
.width() / 2);
821 top_center
.set_y(plugin_size_
.height() / 2);
822 DrawText(top_center
, PP_RESOURCESTRING_PDFLOAD_FAILED
);
825 #ifdef ENABLE_THUMBNAILS
826 thumbnails_
.Paint(&image_data_
, rect
);
830 engine_
->PostPaint();
832 // Must paint scrollbars after the background parts, in case we have an
833 // overlay scrollbar that's over the background. We also do this in a separate
834 // loop because the scrollbar painting logic uses the signal of whether there
835 // are pending paints or not to figure out if it should draw right away or
837 for (size_t i
= 0; i
< paint_rects
.size(); i
++) {
838 PaintIfWidgetIntersects(h_scrollbar_
.get(), paint_rects
[i
], ready
, pending
);
839 PaintIfWidgetIntersects(v_scrollbar_
.get(), paint_rects
[i
], ready
, pending
);
842 if (progress_bar_
.visible())
843 PaintOverlayControl(&progress_bar_
, &image_data_
, ready
);
845 if (page_indicator_
.visible())
846 PaintOverlayControl(&page_indicator_
, &image_data_
, ready
);
848 if (toolbar_
->current_transparency() != kTransparentAlpha
)
849 PaintOverlayControl(toolbar_
.get(), &image_data_
, ready
);
851 // Paint autoscroll anchor if needed.
852 if (is_autoscroll_
) {
853 size_t limit
= ready
->size();
854 for (size_t i
= 0; i
< limit
; i
++) {
855 pp::Rect anchor_rect
= autoscroll_rect_
.Intersect((*ready
)[i
].rect
);
856 if (!anchor_rect
.IsEmpty()) {
857 pp::Rect draw_rc
= pp::Rect(
858 pp::Point(anchor_rect
.x() - autoscroll_rect_
.x(),
859 anchor_rect
.y() - autoscroll_rect_
.y()),
861 // Paint autoscroll anchor.
862 AlphaBlend(autoscroll_anchor_
, draw_rc
,
863 &image_data_
, anchor_rect
.point(), kOpaqueAlpha
);
869 void Instance::PaintOverlayControl(
871 pp::ImageData
* image_data
,
872 std::vector
<PaintManager::ReadyRect
>* ready
) {
873 // Make sure that we only paint overlay controls over an area that's ready,
874 // i.e. not pending. Otherwise we'll mark the control rect as ready and
875 // it'll overwrite the pdf region.
876 std::list
<pp::Rect
> ctrl_rects
;
877 for (size_t i
= 0; i
< ready
->size(); i
++) {
878 pp::Rect rc
= ctrl
->rect().Intersect((*ready
)[i
].rect
);
880 ctrl_rects
.push_back(rc
);
883 if (!ctrl_rects
.empty()) {
884 ctrl
->PaintMultipleRects(image_data
, ctrl_rects
);
886 std::list
<pp::Rect
>::iterator iter
;
887 for (iter
= ctrl_rects
.begin(); iter
!= ctrl_rects
.end(); ++iter
) {
888 ready
->push_back(PaintManager::ReadyRect(*iter
, *image_data
, false));
893 void Instance::DidOpen(int32_t result
) {
894 if (result
== PP_OK
) {
895 engine_
->HandleDocumentLoad(embed_loader_
);
896 } else if (result
!= PP_ERROR_ABORTED
) { // Can happen in tests.
901 void Instance::DidOpenPreview(int32_t result
) {
902 if (result
== PP_OK
) {
903 preview_engine_
.reset(PDFEngine::Create(new PreviewModeClient(this)));
904 preview_engine_
->HandleDocumentLoad(embed_preview_loader_
);
910 void Instance::PaintIfWidgetIntersects(
911 pp::Widget_Dev
* widget
,
912 const pp::Rect
& rect
,
913 std::vector
<PaintManager::ReadyRect
>* ready
,
914 std::vector
<pp::Rect
>* pending
) {
919 if (!widget
->GetLocation(&location
))
922 ScaleRect(device_scale_
, &location
);
923 location
= location
.Intersect(rect
);
924 if (location
.IsEmpty())
927 if (IsOverlayScrollbar()) {
928 // If we're using overlay scrollbars, and there are pending paints under the
929 // scrollbar, don't update the scrollbar instantly. While it would be nice,
930 // we would need to double buffer the plugin area in order to make this
931 // work. This is because we'd need to always have a copy of what the pdf
932 // under the scrollbar looks like, and additionally we couldn't paint the
933 // pdf under the scrollbar if it's ready until we got the preceding flush.
934 // So in practice, it would make painting slower and introduce extra buffer
935 // copies for the general case.
936 for (size_t i
= 0; i
< pending
->size(); ++i
) {
937 if ((*pending
)[i
].Intersects(location
))
941 // Even if none of the pending paints are under the scrollbar, we never want
942 // to paint it if it's over the pdf if there are other pending paints.
943 // Otherwise different parts of the pdf plugin would display at different
945 if (!pending
->empty() && available_area_
.Intersects(rect
)) {
946 pending
->push_back(location
);
951 pp::Rect location_dip
= location
;
952 ScaleRect(1.0f
/ device_scale_
, &location_dip
);
954 DCHECK(!image_data_
.is_null());
955 widget
->Paint(location_dip
, &image_data_
);
957 // Re-scale the rectangle from DIPs to device pixels, so we ensure that we
958 // don't miss any pixels due to rounding outwards in ScaleRect.
959 location
= location_dip
;
960 ScaleRect(device_scale_
, &location
);
962 ready
->push_back(PaintManager::ReadyRect(location
, image_data_
, true));
965 void Instance::OnTimerFired(int32_t) {
966 HandleInputEvent(last_mouse_event_
);
969 void Instance::OnClientTimerFired(int32_t id
) {
970 engine_
->OnCallback(id
);
973 void Instance::OnControlTimerFired(int32_t,
974 const uint32
& control_id
,
975 const uint32
& timer_id
) {
976 if (control_id
== toolbar_
->id()) {
977 toolbar_
->OnTimerFired(timer_id
);
978 } else if (control_id
== progress_bar_
.id()) {
979 if (timer_id
== delayed_progress_timer_id_
) {
980 if (document_load_state_
== LOAD_STATE_LOADING
&&
981 !progress_bar_
.visible()) {
982 progress_bar_
.Fade(true, kProgressFadeTimeoutMs
);
984 delayed_progress_timer_id_
= 0;
986 progress_bar_
.OnTimerFired(timer_id
);
988 } else if (control_id
== kAutoScrollId
) {
989 if (is_autoscroll_
) {
990 if (autoscroll_x_
!= 0 && h_scrollbar_
.get()) {
991 h_scrollbar_
->ScrollBy(PP_SCROLLBY_PIXEL
, autoscroll_x_
);
993 if (autoscroll_y_
!= 0 && v_scrollbar_
.get()) {
994 v_scrollbar_
->ScrollBy(PP_SCROLLBY_PIXEL
, autoscroll_y_
);
998 ScheduleTimer(kAutoScrollId
, kAutoScrollTimeoutMs
);
1000 } else if (control_id
== kPageIndicatorId
) {
1001 page_indicator_
.OnTimerFired(timer_id
);
1003 #ifdef ENABLE_THUMBNAILS
1004 else if (control_id
== thumbnails_
.id()) {
1005 thumbnails_
.OnTimerFired(timer_id
);
1010 void Instance::CalculateBackgroundParts() {
1011 background_parts_
.clear();
1012 int v_scrollbar_thickness
=
1013 GetScaled(v_scrollbar_
.get() ? GetScrollbarReservedThickness() : 0);
1014 int h_scrollbar_thickness
=
1015 GetScaled(h_scrollbar_
.get() ? GetScrollbarReservedThickness() : 0);
1016 int width_without_scrollbar
= std::max(
1017 plugin_size_
.width() - v_scrollbar_thickness
, 0);
1018 int height_without_scrollbar
= std::max(
1019 plugin_size_
.height() - h_scrollbar_thickness
, 0);
1020 int left_width
= available_area_
.x();
1021 int right_start
= available_area_
.right();
1022 int right_width
= abs(width_without_scrollbar
- available_area_
.right());
1023 int bottom
= std::min(available_area_
.bottom(), height_without_scrollbar
);
1025 // Add the left, right, and bottom rectangles. Note: we assume only
1026 // horizontal centering.
1027 BackgroundPart part
;
1028 part
.color
= kBackgroundColorA
<< 24 |
1029 kBackgroundColorR
<< 16 |
1030 kBackgroundColorG
<< 8 |
1032 part
.location
= 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
, unsigned int color
) {
1070 DCHECK(!image_data_
.is_null() || rect
.IsEmpty());
1071 unsigned int* buffer_start
= static_cast<unsigned int*>(image_data_
.data());
1072 int stride
= image_data_
.stride();
1073 unsigned int* ptr
= buffer_start
+ rect
.y() * stride
/ 4 + rect
.x();
1074 int height
= rect
.height();
1075 int width
= rect
.width();
1076 for (int y
= 0; y
< height
; ++y
) {
1077 for (int x
= 0; x
< width
; ++x
)
1083 void Instance::DocumentSizeUpdated(const pp::Size
& size
) {
1084 document_size_
= size
;
1086 OnGeometryChanged(zoom_
, device_scale_
);
1089 void Instance::Invalidate(const pp::Rect
& rect
) {
1090 pp::Rect
offset_rect(rect
);
1091 offset_rect
.Offset(available_area_
.point());
1092 paint_manager_
.InvalidateRect(offset_rect
);
1095 void Instance::Scroll(const pp::Point
& point
) {
1096 pp::Rect scroll_area
= available_area_
;
1097 if (IsOverlayScrollbar()) {
1099 if (h_scrollbar_
.get()) {
1100 h_scrollbar_
->GetLocation(&rc
);
1101 ScaleRect(device_scale_
, &rc
);
1102 if (scroll_area
.bottom() > rc
.y()) {
1103 scroll_area
.set_height(rc
.y() - scroll_area
.y());
1104 paint_manager_
.InvalidateRect(rc
);
1107 if (v_scrollbar_
.get()) {
1108 v_scrollbar_
->GetLocation(&rc
);
1109 ScaleRect(device_scale_
, &rc
);
1110 if (scroll_area
.right() > rc
.x()) {
1111 scroll_area
.set_width(rc
.x() - scroll_area
.x());
1112 paint_manager_
.InvalidateRect(rc
);
1116 paint_manager_
.ScrollRect(scroll_area
, point
);
1118 if (toolbar_
->current_transparency() != kTransparentAlpha
)
1119 paint_manager_
.InvalidateRect(toolbar_
->GetControlsRect());
1121 if (progress_bar_
.visible())
1122 paint_manager_
.InvalidateRect(progress_bar_
.rect());
1125 paint_manager_
.InvalidateRect(autoscroll_rect_
);
1127 if (show_page_indicator_
) {
1128 page_indicator_
.set_current_page(GetPageNumberToDisplay());
1129 page_indicator_
.Splash();
1132 if (page_indicator_
.visible())
1133 paint_manager_
.InvalidateRect(page_indicator_
.rect());
1135 if (on_scroll_callback_
.is_string())
1136 ExecuteScript(on_scroll_callback_
);
1139 void Instance::ScrollToX(int position
) {
1140 if (!h_scrollbar_
.get()) {
1144 int position_dip
= static_cast<int>(position
/ device_scale_
);
1145 h_scrollbar_
->SetValue(position_dip
);
1148 void Instance::ScrollToY(int position
) {
1149 if (!v_scrollbar_
.get()) {
1153 int position_dip
= static_cast<int>(position
/ device_scale_
);
1154 v_scrollbar_
->SetValue(ClipToRange(position_dip
, 0, valid_v_range_
));
1157 void Instance::ScrollToPage(int page
) {
1158 if (!v_scrollbar_
.get())
1161 if (engine_
->GetNumberOfPages() == 0)
1164 int index
= ClipToRange(page
, 0, engine_
->GetNumberOfPages() - 1);
1165 pp::Rect rect
= engine_
->GetPageRect(index
);
1166 // If we are trying to scroll pass the last page,
1167 // scroll to the end of the last page.
1168 int position
= index
< page
? rect
.bottom() : rect
.y();
1169 ScrollToY(position
* zoom_
* device_scale_
);
1172 void Instance::NavigateTo(const std::string
& url
, bool open_in_new_tab
) {
1173 std::string
url_copy(url
);
1175 // Empty |url_copy| is ok, and will effectively be a reload.
1176 // Skip the code below so an empty URL does not turn into "http://", which
1177 // will cause GURL to fail a DCHECK.
1178 if (!url_copy
.empty()) {
1179 // If there's no scheme, add http.
1180 if (url_copy
.find("://") == std::string::npos
&&
1181 url_copy
.find("mailto:") == std::string::npos
) {
1182 url_copy
= std::string("http://") + url_copy
;
1184 // Make sure |url_copy| starts with a valid scheme.
1185 if (url_copy
.find("http://") != 0 &&
1186 url_copy
.find("https://") != 0 &&
1187 url_copy
.find("ftp://") != 0 &&
1188 url_copy
.find("mailto:") != 0) {
1191 // Make sure |url_copy| is not only a scheme.
1192 if (url_copy
== "http://" ||
1193 url_copy
== "https://" ||
1194 url_copy
== "ftp://" ||
1195 url_copy
== "mailto:") {
1199 if (open_in_new_tab
) {
1200 GetWindowObject().Call("open", url_copy
);
1202 GetWindowObject().GetProperty("top").GetProperty("location").
1203 SetProperty("href", url_copy
);
1207 void Instance::UpdateCursor(PP_CursorType_Dev cursor
) {
1208 if (cursor
== cursor_
)
1212 const PPB_CursorControl_Dev
* cursor_interface
=
1213 reinterpret_cast<const PPB_CursorControl_Dev
*>(
1214 pp::Module::Get()->GetBrowserInterface(PPB_CURSOR_CONTROL_DEV_INTERFACE
));
1215 if (!cursor_interface
) {
1220 cursor_interface
->SetCursor(
1221 pp_instance(), cursor_
, pp::ImageData().pp_resource(), NULL
);
1224 void Instance::UpdateTickMarks(const std::vector
<pp::Rect
>& tickmarks
) {
1225 if (!v_scrollbar_
.get())
1228 float inverse_scale
= 1.0f
/ device_scale_
;
1229 std::vector
<pp::Rect
> scaled_tickmarks
= tickmarks
;
1230 for (size_t i
= 0; i
< scaled_tickmarks
.size(); i
++) {
1231 ScaleRect(inverse_scale
, &scaled_tickmarks
[i
]);
1234 v_scrollbar_
->SetTickMarks(
1235 scaled_tickmarks
.empty() ? NULL
: &scaled_tickmarks
[0], tickmarks
.size());
1238 void Instance::NotifyNumberOfFindResultsChanged(int total
, bool final_result
) {
1239 NumberOfFindResultsChanged(total
, final_result
);
1242 void Instance::NotifySelectedFindResultChanged(int current_find_index
) {
1243 SelectedFindResultChanged(current_find_index
);
1246 void Instance::OnEvent(uint32 control_id
, uint32 event_id
, void* data
) {
1247 if (event_id
== Button::EVENT_ID_BUTTON_CLICKED
||
1248 event_id
== Button::EVENT_ID_BUTTON_STATE_CHANGED
) {
1249 switch (control_id
) {
1250 case kFitToPageButtonId
:
1251 UserMetricsRecordAction("PDF.FitToPageButton");
1252 SetZoom(ZOOM_FIT_TO_PAGE
, 0);
1255 case kFitToWidthButtonId
:
1256 UserMetricsRecordAction("PDF.FitToWidthButton");
1257 SetZoom(ZOOM_FIT_TO_WIDTH
, 0);
1260 case kZoomOutButtonId
:
1261 case kZoomInButtonId
:
1262 UserMetricsRecordAction(control_id
== kZoomOutButtonId
?
1263 "PDF.ZoomOutButton" : "PDF.ZoomInButton");
1264 SetZoom(ZOOM_SCALE
, CalculateZoom(control_id
));
1268 UserMetricsRecordAction("PDF.SaveButton");
1271 case kPrintButtonId
:
1272 UserMetricsRecordAction("PDF.PrintButton");
1277 if (control_id
== kThumbnailsId
&&
1278 event_id
== ThumbnailControl::EVENT_ID_THUMBNAIL_SELECTED
) {
1279 int page
= *static_cast<int*>(data
);
1280 pp::Rect
page_rc(engine_
->GetPageRect(page
));
1281 ScrollToY(static_cast<int>(page_rc
.y() * zoom_
* device_scale_
));
1285 void Instance::Invalidate(uint32 control_id
, const pp::Rect
& rc
) {
1286 paint_manager_
.InvalidateRect(rc
);
1289 uint32
Instance::ScheduleTimer(uint32 control_id
, uint32 timeout_ms
) {
1290 current_timer_id_
++;
1291 pp::CompletionCallback callback
=
1292 timer_factory_
.NewCallback(&Instance::OnControlTimerFired
,
1295 pp::Module::Get()->core()->CallOnMainThread(timeout_ms
, callback
);
1296 return current_timer_id_
;
1299 void Instance::SetEventCapture(uint32 control_id
, bool set_capture
) {
1300 // TODO(gene): set event capture here.
1303 void Instance::SetCursor(uint32 control_id
, PP_CursorType_Dev cursor_type
) {
1304 UpdateCursor(cursor_type
);
1307 pp::Instance
* Instance::GetInstance() {
1311 void Instance::GetDocumentPassword(
1312 pp::CompletionCallbackWithOutput
<pp::Var
> callback
) {
1313 std::string
message(GetLocalizedString(PP_RESOURCESTRING_PDFGETPASSWORD
));
1314 pp::Var result
= pp::PDF::ModalPromptForPassword(this, message
);
1315 *callback
.output() = result
.pp_var();
1316 callback
.Run(PP_OK
);
1319 void Instance::Alert(const std::string
& message
) {
1320 GetWindowObject().Call("alert", message
);
1323 bool Instance::Confirm(const std::string
& message
) {
1324 pp::Var result
= GetWindowObject().Call("confirm", message
);
1325 return result
.is_bool() ? result
.AsBool() : false;
1328 std::string
Instance::Prompt(const std::string
& question
,
1329 const std::string
& default_answer
) {
1330 pp::Var result
= GetWindowObject().Call("prompt", question
, default_answer
);
1331 return result
.is_string() ? result
.AsString() : std::string();
1334 std::string
Instance::GetURL() {
1338 void Instance::Email(const std::string
& to
,
1339 const std::string
& cc
,
1340 const std::string
& bcc
,
1341 const std::string
& subject
,
1342 const std::string
& body
) {
1343 std::string javascript
=
1344 "var href = 'mailto:" + net::EscapeUrlEncodedData(to
, false) +
1345 "?cc=" + net::EscapeUrlEncodedData(cc
, false) +
1346 "&bcc=" + net::EscapeUrlEncodedData(bcc
, false) +
1347 "&subject=" + net::EscapeUrlEncodedData(subject
, false) +
1348 "&body=" + net::EscapeUrlEncodedData(body
, false) +
1349 "';var temp = window.open(href, '_blank', " +
1350 "'width=1,height=1');if(temp) temp.close();";
1351 ExecuteScript(javascript
);
1354 void Instance::Print() {
1355 if (!printing_enabled_
||
1356 (!engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
) &&
1357 !engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY
))) {
1361 pp::CompletionCallback callback
=
1362 print_callback_factory_
.NewCallback(&Instance::OnPrint
);
1363 pp::Module::Get()->core()->CallOnMainThread(0, callback
);
1366 void Instance::OnPrint(int32_t) {
1367 pp::PDF::Print(this);
1370 void Instance::SaveAs() {
1371 pp::PDF::SaveAs(this);
1374 void Instance::SubmitForm(const std::string
& url
,
1377 pp::URLRequestInfo
request(this);
1378 request
.SetURL(url
);
1379 request
.SetMethod("POST");
1380 request
.AppendDataToBody(reinterpret_cast<const char*>(data
), length
);
1382 pp::CompletionCallback callback
=
1383 form_factory_
.NewCallback(&Instance::FormDidOpen
);
1384 form_loader_
= CreateURLLoaderInternal();
1385 int rv
= form_loader_
.Open(request
, callback
);
1386 if (rv
!= PP_OK_COMPLETIONPENDING
)
1390 void Instance::FormDidOpen(int32_t result
) {
1391 // TODO: inform the user of success/failure.
1392 if (result
!= PP_OK
) {
1397 std::string
Instance::ShowFileSelectionDialog() {
1398 // Seems like very low priority to implement, since the pdf has no way to get
1399 // the file data anyways. Javascript doesn't let you do this synchronously.
1401 return std::string();
1404 pp::URLLoader
Instance::CreateURLLoader() {
1406 if (!did_call_start_loading_
) {
1407 did_call_start_loading_
= true;
1408 pp::PDF::DidStartLoading(this);
1411 // Disable save and print until the document is fully loaded, since they
1412 // would generate an incomplete document. Need to do this each time we
1413 // call DidStartLoading since that resets the content restrictions.
1414 pp::PDF::SetContentRestriction(this, CONTENT_RESTRICTION_SAVE
|
1415 CONTENT_RESTRICTION_PRINT
);
1418 return CreateURLLoaderInternal();
1421 void Instance::ScheduleCallback(int id
, int delay_in_ms
) {
1422 pp::CompletionCallback callback
=
1423 timer_factory_
.NewCallback(&Instance::OnClientTimerFired
);
1424 pp::Module::Get()->core()->CallOnMainThread(delay_in_ms
, callback
, id
);
1427 void Instance::SearchString(const base::char16
* string
,
1428 const base::char16
* term
,
1429 bool case_sensitive
,
1430 std::vector
<SearchStringResult
>* results
) {
1431 if (!pp::PDF::IsAvailable()) {
1436 PP_PrivateFindResult
* pp_results
;
1438 pp::PDF::SearchString(
1440 reinterpret_cast<const unsigned short*>(string
),
1441 reinterpret_cast<const unsigned short*>(term
),
1446 results
->resize(count
);
1447 for (int i
= 0; i
< count
; ++i
) {
1448 (*results
)[i
].start_index
= pp_results
[i
].start_index
;
1449 (*results
)[i
].length
= pp_results
[i
].length
;
1452 pp::Memory_Dev memory
;
1453 memory
.MemFree(pp_results
);
1456 void Instance::DocumentPaintOccurred() {
1457 if (painted_first_page_
)
1460 painted_first_page_
= true;
1461 UpdateToolbarPosition(false);
1462 toolbar_
->Splash(kToolbarSplashTimeoutMs
);
1464 if (engine_
->GetNumberOfPages() > 1)
1465 show_page_indicator_
= true;
1467 show_page_indicator_
= false;
1469 if (v_scrollbar_
.get() && show_page_indicator_
) {
1470 page_indicator_
.set_current_page(GetPageNumberToDisplay());
1471 page_indicator_
.Splash(kToolbarSplashTimeoutMs
,
1472 kPageIndicatorInitialFadeTimeoutMs
);
1476 void Instance::DocumentLoadComplete(int page_count
) {
1477 // Clear focus state for OSK.
1478 FormTextFieldFocusChange(false);
1480 // Update progress control.
1481 if (progress_bar_
.visible())
1482 progress_bar_
.Fade(false, kProgressFadeTimeoutMs
);
1484 DCHECK(document_load_state_
== LOAD_STATE_LOADING
);
1485 document_load_state_
= LOAD_STATE_COMPLETE
;
1486 UserMetricsRecordAction("PDF.LoadSuccess");
1487 if (on_load_callback_
.is_string())
1488 ExecuteScript(on_load_callback_
);
1489 // Note: If we are in print preview mode on_load_callback_ might call
1490 // ScrollTo{X|Y}() and we don't want to scroll again and override it.
1491 // #page=N is not supported in Print Preview.
1492 if (!IsPrintPreview()) {
1493 int initial_page
= GetInitialPage(url_
);
1494 if (initial_page
>= 0)
1495 ScrollToPage(initial_page
);
1500 if (!pp::PDF::IsAvailable())
1503 if (did_call_start_loading_
) {
1504 pp::PDF::DidStopLoading(this);
1505 did_call_start_loading_
= false;
1508 int content_restrictions
=
1509 CONTENT_RESTRICTION_CUT
| CONTENT_RESTRICTION_PASTE
;
1510 if (!engine_
->HasPermission(PDFEngine::PERMISSION_COPY
))
1511 content_restrictions
|= CONTENT_RESTRICTION_COPY
;
1513 if (!engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
) &&
1514 !engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY
)) {
1515 printing_enabled_
= false;
1516 if (current_tb_info_
== kPDFToolbarButtons
) {
1517 // Remove Print button.
1518 CreateToolbar(kPDFNoPrintToolbarButtons
,
1519 arraysize(kPDFNoPrintToolbarButtons
));
1520 UpdateToolbarPosition(false);
1521 Invalidate(pp::Rect(plugin_size_
));
1525 pp::PDF::SetContentRestriction(this, content_restrictions
);
1527 pp::PDF::HistogramPDFPageCount(this, page_count
);
1530 void Instance::RotateClockwise() {
1531 engine_
->RotateClockwise();
1534 void Instance::RotateCounterclockwise() {
1535 engine_
->RotateCounterclockwise();
1538 void Instance::PreviewDocumentLoadComplete() {
1539 if (preview_document_load_state_
!= LOAD_STATE_LOADING
||
1540 preview_pages_info_
.empty()) {
1544 preview_document_load_state_
= LOAD_STATE_COMPLETE
;
1546 int dest_page_index
= preview_pages_info_
.front().second
;
1547 int src_page_index
=
1548 ExtractPrintPreviewPageIndex(preview_pages_info_
.front().first
);
1549 if (src_page_index
> 0 && dest_page_index
> -1 && preview_engine_
.get())
1550 engine_
->AppendPage(preview_engine_
.get(), dest_page_index
);
1552 preview_pages_info_
.pop();
1553 // |print_preview_page_count_| is not updated yet. Do not load any
1554 // other preview pages till we get this information.
1555 if (print_preview_page_count_
== 0)
1558 if (preview_pages_info_
.size())
1559 LoadAvailablePreviewPage();
1562 void Instance::DocumentLoadFailed() {
1563 DCHECK(document_load_state_
== LOAD_STATE_LOADING
);
1564 UserMetricsRecordAction("PDF.LoadFailure");
1566 // Hide progress control.
1567 progress_bar_
.Fade(false, kProgressFadeTimeoutMs
);
1569 if (did_call_start_loading_
) {
1570 pp::PDF::DidStopLoading(this);
1571 did_call_start_loading_
= false;
1574 document_load_state_
= LOAD_STATE_FAILED
;
1575 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
1578 void Instance::PreviewDocumentLoadFailed() {
1579 UserMetricsRecordAction("PDF.PreviewDocumentLoadFailure");
1580 if (preview_document_load_state_
!= LOAD_STATE_LOADING
||
1581 preview_pages_info_
.empty()) {
1585 preview_document_load_state_
= LOAD_STATE_FAILED
;
1586 preview_pages_info_
.pop();
1588 if (preview_pages_info_
.size())
1589 LoadAvailablePreviewPage();
1592 pp::Instance
* Instance::GetPluginInstance() {
1593 return GetInstance();
1596 void Instance::DocumentHasUnsupportedFeature(const std::string
& feature
) {
1597 std::string
metric("PDF_Unsupported_");
1599 if (!unsupported_features_reported_
.count(metric
)) {
1600 unsupported_features_reported_
.insert(metric
);
1601 UserMetricsRecordAction(metric
);
1604 // Since we use an info bar, only do this for full frame plugins..
1608 if (told_browser_about_unsupported_feature_
)
1610 told_browser_about_unsupported_feature_
= true;
1612 pp::PDF::HasUnsupportedFeature(this);
1615 void Instance::DocumentLoadProgress(uint32 available
, uint32 doc_size
) {
1616 double progress
= 0.0;
1617 if (doc_size
== 0) {
1618 // Document size is unknown. Use heuristics.
1619 // We'll make progress logarithmic from 0 to 100M.
1620 static const double kFactor
= log(100000000.0) / 100.0;
1621 if (available
> 0) {
1622 progress
= log(static_cast<double>(available
)) / kFactor
;
1623 if (progress
> 100.0)
1627 progress
= 100.0 * static_cast<double>(available
) / doc_size
;
1629 progress_bar_
.SetProgress(progress
);
1632 void Instance::FormTextFieldFocusChange(bool in_focus
) {
1633 if (!text_input_
.get())
1636 text_input_
->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_TEXT
);
1638 text_input_
->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_NONE
);
1641 // Called by PDFScriptableObject.
1642 bool Instance::HasScriptableMethod(const pp::Var
& method
, pp::Var
* exception
) {
1643 std::string method_str
= method
.AsString();
1644 return (method_str
== kJSAccessibility
||
1645 method_str
== kJSDocumentLoadComplete
||
1646 method_str
== kJSGetHeight
||
1647 method_str
== kJSGetHorizontalScrollbarThickness
||
1648 method_str
== kJSGetPageLocationNormalized
||
1649 method_str
== kJSGetVerticalScrollbarThickness
||
1650 method_str
== kJSGetWidth
||
1651 method_str
== kJSGetZoomLevel
||
1652 method_str
== kJSGoToPage
||
1653 method_str
== kJSGrayscale
||
1654 method_str
== kJSLoadPreviewPage
||
1655 method_str
== kJSOnLoad
||
1656 method_str
== kJSOnPluginSizeChanged
||
1657 method_str
== kJSOnScroll
||
1658 method_str
== kJSPageXOffset
||
1659 method_str
== kJSPageYOffset
||
1660 method_str
== kJSPrintPreviewPageCount
||
1661 method_str
== kJSReload
||
1662 method_str
== kJSRemovePrintButton
||
1663 method_str
== kJSResetPrintPreviewUrl
||
1664 method_str
== kJSSendKeyEvent
||
1665 method_str
== kJSSetPageNumbers
||
1666 method_str
== kJSSetPageXOffset
||
1667 method_str
== kJSSetPageYOffset
||
1668 method_str
== kJSSetZoomLevel
||
1669 method_str
== kJSZoomFitToHeight
||
1670 method_str
== kJSZoomFitToWidth
||
1671 method_str
== kJSZoomIn
||
1672 method_str
== kJSZoomOut
);
1675 pp::Var
Instance::CallScriptableMethod(const pp::Var
& method
,
1676 const std::vector
<pp::Var
>& args
,
1677 pp::Var
* exception
) {
1678 std::string method_str
= method
.AsString();
1679 if (method_str
== kJSGrayscale
) {
1680 if (args
.size() == 1 && args
[0].is_bool()) {
1681 engine_
->SetGrayscale(args
[0].AsBool());
1683 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
1684 #ifdef ENABLE_THUMBNAILS
1685 if (thumbnails_
.visible())
1686 thumbnails_
.Show(true, true);
1688 return pp::Var(true);
1690 return pp::Var(false);
1692 if (method_str
== kJSOnLoad
) {
1693 if (args
.size() == 1 && args
[0].is_string()) {
1694 on_load_callback_
= args
[0];
1695 return pp::Var(true);
1697 return pp::Var(false);
1699 if (method_str
== kJSOnScroll
) {
1700 if (args
.size() == 1 && args
[0].is_string()) {
1701 on_scroll_callback_
= args
[0];
1702 return pp::Var(true);
1704 return pp::Var(false);
1706 if (method_str
== kJSOnPluginSizeChanged
) {
1707 if (args
.size() == 1 && args
[0].is_string()) {
1708 on_plugin_size_changed_callback_
= args
[0];
1709 return pp::Var(true);
1711 return pp::Var(false);
1713 if (method_str
== kJSReload
) {
1714 document_load_state_
= LOAD_STATE_LOADING
;
1717 preview_engine_
.reset();
1718 print_preview_page_count_
= 0;
1719 engine_
.reset(PDFEngine::Create(this));
1720 engine_
->New(url_
.c_str());
1721 #ifdef ENABLE_THUMBNAILS
1722 thumbnails_
.ResetEngine(engine_
.get());
1726 if (method_str
== kJSResetPrintPreviewUrl
) {
1727 if (args
.size() == 1 && args
[0].is_string()) {
1728 url_
= args
[0].AsString();
1729 preview_pages_info_
= std::queue
<PreviewPageInfo
>();
1730 preview_document_load_state_
= LOAD_STATE_COMPLETE
;
1734 if (method_str
== kJSZoomFitToHeight
) {
1735 SetZoom(ZOOM_FIT_TO_PAGE
, 0);
1738 if (method_str
== kJSZoomFitToWidth
) {
1739 SetZoom(ZOOM_FIT_TO_WIDTH
, 0);
1742 if (method_str
== kJSZoomIn
) {
1743 SetZoom(ZOOM_SCALE
, CalculateZoom(kZoomInButtonId
));
1746 if (method_str
== kJSZoomOut
) {
1747 SetZoom(ZOOM_SCALE
, CalculateZoom(kZoomOutButtonId
));
1750 if (method_str
== kJSSetZoomLevel
) {
1751 if (args
.size() == 1 && args
[0].is_double())
1752 SetZoom(ZOOM_SCALE
, args
[0].AsDouble());
1755 if (method_str
== kJSGetZoomLevel
) {
1756 return pp::Var(zoom_
);
1758 if (method_str
== kJSGetHeight
) {
1759 return pp::Var(plugin_size_
.height());
1761 if (method_str
== kJSGetWidth
) {
1762 return pp::Var(plugin_size_
.width());
1764 if (method_str
== kJSGetHorizontalScrollbarThickness
) {
1766 h_scrollbar_
.get() ? GetScrollbarReservedThickness() : 0);
1768 if (method_str
== kJSGetVerticalScrollbarThickness
) {
1770 v_scrollbar_
.get() ? GetScrollbarReservedThickness() : 0);
1772 if (method_str
== kJSDocumentLoadComplete
) {
1773 return pp::Var((document_load_state_
!= LOAD_STATE_LOADING
));
1775 if (method_str
== kJSPageYOffset
) {
1776 return pp::Var(static_cast<int32_t>(
1777 v_scrollbar_
.get() ? v_scrollbar_
->GetValue() : 0));
1779 if (method_str
== kJSSetPageYOffset
) {
1780 if (args
.size() == 1 && args
[0].is_number() && v_scrollbar_
.get())
1781 ScrollToY(GetScaled(args
[0].AsInt()));
1784 if (method_str
== kJSPageXOffset
) {
1785 return pp::Var(static_cast<int32_t>(
1786 h_scrollbar_
.get() ? h_scrollbar_
->GetValue() : 0));
1788 if (method_str
== kJSSetPageXOffset
) {
1789 if (args
.size() == 1 && args
[0].is_number() && h_scrollbar_
.get())
1790 ScrollToX(GetScaled(args
[0].AsInt()));
1793 if (method_str
== kJSRemovePrintButton
) {
1794 CreateToolbar(kPrintPreviewToolbarButtons
,
1795 arraysize(kPrintPreviewToolbarButtons
));
1796 UpdateToolbarPosition(false);
1797 Invalidate(pp::Rect(plugin_size_
));
1800 if (method_str
== kJSGoToPage
) {
1801 if (args
.size() == 1 && args
[0].is_string()) {
1802 ScrollToPage(atoi(args
[0].AsString().c_str()));
1806 if (method_str
== kJSAccessibility
) {
1807 if (args
.size() == 0) {
1808 base::DictionaryValue node
;
1809 node
.SetInteger(kAccessibleNumberOfPages
, engine_
->GetNumberOfPages());
1810 node
.SetBoolean(kAccessibleLoaded
,
1811 document_load_state_
!= LOAD_STATE_LOADING
);
1812 bool has_permissions
=
1813 engine_
->HasPermission(PDFEngine::PERMISSION_COPY
) ||
1814 engine_
->HasPermission(PDFEngine::PERMISSION_COPY_ACCESSIBLE
);
1815 node
.SetBoolean(kAccessibleCopyable
, has_permissions
);
1817 base::JSONWriter::Write(&node
, &json
);
1818 return pp::Var(json
);
1819 } else if (args
[0].is_number()) {
1820 return pp::Var(engine_
->GetPageAsJSON(args
[0].AsInt()));
1823 if (method_str
== kJSPrintPreviewPageCount
) {
1824 if (args
.size() == 1 && args
[0].is_number())
1825 SetPrintPreviewMode(args
[0].AsInt());
1828 if (method_str
== kJSLoadPreviewPage
) {
1829 if (args
.size() == 2 && args
[0].is_string() && args
[1].is_number())
1830 ProcessPreviewPageInfo(args
[0].AsString(), args
[1].AsInt());
1833 if (method_str
== kJSGetPageLocationNormalized
) {
1834 const size_t kMaxLength
= 30;
1835 char location_info
[kMaxLength
];
1836 int page_idx
= engine_
->GetMostVisiblePage();
1838 return pp::Var(std::string());
1839 pp::Rect rect
= engine_
->GetPageContentsRect(page_idx
);
1840 int v_scrollbar_reserved_thickness
=
1841 v_scrollbar_
.get() ? GetScaled(GetScrollbarReservedThickness()) : 0;
1843 rect
.set_x(rect
.x() + ((plugin_size_
.width() -
1844 v_scrollbar_reserved_thickness
- available_area_
.width()) / 2));
1845 base::snprintf(location_info
,
1847 "%0.4f;%0.4f;%0.4f;%0.4f;",
1848 rect
.x() / static_cast<float>(plugin_size_
.width()),
1849 rect
.y() / static_cast<float>(plugin_size_
.height()),
1850 rect
.width() / static_cast<float>(plugin_size_
.width()),
1851 rect
.height()/ static_cast<float>(plugin_size_
.height()));
1852 return pp::Var(std::string(location_info
));
1854 if (method_str
== kJSSetPageNumbers
) {
1855 if (args
.size() != 1 || !args
[0].is_string())
1857 const int num_pages_signed
= engine_
->GetNumberOfPages();
1858 if (num_pages_signed
<= 0)
1860 scoped_ptr
<base::ListValue
> page_ranges(static_cast<base::ListValue
*>(
1861 base::JSONReader::Read(args
[0].AsString(), false)));
1862 const size_t num_pages
= static_cast<size_t>(num_pages_signed
);
1863 if (!page_ranges
.get() || page_ranges
->GetSize() != num_pages
)
1866 std::vector
<int> print_preview_page_numbers
;
1867 for (size_t index
= 0; index
< num_pages
; ++index
) {
1868 int page_number
= 0; // |page_number| is 1-based.
1869 if (!page_ranges
->GetInteger(index
, &page_number
) || page_number
< 1)
1871 print_preview_page_numbers
.push_back(page_number
);
1873 print_preview_page_numbers_
= print_preview_page_numbers
;
1874 page_indicator_
.set_current_page(GetPageNumberToDisplay());
1877 // This is here to work around https://bugs.webkit.org/show_bug.cgi?id=16735.
1878 // In JS, creating a synthetic keyboard event and dispatching it always
1879 // result in a keycode of 0.
1880 if (method_str
== kJSSendKeyEvent
) {
1881 if (args
.size() == 1 && args
[0].is_number()) {
1882 pp::KeyboardInputEvent
event(
1884 PP_INPUTEVENT_TYPE_KEYDOWN
, // HandleInputEvent only care about this.
1885 0, // timestamp, not used for kbd events.
1887 args
[0].AsInt(), // keycode.
1888 pp::Var()); // no char text needed.
1889 HandleInputEvent(event
);
1895 void Instance::OnGeometryChanged(double old_zoom
, float old_device_scale
) {
1896 bool force_no_horizontal_scrollbar
= false;
1897 int scrollbar_thickness
= GetScrollbarThickness();
1899 if (old_device_scale
!= device_scale_
) {
1900 // Change in device scale forces us to recreate resources
1901 ConfigureNumberImageGenerator();
1903 CreateToolbar(current_tb_info_
, current_tb_info_size_
);
1904 // Load autoscroll anchor image.
1905 autoscroll_anchor_
=
1906 CreateResourceImage(PP_RESOURCEIMAGE_PDF_PAN_SCROLL_ICON
);
1908 ConfigurePageIndicator();
1909 ConfigureProgressBar();
1911 pp::Point scroll_position
= engine_
->GetScrollPosition();
1912 ScalePoint(device_scale_
/ old_device_scale
, &scroll_position
);
1913 engine_
->SetScrollPosition(scroll_position
);
1917 if (zoom_
!= old_zoom
|| device_scale_
!= old_device_scale
)
1918 engine_
->ZoomUpdated(zoom_
* device_scale_
);
1919 if (zoom_
!= old_zoom
)
1922 available_area_
= pp::Rect(plugin_size_
);
1923 if (GetDocumentPixelHeight() > plugin_size_
.height()) {
1924 CreateVerticalScrollbar();
1926 DestroyVerticalScrollbar();
1929 int v_scrollbar_reserved_thickness
=
1930 v_scrollbar_
.get() ? GetScaled(GetScrollbarReservedThickness()) : 0;
1932 if (!force_no_horizontal_scrollbar
&&
1933 GetDocumentPixelWidth() >
1934 (plugin_size_
.width() - v_scrollbar_reserved_thickness
)) {
1935 CreateHorizontalScrollbar();
1937 // Adding the horizontal scrollbar now might cause us to need vertical
1939 if (GetDocumentPixelHeight() >
1940 plugin_size_
.height() - GetScaled(GetScrollbarReservedThickness())) {
1941 CreateVerticalScrollbar();
1945 DestroyHorizontalScrollbar();
1948 #ifdef ENABLE_THUMBNAILS
1949 int thumbnails_pos
= 0, thumbnails_total
= 0;
1951 if (v_scrollbar_
.get()) {
1952 v_scrollbar_
->SetScale(device_scale_
);
1953 available_area_
.set_width(
1954 std::max(0, plugin_size_
.width() - v_scrollbar_reserved_thickness
));
1956 #ifdef ENABLE_THUMBNAILS
1957 int height
= plugin_size_
.height();
1959 int height_dip
= plugin_dip_size_
.height();
1961 #if defined(OS_MACOSX)
1962 // Before Lion, Mac always had the resize at the bottom. After that, it
1964 if ((base::mac::IsOSSnowLeopard() && full_
) ||
1965 (base::mac::IsOSLionOrLater() && h_scrollbar_
.get())) {
1967 if (h_scrollbar_
.get()) {
1968 #endif // defined(OS_MACOSX)
1969 #ifdef ENABLE_THUMBNAILS
1970 height
-= GetScaled(GetScrollbarThickness());
1972 height_dip
-= GetScrollbarThickness();
1974 #ifdef ENABLE_THUMBNAILS
1975 int32 doc_height
= GetDocumentPixelHeight();
1977 int32 doc_height_dip
=
1978 static_cast<int32
>(GetDocumentPixelHeight() / device_scale_
);
1979 #if defined(OS_MACOSX)
1980 // On the Mac we always allow room for the resize button (whose width is
1981 // the same as that of the scrollbar) in full mode. However, if there is no
1982 // no horizontal scrollbar, the end of the scrollbar will scroll past the
1983 // end of the document. This is because the scrollbar assumes that its own
1984 // height (in the case of a vscroll bar) is the same as the height of the
1985 // viewport. Since the viewport is actually larger, we compensate by
1986 // adjusting the document height. Similar logic applies below for the
1987 // horizontal scrollbar.
1988 // For example, if the document size is 1000, and the viewport size is 200,
1989 // then the scrollbar position at the end will be 800. In this case the
1990 // viewport is actally 215 (assuming 15 as the scrollbar width) but the
1991 // scrollbar thinks it is 200. We want the scrollbar position at the end to
1992 // be 785. Making the document size 985 achieves this.
1993 if (full_
&& !h_scrollbar_
.get()) {
1994 #ifdef ENABLE_THUMBNAILS
1995 doc_height
-= GetScaled(GetScrollbarThickness());
1997 doc_height_dip
-= GetScrollbarThickness();
1999 #endif // defined(OS_MACOSX)
2002 position
= v_scrollbar_
->GetValue();
2003 position
= static_cast<int>(position
* zoom_
/ old_zoom
);
2004 valid_v_range_
= doc_height_dip
- height_dip
;
2005 if (position
> valid_v_range_
)
2006 position
= valid_v_range_
;
2008 v_scrollbar_
->SetValue(position
);
2011 loc
.point
.x
= static_cast<int>(available_area_
.right() / device_scale_
);
2012 if (IsOverlayScrollbar())
2013 loc
.point
.x
-= scrollbar_thickness
;
2015 loc
.size
.width
= scrollbar_thickness
;
2016 loc
.size
.height
= height_dip
;
2017 v_scrollbar_
->SetLocation(loc
);
2018 v_scrollbar_
->SetDocumentSize(doc_height_dip
);
2020 #ifdef ENABLE_THUMBNAILS
2021 thumbnails_pos
= position
;
2022 thumbnails_total
= doc_height
- height
;
2026 if (h_scrollbar_
.get()) {
2027 h_scrollbar_
->SetScale(device_scale_
);
2028 available_area_
.set_height(
2029 std::max(0, plugin_size_
.height() -
2030 GetScaled(GetScrollbarReservedThickness())));
2032 int width_dip
= plugin_dip_size_
.width();
2035 #if defined(OS_MACOSX)
2036 if ((base::mac::IsOSSnowLeopard() && full_
) ||
2037 (base::mac::IsOSLionOrLater() && v_scrollbar_
.get())) {
2039 if (v_scrollbar_
.get()) {
2041 width_dip
-= GetScrollbarThickness();
2043 int32 doc_width_dip
=
2044 static_cast<int32
>(GetDocumentPixelWidth() / device_scale_
);
2045 #if defined(OS_MACOSX)
2046 // See comment in the above if (v_scrollbar_.get()) block.
2047 if (full_
&& !v_scrollbar_
.get())
2048 doc_width_dip
-= GetScrollbarThickness();
2049 #endif // defined(OS_MACOSX)
2052 position
= h_scrollbar_
->GetValue();
2053 position
= static_cast<int>(position
* zoom_
/ old_zoom
);
2054 position
= std::min(position
, doc_width_dip
- width_dip
);
2056 h_scrollbar_
->SetValue(position
);
2060 loc
.point
.y
= static_cast<int>(available_area_
.bottom() / device_scale_
);
2061 if (IsOverlayScrollbar())
2062 loc
.point
.y
-= scrollbar_thickness
;
2063 loc
.size
.width
= width_dip
;
2064 loc
.size
.height
= scrollbar_thickness
;
2065 h_scrollbar_
->SetLocation(loc
);
2066 h_scrollbar_
->SetDocumentSize(doc_width_dip
);
2069 int doc_width
= GetDocumentPixelWidth();
2070 if (doc_width
< available_area_
.width()) {
2071 available_area_
.Offset((available_area_
.width() - doc_width
) / 2, 0);
2072 available_area_
.set_width(doc_width
);
2074 int doc_height
= GetDocumentPixelHeight();
2075 if (doc_height
< available_area_
.height()) {
2076 available_area_
.set_height(doc_height
);
2079 // We'll invalidate the entire plugin anyways.
2080 UpdateToolbarPosition(false);
2081 UpdateProgressBarPosition(false);
2082 UpdatePageIndicatorPosition(false);
2084 #ifdef ENABLE_THUMBNAILS
2085 // Update thumbnail control position.
2086 thumbnails_
.SetPosition(thumbnails_pos
, thumbnails_total
, false);
2087 pp::Rect
thumbnails_rc(plugin_size_
.width() - GetScaled(kThumbnailsWidth
), 0,
2088 GetScaled(kThumbnailsWidth
), plugin_size_
.height());
2089 if (v_scrollbar_
.get())
2090 thumbnails_rc
.Offset(-v_scrollbar_reserved_thickness
, 0);
2091 if (h_scrollbar_
.get())
2092 thumbnails_rc
.Inset(0, 0, 0, v_scrollbar_reserved_thickness
);
2093 thumbnails_
.SetRect(thumbnails_rc
, false);
2096 CalculateBackgroundParts();
2097 engine_
->PageOffsetUpdated(available_area_
.point());
2098 engine_
->PluginSizeUpdated(available_area_
.size());
2100 if (!document_size_
.GetArea())
2102 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
2104 if (on_plugin_size_changed_callback_
.is_string())
2105 ExecuteScript(on_plugin_size_changed_callback_
);
2108 void Instance::CreateHorizontalScrollbar() {
2109 if (h_scrollbar_
.get())
2112 h_scrollbar_
.reset(new pp::Scrollbar_Dev(this, false));
2115 void Instance::CreateVerticalScrollbar() {
2116 if (v_scrollbar_
.get())
2119 v_scrollbar_
.reset(new pp::Scrollbar_Dev(this, true));
2122 void Instance::DestroyHorizontalScrollbar() {
2123 if (!h_scrollbar_
.get())
2125 if (h_scrollbar_
->GetValue())
2126 engine_
->ScrolledToXPosition(0);
2127 h_scrollbar_
.reset();
2130 void Instance::DestroyVerticalScrollbar() {
2131 if (!v_scrollbar_
.get())
2133 if (v_scrollbar_
->GetValue())
2134 engine_
->ScrolledToYPosition(0);
2135 v_scrollbar_
.reset();
2136 page_indicator_
.Show(false, true);
2139 int Instance::GetScrollbarThickness() {
2140 if (scrollbar_thickness_
== -1) {
2141 pp::Scrollbar_Dev
temp_scrollbar(this, false);
2142 scrollbar_thickness_
= temp_scrollbar
.GetThickness();
2143 scrollbar_reserved_thickness_
=
2144 temp_scrollbar
.IsOverlay() ? 0 : scrollbar_thickness_
;
2147 return scrollbar_thickness_
;
2150 int Instance::GetScrollbarReservedThickness() {
2151 GetScrollbarThickness();
2152 return scrollbar_reserved_thickness_
;
2155 bool Instance::IsOverlayScrollbar() {
2156 return GetScrollbarReservedThickness() == 0;
2159 void Instance::CreateToolbar(const ToolbarButtonInfo
* tb_info
, size_t size
) {
2160 toolbar_
.reset(new FadingControls());
2165 // Remember the current toolbar information in case we need to recreate the
2167 current_tb_info_
= tb_info
;
2168 current_tb_info_size_
= size
;
2171 pp::Point
origin(kToolbarFadingOffsetLeft
, kToolbarFadingOffsetTop
);
2172 ScalePoint(device_scale_
, &origin
);
2174 std::list
<Button
*> buttons
;
2175 for (size_t i
= 0; i
< size
; i
++) {
2176 Button
* btn
= new Button
;
2177 pp::ImageData normal_face
=
2178 CreateResourceImage(tb_info
[i
].normal
);
2179 btn
->CreateButton(tb_info
[i
].id
,
2185 CreateResourceImage(tb_info
[i
].highlighted
),
2186 CreateResourceImage(tb_info
[i
].pressed
));
2187 buttons
.push_back(btn
);
2189 origin
+= pp::Point(normal_face
.size().width(), 0);
2190 max_height
= std::max(max_height
, normal_face
.size().height());
2193 pp::Rect
rc_toolbar(0, 0,
2194 origin
.x() + GetToolbarRightOffset(),
2195 origin
.y() + max_height
+ GetToolbarBottomOffset());
2196 toolbar_
->CreateFadingControls(
2197 kToolbarId
, rc_toolbar
, false, this, kTransparentAlpha
);
2199 std::list
<Button
*>::iterator iter
;
2200 for (iter
= buttons
.begin(); iter
!= buttons
.end(); ++iter
) {
2201 toolbar_
->AddControl(*iter
);
2205 int Instance::GetToolbarRightOffset() {
2206 int scrollbar_thickness
= GetScrollbarThickness();
2207 return GetScaled(kToolbarFadingOffsetRight
) + 2 * scrollbar_thickness
;
2210 int Instance::GetToolbarBottomOffset() {
2211 int scrollbar_thickness
= GetScrollbarThickness();
2212 return GetScaled(kToolbarFadingOffsetBottom
) + scrollbar_thickness
;
2215 std::vector
<pp::ImageData
> Instance::GetThumbnailResources() {
2216 std::vector
<pp::ImageData
> num_images(10);
2217 num_images
[0] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_0
);
2218 num_images
[1] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_1
);
2219 num_images
[2] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_2
);
2220 num_images
[3] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_3
);
2221 num_images
[4] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_4
);
2222 num_images
[5] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_5
);
2223 num_images
[6] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_6
);
2224 num_images
[7] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_7
);
2225 num_images
[8] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_8
);
2226 num_images
[9] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_9
);
2230 std::vector
<pp::ImageData
> Instance::GetProgressBarResources(
2231 pp::ImageData
* background
) {
2232 std::vector
<pp::ImageData
> result(9);
2233 result
[0] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_0
);
2234 result
[1] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_1
);
2235 result
[2] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_2
);
2236 result
[3] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_3
);
2237 result
[4] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_4
);
2238 result
[5] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_5
);
2239 result
[6] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_6
);
2240 result
[7] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_7
);
2241 result
[8] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_8
);
2242 *background
= CreateResourceImage(
2243 PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_BACKGROUND
);
2247 void Instance::CreatePageIndicator(bool always_visible
) {
2248 page_indicator_
.CreatePageIndicator(kPageIndicatorId
, false, this,
2249 number_image_generator(), always_visible
);
2250 ConfigurePageIndicator();
2253 void Instance::ConfigurePageIndicator() {
2254 pp::ImageData background
=
2255 CreateResourceImage(PP_RESOURCEIMAGE_PDF_PAGE_INDICATOR_BACKGROUND
);
2256 page_indicator_
.Configure(pp::Point(), background
);
2259 void Instance::CreateProgressBar() {
2260 pp::ImageData background
;
2261 std::vector
<pp::ImageData
> images
= GetProgressBarResources(&background
);
2262 std::string text
= GetLocalizedString(PP_RESOURCESTRING_PDFPROGRESSLOADING
);
2263 progress_bar_
.CreateProgressControl(kProgressBarId
, false, this, 0.0,
2264 device_scale_
, images
, background
, text
);
2267 void Instance::ConfigureProgressBar() {
2268 pp::ImageData background
;
2269 std::vector
<pp::ImageData
> images
= GetProgressBarResources(&background
);
2270 progress_bar_
.Reconfigure(background
, images
, device_scale_
);
2273 void Instance::CreateThumbnails() {
2274 thumbnails_
.CreateThumbnailControl(
2275 kThumbnailsId
, pp::Rect(), false, this, engine_
.get(),
2276 number_image_generator());
2279 void Instance::LoadUrl(const std::string
& url
) {
2280 LoadUrlInternal(url
, &embed_loader_
, &Instance::DidOpen
);
2283 void Instance::LoadPreviewUrl(const std::string
& url
) {
2284 LoadUrlInternal(url
, &embed_preview_loader_
, &Instance::DidOpenPreview
);
2287 void Instance::LoadUrlInternal(const std::string
& url
, pp::URLLoader
* loader
,
2288 void (Instance::* method
)(int32_t)) {
2289 pp::URLRequestInfo
request(this);
2290 request
.SetURL(url
);
2291 request
.SetMethod("GET");
2293 *loader
= CreateURLLoaderInternal();
2294 pp::CompletionCallback callback
= loader_factory_
.NewCallback(method
);
2295 int rv
= loader
->Open(request
, callback
);
2296 if (rv
!= PP_OK_COMPLETIONPENDING
)
2300 pp::URLLoader
Instance::CreateURLLoaderInternal() {
2301 pp::URLLoader
loader(this);
2303 const PPB_URLLoaderTrusted
* trusted_interface
=
2304 reinterpret_cast<const PPB_URLLoaderTrusted
*>(
2305 pp::Module::Get()->GetBrowserInterface(
2306 PPB_URLLOADERTRUSTED_INTERFACE
));
2307 if (trusted_interface
)
2308 trusted_interface
->GrantUniversalAccess(loader
.pp_resource());
2312 int Instance::GetInitialPage(const std::string
& url
) {
2313 #if defined(OS_NACL)
2316 size_t found_idx
= url
.find('#');
2317 if (found_idx
== std::string::npos
)
2320 const std::string
& ref
= url
.substr(found_idx
+ 1);
2321 std::vector
<std::string
> fragments
;
2322 Tokenize(ref
, kDelimiters
, &fragments
);
2324 // Page number to return, zero-based.
2327 // Handle the case of http://foo.com/bar#NAMEDDEST. This is not explicitly
2328 // mentioned except by example in the Adobe "PDF Open Parameters" document.
2329 if ((fragments
.size() == 1) && (fragments
[0].find('=') == std::string::npos
))
2330 return engine_
->GetNamedDestinationPage(fragments
[0]);
2332 for (size_t i
= 0; i
< fragments
.size(); ++i
) {
2333 std::vector
<std::string
> key_value
;
2334 base::SplitString(fragments
[i
], '=', &key_value
);
2335 if (key_value
.size() != 2)
2337 const std::string
& key
= key_value
[0];
2338 const std::string
& value
= key_value
[1];
2340 if (base::strcasecmp(kPage
, key
.c_str()) == 0) {
2341 // |page_value| is 1-based.
2342 int page_value
= -1;
2343 if (base::StringToInt(value
, &page_value
) && page_value
> 0)
2344 page
= page_value
- 1;
2347 if (base::strcasecmp(kNamedDest
, key
.c_str()) == 0) {
2348 // |page_value| is 0-based.
2349 int page_value
= engine_
->GetNamedDestinationPage(value
);
2350 if (page_value
>= 0)
2359 void Instance::UpdateToolbarPosition(bool invalidate
) {
2360 pp::Rect ctrl_rc
= toolbar_
->GetControlsRect();
2361 int min_toolbar_width
= ctrl_rc
.width() + GetToolbarRightOffset() +
2362 GetScaled(kToolbarFadingOffsetLeft
);
2363 int min_toolbar_height
= ctrl_rc
.width() + GetToolbarBottomOffset() +
2364 GetScaled(kToolbarFadingOffsetBottom
);
2366 // Update toolbar position
2367 if (plugin_size_
.width() < min_toolbar_width
||
2368 plugin_size_
.height() < min_toolbar_height
) {
2369 // Disable toolbar if it does not fit on the screen.
2370 toolbar_
->Show(false, invalidate
);
2373 plugin_size_
.width() - GetToolbarRightOffset() - ctrl_rc
.right(),
2374 plugin_size_
.height() - GetToolbarBottomOffset() - ctrl_rc
.bottom());
2375 toolbar_
->MoveBy(offset
, invalidate
);
2377 int toolbar_width
= std::max(plugin_size_
.width() / 2, min_toolbar_width
);
2378 toolbar_
->ExpandLeft(toolbar_width
- toolbar_
->rect().width());
2379 toolbar_
->Show(painted_first_page_
, invalidate
);
2383 void Instance::UpdateProgressBarPosition(bool invalidate
) {
2384 // TODO(gene): verify we don't overlap with toolbar.
2385 int scrollbar_thickness
= GetScrollbarThickness();
2386 pp::Point
progress_origin(
2387 scrollbar_thickness
+ GetScaled(kProgressOffsetLeft
),
2388 plugin_size_
.height() - progress_bar_
.rect().height() -
2389 scrollbar_thickness
- GetScaled(kProgressOffsetBottom
));
2390 progress_bar_
.MoveTo(progress_origin
, invalidate
);
2393 void Instance::UpdatePageIndicatorPosition(bool invalidate
) {
2394 int32 doc_height
= static_cast<int>(document_size_
.height() * zoom_
);
2396 plugin_size_
.width() - page_indicator_
.rect().width() -
2397 GetScaled(GetScrollbarReservedThickness()),
2398 page_indicator_
.GetYPosition(engine_
->GetVerticalScrollbarYPosition(),
2399 doc_height
, plugin_size_
.height()));
2400 page_indicator_
.MoveTo(origin
, invalidate
);
2403 void Instance::SetZoom(ZoomMode zoom_mode
, double scale
) {
2404 double old_zoom
= zoom_
;
2406 zoom_mode_
= zoom_mode
;
2407 if (zoom_mode_
== ZOOM_SCALE
)
2411 engine_
->ZoomUpdated(zoom_
* device_scale_
);
2412 OnGeometryChanged(old_zoom
, device_scale_
);
2414 // If fit-to-height, snap to the beginning of the most visible page.
2415 if (zoom_mode_
== ZOOM_FIT_TO_PAGE
) {
2416 ScrollToPage(engine_
->GetMostVisiblePage());
2419 // Update sticky buttons to the current zoom style.
2420 Button
* ftp_btn
= static_cast<Button
*>(
2421 toolbar_
->GetControl(kFitToPageButtonId
));
2422 Button
* ftw_btn
= static_cast<Button
*>(
2423 toolbar_
->GetControl(kFitToWidthButtonId
));
2424 switch (zoom_mode_
) {
2425 case ZOOM_FIT_TO_PAGE
:
2426 ftp_btn
->SetPressedState(true);
2427 ftw_btn
->SetPressedState(false);
2429 case ZOOM_FIT_TO_WIDTH
:
2430 ftw_btn
->SetPressedState(true);
2431 ftp_btn
->SetPressedState(false);
2434 ftw_btn
->SetPressedState(false);
2435 ftp_btn
->SetPressedState(false);
2439 void Instance::UpdateZoomScale() {
2440 switch (zoom_mode_
) {
2442 break; // Keep current scale.
2443 case ZOOM_FIT_TO_PAGE
: {
2444 int page_num
= engine_
->GetFirstVisiblePage();
2447 pp::Rect rc
= engine_
->GetPageRect(page_num
);
2450 // Calculate fit to width zoom level.
2451 double ftw_zoom
= static_cast<double>(plugin_dip_size_
.width() -
2452 GetScrollbarReservedThickness()) / document_size_
.width();
2453 // Calculate fit to height zoom level. If document will not fit
2454 // horizontally, adjust zoom level to allow space for horizontal
2457 static_cast<double>(plugin_dip_size_
.height()) / rc
.height();
2458 if (fth_zoom
* document_size_
.width() >
2459 plugin_dip_size_
.width() - GetScrollbarReservedThickness())
2460 fth_zoom
= static_cast<double>(plugin_dip_size_
.height()
2461 - GetScrollbarReservedThickness()) / rc
.height();
2462 zoom_
= std::min(ftw_zoom
, fth_zoom
);
2464 case ZOOM_FIT_TO_WIDTH
:
2466 if (!document_size_
.width())
2468 zoom_
= static_cast<double>(plugin_dip_size_
.width() -
2469 GetScrollbarReservedThickness()) / document_size_
.width();
2470 if (zoom_mode_
== ZOOM_AUTO
&& zoom_
> 1.0)
2474 zoom_
= ClipToRange(zoom_
, kMinZoom
, kMaxZoom
);
2477 double Instance::CalculateZoom(uint32 control_id
) const {
2478 if (control_id
== kZoomInButtonId
) {
2479 for (size_t i
= 0; i
< chrome_page_zoom::kPresetZoomFactorsSize
; ++i
) {
2480 double current_zoom
= chrome_page_zoom::kPresetZoomFactors
[i
];
2481 if (current_zoom
- content::kEpsilon
> zoom_
)
2482 return current_zoom
;
2485 for (size_t i
= chrome_page_zoom::kPresetZoomFactorsSize
; i
> 0; --i
) {
2486 double current_zoom
= chrome_page_zoom::kPresetZoomFactors
[i
- 1];
2487 if (current_zoom
+ content::kEpsilon
< zoom_
)
2488 return current_zoom
;
2494 pp::ImageData
Instance::CreateResourceImage(PP_ResourceImage image_id
) {
2496 return pp::PDF::GetResourceImageForScale(this, image_id
, device_scale_
);
2498 return pp::PDF::GetResourceImage(this, image_id
);
2501 std::string
Instance::GetLocalizedString(PP_ResourceString id
) {
2502 pp::Var
rv(pp::PDF::GetLocalizedString(this, id
));
2503 if (!rv
.is_string())
2504 return std::string();
2506 return rv
.AsString();
2509 void Instance::DrawText(const pp::Point
& top_center
, PP_ResourceString id
) {
2510 std::string
str(GetLocalizedString(id
));
2512 pp::FontDescription_Dev description
;
2513 description
.set_family(PP_FONTFAMILY_SANSSERIF
);
2514 description
.set_size(kMessageTextSize
* device_scale_
);
2515 pp::Font_Dev
font(this, description
);
2516 int length
= font
.MeasureSimpleText(str
);
2517 pp::Point
point(top_center
);
2518 point
.set_x(point
.x() - length
/ 2);
2519 DCHECK(!image_data_
.is_null());
2520 font
.DrawSimpleText(&image_data_
, str
, point
, kMessageTextColor
);
2523 void Instance::SetPrintPreviewMode(int page_count
) {
2524 if (!IsPrintPreview() || page_count
<= 0) {
2525 print_preview_page_count_
= 0;
2529 print_preview_page_count_
= page_count
;
2531 engine_
->AppendBlankPages(print_preview_page_count_
);
2532 if (preview_pages_info_
.size() > 0)
2533 LoadAvailablePreviewPage();
2536 bool Instance::IsPrintPreview() {
2537 return IsPrintPreviewUrl(url_
);
2540 int Instance::GetPageNumberToDisplay() {
2541 int page
= engine_
->GetMostVisiblePage();
2542 if (IsPrintPreview() && !print_preview_page_numbers_
.empty()) {
2543 page
= ClipToRange
<int>(page
, 0, print_preview_page_numbers_
.size() - 1);
2544 return print_preview_page_numbers_
[page
];
2549 void Instance::ProcessPreviewPageInfo(const std::string
& url
,
2550 int dst_page_index
) {
2551 if (!IsPrintPreview() || print_preview_page_count_
< 0)
2554 int src_page_index
= ExtractPrintPreviewPageIndex(url
);
2555 if (src_page_index
< 1)
2558 preview_pages_info_
.push(std::make_pair(url
, dst_page_index
));
2559 LoadAvailablePreviewPage();
2562 void Instance::LoadAvailablePreviewPage() {
2563 if (preview_pages_info_
.size() <= 0)
2566 std::string url
= preview_pages_info_
.front().first
;
2567 int dst_page_index
= preview_pages_info_
.front().second
;
2568 int src_page_index
= ExtractPrintPreviewPageIndex(url
);
2569 if (src_page_index
< 1 ||
2570 dst_page_index
>= print_preview_page_count_
||
2571 preview_document_load_state_
== LOAD_STATE_LOADING
) {
2575 preview_document_load_state_
= LOAD_STATE_LOADING
;
2576 LoadPreviewUrl(url
);
2579 void Instance::EnableAutoscroll(const pp::Point
& origin
) {
2583 pp::Size client_size
= plugin_size_
;
2584 if (v_scrollbar_
.get())
2585 client_size
.Enlarge(-GetScrollbarThickness(), 0);
2586 if (h_scrollbar_
.get())
2587 client_size
.Enlarge(0, -GetScrollbarThickness());
2589 // Do not allow autoscroll if client area is too small.
2590 if (autoscroll_anchor_
.size().width() > client_size
.width() ||
2591 autoscroll_anchor_
.size().height() > client_size
.height())
2594 autoscroll_rect_
= pp::Rect(
2595 pp::Point(origin
.x() - autoscroll_anchor_
.size().width() / 2,
2596 origin
.y() - autoscroll_anchor_
.size().height() / 2),
2597 autoscroll_anchor_
.size());
2599 // Make sure autoscroll anchor is in the client area.
2600 if (autoscroll_rect_
.right() > client_size
.width()) {
2601 autoscroll_rect_
.set_x(
2602 client_size
.width() - autoscroll_anchor_
.size().width());
2604 if (autoscroll_rect_
.bottom() > client_size
.height()) {
2605 autoscroll_rect_
.set_y(
2606 client_size
.height() - autoscroll_anchor_
.size().height());
2609 if (autoscroll_rect_
.x() < 0)
2610 autoscroll_rect_
.set_x(0);
2611 if (autoscroll_rect_
.y() < 0)
2612 autoscroll_rect_
.set_y(0);
2614 is_autoscroll_
= true;
2615 Invalidate(kAutoScrollId
, autoscroll_rect_
);
2617 ScheduleTimer(kAutoScrollId
, kAutoScrollTimeoutMs
);
2620 void Instance::DisableAutoscroll() {
2621 if (is_autoscroll_
) {
2622 is_autoscroll_
= false;
2623 Invalidate(kAutoScrollId
, autoscroll_rect_
);
2627 PP_CursorType_Dev
Instance::CalculateAutoscroll(const pp::Point
& mouse_pos
) {
2628 // Scroll only if mouse pointer is outside of the anchor area.
2629 if (autoscroll_rect_
.Contains(mouse_pos
)) {
2632 return PP_CURSORTYPE_MIDDLEPANNING
;
2635 // Relative position to the center of anchor area.
2636 pp::Point rel_pos
= mouse_pos
- autoscroll_rect_
.CenterPoint();
2638 // Calculate angle from the X axis. Angle is in range from -pi to pi.
2639 double angle
= atan2(static_cast<double>(rel_pos
.y()),
2640 static_cast<double>(rel_pos
.x()));
2642 autoscroll_x_
= rel_pos
.x() * kAutoScrollFactor
;
2643 autoscroll_y_
= rel_pos
.y() * kAutoScrollFactor
;
2645 // Angle is from -pi to pi. Screen Y is increasing toward bottom,
2646 // so negative angle represent north direction.
2647 if (angle
< - (M_PI
* 7.0 / 8.0)) {
2649 return PP_CURSORTYPE_WESTPANNING
;
2650 } else if (angle
< - (M_PI
* 5.0 / 8.0)) {
2652 return PP_CURSORTYPE_NORTHWESTPANNING
;
2653 } else if (angle
< - (M_PI
* 3.0 / 8.0)) {
2655 return PP_CURSORTYPE_NORTHPANNING
;
2656 } else if (angle
< - (M_PI
* 1.0 / 8.0)) {
2658 return PP_CURSORTYPE_NORTHEASTPANNING
;
2659 } else if (angle
< M_PI
* 1.0 / 8.0) {
2661 return PP_CURSORTYPE_EASTPANNING
;
2662 } else if (angle
< M_PI
* 3.0 / 8.0) {
2664 return PP_CURSORTYPE_SOUTHEASTPANNING
;
2665 } else if (angle
< M_PI
* 5.0 / 8.0) {
2667 return PP_CURSORTYPE_SOUTHPANNING
;
2668 } else if (angle
< M_PI
* 7.0 / 8.0) {
2670 return PP_CURSORTYPE_SOUTHWESTPANNING
;
2673 // went around the circle, going west again
2674 return PP_CURSORTYPE_WESTPANNING
;
2677 void Instance::ConfigureNumberImageGenerator() {
2678 std::vector
<pp::ImageData
> num_images
= GetThumbnailResources();
2679 pp::ImageData number_background
= CreateResourceImage(
2680 PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_NUM_BACKGROUND
);
2681 number_image_generator_
->Configure(number_background
,
2686 NumberImageGenerator
* Instance::number_image_generator() {
2687 if (!number_image_generator_
.get()) {
2688 number_image_generator_
.reset(new NumberImageGenerator(this));
2689 ConfigureNumberImageGenerator();
2691 return number_image_generator_
.get();
2694 int Instance::GetScaled(int x
) const {
2695 return static_cast<int>(x
* device_scale_
);
2698 void Instance::UserMetricsRecordAction(const std::string
& action
) {
2699 pp::PDF::UserMetricsRecordAction(this, pp::Var(action
));
2702 PDFScriptableObject::PDFScriptableObject(Instance
* instance
)
2703 : instance_(instance
) {
2706 PDFScriptableObject::~PDFScriptableObject() {
2709 bool PDFScriptableObject::HasMethod(const pp::Var
& name
, pp::Var
* exception
) {
2710 return instance_
->HasScriptableMethod(name
, exception
);
2713 pp::Var
PDFScriptableObject::Call(const pp::Var
& method
,
2714 const std::vector
<pp::Var
>& args
,
2715 pp::Var
* exception
) {
2716 return instance_
->CallScriptableMethod(method
, args
, exception
);
2719 } // namespace chrome_pdf