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
= 0xFF424242;
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 kJSBookmarksType
[] = "bookmarks";
82 const char kJSBookmarks
[] = "bookmarks";
83 // Get password arguments (Plugin -> Page)
84 const char kJSGetPasswordType
[] = "getPassword";
85 // Get password complete arguments (Page -> Plugin)
86 const char kJSGetPasswordCompleteType
[] = "getPasswordComplete";
87 const char kJSPassword
[] = "password";
88 // Print (Page -> Plugin)
89 const char kJSPrintType
[] = "print";
90 // Save (Page -> Plugin)
91 const char kJSSaveType
[] = "save";
92 // Go to page (Plugin -> Page)
93 const char kJSGoToPageType
[] = "goToPage";
94 const char kJSPageNumber
[] = "page";
95 // Reset print preview mode (Page -> Plugin)
96 const char kJSResetPrintPreviewModeType
[] = "resetPrintPreviewMode";
97 const char kJSPrintPreviewUrl
[] = "url";
98 const char kJSPrintPreviewGrayscale
[] = "grayscale";
99 const char kJSPrintPreviewPageCount
[] = "pageCount";
100 // Load preview page (Page -> Plugin)
101 const char kJSLoadPreviewPageType
[] = "loadPreviewPage";
102 const char kJSPreviewPageUrl
[] = "url";
103 const char kJSPreviewPageIndex
[] = "index";
104 // Set scroll position (Plugin -> Page)
105 const char kJSSetScrollPositionType
[] = "setScrollPosition";
106 const char kJSPositionX
[] = "x";
107 const char kJSPositionY
[] = "y";
108 // Set translated strings (Plugin -> Page)
109 const char kJSSetTranslatedStringsType
[] = "setTranslatedStrings";
110 const char kJSGetPasswordString
[] = "getPasswordString";
111 const char kJSLoadingString
[] = "loadingString";
112 const char kJSLoadFailedString
[] = "loadFailedString";
113 // Request accessibility JSON data (Page -> Plugin)
114 const char kJSGetAccessibilityJSONType
[] = "getAccessibilityJSON";
115 const char kJSAccessibilityPageNumber
[] = "page";
116 // Reply with accessibility JSON data (Plugin -> Page)
117 const char kJSGetAccessibilityJSONReplyType
[] = "getAccessibilityJSONReply";
118 const char kJSAccessibilityJSON
[] = "json";
119 // Cancel the stream URL request (Plugin -> Page)
120 const char kJSCancelStreamUrlType
[] = "cancelStreamUrl";
121 // Navigate to the given URL (Plugin -> Page)
122 const char kJSNavigateType
[] = "navigate";
123 const char kJSNavigateUrl
[] = "url";
124 const char kJSNavigateNewTab
[] = "newTab";
125 // Open the email editor with the given parameters (Plugin -> Page)
126 const char kJSEmailType
[] = "email";
127 const char kJSEmailTo
[] = "to";
128 const char kJSEmailCc
[] = "cc";
129 const char kJSEmailBcc
[] = "bcc";
130 const char kJSEmailSubject
[] = "subject";
131 const char kJSEmailBody
[] = "body";
132 // Rotation (Page -> Plugin)
133 const char kJSRotateClockwiseType
[] = "rotateClockwise";
134 const char kJSRotateCounterclockwiseType
[] = "rotateCounterclockwise";
135 // Select all text in the document (Page -> Plugin)
136 const char kJSSelectAllType
[] = "selectAll";
137 // Get the selected text in the document (Page -> Plugin)
138 const char kJSGetSelectedTextType
[] = "getSelectedText";
139 // Reply with selected text (Plugin -> Page)
140 const char kJSGetSelectedTextReplyType
[] = "getSelectedTextReply";
141 const char kJSSelectedText
[] = "selectedText";
143 // Get the named destination with the given name (Page -> Plugin)
144 const char KJSGetNamedDestinationType
[] = "getNamedDestination";
145 const char KJSGetNamedDestination
[] = "namedDestination";
146 // Reply with the page number of the named destination (Plugin -> Page)
147 const char kJSGetNamedDestinationReplyType
[] = "getNamedDestinationReply";
148 const char kJSNamedDestinationPageNumber
[] = "pageNumber";
150 // Selecting text in document (Plugin -> Page)
151 const char kJSSetIsSelectingType
[] = "setIsSelecting";
152 const char kJSIsSelecting
[] = "isSelecting";
154 const int kFindResultCooldownMs
= 100;
156 const double kMinZoom
= 0.01;
160 static const char kPPPPdfInterface
[] = PPP_PDF_INTERFACE_1
;
162 PP_Var
GetLinkAtPosition(PP_Instance instance
, PP_Point point
) {
164 void* object
= pp::Instance::GetPerInstanceObject(instance
, kPPPPdfInterface
);
166 var
= static_cast<OutOfProcessInstance
*>(object
)->GetLinkAtPosition(
172 void Transform(PP_Instance instance
, PP_PrivatePageTransformType type
) {
174 pp::Instance::GetPerInstanceObject(instance
, kPPPPdfInterface
);
176 OutOfProcessInstance
* obj_instance
=
177 static_cast<OutOfProcessInstance
*>(object
);
179 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CW
:
180 obj_instance
->RotateClockwise();
182 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CCW
:
183 obj_instance
->RotateCounterclockwise();
189 PP_Bool
GetPrintPresetOptionsFromDocument(
190 PP_Instance instance
,
191 PP_PdfPrintPresetOptions_Dev
* options
) {
192 void* object
= pp::Instance::GetPerInstanceObject(instance
, kPPPPdfInterface
);
194 OutOfProcessInstance
* obj_instance
=
195 static_cast<OutOfProcessInstance
*>(object
);
196 obj_instance
->GetPrintPresetOptionsFromDocument(options
);
201 const PPP_Pdf ppp_private
= {
204 &GetPrintPresetOptionsFromDocument
207 int ExtractPrintPreviewPageIndex(const std::string
& src_url
) {
208 // Sample |src_url| format: chrome://print/id/page_index/print.pdf
209 std::vector
<std::string
> url_substr
;
210 base::SplitString(src_url
.substr(strlen(kChromePrint
)), '/', &url_substr
);
211 if (url_substr
.size() != 3)
214 if (url_substr
[2] != "print.pdf")
218 if (!base::StringToInt(url_substr
[1], &page_index
))
223 bool IsPrintPreviewUrl(const std::string
& url
) {
224 return url
.substr(0, strlen(kChromePrint
)) == kChromePrint
;
227 void ScalePoint(float scale
, pp::Point
* point
) {
228 point
->set_x(static_cast<int>(point
->x() * scale
));
229 point
->set_y(static_cast<int>(point
->y() * scale
));
232 void ScaleRect(float scale
, pp::Rect
* rect
) {
233 int left
= static_cast<int>(floorf(rect
->x() * scale
));
234 int top
= static_cast<int>(floorf(rect
->y() * scale
));
235 int right
= static_cast<int>(ceilf((rect
->x() + rect
->width()) * scale
));
236 int bottom
= static_cast<int>(ceilf((rect
->y() + rect
->height()) * scale
));
237 rect
->SetRect(left
, top
, right
- left
, bottom
- top
);
240 // TODO(raymes): Remove this dependency on VarPrivate/InstancePrivate. It's
241 // needed right now to do a synchronous call to JavaScript, but we could easily
242 // replace this with a custom PPB_PDF function.
243 pp::Var
ModalDialog(const pp::Instance
* instance
,
244 const std::string
& type
,
245 const std::string
& message
,
246 const std::string
& default_answer
) {
247 const PPB_Instance_Private
* interface
=
248 reinterpret_cast<const PPB_Instance_Private
*>(
249 pp::Module::Get()->GetBrowserInterface(
250 PPB_INSTANCE_PRIVATE_INTERFACE
));
251 pp::VarPrivate
window(pp::PASS_REF
,
252 interface
->GetWindowObject(instance
->pp_instance()));
253 if (default_answer
.empty())
254 return window
.Call(type
, message
);
256 return window
.Call(type
, message
, default_answer
);
261 OutOfProcessInstance::OutOfProcessInstance(PP_Instance instance
)
262 : pp::Instance(instance
),
263 pp::Find_Private(this),
264 pp::Printing_Dev(this),
265 pp::Selection_Dev(this),
266 cursor_(PP_CURSORTYPE_POINTER
),
270 paint_manager_(this, this, true),
272 document_load_state_(LOAD_STATE_LOADING
),
273 preview_document_load_state_(LOAD_STATE_COMPLETE
),
275 told_browser_about_unsupported_feature_(false),
276 print_preview_page_count_(0),
277 last_progress_sent_(0),
278 recently_sent_find_update_(false),
279 received_viewport_message_(false),
280 did_call_start_loading_(false),
281 stop_scrolling_(false),
282 background_color_(kBackgroundColor
) {
283 loader_factory_
.Initialize(this);
284 timer_factory_
.Initialize(this);
285 form_factory_
.Initialize(this);
286 print_callback_factory_
.Initialize(this);
287 engine_
.reset(PDFEngine::Create(this));
288 pp::Module::Get()->AddPluginInterface(kPPPPdfInterface
, &ppp_private
);
289 AddPerInstanceObject(kPPPPdfInterface
, this);
291 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_MOUSE
);
292 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_KEYBOARD
);
293 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_TOUCH
);
296 OutOfProcessInstance::~OutOfProcessInstance() {
297 RemovePerInstanceObject(kPPPPdfInterface
, this);
298 // Explicitly reset the PDFEngine during destruction as it may call back into
303 bool OutOfProcessInstance::Init(uint32_t argc
,
305 const char* argv
[]) {
306 // Check if the PDF is being loaded in the PDF chrome extension. We only allow
307 // the plugin to be put into "full frame" mode when it is being loaded in the
308 // extension because this enables some features that we don't want pages
309 // abusing outside of the extension.
310 pp::Var document_url_var
= pp::URLUtil_Dev::Get()->GetDocumentURL(this);
311 std::string document_url
= document_url_var
.is_string() ?
312 document_url_var
.AsString() : std::string();
313 std::string extension_url
= std::string(kChromeExtension
);
315 !document_url
.compare(0, extension_url
.size(), extension_url
);
318 // Check if the plugin is full frame. This is passed in from JS.
319 for (uint32_t i
= 0; i
< argc
; ++i
) {
320 if (strcmp(argn
[i
], "full-frame") == 0) {
327 // Only allow the plugin to handle find requests if it is full frame.
329 SetPluginToHandleFindRequests();
331 // Send translated strings to the extension where they will be displayed.
332 // TODO(raymes): It would be better to get these in the extension directly
333 // through an API but no such API currently exists.
334 pp::VarDictionary translated_strings
;
335 translated_strings
.Set(kType
, kJSSetTranslatedStringsType
);
336 translated_strings
.Set(kJSGetPasswordString
,
337 GetLocalizedString(PP_RESOURCESTRING_PDFGETPASSWORD
));
338 translated_strings
.Set(kJSLoadingString
,
339 GetLocalizedString(PP_RESOURCESTRING_PDFLOADING
));
340 translated_strings
.Set(kJSLoadFailedString
,
341 GetLocalizedString(PP_RESOURCESTRING_PDFLOAD_FAILED
));
342 PostMessage(translated_strings
);
344 text_input_
.reset(new pp::TextInput_Dev(this));
346 const char* stream_url
= NULL
;
347 const char* original_url
= NULL
;
348 const char* headers
= NULL
;
349 bool is_material
= false;
350 for (uint32_t i
= 0; i
< argc
; ++i
) {
351 if (strcmp(argn
[i
], "src") == 0)
352 original_url
= argv
[i
];
353 else if (strcmp(argn
[i
], "stream-url") == 0)
354 stream_url
= argv
[i
];
355 else if (strcmp(argn
[i
], "headers") == 0)
357 else if (strcmp(argn
[i
], "is-material") == 0)
362 background_color_
= kBackgroundColorMaterial
;
364 background_color_
= kBackgroundColor
;
366 // TODO(raymes): This is a hack to ensure that if no headers are passed in
367 // then we get the right MIME type. When the in process plugin is removed we
368 // can fix the document loader properly and remove this hack.
369 if (!headers
|| strcmp(headers
, "") == 0)
370 headers
= "content-type: application/pdf";
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());
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 pp::FloatPoint
scroll_offset_float(scroll_offset
.x(),
604 scroll_offset_float
= BoundScrollOffsetToDocument(scroll_offset_float
);
605 engine_
->ScrolledToXPosition(scroll_offset_float
.x() * device_scale_
);
606 engine_
->ScrolledToYPosition(scroll_offset_float
.y() * device_scale_
);
610 void OutOfProcessInstance::GetPrintPresetOptionsFromDocument(
611 PP_PdfPrintPresetOptions_Dev
* options
) {
612 options
->is_scaling_disabled
= PP_FromBool(IsPrintScalingDisabled());
614 static_cast<PP_PrivateDuplexMode_Dev
>(engine_
->GetDuplexType());
615 options
->copies
= engine_
->GetCopiesToPrint();
616 pp::Size uniform_page_size
;
617 options
->is_page_size_uniform
=
618 PP_FromBool(engine_
->GetPageSizeAndUniformity(&uniform_page_size
));
619 options
->uniform_page_size
= uniform_page_size
;
622 pp::Var
OutOfProcessInstance::GetLinkAtPosition(
623 const pp::Point
& point
) {
624 pp::Point
offset_point(point
);
625 ScalePoint(device_scale_
, &offset_point
);
626 offset_point
.set_x(offset_point
.x() - available_area_
.x());
627 return engine_
->GetLinkAtPosition(offset_point
);
630 pp::Var
OutOfProcessInstance::GetSelectedText(bool html
) {
633 return engine_
->GetSelectedText();
636 uint32_t OutOfProcessInstance::QuerySupportedPrintOutputFormats() {
637 return engine_
->QuerySupportedPrintOutputFormats();
640 int32_t OutOfProcessInstance::PrintBegin(
641 const PP_PrintSettings_Dev
& print_settings
) {
642 // For us num_pages is always equal to the number of pages in the PDF
643 // document irrespective of the printable area.
644 int32_t ret
= engine_
->GetNumberOfPages();
648 uint32_t supported_formats
= engine_
->QuerySupportedPrintOutputFormats();
649 if ((print_settings
.format
& supported_formats
) == 0)
652 print_settings_
.is_printing
= true;
653 print_settings_
.pepper_print_settings
= print_settings
;
654 engine_
->PrintBegin();
658 pp::Resource
OutOfProcessInstance::PrintPages(
659 const PP_PrintPageNumberRange_Dev
* page_ranges
,
660 uint32_t page_range_count
) {
661 if (!print_settings_
.is_printing
)
662 return pp::Resource();
664 print_settings_
.print_pages_called_
= true;
665 return engine_
->PrintPages(page_ranges
, page_range_count
,
666 print_settings_
.pepper_print_settings
);
669 void OutOfProcessInstance::PrintEnd() {
670 if (print_settings_
.print_pages_called_
)
671 UserMetricsRecordAction("PDF.PrintPage");
672 print_settings_
.Clear();
676 bool OutOfProcessInstance::IsPrintScalingDisabled() {
677 return !engine_
->GetPrintScaling();
680 bool OutOfProcessInstance::StartFind(const std::string
& text
,
681 bool case_sensitive
) {
682 engine_
->StartFind(text
.c_str(), case_sensitive
);
686 void OutOfProcessInstance::SelectFindResult(bool forward
) {
687 engine_
->SelectFindResult(forward
);
690 void OutOfProcessInstance::StopFind() {
693 SetTickmarks(tickmarks_
);
696 void OutOfProcessInstance::OnPaint(
697 const std::vector
<pp::Rect
>& paint_rects
,
698 std::vector
<PaintManager::ReadyRect
>* ready
,
699 std::vector
<pp::Rect
>* pending
) {
700 if (image_data_
.is_null()) {
701 DCHECK(plugin_size_
.IsEmpty());
705 first_paint_
= false;
706 pp::Rect rect
= pp::Rect(pp::Point(), image_data_
.size());
707 FillRect(rect
, background_color_
);
708 ready
->push_back(PaintManager::ReadyRect(rect
, image_data_
, true));
711 if (!received_viewport_message_
)
716 for (size_t i
= 0; i
< paint_rects
.size(); i
++) {
717 // Intersect with plugin area since there could be pending invalidates from
718 // when the plugin area was larger.
720 paint_rects
[i
].Intersect(pp::Rect(pp::Point(), plugin_size_
));
724 pp::Rect pdf_rect
= available_area_
.Intersect(rect
);
725 if (!pdf_rect
.IsEmpty()) {
726 pdf_rect
.Offset(available_area_
.x() * -1, 0);
728 std::vector
<pp::Rect
> pdf_ready
;
729 std::vector
<pp::Rect
> pdf_pending
;
730 engine_
->Paint(pdf_rect
, &image_data_
, &pdf_ready
, &pdf_pending
);
731 for (size_t j
= 0; j
< pdf_ready
.size(); ++j
) {
732 pdf_ready
[j
].Offset(available_area_
.point());
734 PaintManager::ReadyRect(pdf_ready
[j
], image_data_
, false));
736 for (size_t j
= 0; j
< pdf_pending
.size(); ++j
) {
737 pdf_pending
[j
].Offset(available_area_
.point());
738 pending
->push_back(pdf_pending
[j
]);
742 for (size_t j
= 0; j
< background_parts_
.size(); ++j
) {
743 pp::Rect intersection
= background_parts_
[j
].location
.Intersect(rect
);
744 if (!intersection
.IsEmpty()) {
745 FillRect(intersection
, background_parts_
[j
].color
);
747 PaintManager::ReadyRect(intersection
, image_data_
, false));
752 engine_
->PostPaint();
755 void OutOfProcessInstance::DidOpen(int32_t result
) {
756 if (result
== PP_OK
) {
757 if (!engine_
->HandleDocumentLoad(embed_loader_
)) {
758 document_load_state_
= LOAD_STATE_LOADING
;
759 DocumentLoadFailed();
761 } else if (result
!= PP_ERROR_ABORTED
) { // Can happen in tests.
763 DocumentLoadFailed();
766 // If it's a progressive load, cancel the stream URL request so that requests
767 // can be made on the original URL.
768 // TODO(raymes): Make this clearer once the in-process plugin is deleted.
769 if (engine_
->IsProgressiveLoad()) {
770 pp::VarDictionary message
;
771 message
.Set(kType
, kJSCancelStreamUrlType
);
772 PostMessage(message
);
776 void OutOfProcessInstance::DidOpenPreview(int32_t result
) {
777 if (result
== PP_OK
) {
778 preview_engine_
.reset(PDFEngine::Create(new PreviewModeClient(this)));
779 preview_engine_
->HandleDocumentLoad(embed_preview_loader_
);
785 void OutOfProcessInstance::OnClientTimerFired(int32_t id
) {
786 engine_
->OnCallback(id
);
789 void OutOfProcessInstance::CalculateBackgroundParts() {
790 background_parts_
.clear();
791 int left_width
= available_area_
.x();
792 int right_start
= available_area_
.right();
793 int right_width
= abs(plugin_size_
.width() - available_area_
.right());
794 int bottom
= std::min(available_area_
.bottom(), plugin_size_
.height());
796 // Add the left, right, and bottom rectangles. Note: we assume only
797 // horizontal centering.
798 BackgroundPart part
= {
799 pp::Rect(0, 0, left_width
, bottom
),
802 if (!part
.location
.IsEmpty())
803 background_parts_
.push_back(part
);
804 part
.location
= pp::Rect(right_start
, 0, right_width
, bottom
);
805 if (!part
.location
.IsEmpty())
806 background_parts_
.push_back(part
);
807 part
.location
= pp::Rect(
808 0, bottom
, plugin_size_
.width(), plugin_size_
.height() - bottom
);
809 if (!part
.location
.IsEmpty())
810 background_parts_
.push_back(part
);
813 int OutOfProcessInstance::GetDocumentPixelWidth() const {
814 return static_cast<int>(ceil(document_size_
.width() * zoom_
* device_scale_
));
817 int OutOfProcessInstance::GetDocumentPixelHeight() const {
818 return static_cast<int>(
819 ceil(document_size_
.height() * zoom_
* device_scale_
));
822 void OutOfProcessInstance::FillRect(const pp::Rect
& rect
, uint32 color
) {
823 DCHECK(!image_data_
.is_null() || rect
.IsEmpty());
824 uint32
* buffer_start
= static_cast<uint32
*>(image_data_
.data());
825 int stride
= image_data_
.stride();
826 uint32
* ptr
= buffer_start
+ rect
.y() * stride
/ 4 + rect
.x();
827 int height
= rect
.height();
828 int width
= rect
.width();
829 for (int y
= 0; y
< height
; ++y
) {
830 for (int x
= 0; x
< width
; ++x
)
836 void OutOfProcessInstance::DocumentSizeUpdated(const pp::Size
& size
) {
837 document_size_
= size
;
839 pp::VarDictionary dimensions
;
840 dimensions
.Set(kType
, kJSDocumentDimensionsType
);
841 dimensions
.Set(kJSDocumentWidth
, pp::Var(document_size_
.width()));
842 dimensions
.Set(kJSDocumentHeight
, pp::Var(document_size_
.height()));
843 pp::VarArray page_dimensions_array
;
844 int num_pages
= engine_
->GetNumberOfPages();
845 for (int i
= 0; i
< num_pages
; ++i
) {
846 pp::Rect page_rect
= engine_
->GetPageRect(i
);
847 pp::VarDictionary page_dimensions
;
848 page_dimensions
.Set(kJSPageX
, pp::Var(page_rect
.x()));
849 page_dimensions
.Set(kJSPageY
, pp::Var(page_rect
.y()));
850 page_dimensions
.Set(kJSPageWidth
, pp::Var(page_rect
.width()));
851 page_dimensions
.Set(kJSPageHeight
, pp::Var(page_rect
.height()));
852 page_dimensions_array
.Set(i
, page_dimensions
);
854 dimensions
.Set(kJSPageDimensions
, page_dimensions_array
);
855 PostMessage(dimensions
);
857 OnGeometryChanged(zoom_
, device_scale_
);
860 void OutOfProcessInstance::Invalidate(const pp::Rect
& rect
) {
861 pp::Rect
offset_rect(rect
);
862 offset_rect
.Offset(available_area_
.point());
863 paint_manager_
.InvalidateRect(offset_rect
);
866 void OutOfProcessInstance::Scroll(const pp::Point
& point
) {
867 if (!image_data_
.is_null())
868 paint_manager_
.ScrollRect(available_area_
, point
);
871 void OutOfProcessInstance::ScrollToX(int x
) {
872 pp::VarDictionary position
;
873 position
.Set(kType
, kJSSetScrollPositionType
);
874 position
.Set(kJSPositionX
, pp::Var(x
/ device_scale_
));
875 PostMessage(position
);
878 void OutOfProcessInstance::ScrollToY(int y
) {
879 pp::VarDictionary position
;
880 position
.Set(kType
, kJSSetScrollPositionType
);
881 position
.Set(kJSPositionY
, pp::Var(y
/ device_scale_
));
882 PostMessage(position
);
885 void OutOfProcessInstance::ScrollToPage(int page
) {
886 if (engine_
->GetNumberOfPages() == 0)
889 pp::VarDictionary message
;
890 message
.Set(kType
, kJSGoToPageType
);
891 message
.Set(kJSPageNumber
, pp::Var(page
));
892 PostMessage(message
);
895 void OutOfProcessInstance::NavigateTo(const std::string
& url
,
896 bool open_in_new_tab
) {
897 pp::VarDictionary message
;
898 message
.Set(kType
, kJSNavigateType
);
899 message
.Set(kJSNavigateUrl
, url
);
900 message
.Set(kJSNavigateNewTab
, open_in_new_tab
);
901 PostMessage(message
);
904 void OutOfProcessInstance::UpdateCursor(PP_CursorType_Dev cursor
) {
905 if (cursor
== cursor_
)
909 const PPB_CursorControl_Dev
* cursor_interface
=
910 reinterpret_cast<const PPB_CursorControl_Dev
*>(
911 pp::Module::Get()->GetBrowserInterface(PPB_CURSOR_CONTROL_DEV_INTERFACE
));
912 if (!cursor_interface
) {
917 cursor_interface
->SetCursor(
918 pp_instance(), cursor_
, pp::ImageData().pp_resource(), NULL
);
921 void OutOfProcessInstance::UpdateTickMarks(
922 const std::vector
<pp::Rect
>& tickmarks
) {
923 float inverse_scale
= 1.0f
/ device_scale_
;
924 std::vector
<pp::Rect
> scaled_tickmarks
= tickmarks
;
925 for (size_t i
= 0; i
< scaled_tickmarks
.size(); i
++)
926 ScaleRect(inverse_scale
, &scaled_tickmarks
[i
]);
927 tickmarks_
= scaled_tickmarks
;
930 void OutOfProcessInstance::NotifyNumberOfFindResultsChanged(int total
,
932 // We don't want to spam the renderer with too many updates to the number of
933 // find results. Don't send an update if we sent one too recently. If it's the
934 // final update, we always send it though.
936 NumberOfFindResultsChanged(total
, final_result
);
937 SetTickmarks(tickmarks_
);
941 if (recently_sent_find_update_
)
944 NumberOfFindResultsChanged(total
, final_result
);
945 SetTickmarks(tickmarks_
);
946 recently_sent_find_update_
= true;
947 pp::CompletionCallback callback
=
948 timer_factory_
.NewCallback(
949 &OutOfProcessInstance::ResetRecentlySentFindUpdate
);
950 pp::Module::Get()->core()->CallOnMainThread(kFindResultCooldownMs
,
954 void OutOfProcessInstance::NotifySelectedFindResultChanged(
955 int current_find_index
) {
956 DCHECK_GE(current_find_index
, 0);
957 SelectedFindResultChanged(current_find_index
);
960 void OutOfProcessInstance::GetDocumentPassword(
961 pp::CompletionCallbackWithOutput
<pp::Var
> callback
) {
962 if (password_callback_
) {
967 password_callback_
.reset(
968 new pp::CompletionCallbackWithOutput
<pp::Var
>(callback
));
969 pp::VarDictionary message
;
970 message
.Set(pp::Var(kType
), pp::Var(kJSGetPasswordType
));
971 PostMessage(message
);
974 void OutOfProcessInstance::Alert(const std::string
& message
) {
975 ModalDialog(this, "alert", message
, std::string());
978 bool OutOfProcessInstance::Confirm(const std::string
& message
) {
979 pp::Var result
= ModalDialog(this, "confirm", message
, std::string());
980 return result
.is_bool() ? result
.AsBool() : false;
983 std::string
OutOfProcessInstance::Prompt(const std::string
& question
,
984 const std::string
& default_answer
) {
985 pp::Var result
= ModalDialog(this, "prompt", question
, default_answer
);
986 return result
.is_string() ? result
.AsString() : std::string();
989 std::string
OutOfProcessInstance::GetURL() {
993 void OutOfProcessInstance::Email(const std::string
& to
,
994 const std::string
& cc
,
995 const std::string
& bcc
,
996 const std::string
& subject
,
997 const std::string
& body
) {
998 pp::VarDictionary message
;
999 message
.Set(pp::Var(kType
), pp::Var(kJSEmailType
));
1000 message
.Set(pp::Var(kJSEmailTo
),
1001 pp::Var(net::EscapeUrlEncodedData(to
, false)));
1002 message
.Set(pp::Var(kJSEmailCc
),
1003 pp::Var(net::EscapeUrlEncodedData(cc
, false)));
1004 message
.Set(pp::Var(kJSEmailBcc
),
1005 pp::Var(net::EscapeUrlEncodedData(bcc
, false)));
1006 message
.Set(pp::Var(kJSEmailSubject
),
1007 pp::Var(net::EscapeUrlEncodedData(subject
, false)));
1008 message
.Set(pp::Var(kJSEmailBody
),
1009 pp::Var(net::EscapeUrlEncodedData(body
, false)));
1010 PostMessage(message
);
1013 void OutOfProcessInstance::Print() {
1014 if (!engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
) &&
1015 !engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY
)) {
1019 pp::CompletionCallback callback
=
1020 print_callback_factory_
.NewCallback(&OutOfProcessInstance::OnPrint
);
1021 pp::Module::Get()->core()->CallOnMainThread(0, callback
);
1024 void OutOfProcessInstance::OnPrint(int32_t) {
1025 pp::PDF::Print(this);
1028 void OutOfProcessInstance::SubmitForm(const std::string
& url
,
1031 pp::URLRequestInfo
request(this);
1032 request
.SetURL(url
);
1033 request
.SetMethod("POST");
1034 request
.AppendDataToBody(reinterpret_cast<const char*>(data
), length
);
1036 pp::CompletionCallback callback
=
1037 form_factory_
.NewCallback(&OutOfProcessInstance::FormDidOpen
);
1038 form_loader_
= CreateURLLoaderInternal();
1039 int rv
= form_loader_
.Open(request
, callback
);
1040 if (rv
!= PP_OK_COMPLETIONPENDING
)
1044 void OutOfProcessInstance::FormDidOpen(int32_t result
) {
1045 // TODO: inform the user of success/failure.
1046 if (result
!= PP_OK
) {
1051 std::string
OutOfProcessInstance::ShowFileSelectionDialog() {
1052 // Seems like very low priority to implement, since the pdf has no way to get
1053 // the file data anyways. Javascript doesn't let you do this synchronously.
1055 return std::string();
1058 pp::URLLoader
OutOfProcessInstance::CreateURLLoader() {
1060 if (!did_call_start_loading_
) {
1061 did_call_start_loading_
= true;
1062 pp::PDF::DidStartLoading(this);
1065 // Disable save and print until the document is fully loaded, since they
1066 // would generate an incomplete document. Need to do this each time we
1067 // call DidStartLoading since that resets the content restrictions.
1068 pp::PDF::SetContentRestriction(this, CONTENT_RESTRICTION_SAVE
|
1069 CONTENT_RESTRICTION_PRINT
);
1072 return CreateURLLoaderInternal();
1075 void OutOfProcessInstance::ScheduleCallback(int id
, int delay_in_ms
) {
1076 pp::CompletionCallback callback
=
1077 timer_factory_
.NewCallback(&OutOfProcessInstance::OnClientTimerFired
);
1078 pp::Module::Get()->core()->CallOnMainThread(delay_in_ms
, callback
, id
);
1081 void OutOfProcessInstance::SearchString(const base::char16
* string
,
1082 const base::char16
* term
,
1083 bool case_sensitive
,
1084 std::vector
<SearchStringResult
>* results
) {
1085 PP_PrivateFindResult
* pp_results
;
1087 pp::PDF::SearchString(
1089 reinterpret_cast<const unsigned short*>(string
),
1090 reinterpret_cast<const unsigned short*>(term
),
1095 results
->resize(count
);
1096 for (int i
= 0; i
< count
; ++i
) {
1097 (*results
)[i
].start_index
= pp_results
[i
].start_index
;
1098 (*results
)[i
].length
= pp_results
[i
].length
;
1101 pp::Memory_Dev memory
;
1102 memory
.MemFree(pp_results
);
1105 void OutOfProcessInstance::DocumentPaintOccurred() {
1108 void OutOfProcessInstance::DocumentLoadComplete(int page_count
) {
1109 // Clear focus state for OSK.
1110 FormTextFieldFocusChange(false);
1112 DCHECK(document_load_state_
== LOAD_STATE_LOADING
);
1113 document_load_state_
= LOAD_STATE_COMPLETE
;
1114 UserMetricsRecordAction("PDF.LoadSuccess");
1116 // Note: If we are in print preview mode the scroll location is retained
1117 // across document loads so we don't want to scroll again and override it.
1118 if (IsPrintPreview()) {
1119 AppendBlankPrintPreviewPages();
1120 OnGeometryChanged(0, 0);
1123 pp::VarDictionary bookmarks_message
;
1124 bookmarks_message
.Set(pp::Var(kType
), pp::Var(kJSBookmarksType
));
1125 bookmarks_message
.Set(pp::Var(kJSBookmarks
), engine_
->GetBookmarks());
1126 PostMessage(bookmarks_message
);
1128 pp::VarDictionary progress_message
;
1129 progress_message
.Set(pp::Var(kType
), pp::Var(kJSLoadProgressType
));
1130 progress_message
.Set(pp::Var(kJSProgressPercentage
), pp::Var(100));
1131 PostMessage(progress_message
);
1136 if (did_call_start_loading_
) {
1137 pp::PDF::DidStopLoading(this);
1138 did_call_start_loading_
= false;
1141 int content_restrictions
=
1142 CONTENT_RESTRICTION_CUT
| CONTENT_RESTRICTION_PASTE
;
1143 if (!engine_
->HasPermission(PDFEngine::PERMISSION_COPY
))
1144 content_restrictions
|= CONTENT_RESTRICTION_COPY
;
1146 pp::PDF::SetContentRestriction(this, content_restrictions
);
1148 uma_
.HistogramCustomCounts("PDF.PageCount", page_count
,
1152 void OutOfProcessInstance::RotateClockwise() {
1153 engine_
->RotateClockwise();
1156 void OutOfProcessInstance::RotateCounterclockwise() {
1157 engine_
->RotateCounterclockwise();
1160 void OutOfProcessInstance::PreviewDocumentLoadComplete() {
1161 if (preview_document_load_state_
!= LOAD_STATE_LOADING
||
1162 preview_pages_info_
.empty()) {
1166 preview_document_load_state_
= LOAD_STATE_COMPLETE
;
1168 int dest_page_index
= preview_pages_info_
.front().second
;
1169 int src_page_index
=
1170 ExtractPrintPreviewPageIndex(preview_pages_info_
.front().first
);
1171 if (src_page_index
> 0 && dest_page_index
> -1 && preview_engine_
.get())
1172 engine_
->AppendPage(preview_engine_
.get(), dest_page_index
);
1174 preview_pages_info_
.pop();
1175 // |print_preview_page_count_| is not updated yet. Do not load any
1176 // other preview pages till we get this information.
1177 if (print_preview_page_count_
== 0)
1180 if (preview_pages_info_
.size())
1181 LoadAvailablePreviewPage();
1184 void OutOfProcessInstance::DocumentLoadFailed() {
1185 DCHECK(document_load_state_
== LOAD_STATE_LOADING
);
1186 UserMetricsRecordAction("PDF.LoadFailure");
1188 if (did_call_start_loading_
) {
1189 pp::PDF::DidStopLoading(this);
1190 did_call_start_loading_
= false;
1193 document_load_state_
= LOAD_STATE_FAILED
;
1194 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
1196 // Send a progress value of -1 to indicate a failure.
1197 pp::VarDictionary message
;
1198 message
.Set(pp::Var(kType
), pp::Var(kJSLoadProgressType
));
1199 message
.Set(pp::Var(kJSProgressPercentage
), pp::Var(-1));
1200 PostMessage(message
);
1203 void OutOfProcessInstance::PreviewDocumentLoadFailed() {
1204 UserMetricsRecordAction("PDF.PreviewDocumentLoadFailure");
1205 if (preview_document_load_state_
!= LOAD_STATE_LOADING
||
1206 preview_pages_info_
.empty()) {
1210 preview_document_load_state_
= LOAD_STATE_FAILED
;
1211 preview_pages_info_
.pop();
1213 if (preview_pages_info_
.size())
1214 LoadAvailablePreviewPage();
1217 pp::Instance
* OutOfProcessInstance::GetPluginInstance() {
1221 void OutOfProcessInstance::DocumentHasUnsupportedFeature(
1222 const std::string
& feature
) {
1223 std::string
metric("PDF_Unsupported_");
1225 if (!unsupported_features_reported_
.count(metric
)) {
1226 unsupported_features_reported_
.insert(metric
);
1227 UserMetricsRecordAction(metric
);
1230 // Since we use an info bar, only do this for full frame plugins..
1234 if (told_browser_about_unsupported_feature_
)
1236 told_browser_about_unsupported_feature_
= true;
1238 pp::PDF::HasUnsupportedFeature(this);
1241 void OutOfProcessInstance::DocumentLoadProgress(uint32 available
,
1243 double progress
= 0.0;
1244 if (doc_size
== 0) {
1245 // Document size is unknown. Use heuristics.
1246 // We'll make progress logarithmic from 0 to 100M.
1247 static const double kFactor
= log(100000000.0) / 100.0;
1248 if (available
> 0) {
1249 progress
= log(static_cast<double>(available
)) / kFactor
;
1250 if (progress
> 100.0)
1254 progress
= 100.0 * static_cast<double>(available
) / doc_size
;
1257 // We send 100% load progress in DocumentLoadComplete.
1258 if (progress
>= 100)
1261 // Avoid sending too many progress messages over PostMessage.
1262 if (progress
> last_progress_sent_
+ 1) {
1263 last_progress_sent_
= progress
;
1264 pp::VarDictionary message
;
1265 message
.Set(pp::Var(kType
), pp::Var(kJSLoadProgressType
));
1266 message
.Set(pp::Var(kJSProgressPercentage
), pp::Var(progress
));
1267 PostMessage(message
);
1271 void OutOfProcessInstance::FormTextFieldFocusChange(bool in_focus
) {
1272 if (!text_input_
.get())
1275 text_input_
->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_TEXT
);
1277 text_input_
->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_NONE
);
1280 void OutOfProcessInstance::ResetRecentlySentFindUpdate(int32_t /* unused */) {
1281 recently_sent_find_update_
= false;
1284 void OutOfProcessInstance::OnGeometryChanged(double old_zoom
,
1285 float old_device_scale
) {
1286 if (zoom_
!= old_zoom
|| device_scale_
!= old_device_scale
)
1287 engine_
->ZoomUpdated(zoom_
* device_scale_
);
1289 available_area_
= pp::Rect(plugin_size_
);
1290 int doc_width
= GetDocumentPixelWidth();
1291 if (doc_width
< available_area_
.width()) {
1292 available_area_
.Offset((available_area_
.width() - doc_width
) / 2, 0);
1293 available_area_
.set_width(doc_width
);
1295 int doc_height
= GetDocumentPixelHeight();
1296 if (doc_height
< available_area_
.height()) {
1297 available_area_
.set_height(doc_height
);
1300 CalculateBackgroundParts();
1301 engine_
->PageOffsetUpdated(available_area_
.point());
1302 engine_
->PluginSizeUpdated(available_area_
.size());
1304 if (!document_size_
.GetArea())
1306 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
1309 void OutOfProcessInstance::LoadUrl(const std::string
& url
) {
1310 LoadUrlInternal(url
, &embed_loader_
, &OutOfProcessInstance::DidOpen
);
1313 void OutOfProcessInstance::LoadPreviewUrl(const std::string
& url
) {
1314 LoadUrlInternal(url
, &embed_preview_loader_
,
1315 &OutOfProcessInstance::DidOpenPreview
);
1318 void OutOfProcessInstance::LoadUrlInternal(
1319 const std::string
& url
,
1320 pp::URLLoader
* loader
,
1321 void (OutOfProcessInstance::* method
)(int32_t)) {
1322 pp::URLRequestInfo
request(this);
1323 request
.SetURL(url
);
1324 request
.SetMethod("GET");
1326 *loader
= CreateURLLoaderInternal();
1327 pp::CompletionCallback callback
= loader_factory_
.NewCallback(method
);
1328 int rv
= loader
->Open(request
, callback
);
1329 if (rv
!= PP_OK_COMPLETIONPENDING
)
1333 pp::URLLoader
OutOfProcessInstance::CreateURLLoaderInternal() {
1334 pp::URLLoader
loader(this);
1336 const PPB_URLLoaderTrusted
* trusted_interface
=
1337 reinterpret_cast<const PPB_URLLoaderTrusted
*>(
1338 pp::Module::Get()->GetBrowserInterface(
1339 PPB_URLLOADERTRUSTED_INTERFACE
));
1340 if (trusted_interface
)
1341 trusted_interface
->GrantUniversalAccess(loader
.pp_resource());
1345 void OutOfProcessInstance::SetZoom(double scale
) {
1346 double old_zoom
= zoom_
;
1348 OnGeometryChanged(old_zoom
, device_scale_
);
1351 std::string
OutOfProcessInstance::GetLocalizedString(PP_ResourceString id
) {
1352 pp::Var
rv(pp::PDF::GetLocalizedString(this, id
));
1353 if (!rv
.is_string())
1354 return std::string();
1356 return rv
.AsString();
1359 void OutOfProcessInstance::AppendBlankPrintPreviewPages() {
1360 if (print_preview_page_count_
== 0)
1362 engine_
->AppendBlankPages(print_preview_page_count_
);
1363 if (preview_pages_info_
.size() > 0)
1364 LoadAvailablePreviewPage();
1367 bool OutOfProcessInstance::IsPrintPreview() {
1368 return IsPrintPreviewUrl(url_
);
1371 uint32
OutOfProcessInstance::GetBackgroundColor() {
1372 return background_color_
;
1375 void OutOfProcessInstance::IsSelectingChanged(bool is_selecting
) {
1376 pp::VarDictionary message
;
1377 message
.Set(kType
, kJSSetIsSelectingType
);
1378 message
.Set(kJSIsSelecting
, pp::Var(is_selecting
));
1379 PostMessage(message
);
1382 void OutOfProcessInstance::ProcessPreviewPageInfo(const std::string
& url
,
1383 int dst_page_index
) {
1384 if (!IsPrintPreview())
1387 int src_page_index
= ExtractPrintPreviewPageIndex(url
);
1388 if (src_page_index
< 1)
1391 preview_pages_info_
.push(std::make_pair(url
, dst_page_index
));
1392 LoadAvailablePreviewPage();
1395 void OutOfProcessInstance::LoadAvailablePreviewPage() {
1396 if (preview_pages_info_
.size() <= 0 ||
1397 document_load_state_
!= LOAD_STATE_COMPLETE
) {
1401 std::string url
= preview_pages_info_
.front().first
;
1402 int dst_page_index
= preview_pages_info_
.front().second
;
1403 int src_page_index
= ExtractPrintPreviewPageIndex(url
);
1404 if (src_page_index
< 1 ||
1405 dst_page_index
>= print_preview_page_count_
||
1406 preview_document_load_state_
== LOAD_STATE_LOADING
) {
1410 preview_document_load_state_
= LOAD_STATE_LOADING
;
1411 LoadPreviewUrl(url
);
1414 void OutOfProcessInstance::UserMetricsRecordAction(
1415 const std::string
& action
) {
1416 // TODO(raymes): Move this function to PPB_UMA_Private.
1417 pp::PDF::UserMetricsRecordAction(this, pp::Var(action
));
1420 pp::FloatPoint
OutOfProcessInstance::BoundScrollOffsetToDocument(
1421 const pp::FloatPoint
& scroll_offset
) {
1422 float max_x
= document_size_
.width() * zoom_
- plugin_dip_size_
.width();
1423 float x
= std::max(std::min(scroll_offset
.x(), max_x
), 0.0f
);
1424 float max_y
= document_size_
.height() * zoom_
- plugin_dip_size_
.height();
1425 float y
= std::max(std::min(scroll_offset
.y(), max_y
), 0.0f
);
1426 return pp::FloatPoint(x
, y
);
1429 } // namespace chrome_pdf