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"
44 #include "v8/include/v8.h"
46 #if defined(OS_MACOSX)
47 #include "base/mac/mac_util.h"
50 namespace chrome_pdf
{
52 struct ToolbarButtonInfo
{
54 Button::ButtonStyle style
;
55 PP_ResourceImage normal
;
56 PP_ResourceImage highlighted
;
57 PP_ResourceImage pressed
;
62 // Uncomment following #define to enable thumbnails.
63 // #define ENABLE_THUMBNAILS
65 const uint32 kToolbarSplashTimeoutMs
= 6000;
66 const uint32 kMessageTextColor
= 0xFF575757;
67 const uint32 kMessageTextSize
= 22;
68 const uint32 kProgressFadeTimeoutMs
= 250;
69 const uint32 kProgressDelayTimeoutMs
= 1000;
70 const uint32 kAutoScrollTimeoutMs
= 50;
71 const double kAutoScrollFactor
= 0.2;
73 // Javascript methods.
74 const char kJSAccessibility
[] = "accessibility";
75 const char kJSDocumentLoadComplete
[] = "documentLoadComplete";
76 const char kJSGetHeight
[] = "getHeight";
77 const char kJSGetHorizontalScrollbarThickness
[] =
78 "getHorizontalScrollbarThickness";
79 const char kJSGetPageLocationNormalized
[] = "getPageLocationNormalized";
80 const char kJSGetSelectedText
[] = "getSelectedText";
81 const char kJSGetVerticalScrollbarThickness
[] = "getVerticalScrollbarThickness";
82 const char kJSGetWidth
[] = "getWidth";
83 const char kJSGetZoomLevel
[] = "getZoomLevel";
84 const char kJSGoToPage
[] = "goToPage";
85 const char kJSGrayscale
[] = "grayscale";
86 const char kJSLoadPreviewPage
[] = "loadPreviewPage";
87 const char kJSOnLoad
[] = "onload";
88 const char kJSOnPluginSizeChanged
[] = "onPluginSizeChanged";
89 const char kJSOnScroll
[] = "onScroll";
90 const char kJSPageXOffset
[] = "pageXOffset";
91 const char kJSPageYOffset
[] = "pageYOffset";
92 const char kJSPrintPreviewPageCount
[] = "printPreviewPageCount";
93 const char kJSReload
[] = "reload";
94 const char kJSRemovePrintButton
[] = "removePrintButton";
95 const char kJSResetPrintPreviewUrl
[] = "resetPrintPreviewUrl";
96 const char kJSSendKeyEvent
[] = "sendKeyEvent";
97 const char kJSSetPageNumbers
[] = "setPageNumbers";
98 const char kJSSetPageXOffset
[] = "setPageXOffset";
99 const char kJSSetPageYOffset
[] = "setPageYOffset";
100 const char kJSSetZoomLevel
[] = "setZoomLevel";
101 const char kJSZoomFitToHeight
[] = "fitToHeight";
102 const char kJSZoomFitToWidth
[] = "fitToWidth";
103 const char kJSZoomIn
[] = "zoomIn";
104 const char kJSZoomOut
[] = "zoomOut";
106 // URL reference parameters.
107 // For more possible parameters, see RFC 3778 and the "PDF Open Parameters"
108 // document from Adobe.
109 const char kDelimiters
[] = "#&";
110 const char kNamedDest
[] = "nameddest";
111 const char kPage
[] = "page";
113 const char kChromePrint
[] = "chrome://print/";
115 // Dictionary Value key names for the document accessibility info
116 const char kAccessibleNumberOfPages
[] = "numberOfPages";
117 const char kAccessibleLoaded
[] = "loaded";
118 const char kAccessibleCopyable
[] = "copyable";
120 const ToolbarButtonInfo kPDFToolbarButtons
[] = {
121 { kFitToPageButtonId
, Button::BUTTON_STATE
,
122 PP_RESOURCEIMAGE_PDF_BUTTON_FTP
,
123 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_HOVER
,
124 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_PRESSED
},
125 { kFitToWidthButtonId
, Button::BUTTON_STATE
,
126 PP_RESOURCEIMAGE_PDF_BUTTON_FTW
,
127 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_HOVER
,
128 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_PRESSED
},
129 { kZoomOutButtonId
, Button::BUTTON_CLICKABLE
,
130 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT
,
131 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_HOVER
,
132 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_PRESSED
},
133 { kZoomInButtonId
, Button::BUTTON_CLICKABLE
,
134 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN
,
135 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_HOVER
,
136 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_PRESSED
},
137 { kSaveButtonId
, Button::BUTTON_CLICKABLE
,
138 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE
,
139 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE_HOVER
,
140 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE_PRESSED
},
141 { kPrintButtonId
, Button::BUTTON_CLICKABLE
,
142 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT
,
143 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_HOVER
,
144 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_PRESSED
},
147 const ToolbarButtonInfo kPDFNoPrintToolbarButtons
[] = {
148 { kFitToPageButtonId
, Button::BUTTON_STATE
,
149 PP_RESOURCEIMAGE_PDF_BUTTON_FTP
,
150 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_HOVER
,
151 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_PRESSED
},
152 { kFitToWidthButtonId
, Button::BUTTON_STATE
,
153 PP_RESOURCEIMAGE_PDF_BUTTON_FTW
,
154 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_HOVER
,
155 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_PRESSED
},
156 { kZoomOutButtonId
, Button::BUTTON_CLICKABLE
,
157 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT
,
158 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_HOVER
,
159 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_PRESSED
},
160 { kZoomInButtonId
, Button::BUTTON_CLICKABLE
,
161 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN
,
162 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_HOVER
,
163 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_PRESSED
},
164 { kSaveButtonId
, Button::BUTTON_CLICKABLE
,
165 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE
,
166 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE_HOVER
,
167 PP_RESOURCEIMAGE_PDF_BUTTON_SAVE_PRESSED
},
168 { kPrintButtonId
, Button::BUTTON_CLICKABLE
,
169 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_DISABLED
,
170 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_DISABLED
,
171 PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_DISABLED
}
174 const ToolbarButtonInfo kPrintPreviewToolbarButtons
[] = {
175 { kFitToPageButtonId
, Button::BUTTON_STATE
,
176 PP_RESOURCEIMAGE_PDF_BUTTON_FTP
,
177 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_HOVER
,
178 PP_RESOURCEIMAGE_PDF_BUTTON_FTP_PRESSED
},
179 { kFitToWidthButtonId
, Button::BUTTON_STATE
,
180 PP_RESOURCEIMAGE_PDF_BUTTON_FTW
,
181 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_HOVER
,
182 PP_RESOURCEIMAGE_PDF_BUTTON_FTW_PRESSED
},
183 { kZoomOutButtonId
, Button::BUTTON_CLICKABLE
,
184 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT
,
185 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_HOVER
,
186 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_PRESSED
},
187 { kZoomInButtonId
, Button::BUTTON_CLICKABLE
,
188 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_END
,
189 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_END_HOVER
,
190 PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_END_PRESSED
},
193 static const char kPPPPdfInterface
[] = PPP_PDF_INTERFACE_1
;
195 PP_Var
GetLinkAtPosition(PP_Instance instance
, PP_Point point
) {
198 pp::Instance::GetPerInstanceObject(instance
, kPPPPdfInterface
);
200 var
= static_cast<Instance
*>(object
)->GetLinkAtPosition(pp::Point(point
));
204 void Transform(PP_Instance instance
, PP_PrivatePageTransformType type
) {
206 pp::Instance::GetPerInstanceObject(instance
, kPPPPdfInterface
);
208 Instance
* obj_instance
= static_cast<Instance
*>(object
);
210 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CW
:
211 obj_instance
->RotateClockwise();
213 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CCW
:
214 obj_instance
->RotateCounterclockwise();
220 PP_Bool
GetPrintPresetOptionsFromDocument(
221 PP_Instance instance
,
222 PP_PdfPrintPresetOptions_Dev
* options
) {
223 void* object
= pp::Instance::GetPerInstanceObject(instance
, kPPPPdfInterface
);
225 Instance
* obj_instance
= static_cast<Instance
*>(object
);
226 obj_instance
->GetPrintPresetOptionsFromDocument(options
);
231 const PPP_Pdf ppp_private
= {
234 &GetPrintPresetOptionsFromDocument
237 int ExtractPrintPreviewPageIndex(const std::string
& src_url
) {
238 // Sample |src_url| format: chrome://print/id/page_index/print.pdf
239 std::vector
<std::string
> url_substr
;
240 base::SplitString(src_url
.substr(strlen(kChromePrint
)), '/', &url_substr
);
241 if (url_substr
.size() != 3)
244 if (url_substr
[2] != "print.pdf")
248 if (!base::StringToInt(url_substr
[1], &page_index
))
253 bool IsPrintPreviewUrl(const std::string
& url
) {
254 return url
.substr(0, strlen(kChromePrint
)) == kChromePrint
;
257 void ScalePoint(float scale
, pp::Point
* point
) {
258 point
->set_x(static_cast<int>(point
->x() * scale
));
259 point
->set_y(static_cast<int>(point
->y() * scale
));
262 void ScaleRect(float scale
, pp::Rect
* rect
) {
263 int left
= static_cast<int>(floorf(rect
->x() * scale
));
264 int top
= static_cast<int>(floorf(rect
->y() * scale
));
265 int right
= static_cast<int>(ceilf((rect
->x() + rect
->width()) * scale
));
266 int bottom
= static_cast<int>(ceilf((rect
->y() + rect
->height()) * scale
));
267 rect
->SetRect(left
, top
, right
- left
, bottom
- top
);
271 T
ClipToRange(T value
, T lower_boundary
, T upper_boundary
) {
272 DCHECK(lower_boundary
<= upper_boundary
);
273 return std::max
<T
>(lower_boundary
, std::min
<T
>(value
, upper_boundary
));
278 Instance::Instance(PP_Instance instance
)
279 : pp::InstancePrivate(instance
),
280 pp::Find_Private(this),
281 pp::Printing_Dev(this),
282 pp::Selection_Dev(this),
283 pp::WidgetClient_Dev(this),
285 cursor_(PP_CURSORTYPE_POINTER
),
286 timer_pending_(false),
287 current_timer_id_(0),
290 printing_enabled_(true),
291 hidpi_enabled_(false),
292 full_(IsFullFrame()),
293 zoom_mode_(full_
? ZOOM_AUTO
: ZOOM_SCALE
),
294 did_call_start_loading_(false),
295 is_autoscroll_(false),
296 scrollbar_thickness_(-1),
297 scrollbar_reserved_thickness_(-1),
298 current_tb_info_(NULL
),
299 current_tb_info_size_(0),
300 paint_manager_(this, this, true),
301 delayed_progress_timer_id_(0),
303 painted_first_page_(false),
304 show_page_indicator_(false),
305 document_load_state_(LOAD_STATE_LOADING
),
306 preview_document_load_state_(LOAD_STATE_COMPLETE
),
307 told_browser_about_unsupported_feature_(false),
308 print_preview_page_count_(0) {
309 loader_factory_
.Initialize(this);
310 timer_factory_
.Initialize(this);
311 form_factory_
.Initialize(this);
312 callback_factory_
.Initialize(this);
313 engine_
.reset(PDFEngine::Create(this));
314 pp::Module::Get()->AddPluginInterface(kPPPPdfInterface
, &ppp_private
);
315 AddPerInstanceObject(kPPPPdfInterface
, this);
317 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_MOUSE
);
318 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_WHEEL
);
319 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_KEYBOARD
);
320 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_TOUCH
);
323 Instance::~Instance() {
324 if (timer_pending_
) {
325 timer_factory_
.CancelAll();
326 timer_pending_
= false;
328 // The engine may try to access this instance during its destruction.
329 // Make sure this happens early while the instance is still intact.
331 RemovePerInstanceObject(kPPPPdfInterface
, this);
334 bool Instance::Init(uint32_t argc
, const char* argn
[], const char* argv
[]) {
335 v8::StartupData natives
;
336 v8::StartupData snapshot
;
337 pp::PDF::GetV8ExternalSnapshotData(this, &natives
.data
, &natives
.raw_size
,
338 &snapshot
.data
, &snapshot
.raw_size
);
340 natives
.compressed_size
= natives
.raw_size
;
341 snapshot
.compressed_size
= snapshot
.raw_size
;
342 v8::V8::SetNativesDataBlob(&natives
);
343 v8::V8::SetSnapshotDataBlob(&snapshot
);
346 // For now, we hide HiDPI support behind a flag.
347 if (pp::PDF::IsFeatureEnabled(this, PP_PDFFEATURE_HIDPI
))
348 hidpi_enabled_
= true;
350 printing_enabled_
= pp::PDF::IsFeatureEnabled(this, PP_PDFFEATURE_PRINTING
);
351 if (printing_enabled_
) {
352 CreateToolbar(kPDFToolbarButtons
, arraysize(kPDFToolbarButtons
));
354 CreateToolbar(kPDFNoPrintToolbarButtons
,
355 arraysize(kPDFNoPrintToolbarButtons
));
360 // Load autoscroll anchor image.
362 CreateResourceImage(PP_RESOURCEIMAGE_PDF_PAN_SCROLL_ICON
);
364 #ifdef ENABLE_THUMBNAILS
367 const char* url
= NULL
;
368 for (uint32_t i
= 0; i
< argc
; ++i
) {
369 if (strcmp(argn
[i
], "src") == 0) {
378 CreatePageIndicator(IsPrintPreviewUrl(url
));
381 // For PDFs embedded in a frame, we don't get the data automatically like we
382 // do for full-frame loads. Start loading the data manually.
385 DCHECK(!did_call_start_loading_
);
386 pp::PDF::DidStartLoading(this);
387 did_call_start_loading_
= true;
390 ZoomLimitsChanged(kMinZoom
, kMaxZoom
);
392 text_input_
.reset(new pp::TextInput_Dev(this));
395 return engine_
->New(url
);
398 bool Instance::HandleDocumentLoad(const pp::URLLoader
& loader
) {
399 delayed_progress_timer_id_
= ScheduleTimer(kProgressBarId
,
400 kProgressDelayTimeoutMs
);
401 return engine_
->HandleDocumentLoad(loader
);
404 bool Instance::HandleInputEvent(const pp::InputEvent
& event
) {
405 // To simplify things, convert the event into device coordinates if it is
407 pp::InputEvent
event_device_res(event
);
409 pp::MouseInputEvent
mouse_event(event
);
410 if (!mouse_event
.is_null()) {
411 pp::Point point
= mouse_event
.GetPosition();
412 pp::Point movement
= mouse_event
.GetMovement();
413 ScalePoint(device_scale_
, &point
);
414 ScalePoint(device_scale_
, &movement
);
415 mouse_event
= pp::MouseInputEvent(
418 event
.GetTimeStamp(),
419 event
.GetModifiers(),
420 mouse_event
.GetButton(),
422 mouse_event
.GetClickCount(),
424 event_device_res
= mouse_event
;
428 // Check if we need to go to autoscroll mode.
429 if (event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE
&&
430 (event
.GetModifiers() & PP_INPUTEVENT_MODIFIER_MIDDLEBUTTONDOWN
)) {
431 pp::MouseInputEvent
mouse_event(event_device_res
);
432 pp::Point pos
= mouse_event
.GetPosition();
433 EnableAutoscroll(pos
);
434 UpdateCursor(CalculateAutoscroll(pos
));
437 // Quit autoscrolling on any other event.
441 #ifdef ENABLE_THUMBNAILS
442 if (event
.GetType() == PP_INPUTEVENT_TYPE_MOUSELEAVE
)
443 thumbnails_
.SlideOut();
445 if (thumbnails_
.HandleEvent(event_device_res
))
449 if (toolbar_
->HandleEvent(event_device_res
))
452 #ifdef ENABLE_THUMBNAILS
453 if (v_scrollbar_
.get() && event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE
) {
454 pp::MouseInputEvent
mouse_event(event
);
455 pp::Point pt
= mouse_event
.GetPosition();
456 pp::Rect v_scrollbar_rc
;
457 v_scrollbar_
->GetLocation(&v_scrollbar_rc
);
458 // There is a bug (https://bugs.webkit.org/show_bug.cgi?id=45208)
459 // in the webkit that makes event.u.mouse.button
460 // equal to PP_INPUTEVENT_MOUSEBUTTON_LEFT, even when no button is pressed.
461 // To work around this issue we use modifier for now, and will switch
462 // to button once the bug is fixed and webkit got merged back to our tree.
463 if (v_scrollbar_rc
.Contains(pt
) &&
464 (event
.GetModifiers() & PP_INPUTEVENT_MODIFIER_LEFTBUTTONDOWN
)) {
465 thumbnails_
.SlideIn();
468 // When scrollbar is in the scrolling mode we should display thumbnails
469 // even the mouse is outside the thumbnail and scrollbar areas.
470 // If mouse is outside plugin area, we are still getting mouse move events
471 // while scrolling. See bug description for details:
472 // http://code.google.com/p/chromium/issues/detail?id=56444
473 if (!v_scrollbar_rc
.Contains(pt
) && thumbnails_
.visible() &&
474 !(event
.GetModifiers() & PP_INPUTEVENT_MODIFIER_LEFTBUTTONDOWN
) &&
475 !thumbnails_
.rect().Contains(pt
)) {
476 thumbnails_
.SlideOut();
481 // Need to pass the event to the engine first, since if we're over an edit
482 // control we want it to get keyboard events (like space) instead of the
484 // TODO: will have to offset the mouse coordinates once we support bidi and
485 // there could be scrollbars on the left.
486 pp::InputEvent
offset_event(event_device_res
);
487 bool try_engine_first
= true;
488 switch (offset_event
.GetType()) {
489 case PP_INPUTEVENT_TYPE_MOUSEDOWN
:
490 case PP_INPUTEVENT_TYPE_MOUSEUP
:
491 case PP_INPUTEVENT_TYPE_MOUSEMOVE
:
492 case PP_INPUTEVENT_TYPE_MOUSEENTER
:
493 case PP_INPUTEVENT_TYPE_MOUSELEAVE
: {
494 pp::MouseInputEvent
mouse_event(event_device_res
);
495 pp::MouseInputEvent
mouse_event_dip(event
);
496 pp::Point point
= mouse_event
.GetPosition();
497 point
.set_x(point
.x() - available_area_
.x());
498 offset_event
= pp::MouseInputEvent(
501 event
.GetTimeStamp(),
502 event
.GetModifiers(),
503 mouse_event
.GetButton(),
505 mouse_event
.GetClickCount(),
506 mouse_event
.GetMovement());
507 if (!engine_
->IsSelecting()) {
508 if (!IsOverlayScrollbar() &&
509 !available_area_
.Contains(mouse_event
.GetPosition())) {
510 try_engine_first
= false;
511 } else if (IsOverlayScrollbar()) {
513 if ((v_scrollbar_
.get() && v_scrollbar_
->GetLocation(&temp
) &&
514 temp
.Contains(mouse_event_dip
.GetPosition())) ||
515 (h_scrollbar_
.get() && h_scrollbar_
->GetLocation(&temp
) &&
516 temp
.Contains(mouse_event_dip
.GetPosition()))) {
517 try_engine_first
= false;
526 if (try_engine_first
&& engine_
->HandleEvent(offset_event
))
529 // Left/Right arrows should scroll to the beginning of the Prev/Next page if
530 // there is no horizontal scroll bar.
531 // If fit-to-height, PgDown/PgUp should scroll to the beginning of the
532 // Prev/Next page. Spacebar / shift+spacebar should do the same.
533 if (v_scrollbar_
.get() && event
.GetType() == PP_INPUTEVENT_TYPE_KEYDOWN
) {
534 pp::KeyboardInputEvent
keyboard_event(event
);
535 bool no_h_scrollbar
= !h_scrollbar_
.get();
536 uint32_t key_code
= keyboard_event
.GetKeyCode();
537 bool page_down
= no_h_scrollbar
&& key_code
== ui::VKEY_RIGHT
;
538 bool page_up
= no_h_scrollbar
&& key_code
== ui::VKEY_LEFT
;
539 if (zoom_mode_
== ZOOM_FIT_TO_PAGE
) {
541 keyboard_event
.GetModifiers() & PP_INPUTEVENT_MODIFIER_SHIFTKEY
;
542 bool key_is_space
= key_code
== ui::VKEY_SPACE
;
543 page_down
|= key_is_space
|| key_code
== ui::VKEY_NEXT
;
544 page_up
|= (key_is_space
&& has_shift
) || (key_code
== ui::VKEY_PRIOR
);
547 int page
= engine_
->GetFirstVisiblePage();
550 // Engine calculates visible page including delimiter to the page size.
551 // We need to check here if the page itself is completely out of view and
552 // scroll to the next one in that case.
553 if (engine_
->GetPageRect(page
).bottom() * zoom_
<=
554 v_scrollbar_
->GetValue())
556 ScrollToPage(page
+ 1);
557 UpdateCursor(PP_CURSORTYPE_POINTER
);
559 } else if (page_up
) {
560 int page
= engine_
->GetFirstVisiblePage();
563 if (engine_
->GetPageRect(page
).y() * zoom_
>= v_scrollbar_
->GetValue())
566 UpdateCursor(PP_CURSORTYPE_POINTER
);
571 if (v_scrollbar_
.get() && v_scrollbar_
->HandleEvent(event
)) {
572 UpdateCursor(PP_CURSORTYPE_POINTER
);
576 if (h_scrollbar_
.get() && h_scrollbar_
->HandleEvent(event
)) {
577 UpdateCursor(PP_CURSORTYPE_POINTER
);
581 if (timer_pending_
&&
582 (event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEUP
||
583 event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE
)) {
584 timer_factory_
.CancelAll();
585 timer_pending_
= false;
586 } else if (event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE
&&
587 engine_
->IsSelecting()) {
588 bool set_timer
= false;
589 pp::MouseInputEvent
mouse_event(event
);
590 if (v_scrollbar_
.get() &&
591 (mouse_event
.GetPosition().y() <= 0 ||
592 mouse_event
.GetPosition().y() >= (plugin_dip_size_
.height() - 1))) {
593 v_scrollbar_
->ScrollBy(
594 PP_SCROLLBY_LINE
, mouse_event
.GetPosition().y() >= 0 ? 1: -1);
597 if (h_scrollbar_
.get() &&
598 (mouse_event
.GetPosition().x() <= 0 ||
599 mouse_event
.GetPosition().x() >= (plugin_dip_size_
.width() - 1))) {
600 h_scrollbar_
->ScrollBy(PP_SCROLLBY_LINE
,
601 mouse_event
.GetPosition().x() >= 0 ? 1: -1);
606 last_mouse_event_
= pp::MouseInputEvent(event
);
608 pp::CompletionCallback callback
=
609 timer_factory_
.NewCallback(&Instance::OnTimerFired
);
610 pp::Module::Get()->core()->CallOnMainThread(kDragTimerMs
, callback
);
611 timer_pending_
= true;
615 if (event
.GetType() == PP_INPUTEVENT_TYPE_KEYDOWN
) {
616 pp::KeyboardInputEvent
keyboard_event(event
);
617 const uint32 modifier
= event
.GetModifiers();
618 if (modifier
& kDefaultKeyModifier
) {
619 switch (keyboard_event
.GetKeyCode()) {
621 engine_
->SelectAll();
625 if (modifier
& PP_INPUTEVENT_MODIFIER_CONTROLKEY
) {
626 switch (keyboard_event
.GetKeyCode()) {
629 engine_
->RotateCounterclockwise();
633 engine_
->RotateClockwise();
639 // Return true for unhandled clicks so the plugin takes focus.
640 return (event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN
);
643 void Instance::DidChangeView(const pp::View
& view
) {
644 pp::Rect
view_rect(view
.GetRect());
645 float device_scale
= 1.0f
;
646 float old_device_scale
= device_scale_
;
648 device_scale
= view
.GetDeviceScale();
649 pp::Size
view_device_size(view_rect
.width() * device_scale
,
650 view_rect
.height() * device_scale
);
651 if (view_device_size
== plugin_size_
&& device_scale
== device_scale_
)
652 return; // We don't care about the position, only the size.
654 image_data_
= pp::ImageData();
655 device_scale_
= device_scale
;
656 plugin_dip_size_
= view_rect
.size();
657 plugin_size_
= view_device_size
;
659 paint_manager_
.SetSize(view_device_size
, device_scale_
);
661 image_data_
= pp::ImageData(this,
662 PP_IMAGEDATAFORMAT_BGRA_PREMUL
,
665 if (image_data_
.is_null()) {
666 DCHECK(plugin_size_
.IsEmpty());
670 // View dimensions changed, disable autoscroll (if it was enabled).
673 OnGeometryChanged(zoom_
, old_device_scale
);
676 pp::Var
Instance::GetInstanceObject() {
677 if (instance_object_
.is_undefined()) {
678 PDFScriptableObject
* object
= new PDFScriptableObject(this);
679 // The pp::Var takes ownership of object here.
680 instance_object_
= pp::VarPrivate(this, object
);
683 return instance_object_
;
686 void Instance::GetPrintPresetOptionsFromDocument(
687 PP_PdfPrintPresetOptions_Dev
* options
) {
688 options
->is_scaling_disabled
= PP_FromBool(IsPrintScalingDisabled());
689 options
->copies
= engine_
->GetCopiesToPrint();
692 pp::Var
Instance::GetLinkAtPosition(const pp::Point
& point
) {
693 pp::Point
offset_point(point
);
694 ScalePoint(device_scale_
, &offset_point
);
695 offset_point
.set_x(offset_point
.x() - available_area_
.x());
696 return engine_
->GetLinkAtPosition(offset_point
);
699 pp::Var
Instance::GetSelectedText(bool html
) {
700 if (html
|| !engine_
->HasPermission(PDFEngine::PERMISSION_COPY
))
702 return engine_
->GetSelectedText();
705 void Instance::InvalidateWidget(pp::Widget_Dev widget
,
706 const pp::Rect
& dirty_rect
) {
707 if (v_scrollbar_
.get() && *v_scrollbar_
== widget
) {
708 if (!image_data_
.is_null())
709 v_scrollbar_
->Paint(dirty_rect
.pp_rect(), &image_data_
);
710 } else if (h_scrollbar_
.get() && *h_scrollbar_
== widget
) {
711 if (!image_data_
.is_null())
712 h_scrollbar_
->Paint(dirty_rect
.pp_rect(), &image_data_
);
714 // Possible to hit this condition since sometimes the scrollbar codes posts
715 // a task to do something later, and we could have deleted our reference in
720 pp::Rect dirty_rect_scaled
= dirty_rect
;
721 ScaleRect(device_scale_
, &dirty_rect_scaled
);
722 paint_manager_
.InvalidateRect(dirty_rect_scaled
);
725 void Instance::ScrollbarValueChanged(pp::Scrollbar_Dev scrollbar
,
727 value
= GetScaled(value
);
728 if (v_scrollbar_
.get() && *v_scrollbar_
== scrollbar
) {
729 engine_
->ScrolledToYPosition(value
);
731 v_scrollbar_
->GetLocation(&rc
);
732 int32 doc_height
= GetDocumentPixelHeight();
733 doc_height
-= GetScaled(rc
.height());
734 #ifdef ENABLE_THUMBNAILS
735 if (thumbnails_
.visible()) {
736 thumbnails_
.SetPosition(value
, doc_height
, true);
740 plugin_size_
.width() - page_indicator_
.rect().width() -
741 GetScaled(GetScrollbarReservedThickness()),
742 page_indicator_
.GetYPosition(value
, doc_height
, plugin_size_
.height()));
743 page_indicator_
.MoveTo(origin
, page_indicator_
.visible());
744 } else if (h_scrollbar_
.get() && *h_scrollbar_
== scrollbar
) {
745 engine_
->ScrolledToXPosition(value
);
749 void Instance::ScrollbarOverlayChanged(pp::Scrollbar_Dev scrollbar
,
751 scrollbar_reserved_thickness_
= overlay
? 0 : scrollbar_thickness_
;
752 OnGeometryChanged(zoom_
, device_scale_
);
755 uint32_t Instance::QuerySupportedPrintOutputFormats() {
756 return engine_
->QuerySupportedPrintOutputFormats();
759 int32_t Instance::PrintBegin(const PP_PrintSettings_Dev
& print_settings
) {
760 // For us num_pages is always equal to the number of pages in the PDF
761 // document irrespective of the printable area.
762 int32_t ret
= engine_
->GetNumberOfPages();
766 uint32_t supported_formats
= engine_
->QuerySupportedPrintOutputFormats();
767 if ((print_settings
.format
& supported_formats
) == 0)
770 print_settings_
.is_printing
= true;
771 print_settings_
.pepper_print_settings
= print_settings
;
772 engine_
->PrintBegin();
776 pp::Resource
Instance::PrintPages(
777 const PP_PrintPageNumberRange_Dev
* page_ranges
,
778 uint32_t page_range_count
) {
779 if (!print_settings_
.is_printing
)
780 return pp::Resource();
782 print_settings_
.print_pages_called_
= true;
783 return engine_
->PrintPages(page_ranges
, page_range_count
,
784 print_settings_
.pepper_print_settings
);
787 void Instance::PrintEnd() {
788 if (print_settings_
.print_pages_called_
)
789 UserMetricsRecordAction("PDF.PrintPage");
790 print_settings_
.Clear();
794 bool Instance::IsPrintScalingDisabled() {
795 return !engine_
->GetPrintScaling();
798 bool Instance::StartFind(const std::string
& text
, bool case_sensitive
) {
799 engine_
->StartFind(text
.c_str(), case_sensitive
);
803 void Instance::SelectFindResult(bool forward
) {
804 engine_
->SelectFindResult(forward
);
807 void Instance::StopFind() {
811 void Instance::Zoom(double scale
, bool text_only
) {
812 UserMetricsRecordAction("PDF.ZoomFromBrowser");
814 // If the zoom level doesn't change it means that this zoom change might have
815 // been initiated by the plugin. In that case, we don't want to change the
816 // zoom mode to ZOOM_SCALE as it may have been intentionally set to
817 // ZOOM_FIT_TO_PAGE or some other value when the zoom was last changed.
821 SetZoom(ZOOM_SCALE
, scale
);
824 void Instance::ZoomChanged(double factor
) {
826 Zoom_Dev::ZoomChanged(factor
);
829 void Instance::OnPaint(const std::vector
<pp::Rect
>& paint_rects
,
830 std::vector
<PaintManager::ReadyRect
>* ready
,
831 std::vector
<pp::Rect
>* pending
) {
832 if (image_data_
.is_null()) {
833 DCHECK(plugin_size_
.IsEmpty());
837 first_paint_
= false;
838 pp::Rect rect
= pp::Rect(pp::Point(), plugin_size_
);
839 FillRect(rect
, kBackgroundColor
);
840 ready
->push_back(PaintManager::ReadyRect(rect
, image_data_
, true));
841 *pending
= paint_rects
;
847 for (size_t i
= 0; i
< paint_rects
.size(); i
++) {
848 // Intersect with plugin area since there could be pending invalidates from
849 // when the plugin area was larger.
851 paint_rects
[i
].Intersect(pp::Rect(pp::Point(), plugin_size_
));
855 pp::Rect pdf_rect
= available_area_
.Intersect(rect
);
856 if (!pdf_rect
.IsEmpty()) {
857 pdf_rect
.Offset(available_area_
.x() * -1, 0);
859 std::vector
<pp::Rect
> pdf_ready
;
860 std::vector
<pp::Rect
> pdf_pending
;
861 engine_
->Paint(pdf_rect
, &image_data_
, &pdf_ready
, &pdf_pending
);
862 for (size_t j
= 0; j
< pdf_ready
.size(); ++j
) {
863 pdf_ready
[j
].Offset(available_area_
.point());
865 PaintManager::ReadyRect(pdf_ready
[j
], image_data_
, false));
867 for (size_t j
= 0; j
< pdf_pending
.size(); ++j
) {
868 pdf_pending
[j
].Offset(available_area_
.point());
869 pending
->push_back(pdf_pending
[j
]);
873 for (size_t j
= 0; j
< background_parts_
.size(); ++j
) {
874 pp::Rect intersection
= background_parts_
[j
].location
.Intersect(rect
);
875 if (!intersection
.IsEmpty()) {
876 FillRect(intersection
, background_parts_
[j
].color
);
878 PaintManager::ReadyRect(intersection
, image_data_
, false));
882 if (document_load_state_
== LOAD_STATE_FAILED
) {
883 pp::Point top_center
;
884 top_center
.set_x(plugin_size_
.width() / 2);
885 top_center
.set_y(plugin_size_
.height() / 2);
886 DrawText(top_center
, PP_RESOURCESTRING_PDFLOAD_FAILED
);
889 #ifdef ENABLE_THUMBNAILS
890 thumbnails_
.Paint(&image_data_
, rect
);
894 engine_
->PostPaint();
896 // Must paint scrollbars after the background parts, in case we have an
897 // overlay scrollbar that's over the background. We also do this in a separate
898 // loop because the scrollbar painting logic uses the signal of whether there
899 // are pending paints or not to figure out if it should draw right away or
901 for (size_t i
= 0; i
< paint_rects
.size(); i
++) {
902 PaintIfWidgetIntersects(h_scrollbar_
.get(), paint_rects
[i
], ready
, pending
);
903 PaintIfWidgetIntersects(v_scrollbar_
.get(), paint_rects
[i
], ready
, pending
);
906 if (progress_bar_
.visible())
907 PaintOverlayControl(&progress_bar_
, &image_data_
, ready
);
909 if (page_indicator_
.visible())
910 PaintOverlayControl(&page_indicator_
, &image_data_
, ready
);
912 if (toolbar_
->current_transparency() != kTransparentAlpha
)
913 PaintOverlayControl(toolbar_
.get(), &image_data_
, ready
);
915 // Paint autoscroll anchor if needed.
916 if (is_autoscroll_
) {
917 size_t limit
= ready
->size();
918 for (size_t i
= 0; i
< limit
; i
++) {
919 pp::Rect anchor_rect
= autoscroll_rect_
.Intersect((*ready
)[i
].rect
);
920 if (!anchor_rect
.IsEmpty()) {
921 pp::Rect draw_rc
= pp::Rect(
922 pp::Point(anchor_rect
.x() - autoscroll_rect_
.x(),
923 anchor_rect
.y() - autoscroll_rect_
.y()),
925 // Paint autoscroll anchor.
926 AlphaBlend(autoscroll_anchor_
, draw_rc
,
927 &image_data_
, anchor_rect
.point(), kOpaqueAlpha
);
933 void Instance::PaintOverlayControl(
935 pp::ImageData
* image_data
,
936 std::vector
<PaintManager::ReadyRect
>* ready
) {
937 // Make sure that we only paint overlay controls over an area that's ready,
938 // i.e. not pending. Otherwise we'll mark the control rect as ready and
939 // it'll overwrite the pdf region.
940 std::list
<pp::Rect
> ctrl_rects
;
941 for (size_t i
= 0; i
< ready
->size(); i
++) {
942 pp::Rect rc
= ctrl
->rect().Intersect((*ready
)[i
].rect
);
944 ctrl_rects
.push_back(rc
);
947 if (!ctrl_rects
.empty()) {
948 ctrl
->PaintMultipleRects(image_data
, ctrl_rects
);
950 std::list
<pp::Rect
>::iterator iter
;
951 for (iter
= ctrl_rects
.begin(); iter
!= ctrl_rects
.end(); ++iter
) {
952 ready
->push_back(PaintManager::ReadyRect(*iter
, *image_data
, false));
957 void Instance::DidOpen(int32_t result
) {
958 if (result
== PP_OK
) {
959 engine_
->HandleDocumentLoad(embed_loader_
);
960 } else if (result
!= PP_ERROR_ABORTED
) { // Can happen in tests.
965 void Instance::DidOpenPreview(int32_t result
) {
966 if (result
== PP_OK
) {
967 preview_engine_
.reset(PDFEngine::Create(new PreviewModeClient(this)));
968 preview_engine_
->HandleDocumentLoad(embed_preview_loader_
);
974 void Instance::PaintIfWidgetIntersects(
975 pp::Widget_Dev
* widget
,
976 const pp::Rect
& rect
,
977 std::vector
<PaintManager::ReadyRect
>* ready
,
978 std::vector
<pp::Rect
>* pending
) {
983 if (!widget
->GetLocation(&location
))
986 ScaleRect(device_scale_
, &location
);
987 location
= location
.Intersect(rect
);
988 if (location
.IsEmpty())
991 if (IsOverlayScrollbar()) {
992 // If we're using overlay scrollbars, and there are pending paints under the
993 // scrollbar, don't update the scrollbar instantly. While it would be nice,
994 // we would need to double buffer the plugin area in order to make this
995 // work. This is because we'd need to always have a copy of what the pdf
996 // under the scrollbar looks like, and additionally we couldn't paint the
997 // pdf under the scrollbar if it's ready until we got the preceding flush.
998 // So in practice, it would make painting slower and introduce extra buffer
999 // copies for the general case.
1000 for (size_t i
= 0; i
< pending
->size(); ++i
) {
1001 if ((*pending
)[i
].Intersects(location
))
1005 // Even if none of the pending paints are under the scrollbar, we never want
1006 // to paint it if it's over the pdf if there are other pending paints.
1007 // Otherwise different parts of the pdf plugin would display at different
1009 if (!pending
->empty() && available_area_
.Intersects(rect
)) {
1010 pending
->push_back(location
);
1015 pp::Rect location_dip
= location
;
1016 ScaleRect(1.0f
/ device_scale_
, &location_dip
);
1018 DCHECK(!image_data_
.is_null());
1019 widget
->Paint(location_dip
, &image_data_
);
1021 ready
->push_back(PaintManager::ReadyRect(location
, image_data_
, true));
1024 void Instance::OnTimerFired(int32_t) {
1025 HandleInputEvent(last_mouse_event_
);
1028 void Instance::OnClientTimerFired(int32_t id
) {
1029 engine_
->OnCallback(id
);
1032 void Instance::OnControlTimerFired(int32_t,
1033 const uint32
& control_id
,
1034 const uint32
& timer_id
) {
1035 if (control_id
== toolbar_
->id()) {
1036 toolbar_
->OnTimerFired(timer_id
);
1037 } else if (control_id
== progress_bar_
.id()) {
1038 if (timer_id
== delayed_progress_timer_id_
) {
1039 if (document_load_state_
== LOAD_STATE_LOADING
&&
1040 !progress_bar_
.visible()) {
1041 progress_bar_
.Fade(true, kProgressFadeTimeoutMs
);
1043 delayed_progress_timer_id_
= 0;
1045 progress_bar_
.OnTimerFired(timer_id
);
1047 } else if (control_id
== kAutoScrollId
) {
1048 if (is_autoscroll_
) {
1049 if (autoscroll_x_
!= 0 && h_scrollbar_
.get()) {
1050 h_scrollbar_
->ScrollBy(PP_SCROLLBY_PIXEL
, autoscroll_x_
);
1052 if (autoscroll_y_
!= 0 && v_scrollbar_
.get()) {
1053 v_scrollbar_
->ScrollBy(PP_SCROLLBY_PIXEL
, autoscroll_y_
);
1056 // Reschedule timer.
1057 ScheduleTimer(kAutoScrollId
, kAutoScrollTimeoutMs
);
1059 } else if (control_id
== kPageIndicatorId
) {
1060 page_indicator_
.OnTimerFired(timer_id
);
1062 #ifdef ENABLE_THUMBNAILS
1063 else if (control_id
== thumbnails_
.id()) {
1064 thumbnails_
.OnTimerFired(timer_id
);
1069 void Instance::CalculateBackgroundParts() {
1070 background_parts_
.clear();
1071 int v_scrollbar_thickness
=
1072 GetScaled(v_scrollbar_
.get() ? GetScrollbarReservedThickness() : 0);
1073 int h_scrollbar_thickness
=
1074 GetScaled(h_scrollbar_
.get() ? GetScrollbarReservedThickness() : 0);
1075 int width_without_scrollbar
= std::max(
1076 plugin_size_
.width() - v_scrollbar_thickness
, 0);
1077 int height_without_scrollbar
= std::max(
1078 plugin_size_
.height() - h_scrollbar_thickness
, 0);
1079 int left_width
= available_area_
.x();
1080 int right_start
= available_area_
.right();
1081 int right_width
= abs(width_without_scrollbar
- available_area_
.right());
1082 int bottom
= std::min(available_area_
.bottom(), height_without_scrollbar
);
1084 // Add the left, right, and bottom rectangles. Note: we assume only
1085 // horizontal centering.
1086 BackgroundPart part
= {
1087 pp::Rect(0, 0, left_width
, bottom
),
1090 if (!part
.location
.IsEmpty())
1091 background_parts_
.push_back(part
);
1092 part
.location
= pp::Rect(right_start
, 0, right_width
, bottom
);
1093 if (!part
.location
.IsEmpty())
1094 background_parts_
.push_back(part
);
1095 part
.location
= pp::Rect(
1096 0, bottom
, width_without_scrollbar
, height_without_scrollbar
- bottom
);
1097 if (!part
.location
.IsEmpty())
1098 background_parts_
.push_back(part
);
1100 if (h_scrollbar_thickness
1101 #if defined(OS_MACOSX)
1106 v_scrollbar_thickness
) {
1107 part
.color
= 0xFFFFFFFF;
1108 part
.location
= pp::Rect(plugin_size_
.width() - v_scrollbar_thickness
,
1109 plugin_size_
.height() - h_scrollbar_thickness
,
1110 h_scrollbar_thickness
,
1111 v_scrollbar_thickness
);
1112 background_parts_
.push_back(part
);
1116 int Instance::GetDocumentPixelWidth() const {
1117 return static_cast<int>(ceil(document_size_
.width() * zoom_
* device_scale_
));
1120 int Instance::GetDocumentPixelHeight() const {
1121 return static_cast<int>(ceil(document_size_
.height() *
1126 void Instance::FillRect(const pp::Rect
& rect
, uint32 color
) {
1127 DCHECK(!image_data_
.is_null() || rect
.IsEmpty());
1128 uint32
* buffer_start
= static_cast<uint32
*>(image_data_
.data());
1129 int stride
= image_data_
.stride();
1130 uint32
* ptr
= buffer_start
+ rect
.y() * stride
/ 4 + rect
.x();
1131 int height
= rect
.height();
1132 int width
= rect
.width();
1133 for (int y
= 0; y
< height
; ++y
) {
1134 for (int x
= 0; x
< width
; ++x
)
1140 void Instance::DocumentSizeUpdated(const pp::Size
& size
) {
1141 document_size_
= size
;
1143 OnGeometryChanged(zoom_
, device_scale_
);
1146 void Instance::Invalidate(const pp::Rect
& rect
) {
1147 pp::Rect
offset_rect(rect
);
1148 offset_rect
.Offset(available_area_
.point());
1149 paint_manager_
.InvalidateRect(offset_rect
);
1152 void Instance::Scroll(const pp::Point
& point
) {
1153 pp::Rect scroll_area
= available_area_
;
1154 if (IsOverlayScrollbar()) {
1156 if (h_scrollbar_
.get()) {
1157 h_scrollbar_
->GetLocation(&rc
);
1158 ScaleRect(device_scale_
, &rc
);
1159 if (scroll_area
.bottom() > rc
.y()) {
1160 scroll_area
.set_height(rc
.y() - scroll_area
.y());
1161 paint_manager_
.InvalidateRect(rc
);
1164 if (v_scrollbar_
.get()) {
1165 v_scrollbar_
->GetLocation(&rc
);
1166 ScaleRect(device_scale_
, &rc
);
1167 if (scroll_area
.right() > rc
.x()) {
1168 scroll_area
.set_width(rc
.x() - scroll_area
.x());
1169 paint_manager_
.InvalidateRect(rc
);
1173 paint_manager_
.ScrollRect(scroll_area
, point
);
1175 if (toolbar_
->current_transparency() != kTransparentAlpha
)
1176 paint_manager_
.InvalidateRect(toolbar_
->GetControlsRect());
1178 if (progress_bar_
.visible())
1179 paint_manager_
.InvalidateRect(progress_bar_
.rect());
1182 paint_manager_
.InvalidateRect(autoscroll_rect_
);
1184 if (show_page_indicator_
) {
1185 page_indicator_
.set_current_page(GetPageNumberToDisplay());
1186 page_indicator_
.Splash();
1189 if (page_indicator_
.visible())
1190 paint_manager_
.InvalidateRect(page_indicator_
.rect());
1192 // Run the scroll callback asynchronously. This function can be invoked by a
1193 // layout change which should not re-enter into JS synchronously.
1194 pp::CompletionCallback callback
=
1195 callback_factory_
.NewCallback(&Instance::RunCallback
,
1196 on_scroll_callback_
);
1197 pp::Module::Get()->core()->CallOnMainThread(0, callback
);
1200 void Instance::ScrollToX(int position
) {
1201 if (!h_scrollbar_
.get()) {
1205 int position_dip
= static_cast<int>(position
/ device_scale_
);
1206 h_scrollbar_
->SetValue(position_dip
);
1209 void Instance::ScrollToY(int position
) {
1210 if (!v_scrollbar_
.get()) {
1214 int position_dip
= static_cast<int>(position
/ device_scale_
);
1215 v_scrollbar_
->SetValue(ClipToRange(position_dip
, 0, valid_v_range_
));
1218 void Instance::ScrollToPage(int page
) {
1219 if (!v_scrollbar_
.get())
1222 if (engine_
->GetNumberOfPages() == 0)
1225 int index
= ClipToRange(page
, 0, engine_
->GetNumberOfPages() - 1);
1226 pp::Rect rect
= engine_
->GetPageRect(index
);
1227 // If we are trying to scroll pass the last page,
1228 // scroll to the end of the last page.
1229 int position
= index
< page
? rect
.bottom() : rect
.y();
1230 ScrollToY(position
* zoom_
* device_scale_
);
1233 void Instance::NavigateTo(const std::string
& url
, bool open_in_new_tab
) {
1234 std::string
url_copy(url
);
1236 // Empty |url_copy| is ok, and will effectively be a reload.
1237 // Skip the code below so an empty URL does not turn into "http://", which
1238 // will cause GURL to fail a DCHECK.
1239 if (!url_copy
.empty()) {
1240 // If |url_copy| starts with '#', then it's for the same URL with a
1241 // different URL fragment.
1242 if (url_copy
[0] == '#') {
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 void Instance::PreviewDocumentLoadComplete() {
1617 if (preview_document_load_state_
!= LOAD_STATE_LOADING
||
1618 preview_pages_info_
.empty()) {
1622 preview_document_load_state_
= LOAD_STATE_COMPLETE
;
1624 int dest_page_index
= preview_pages_info_
.front().second
;
1625 int src_page_index
=
1626 ExtractPrintPreviewPageIndex(preview_pages_info_
.front().first
);
1627 if (src_page_index
> 0 && dest_page_index
> -1 && preview_engine_
.get())
1628 engine_
->AppendPage(preview_engine_
.get(), dest_page_index
);
1630 preview_pages_info_
.pop();
1631 // |print_preview_page_count_| is not updated yet. Do not load any
1632 // other preview pages till we get this information.
1633 if (print_preview_page_count_
== 0)
1636 if (preview_pages_info_
.size())
1637 LoadAvailablePreviewPage();
1640 void Instance::DocumentLoadFailed() {
1641 DCHECK(document_load_state_
== LOAD_STATE_LOADING
);
1642 UserMetricsRecordAction("PDF.LoadFailure");
1644 // Hide progress control.
1645 progress_bar_
.Fade(false, kProgressFadeTimeoutMs
);
1647 if (did_call_start_loading_
) {
1648 pp::PDF::DidStopLoading(this);
1649 did_call_start_loading_
= false;
1652 document_load_state_
= LOAD_STATE_FAILED
;
1653 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
1656 void Instance::PreviewDocumentLoadFailed() {
1657 UserMetricsRecordAction("PDF.PreviewDocumentLoadFailure");
1658 if (preview_document_load_state_
!= LOAD_STATE_LOADING
||
1659 preview_pages_info_
.empty()) {
1663 preview_document_load_state_
= LOAD_STATE_FAILED
;
1664 preview_pages_info_
.pop();
1666 if (preview_pages_info_
.size())
1667 LoadAvailablePreviewPage();
1670 pp::Instance
* Instance::GetPluginInstance() {
1671 return GetInstance();
1674 void Instance::DocumentHasUnsupportedFeature(const std::string
& feature
) {
1675 std::string
metric("PDF_Unsupported_");
1677 if (!unsupported_features_reported_
.count(metric
)) {
1678 unsupported_features_reported_
.insert(metric
);
1679 UserMetricsRecordAction(metric
);
1682 // Since we use an info bar, only do this for full frame plugins..
1686 if (told_browser_about_unsupported_feature_
)
1688 told_browser_about_unsupported_feature_
= true;
1690 pp::PDF::HasUnsupportedFeature(this);
1693 void Instance::DocumentLoadProgress(uint32 available
, uint32 doc_size
) {
1694 double progress
= 0.0;
1695 if (doc_size
== 0) {
1696 // Document size is unknown. Use heuristics.
1697 // We'll make progress logarithmic from 0 to 100M.
1698 static const double kFactor
= log(100000000.0) / 100.0;
1699 if (available
> 0) {
1700 progress
= log(static_cast<double>(available
)) / kFactor
;
1701 if (progress
> 100.0)
1705 progress
= 100.0 * static_cast<double>(available
) / doc_size
;
1707 progress_bar_
.SetProgress(progress
);
1710 void Instance::FormTextFieldFocusChange(bool in_focus
) {
1711 if (!text_input_
.get())
1714 text_input_
->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_TEXT
);
1716 text_input_
->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_NONE
);
1719 // Called by PDFScriptableObject.
1720 bool Instance::HasScriptableMethod(const pp::Var
& method
, pp::Var
* exception
) {
1721 std::string method_str
= method
.AsString();
1722 return (method_str
== kJSAccessibility
||
1723 method_str
== kJSDocumentLoadComplete
||
1724 method_str
== kJSGetHeight
||
1725 method_str
== kJSGetHorizontalScrollbarThickness
||
1726 method_str
== kJSGetPageLocationNormalized
||
1727 method_str
== kJSGetSelectedText
||
1728 method_str
== kJSGetVerticalScrollbarThickness
||
1729 method_str
== kJSGetWidth
||
1730 method_str
== kJSGetZoomLevel
||
1731 method_str
== kJSGoToPage
||
1732 method_str
== kJSGrayscale
||
1733 method_str
== kJSLoadPreviewPage
||
1734 method_str
== kJSOnLoad
||
1735 method_str
== kJSOnPluginSizeChanged
||
1736 method_str
== kJSOnScroll
||
1737 method_str
== kJSPageXOffset
||
1738 method_str
== kJSPageYOffset
||
1739 method_str
== kJSPrintPreviewPageCount
||
1740 method_str
== kJSReload
||
1741 method_str
== kJSRemovePrintButton
||
1742 method_str
== kJSResetPrintPreviewUrl
||
1743 method_str
== kJSSendKeyEvent
||
1744 method_str
== kJSSetPageNumbers
||
1745 method_str
== kJSSetPageXOffset
||
1746 method_str
== kJSSetPageYOffset
||
1747 method_str
== kJSSetZoomLevel
||
1748 method_str
== kJSZoomFitToHeight
||
1749 method_str
== kJSZoomFitToWidth
||
1750 method_str
== kJSZoomIn
||
1751 method_str
== kJSZoomOut
);
1754 pp::Var
Instance::CallScriptableMethod(const pp::Var
& method
,
1755 const std::vector
<pp::Var
>& args
,
1756 pp::Var
* exception
) {
1757 std::string method_str
= method
.AsString();
1758 if (method_str
== kJSGrayscale
) {
1759 if (args
.size() == 1 && args
[0].is_bool()) {
1760 engine_
->SetGrayscale(args
[0].AsBool());
1762 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
1763 #ifdef ENABLE_THUMBNAILS
1764 if (thumbnails_
.visible())
1765 thumbnails_
.Show(true, true);
1767 return pp::Var(true);
1769 return pp::Var(false);
1771 if (method_str
== kJSOnLoad
) {
1772 if (args
.size() == 1 && args
[0].is_string()) {
1773 on_load_callback_
= args
[0];
1774 return pp::Var(true);
1776 return pp::Var(false);
1778 if (method_str
== kJSOnScroll
) {
1779 if (args
.size() == 1 && args
[0].is_string()) {
1780 on_scroll_callback_
= args
[0];
1781 return pp::Var(true);
1783 return pp::Var(false);
1785 if (method_str
== kJSOnPluginSizeChanged
) {
1786 if (args
.size() == 1 && args
[0].is_string()) {
1787 on_plugin_size_changed_callback_
= args
[0];
1788 return pp::Var(true);
1790 return pp::Var(false);
1792 if (method_str
== kJSReload
) {
1793 document_load_state_
= LOAD_STATE_LOADING
;
1796 preview_engine_
.reset();
1797 print_preview_page_count_
= 0;
1798 engine_
.reset(PDFEngine::Create(this));
1799 engine_
->New(url_
.c_str());
1800 #ifdef ENABLE_THUMBNAILS
1801 thumbnails_
.ResetEngine(engine_
.get());
1805 if (method_str
== kJSResetPrintPreviewUrl
) {
1806 if (args
.size() == 1 && args
[0].is_string()) {
1807 url_
= args
[0].AsString();
1808 preview_pages_info_
= std::queue
<PreviewPageInfo
>();
1809 preview_document_load_state_
= LOAD_STATE_COMPLETE
;
1813 if (method_str
== kJSZoomFitToHeight
) {
1814 SetZoom(ZOOM_FIT_TO_PAGE
, 0);
1817 if (method_str
== kJSZoomFitToWidth
) {
1818 SetZoom(ZOOM_FIT_TO_WIDTH
, 0);
1821 if (method_str
== kJSZoomIn
) {
1822 SetZoom(ZOOM_SCALE
, CalculateZoom(kZoomInButtonId
));
1825 if (method_str
== kJSZoomOut
) {
1826 SetZoom(ZOOM_SCALE
, CalculateZoom(kZoomOutButtonId
));
1829 if (method_str
== kJSSetZoomLevel
) {
1830 if (args
.size() == 1 && args
[0].is_number())
1831 SetZoom(ZOOM_SCALE
, args
[0].AsDouble());
1834 if (method_str
== kJSGetZoomLevel
) {
1835 return pp::Var(zoom_
);
1837 if (method_str
== kJSGetHeight
) {
1838 return pp::Var(plugin_size_
.height());
1840 if (method_str
== kJSGetWidth
) {
1841 return pp::Var(plugin_size_
.width());
1843 if (method_str
== kJSGetHorizontalScrollbarThickness
) {
1845 h_scrollbar_
.get() ? GetScrollbarReservedThickness() : 0);
1847 if (method_str
== kJSGetVerticalScrollbarThickness
) {
1849 v_scrollbar_
.get() ? GetScrollbarReservedThickness() : 0);
1851 if (method_str
== kJSGetSelectedText
) {
1852 return GetSelectedText(false);
1854 if (method_str
== kJSDocumentLoadComplete
) {
1855 return pp::Var((document_load_state_
!= LOAD_STATE_LOADING
));
1857 if (method_str
== kJSPageYOffset
) {
1858 return pp::Var(static_cast<int32_t>(
1859 v_scrollbar_
.get() ? v_scrollbar_
->GetValue() : 0));
1861 if (method_str
== kJSSetPageYOffset
) {
1862 if (args
.size() == 1 && args
[0].is_number() && v_scrollbar_
.get())
1863 ScrollToY(GetScaled(args
[0].AsInt()));
1866 if (method_str
== kJSPageXOffset
) {
1867 return pp::Var(static_cast<int32_t>(
1868 h_scrollbar_
.get() ? h_scrollbar_
->GetValue() : 0));
1870 if (method_str
== kJSSetPageXOffset
) {
1871 if (args
.size() == 1 && args
[0].is_number() && h_scrollbar_
.get())
1872 ScrollToX(GetScaled(args
[0].AsInt()));
1875 if (method_str
== kJSRemovePrintButton
) {
1876 CreateToolbar(kPrintPreviewToolbarButtons
,
1877 arraysize(kPrintPreviewToolbarButtons
));
1878 UpdateToolbarPosition(false);
1879 Invalidate(pp::Rect(plugin_size_
));
1882 if (method_str
== kJSGoToPage
) {
1883 if (args
.size() == 1 && args
[0].is_string()) {
1884 ScrollToPage(atoi(args
[0].AsString().c_str()));
1888 if (method_str
== kJSAccessibility
) {
1889 if (args
.size() == 0) {
1890 base::DictionaryValue node
;
1891 node
.SetInteger(kAccessibleNumberOfPages
, engine_
->GetNumberOfPages());
1892 node
.SetBoolean(kAccessibleLoaded
,
1893 document_load_state_
!= LOAD_STATE_LOADING
);
1894 bool has_permissions
=
1895 engine_
->HasPermission(PDFEngine::PERMISSION_COPY
) ||
1896 engine_
->HasPermission(PDFEngine::PERMISSION_COPY_ACCESSIBLE
);
1897 node
.SetBoolean(kAccessibleCopyable
, has_permissions
);
1899 base::JSONWriter::Write(&node
, &json
);
1900 return pp::Var(json
);
1901 } else if (args
[0].is_number()) {
1902 return pp::Var(engine_
->GetPageAsJSON(args
[0].AsInt()));
1905 if (method_str
== kJSPrintPreviewPageCount
) {
1906 if (args
.size() == 1 && args
[0].is_number())
1907 SetPrintPreviewMode(args
[0].AsInt());
1910 if (method_str
== kJSLoadPreviewPage
) {
1911 if (args
.size() == 2 && args
[0].is_string() && args
[1].is_number())
1912 ProcessPreviewPageInfo(args
[0].AsString(), args
[1].AsInt());
1915 if (method_str
== kJSGetPageLocationNormalized
) {
1916 const size_t kMaxLength
= 30;
1917 char location_info
[kMaxLength
];
1918 int page_idx
= engine_
->GetMostVisiblePage();
1920 return pp::Var(std::string());
1921 pp::Rect rect
= engine_
->GetPageContentsRect(page_idx
);
1922 int v_scrollbar_reserved_thickness
=
1923 v_scrollbar_
.get() ? GetScaled(GetScrollbarReservedThickness()) : 0;
1925 rect
.set_x(rect
.x() + ((plugin_size_
.width() -
1926 v_scrollbar_reserved_thickness
- available_area_
.width()) / 2));
1927 base::snprintf(location_info
,
1929 "%0.4f;%0.4f;%0.4f;%0.4f;",
1930 rect
.x() / static_cast<float>(plugin_size_
.width()),
1931 rect
.y() / static_cast<float>(plugin_size_
.height()),
1932 rect
.width() / static_cast<float>(plugin_size_
.width()),
1933 rect
.height()/ static_cast<float>(plugin_size_
.height()));
1934 return pp::Var(std::string(location_info
));
1936 if (method_str
== kJSSetPageNumbers
) {
1937 if (args
.size() != 1 || !args
[0].is_string())
1939 const int num_pages_signed
= engine_
->GetNumberOfPages();
1940 if (num_pages_signed
<= 0)
1942 scoped_ptr
<base::ListValue
> page_ranges(static_cast<base::ListValue
*>(
1943 base::JSONReader::Read(args
[0].AsString(), false)));
1944 const size_t num_pages
= static_cast<size_t>(num_pages_signed
);
1945 if (!page_ranges
.get() || page_ranges
->GetSize() != num_pages
)
1948 std::vector
<int> print_preview_page_numbers
;
1949 for (size_t index
= 0; index
< num_pages
; ++index
) {
1950 int page_number
= 0; // |page_number| is 1-based.
1951 if (!page_ranges
->GetInteger(index
, &page_number
) || page_number
< 1)
1953 print_preview_page_numbers
.push_back(page_number
);
1955 print_preview_page_numbers_
= print_preview_page_numbers
;
1956 page_indicator_
.set_current_page(GetPageNumberToDisplay());
1959 // This is here to work around https://bugs.webkit.org/show_bug.cgi?id=16735.
1960 // In JS, creating a synthetic keyboard event and dispatching it always
1961 // result in a keycode of 0.
1962 if (method_str
== kJSSendKeyEvent
) {
1963 if (args
.size() == 1 && args
[0].is_number()) {
1964 pp::KeyboardInputEvent
event(
1966 PP_INPUTEVENT_TYPE_KEYDOWN
, // HandleInputEvent only care about this.
1967 0, // timestamp, not used for kbd events.
1969 args
[0].AsInt(), // keycode.
1970 pp::Var()); // no char text needed.
1971 HandleInputEvent(event
);
1977 void Instance::OnGeometryChanged(double old_zoom
, float old_device_scale
) {
1978 bool force_no_horizontal_scrollbar
= false;
1979 int scrollbar_thickness
= GetScrollbarThickness();
1981 if (old_device_scale
!= device_scale_
) {
1982 // Change in device scale forces us to recreate resources
1983 ConfigureNumberImageGenerator();
1985 CreateToolbar(current_tb_info_
, current_tb_info_size_
);
1986 // Load autoscroll anchor image.
1987 autoscroll_anchor_
=
1988 CreateResourceImage(PP_RESOURCEIMAGE_PDF_PAN_SCROLL_ICON
);
1990 ConfigurePageIndicator();
1991 ConfigureProgressBar();
1993 pp::Point scroll_position
= engine_
->GetScrollPosition();
1994 ScalePoint(device_scale_
/ old_device_scale
, &scroll_position
);
1995 engine_
->SetScrollPosition(scroll_position
);
1999 if (zoom_
!= old_zoom
|| device_scale_
!= old_device_scale
)
2000 engine_
->ZoomUpdated(zoom_
* device_scale_
);
2001 if (zoom_
!= old_zoom
)
2004 available_area_
= pp::Rect(plugin_size_
);
2005 if (GetDocumentPixelHeight() > plugin_size_
.height()) {
2006 CreateVerticalScrollbar();
2008 DestroyVerticalScrollbar();
2011 int v_scrollbar_reserved_thickness
=
2012 v_scrollbar_
.get() ? GetScaled(GetScrollbarReservedThickness()) : 0;
2014 if (!force_no_horizontal_scrollbar
&&
2015 GetDocumentPixelWidth() >
2016 (plugin_size_
.width() - v_scrollbar_reserved_thickness
)) {
2017 CreateHorizontalScrollbar();
2019 // Adding the horizontal scrollbar now might cause us to need vertical
2021 if (GetDocumentPixelHeight() >
2022 plugin_size_
.height() - GetScaled(GetScrollbarReservedThickness())) {
2023 CreateVerticalScrollbar();
2027 DestroyHorizontalScrollbar();
2030 #ifdef ENABLE_THUMBNAILS
2031 int thumbnails_pos
= 0, thumbnails_total
= 0;
2033 if (v_scrollbar_
.get()) {
2034 v_scrollbar_
->SetScale(device_scale_
);
2035 available_area_
.set_width(
2036 std::max(0, plugin_size_
.width() - v_scrollbar_reserved_thickness
));
2038 #ifdef ENABLE_THUMBNAILS
2039 int height
= plugin_size_
.height();
2041 int height_dip
= plugin_dip_size_
.height();
2043 #if defined(OS_MACOSX)
2044 // Before Lion, Mac always had the resize at the bottom. After that, it
2046 if ((base::mac::IsOSSnowLeopard() && full_
) ||
2047 (base::mac::IsOSLionOrLater() && h_scrollbar_
.get())) {
2049 if (h_scrollbar_
.get()) {
2050 #endif // defined(OS_MACOSX)
2051 #ifdef ENABLE_THUMBNAILS
2052 height
-= GetScaled(GetScrollbarThickness());
2054 height_dip
-= GetScrollbarThickness();
2056 #ifdef ENABLE_THUMBNAILS
2057 int32 doc_height
= GetDocumentPixelHeight();
2059 int32 doc_height_dip
=
2060 static_cast<int32
>(GetDocumentPixelHeight() / device_scale_
);
2061 #if defined(OS_MACOSX)
2062 // On the Mac we always allow room for the resize button (whose width is
2063 // the same as that of the scrollbar) in full mode. However, if there is no
2064 // no horizontal scrollbar, the end of the scrollbar will scroll past the
2065 // end of the document. This is because the scrollbar assumes that its own
2066 // height (in the case of a vscroll bar) is the same as the height of the
2067 // viewport. Since the viewport is actually larger, we compensate by
2068 // adjusting the document height. Similar logic applies below for the
2069 // horizontal scrollbar.
2070 // For example, if the document size is 1000, and the viewport size is 200,
2071 // then the scrollbar position at the end will be 800. In this case the
2072 // viewport is actally 215 (assuming 15 as the scrollbar width) but the
2073 // scrollbar thinks it is 200. We want the scrollbar position at the end to
2074 // be 785. Making the document size 985 achieves this.
2075 if (full_
&& !h_scrollbar_
.get()) {
2076 #ifdef ENABLE_THUMBNAILS
2077 doc_height
-= GetScaled(GetScrollbarThickness());
2079 doc_height_dip
-= GetScrollbarThickness();
2081 #endif // defined(OS_MACOSX)
2084 position
= v_scrollbar_
->GetValue();
2085 position
= static_cast<int>(position
* zoom_
/ old_zoom
);
2086 valid_v_range_
= doc_height_dip
- height_dip
;
2087 if (position
> valid_v_range_
)
2088 position
= valid_v_range_
;
2090 v_scrollbar_
->SetValue(position
);
2093 loc
.point
.x
= static_cast<int>(available_area_
.right() / device_scale_
);
2094 if (IsOverlayScrollbar())
2095 loc
.point
.x
-= scrollbar_thickness
;
2097 loc
.size
.width
= scrollbar_thickness
;
2098 loc
.size
.height
= height_dip
;
2099 v_scrollbar_
->SetLocation(loc
);
2100 v_scrollbar_
->SetDocumentSize(doc_height_dip
);
2102 #ifdef ENABLE_THUMBNAILS
2103 thumbnails_pos
= position
;
2104 thumbnails_total
= doc_height
- height
;
2108 if (h_scrollbar_
.get()) {
2109 h_scrollbar_
->SetScale(device_scale_
);
2110 available_area_
.set_height(
2111 std::max(0, plugin_size_
.height() -
2112 GetScaled(GetScrollbarReservedThickness())));
2114 int width_dip
= plugin_dip_size_
.width();
2117 #if defined(OS_MACOSX)
2118 if ((base::mac::IsOSSnowLeopard() && full_
) ||
2119 (base::mac::IsOSLionOrLater() && v_scrollbar_
.get())) {
2121 if (v_scrollbar_
.get()) {
2123 width_dip
-= GetScrollbarThickness();
2125 int32 doc_width_dip
=
2126 static_cast<int32
>(GetDocumentPixelWidth() / device_scale_
);
2127 #if defined(OS_MACOSX)
2128 // See comment in the above if (v_scrollbar_.get()) block.
2129 if (full_
&& !v_scrollbar_
.get())
2130 doc_width_dip
-= GetScrollbarThickness();
2131 #endif // defined(OS_MACOSX)
2134 position
= h_scrollbar_
->GetValue();
2135 position
= static_cast<int>(position
* zoom_
/ old_zoom
);
2136 position
= std::min(position
, doc_width_dip
- width_dip
);
2138 h_scrollbar_
->SetValue(position
);
2142 loc
.point
.y
= static_cast<int>(available_area_
.bottom() / device_scale_
);
2143 if (IsOverlayScrollbar())
2144 loc
.point
.y
-= scrollbar_thickness
;
2145 loc
.size
.width
= width_dip
;
2146 loc
.size
.height
= scrollbar_thickness
;
2147 h_scrollbar_
->SetLocation(loc
);
2148 h_scrollbar_
->SetDocumentSize(doc_width_dip
);
2151 int doc_width
= GetDocumentPixelWidth();
2152 if (doc_width
< available_area_
.width()) {
2153 available_area_
.Offset((available_area_
.width() - doc_width
) / 2, 0);
2154 available_area_
.set_width(doc_width
);
2156 int doc_height
= GetDocumentPixelHeight();
2157 if (doc_height
< available_area_
.height()) {
2158 available_area_
.set_height(doc_height
);
2161 // We'll invalidate the entire plugin anyways.
2162 UpdateToolbarPosition(false);
2163 UpdateProgressBarPosition(false);
2164 UpdatePageIndicatorPosition(false);
2166 #ifdef ENABLE_THUMBNAILS
2167 // Update thumbnail control position.
2168 thumbnails_
.SetPosition(thumbnails_pos
, thumbnails_total
, false);
2169 pp::Rect
thumbnails_rc(plugin_size_
.width() - GetScaled(kThumbnailsWidth
), 0,
2170 GetScaled(kThumbnailsWidth
), plugin_size_
.height());
2171 if (v_scrollbar_
.get())
2172 thumbnails_rc
.Offset(-v_scrollbar_reserved_thickness
, 0);
2173 if (h_scrollbar_
.get())
2174 thumbnails_rc
.Inset(0, 0, 0, v_scrollbar_reserved_thickness
);
2175 thumbnails_
.SetRect(thumbnails_rc
, false);
2178 CalculateBackgroundParts();
2179 engine_
->PageOffsetUpdated(available_area_
.point());
2180 engine_
->PluginSizeUpdated(available_area_
.size());
2182 if (!document_size_
.GetArea())
2184 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
2186 // Run the plugin size change callback asynchronously. This function can be
2187 // invoked by a layout change which should not re-enter into JS synchronously.
2188 pp::CompletionCallback callback
=
2189 callback_factory_
.NewCallback(&Instance::RunCallback
,
2190 on_plugin_size_changed_callback_
);
2191 pp::Module::Get()->core()->CallOnMainThread(0, callback
);
2194 void Instance::RunCallback(int32_t, pp::Var callback
) {
2195 if (callback
.is_string())
2196 ExecuteScript(callback
);
2199 void Instance::CreateHorizontalScrollbar() {
2200 if (h_scrollbar_
.get())
2203 h_scrollbar_
.reset(new pp::Scrollbar_Dev(this, false));
2206 void Instance::CreateVerticalScrollbar() {
2207 if (v_scrollbar_
.get())
2210 v_scrollbar_
.reset(new pp::Scrollbar_Dev(this, true));
2213 void Instance::DestroyHorizontalScrollbar() {
2214 if (!h_scrollbar_
.get())
2216 if (h_scrollbar_
->GetValue())
2217 engine_
->ScrolledToXPosition(0);
2218 h_scrollbar_
.reset();
2221 void Instance::DestroyVerticalScrollbar() {
2222 if (!v_scrollbar_
.get())
2224 if (v_scrollbar_
->GetValue())
2225 engine_
->ScrolledToYPosition(0);
2226 v_scrollbar_
.reset();
2227 page_indicator_
.Show(false, true);
2230 int Instance::GetScrollbarThickness() {
2231 if (scrollbar_thickness_
== -1) {
2232 pp::Scrollbar_Dev
temp_scrollbar(this, false);
2233 scrollbar_thickness_
= temp_scrollbar
.GetThickness();
2234 scrollbar_reserved_thickness_
=
2235 temp_scrollbar
.IsOverlay() ? 0 : scrollbar_thickness_
;
2238 return scrollbar_thickness_
;
2241 int Instance::GetScrollbarReservedThickness() {
2242 GetScrollbarThickness();
2243 return scrollbar_reserved_thickness_
;
2246 bool Instance::IsOverlayScrollbar() {
2247 return GetScrollbarReservedThickness() == 0;
2250 void Instance::CreateToolbar(const ToolbarButtonInfo
* tb_info
, size_t size
) {
2251 toolbar_
.reset(new FadingControls());
2256 // Remember the current toolbar information in case we need to recreate the
2258 current_tb_info_
= tb_info
;
2259 current_tb_info_size_
= size
;
2262 pp::Point
origin(kToolbarFadingOffsetLeft
, kToolbarFadingOffsetTop
);
2263 ScalePoint(device_scale_
, &origin
);
2265 std::list
<Button
*> buttons
;
2266 for (size_t i
= 0; i
< size
; i
++) {
2267 Button
* btn
= new Button
;
2268 pp::ImageData normal_face
=
2269 CreateResourceImage(tb_info
[i
].normal
);
2270 btn
->CreateButton(tb_info
[i
].id
,
2276 CreateResourceImage(tb_info
[i
].highlighted
),
2277 CreateResourceImage(tb_info
[i
].pressed
));
2278 buttons
.push_back(btn
);
2280 origin
+= pp::Point(normal_face
.size().width(), 0);
2281 max_height
= std::max(max_height
, normal_face
.size().height());
2284 pp::Rect
rc_toolbar(0, 0,
2285 origin
.x() + GetToolbarRightOffset(),
2286 origin
.y() + max_height
+ GetToolbarBottomOffset());
2287 toolbar_
->CreateFadingControls(
2288 kToolbarId
, rc_toolbar
, false, this, kTransparentAlpha
);
2290 std::list
<Button
*>::iterator iter
;
2291 for (iter
= buttons
.begin(); iter
!= buttons
.end(); ++iter
) {
2292 toolbar_
->AddControl(*iter
);
2296 int Instance::GetToolbarRightOffset() {
2297 int scrollbar_thickness
= GetScrollbarThickness();
2298 return GetScaled(kToolbarFadingOffsetRight
) + 2 * scrollbar_thickness
;
2301 int Instance::GetToolbarBottomOffset() {
2302 int scrollbar_thickness
= GetScrollbarThickness();
2303 return GetScaled(kToolbarFadingOffsetBottom
) + scrollbar_thickness
;
2306 std::vector
<pp::ImageData
> Instance::GetThumbnailResources() {
2307 std::vector
<pp::ImageData
> num_images(10);
2308 num_images
[0] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_0
);
2309 num_images
[1] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_1
);
2310 num_images
[2] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_2
);
2311 num_images
[3] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_3
);
2312 num_images
[4] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_4
);
2313 num_images
[5] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_5
);
2314 num_images
[6] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_6
);
2315 num_images
[7] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_7
);
2316 num_images
[8] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_8
);
2317 num_images
[9] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_9
);
2321 std::vector
<pp::ImageData
> Instance::GetProgressBarResources(
2322 pp::ImageData
* background
) {
2323 std::vector
<pp::ImageData
> result(9);
2324 result
[0] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_0
);
2325 result
[1] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_1
);
2326 result
[2] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_2
);
2327 result
[3] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_3
);
2328 result
[4] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_4
);
2329 result
[5] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_5
);
2330 result
[6] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_6
);
2331 result
[7] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_7
);
2332 result
[8] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_8
);
2333 *background
= CreateResourceImage(
2334 PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_BACKGROUND
);
2338 void Instance::CreatePageIndicator(bool always_visible
) {
2339 page_indicator_
.CreatePageIndicator(kPageIndicatorId
, false, this,
2340 number_image_generator(), always_visible
);
2341 ConfigurePageIndicator();
2344 void Instance::ConfigurePageIndicator() {
2345 pp::ImageData background
=
2346 CreateResourceImage(PP_RESOURCEIMAGE_PDF_PAGE_INDICATOR_BACKGROUND
);
2347 page_indicator_
.Configure(pp::Point(), background
);
2350 void Instance::CreateProgressBar() {
2351 pp::ImageData background
;
2352 std::vector
<pp::ImageData
> images
= GetProgressBarResources(&background
);
2353 std::string text
= GetLocalizedString(PP_RESOURCESTRING_PDFPROGRESSLOADING
);
2354 progress_bar_
.CreateProgressControl(kProgressBarId
, false, this, 0.0,
2355 device_scale_
, images
, background
, text
);
2358 void Instance::ConfigureProgressBar() {
2359 pp::ImageData background
;
2360 std::vector
<pp::ImageData
> images
= GetProgressBarResources(&background
);
2361 progress_bar_
.Reconfigure(background
, images
, device_scale_
);
2364 void Instance::CreateThumbnails() {
2365 thumbnails_
.CreateThumbnailControl(
2366 kThumbnailsId
, pp::Rect(), false, this, engine_
.get(),
2367 number_image_generator());
2370 void Instance::LoadUrl(const std::string
& url
) {
2371 LoadUrlInternal(url
, &embed_loader_
, &Instance::DidOpen
);
2374 void Instance::LoadPreviewUrl(const std::string
& url
) {
2375 LoadUrlInternal(url
, &embed_preview_loader_
, &Instance::DidOpenPreview
);
2378 void Instance::LoadUrlInternal(const std::string
& url
, pp::URLLoader
* loader
,
2379 void (Instance::* method
)(int32_t)) {
2380 pp::URLRequestInfo
request(this);
2381 request
.SetURL(url
);
2382 request
.SetMethod("GET");
2384 *loader
= CreateURLLoaderInternal();
2385 pp::CompletionCallback callback
= loader_factory_
.NewCallback(method
);
2386 int rv
= loader
->Open(request
, callback
);
2387 if (rv
!= PP_OK_COMPLETIONPENDING
)
2391 pp::URLLoader
Instance::CreateURLLoaderInternal() {
2392 pp::URLLoader
loader(this);
2394 const PPB_URLLoaderTrusted
* trusted_interface
=
2395 reinterpret_cast<const PPB_URLLoaderTrusted
*>(
2396 pp::Module::Get()->GetBrowserInterface(
2397 PPB_URLLOADERTRUSTED_INTERFACE
));
2398 if (trusted_interface
)
2399 trusted_interface
->GrantUniversalAccess(loader
.pp_resource());
2403 int Instance::GetInitialPage(const std::string
& url
) {
2404 size_t found_idx
= url
.find('#');
2405 if (found_idx
== std::string::npos
)
2408 const std::string
& ref
= url
.substr(found_idx
+ 1);
2409 std::vector
<std::string
> fragments
;
2410 Tokenize(ref
, kDelimiters
, &fragments
);
2412 // Page number to return, zero-based.
2415 // Handle the case of http://foo.com/bar#NAMEDDEST. This is not explicitly
2416 // mentioned except by example in the Adobe "PDF Open Parameters" document.
2417 if ((fragments
.size() == 1) && (fragments
[0].find('=') == std::string::npos
))
2418 return engine_
->GetNamedDestinationPage(fragments
[0]);
2420 for (size_t i
= 0; i
< fragments
.size(); ++i
) {
2421 std::vector
<std::string
> key_value
;
2422 base::SplitString(fragments
[i
], '=', &key_value
);
2423 if (key_value
.size() != 2)
2425 const std::string
& key
= key_value
[0];
2426 const std::string
& value
= key_value
[1];
2428 if (base::strcasecmp(kPage
, key
.c_str()) == 0) {
2429 // |page_value| is 1-based.
2430 int page_value
= -1;
2431 if (base::StringToInt(value
, &page_value
) && page_value
> 0)
2432 page
= page_value
- 1;
2435 if (base::strcasecmp(kNamedDest
, key
.c_str()) == 0) {
2436 // |page_value| is 0-based.
2437 int page_value
= engine_
->GetNamedDestinationPage(value
);
2438 if (page_value
>= 0)
2446 void Instance::UpdateToolbarPosition(bool invalidate
) {
2447 pp::Rect ctrl_rc
= toolbar_
->GetControlsRect();
2448 int min_toolbar_width
= ctrl_rc
.width() + GetToolbarRightOffset() +
2449 GetScaled(kToolbarFadingOffsetLeft
);
2450 int min_toolbar_height
= ctrl_rc
.width() + GetToolbarBottomOffset() +
2451 GetScaled(kToolbarFadingOffsetBottom
);
2453 // Update toolbar position
2454 if (plugin_size_
.width() < min_toolbar_width
||
2455 plugin_size_
.height() < min_toolbar_height
) {
2456 // Disable toolbar if it does not fit on the screen.
2457 toolbar_
->Show(false, invalidate
);
2460 plugin_size_
.width() - GetToolbarRightOffset() - ctrl_rc
.right(),
2461 plugin_size_
.height() - GetToolbarBottomOffset() - ctrl_rc
.bottom());
2462 toolbar_
->MoveBy(offset
, invalidate
);
2464 int toolbar_width
= std::max(plugin_size_
.width() / 2, min_toolbar_width
);
2465 toolbar_
->ExpandLeft(toolbar_width
- toolbar_
->rect().width());
2466 toolbar_
->Show(painted_first_page_
, invalidate
);
2470 void Instance::UpdateProgressBarPosition(bool invalidate
) {
2471 // TODO(gene): verify we don't overlap with toolbar.
2472 int scrollbar_thickness
= GetScrollbarThickness();
2473 pp::Point
progress_origin(
2474 scrollbar_thickness
+ GetScaled(kProgressOffsetLeft
),
2475 plugin_size_
.height() - progress_bar_
.rect().height() -
2476 scrollbar_thickness
- GetScaled(kProgressOffsetBottom
));
2477 progress_bar_
.MoveTo(progress_origin
, invalidate
);
2480 void Instance::UpdatePageIndicatorPosition(bool invalidate
) {
2481 int32 doc_height
= static_cast<int>(document_size_
.height() * zoom_
);
2483 plugin_size_
.width() - page_indicator_
.rect().width() -
2484 GetScaled(GetScrollbarReservedThickness()),
2485 page_indicator_
.GetYPosition(engine_
->GetVerticalScrollbarYPosition(),
2486 doc_height
, plugin_size_
.height()));
2487 page_indicator_
.MoveTo(origin
, invalidate
);
2490 void Instance::SetZoom(ZoomMode zoom_mode
, double scale
) {
2491 double old_zoom
= zoom_
;
2493 zoom_mode_
= zoom_mode
;
2494 if (zoom_mode_
== ZOOM_SCALE
)
2498 engine_
->ZoomUpdated(zoom_
* device_scale_
);
2499 OnGeometryChanged(old_zoom
, device_scale_
);
2501 // If fit-to-height, snap to the beginning of the most visible page.
2502 if (zoom_mode_
== ZOOM_FIT_TO_PAGE
) {
2503 ScrollToPage(engine_
->GetMostVisiblePage());
2506 // Update sticky buttons to the current zoom style.
2507 Button
* ftp_btn
= static_cast<Button
*>(
2508 toolbar_
->GetControl(kFitToPageButtonId
));
2509 Button
* ftw_btn
= static_cast<Button
*>(
2510 toolbar_
->GetControl(kFitToWidthButtonId
));
2511 switch (zoom_mode_
) {
2512 case ZOOM_FIT_TO_PAGE
:
2513 ftp_btn
->SetPressedState(true);
2514 ftw_btn
->SetPressedState(false);
2516 case ZOOM_FIT_TO_WIDTH
:
2517 ftw_btn
->SetPressedState(true);
2518 ftp_btn
->SetPressedState(false);
2521 ftw_btn
->SetPressedState(false);
2522 ftp_btn
->SetPressedState(false);
2526 void Instance::UpdateZoomScale() {
2527 switch (zoom_mode_
) {
2529 break; // Keep current scale.
2530 case ZOOM_FIT_TO_PAGE
: {
2531 int page_num
= engine_
->GetFirstVisiblePage();
2534 pp::Rect rc
= engine_
->GetPageRect(page_num
);
2537 // Calculate fit to width zoom level.
2538 double ftw_zoom
= static_cast<double>(plugin_dip_size_
.width() -
2539 GetScrollbarReservedThickness()) / document_size_
.width();
2540 // Calculate fit to height zoom level. If document will not fit
2541 // horizontally, adjust zoom level to allow space for horizontal
2544 static_cast<double>(plugin_dip_size_
.height()) / rc
.height();
2545 if (fth_zoom
* document_size_
.width() >
2546 plugin_dip_size_
.width() - GetScrollbarReservedThickness())
2547 fth_zoom
= static_cast<double>(plugin_dip_size_
.height()
2548 - GetScrollbarReservedThickness()) / rc
.height();
2549 zoom_
= std::min(ftw_zoom
, fth_zoom
);
2551 case ZOOM_FIT_TO_WIDTH
:
2553 if (!document_size_
.width())
2555 zoom_
= static_cast<double>(plugin_dip_size_
.width() -
2556 GetScrollbarReservedThickness()) / document_size_
.width();
2557 if (zoom_mode_
== ZOOM_AUTO
&& zoom_
> 1.0)
2561 zoom_
= ClipToRange(zoom_
, kMinZoom
, kMaxZoom
);
2564 double Instance::CalculateZoom(uint32 control_id
) const {
2565 if (control_id
== kZoomInButtonId
) {
2566 for (size_t i
= 0; i
< chrome_page_zoom::kPresetZoomFactorsSize
; ++i
) {
2567 double current_zoom
= chrome_page_zoom::kPresetZoomFactors
[i
];
2568 if (current_zoom
- content::kEpsilon
> zoom_
)
2569 return current_zoom
;
2572 for (size_t i
= chrome_page_zoom::kPresetZoomFactorsSize
; i
> 0; --i
) {
2573 double current_zoom
= chrome_page_zoom::kPresetZoomFactors
[i
- 1];
2574 if (current_zoom
+ content::kEpsilon
< zoom_
)
2575 return current_zoom
;
2581 pp::ImageData
Instance::CreateResourceImage(PP_ResourceImage image_id
) {
2582 pp::ImageData resource_data
;
2583 if (hidpi_enabled_
) {
2585 pp::PDF::GetResourceImageForScale(this, image_id
, device_scale_
);
2588 return resource_data
.data() ? resource_data
2589 : pp::PDF::GetResourceImage(this, image_id
);
2592 std::string
Instance::GetLocalizedString(PP_ResourceString id
) {
2593 pp::Var
rv(pp::PDF::GetLocalizedString(this, id
));
2594 if (!rv
.is_string())
2595 return std::string();
2597 return rv
.AsString();
2600 void Instance::DrawText(const pp::Point
& top_center
, PP_ResourceString id
) {
2601 std::string
str(GetLocalizedString(id
));
2603 pp::FontDescription_Dev description
;
2604 description
.set_family(PP_FONTFAMILY_SANSSERIF
);
2605 description
.set_size(kMessageTextSize
* device_scale_
);
2606 pp::Font_Dev
font(this, description
);
2607 int length
= font
.MeasureSimpleText(str
);
2608 pp::Point
point(top_center
);
2609 point
.set_x(point
.x() - length
/ 2);
2610 DCHECK(!image_data_
.is_null());
2611 font
.DrawSimpleText(&image_data_
, str
, point
, kMessageTextColor
);
2614 void Instance::SetPrintPreviewMode(int page_count
) {
2615 if (!IsPrintPreview() || page_count
<= 0) {
2616 print_preview_page_count_
= 0;
2620 print_preview_page_count_
= page_count
;
2622 engine_
->AppendBlankPages(print_preview_page_count_
);
2623 if (preview_pages_info_
.size() > 0)
2624 LoadAvailablePreviewPage();
2627 bool Instance::IsPrintPreview() {
2628 return IsPrintPreviewUrl(url_
);
2631 int Instance::GetPageNumberToDisplay() {
2632 int page
= engine_
->GetMostVisiblePage();
2633 if (IsPrintPreview() && !print_preview_page_numbers_
.empty()) {
2634 page
= ClipToRange
<int>(page
, 0, print_preview_page_numbers_
.size() - 1);
2635 return print_preview_page_numbers_
[page
];
2640 void Instance::ProcessPreviewPageInfo(const std::string
& url
,
2641 int dst_page_index
) {
2642 if (!IsPrintPreview() || print_preview_page_count_
< 0)
2645 int src_page_index
= ExtractPrintPreviewPageIndex(url
);
2646 if (src_page_index
< 1)
2649 preview_pages_info_
.push(std::make_pair(url
, dst_page_index
));
2650 LoadAvailablePreviewPage();
2653 void Instance::LoadAvailablePreviewPage() {
2654 if (preview_pages_info_
.size() <= 0)
2657 std::string url
= preview_pages_info_
.front().first
;
2658 int dst_page_index
= preview_pages_info_
.front().second
;
2659 int src_page_index
= ExtractPrintPreviewPageIndex(url
);
2660 if (src_page_index
< 1 ||
2661 dst_page_index
>= print_preview_page_count_
||
2662 preview_document_load_state_
== LOAD_STATE_LOADING
) {
2666 preview_document_load_state_
= LOAD_STATE_LOADING
;
2667 LoadPreviewUrl(url
);
2670 void Instance::EnableAutoscroll(const pp::Point
& origin
) {
2674 pp::Size client_size
= plugin_size_
;
2675 if (v_scrollbar_
.get())
2676 client_size
.Enlarge(-GetScrollbarThickness(), 0);
2677 if (h_scrollbar_
.get())
2678 client_size
.Enlarge(0, -GetScrollbarThickness());
2680 // Do not allow autoscroll if client area is too small.
2681 if (autoscroll_anchor_
.size().width() > client_size
.width() ||
2682 autoscroll_anchor_
.size().height() > client_size
.height())
2685 autoscroll_rect_
= pp::Rect(
2686 pp::Point(origin
.x() - autoscroll_anchor_
.size().width() / 2,
2687 origin
.y() - autoscroll_anchor_
.size().height() / 2),
2688 autoscroll_anchor_
.size());
2690 // Make sure autoscroll anchor is in the client area.
2691 if (autoscroll_rect_
.right() > client_size
.width()) {
2692 autoscroll_rect_
.set_x(
2693 client_size
.width() - autoscroll_anchor_
.size().width());
2695 if (autoscroll_rect_
.bottom() > client_size
.height()) {
2696 autoscroll_rect_
.set_y(
2697 client_size
.height() - autoscroll_anchor_
.size().height());
2700 if (autoscroll_rect_
.x() < 0)
2701 autoscroll_rect_
.set_x(0);
2702 if (autoscroll_rect_
.y() < 0)
2703 autoscroll_rect_
.set_y(0);
2705 is_autoscroll_
= true;
2706 Invalidate(kAutoScrollId
, autoscroll_rect_
);
2708 ScheduleTimer(kAutoScrollId
, kAutoScrollTimeoutMs
);
2711 void Instance::DisableAutoscroll() {
2712 if (is_autoscroll_
) {
2713 is_autoscroll_
= false;
2714 Invalidate(kAutoScrollId
, autoscroll_rect_
);
2718 PP_CursorType_Dev
Instance::CalculateAutoscroll(const pp::Point
& mouse_pos
) {
2719 // Scroll only if mouse pointer is outside of the anchor area.
2720 if (autoscroll_rect_
.Contains(mouse_pos
)) {
2723 return PP_CURSORTYPE_MIDDLEPANNING
;
2726 // Relative position to the center of anchor area.
2727 pp::Point rel_pos
= mouse_pos
- autoscroll_rect_
.CenterPoint();
2729 // Calculate angle from the X axis. Angle is in range from -pi to pi.
2730 double angle
= atan2(static_cast<double>(rel_pos
.y()),
2731 static_cast<double>(rel_pos
.x()));
2733 autoscroll_x_
= rel_pos
.x() * kAutoScrollFactor
;
2734 autoscroll_y_
= rel_pos
.y() * kAutoScrollFactor
;
2736 // Angle is from -pi to pi. Screen Y is increasing toward bottom,
2737 // so negative angle represent north direction.
2738 if (angle
< - (M_PI
* 7.0 / 8.0)) {
2740 return PP_CURSORTYPE_WESTPANNING
;
2741 } else if (angle
< - (M_PI
* 5.0 / 8.0)) {
2743 return PP_CURSORTYPE_NORTHWESTPANNING
;
2744 } else if (angle
< - (M_PI
* 3.0 / 8.0)) {
2746 return PP_CURSORTYPE_NORTHPANNING
;
2747 } else if (angle
< - (M_PI
* 1.0 / 8.0)) {
2749 return PP_CURSORTYPE_NORTHEASTPANNING
;
2750 } else if (angle
< M_PI
* 1.0 / 8.0) {
2752 return PP_CURSORTYPE_EASTPANNING
;
2753 } else if (angle
< M_PI
* 3.0 / 8.0) {
2755 return PP_CURSORTYPE_SOUTHEASTPANNING
;
2756 } else if (angle
< M_PI
* 5.0 / 8.0) {
2758 return PP_CURSORTYPE_SOUTHPANNING
;
2759 } else if (angle
< M_PI
* 7.0 / 8.0) {
2761 return PP_CURSORTYPE_SOUTHWESTPANNING
;
2764 // went around the circle, going west again
2765 return PP_CURSORTYPE_WESTPANNING
;
2768 void Instance::ConfigureNumberImageGenerator() {
2769 std::vector
<pp::ImageData
> num_images
= GetThumbnailResources();
2770 pp::ImageData number_background
= CreateResourceImage(
2771 PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_NUM_BACKGROUND
);
2772 number_image_generator_
->Configure(number_background
,
2777 NumberImageGenerator
* Instance::number_image_generator() {
2778 if (!number_image_generator_
.get()) {
2779 number_image_generator_
.reset(new NumberImageGenerator(this));
2780 ConfigureNumberImageGenerator();
2782 return number_image_generator_
.get();
2785 int Instance::GetScaled(int x
) const {
2786 return static_cast<int>(x
* device_scale_
);
2789 void Instance::UserMetricsRecordAction(const std::string
& action
) {
2790 pp::PDF::UserMetricsRecordAction(this, pp::Var(action
));
2793 PDFScriptableObject::PDFScriptableObject(Instance
* instance
)
2794 : instance_(instance
) {
2797 PDFScriptableObject::~PDFScriptableObject() {
2800 bool PDFScriptableObject::HasMethod(const pp::Var
& name
, pp::Var
* exception
) {
2801 return instance_
->HasScriptableMethod(name
, exception
);
2804 pp::Var
PDFScriptableObject::Call(const pp::Var
& method
,
2805 const std::vector
<pp::Var
>& args
,
2806 pp::Var
* exception
) {
2807 return instance_
->CallScriptableMethod(method
, args
, exception
);
2810 } // namespace chrome_pdf