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/strings/utf_string_conversions.h"
20 #include "base/values.h"
21 #include "chrome/common/content_restriction.h"
22 #include "net/base/escape.h"
24 #include "ppapi/c/dev/ppb_cursor_control_dev.h"
25 #include "ppapi/c/pp_errors.h"
26 #include "ppapi/c/pp_rect.h"
27 #include "ppapi/c/private/ppb_instance_private.h"
28 #include "ppapi/c/private/ppp_pdf.h"
29 #include "ppapi/c/trusted/ppb_url_loader_trusted.h"
30 #include "ppapi/cpp/core.h"
31 #include "ppapi/cpp/dev/memory_dev.h"
32 #include "ppapi/cpp/dev/text_input_dev.h"
33 #include "ppapi/cpp/dev/url_util_dev.h"
34 #include "ppapi/cpp/module.h"
35 #include "ppapi/cpp/point.h"
36 #include "ppapi/cpp/private/pdf.h"
37 #include "ppapi/cpp/private/var_private.h"
38 #include "ppapi/cpp/rect.h"
39 #include "ppapi/cpp/resource.h"
40 #include "ppapi/cpp/url_request_info.h"
41 #include "ppapi/cpp/var_array.h"
42 #include "ppapi/cpp/var_dictionary.h"
43 #include "ui/events/keycodes/keyboard_codes.h"
45 namespace chrome_pdf
{
47 const char kChromePrint
[] = "chrome://print/";
48 const char kChromeExtension
[] =
49 "chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai";
51 // Dictionary Value key names for the document accessibility info
52 const char kAccessibleNumberOfPages
[] = "numberOfPages";
53 const char kAccessibleLoaded
[] = "loaded";
54 const char kAccessibleCopyable
[] = "copyable";
56 // PDF background colors.
57 const uint32 kBackgroundColor
= 0xFFCCCCCC;
58 const uint32 kBackgroundColorMaterial
= 0xFF525659;
60 // Constants used in handling postMessage() messages.
61 const char kType
[] = "type";
62 // Viewport message arguments. (Page -> Plugin).
63 const char kJSViewportType
[] = "viewport";
64 const char kJSXOffset
[] = "xOffset";
65 const char kJSYOffset
[] = "yOffset";
66 const char kJSZoom
[] = "zoom";
67 // Stop scrolling message (Page -> Plugin)
68 const char kJSStopScrollingType
[] = "stopScrolling";
69 // Document dimension arguments (Plugin -> Page).
70 const char kJSDocumentDimensionsType
[] = "documentDimensions";
71 const char kJSDocumentWidth
[] = "width";
72 const char kJSDocumentHeight
[] = "height";
73 const char kJSPageDimensions
[] = "pageDimensions";
74 const char kJSPageX
[] = "x";
75 const char kJSPageY
[] = "y";
76 const char kJSPageWidth
[] = "width";
77 const char kJSPageHeight
[] = "height";
78 // Document load progress arguments (Plugin -> Page)
79 const char kJSLoadProgressType
[] = "loadProgress";
80 const char kJSProgressPercentage
[] = "progress";
82 const char kJSMetadataType
[] = "metadata";
83 const char kJSBookmarks
[] = "bookmarks";
84 const char kJSTitle
[] = "title";
85 // Get password arguments (Plugin -> Page)
86 const char kJSGetPasswordType
[] = "getPassword";
87 // Get password complete arguments (Page -> Plugin)
88 const char kJSGetPasswordCompleteType
[] = "getPasswordComplete";
89 const char kJSPassword
[] = "password";
90 // Print (Page -> Plugin)
91 const char kJSPrintType
[] = "print";
92 // Save (Page -> Plugin)
93 const char kJSSaveType
[] = "save";
94 // Go to page (Plugin -> Page)
95 const char kJSGoToPageType
[] = "goToPage";
96 const char kJSPageNumber
[] = "page";
97 // Reset print preview mode (Page -> Plugin)
98 const char kJSResetPrintPreviewModeType
[] = "resetPrintPreviewMode";
99 const char kJSPrintPreviewUrl
[] = "url";
100 const char kJSPrintPreviewGrayscale
[] = "grayscale";
101 const char kJSPrintPreviewPageCount
[] = "pageCount";
102 // Load preview page (Page -> Plugin)
103 const char kJSLoadPreviewPageType
[] = "loadPreviewPage";
104 const char kJSPreviewPageUrl
[] = "url";
105 const char kJSPreviewPageIndex
[] = "index";
106 // Set scroll position (Plugin -> Page)
107 const char kJSSetScrollPositionType
[] = "setScrollPosition";
108 const char kJSPositionX
[] = "x";
109 const char kJSPositionY
[] = "y";
110 // Set translated strings (Plugin -> Page)
111 const char kJSSetTranslatedStringsType
[] = "setTranslatedStrings";
112 const char kJSGetPasswordString
[] = "getPasswordString";
113 const char kJSLoadingString
[] = "loadingString";
114 const char kJSLoadFailedString
[] = "loadFailedString";
115 // Request accessibility JSON data (Page -> Plugin)
116 const char kJSGetAccessibilityJSONType
[] = "getAccessibilityJSON";
117 const char kJSAccessibilityPageNumber
[] = "page";
118 // Reply with accessibility JSON data (Plugin -> Page)
119 const char kJSGetAccessibilityJSONReplyType
[] = "getAccessibilityJSONReply";
120 const char kJSAccessibilityJSON
[] = "json";
121 // Cancel the stream URL request (Plugin -> Page)
122 const char kJSCancelStreamUrlType
[] = "cancelStreamUrl";
123 // Navigate to the given URL (Plugin -> Page)
124 const char kJSNavigateType
[] = "navigate";
125 const char kJSNavigateUrl
[] = "url";
126 const char kJSNavigateNewTab
[] = "newTab";
127 // Open the email editor with the given parameters (Plugin -> Page)
128 const char kJSEmailType
[] = "email";
129 const char kJSEmailTo
[] = "to";
130 const char kJSEmailCc
[] = "cc";
131 const char kJSEmailBcc
[] = "bcc";
132 const char kJSEmailSubject
[] = "subject";
133 const char kJSEmailBody
[] = "body";
134 // Rotation (Page -> Plugin)
135 const char kJSRotateClockwiseType
[] = "rotateClockwise";
136 const char kJSRotateCounterclockwiseType
[] = "rotateCounterclockwise";
137 // Select all text in the document (Page -> Plugin)
138 const char kJSSelectAllType
[] = "selectAll";
139 // Get the selected text in the document (Page -> Plugin)
140 const char kJSGetSelectedTextType
[] = "getSelectedText";
141 // Reply with selected text (Plugin -> Page)
142 const char kJSGetSelectedTextReplyType
[] = "getSelectedTextReply";
143 const char kJSSelectedText
[] = "selectedText";
145 // Get the named destination with the given name (Page -> Plugin)
146 const char KJSGetNamedDestinationType
[] = "getNamedDestination";
147 const char KJSGetNamedDestination
[] = "namedDestination";
148 // Reply with the page number of the named destination (Plugin -> Page)
149 const char kJSGetNamedDestinationReplyType
[] = "getNamedDestinationReply";
150 const char kJSNamedDestinationPageNumber
[] = "pageNumber";
152 // Selecting text in document (Plugin -> Page)
153 const char kJSSetIsSelectingType
[] = "setIsSelecting";
154 const char kJSIsSelecting
[] = "isSelecting";
156 const int kFindResultCooldownMs
= 100;
158 const double kMinZoom
= 0.01;
162 static const char kPPPPdfInterface
[] = PPP_PDF_INTERFACE_1
;
164 PP_Var
GetLinkAtPosition(PP_Instance instance
, PP_Point point
) {
166 void* object
= pp::Instance::GetPerInstanceObject(instance
, kPPPPdfInterface
);
168 var
= static_cast<OutOfProcessInstance
*>(object
)->GetLinkAtPosition(
174 void Transform(PP_Instance instance
, PP_PrivatePageTransformType type
) {
176 pp::Instance::GetPerInstanceObject(instance
, kPPPPdfInterface
);
178 OutOfProcessInstance
* obj_instance
=
179 static_cast<OutOfProcessInstance
*>(object
);
181 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CW
:
182 obj_instance
->RotateClockwise();
184 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CCW
:
185 obj_instance
->RotateCounterclockwise();
191 PP_Bool
GetPrintPresetOptionsFromDocument(
192 PP_Instance instance
,
193 PP_PdfPrintPresetOptions_Dev
* options
) {
194 void* object
= pp::Instance::GetPerInstanceObject(instance
, kPPPPdfInterface
);
196 OutOfProcessInstance
* obj_instance
=
197 static_cast<OutOfProcessInstance
*>(object
);
198 obj_instance
->GetPrintPresetOptionsFromDocument(options
);
203 const PPP_Pdf ppp_private
= {
206 &GetPrintPresetOptionsFromDocument
209 int ExtractPrintPreviewPageIndex(const std::string
& src_url
) {
210 // Sample |src_url| format: chrome://print/id/page_index/print.pdf
211 std::vector
<std::string
> url_substr
= base::SplitString(
212 src_url
.substr(strlen(kChromePrint
)), "/",
213 base::TRIM_WHITESPACE
, base::SPLIT_WANT_ALL
);
214 if (url_substr
.size() != 3)
217 if (url_substr
[2] != "print.pdf")
221 if (!base::StringToInt(url_substr
[1], &page_index
))
226 bool IsPrintPreviewUrl(const std::string
& url
) {
227 return url
.substr(0, strlen(kChromePrint
)) == kChromePrint
;
230 void ScalePoint(float scale
, pp::Point
* point
) {
231 point
->set_x(static_cast<int>(point
->x() * scale
));
232 point
->set_y(static_cast<int>(point
->y() * scale
));
235 void ScaleRect(float scale
, pp::Rect
* rect
) {
236 int left
= static_cast<int>(floorf(rect
->x() * scale
));
237 int top
= static_cast<int>(floorf(rect
->y() * scale
));
238 int right
= static_cast<int>(ceilf((rect
->x() + rect
->width()) * scale
));
239 int bottom
= static_cast<int>(ceilf((rect
->y() + rect
->height()) * scale
));
240 rect
->SetRect(left
, top
, right
- left
, bottom
- top
);
243 // TODO(raymes): Remove this dependency on VarPrivate/InstancePrivate. It's
244 // needed right now to do a synchronous call to JavaScript, but we could easily
245 // replace this with a custom PPB_PDF function.
246 pp::Var
ModalDialog(const pp::Instance
* instance
,
247 const std::string
& type
,
248 const std::string
& message
,
249 const std::string
& default_answer
) {
250 const PPB_Instance_Private
* interface
=
251 reinterpret_cast<const PPB_Instance_Private
*>(
252 pp::Module::Get()->GetBrowserInterface(
253 PPB_INSTANCE_PRIVATE_INTERFACE
));
254 pp::VarPrivate
window(pp::PASS_REF
,
255 interface
->GetWindowObject(instance
->pp_instance()));
256 if (default_answer
.empty())
257 return window
.Call(type
, message
);
259 return window
.Call(type
, message
, default_answer
);
264 OutOfProcessInstance::OutOfProcessInstance(PP_Instance instance
)
265 : pp::Instance(instance
),
266 pp::Find_Private(this),
267 pp::Printing_Dev(this),
268 cursor_(PP_CURSORTYPE_POINTER
),
272 paint_manager_(this, this, true),
274 document_load_state_(LOAD_STATE_LOADING
),
275 preview_document_load_state_(LOAD_STATE_COMPLETE
),
277 told_browser_about_unsupported_feature_(false),
278 print_preview_page_count_(0),
279 last_progress_sent_(0),
280 recently_sent_find_update_(false),
281 received_viewport_message_(false),
282 did_call_start_loading_(false),
283 stop_scrolling_(false),
284 background_color_(kBackgroundColor
),
285 top_toolbar_height_(0) {
286 loader_factory_
.Initialize(this);
287 timer_factory_
.Initialize(this);
288 form_factory_
.Initialize(this);
289 print_callback_factory_
.Initialize(this);
290 engine_
.reset(PDFEngine::Create(this));
291 pp::Module::Get()->AddPluginInterface(kPPPPdfInterface
, &ppp_private
);
292 AddPerInstanceObject(kPPPPdfInterface
, this);
294 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_MOUSE
);
295 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_KEYBOARD
);
296 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_TOUCH
);
299 OutOfProcessInstance::~OutOfProcessInstance() {
300 RemovePerInstanceObject(kPPPPdfInterface
, this);
301 // Explicitly reset the PDFEngine during destruction as it may call back into
306 bool OutOfProcessInstance::Init(uint32_t argc
,
308 const char* argv
[]) {
309 // Check if the PDF is being loaded in the PDF chrome extension. We only allow
310 // the plugin to be loaded in the extension and print preview to avoid
311 // exposing sensitive APIs directly to external websites.
312 pp::Var document_url_var
= pp::URLUtil_Dev::Get()->GetDocumentURL(this);
313 if (!document_url_var
.is_string())
315 std::string document_url
= document_url_var
.AsString();
316 std::string extension_url
= std::string(kChromeExtension
);
317 std::string print_preview_url
= std::string(kChromePrint
);
318 if (!base::StringPiece(document_url
).starts_with(kChromeExtension
) &&
319 !base::StringPiece(document_url
).starts_with(kChromePrint
)) {
323 // Check if the plugin is full frame. This is passed in from JS.
324 for (uint32_t i
= 0; i
< argc
; ++i
) {
325 if (strcmp(argn
[i
], "full-frame") == 0) {
331 // Only allow the plugin to handle find requests if it is full frame.
333 SetPluginToHandleFindRequests();
335 // Send translated strings to the extension where they will be displayed.
336 // TODO(raymes): It would be better to get these in the extension directly
337 // through an API but no such API currently exists.
338 pp::VarDictionary translated_strings
;
339 translated_strings
.Set(kType
, kJSSetTranslatedStringsType
);
340 translated_strings
.Set(kJSGetPasswordString
,
341 GetLocalizedString(PP_RESOURCESTRING_PDFGETPASSWORD
));
342 translated_strings
.Set(kJSLoadingString
,
343 GetLocalizedString(PP_RESOURCESTRING_PDFLOADING
));
344 translated_strings
.Set(kJSLoadFailedString
,
345 GetLocalizedString(PP_RESOURCESTRING_PDFLOAD_FAILED
));
346 PostMessage(translated_strings
);
348 text_input_
.reset(new pp::TextInput_Dev(this));
350 const char* stream_url
= nullptr;
351 const char* original_url
= nullptr;
352 const char* headers
= nullptr;
353 bool is_material
= false;
354 for (uint32_t i
= 0; i
< argc
; ++i
) {
355 if (strcmp(argn
[i
], "src") == 0)
356 original_url
= argv
[i
];
357 else if (strcmp(argn
[i
], "stream-url") == 0)
358 stream_url
= argv
[i
];
359 else if (strcmp(argn
[i
], "headers") == 0)
361 else if (strcmp(argn
[i
], "is-material") == 0)
363 else if (strcmp(argn
[i
], "top-toolbar-height") == 0)
364 base::StringToInt(argv
[i
], &top_toolbar_height_
);
368 background_color_
= kBackgroundColorMaterial
;
370 background_color_
= kBackgroundColor
;
376 stream_url
= original_url
;
378 // If we're in print preview mode we don't need to load the document yet.
379 // A |kJSResetPrintPreviewModeType| message will be sent to the plugin letting
380 // it know the url to load. By not loading here we avoid loading the same
382 if (IsPrintPreviewUrl(original_url
))
387 return engine_
->New(original_url
, headers
);
390 void OutOfProcessInstance::HandleMessage(const pp::Var
& message
) {
391 pp::VarDictionary
dict(message
);
392 if (!dict
.Get(kType
).is_string()) {
397 std::string type
= dict
.Get(kType
).AsString();
399 if (type
== kJSViewportType
&&
400 dict
.Get(pp::Var(kJSXOffset
)).is_number() &&
401 dict
.Get(pp::Var(kJSYOffset
)).is_number() &&
402 dict
.Get(pp::Var(kJSZoom
)).is_number()) {
403 received_viewport_message_
= true;
404 stop_scrolling_
= false;
405 double zoom
= dict
.Get(pp::Var(kJSZoom
)).AsDouble();
406 pp::FloatPoint
scroll_offset(dict
.Get(pp::Var(kJSXOffset
)).AsDouble(),
407 dict
.Get(pp::Var(kJSYOffset
)).AsDouble());
409 // Bound the input parameters.
410 zoom
= std::max(kMinZoom
, zoom
);
412 scroll_offset
= BoundScrollOffsetToDocument(scroll_offset
);
413 engine_
->ScrolledToXPosition(scroll_offset
.x() * device_scale_
);
414 engine_
->ScrolledToYPosition(scroll_offset
.y() * device_scale_
);
415 } else if (type
== kJSGetPasswordCompleteType
&&
416 dict
.Get(pp::Var(kJSPassword
)).is_string()) {
417 if (password_callback_
) {
418 pp::CompletionCallbackWithOutput
<pp::Var
> callback
= *password_callback_
;
419 password_callback_
.reset();
420 *callback
.output() = dict
.Get(pp::Var(kJSPassword
)).pp_var();
425 } else if (type
== kJSPrintType
) {
427 } else if (type
== kJSSaveType
) {
428 pp::PDF::SaveAs(this);
429 } else if (type
== kJSRotateClockwiseType
) {
431 } else if (type
== kJSRotateCounterclockwiseType
) {
432 RotateCounterclockwise();
433 } else if (type
== kJSSelectAllType
) {
434 engine_
->SelectAll();
435 } else if (type
== kJSResetPrintPreviewModeType
&&
436 dict
.Get(pp::Var(kJSPrintPreviewUrl
)).is_string() &&
437 dict
.Get(pp::Var(kJSPrintPreviewGrayscale
)).is_bool() &&
438 dict
.Get(pp::Var(kJSPrintPreviewPageCount
)).is_int()) {
439 url_
= dict
.Get(pp::Var(kJSPrintPreviewUrl
)).AsString();
440 preview_pages_info_
= std::queue
<PreviewPageInfo
>();
441 preview_document_load_state_
= LOAD_STATE_COMPLETE
;
442 document_load_state_
= LOAD_STATE_LOADING
;
444 preview_engine_
.reset();
445 engine_
.reset(PDFEngine::Create(this));
446 engine_
->SetGrayscale(dict
.Get(pp::Var(kJSPrintPreviewGrayscale
)).AsBool());
447 engine_
->New(url_
.c_str(), nullptr /* empty header */);
449 print_preview_page_count_
=
450 std::max(dict
.Get(pp::Var(kJSPrintPreviewPageCount
)).AsInt(), 0);
452 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
453 } else if (type
== kJSLoadPreviewPageType
&&
454 dict
.Get(pp::Var(kJSPreviewPageUrl
)).is_string() &&
455 dict
.Get(pp::Var(kJSPreviewPageIndex
)).is_int()) {
456 ProcessPreviewPageInfo(dict
.Get(pp::Var(kJSPreviewPageUrl
)).AsString(),
457 dict
.Get(pp::Var(kJSPreviewPageIndex
)).AsInt());
458 } else if (type
== kJSGetAccessibilityJSONType
) {
459 pp::VarDictionary reply
;
460 reply
.Set(pp::Var(kType
), pp::Var(kJSGetAccessibilityJSONReplyType
));
461 if (dict
.Get(pp::Var(kJSAccessibilityPageNumber
)).is_int()) {
462 int page
= dict
.Get(pp::Var(kJSAccessibilityPageNumber
)).AsInt();
463 reply
.Set(pp::Var(kJSAccessibilityJSON
),
464 pp::Var(engine_
->GetPageAsJSON(page
)));
466 base::DictionaryValue node
;
467 node
.SetInteger(kAccessibleNumberOfPages
, engine_
->GetNumberOfPages());
468 node
.SetBoolean(kAccessibleLoaded
,
469 document_load_state_
!= LOAD_STATE_LOADING
);
470 bool has_permissions
=
471 engine_
->HasPermission(PDFEngine::PERMISSION_COPY
) ||
472 engine_
->HasPermission(PDFEngine::PERMISSION_COPY_ACCESSIBLE
);
473 node
.SetBoolean(kAccessibleCopyable
, has_permissions
);
475 base::JSONWriter::Write(node
, &json
);
476 reply
.Set(pp::Var(kJSAccessibilityJSON
), pp::Var(json
));
479 } else if (type
== kJSStopScrollingType
) {
480 stop_scrolling_
= true;
481 } else if (type
== kJSGetSelectedTextType
) {
482 std::string selected_text
= engine_
->GetSelectedText();
483 // Always return unix newlines to JS.
484 base::ReplaceChars(selected_text
, "\r", std::string(), &selected_text
);
485 pp::VarDictionary reply
;
486 reply
.Set(pp::Var(kType
), pp::Var(kJSGetSelectedTextReplyType
));
487 reply
.Set(pp::Var(kJSSelectedText
), selected_text
);
489 } else if (type
== KJSGetNamedDestinationType
&&
490 dict
.Get(pp::Var(KJSGetNamedDestination
)).is_string()) {
491 int page_number
= engine_
->GetNamedDestinationPage(
492 dict
.Get(pp::Var(KJSGetNamedDestination
)).AsString());
493 pp::VarDictionary reply
;
494 reply
.Set(pp::Var(kType
), pp::Var(kJSGetNamedDestinationReplyType
));
495 if (page_number
>= 0)
496 reply
.Set(pp::Var(kJSNamedDestinationPageNumber
), page_number
);
503 bool OutOfProcessInstance::HandleInputEvent(
504 const pp::InputEvent
& event
) {
505 // To simplify things, convert the event into device coordinates if it is
507 pp::InputEvent
event_device_res(event
);
509 pp::MouseInputEvent
mouse_event(event
);
510 if (!mouse_event
.is_null()) {
511 pp::Point point
= mouse_event
.GetPosition();
512 pp::Point movement
= mouse_event
.GetMovement();
513 ScalePoint(device_scale_
, &point
);
514 ScalePoint(device_scale_
, &movement
);
515 mouse_event
= pp::MouseInputEvent(
518 event
.GetTimeStamp(),
519 event
.GetModifiers(),
520 mouse_event
.GetButton(),
522 mouse_event
.GetClickCount(),
524 event_device_res
= mouse_event
;
528 pp::InputEvent
offset_event(event_device_res
);
529 switch (offset_event
.GetType()) {
530 case PP_INPUTEVENT_TYPE_MOUSEDOWN
:
531 case PP_INPUTEVENT_TYPE_MOUSEUP
:
532 case PP_INPUTEVENT_TYPE_MOUSEMOVE
:
533 case PP_INPUTEVENT_TYPE_MOUSEENTER
:
534 case PP_INPUTEVENT_TYPE_MOUSELEAVE
: {
535 pp::MouseInputEvent
mouse_event(event_device_res
);
536 pp::MouseInputEvent
mouse_event_dip(event
);
537 pp::Point point
= mouse_event
.GetPosition();
538 point
.set_x(point
.x() - available_area_
.x());
539 offset_event
= pp::MouseInputEvent(
542 event
.GetTimeStamp(),
543 event
.GetModifiers(),
544 mouse_event
.GetButton(),
546 mouse_event
.GetClickCount(),
547 mouse_event
.GetMovement());
553 if (engine_
->HandleEvent(offset_event
))
556 // Middle click is used for scrolling and is handled by the container page.
557 pp::MouseInputEvent
mouse_event(event_device_res
);
558 if (!mouse_event
.is_null() &&
559 mouse_event
.GetButton() == PP_INPUTEVENT_MOUSEBUTTON_MIDDLE
) {
563 // Return true for unhandled clicks so the plugin takes focus.
564 return (event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN
);
567 void OutOfProcessInstance::DidChangeView(const pp::View
& view
) {
568 pp::Rect
view_rect(view
.GetRect());
569 float old_device_scale
= device_scale_
;
570 float device_scale
= view
.GetDeviceScale();
571 pp::Size
view_device_size(view_rect
.width() * device_scale
,
572 view_rect
.height() * device_scale
);
574 if (view_device_size
!= plugin_size_
|| device_scale
!= device_scale_
) {
575 device_scale_
= device_scale
;
576 plugin_dip_size_
= view_rect
.size();
577 plugin_size_
= view_device_size
;
579 paint_manager_
.SetSize(view_device_size
, device_scale_
);
581 pp::Size new_image_data_size
= PaintManager::GetNewContextSize(
584 if (new_image_data_size
!= image_data_
.size()) {
585 image_data_
= pp::ImageData(this,
586 PP_IMAGEDATAFORMAT_BGRA_PREMUL
,
592 if (image_data_
.is_null()) {
593 DCHECK(plugin_size_
.IsEmpty());
597 OnGeometryChanged(zoom_
, old_device_scale
);
600 if (!stop_scrolling_
) {
601 pp::Point
scroll_offset(view
.GetScrollOffset());
602 // Because view messages come from the DOM, the coordinates of the viewport
603 // are 0-based (i.e. they do not correspond to the viewport's coordinates in
604 // JS), so we need to subtract the toolbar height to convert them into
605 // viewport coordinates.
606 pp::FloatPoint
scroll_offset_float(scroll_offset
.x(),
607 scroll_offset
.y() - top_toolbar_height_
);
608 scroll_offset_float
= BoundScrollOffsetToDocument(scroll_offset_float
);
609 engine_
->ScrolledToXPosition(scroll_offset_float
.x() * device_scale_
);
610 engine_
->ScrolledToYPosition(scroll_offset_float
.y() * device_scale_
);
614 void OutOfProcessInstance::GetPrintPresetOptionsFromDocument(
615 PP_PdfPrintPresetOptions_Dev
* options
) {
616 options
->is_scaling_disabled
= PP_FromBool(IsPrintScalingDisabled());
618 static_cast<PP_PrivateDuplexMode_Dev
>(engine_
->GetDuplexType());
619 options
->copies
= engine_
->GetCopiesToPrint();
620 pp::Size uniform_page_size
;
621 options
->is_page_size_uniform
=
622 PP_FromBool(engine_
->GetPageSizeAndUniformity(&uniform_page_size
));
623 options
->uniform_page_size
= uniform_page_size
;
626 pp::Var
OutOfProcessInstance::GetLinkAtPosition(
627 const pp::Point
& point
) {
628 pp::Point
offset_point(point
);
629 ScalePoint(device_scale_
, &offset_point
);
630 offset_point
.set_x(offset_point
.x() - available_area_
.x());
631 return engine_
->GetLinkAtPosition(offset_point
);
634 uint32_t OutOfProcessInstance::QuerySupportedPrintOutputFormats() {
635 return engine_
->QuerySupportedPrintOutputFormats();
638 int32_t OutOfProcessInstance::PrintBegin(
639 const PP_PrintSettings_Dev
& print_settings
) {
640 // For us num_pages is always equal to the number of pages in the PDF
641 // document irrespective of the printable area.
642 int32_t ret
= engine_
->GetNumberOfPages();
646 uint32_t supported_formats
= engine_
->QuerySupportedPrintOutputFormats();
647 if ((print_settings
.format
& supported_formats
) == 0)
650 print_settings_
.is_printing
= true;
651 print_settings_
.pepper_print_settings
= print_settings
;
652 engine_
->PrintBegin();
656 pp::Resource
OutOfProcessInstance::PrintPages(
657 const PP_PrintPageNumberRange_Dev
* page_ranges
,
658 uint32_t page_range_count
) {
659 if (!print_settings_
.is_printing
)
660 return pp::Resource();
662 print_settings_
.print_pages_called_
= true;
663 return engine_
->PrintPages(page_ranges
, page_range_count
,
664 print_settings_
.pepper_print_settings
);
667 void OutOfProcessInstance::PrintEnd() {
668 if (print_settings_
.print_pages_called_
)
669 UserMetricsRecordAction("PDF.PrintPage");
670 print_settings_
.Clear();
674 bool OutOfProcessInstance::IsPrintScalingDisabled() {
675 return !engine_
->GetPrintScaling();
678 bool OutOfProcessInstance::StartFind(const std::string
& text
,
679 bool case_sensitive
) {
680 engine_
->StartFind(text
.c_str(), case_sensitive
);
684 void OutOfProcessInstance::SelectFindResult(bool forward
) {
685 engine_
->SelectFindResult(forward
);
688 void OutOfProcessInstance::StopFind() {
691 SetTickmarks(tickmarks_
);
694 void OutOfProcessInstance::OnPaint(
695 const std::vector
<pp::Rect
>& paint_rects
,
696 std::vector
<PaintManager::ReadyRect
>* ready
,
697 std::vector
<pp::Rect
>* pending
) {
698 if (image_data_
.is_null()) {
699 DCHECK(plugin_size_
.IsEmpty());
703 first_paint_
= false;
704 pp::Rect rect
= pp::Rect(pp::Point(), image_data_
.size());
705 FillRect(rect
, background_color_
);
706 ready
->push_back(PaintManager::ReadyRect(rect
, image_data_
, true));
709 if (!received_viewport_message_
)
714 for (size_t i
= 0; i
< paint_rects
.size(); i
++) {
715 // Intersect with plugin area since there could be pending invalidates from
716 // when the plugin area was larger.
718 paint_rects
[i
].Intersect(pp::Rect(pp::Point(), plugin_size_
));
722 pp::Rect pdf_rect
= available_area_
.Intersect(rect
);
723 if (!pdf_rect
.IsEmpty()) {
724 pdf_rect
.Offset(available_area_
.x() * -1, 0);
726 std::vector
<pp::Rect
> pdf_ready
;
727 std::vector
<pp::Rect
> pdf_pending
;
728 engine_
->Paint(pdf_rect
, &image_data_
, &pdf_ready
, &pdf_pending
);
729 for (size_t j
= 0; j
< pdf_ready
.size(); ++j
) {
730 pdf_ready
[j
].Offset(available_area_
.point());
732 PaintManager::ReadyRect(pdf_ready
[j
], image_data_
, false));
734 for (size_t j
= 0; j
< pdf_pending
.size(); ++j
) {
735 pdf_pending
[j
].Offset(available_area_
.point());
736 pending
->push_back(pdf_pending
[j
]);
740 // Ensure the region above the first page (if any) is filled;
741 int32_t first_page_ypos
= engine_
->GetNumberOfPages() == 0 ?
742 0 : engine_
->GetPageScreenRect(0).y();
743 if (rect
.y() < first_page_ypos
) {
744 pp::Rect region
= rect
.Intersect(pp::Rect(
745 pp::Point(), pp::Size(plugin_size_
.width(), first_page_ypos
)));
746 ready
->push_back(PaintManager::ReadyRect(region
, image_data_
, false));
747 FillRect(region
, background_color_
);
750 for (size_t j
= 0; j
< background_parts_
.size(); ++j
) {
751 pp::Rect intersection
= background_parts_
[j
].location
.Intersect(rect
);
752 if (!intersection
.IsEmpty()) {
753 FillRect(intersection
, background_parts_
[j
].color
);
755 PaintManager::ReadyRect(intersection
, image_data_
, false));
760 engine_
->PostPaint();
763 void OutOfProcessInstance::DidOpen(int32_t result
) {
764 if (result
== PP_OK
) {
765 if (!engine_
->HandleDocumentLoad(embed_loader_
)) {
766 document_load_state_
= LOAD_STATE_LOADING
;
767 DocumentLoadFailed();
769 } else if (result
!= PP_ERROR_ABORTED
) { // Can happen in tests.
771 DocumentLoadFailed();
774 // If it's a progressive load, cancel the stream URL request so that requests
775 // can be made on the original URL.
776 // TODO(raymes): Make this clearer once the in-process plugin is deleted.
777 if (engine_
->IsProgressiveLoad()) {
778 pp::VarDictionary message
;
779 message
.Set(kType
, kJSCancelStreamUrlType
);
780 PostMessage(message
);
784 void OutOfProcessInstance::DidOpenPreview(int32_t result
) {
785 if (result
== PP_OK
) {
786 preview_client_
.reset(new PreviewModeClient(this));
787 preview_engine_
.reset(PDFEngine::Create(preview_client_
.get()));
788 preview_engine_
->HandleDocumentLoad(embed_preview_loader_
);
794 void OutOfProcessInstance::OnClientTimerFired(int32_t id
) {
795 engine_
->OnCallback(id
);
798 void OutOfProcessInstance::CalculateBackgroundParts() {
799 background_parts_
.clear();
800 int left_width
= available_area_
.x();
801 int right_start
= available_area_
.right();
802 int right_width
= abs(plugin_size_
.width() - available_area_
.right());
803 int bottom
= std::min(available_area_
.bottom(), plugin_size_
.height());
805 // Add the left, right, and bottom rectangles. Note: we assume only
806 // horizontal centering.
807 BackgroundPart part
= {
808 pp::Rect(0, 0, left_width
, bottom
),
811 if (!part
.location
.IsEmpty())
812 background_parts_
.push_back(part
);
813 part
.location
= pp::Rect(right_start
, 0, right_width
, bottom
);
814 if (!part
.location
.IsEmpty())
815 background_parts_
.push_back(part
);
816 part
.location
= pp::Rect(
817 0, bottom
, plugin_size_
.width(), plugin_size_
.height() - bottom
);
818 if (!part
.location
.IsEmpty())
819 background_parts_
.push_back(part
);
822 int OutOfProcessInstance::GetDocumentPixelWidth() const {
823 return static_cast<int>(ceil(document_size_
.width() * zoom_
* device_scale_
));
826 int OutOfProcessInstance::GetDocumentPixelHeight() const {
827 return static_cast<int>(
828 ceil(document_size_
.height() * zoom_
* device_scale_
));
831 void OutOfProcessInstance::FillRect(const pp::Rect
& rect
, uint32 color
) {
832 DCHECK(!image_data_
.is_null() || rect
.IsEmpty());
833 uint32
* buffer_start
= static_cast<uint32
*>(image_data_
.data());
834 int stride
= image_data_
.stride();
835 uint32
* ptr
= buffer_start
+ rect
.y() * stride
/ 4 + rect
.x();
836 int height
= rect
.height();
837 int width
= rect
.width();
838 for (int y
= 0; y
< height
; ++y
) {
839 for (int x
= 0; x
< width
; ++x
)
845 void OutOfProcessInstance::DocumentSizeUpdated(const pp::Size
& size
) {
846 document_size_
= size
;
848 pp::VarDictionary dimensions
;
849 dimensions
.Set(kType
, kJSDocumentDimensionsType
);
850 dimensions
.Set(kJSDocumentWidth
, pp::Var(document_size_
.width()));
851 dimensions
.Set(kJSDocumentHeight
, pp::Var(document_size_
.height()));
852 pp::VarArray page_dimensions_array
;
853 int num_pages
= engine_
->GetNumberOfPages();
854 for (int i
= 0; i
< num_pages
; ++i
) {
855 pp::Rect page_rect
= engine_
->GetPageRect(i
);
856 pp::VarDictionary page_dimensions
;
857 page_dimensions
.Set(kJSPageX
, pp::Var(page_rect
.x()));
858 page_dimensions
.Set(kJSPageY
, pp::Var(page_rect
.y()));
859 page_dimensions
.Set(kJSPageWidth
, pp::Var(page_rect
.width()));
860 page_dimensions
.Set(kJSPageHeight
, pp::Var(page_rect
.height()));
861 page_dimensions_array
.Set(i
, page_dimensions
);
863 dimensions
.Set(kJSPageDimensions
, page_dimensions_array
);
864 PostMessage(dimensions
);
866 OnGeometryChanged(zoom_
, device_scale_
);
869 void OutOfProcessInstance::Invalidate(const pp::Rect
& rect
) {
870 pp::Rect
offset_rect(rect
);
871 offset_rect
.Offset(available_area_
.point());
872 paint_manager_
.InvalidateRect(offset_rect
);
875 void OutOfProcessInstance::Scroll(const pp::Point
& point
) {
876 if (!image_data_
.is_null())
877 paint_manager_
.ScrollRect(available_area_
, point
);
880 void OutOfProcessInstance::ScrollToX(int x
) {
881 pp::VarDictionary position
;
882 position
.Set(kType
, kJSSetScrollPositionType
);
883 position
.Set(kJSPositionX
, pp::Var(x
/ device_scale_
));
884 PostMessage(position
);
887 void OutOfProcessInstance::ScrollToY(int y
) {
888 pp::VarDictionary position
;
889 position
.Set(kType
, kJSSetScrollPositionType
);
890 position
.Set(kJSPositionY
, pp::Var(y
/ device_scale_
));
891 PostMessage(position
);
894 void OutOfProcessInstance::ScrollToPage(int page
) {
895 if (engine_
->GetNumberOfPages() == 0)
898 pp::VarDictionary message
;
899 message
.Set(kType
, kJSGoToPageType
);
900 message
.Set(kJSPageNumber
, pp::Var(page
));
901 PostMessage(message
);
904 void OutOfProcessInstance::NavigateTo(const std::string
& url
,
905 bool open_in_new_tab
) {
906 pp::VarDictionary message
;
907 message
.Set(kType
, kJSNavigateType
);
908 message
.Set(kJSNavigateUrl
, url
);
909 message
.Set(kJSNavigateNewTab
, open_in_new_tab
);
910 PostMessage(message
);
913 void OutOfProcessInstance::UpdateCursor(PP_CursorType_Dev cursor
) {
914 if (cursor
== cursor_
)
918 const PPB_CursorControl_Dev
* cursor_interface
=
919 reinterpret_cast<const PPB_CursorControl_Dev
*>(
920 pp::Module::Get()->GetBrowserInterface(PPB_CURSOR_CONTROL_DEV_INTERFACE
));
921 if (!cursor_interface
) {
926 cursor_interface
->SetCursor(
927 pp_instance(), cursor_
, pp::ImageData().pp_resource(), nullptr);
930 void OutOfProcessInstance::UpdateTickMarks(
931 const std::vector
<pp::Rect
>& tickmarks
) {
932 float inverse_scale
= 1.0f
/ device_scale_
;
933 std::vector
<pp::Rect
> scaled_tickmarks
= tickmarks
;
934 for (size_t i
= 0; i
< scaled_tickmarks
.size(); i
++)
935 ScaleRect(inverse_scale
, &scaled_tickmarks
[i
]);
936 tickmarks_
= scaled_tickmarks
;
939 void OutOfProcessInstance::NotifyNumberOfFindResultsChanged(int total
,
941 // We don't want to spam the renderer with too many updates to the number of
942 // find results. Don't send an update if we sent one too recently. If it's the
943 // final update, we always send it though.
945 NumberOfFindResultsChanged(total
, final_result
);
946 SetTickmarks(tickmarks_
);
950 if (recently_sent_find_update_
)
953 NumberOfFindResultsChanged(total
, final_result
);
954 SetTickmarks(tickmarks_
);
955 recently_sent_find_update_
= true;
956 pp::CompletionCallback callback
=
957 timer_factory_
.NewCallback(
958 &OutOfProcessInstance::ResetRecentlySentFindUpdate
);
959 pp::Module::Get()->core()->CallOnMainThread(kFindResultCooldownMs
,
963 void OutOfProcessInstance::NotifySelectedFindResultChanged(
964 int current_find_index
) {
965 DCHECK_GE(current_find_index
, 0);
966 SelectedFindResultChanged(current_find_index
);
969 void OutOfProcessInstance::GetDocumentPassword(
970 pp::CompletionCallbackWithOutput
<pp::Var
> callback
) {
971 if (password_callback_
) {
976 password_callback_
.reset(
977 new pp::CompletionCallbackWithOutput
<pp::Var
>(callback
));
978 pp::VarDictionary message
;
979 message
.Set(pp::Var(kType
), pp::Var(kJSGetPasswordType
));
980 PostMessage(message
);
983 void OutOfProcessInstance::Alert(const std::string
& message
) {
984 ModalDialog(this, "alert", message
, std::string());
987 bool OutOfProcessInstance::Confirm(const std::string
& message
) {
988 pp::Var result
= ModalDialog(this, "confirm", message
, std::string());
989 return result
.is_bool() ? result
.AsBool() : false;
992 std::string
OutOfProcessInstance::Prompt(const std::string
& question
,
993 const std::string
& default_answer
) {
994 pp::Var result
= ModalDialog(this, "prompt", question
, default_answer
);
995 return result
.is_string() ? result
.AsString() : std::string();
998 std::string
OutOfProcessInstance::GetURL() {
1002 void OutOfProcessInstance::Email(const std::string
& to
,
1003 const std::string
& cc
,
1004 const std::string
& bcc
,
1005 const std::string
& subject
,
1006 const std::string
& body
) {
1007 pp::VarDictionary message
;
1008 message
.Set(pp::Var(kType
), pp::Var(kJSEmailType
));
1009 message
.Set(pp::Var(kJSEmailTo
),
1010 pp::Var(net::EscapeUrlEncodedData(to
, false)));
1011 message
.Set(pp::Var(kJSEmailCc
),
1012 pp::Var(net::EscapeUrlEncodedData(cc
, false)));
1013 message
.Set(pp::Var(kJSEmailBcc
),
1014 pp::Var(net::EscapeUrlEncodedData(bcc
, false)));
1015 message
.Set(pp::Var(kJSEmailSubject
),
1016 pp::Var(net::EscapeUrlEncodedData(subject
, false)));
1017 message
.Set(pp::Var(kJSEmailBody
),
1018 pp::Var(net::EscapeUrlEncodedData(body
, false)));
1019 PostMessage(message
);
1022 void OutOfProcessInstance::Print() {
1023 if (!engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
) &&
1024 !engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY
)) {
1028 pp::CompletionCallback callback
=
1029 print_callback_factory_
.NewCallback(&OutOfProcessInstance::OnPrint
);
1030 pp::Module::Get()->core()->CallOnMainThread(0, callback
);
1033 void OutOfProcessInstance::OnPrint(int32_t) {
1034 pp::PDF::Print(this);
1037 void OutOfProcessInstance::SubmitForm(const std::string
& url
,
1040 pp::URLRequestInfo
request(this);
1041 request
.SetURL(url
);
1042 request
.SetMethod("POST");
1043 request
.AppendDataToBody(reinterpret_cast<const char*>(data
), length
);
1045 pp::CompletionCallback callback
=
1046 form_factory_
.NewCallback(&OutOfProcessInstance::FormDidOpen
);
1047 form_loader_
= CreateURLLoaderInternal();
1048 int rv
= form_loader_
.Open(request
, callback
);
1049 if (rv
!= PP_OK_COMPLETIONPENDING
)
1053 void OutOfProcessInstance::FormDidOpen(int32_t result
) {
1054 // TODO: inform the user of success/failure.
1055 if (result
!= PP_OK
) {
1060 std::string
OutOfProcessInstance::ShowFileSelectionDialog() {
1061 // Seems like very low priority to implement, since the pdf has no way to get
1062 // the file data anyways. Javascript doesn't let you do this synchronously.
1064 return std::string();
1067 pp::URLLoader
OutOfProcessInstance::CreateURLLoader() {
1069 if (!did_call_start_loading_
) {
1070 did_call_start_loading_
= true;
1071 pp::PDF::DidStartLoading(this);
1074 // Disable save and print until the document is fully loaded, since they
1075 // would generate an incomplete document. Need to do this each time we
1076 // call DidStartLoading since that resets the content restrictions.
1077 pp::PDF::SetContentRestriction(this, CONTENT_RESTRICTION_SAVE
|
1078 CONTENT_RESTRICTION_PRINT
);
1081 return CreateURLLoaderInternal();
1084 void OutOfProcessInstance::ScheduleCallback(int id
, int delay_in_ms
) {
1085 pp::CompletionCallback callback
=
1086 timer_factory_
.NewCallback(&OutOfProcessInstance::OnClientTimerFired
);
1087 pp::Module::Get()->core()->CallOnMainThread(delay_in_ms
, callback
, id
);
1090 void OutOfProcessInstance::SearchString(const base::char16
* string
,
1091 const base::char16
* term
,
1092 bool case_sensitive
,
1093 std::vector
<SearchStringResult
>* results
) {
1094 PP_PrivateFindResult
* pp_results
;
1096 pp::PDF::SearchString(
1098 reinterpret_cast<const unsigned short*>(string
),
1099 reinterpret_cast<const unsigned short*>(term
),
1104 results
->resize(count
);
1105 for (int i
= 0; i
< count
; ++i
) {
1106 (*results
)[i
].start_index
= pp_results
[i
].start_index
;
1107 (*results
)[i
].length
= pp_results
[i
].length
;
1110 pp::Memory_Dev memory
;
1111 memory
.MemFree(pp_results
);
1114 void OutOfProcessInstance::DocumentPaintOccurred() {
1117 void OutOfProcessInstance::DocumentLoadComplete(int page_count
) {
1118 // Clear focus state for OSK.
1119 FormTextFieldFocusChange(false);
1121 DCHECK(document_load_state_
== LOAD_STATE_LOADING
);
1122 document_load_state_
= LOAD_STATE_COMPLETE
;
1123 UserMetricsRecordAction("PDF.LoadSuccess");
1125 // Note: If we are in print preview mode the scroll location is retained
1126 // across document loads so we don't want to scroll again and override it.
1127 if (IsPrintPreview()) {
1128 AppendBlankPrintPreviewPages();
1129 OnGeometryChanged(0, 0);
1132 pp::VarDictionary metadata_message
;
1133 metadata_message
.Set(pp::Var(kType
), pp::Var(kJSMetadataType
));
1134 std::string title
= engine_
->GetMetadata("Title");
1135 if (!base::TrimWhitespace(base::UTF8ToUTF16(title
), base::TRIM_ALL
).empty())
1136 metadata_message
.Set(pp::Var(kJSTitle
), pp::Var(title
));
1138 metadata_message
.Set(pp::Var(kJSBookmarks
), engine_
->GetBookmarks());
1139 PostMessage(metadata_message
);
1141 pp::VarDictionary progress_message
;
1142 progress_message
.Set(pp::Var(kType
), pp::Var(kJSLoadProgressType
));
1143 progress_message
.Set(pp::Var(kJSProgressPercentage
), pp::Var(100));
1144 PostMessage(progress_message
);
1149 if (did_call_start_loading_
) {
1150 pp::PDF::DidStopLoading(this);
1151 did_call_start_loading_
= false;
1154 int content_restrictions
=
1155 CONTENT_RESTRICTION_CUT
| CONTENT_RESTRICTION_PASTE
;
1156 if (!engine_
->HasPermission(PDFEngine::PERMISSION_COPY
))
1157 content_restrictions
|= CONTENT_RESTRICTION_COPY
;
1159 if (!engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
) &&
1160 !engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY
)) {
1161 content_restrictions
|= CONTENT_RESTRICTION_PRINT
;
1164 pp::PDF::SetContentRestriction(this, content_restrictions
);
1166 uma_
.HistogramCustomCounts("PDF.PageCount", page_count
, 1, 1000000, 50);
1169 void OutOfProcessInstance::RotateClockwise() {
1170 engine_
->RotateClockwise();
1173 void OutOfProcessInstance::RotateCounterclockwise() {
1174 engine_
->RotateCounterclockwise();
1177 void OutOfProcessInstance::PreviewDocumentLoadComplete() {
1178 if (preview_document_load_state_
!= LOAD_STATE_LOADING
||
1179 preview_pages_info_
.empty()) {
1183 preview_document_load_state_
= LOAD_STATE_COMPLETE
;
1185 int dest_page_index
= preview_pages_info_
.front().second
;
1186 int src_page_index
=
1187 ExtractPrintPreviewPageIndex(preview_pages_info_
.front().first
);
1188 if (src_page_index
> 0 && dest_page_index
> -1 && preview_engine_
.get())
1189 engine_
->AppendPage(preview_engine_
.get(), dest_page_index
);
1191 preview_pages_info_
.pop();
1192 // |print_preview_page_count_| is not updated yet. Do not load any
1193 // other preview pages till we get this information.
1194 if (print_preview_page_count_
== 0)
1197 if (!preview_pages_info_
.empty())
1198 LoadAvailablePreviewPage();
1201 void OutOfProcessInstance::DocumentLoadFailed() {
1202 DCHECK(document_load_state_
== LOAD_STATE_LOADING
);
1203 UserMetricsRecordAction("PDF.LoadFailure");
1205 if (did_call_start_loading_
) {
1206 pp::PDF::DidStopLoading(this);
1207 did_call_start_loading_
= false;
1210 document_load_state_
= LOAD_STATE_FAILED
;
1211 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
1213 // Send a progress value of -1 to indicate a failure.
1214 pp::VarDictionary message
;
1215 message
.Set(pp::Var(kType
), pp::Var(kJSLoadProgressType
));
1216 message
.Set(pp::Var(kJSProgressPercentage
), pp::Var(-1));
1217 PostMessage(message
);
1220 void OutOfProcessInstance::PreviewDocumentLoadFailed() {
1221 UserMetricsRecordAction("PDF.PreviewDocumentLoadFailure");
1222 if (preview_document_load_state_
!= LOAD_STATE_LOADING
||
1223 preview_pages_info_
.empty()) {
1227 preview_document_load_state_
= LOAD_STATE_FAILED
;
1228 preview_pages_info_
.pop();
1230 if (!preview_pages_info_
.empty())
1231 LoadAvailablePreviewPage();
1234 pp::Instance
* OutOfProcessInstance::GetPluginInstance() {
1238 void OutOfProcessInstance::DocumentHasUnsupportedFeature(
1239 const std::string
& feature
) {
1240 std::string
metric("PDF_Unsupported_");
1242 if (!unsupported_features_reported_
.count(metric
)) {
1243 unsupported_features_reported_
.insert(metric
);
1244 UserMetricsRecordAction(metric
);
1247 // Since we use an info bar, only do this for full frame plugins..
1251 if (told_browser_about_unsupported_feature_
)
1253 told_browser_about_unsupported_feature_
= true;
1255 pp::PDF::HasUnsupportedFeature(this);
1258 void OutOfProcessInstance::DocumentLoadProgress(uint32 available
,
1260 double progress
= 0.0;
1261 if (doc_size
== 0) {
1262 // Document size is unknown. Use heuristics.
1263 // We'll make progress logarithmic from 0 to 100M.
1264 static const double kFactor
= log(100000000.0) / 100.0;
1265 if (available
> 0) {
1266 progress
= log(static_cast<double>(available
)) / kFactor
;
1267 if (progress
> 100.0)
1271 progress
= 100.0 * static_cast<double>(available
) / doc_size
;
1274 // We send 100% load progress in DocumentLoadComplete.
1275 if (progress
>= 100)
1278 // Avoid sending too many progress messages over PostMessage.
1279 if (progress
> last_progress_sent_
+ 1) {
1280 last_progress_sent_
= progress
;
1281 pp::VarDictionary message
;
1282 message
.Set(pp::Var(kType
), pp::Var(kJSLoadProgressType
));
1283 message
.Set(pp::Var(kJSProgressPercentage
), pp::Var(progress
));
1284 PostMessage(message
);
1288 void OutOfProcessInstance::FormTextFieldFocusChange(bool in_focus
) {
1289 if (!text_input_
.get())
1292 text_input_
->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_TEXT
);
1294 text_input_
->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_NONE
);
1297 void OutOfProcessInstance::ResetRecentlySentFindUpdate(int32_t /* unused */) {
1298 recently_sent_find_update_
= false;
1301 void OutOfProcessInstance::OnGeometryChanged(double old_zoom
,
1302 float old_device_scale
) {
1303 if (zoom_
!= old_zoom
|| device_scale_
!= old_device_scale
)
1304 engine_
->ZoomUpdated(zoom_
* device_scale_
);
1306 available_area_
= pp::Rect(plugin_size_
);
1307 int doc_width
= GetDocumentPixelWidth();
1308 if (doc_width
< available_area_
.width()) {
1309 available_area_
.Offset((available_area_
.width() - doc_width
) / 2, 0);
1310 available_area_
.set_width(doc_width
);
1312 int bottom_of_document
=
1313 GetDocumentPixelHeight() + (top_toolbar_height_
* device_scale_
);
1314 if (bottom_of_document
< available_area_
.height())
1315 available_area_
.set_height(bottom_of_document
);
1317 CalculateBackgroundParts();
1318 engine_
->PageOffsetUpdated(available_area_
.point());
1319 engine_
->PluginSizeUpdated(available_area_
.size());
1321 if (!document_size_
.GetArea())
1323 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
1326 void OutOfProcessInstance::LoadUrl(const std::string
& url
) {
1327 LoadUrlInternal(url
, &embed_loader_
, &OutOfProcessInstance::DidOpen
);
1330 void OutOfProcessInstance::LoadPreviewUrl(const std::string
& url
) {
1331 LoadUrlInternal(url
, &embed_preview_loader_
,
1332 &OutOfProcessInstance::DidOpenPreview
);
1335 void OutOfProcessInstance::LoadUrlInternal(
1336 const std::string
& url
,
1337 pp::URLLoader
* loader
,
1338 void (OutOfProcessInstance::* method
)(int32_t)) {
1339 pp::URLRequestInfo
request(this);
1340 request
.SetURL(url
);
1341 request
.SetMethod("GET");
1343 *loader
= CreateURLLoaderInternal();
1344 pp::CompletionCallback callback
= loader_factory_
.NewCallback(method
);
1345 int rv
= loader
->Open(request
, callback
);
1346 if (rv
!= PP_OK_COMPLETIONPENDING
)
1350 pp::URLLoader
OutOfProcessInstance::CreateURLLoaderInternal() {
1351 pp::URLLoader
loader(this);
1353 const PPB_URLLoaderTrusted
* trusted_interface
=
1354 reinterpret_cast<const PPB_URLLoaderTrusted
*>(
1355 pp::Module::Get()->GetBrowserInterface(
1356 PPB_URLLOADERTRUSTED_INTERFACE
));
1357 if (trusted_interface
)
1358 trusted_interface
->GrantUniversalAccess(loader
.pp_resource());
1362 void OutOfProcessInstance::SetZoom(double scale
) {
1363 double old_zoom
= zoom_
;
1365 OnGeometryChanged(old_zoom
, device_scale_
);
1368 std::string
OutOfProcessInstance::GetLocalizedString(PP_ResourceString id
) {
1369 pp::Var
rv(pp::PDF::GetLocalizedString(this, id
));
1370 if (!rv
.is_string())
1371 return std::string();
1373 return rv
.AsString();
1376 void OutOfProcessInstance::AppendBlankPrintPreviewPages() {
1377 if (print_preview_page_count_
== 0)
1379 engine_
->AppendBlankPages(print_preview_page_count_
);
1380 if (!preview_pages_info_
.empty())
1381 LoadAvailablePreviewPage();
1384 bool OutOfProcessInstance::IsPrintPreview() {
1385 return IsPrintPreviewUrl(url_
);
1388 uint32
OutOfProcessInstance::GetBackgroundColor() {
1389 return background_color_
;
1392 void OutOfProcessInstance::IsSelectingChanged(bool is_selecting
) {
1393 pp::VarDictionary message
;
1394 message
.Set(kType
, kJSSetIsSelectingType
);
1395 message
.Set(kJSIsSelecting
, pp::Var(is_selecting
));
1396 PostMessage(message
);
1399 void OutOfProcessInstance::ProcessPreviewPageInfo(const std::string
& url
,
1400 int dst_page_index
) {
1401 if (!IsPrintPreview())
1404 int src_page_index
= ExtractPrintPreviewPageIndex(url
);
1405 if (src_page_index
< 1)
1408 preview_pages_info_
.push(std::make_pair(url
, dst_page_index
));
1409 LoadAvailablePreviewPage();
1412 void OutOfProcessInstance::LoadAvailablePreviewPage() {
1413 if (preview_pages_info_
.empty() ||
1414 document_load_state_
!= LOAD_STATE_COMPLETE
) {
1418 std::string url
= preview_pages_info_
.front().first
;
1419 int dst_page_index
= preview_pages_info_
.front().second
;
1420 int src_page_index
= ExtractPrintPreviewPageIndex(url
);
1421 if (src_page_index
< 1 ||
1422 dst_page_index
>= print_preview_page_count_
||
1423 preview_document_load_state_
== LOAD_STATE_LOADING
) {
1427 preview_document_load_state_
= LOAD_STATE_LOADING
;
1428 LoadPreviewUrl(url
);
1431 void OutOfProcessInstance::UserMetricsRecordAction(
1432 const std::string
& action
) {
1433 // TODO(raymes): Move this function to PPB_UMA_Private.
1434 pp::PDF::UserMetricsRecordAction(this, pp::Var(action
));
1437 pp::FloatPoint
OutOfProcessInstance::BoundScrollOffsetToDocument(
1438 const pp::FloatPoint
& scroll_offset
) {
1439 float max_x
= document_size_
.width() * zoom_
- plugin_dip_size_
.width();
1440 float x
= std::max(std::min(scroll_offset
.x(), max_x
), 0.0f
);
1441 float min_y
= -top_toolbar_height_
;
1442 float max_y
= document_size_
.height() * zoom_
- plugin_dip_size_
.height();
1443 float y
= std::max(std::min(scroll_offset
.y(), max_y
), min_y
);
1444 return pp::FloatPoint(x
, y
);
1447 } // namespace chrome_pdf