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/out_of_process_instance.h"
7 #include <algorithm> // for min/max()
8 #define _USE_MATH_DEFINES // for M_PI
9 #include <cmath> // for log() and pow()
13 #include "base/json/json_reader.h"
14 #include "base/json/json_writer.h"
15 #include "base/logging.h"
16 #include "base/strings/string_number_conversions.h"
17 #include "base/strings/string_split.h"
18 #include "base/strings/string_util.h"
19 #include "base/values.h"
20 #include "chrome/common/content_restriction.h"
21 #include "net/base/escape.h"
23 #include "ppapi/c/dev/ppb_cursor_control_dev.h"
24 #include "ppapi/c/pp_errors.h"
25 #include "ppapi/c/pp_rect.h"
26 #include "ppapi/c/private/ppb_instance_private.h"
27 #include "ppapi/c/private/ppp_pdf.h"
28 #include "ppapi/c/trusted/ppb_url_loader_trusted.h"
29 #include "ppapi/cpp/core.h"
30 #include "ppapi/cpp/dev/memory_dev.h"
31 #include "ppapi/cpp/dev/text_input_dev.h"
32 #include "ppapi/cpp/dev/url_util_dev.h"
33 #include "ppapi/cpp/module.h"
34 #include "ppapi/cpp/point.h"
35 #include "ppapi/cpp/private/pdf.h"
36 #include "ppapi/cpp/private/var_private.h"
37 #include "ppapi/cpp/rect.h"
38 #include "ppapi/cpp/resource.h"
39 #include "ppapi/cpp/url_request_info.h"
40 #include "ppapi/cpp/var_array.h"
41 #include "ppapi/cpp/var_dictionary.h"
42 #include "ui/events/keycodes/keyboard_codes.h"
44 namespace chrome_pdf
{
46 const char kChromePrint
[] = "chrome://print/";
47 const char kChromeExtension
[] =
48 "chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai";
50 // Dictionary Value key names for the document accessibility info
51 const char kAccessibleNumberOfPages
[] = "numberOfPages";
52 const char kAccessibleLoaded
[] = "loaded";
53 const char kAccessibleCopyable
[] = "copyable";
55 // PDF background colors.
56 const uint32 kBackgroundColor
= 0xFFCCCCCC;
57 const uint32 kBackgroundColorMaterial
= 0xFF525659;
59 // Constants used in handling postMessage() messages.
60 const char kType
[] = "type";
61 // Viewport message arguments. (Page -> Plugin).
62 const char kJSViewportType
[] = "viewport";
63 const char kJSXOffset
[] = "xOffset";
64 const char kJSYOffset
[] = "yOffset";
65 const char kJSZoom
[] = "zoom";
66 // Stop scrolling message (Page -> Plugin)
67 const char kJSStopScrollingType
[] = "stopScrolling";
68 // Document dimension arguments (Plugin -> Page).
69 const char kJSDocumentDimensionsType
[] = "documentDimensions";
70 const char kJSDocumentWidth
[] = "width";
71 const char kJSDocumentHeight
[] = "height";
72 const char kJSPageDimensions
[] = "pageDimensions";
73 const char kJSPageX
[] = "x";
74 const char kJSPageY
[] = "y";
75 const char kJSPageWidth
[] = "width";
76 const char kJSPageHeight
[] = "height";
77 // Document load progress arguments (Plugin -> Page)
78 const char kJSLoadProgressType
[] = "loadProgress";
79 const char kJSProgressPercentage
[] = "progress";
81 const char kJSMetadataType
[] = "metadata";
82 const char kJSBookmarks
[] = "bookmarks";
83 const char kJSTitle
[] = "title";
84 // Get password arguments (Plugin -> Page)
85 const char kJSGetPasswordType
[] = "getPassword";
86 // Get password complete arguments (Page -> Plugin)
87 const char kJSGetPasswordCompleteType
[] = "getPasswordComplete";
88 const char kJSPassword
[] = "password";
89 // Print (Page -> Plugin)
90 const char kJSPrintType
[] = "print";
91 // Save (Page -> Plugin)
92 const char kJSSaveType
[] = "save";
93 // Go to page (Plugin -> Page)
94 const char kJSGoToPageType
[] = "goToPage";
95 const char kJSPageNumber
[] = "page";
96 // Reset print preview mode (Page -> Plugin)
97 const char kJSResetPrintPreviewModeType
[] = "resetPrintPreviewMode";
98 const char kJSPrintPreviewUrl
[] = "url";
99 const char kJSPrintPreviewGrayscale
[] = "grayscale";
100 const char kJSPrintPreviewPageCount
[] = "pageCount";
101 // Load preview page (Page -> Plugin)
102 const char kJSLoadPreviewPageType
[] = "loadPreviewPage";
103 const char kJSPreviewPageUrl
[] = "url";
104 const char kJSPreviewPageIndex
[] = "index";
105 // Set scroll position (Plugin -> Page)
106 const char kJSSetScrollPositionType
[] = "setScrollPosition";
107 const char kJSPositionX
[] = "x";
108 const char kJSPositionY
[] = "y";
109 // Set translated strings (Plugin -> Page)
110 const char kJSSetTranslatedStringsType
[] = "setTranslatedStrings";
111 const char kJSGetPasswordString
[] = "getPasswordString";
112 const char kJSLoadingString
[] = "loadingString";
113 const char kJSLoadFailedString
[] = "loadFailedString";
114 // Request accessibility JSON data (Page -> Plugin)
115 const char kJSGetAccessibilityJSONType
[] = "getAccessibilityJSON";
116 const char kJSAccessibilityPageNumber
[] = "page";
117 // Reply with accessibility JSON data (Plugin -> Page)
118 const char kJSGetAccessibilityJSONReplyType
[] = "getAccessibilityJSONReply";
119 const char kJSAccessibilityJSON
[] = "json";
120 // Cancel the stream URL request (Plugin -> Page)
121 const char kJSCancelStreamUrlType
[] = "cancelStreamUrl";
122 // Navigate to the given URL (Plugin -> Page)
123 const char kJSNavigateType
[] = "navigate";
124 const char kJSNavigateUrl
[] = "url";
125 const char kJSNavigateNewTab
[] = "newTab";
126 // Open the email editor with the given parameters (Plugin -> Page)
127 const char kJSEmailType
[] = "email";
128 const char kJSEmailTo
[] = "to";
129 const char kJSEmailCc
[] = "cc";
130 const char kJSEmailBcc
[] = "bcc";
131 const char kJSEmailSubject
[] = "subject";
132 const char kJSEmailBody
[] = "body";
133 // Rotation (Page -> Plugin)
134 const char kJSRotateClockwiseType
[] = "rotateClockwise";
135 const char kJSRotateCounterclockwiseType
[] = "rotateCounterclockwise";
136 // Select all text in the document (Page -> Plugin)
137 const char kJSSelectAllType
[] = "selectAll";
138 // Get the selected text in the document (Page -> Plugin)
139 const char kJSGetSelectedTextType
[] = "getSelectedText";
140 // Reply with selected text (Plugin -> Page)
141 const char kJSGetSelectedTextReplyType
[] = "getSelectedTextReply";
142 const char kJSSelectedText
[] = "selectedText";
144 // Get the named destination with the given name (Page -> Plugin)
145 const char KJSGetNamedDestinationType
[] = "getNamedDestination";
146 const char KJSGetNamedDestination
[] = "namedDestination";
147 // Reply with the page number of the named destination (Plugin -> Page)
148 const char kJSGetNamedDestinationReplyType
[] = "getNamedDestinationReply";
149 const char kJSNamedDestinationPageNumber
[] = "pageNumber";
151 // Selecting text in document (Plugin -> Page)
152 const char kJSSetIsSelectingType
[] = "setIsSelecting";
153 const char kJSIsSelecting
[] = "isSelecting";
155 const int kFindResultCooldownMs
= 100;
157 const double kMinZoom
= 0.01;
161 static const char kPPPPdfInterface
[] = PPP_PDF_INTERFACE_1
;
163 PP_Var
GetLinkAtPosition(PP_Instance instance
, PP_Point point
) {
165 void* object
= pp::Instance::GetPerInstanceObject(instance
, kPPPPdfInterface
);
167 var
= static_cast<OutOfProcessInstance
*>(object
)->GetLinkAtPosition(
173 void Transform(PP_Instance instance
, PP_PrivatePageTransformType type
) {
175 pp::Instance::GetPerInstanceObject(instance
, kPPPPdfInterface
);
177 OutOfProcessInstance
* obj_instance
=
178 static_cast<OutOfProcessInstance
*>(object
);
180 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CW
:
181 obj_instance
->RotateClockwise();
183 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CCW
:
184 obj_instance
->RotateCounterclockwise();
190 PP_Bool
GetPrintPresetOptionsFromDocument(
191 PP_Instance instance
,
192 PP_PdfPrintPresetOptions_Dev
* options
) {
193 void* object
= pp::Instance::GetPerInstanceObject(instance
, kPPPPdfInterface
);
195 OutOfProcessInstance
* obj_instance
=
196 static_cast<OutOfProcessInstance
*>(object
);
197 obj_instance
->GetPrintPresetOptionsFromDocument(options
);
202 const PPP_Pdf ppp_private
= {
205 &GetPrintPresetOptionsFromDocument
208 int ExtractPrintPreviewPageIndex(const std::string
& src_url
) {
209 // Sample |src_url| format: chrome://print/id/page_index/print.pdf
210 std::vector
<std::string
> url_substr
= base::SplitString(
211 src_url
.substr(strlen(kChromePrint
)), "/",
212 base::TRIM_WHITESPACE
, base::SPLIT_WANT_ALL
);
213 if (url_substr
.size() != 3)
216 if (url_substr
[2] != "print.pdf")
220 if (!base::StringToInt(url_substr
[1], &page_index
))
225 bool IsPrintPreviewUrl(const std::string
& url
) {
226 return url
.substr(0, strlen(kChromePrint
)) == kChromePrint
;
229 void ScalePoint(float scale
, pp::Point
* point
) {
230 point
->set_x(static_cast<int>(point
->x() * scale
));
231 point
->set_y(static_cast<int>(point
->y() * scale
));
234 void ScaleRect(float scale
, pp::Rect
* rect
) {
235 int left
= static_cast<int>(floorf(rect
->x() * scale
));
236 int top
= static_cast<int>(floorf(rect
->y() * scale
));
237 int right
= static_cast<int>(ceilf((rect
->x() + rect
->width()) * scale
));
238 int bottom
= static_cast<int>(ceilf((rect
->y() + rect
->height()) * scale
));
239 rect
->SetRect(left
, top
, right
- left
, bottom
- top
);
242 // TODO(raymes): Remove this dependency on VarPrivate/InstancePrivate. It's
243 // needed right now to do a synchronous call to JavaScript, but we could easily
244 // replace this with a custom PPB_PDF function.
245 pp::Var
ModalDialog(const pp::Instance
* instance
,
246 const std::string
& type
,
247 const std::string
& message
,
248 const std::string
& default_answer
) {
249 const PPB_Instance_Private
* interface
=
250 reinterpret_cast<const PPB_Instance_Private
*>(
251 pp::Module::Get()->GetBrowserInterface(
252 PPB_INSTANCE_PRIVATE_INTERFACE
));
253 pp::VarPrivate
window(pp::PASS_REF
,
254 interface
->GetWindowObject(instance
->pp_instance()));
255 if (default_answer
.empty())
256 return window
.Call(type
, message
);
258 return window
.Call(type
, message
, default_answer
);
263 OutOfProcessInstance::OutOfProcessInstance(PP_Instance instance
)
264 : pp::Instance(instance
),
265 pp::Find_Private(this),
266 pp::Printing_Dev(this),
267 cursor_(PP_CURSORTYPE_POINTER
),
271 paint_manager_(this, this, true),
273 document_load_state_(LOAD_STATE_LOADING
),
274 preview_document_load_state_(LOAD_STATE_COMPLETE
),
276 told_browser_about_unsupported_feature_(false),
277 print_preview_page_count_(0),
278 last_progress_sent_(0),
279 recently_sent_find_update_(false),
280 received_viewport_message_(false),
281 did_call_start_loading_(false),
282 stop_scrolling_(false),
283 background_color_(kBackgroundColor
),
284 top_toolbar_height_(0) {
285 loader_factory_
.Initialize(this);
286 timer_factory_
.Initialize(this);
287 form_factory_
.Initialize(this);
288 print_callback_factory_
.Initialize(this);
289 engine_
.reset(PDFEngine::Create(this));
290 pp::Module::Get()->AddPluginInterface(kPPPPdfInterface
, &ppp_private
);
291 AddPerInstanceObject(kPPPPdfInterface
, this);
293 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_MOUSE
);
294 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_KEYBOARD
);
295 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_TOUCH
);
298 OutOfProcessInstance::~OutOfProcessInstance() {
299 RemovePerInstanceObject(kPPPPdfInterface
, this);
300 // Explicitly reset the PDFEngine during destruction as it may call back into
305 bool OutOfProcessInstance::Init(uint32_t argc
,
307 const char* argv
[]) {
308 // Check if the PDF is being loaded in the PDF chrome extension. We only allow
309 // the plugin to be loaded in the extension and print preview to avoid
310 // exposing sensitive APIs directly to external websites.
311 pp::Var document_url_var
= pp::URLUtil_Dev::Get()->GetDocumentURL(this);
312 if (!document_url_var
.is_string())
314 std::string document_url
= document_url_var
.AsString();
315 std::string extension_url
= std::string(kChromeExtension
);
316 std::string print_preview_url
= std::string(kChromePrint
);
317 if (!base::StringPiece(document_url
).starts_with(kChromeExtension
) &&
318 !base::StringPiece(document_url
).starts_with(kChromePrint
)) {
322 // Check if the plugin is full frame. This is passed in from JS.
323 for (uint32_t i
= 0; i
< argc
; ++i
) {
324 if (strcmp(argn
[i
], "full-frame") == 0) {
330 // Only allow the plugin to handle find requests if it is full frame.
332 SetPluginToHandleFindRequests();
334 // Send translated strings to the extension where they will be displayed.
335 // TODO(raymes): It would be better to get these in the extension directly
336 // through an API but no such API currently exists.
337 pp::VarDictionary translated_strings
;
338 translated_strings
.Set(kType
, kJSSetTranslatedStringsType
);
339 translated_strings
.Set(kJSGetPasswordString
,
340 GetLocalizedString(PP_RESOURCESTRING_PDFGETPASSWORD
));
341 translated_strings
.Set(kJSLoadingString
,
342 GetLocalizedString(PP_RESOURCESTRING_PDFLOADING
));
343 translated_strings
.Set(kJSLoadFailedString
,
344 GetLocalizedString(PP_RESOURCESTRING_PDFLOAD_FAILED
));
345 PostMessage(translated_strings
);
347 text_input_
.reset(new pp::TextInput_Dev(this));
349 const char* stream_url
= nullptr;
350 const char* original_url
= nullptr;
351 const char* headers
= nullptr;
352 bool is_material
= false;
353 for (uint32_t i
= 0; i
< argc
; ++i
) {
354 if (strcmp(argn
[i
], "src") == 0)
355 original_url
= argv
[i
];
356 else if (strcmp(argn
[i
], "stream-url") == 0)
357 stream_url
= argv
[i
];
358 else if (strcmp(argn
[i
], "headers") == 0)
360 else if (strcmp(argn
[i
], "is-material") == 0)
362 else if (strcmp(argn
[i
], "top-toolbar-height") == 0)
363 base::StringToInt(argv
[i
], &top_toolbar_height_
);
367 background_color_
= kBackgroundColorMaterial
;
369 background_color_
= kBackgroundColor
;
375 stream_url
= original_url
;
377 // If we're in print preview mode we don't need to load the document yet.
378 // A |kJSResetPrintPreviewModeType| message will be sent to the plugin letting
379 // it know the url to load. By not loading here we avoid loading the same
381 if (IsPrintPreviewUrl(original_url
))
386 return engine_
->New(original_url
, headers
);
389 void OutOfProcessInstance::HandleMessage(const pp::Var
& message
) {
390 pp::VarDictionary
dict(message
);
391 if (!dict
.Get(kType
).is_string()) {
396 std::string type
= dict
.Get(kType
).AsString();
398 if (type
== kJSViewportType
&&
399 dict
.Get(pp::Var(kJSXOffset
)).is_number() &&
400 dict
.Get(pp::Var(kJSYOffset
)).is_number() &&
401 dict
.Get(pp::Var(kJSZoom
)).is_number()) {
402 received_viewport_message_
= true;
403 stop_scrolling_
= false;
404 double zoom
= dict
.Get(pp::Var(kJSZoom
)).AsDouble();
405 pp::FloatPoint
scroll_offset(dict
.Get(pp::Var(kJSXOffset
)).AsDouble(),
406 dict
.Get(pp::Var(kJSYOffset
)).AsDouble());
408 // Bound the input parameters.
409 zoom
= std::max(kMinZoom
, zoom
);
411 scroll_offset
= BoundScrollOffsetToDocument(scroll_offset
);
412 engine_
->ScrolledToXPosition(scroll_offset
.x() * device_scale_
);
413 engine_
->ScrolledToYPosition(scroll_offset
.y() * device_scale_
);
414 } else if (type
== kJSGetPasswordCompleteType
&&
415 dict
.Get(pp::Var(kJSPassword
)).is_string()) {
416 if (password_callback_
) {
417 pp::CompletionCallbackWithOutput
<pp::Var
> callback
= *password_callback_
;
418 password_callback_
.reset();
419 *callback
.output() = dict
.Get(pp::Var(kJSPassword
)).pp_var();
424 } else if (type
== kJSPrintType
) {
426 } else if (type
== kJSSaveType
) {
427 pp::PDF::SaveAs(this);
428 } else if (type
== kJSRotateClockwiseType
) {
430 } else if (type
== kJSRotateCounterclockwiseType
) {
431 RotateCounterclockwise();
432 } else if (type
== kJSSelectAllType
) {
433 engine_
->SelectAll();
434 } else if (type
== kJSResetPrintPreviewModeType
&&
435 dict
.Get(pp::Var(kJSPrintPreviewUrl
)).is_string() &&
436 dict
.Get(pp::Var(kJSPrintPreviewGrayscale
)).is_bool() &&
437 dict
.Get(pp::Var(kJSPrintPreviewPageCount
)).is_int()) {
438 url_
= dict
.Get(pp::Var(kJSPrintPreviewUrl
)).AsString();
439 preview_pages_info_
= std::queue
<PreviewPageInfo
>();
440 preview_document_load_state_
= LOAD_STATE_COMPLETE
;
441 document_load_state_
= LOAD_STATE_LOADING
;
443 preview_engine_
.reset();
444 engine_
.reset(PDFEngine::Create(this));
445 engine_
->SetGrayscale(dict
.Get(pp::Var(kJSPrintPreviewGrayscale
)).AsBool());
446 engine_
->New(url_
.c_str(), nullptr /* empty header */);
448 print_preview_page_count_
=
449 std::max(dict
.Get(pp::Var(kJSPrintPreviewPageCount
)).AsInt(), 0);
451 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
452 } else if (type
== kJSLoadPreviewPageType
&&
453 dict
.Get(pp::Var(kJSPreviewPageUrl
)).is_string() &&
454 dict
.Get(pp::Var(kJSPreviewPageIndex
)).is_int()) {
455 ProcessPreviewPageInfo(dict
.Get(pp::Var(kJSPreviewPageUrl
)).AsString(),
456 dict
.Get(pp::Var(kJSPreviewPageIndex
)).AsInt());
457 } else if (type
== kJSGetAccessibilityJSONType
) {
458 pp::VarDictionary reply
;
459 reply
.Set(pp::Var(kType
), pp::Var(kJSGetAccessibilityJSONReplyType
));
460 if (dict
.Get(pp::Var(kJSAccessibilityPageNumber
)).is_int()) {
461 int page
= dict
.Get(pp::Var(kJSAccessibilityPageNumber
)).AsInt();
462 reply
.Set(pp::Var(kJSAccessibilityJSON
),
463 pp::Var(engine_
->GetPageAsJSON(page
)));
465 base::DictionaryValue node
;
466 node
.SetInteger(kAccessibleNumberOfPages
, engine_
->GetNumberOfPages());
467 node
.SetBoolean(kAccessibleLoaded
,
468 document_load_state_
!= LOAD_STATE_LOADING
);
469 bool has_permissions
=
470 engine_
->HasPermission(PDFEngine::PERMISSION_COPY
) ||
471 engine_
->HasPermission(PDFEngine::PERMISSION_COPY_ACCESSIBLE
);
472 node
.SetBoolean(kAccessibleCopyable
, has_permissions
);
474 base::JSONWriter::Write(node
, &json
);
475 reply
.Set(pp::Var(kJSAccessibilityJSON
), pp::Var(json
));
478 } else if (type
== kJSStopScrollingType
) {
479 stop_scrolling_
= true;
480 } else if (type
== kJSGetSelectedTextType
) {
481 std::string selected_text
= engine_
->GetSelectedText();
482 // Always return unix newlines to JS.
483 base::ReplaceChars(selected_text
, "\r", std::string(), &selected_text
);
484 pp::VarDictionary reply
;
485 reply
.Set(pp::Var(kType
), pp::Var(kJSGetSelectedTextReplyType
));
486 reply
.Set(pp::Var(kJSSelectedText
), selected_text
);
488 } else if (type
== KJSGetNamedDestinationType
&&
489 dict
.Get(pp::Var(KJSGetNamedDestination
)).is_string()) {
490 int page_number
= engine_
->GetNamedDestinationPage(
491 dict
.Get(pp::Var(KJSGetNamedDestination
)).AsString());
492 pp::VarDictionary reply
;
493 reply
.Set(pp::Var(kType
), pp::Var(kJSGetNamedDestinationReplyType
));
494 if (page_number
>= 0)
495 reply
.Set(pp::Var(kJSNamedDestinationPageNumber
), page_number
);
502 bool OutOfProcessInstance::HandleInputEvent(
503 const pp::InputEvent
& event
) {
504 // To simplify things, convert the event into device coordinates if it is
506 pp::InputEvent
event_device_res(event
);
508 pp::MouseInputEvent
mouse_event(event
);
509 if (!mouse_event
.is_null()) {
510 pp::Point point
= mouse_event
.GetPosition();
511 pp::Point movement
= mouse_event
.GetMovement();
512 ScalePoint(device_scale_
, &point
);
513 ScalePoint(device_scale_
, &movement
);
514 mouse_event
= pp::MouseInputEvent(
517 event
.GetTimeStamp(),
518 event
.GetModifiers(),
519 mouse_event
.GetButton(),
521 mouse_event
.GetClickCount(),
523 event_device_res
= mouse_event
;
527 pp::InputEvent
offset_event(event_device_res
);
528 switch (offset_event
.GetType()) {
529 case PP_INPUTEVENT_TYPE_MOUSEDOWN
:
530 case PP_INPUTEVENT_TYPE_MOUSEUP
:
531 case PP_INPUTEVENT_TYPE_MOUSEMOVE
:
532 case PP_INPUTEVENT_TYPE_MOUSEENTER
:
533 case PP_INPUTEVENT_TYPE_MOUSELEAVE
: {
534 pp::MouseInputEvent
mouse_event(event_device_res
);
535 pp::MouseInputEvent
mouse_event_dip(event
);
536 pp::Point point
= mouse_event
.GetPosition();
537 point
.set_x(point
.x() - available_area_
.x());
538 offset_event
= pp::MouseInputEvent(
541 event
.GetTimeStamp(),
542 event
.GetModifiers(),
543 mouse_event
.GetButton(),
545 mouse_event
.GetClickCount(),
546 mouse_event
.GetMovement());
552 if (engine_
->HandleEvent(offset_event
))
555 // Middle click is used for scrolling and is handled by the container page.
556 pp::MouseInputEvent
mouse_event(event_device_res
);
557 if (!mouse_event
.is_null() &&
558 mouse_event
.GetButton() == PP_INPUTEVENT_MOUSEBUTTON_MIDDLE
) {
562 // Return true for unhandled clicks so the plugin takes focus.
563 return (event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN
);
566 void OutOfProcessInstance::DidChangeView(const pp::View
& view
) {
567 pp::Rect
view_rect(view
.GetRect());
568 float old_device_scale
= device_scale_
;
569 float device_scale
= view
.GetDeviceScale();
570 pp::Size
view_device_size(view_rect
.width() * device_scale
,
571 view_rect
.height() * device_scale
);
573 if (view_device_size
!= plugin_size_
|| device_scale
!= device_scale_
) {
574 device_scale_
= device_scale
;
575 plugin_dip_size_
= view_rect
.size();
576 plugin_size_
= view_device_size
;
578 paint_manager_
.SetSize(view_device_size
, device_scale_
);
580 pp::Size new_image_data_size
= PaintManager::GetNewContextSize(
583 if (new_image_data_size
!= image_data_
.size()) {
584 image_data_
= pp::ImageData(this,
585 PP_IMAGEDATAFORMAT_BGRA_PREMUL
,
591 if (image_data_
.is_null()) {
592 DCHECK(plugin_size_
.IsEmpty());
596 OnGeometryChanged(zoom_
, old_device_scale
);
599 if (!stop_scrolling_
) {
600 pp::Point
scroll_offset(view
.GetScrollOffset());
601 // Because view messages come from the DOM, the coordinates of the viewport
602 // are 0-based (i.e. they do not correspond to the viewport's coordinates in
603 // JS), so we need to subtract the toolbar height to convert them into
604 // viewport coordinates.
605 pp::FloatPoint
scroll_offset_float(scroll_offset
.x(),
606 scroll_offset
.y() - top_toolbar_height_
);
607 scroll_offset_float
= BoundScrollOffsetToDocument(scroll_offset_float
);
608 engine_
->ScrolledToXPosition(scroll_offset_float
.x() * device_scale_
);
609 engine_
->ScrolledToYPosition(scroll_offset_float
.y() * device_scale_
);
613 void OutOfProcessInstance::GetPrintPresetOptionsFromDocument(
614 PP_PdfPrintPresetOptions_Dev
* options
) {
615 options
->is_scaling_disabled
= PP_FromBool(IsPrintScalingDisabled());
617 static_cast<PP_PrivateDuplexMode_Dev
>(engine_
->GetDuplexType());
618 options
->copies
= engine_
->GetCopiesToPrint();
619 pp::Size uniform_page_size
;
620 options
->is_page_size_uniform
=
621 PP_FromBool(engine_
->GetPageSizeAndUniformity(&uniform_page_size
));
622 options
->uniform_page_size
= uniform_page_size
;
625 pp::Var
OutOfProcessInstance::GetLinkAtPosition(
626 const pp::Point
& point
) {
627 pp::Point
offset_point(point
);
628 ScalePoint(device_scale_
, &offset_point
);
629 offset_point
.set_x(offset_point
.x() - available_area_
.x());
630 return engine_
->GetLinkAtPosition(offset_point
);
633 uint32_t OutOfProcessInstance::QuerySupportedPrintOutputFormats() {
634 return engine_
->QuerySupportedPrintOutputFormats();
637 int32_t OutOfProcessInstance::PrintBegin(
638 const PP_PrintSettings_Dev
& print_settings
) {
639 // For us num_pages is always equal to the number of pages in the PDF
640 // document irrespective of the printable area.
641 int32_t ret
= engine_
->GetNumberOfPages();
645 uint32_t supported_formats
= engine_
->QuerySupportedPrintOutputFormats();
646 if ((print_settings
.format
& supported_formats
) == 0)
649 print_settings_
.is_printing
= true;
650 print_settings_
.pepper_print_settings
= print_settings
;
651 engine_
->PrintBegin();
655 pp::Resource
OutOfProcessInstance::PrintPages(
656 const PP_PrintPageNumberRange_Dev
* page_ranges
,
657 uint32_t page_range_count
) {
658 if (!print_settings_
.is_printing
)
659 return pp::Resource();
661 print_settings_
.print_pages_called_
= true;
662 return engine_
->PrintPages(page_ranges
, page_range_count
,
663 print_settings_
.pepper_print_settings
);
666 void OutOfProcessInstance::PrintEnd() {
667 if (print_settings_
.print_pages_called_
)
668 UserMetricsRecordAction("PDF.PrintPage");
669 print_settings_
.Clear();
673 bool OutOfProcessInstance::IsPrintScalingDisabled() {
674 return !engine_
->GetPrintScaling();
677 bool OutOfProcessInstance::StartFind(const std::string
& text
,
678 bool case_sensitive
) {
679 engine_
->StartFind(text
.c_str(), case_sensitive
);
683 void OutOfProcessInstance::SelectFindResult(bool forward
) {
684 engine_
->SelectFindResult(forward
);
687 void OutOfProcessInstance::StopFind() {
690 SetTickmarks(tickmarks_
);
693 void OutOfProcessInstance::OnPaint(
694 const std::vector
<pp::Rect
>& paint_rects
,
695 std::vector
<PaintManager::ReadyRect
>* ready
,
696 std::vector
<pp::Rect
>* pending
) {
697 if (image_data_
.is_null()) {
698 DCHECK(plugin_size_
.IsEmpty());
702 first_paint_
= false;
703 pp::Rect rect
= pp::Rect(pp::Point(), image_data_
.size());
704 FillRect(rect
, background_color_
);
705 ready
->push_back(PaintManager::ReadyRect(rect
, image_data_
, true));
708 if (!received_viewport_message_
)
713 for (size_t i
= 0; i
< paint_rects
.size(); i
++) {
714 // Intersect with plugin area since there could be pending invalidates from
715 // when the plugin area was larger.
717 paint_rects
[i
].Intersect(pp::Rect(pp::Point(), plugin_size_
));
721 pp::Rect pdf_rect
= available_area_
.Intersect(rect
);
722 if (!pdf_rect
.IsEmpty()) {
723 pdf_rect
.Offset(available_area_
.x() * -1, 0);
725 std::vector
<pp::Rect
> pdf_ready
;
726 std::vector
<pp::Rect
> pdf_pending
;
727 engine_
->Paint(pdf_rect
, &image_data_
, &pdf_ready
, &pdf_pending
);
728 for (size_t j
= 0; j
< pdf_ready
.size(); ++j
) {
729 pdf_ready
[j
].Offset(available_area_
.point());
731 PaintManager::ReadyRect(pdf_ready
[j
], image_data_
, false));
733 for (size_t j
= 0; j
< pdf_pending
.size(); ++j
) {
734 pdf_pending
[j
].Offset(available_area_
.point());
735 pending
->push_back(pdf_pending
[j
]);
739 // Ensure the region above the first page (if any) is filled;
740 int32_t first_page_ypos
= engine_
->GetNumberOfPages() == 0 ?
741 0 : engine_
->GetPageScreenRect(0).y();
742 if (rect
.y() < first_page_ypos
) {
743 pp::Rect region
= rect
.Intersect(pp::Rect(
744 pp::Point(), pp::Size(plugin_size_
.width(), first_page_ypos
)));
745 ready
->push_back(PaintManager::ReadyRect(region
, image_data_
, false));
746 FillRect(region
, background_color_
);
749 for (size_t j
= 0; j
< background_parts_
.size(); ++j
) {
750 pp::Rect intersection
= background_parts_
[j
].location
.Intersect(rect
);
751 if (!intersection
.IsEmpty()) {
752 FillRect(intersection
, background_parts_
[j
].color
);
754 PaintManager::ReadyRect(intersection
, image_data_
, false));
759 engine_
->PostPaint();
762 void OutOfProcessInstance::DidOpen(int32_t result
) {
763 if (result
== PP_OK
) {
764 if (!engine_
->HandleDocumentLoad(embed_loader_
)) {
765 document_load_state_
= LOAD_STATE_LOADING
;
766 DocumentLoadFailed();
768 } else if (result
!= PP_ERROR_ABORTED
) { // Can happen in tests.
770 DocumentLoadFailed();
773 // If it's a progressive load, cancel the stream URL request so that requests
774 // can be made on the original URL.
775 // TODO(raymes): Make this clearer once the in-process plugin is deleted.
776 if (engine_
->IsProgressiveLoad()) {
777 pp::VarDictionary message
;
778 message
.Set(kType
, kJSCancelStreamUrlType
);
779 PostMessage(message
);
783 void OutOfProcessInstance::DidOpenPreview(int32_t result
) {
784 if (result
== PP_OK
) {
785 preview_client_
.reset(new PreviewModeClient(this));
786 preview_engine_
.reset(PDFEngine::Create(preview_client_
.get()));
787 preview_engine_
->HandleDocumentLoad(embed_preview_loader_
);
793 void OutOfProcessInstance::OnClientTimerFired(int32_t id
) {
794 engine_
->OnCallback(id
);
797 void OutOfProcessInstance::CalculateBackgroundParts() {
798 background_parts_
.clear();
799 int left_width
= available_area_
.x();
800 int right_start
= available_area_
.right();
801 int right_width
= abs(plugin_size_
.width() - available_area_
.right());
802 int bottom
= std::min(available_area_
.bottom(), plugin_size_
.height());
804 // Add the left, right, and bottom rectangles. Note: we assume only
805 // horizontal centering.
806 BackgroundPart part
= {
807 pp::Rect(0, 0, left_width
, bottom
),
810 if (!part
.location
.IsEmpty())
811 background_parts_
.push_back(part
);
812 part
.location
= pp::Rect(right_start
, 0, right_width
, bottom
);
813 if (!part
.location
.IsEmpty())
814 background_parts_
.push_back(part
);
815 part
.location
= pp::Rect(
816 0, bottom
, plugin_size_
.width(), plugin_size_
.height() - bottom
);
817 if (!part
.location
.IsEmpty())
818 background_parts_
.push_back(part
);
821 int OutOfProcessInstance::GetDocumentPixelWidth() const {
822 return static_cast<int>(ceil(document_size_
.width() * zoom_
* device_scale_
));
825 int OutOfProcessInstance::GetDocumentPixelHeight() const {
826 return static_cast<int>(
827 ceil(document_size_
.height() * zoom_
* device_scale_
));
830 void OutOfProcessInstance::FillRect(const pp::Rect
& rect
, uint32 color
) {
831 DCHECK(!image_data_
.is_null() || rect
.IsEmpty());
832 uint32
* buffer_start
= static_cast<uint32
*>(image_data_
.data());
833 int stride
= image_data_
.stride();
834 uint32
* ptr
= buffer_start
+ rect
.y() * stride
/ 4 + rect
.x();
835 int height
= rect
.height();
836 int width
= rect
.width();
837 for (int y
= 0; y
< height
; ++y
) {
838 for (int x
= 0; x
< width
; ++x
)
844 void OutOfProcessInstance::DocumentSizeUpdated(const pp::Size
& size
) {
845 document_size_
= size
;
847 pp::VarDictionary dimensions
;
848 dimensions
.Set(kType
, kJSDocumentDimensionsType
);
849 dimensions
.Set(kJSDocumentWidth
, pp::Var(document_size_
.width()));
850 dimensions
.Set(kJSDocumentHeight
, pp::Var(document_size_
.height()));
851 pp::VarArray page_dimensions_array
;
852 int num_pages
= engine_
->GetNumberOfPages();
853 for (int i
= 0; i
< num_pages
; ++i
) {
854 pp::Rect page_rect
= engine_
->GetPageRect(i
);
855 pp::VarDictionary page_dimensions
;
856 page_dimensions
.Set(kJSPageX
, pp::Var(page_rect
.x()));
857 page_dimensions
.Set(kJSPageY
, pp::Var(page_rect
.y()));
858 page_dimensions
.Set(kJSPageWidth
, pp::Var(page_rect
.width()));
859 page_dimensions
.Set(kJSPageHeight
, pp::Var(page_rect
.height()));
860 page_dimensions_array
.Set(i
, page_dimensions
);
862 dimensions
.Set(kJSPageDimensions
, page_dimensions_array
);
863 PostMessage(dimensions
);
865 OnGeometryChanged(zoom_
, device_scale_
);
868 void OutOfProcessInstance::Invalidate(const pp::Rect
& rect
) {
869 pp::Rect
offset_rect(rect
);
870 offset_rect
.Offset(available_area_
.point());
871 paint_manager_
.InvalidateRect(offset_rect
);
874 void OutOfProcessInstance::Scroll(const pp::Point
& point
) {
875 if (!image_data_
.is_null())
876 paint_manager_
.ScrollRect(available_area_
, point
);
879 void OutOfProcessInstance::ScrollToX(int x
) {
880 pp::VarDictionary position
;
881 position
.Set(kType
, kJSSetScrollPositionType
);
882 position
.Set(kJSPositionX
, pp::Var(x
/ device_scale_
));
883 PostMessage(position
);
886 void OutOfProcessInstance::ScrollToY(int y
) {
887 pp::VarDictionary position
;
888 position
.Set(kType
, kJSSetScrollPositionType
);
889 position
.Set(kJSPositionY
, pp::Var(y
/ device_scale_
));
890 PostMessage(position
);
893 void OutOfProcessInstance::ScrollToPage(int page
) {
894 if (engine_
->GetNumberOfPages() == 0)
897 pp::VarDictionary message
;
898 message
.Set(kType
, kJSGoToPageType
);
899 message
.Set(kJSPageNumber
, pp::Var(page
));
900 PostMessage(message
);
903 void OutOfProcessInstance::NavigateTo(const std::string
& url
,
904 bool open_in_new_tab
) {
905 pp::VarDictionary message
;
906 message
.Set(kType
, kJSNavigateType
);
907 message
.Set(kJSNavigateUrl
, url
);
908 message
.Set(kJSNavigateNewTab
, open_in_new_tab
);
909 PostMessage(message
);
912 void OutOfProcessInstance::UpdateCursor(PP_CursorType_Dev cursor
) {
913 if (cursor
== cursor_
)
917 const PPB_CursorControl_Dev
* cursor_interface
=
918 reinterpret_cast<const PPB_CursorControl_Dev
*>(
919 pp::Module::Get()->GetBrowserInterface(PPB_CURSOR_CONTROL_DEV_INTERFACE
));
920 if (!cursor_interface
) {
925 cursor_interface
->SetCursor(
926 pp_instance(), cursor_
, pp::ImageData().pp_resource(), nullptr);
929 void OutOfProcessInstance::UpdateTickMarks(
930 const std::vector
<pp::Rect
>& tickmarks
) {
931 float inverse_scale
= 1.0f
/ device_scale_
;
932 std::vector
<pp::Rect
> scaled_tickmarks
= tickmarks
;
933 for (size_t i
= 0; i
< scaled_tickmarks
.size(); i
++)
934 ScaleRect(inverse_scale
, &scaled_tickmarks
[i
]);
935 tickmarks_
= scaled_tickmarks
;
938 void OutOfProcessInstance::NotifyNumberOfFindResultsChanged(int total
,
940 // We don't want to spam the renderer with too many updates to the number of
941 // find results. Don't send an update if we sent one too recently. If it's the
942 // final update, we always send it though.
944 NumberOfFindResultsChanged(total
, final_result
);
945 SetTickmarks(tickmarks_
);
949 if (recently_sent_find_update_
)
952 NumberOfFindResultsChanged(total
, final_result
);
953 SetTickmarks(tickmarks_
);
954 recently_sent_find_update_
= true;
955 pp::CompletionCallback callback
=
956 timer_factory_
.NewCallback(
957 &OutOfProcessInstance::ResetRecentlySentFindUpdate
);
958 pp::Module::Get()->core()->CallOnMainThread(kFindResultCooldownMs
,
962 void OutOfProcessInstance::NotifySelectedFindResultChanged(
963 int current_find_index
) {
964 DCHECK_GE(current_find_index
, 0);
965 SelectedFindResultChanged(current_find_index
);
968 void OutOfProcessInstance::GetDocumentPassword(
969 pp::CompletionCallbackWithOutput
<pp::Var
> callback
) {
970 if (password_callback_
) {
975 password_callback_
.reset(
976 new pp::CompletionCallbackWithOutput
<pp::Var
>(callback
));
977 pp::VarDictionary message
;
978 message
.Set(pp::Var(kType
), pp::Var(kJSGetPasswordType
));
979 PostMessage(message
);
982 void OutOfProcessInstance::Alert(const std::string
& message
) {
983 ModalDialog(this, "alert", message
, std::string());
986 bool OutOfProcessInstance::Confirm(const std::string
& message
) {
987 pp::Var result
= ModalDialog(this, "confirm", message
, std::string());
988 return result
.is_bool() ? result
.AsBool() : false;
991 std::string
OutOfProcessInstance::Prompt(const std::string
& question
,
992 const std::string
& default_answer
) {
993 pp::Var result
= ModalDialog(this, "prompt", question
, default_answer
);
994 return result
.is_string() ? result
.AsString() : std::string();
997 std::string
OutOfProcessInstance::GetURL() {
1001 void OutOfProcessInstance::Email(const std::string
& to
,
1002 const std::string
& cc
,
1003 const std::string
& bcc
,
1004 const std::string
& subject
,
1005 const std::string
& body
) {
1006 pp::VarDictionary message
;
1007 message
.Set(pp::Var(kType
), pp::Var(kJSEmailType
));
1008 message
.Set(pp::Var(kJSEmailTo
),
1009 pp::Var(net::EscapeUrlEncodedData(to
, false)));
1010 message
.Set(pp::Var(kJSEmailCc
),
1011 pp::Var(net::EscapeUrlEncodedData(cc
, false)));
1012 message
.Set(pp::Var(kJSEmailBcc
),
1013 pp::Var(net::EscapeUrlEncodedData(bcc
, false)));
1014 message
.Set(pp::Var(kJSEmailSubject
),
1015 pp::Var(net::EscapeUrlEncodedData(subject
, false)));
1016 message
.Set(pp::Var(kJSEmailBody
),
1017 pp::Var(net::EscapeUrlEncodedData(body
, false)));
1018 PostMessage(message
);
1021 void OutOfProcessInstance::Print() {
1022 if (!engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
) &&
1023 !engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY
)) {
1027 pp::CompletionCallback callback
=
1028 print_callback_factory_
.NewCallback(&OutOfProcessInstance::OnPrint
);
1029 pp::Module::Get()->core()->CallOnMainThread(0, callback
);
1032 void OutOfProcessInstance::OnPrint(int32_t) {
1033 pp::PDF::Print(this);
1036 void OutOfProcessInstance::SubmitForm(const std::string
& url
,
1039 pp::URLRequestInfo
request(this);
1040 request
.SetURL(url
);
1041 request
.SetMethod("POST");
1042 request
.AppendDataToBody(reinterpret_cast<const char*>(data
), length
);
1044 pp::CompletionCallback callback
=
1045 form_factory_
.NewCallback(&OutOfProcessInstance::FormDidOpen
);
1046 form_loader_
= CreateURLLoaderInternal();
1047 int rv
= form_loader_
.Open(request
, callback
);
1048 if (rv
!= PP_OK_COMPLETIONPENDING
)
1052 void OutOfProcessInstance::FormDidOpen(int32_t result
) {
1053 // TODO: inform the user of success/failure.
1054 if (result
!= PP_OK
) {
1059 std::string
OutOfProcessInstance::ShowFileSelectionDialog() {
1060 // Seems like very low priority to implement, since the pdf has no way to get
1061 // the file data anyways. Javascript doesn't let you do this synchronously.
1063 return std::string();
1066 pp::URLLoader
OutOfProcessInstance::CreateURLLoader() {
1068 if (!did_call_start_loading_
) {
1069 did_call_start_loading_
= true;
1070 pp::PDF::DidStartLoading(this);
1073 // Disable save and print until the document is fully loaded, since they
1074 // would generate an incomplete document. Need to do this each time we
1075 // call DidStartLoading since that resets the content restrictions.
1076 pp::PDF::SetContentRestriction(this, CONTENT_RESTRICTION_SAVE
|
1077 CONTENT_RESTRICTION_PRINT
);
1080 return CreateURLLoaderInternal();
1083 void OutOfProcessInstance::ScheduleCallback(int id
, int delay_in_ms
) {
1084 pp::CompletionCallback callback
=
1085 timer_factory_
.NewCallback(&OutOfProcessInstance::OnClientTimerFired
);
1086 pp::Module::Get()->core()->CallOnMainThread(delay_in_ms
, callback
, id
);
1089 void OutOfProcessInstance::SearchString(const base::char16
* string
,
1090 const base::char16
* term
,
1091 bool case_sensitive
,
1092 std::vector
<SearchStringResult
>* results
) {
1093 PP_PrivateFindResult
* pp_results
;
1095 pp::PDF::SearchString(
1097 reinterpret_cast<const unsigned short*>(string
),
1098 reinterpret_cast<const unsigned short*>(term
),
1103 results
->resize(count
);
1104 for (int i
= 0; i
< count
; ++i
) {
1105 (*results
)[i
].start_index
= pp_results
[i
].start_index
;
1106 (*results
)[i
].length
= pp_results
[i
].length
;
1109 pp::Memory_Dev memory
;
1110 memory
.MemFree(pp_results
);
1113 void OutOfProcessInstance::DocumentPaintOccurred() {
1116 void OutOfProcessInstance::DocumentLoadComplete(int page_count
) {
1117 // Clear focus state for OSK.
1118 FormTextFieldFocusChange(false);
1120 DCHECK(document_load_state_
== LOAD_STATE_LOADING
);
1121 document_load_state_
= LOAD_STATE_COMPLETE
;
1122 UserMetricsRecordAction("PDF.LoadSuccess");
1124 // Note: If we are in print preview mode the scroll location is retained
1125 // across document loads so we don't want to scroll again and override it.
1126 if (IsPrintPreview()) {
1127 AppendBlankPrintPreviewPages();
1128 OnGeometryChanged(0, 0);
1131 pp::VarDictionary metadata_message
;
1132 metadata_message
.Set(pp::Var(kType
), pp::Var(kJSMetadataType
));
1133 std::string title
= engine_
->GetMetadata("Title");
1135 metadata_message
.Set(pp::Var(kJSTitle
), pp::Var(title
));
1137 metadata_message
.Set(pp::Var(kJSBookmarks
), engine_
->GetBookmarks());
1138 PostMessage(metadata_message
);
1140 pp::VarDictionary progress_message
;
1141 progress_message
.Set(pp::Var(kType
), pp::Var(kJSLoadProgressType
));
1142 progress_message
.Set(pp::Var(kJSProgressPercentage
), pp::Var(100));
1143 PostMessage(progress_message
);
1148 if (did_call_start_loading_
) {
1149 pp::PDF::DidStopLoading(this);
1150 did_call_start_loading_
= false;
1153 int content_restrictions
=
1154 CONTENT_RESTRICTION_CUT
| CONTENT_RESTRICTION_PASTE
;
1155 if (!engine_
->HasPermission(PDFEngine::PERMISSION_COPY
))
1156 content_restrictions
|= CONTENT_RESTRICTION_COPY
;
1158 if (!engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
) &&
1159 !engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY
)) {
1160 content_restrictions
|= CONTENT_RESTRICTION_PRINT
;
1163 pp::PDF::SetContentRestriction(this, content_restrictions
);
1165 uma_
.HistogramCustomCounts("PDF.PageCount", page_count
, 1, 1000000, 50);
1168 void OutOfProcessInstance::RotateClockwise() {
1169 engine_
->RotateClockwise();
1172 void OutOfProcessInstance::RotateCounterclockwise() {
1173 engine_
->RotateCounterclockwise();
1176 void OutOfProcessInstance::PreviewDocumentLoadComplete() {
1177 if (preview_document_load_state_
!= LOAD_STATE_LOADING
||
1178 preview_pages_info_
.empty()) {
1182 preview_document_load_state_
= LOAD_STATE_COMPLETE
;
1184 int dest_page_index
= preview_pages_info_
.front().second
;
1185 int src_page_index
=
1186 ExtractPrintPreviewPageIndex(preview_pages_info_
.front().first
);
1187 if (src_page_index
> 0 && dest_page_index
> -1 && preview_engine_
.get())
1188 engine_
->AppendPage(preview_engine_
.get(), dest_page_index
);
1190 preview_pages_info_
.pop();
1191 // |print_preview_page_count_| is not updated yet. Do not load any
1192 // other preview pages till we get this information.
1193 if (print_preview_page_count_
== 0)
1196 if (!preview_pages_info_
.empty())
1197 LoadAvailablePreviewPage();
1200 void OutOfProcessInstance::DocumentLoadFailed() {
1201 DCHECK(document_load_state_
== LOAD_STATE_LOADING
);
1202 UserMetricsRecordAction("PDF.LoadFailure");
1204 if (did_call_start_loading_
) {
1205 pp::PDF::DidStopLoading(this);
1206 did_call_start_loading_
= false;
1209 document_load_state_
= LOAD_STATE_FAILED
;
1210 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
1212 // Send a progress value of -1 to indicate a failure.
1213 pp::VarDictionary message
;
1214 message
.Set(pp::Var(kType
), pp::Var(kJSLoadProgressType
));
1215 message
.Set(pp::Var(kJSProgressPercentage
), pp::Var(-1));
1216 PostMessage(message
);
1219 void OutOfProcessInstance::PreviewDocumentLoadFailed() {
1220 UserMetricsRecordAction("PDF.PreviewDocumentLoadFailure");
1221 if (preview_document_load_state_
!= LOAD_STATE_LOADING
||
1222 preview_pages_info_
.empty()) {
1226 preview_document_load_state_
= LOAD_STATE_FAILED
;
1227 preview_pages_info_
.pop();
1229 if (!preview_pages_info_
.empty())
1230 LoadAvailablePreviewPage();
1233 pp::Instance
* OutOfProcessInstance::GetPluginInstance() {
1237 void OutOfProcessInstance::DocumentHasUnsupportedFeature(
1238 const std::string
& feature
) {
1239 std::string
metric("PDF_Unsupported_");
1241 if (!unsupported_features_reported_
.count(metric
)) {
1242 unsupported_features_reported_
.insert(metric
);
1243 UserMetricsRecordAction(metric
);
1246 // Since we use an info bar, only do this for full frame plugins..
1250 if (told_browser_about_unsupported_feature_
)
1252 told_browser_about_unsupported_feature_
= true;
1254 pp::PDF::HasUnsupportedFeature(this);
1257 void OutOfProcessInstance::DocumentLoadProgress(uint32 available
,
1259 double progress
= 0.0;
1260 if (doc_size
== 0) {
1261 // Document size is unknown. Use heuristics.
1262 // We'll make progress logarithmic from 0 to 100M.
1263 static const double kFactor
= log(100000000.0) / 100.0;
1264 if (available
> 0) {
1265 progress
= log(static_cast<double>(available
)) / kFactor
;
1266 if (progress
> 100.0)
1270 progress
= 100.0 * static_cast<double>(available
) / doc_size
;
1273 // We send 100% load progress in DocumentLoadComplete.
1274 if (progress
>= 100)
1277 // Avoid sending too many progress messages over PostMessage.
1278 if (progress
> last_progress_sent_
+ 1) {
1279 last_progress_sent_
= progress
;
1280 pp::VarDictionary message
;
1281 message
.Set(pp::Var(kType
), pp::Var(kJSLoadProgressType
));
1282 message
.Set(pp::Var(kJSProgressPercentage
), pp::Var(progress
));
1283 PostMessage(message
);
1287 void OutOfProcessInstance::FormTextFieldFocusChange(bool in_focus
) {
1288 if (!text_input_
.get())
1291 text_input_
->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_TEXT
);
1293 text_input_
->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_NONE
);
1296 void OutOfProcessInstance::ResetRecentlySentFindUpdate(int32_t /* unused */) {
1297 recently_sent_find_update_
= false;
1300 void OutOfProcessInstance::OnGeometryChanged(double old_zoom
,
1301 float old_device_scale
) {
1302 if (zoom_
!= old_zoom
|| device_scale_
!= old_device_scale
)
1303 engine_
->ZoomUpdated(zoom_
* device_scale_
);
1305 available_area_
= pp::Rect(plugin_size_
);
1306 int doc_width
= GetDocumentPixelWidth();
1307 if (doc_width
< available_area_
.width()) {
1308 available_area_
.Offset((available_area_
.width() - doc_width
) / 2, 0);
1309 available_area_
.set_width(doc_width
);
1311 int bottom_of_document
=
1312 GetDocumentPixelHeight() + (top_toolbar_height_
* device_scale_
);
1313 if (bottom_of_document
< available_area_
.height())
1314 available_area_
.set_height(bottom_of_document
);
1316 CalculateBackgroundParts();
1317 engine_
->PageOffsetUpdated(available_area_
.point());
1318 engine_
->PluginSizeUpdated(available_area_
.size());
1320 if (!document_size_
.GetArea())
1322 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
1325 void OutOfProcessInstance::LoadUrl(const std::string
& url
) {
1326 LoadUrlInternal(url
, &embed_loader_
, &OutOfProcessInstance::DidOpen
);
1329 void OutOfProcessInstance::LoadPreviewUrl(const std::string
& url
) {
1330 LoadUrlInternal(url
, &embed_preview_loader_
,
1331 &OutOfProcessInstance::DidOpenPreview
);
1334 void OutOfProcessInstance::LoadUrlInternal(
1335 const std::string
& url
,
1336 pp::URLLoader
* loader
,
1337 void (OutOfProcessInstance::* method
)(int32_t)) {
1338 pp::URLRequestInfo
request(this);
1339 request
.SetURL(url
);
1340 request
.SetMethod("GET");
1342 *loader
= CreateURLLoaderInternal();
1343 pp::CompletionCallback callback
= loader_factory_
.NewCallback(method
);
1344 int rv
= loader
->Open(request
, callback
);
1345 if (rv
!= PP_OK_COMPLETIONPENDING
)
1349 pp::URLLoader
OutOfProcessInstance::CreateURLLoaderInternal() {
1350 pp::URLLoader
loader(this);
1352 const PPB_URLLoaderTrusted
* trusted_interface
=
1353 reinterpret_cast<const PPB_URLLoaderTrusted
*>(
1354 pp::Module::Get()->GetBrowserInterface(
1355 PPB_URLLOADERTRUSTED_INTERFACE
));
1356 if (trusted_interface
)
1357 trusted_interface
->GrantUniversalAccess(loader
.pp_resource());
1361 void OutOfProcessInstance::SetZoom(double scale
) {
1362 double old_zoom
= zoom_
;
1364 OnGeometryChanged(old_zoom
, device_scale_
);
1367 std::string
OutOfProcessInstance::GetLocalizedString(PP_ResourceString id
) {
1368 pp::Var
rv(pp::PDF::GetLocalizedString(this, id
));
1369 if (!rv
.is_string())
1370 return std::string();
1372 return rv
.AsString();
1375 void OutOfProcessInstance::AppendBlankPrintPreviewPages() {
1376 if (print_preview_page_count_
== 0)
1378 engine_
->AppendBlankPages(print_preview_page_count_
);
1379 if (!preview_pages_info_
.empty())
1380 LoadAvailablePreviewPage();
1383 bool OutOfProcessInstance::IsPrintPreview() {
1384 return IsPrintPreviewUrl(url_
);
1387 uint32
OutOfProcessInstance::GetBackgroundColor() {
1388 return background_color_
;
1391 void OutOfProcessInstance::IsSelectingChanged(bool is_selecting
) {
1392 pp::VarDictionary message
;
1393 message
.Set(kType
, kJSSetIsSelectingType
);
1394 message
.Set(kJSIsSelecting
, pp::Var(is_selecting
));
1395 PostMessage(message
);
1398 void OutOfProcessInstance::ProcessPreviewPageInfo(const std::string
& url
,
1399 int dst_page_index
) {
1400 if (!IsPrintPreview())
1403 int src_page_index
= ExtractPrintPreviewPageIndex(url
);
1404 if (src_page_index
< 1)
1407 preview_pages_info_
.push(std::make_pair(url
, dst_page_index
));
1408 LoadAvailablePreviewPage();
1411 void OutOfProcessInstance::LoadAvailablePreviewPage() {
1412 if (preview_pages_info_
.empty() ||
1413 document_load_state_
!= LOAD_STATE_COMPLETE
) {
1417 std::string url
= preview_pages_info_
.front().first
;
1418 int dst_page_index
= preview_pages_info_
.front().second
;
1419 int src_page_index
= ExtractPrintPreviewPageIndex(url
);
1420 if (src_page_index
< 1 ||
1421 dst_page_index
>= print_preview_page_count_
||
1422 preview_document_load_state_
== LOAD_STATE_LOADING
) {
1426 preview_document_load_state_
= LOAD_STATE_LOADING
;
1427 LoadPreviewUrl(url
);
1430 void OutOfProcessInstance::UserMetricsRecordAction(
1431 const std::string
& action
) {
1432 // TODO(raymes): Move this function to PPB_UMA_Private.
1433 pp::PDF::UserMetricsRecordAction(this, pp::Var(action
));
1436 pp::FloatPoint
OutOfProcessInstance::BoundScrollOffsetToDocument(
1437 const pp::FloatPoint
& scroll_offset
) {
1438 float max_x
= document_size_
.width() * zoom_
- plugin_dip_size_
.width();
1439 float x
= std::max(std::min(scroll_offset
.x(), max_x
), 0.0f
);
1440 float min_y
= -top_toolbar_height_
;
1441 float max_y
= document_size_
.height() * zoom_
- plugin_dip_size_
.height();
1442 float y
= std::max(std::min(scroll_offset
.y(), max_y
), min_y
);
1443 return pp::FloatPoint(x
, y
);
1446 } // namespace chrome_pdf