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_engine_
.reset(PDFEngine::Create(new PreviewModeClient(this)));
786 preview_engine_
->HandleDocumentLoad(embed_preview_loader_
);
792 void OutOfProcessInstance::OnClientTimerFired(int32_t id
) {
793 engine_
->OnCallback(id
);
796 void OutOfProcessInstance::CalculateBackgroundParts() {
797 background_parts_
.clear();
798 int left_width
= available_area_
.x();
799 int right_start
= available_area_
.right();
800 int right_width
= abs(plugin_size_
.width() - available_area_
.right());
801 int bottom
= std::min(available_area_
.bottom(), plugin_size_
.height());
803 // Add the left, right, and bottom rectangles. Note: we assume only
804 // horizontal centering.
805 BackgroundPart part
= {
806 pp::Rect(0, 0, left_width
, bottom
),
809 if (!part
.location
.IsEmpty())
810 background_parts_
.push_back(part
);
811 part
.location
= pp::Rect(right_start
, 0, right_width
, bottom
);
812 if (!part
.location
.IsEmpty())
813 background_parts_
.push_back(part
);
814 part
.location
= pp::Rect(
815 0, bottom
, plugin_size_
.width(), plugin_size_
.height() - bottom
);
816 if (!part
.location
.IsEmpty())
817 background_parts_
.push_back(part
);
820 int OutOfProcessInstance::GetDocumentPixelWidth() const {
821 return static_cast<int>(ceil(document_size_
.width() * zoom_
* device_scale_
));
824 int OutOfProcessInstance::GetDocumentPixelHeight() const {
825 return static_cast<int>(
826 ceil(document_size_
.height() * zoom_
* device_scale_
));
829 void OutOfProcessInstance::FillRect(const pp::Rect
& rect
, uint32 color
) {
830 DCHECK(!image_data_
.is_null() || rect
.IsEmpty());
831 uint32
* buffer_start
= static_cast<uint32
*>(image_data_
.data());
832 int stride
= image_data_
.stride();
833 uint32
* ptr
= buffer_start
+ rect
.y() * stride
/ 4 + rect
.x();
834 int height
= rect
.height();
835 int width
= rect
.width();
836 for (int y
= 0; y
< height
; ++y
) {
837 for (int x
= 0; x
< width
; ++x
)
843 void OutOfProcessInstance::DocumentSizeUpdated(const pp::Size
& size
) {
844 document_size_
= size
;
846 pp::VarDictionary dimensions
;
847 dimensions
.Set(kType
, kJSDocumentDimensionsType
);
848 dimensions
.Set(kJSDocumentWidth
, pp::Var(document_size_
.width()));
849 dimensions
.Set(kJSDocumentHeight
, pp::Var(document_size_
.height()));
850 pp::VarArray page_dimensions_array
;
851 int num_pages
= engine_
->GetNumberOfPages();
852 for (int i
= 0; i
< num_pages
; ++i
) {
853 pp::Rect page_rect
= engine_
->GetPageRect(i
);
854 pp::VarDictionary page_dimensions
;
855 page_dimensions
.Set(kJSPageX
, pp::Var(page_rect
.x()));
856 page_dimensions
.Set(kJSPageY
, pp::Var(page_rect
.y()));
857 page_dimensions
.Set(kJSPageWidth
, pp::Var(page_rect
.width()));
858 page_dimensions
.Set(kJSPageHeight
, pp::Var(page_rect
.height()));
859 page_dimensions_array
.Set(i
, page_dimensions
);
861 dimensions
.Set(kJSPageDimensions
, page_dimensions_array
);
862 PostMessage(dimensions
);
864 OnGeometryChanged(zoom_
, device_scale_
);
867 void OutOfProcessInstance::Invalidate(const pp::Rect
& rect
) {
868 pp::Rect
offset_rect(rect
);
869 offset_rect
.Offset(available_area_
.point());
870 paint_manager_
.InvalidateRect(offset_rect
);
873 void OutOfProcessInstance::Scroll(const pp::Point
& point
) {
874 if (!image_data_
.is_null())
875 paint_manager_
.ScrollRect(available_area_
, point
);
878 void OutOfProcessInstance::ScrollToX(int x
) {
879 pp::VarDictionary position
;
880 position
.Set(kType
, kJSSetScrollPositionType
);
881 position
.Set(kJSPositionX
, pp::Var(x
/ device_scale_
));
882 PostMessage(position
);
885 void OutOfProcessInstance::ScrollToY(int y
) {
886 pp::VarDictionary position
;
887 position
.Set(kType
, kJSSetScrollPositionType
);
888 position
.Set(kJSPositionY
, pp::Var(y
/ device_scale_
));
889 PostMessage(position
);
892 void OutOfProcessInstance::ScrollToPage(int page
) {
893 if (engine_
->GetNumberOfPages() == 0)
896 pp::VarDictionary message
;
897 message
.Set(kType
, kJSGoToPageType
);
898 message
.Set(kJSPageNumber
, pp::Var(page
));
899 PostMessage(message
);
902 void OutOfProcessInstance::NavigateTo(const std::string
& url
,
903 bool open_in_new_tab
) {
904 pp::VarDictionary message
;
905 message
.Set(kType
, kJSNavigateType
);
906 message
.Set(kJSNavigateUrl
, url
);
907 message
.Set(kJSNavigateNewTab
, open_in_new_tab
);
908 PostMessage(message
);
911 void OutOfProcessInstance::UpdateCursor(PP_CursorType_Dev cursor
) {
912 if (cursor
== cursor_
)
916 const PPB_CursorControl_Dev
* cursor_interface
=
917 reinterpret_cast<const PPB_CursorControl_Dev
*>(
918 pp::Module::Get()->GetBrowserInterface(PPB_CURSOR_CONTROL_DEV_INTERFACE
));
919 if (!cursor_interface
) {
924 cursor_interface
->SetCursor(
925 pp_instance(), cursor_
, pp::ImageData().pp_resource(), nullptr);
928 void OutOfProcessInstance::UpdateTickMarks(
929 const std::vector
<pp::Rect
>& tickmarks
) {
930 float inverse_scale
= 1.0f
/ device_scale_
;
931 std::vector
<pp::Rect
> scaled_tickmarks
= tickmarks
;
932 for (size_t i
= 0; i
< scaled_tickmarks
.size(); i
++)
933 ScaleRect(inverse_scale
, &scaled_tickmarks
[i
]);
934 tickmarks_
= scaled_tickmarks
;
937 void OutOfProcessInstance::NotifyNumberOfFindResultsChanged(int total
,
939 // We don't want to spam the renderer with too many updates to the number of
940 // find results. Don't send an update if we sent one too recently. If it's the
941 // final update, we always send it though.
943 NumberOfFindResultsChanged(total
, final_result
);
944 SetTickmarks(tickmarks_
);
948 if (recently_sent_find_update_
)
951 NumberOfFindResultsChanged(total
, final_result
);
952 SetTickmarks(tickmarks_
);
953 recently_sent_find_update_
= true;
954 pp::CompletionCallback callback
=
955 timer_factory_
.NewCallback(
956 &OutOfProcessInstance::ResetRecentlySentFindUpdate
);
957 pp::Module::Get()->core()->CallOnMainThread(kFindResultCooldownMs
,
961 void OutOfProcessInstance::NotifySelectedFindResultChanged(
962 int current_find_index
) {
963 DCHECK_GE(current_find_index
, 0);
964 SelectedFindResultChanged(current_find_index
);
967 void OutOfProcessInstance::GetDocumentPassword(
968 pp::CompletionCallbackWithOutput
<pp::Var
> callback
) {
969 if (password_callback_
) {
974 password_callback_
.reset(
975 new pp::CompletionCallbackWithOutput
<pp::Var
>(callback
));
976 pp::VarDictionary message
;
977 message
.Set(pp::Var(kType
), pp::Var(kJSGetPasswordType
));
978 PostMessage(message
);
981 void OutOfProcessInstance::Alert(const std::string
& message
) {
982 ModalDialog(this, "alert", message
, std::string());
985 bool OutOfProcessInstance::Confirm(const std::string
& message
) {
986 pp::Var result
= ModalDialog(this, "confirm", message
, std::string());
987 return result
.is_bool() ? result
.AsBool() : false;
990 std::string
OutOfProcessInstance::Prompt(const std::string
& question
,
991 const std::string
& default_answer
) {
992 pp::Var result
= ModalDialog(this, "prompt", question
, default_answer
);
993 return result
.is_string() ? result
.AsString() : std::string();
996 std::string
OutOfProcessInstance::GetURL() {
1000 void OutOfProcessInstance::Email(const std::string
& to
,
1001 const std::string
& cc
,
1002 const std::string
& bcc
,
1003 const std::string
& subject
,
1004 const std::string
& body
) {
1005 pp::VarDictionary message
;
1006 message
.Set(pp::Var(kType
), pp::Var(kJSEmailType
));
1007 message
.Set(pp::Var(kJSEmailTo
),
1008 pp::Var(net::EscapeUrlEncodedData(to
, false)));
1009 message
.Set(pp::Var(kJSEmailCc
),
1010 pp::Var(net::EscapeUrlEncodedData(cc
, false)));
1011 message
.Set(pp::Var(kJSEmailBcc
),
1012 pp::Var(net::EscapeUrlEncodedData(bcc
, false)));
1013 message
.Set(pp::Var(kJSEmailSubject
),
1014 pp::Var(net::EscapeUrlEncodedData(subject
, false)));
1015 message
.Set(pp::Var(kJSEmailBody
),
1016 pp::Var(net::EscapeUrlEncodedData(body
, false)));
1017 PostMessage(message
);
1020 void OutOfProcessInstance::Print() {
1021 if (!engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
) &&
1022 !engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY
)) {
1026 pp::CompletionCallback callback
=
1027 print_callback_factory_
.NewCallback(&OutOfProcessInstance::OnPrint
);
1028 pp::Module::Get()->core()->CallOnMainThread(0, callback
);
1031 void OutOfProcessInstance::OnPrint(int32_t) {
1032 pp::PDF::Print(this);
1035 void OutOfProcessInstance::SubmitForm(const std::string
& url
,
1038 pp::URLRequestInfo
request(this);
1039 request
.SetURL(url
);
1040 request
.SetMethod("POST");
1041 request
.AppendDataToBody(reinterpret_cast<const char*>(data
), length
);
1043 pp::CompletionCallback callback
=
1044 form_factory_
.NewCallback(&OutOfProcessInstance::FormDidOpen
);
1045 form_loader_
= CreateURLLoaderInternal();
1046 int rv
= form_loader_
.Open(request
, callback
);
1047 if (rv
!= PP_OK_COMPLETIONPENDING
)
1051 void OutOfProcessInstance::FormDidOpen(int32_t result
) {
1052 // TODO: inform the user of success/failure.
1053 if (result
!= PP_OK
) {
1058 std::string
OutOfProcessInstance::ShowFileSelectionDialog() {
1059 // Seems like very low priority to implement, since the pdf has no way to get
1060 // the file data anyways. Javascript doesn't let you do this synchronously.
1062 return std::string();
1065 pp::URLLoader
OutOfProcessInstance::CreateURLLoader() {
1067 if (!did_call_start_loading_
) {
1068 did_call_start_loading_
= true;
1069 pp::PDF::DidStartLoading(this);
1072 // Disable save and print until the document is fully loaded, since they
1073 // would generate an incomplete document. Need to do this each time we
1074 // call DidStartLoading since that resets the content restrictions.
1075 pp::PDF::SetContentRestriction(this, CONTENT_RESTRICTION_SAVE
|
1076 CONTENT_RESTRICTION_PRINT
);
1079 return CreateURLLoaderInternal();
1082 void OutOfProcessInstance::ScheduleCallback(int id
, int delay_in_ms
) {
1083 pp::CompletionCallback callback
=
1084 timer_factory_
.NewCallback(&OutOfProcessInstance::OnClientTimerFired
);
1085 pp::Module::Get()->core()->CallOnMainThread(delay_in_ms
, callback
, id
);
1088 void OutOfProcessInstance::SearchString(const base::char16
* string
,
1089 const base::char16
* term
,
1090 bool case_sensitive
,
1091 std::vector
<SearchStringResult
>* results
) {
1092 PP_PrivateFindResult
* pp_results
;
1094 pp::PDF::SearchString(
1096 reinterpret_cast<const unsigned short*>(string
),
1097 reinterpret_cast<const unsigned short*>(term
),
1102 results
->resize(count
);
1103 for (int i
= 0; i
< count
; ++i
) {
1104 (*results
)[i
].start_index
= pp_results
[i
].start_index
;
1105 (*results
)[i
].length
= pp_results
[i
].length
;
1108 pp::Memory_Dev memory
;
1109 memory
.MemFree(pp_results
);
1112 void OutOfProcessInstance::DocumentPaintOccurred() {
1115 void OutOfProcessInstance::DocumentLoadComplete(int page_count
) {
1116 // Clear focus state for OSK.
1117 FormTextFieldFocusChange(false);
1119 DCHECK(document_load_state_
== LOAD_STATE_LOADING
);
1120 document_load_state_
= LOAD_STATE_COMPLETE
;
1121 UserMetricsRecordAction("PDF.LoadSuccess");
1123 // Note: If we are in print preview mode the scroll location is retained
1124 // across document loads so we don't want to scroll again and override it.
1125 if (IsPrintPreview()) {
1126 AppendBlankPrintPreviewPages();
1127 OnGeometryChanged(0, 0);
1130 pp::VarDictionary metadata_message
;
1131 metadata_message
.Set(pp::Var(kType
), pp::Var(kJSMetadataType
));
1132 std::string title
= engine_
->GetMetadata("Title");
1134 metadata_message
.Set(pp::Var(kJSTitle
), pp::Var(title
));
1136 metadata_message
.Set(pp::Var(kJSBookmarks
), engine_
->GetBookmarks());
1137 PostMessage(metadata_message
);
1139 pp::VarDictionary progress_message
;
1140 progress_message
.Set(pp::Var(kType
), pp::Var(kJSLoadProgressType
));
1141 progress_message
.Set(pp::Var(kJSProgressPercentage
), pp::Var(100));
1142 PostMessage(progress_message
);
1147 if (did_call_start_loading_
) {
1148 pp::PDF::DidStopLoading(this);
1149 did_call_start_loading_
= false;
1152 int content_restrictions
=
1153 CONTENT_RESTRICTION_CUT
| CONTENT_RESTRICTION_PASTE
;
1154 if (!engine_
->HasPermission(PDFEngine::PERMISSION_COPY
))
1155 content_restrictions
|= CONTENT_RESTRICTION_COPY
;
1157 if (!engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
) &&
1158 !engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY
)) {
1159 content_restrictions
|= CONTENT_RESTRICTION_PRINT
;
1162 pp::PDF::SetContentRestriction(this, content_restrictions
);
1164 uma_
.HistogramCustomCounts("PDF.PageCount", page_count
, 1, 1000000, 50);
1167 void OutOfProcessInstance::RotateClockwise() {
1168 engine_
->RotateClockwise();
1171 void OutOfProcessInstance::RotateCounterclockwise() {
1172 engine_
->RotateCounterclockwise();
1175 void OutOfProcessInstance::PreviewDocumentLoadComplete() {
1176 if (preview_document_load_state_
!= LOAD_STATE_LOADING
||
1177 preview_pages_info_
.empty()) {
1181 preview_document_load_state_
= LOAD_STATE_COMPLETE
;
1183 int dest_page_index
= preview_pages_info_
.front().second
;
1184 int src_page_index
=
1185 ExtractPrintPreviewPageIndex(preview_pages_info_
.front().first
);
1186 if (src_page_index
> 0 && dest_page_index
> -1 && preview_engine_
.get())
1187 engine_
->AppendPage(preview_engine_
.get(), dest_page_index
);
1189 preview_pages_info_
.pop();
1190 // |print_preview_page_count_| is not updated yet. Do not load any
1191 // other preview pages till we get this information.
1192 if (print_preview_page_count_
== 0)
1195 if (!preview_pages_info_
.empty())
1196 LoadAvailablePreviewPage();
1199 void OutOfProcessInstance::DocumentLoadFailed() {
1200 DCHECK(document_load_state_
== LOAD_STATE_LOADING
);
1201 UserMetricsRecordAction("PDF.LoadFailure");
1203 if (did_call_start_loading_
) {
1204 pp::PDF::DidStopLoading(this);
1205 did_call_start_loading_
= false;
1208 document_load_state_
= LOAD_STATE_FAILED
;
1209 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
1211 // Send a progress value of -1 to indicate a failure.
1212 pp::VarDictionary message
;
1213 message
.Set(pp::Var(kType
), pp::Var(kJSLoadProgressType
));
1214 message
.Set(pp::Var(kJSProgressPercentage
), pp::Var(-1));
1215 PostMessage(message
);
1218 void OutOfProcessInstance::PreviewDocumentLoadFailed() {
1219 UserMetricsRecordAction("PDF.PreviewDocumentLoadFailure");
1220 if (preview_document_load_state_
!= LOAD_STATE_LOADING
||
1221 preview_pages_info_
.empty()) {
1225 preview_document_load_state_
= LOAD_STATE_FAILED
;
1226 preview_pages_info_
.pop();
1228 if (!preview_pages_info_
.empty())
1229 LoadAvailablePreviewPage();
1232 pp::Instance
* OutOfProcessInstance::GetPluginInstance() {
1236 void OutOfProcessInstance::DocumentHasUnsupportedFeature(
1237 const std::string
& feature
) {
1238 std::string
metric("PDF_Unsupported_");
1240 if (!unsupported_features_reported_
.count(metric
)) {
1241 unsupported_features_reported_
.insert(metric
);
1242 UserMetricsRecordAction(metric
);
1245 // Since we use an info bar, only do this for full frame plugins..
1249 if (told_browser_about_unsupported_feature_
)
1251 told_browser_about_unsupported_feature_
= true;
1253 pp::PDF::HasUnsupportedFeature(this);
1256 void OutOfProcessInstance::DocumentLoadProgress(uint32 available
,
1258 double progress
= 0.0;
1259 if (doc_size
== 0) {
1260 // Document size is unknown. Use heuristics.
1261 // We'll make progress logarithmic from 0 to 100M.
1262 static const double kFactor
= log(100000000.0) / 100.0;
1263 if (available
> 0) {
1264 progress
= log(static_cast<double>(available
)) / kFactor
;
1265 if (progress
> 100.0)
1269 progress
= 100.0 * static_cast<double>(available
) / doc_size
;
1272 // We send 100% load progress in DocumentLoadComplete.
1273 if (progress
>= 100)
1276 // Avoid sending too many progress messages over PostMessage.
1277 if (progress
> last_progress_sent_
+ 1) {
1278 last_progress_sent_
= progress
;
1279 pp::VarDictionary message
;
1280 message
.Set(pp::Var(kType
), pp::Var(kJSLoadProgressType
));
1281 message
.Set(pp::Var(kJSProgressPercentage
), pp::Var(progress
));
1282 PostMessage(message
);
1286 void OutOfProcessInstance::FormTextFieldFocusChange(bool in_focus
) {
1287 if (!text_input_
.get())
1290 text_input_
->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_TEXT
);
1292 text_input_
->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_NONE
);
1295 void OutOfProcessInstance::ResetRecentlySentFindUpdate(int32_t /* unused */) {
1296 recently_sent_find_update_
= false;
1299 void OutOfProcessInstance::OnGeometryChanged(double old_zoom
,
1300 float old_device_scale
) {
1301 if (zoom_
!= old_zoom
|| device_scale_
!= old_device_scale
)
1302 engine_
->ZoomUpdated(zoom_
* device_scale_
);
1304 available_area_
= pp::Rect(plugin_size_
);
1305 int doc_width
= GetDocumentPixelWidth();
1306 if (doc_width
< available_area_
.width()) {
1307 available_area_
.Offset((available_area_
.width() - doc_width
) / 2, 0);
1308 available_area_
.set_width(doc_width
);
1310 int bottom_of_document
=
1311 GetDocumentPixelHeight() + (top_toolbar_height_
* device_scale_
);
1312 if (bottom_of_document
< available_area_
.height())
1313 available_area_
.set_height(bottom_of_document
);
1315 CalculateBackgroundParts();
1316 engine_
->PageOffsetUpdated(available_area_
.point());
1317 engine_
->PluginSizeUpdated(available_area_
.size());
1319 if (!document_size_
.GetArea())
1321 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
1324 void OutOfProcessInstance::LoadUrl(const std::string
& url
) {
1325 LoadUrlInternal(url
, &embed_loader_
, &OutOfProcessInstance::DidOpen
);
1328 void OutOfProcessInstance::LoadPreviewUrl(const std::string
& url
) {
1329 LoadUrlInternal(url
, &embed_preview_loader_
,
1330 &OutOfProcessInstance::DidOpenPreview
);
1333 void OutOfProcessInstance::LoadUrlInternal(
1334 const std::string
& url
,
1335 pp::URLLoader
* loader
,
1336 void (OutOfProcessInstance::* method
)(int32_t)) {
1337 pp::URLRequestInfo
request(this);
1338 request
.SetURL(url
);
1339 request
.SetMethod("GET");
1341 *loader
= CreateURLLoaderInternal();
1342 pp::CompletionCallback callback
= loader_factory_
.NewCallback(method
);
1343 int rv
= loader
->Open(request
, callback
);
1344 if (rv
!= PP_OK_COMPLETIONPENDING
)
1348 pp::URLLoader
OutOfProcessInstance::CreateURLLoaderInternal() {
1349 pp::URLLoader
loader(this);
1351 const PPB_URLLoaderTrusted
* trusted_interface
=
1352 reinterpret_cast<const PPB_URLLoaderTrusted
*>(
1353 pp::Module::Get()->GetBrowserInterface(
1354 PPB_URLLOADERTRUSTED_INTERFACE
));
1355 if (trusted_interface
)
1356 trusted_interface
->GrantUniversalAccess(loader
.pp_resource());
1360 void OutOfProcessInstance::SetZoom(double scale
) {
1361 double old_zoom
= zoom_
;
1363 OnGeometryChanged(old_zoom
, device_scale_
);
1366 std::string
OutOfProcessInstance::GetLocalizedString(PP_ResourceString id
) {
1367 pp::Var
rv(pp::PDF::GetLocalizedString(this, id
));
1368 if (!rv
.is_string())
1369 return std::string();
1371 return rv
.AsString();
1374 void OutOfProcessInstance::AppendBlankPrintPreviewPages() {
1375 if (print_preview_page_count_
== 0)
1377 engine_
->AppendBlankPages(print_preview_page_count_
);
1378 if (!preview_pages_info_
.empty())
1379 LoadAvailablePreviewPage();
1382 bool OutOfProcessInstance::IsPrintPreview() {
1383 return IsPrintPreviewUrl(url_
);
1386 uint32
OutOfProcessInstance::GetBackgroundColor() {
1387 return background_color_
;
1390 void OutOfProcessInstance::IsSelectingChanged(bool is_selecting
) {
1391 pp::VarDictionary message
;
1392 message
.Set(kType
, kJSSetIsSelectingType
);
1393 message
.Set(kJSIsSelecting
, pp::Var(is_selecting
));
1394 PostMessage(message
);
1397 void OutOfProcessInstance::ProcessPreviewPageInfo(const std::string
& url
,
1398 int dst_page_index
) {
1399 if (!IsPrintPreview())
1402 int src_page_index
= ExtractPrintPreviewPageIndex(url
);
1403 if (src_page_index
< 1)
1406 preview_pages_info_
.push(std::make_pair(url
, dst_page_index
));
1407 LoadAvailablePreviewPage();
1410 void OutOfProcessInstance::LoadAvailablePreviewPage() {
1411 if (preview_pages_info_
.empty() ||
1412 document_load_state_
!= LOAD_STATE_COMPLETE
) {
1416 std::string url
= preview_pages_info_
.front().first
;
1417 int dst_page_index
= preview_pages_info_
.front().second
;
1418 int src_page_index
= ExtractPrintPreviewPageIndex(url
);
1419 if (src_page_index
< 1 ||
1420 dst_page_index
>= print_preview_page_count_
||
1421 preview_document_load_state_
== LOAD_STATE_LOADING
) {
1425 preview_document_load_state_
= LOAD_STATE_LOADING
;
1426 LoadPreviewUrl(url
);
1429 void OutOfProcessInstance::UserMetricsRecordAction(
1430 const std::string
& action
) {
1431 // TODO(raymes): Move this function to PPB_UMA_Private.
1432 pp::PDF::UserMetricsRecordAction(this, pp::Var(action
));
1435 pp::FloatPoint
OutOfProcessInstance::BoundScrollOffsetToDocument(
1436 const pp::FloatPoint
& scroll_offset
) {
1437 float max_x
= document_size_
.width() * zoom_
- plugin_dip_size_
.width();
1438 float x
= std::max(std::min(scroll_offset
.x(), max_x
), 0.0f
);
1439 float min_y
= -top_toolbar_height_
;
1440 float max_y
= document_size_
.height() * zoom_
- plugin_dip_size_
.height();
1441 float y
= std::max(std::min(scroll_offset
.y(), max_y
), min_y
);
1442 return pp::FloatPoint(x
, y
);
1445 } // namespace chrome_pdf