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
= 0xFFEEEEEE;
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);
300 bool OutOfProcessInstance::Init(uint32_t argc
,
302 const char* argv
[]) {
303 // Check if the PDF is being loaded in the PDF chrome extension. We only allow
304 // the plugin to be put into "full frame" mode when it is being loaded in the
305 // extension because this enables some features that we don't want pages
306 // abusing outside of the extension.
307 pp::Var document_url_var
= pp::URLUtil_Dev::Get()->GetDocumentURL(this);
308 std::string document_url
= document_url_var
.is_string() ?
309 document_url_var
.AsString() : std::string();
310 std::string extension_url
= std::string(kChromeExtension
);
312 !document_url
.compare(0, extension_url
.size(), extension_url
);
315 // Check if the plugin is full frame. This is passed in from JS.
316 for (uint32_t i
= 0; i
< argc
; ++i
) {
317 if (strcmp(argn
[i
], "full-frame") == 0) {
324 // Only allow the plugin to handle find requests if it is full frame.
326 SetPluginToHandleFindRequests();
328 // Send translated strings to the extension where they will be displayed.
329 // TODO(raymes): It would be better to get these in the extension directly
330 // through an API but no such API currently exists.
331 pp::VarDictionary translated_strings
;
332 translated_strings
.Set(kType
, kJSSetTranslatedStringsType
);
333 translated_strings
.Set(kJSGetPasswordString
,
334 GetLocalizedString(PP_RESOURCESTRING_PDFGETPASSWORD
));
335 translated_strings
.Set(kJSLoadingString
,
336 GetLocalizedString(PP_RESOURCESTRING_PDFLOADING
));
337 translated_strings
.Set(kJSLoadFailedString
,
338 GetLocalizedString(PP_RESOURCESTRING_PDFLOAD_FAILED
));
339 PostMessage(translated_strings
);
341 text_input_
.reset(new pp::TextInput_Dev(this));
343 const char* stream_url
= NULL
;
344 const char* original_url
= NULL
;
345 const char* headers
= NULL
;
346 bool is_material
= false;
347 for (uint32_t i
= 0; i
< argc
; ++i
) {
348 if (strcmp(argn
[i
], "src") == 0)
349 original_url
= argv
[i
];
350 else if (strcmp(argn
[i
], "stream-url") == 0)
351 stream_url
= argv
[i
];
352 else if (strcmp(argn
[i
], "headers") == 0)
354 else if (strcmp(argn
[i
], "is-material") == 0)
359 background_color_
= kBackgroundColorMaterial
;
361 background_color_
= kBackgroundColor
;
363 // TODO(raymes): This is a hack to ensure that if no headers are passed in
364 // then we get the right MIME type. When the in process plugin is removed we
365 // can fix the document loader properly and remove this hack.
366 if (!headers
|| strcmp(headers
, "") == 0)
367 headers
= "content-type: application/pdf";
373 stream_url
= original_url
;
375 // If we're in print preview mode we don't need to load the document yet.
376 // A |kJSResetPrintPreviewModeType| message will be sent to the plugin letting
377 // it know the url to load. By not loading here we avoid loading the same
379 if (IsPrintPreviewUrl(original_url
))
384 return engine_
->New(original_url
, headers
);
387 void OutOfProcessInstance::HandleMessage(const pp::Var
& message
) {
388 pp::VarDictionary
dict(message
);
389 if (!dict
.Get(kType
).is_string()) {
394 std::string type
= dict
.Get(kType
).AsString();
396 if (type
== kJSViewportType
&&
397 dict
.Get(pp::Var(kJSXOffset
)).is_number() &&
398 dict
.Get(pp::Var(kJSYOffset
)).is_number() &&
399 dict
.Get(pp::Var(kJSZoom
)).is_number()) {
400 received_viewport_message_
= true;
401 stop_scrolling_
= false;
402 double zoom
= dict
.Get(pp::Var(kJSZoom
)).AsDouble();
403 pp::FloatPoint
scroll_offset(dict
.Get(pp::Var(kJSXOffset
)).AsDouble(),
404 dict
.Get(pp::Var(kJSYOffset
)).AsDouble());
406 // Bound the input parameters.
407 zoom
= std::max(kMinZoom
, zoom
);
409 scroll_offset
= BoundScrollOffsetToDocument(scroll_offset
);
410 engine_
->ScrolledToXPosition(scroll_offset
.x() * device_scale_
);
411 engine_
->ScrolledToYPosition(scroll_offset
.y() * device_scale_
);
412 } else if (type
== kJSGetPasswordCompleteType
&&
413 dict
.Get(pp::Var(kJSPassword
)).is_string()) {
414 if (password_callback_
) {
415 pp::CompletionCallbackWithOutput
<pp::Var
> callback
= *password_callback_
;
416 password_callback_
.reset();
417 *callback
.output() = dict
.Get(pp::Var(kJSPassword
)).pp_var();
422 } else if (type
== kJSPrintType
) {
424 } else if (type
== kJSSaveType
) {
425 pp::PDF::SaveAs(this);
426 } else if (type
== kJSRotateClockwiseType
) {
428 } else if (type
== kJSRotateCounterclockwiseType
) {
429 RotateCounterclockwise();
430 } else if (type
== kJSSelectAllType
) {
431 engine_
->SelectAll();
432 } else if (type
== kJSResetPrintPreviewModeType
&&
433 dict
.Get(pp::Var(kJSPrintPreviewUrl
)).is_string() &&
434 dict
.Get(pp::Var(kJSPrintPreviewGrayscale
)).is_bool() &&
435 dict
.Get(pp::Var(kJSPrintPreviewPageCount
)).is_int()) {
436 url_
= dict
.Get(pp::Var(kJSPrintPreviewUrl
)).AsString();
437 preview_pages_info_
= std::queue
<PreviewPageInfo
>();
438 preview_document_load_state_
= LOAD_STATE_COMPLETE
;
439 document_load_state_
= LOAD_STATE_LOADING
;
441 preview_engine_
.reset();
442 engine_
.reset(PDFEngine::Create(this));
443 engine_
->SetGrayscale(dict
.Get(pp::Var(kJSPrintPreviewGrayscale
)).AsBool());
444 engine_
->New(url_
.c_str());
446 print_preview_page_count_
=
447 std::max(dict
.Get(pp::Var(kJSPrintPreviewPageCount
)).AsInt(), 0);
449 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
450 } else if (type
== kJSLoadPreviewPageType
&&
451 dict
.Get(pp::Var(kJSPreviewPageUrl
)).is_string() &&
452 dict
.Get(pp::Var(kJSPreviewPageIndex
)).is_int()) {
453 ProcessPreviewPageInfo(dict
.Get(pp::Var(kJSPreviewPageUrl
)).AsString(),
454 dict
.Get(pp::Var(kJSPreviewPageIndex
)).AsInt());
455 } else if (type
== kJSGetAccessibilityJSONType
) {
456 pp::VarDictionary reply
;
457 reply
.Set(pp::Var(kType
), pp::Var(kJSGetAccessibilityJSONReplyType
));
458 if (dict
.Get(pp::Var(kJSAccessibilityPageNumber
)).is_int()) {
459 int page
= dict
.Get(pp::Var(kJSAccessibilityPageNumber
)).AsInt();
460 reply
.Set(pp::Var(kJSAccessibilityJSON
),
461 pp::Var(engine_
->GetPageAsJSON(page
)));
463 base::DictionaryValue node
;
464 node
.SetInteger(kAccessibleNumberOfPages
, engine_
->GetNumberOfPages());
465 node
.SetBoolean(kAccessibleLoaded
,
466 document_load_state_
!= LOAD_STATE_LOADING
);
467 bool has_permissions
=
468 engine_
->HasPermission(PDFEngine::PERMISSION_COPY
) ||
469 engine_
->HasPermission(PDFEngine::PERMISSION_COPY_ACCESSIBLE
);
470 node
.SetBoolean(kAccessibleCopyable
, has_permissions
);
472 base::JSONWriter::Write(&node
, &json
);
473 reply
.Set(pp::Var(kJSAccessibilityJSON
), pp::Var(json
));
476 } else if (type
== kJSStopScrollingType
) {
477 stop_scrolling_
= true;
478 } else if (type
== kJSGetSelectedTextType
) {
479 std::string selected_text
= engine_
->GetSelectedText();
480 // Always return unix newlines to JS.
481 base::ReplaceChars(selected_text
, "\r", std::string(), &selected_text
);
482 pp::VarDictionary reply
;
483 reply
.Set(pp::Var(kType
), pp::Var(kJSGetSelectedTextReplyType
));
484 reply
.Set(pp::Var(kJSSelectedText
), selected_text
);
486 } else if (type
== KJSGetNamedDestinationType
&&
487 dict
.Get(pp::Var(KJSGetNamedDestination
)).is_string()) {
488 int page_number
= engine_
->GetNamedDestinationPage(
489 dict
.Get(pp::Var(KJSGetNamedDestination
)).AsString());
490 pp::VarDictionary reply
;
491 reply
.Set(pp::Var(kType
), pp::Var(kJSGetNamedDestinationReplyType
));
492 if (page_number
>= 0)
493 reply
.Set(pp::Var(kJSNamedDestinationPageNumber
), page_number
);
500 bool OutOfProcessInstance::HandleInputEvent(
501 const pp::InputEvent
& event
) {
502 // To simplify things, convert the event into device coordinates if it is
504 pp::InputEvent
event_device_res(event
);
506 pp::MouseInputEvent
mouse_event(event
);
507 if (!mouse_event
.is_null()) {
508 pp::Point point
= mouse_event
.GetPosition();
509 pp::Point movement
= mouse_event
.GetMovement();
510 ScalePoint(device_scale_
, &point
);
511 ScalePoint(device_scale_
, &movement
);
512 mouse_event
= pp::MouseInputEvent(
515 event
.GetTimeStamp(),
516 event
.GetModifiers(),
517 mouse_event
.GetButton(),
519 mouse_event
.GetClickCount(),
521 event_device_res
= mouse_event
;
525 pp::InputEvent
offset_event(event_device_res
);
526 switch (offset_event
.GetType()) {
527 case PP_INPUTEVENT_TYPE_MOUSEDOWN
:
528 case PP_INPUTEVENT_TYPE_MOUSEUP
:
529 case PP_INPUTEVENT_TYPE_MOUSEMOVE
:
530 case PP_INPUTEVENT_TYPE_MOUSEENTER
:
531 case PP_INPUTEVENT_TYPE_MOUSELEAVE
: {
532 pp::MouseInputEvent
mouse_event(event_device_res
);
533 pp::MouseInputEvent
mouse_event_dip(event
);
534 pp::Point point
= mouse_event
.GetPosition();
535 point
.set_x(point
.x() - available_area_
.x());
536 offset_event
= pp::MouseInputEvent(
539 event
.GetTimeStamp(),
540 event
.GetModifiers(),
541 mouse_event
.GetButton(),
543 mouse_event
.GetClickCount(),
544 mouse_event
.GetMovement());
550 if (engine_
->HandleEvent(offset_event
))
553 // TODO(raymes): Implement this scroll behavior in JS:
554 // When click+dragging, scroll the document correctly.
556 // Return true for unhandled clicks so the plugin takes focus.
557 return (event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN
);
560 void OutOfProcessInstance::DidChangeView(const pp::View
& view
) {
561 pp::Rect
view_rect(view
.GetRect());
562 float old_device_scale
= device_scale_
;
563 float device_scale
= view
.GetDeviceScale();
564 pp::Size
view_device_size(view_rect
.width() * device_scale
,
565 view_rect
.height() * device_scale
);
567 if (view_device_size
!= plugin_size_
|| device_scale
!= device_scale_
) {
568 device_scale_
= device_scale
;
569 plugin_dip_size_
= view_rect
.size();
570 plugin_size_
= view_device_size
;
572 paint_manager_
.SetSize(view_device_size
, device_scale_
);
574 pp::Size new_image_data_size
= PaintManager::GetNewContextSize(
577 if (new_image_data_size
!= image_data_
.size()) {
578 image_data_
= pp::ImageData(this,
579 PP_IMAGEDATAFORMAT_BGRA_PREMUL
,
585 if (image_data_
.is_null()) {
586 DCHECK(plugin_size_
.IsEmpty());
590 OnGeometryChanged(zoom_
, old_device_scale
);
593 if (!stop_scrolling_
) {
594 pp::Point
scroll_offset(view
.GetScrollOffset());
595 pp::FloatPoint
scroll_offset_float(scroll_offset
.x(),
597 scroll_offset_float
= BoundScrollOffsetToDocument(scroll_offset_float
);
598 engine_
->ScrolledToXPosition(scroll_offset_float
.x() * device_scale_
);
599 engine_
->ScrolledToYPosition(scroll_offset_float
.y() * device_scale_
);
603 void OutOfProcessInstance::GetPrintPresetOptionsFromDocument(
604 PP_PdfPrintPresetOptions_Dev
* options
) {
605 options
->is_scaling_disabled
= PP_FromBool(IsPrintScalingDisabled());
606 options
->copies
= engine_
->GetCopiesToPrint();
609 pp::Var
OutOfProcessInstance::GetLinkAtPosition(
610 const pp::Point
& point
) {
611 pp::Point
offset_point(point
);
612 ScalePoint(device_scale_
, &offset_point
);
613 offset_point
.set_x(offset_point
.x() - available_area_
.x());
614 return engine_
->GetLinkAtPosition(offset_point
);
617 pp::Var
OutOfProcessInstance::GetSelectedText(bool html
) {
620 return engine_
->GetSelectedText();
623 uint32_t OutOfProcessInstance::QuerySupportedPrintOutputFormats() {
624 return engine_
->QuerySupportedPrintOutputFormats();
627 int32_t OutOfProcessInstance::PrintBegin(
628 const PP_PrintSettings_Dev
& print_settings
) {
629 // For us num_pages is always equal to the number of pages in the PDF
630 // document irrespective of the printable area.
631 int32_t ret
= engine_
->GetNumberOfPages();
635 uint32_t supported_formats
= engine_
->QuerySupportedPrintOutputFormats();
636 if ((print_settings
.format
& supported_formats
) == 0)
639 print_settings_
.is_printing
= true;
640 print_settings_
.pepper_print_settings
= print_settings
;
641 engine_
->PrintBegin();
645 pp::Resource
OutOfProcessInstance::PrintPages(
646 const PP_PrintPageNumberRange_Dev
* page_ranges
,
647 uint32_t page_range_count
) {
648 if (!print_settings_
.is_printing
)
649 return pp::Resource();
651 print_settings_
.print_pages_called_
= true;
652 return engine_
->PrintPages(page_ranges
, page_range_count
,
653 print_settings_
.pepper_print_settings
);
656 void OutOfProcessInstance::PrintEnd() {
657 if (print_settings_
.print_pages_called_
)
658 UserMetricsRecordAction("PDF.PrintPage");
659 print_settings_
.Clear();
663 bool OutOfProcessInstance::IsPrintScalingDisabled() {
664 return !engine_
->GetPrintScaling();
667 bool OutOfProcessInstance::StartFind(const std::string
& text
,
668 bool case_sensitive
) {
669 engine_
->StartFind(text
.c_str(), case_sensitive
);
673 void OutOfProcessInstance::SelectFindResult(bool forward
) {
674 engine_
->SelectFindResult(forward
);
677 void OutOfProcessInstance::StopFind() {
680 SetTickmarks(tickmarks_
);
683 void OutOfProcessInstance::OnPaint(
684 const std::vector
<pp::Rect
>& paint_rects
,
685 std::vector
<PaintManager::ReadyRect
>* ready
,
686 std::vector
<pp::Rect
>* pending
) {
687 if (image_data_
.is_null()) {
688 DCHECK(plugin_size_
.IsEmpty());
692 first_paint_
= false;
693 pp::Rect rect
= pp::Rect(pp::Point(), image_data_
.size());
694 FillRect(rect
, background_color_
);
695 ready
->push_back(PaintManager::ReadyRect(rect
, image_data_
, true));
698 if (!received_viewport_message_
)
703 for (size_t i
= 0; i
< paint_rects
.size(); i
++) {
704 // Intersect with plugin area since there could be pending invalidates from
705 // when the plugin area was larger.
707 paint_rects
[i
].Intersect(pp::Rect(pp::Point(), plugin_size_
));
711 pp::Rect pdf_rect
= available_area_
.Intersect(rect
);
712 if (!pdf_rect
.IsEmpty()) {
713 pdf_rect
.Offset(available_area_
.x() * -1, 0);
715 std::vector
<pp::Rect
> pdf_ready
;
716 std::vector
<pp::Rect
> pdf_pending
;
717 engine_
->Paint(pdf_rect
, &image_data_
, &pdf_ready
, &pdf_pending
);
718 for (size_t j
= 0; j
< pdf_ready
.size(); ++j
) {
719 pdf_ready
[j
].Offset(available_area_
.point());
721 PaintManager::ReadyRect(pdf_ready
[j
], image_data_
, false));
723 for (size_t j
= 0; j
< pdf_pending
.size(); ++j
) {
724 pdf_pending
[j
].Offset(available_area_
.point());
725 pending
->push_back(pdf_pending
[j
]);
729 for (size_t j
= 0; j
< background_parts_
.size(); ++j
) {
730 pp::Rect intersection
= background_parts_
[j
].location
.Intersect(rect
);
731 if (!intersection
.IsEmpty()) {
732 FillRect(intersection
, background_parts_
[j
].color
);
734 PaintManager::ReadyRect(intersection
, image_data_
, false));
739 engine_
->PostPaint();
742 void OutOfProcessInstance::DidOpen(int32_t result
) {
743 if (result
== PP_OK
) {
744 if (!engine_
->HandleDocumentLoad(embed_loader_
)) {
745 document_load_state_
= LOAD_STATE_LOADING
;
746 DocumentLoadFailed();
748 } else if (result
!= PP_ERROR_ABORTED
) { // Can happen in tests.
750 DocumentLoadFailed();
753 // If it's a progressive load, cancel the stream URL request so that requests
754 // can be made on the original URL.
755 // TODO(raymes): Make this clearer once the in-process plugin is deleted.
756 if (engine_
->IsProgressiveLoad()) {
757 pp::VarDictionary message
;
758 message
.Set(kType
, kJSCancelStreamUrlType
);
759 PostMessage(message
);
763 void OutOfProcessInstance::DidOpenPreview(int32_t result
) {
764 if (result
== PP_OK
) {
765 preview_engine_
.reset(PDFEngine::Create(new PreviewModeClient(this)));
766 preview_engine_
->HandleDocumentLoad(embed_preview_loader_
);
772 void OutOfProcessInstance::OnClientTimerFired(int32_t id
) {
773 engine_
->OnCallback(id
);
776 void OutOfProcessInstance::CalculateBackgroundParts() {
777 background_parts_
.clear();
778 int left_width
= available_area_
.x();
779 int right_start
= available_area_
.right();
780 int right_width
= abs(plugin_size_
.width() - available_area_
.right());
781 int bottom
= std::min(available_area_
.bottom(), plugin_size_
.height());
783 // Add the left, right, and bottom rectangles. Note: we assume only
784 // horizontal centering.
785 BackgroundPart part
= {
786 pp::Rect(0, 0, left_width
, bottom
),
789 if (!part
.location
.IsEmpty())
790 background_parts_
.push_back(part
);
791 part
.location
= pp::Rect(right_start
, 0, right_width
, bottom
);
792 if (!part
.location
.IsEmpty())
793 background_parts_
.push_back(part
);
794 part
.location
= pp::Rect(
795 0, bottom
, plugin_size_
.width(), plugin_size_
.height() - bottom
);
796 if (!part
.location
.IsEmpty())
797 background_parts_
.push_back(part
);
800 int OutOfProcessInstance::GetDocumentPixelWidth() const {
801 return static_cast<int>(ceil(document_size_
.width() * zoom_
* device_scale_
));
804 int OutOfProcessInstance::GetDocumentPixelHeight() const {
805 return static_cast<int>(
806 ceil(document_size_
.height() * zoom_
* device_scale_
));
809 void OutOfProcessInstance::FillRect(const pp::Rect
& rect
, uint32 color
) {
810 DCHECK(!image_data_
.is_null() || rect
.IsEmpty());
811 uint32
* buffer_start
= static_cast<uint32
*>(image_data_
.data());
812 int stride
= image_data_
.stride();
813 uint32
* ptr
= buffer_start
+ rect
.y() * stride
/ 4 + rect
.x();
814 int height
= rect
.height();
815 int width
= rect
.width();
816 for (int y
= 0; y
< height
; ++y
) {
817 for (int x
= 0; x
< width
; ++x
)
823 void OutOfProcessInstance::DocumentSizeUpdated(const pp::Size
& size
) {
824 document_size_
= size
;
826 pp::VarDictionary dimensions
;
827 dimensions
.Set(kType
, kJSDocumentDimensionsType
);
828 dimensions
.Set(kJSDocumentWidth
, pp::Var(document_size_
.width()));
829 dimensions
.Set(kJSDocumentHeight
, pp::Var(document_size_
.height()));
830 pp::VarArray page_dimensions_array
;
831 int num_pages
= engine_
->GetNumberOfPages();
832 for (int i
= 0; i
< num_pages
; ++i
) {
833 pp::Rect page_rect
= engine_
->GetPageRect(i
);
834 pp::VarDictionary page_dimensions
;
835 page_dimensions
.Set(kJSPageX
, pp::Var(page_rect
.x()));
836 page_dimensions
.Set(kJSPageY
, pp::Var(page_rect
.y()));
837 page_dimensions
.Set(kJSPageWidth
, pp::Var(page_rect
.width()));
838 page_dimensions
.Set(kJSPageHeight
, pp::Var(page_rect
.height()));
839 page_dimensions_array
.Set(i
, page_dimensions
);
841 dimensions
.Set(kJSPageDimensions
, page_dimensions_array
);
842 PostMessage(dimensions
);
844 OnGeometryChanged(zoom_
, device_scale_
);
847 void OutOfProcessInstance::Invalidate(const pp::Rect
& rect
) {
848 pp::Rect
offset_rect(rect
);
849 offset_rect
.Offset(available_area_
.point());
850 paint_manager_
.InvalidateRect(offset_rect
);
853 void OutOfProcessInstance::Scroll(const pp::Point
& point
) {
854 if (!image_data_
.is_null())
855 paint_manager_
.ScrollRect(available_area_
, point
);
858 void OutOfProcessInstance::ScrollToX(int x
) {
859 pp::VarDictionary position
;
860 position
.Set(kType
, kJSSetScrollPositionType
);
861 position
.Set(kJSPositionX
, pp::Var(x
/ device_scale_
));
862 PostMessage(position
);
865 void OutOfProcessInstance::ScrollToY(int y
) {
866 pp::VarDictionary position
;
867 position
.Set(kType
, kJSSetScrollPositionType
);
868 position
.Set(kJSPositionY
, pp::Var(y
/ device_scale_
));
869 PostMessage(position
);
872 void OutOfProcessInstance::ScrollToPage(int page
) {
873 if (engine_
->GetNumberOfPages() == 0)
876 pp::VarDictionary message
;
877 message
.Set(kType
, kJSGoToPageType
);
878 message
.Set(kJSPageNumber
, pp::Var(page
));
879 PostMessage(message
);
882 void OutOfProcessInstance::NavigateTo(const std::string
& url
,
883 bool open_in_new_tab
) {
884 pp::VarDictionary message
;
885 message
.Set(kType
, kJSNavigateType
);
886 message
.Set(kJSNavigateUrl
, url
);
887 message
.Set(kJSNavigateNewTab
, open_in_new_tab
);
888 PostMessage(message
);
891 void OutOfProcessInstance::UpdateCursor(PP_CursorType_Dev cursor
) {
892 if (cursor
== cursor_
)
896 const PPB_CursorControl_Dev
* cursor_interface
=
897 reinterpret_cast<const PPB_CursorControl_Dev
*>(
898 pp::Module::Get()->GetBrowserInterface(PPB_CURSOR_CONTROL_DEV_INTERFACE
));
899 if (!cursor_interface
) {
904 cursor_interface
->SetCursor(
905 pp_instance(), cursor_
, pp::ImageData().pp_resource(), NULL
);
908 void OutOfProcessInstance::UpdateTickMarks(
909 const std::vector
<pp::Rect
>& tickmarks
) {
910 float inverse_scale
= 1.0f
/ device_scale_
;
911 std::vector
<pp::Rect
> scaled_tickmarks
= tickmarks
;
912 for (size_t i
= 0; i
< scaled_tickmarks
.size(); i
++)
913 ScaleRect(inverse_scale
, &scaled_tickmarks
[i
]);
914 tickmarks_
= scaled_tickmarks
;
917 void OutOfProcessInstance::NotifyNumberOfFindResultsChanged(int total
,
919 // We don't want to spam the renderer with too many updates to the number of
920 // find results. Don't send an update if we sent one too recently. If it's the
921 // final update, we always send it though.
923 NumberOfFindResultsChanged(total
, final_result
);
924 SetTickmarks(tickmarks_
);
928 if (recently_sent_find_update_
)
931 NumberOfFindResultsChanged(total
, final_result
);
932 SetTickmarks(tickmarks_
);
933 recently_sent_find_update_
= true;
934 pp::CompletionCallback callback
=
935 timer_factory_
.NewCallback(
936 &OutOfProcessInstance::ResetRecentlySentFindUpdate
);
937 pp::Module::Get()->core()->CallOnMainThread(kFindResultCooldownMs
,
941 void OutOfProcessInstance::NotifySelectedFindResultChanged(
942 int current_find_index
) {
943 DCHECK_GE(current_find_index
, 0);
944 SelectedFindResultChanged(current_find_index
);
947 void OutOfProcessInstance::GetDocumentPassword(
948 pp::CompletionCallbackWithOutput
<pp::Var
> callback
) {
949 if (password_callback_
) {
954 password_callback_
.reset(
955 new pp::CompletionCallbackWithOutput
<pp::Var
>(callback
));
956 pp::VarDictionary message
;
957 message
.Set(pp::Var(kType
), pp::Var(kJSGetPasswordType
));
958 PostMessage(message
);
961 void OutOfProcessInstance::Alert(const std::string
& message
) {
962 ModalDialog(this, "alert", message
, std::string());
965 bool OutOfProcessInstance::Confirm(const std::string
& message
) {
966 pp::Var result
= ModalDialog(this, "confirm", message
, std::string());
967 return result
.is_bool() ? result
.AsBool() : false;
970 std::string
OutOfProcessInstance::Prompt(const std::string
& question
,
971 const std::string
& default_answer
) {
972 pp::Var result
= ModalDialog(this, "prompt", question
, default_answer
);
973 return result
.is_string() ? result
.AsString() : std::string();
976 std::string
OutOfProcessInstance::GetURL() {
980 void OutOfProcessInstance::Email(const std::string
& to
,
981 const std::string
& cc
,
982 const std::string
& bcc
,
983 const std::string
& subject
,
984 const std::string
& body
) {
985 pp::VarDictionary message
;
986 message
.Set(pp::Var(kType
), pp::Var(kJSEmailType
));
987 message
.Set(pp::Var(kJSEmailTo
),
988 pp::Var(net::EscapeUrlEncodedData(to
, false)));
989 message
.Set(pp::Var(kJSEmailCc
),
990 pp::Var(net::EscapeUrlEncodedData(cc
, false)));
991 message
.Set(pp::Var(kJSEmailBcc
),
992 pp::Var(net::EscapeUrlEncodedData(bcc
, false)));
993 message
.Set(pp::Var(kJSEmailSubject
),
994 pp::Var(net::EscapeUrlEncodedData(subject
, false)));
995 message
.Set(pp::Var(kJSEmailBody
),
996 pp::Var(net::EscapeUrlEncodedData(body
, false)));
997 PostMessage(message
);
1000 void OutOfProcessInstance::Print() {
1001 if (!engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
) &&
1002 !engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY
)) {
1006 pp::CompletionCallback callback
=
1007 print_callback_factory_
.NewCallback(&OutOfProcessInstance::OnPrint
);
1008 pp::Module::Get()->core()->CallOnMainThread(0, callback
);
1011 void OutOfProcessInstance::OnPrint(int32_t) {
1012 pp::PDF::Print(this);
1015 void OutOfProcessInstance::SubmitForm(const std::string
& url
,
1018 pp::URLRequestInfo
request(this);
1019 request
.SetURL(url
);
1020 request
.SetMethod("POST");
1021 request
.AppendDataToBody(reinterpret_cast<const char*>(data
), length
);
1023 pp::CompletionCallback callback
=
1024 form_factory_
.NewCallback(&OutOfProcessInstance::FormDidOpen
);
1025 form_loader_
= CreateURLLoaderInternal();
1026 int rv
= form_loader_
.Open(request
, callback
);
1027 if (rv
!= PP_OK_COMPLETIONPENDING
)
1031 void OutOfProcessInstance::FormDidOpen(int32_t result
) {
1032 // TODO: inform the user of success/failure.
1033 if (result
!= PP_OK
) {
1038 std::string
OutOfProcessInstance::ShowFileSelectionDialog() {
1039 // Seems like very low priority to implement, since the pdf has no way to get
1040 // the file data anyways. Javascript doesn't let you do this synchronously.
1042 return std::string();
1045 pp::URLLoader
OutOfProcessInstance::CreateURLLoader() {
1047 if (!did_call_start_loading_
) {
1048 did_call_start_loading_
= true;
1049 pp::PDF::DidStartLoading(this);
1052 // Disable save and print until the document is fully loaded, since they
1053 // would generate an incomplete document. Need to do this each time we
1054 // call DidStartLoading since that resets the content restrictions.
1055 pp::PDF::SetContentRestriction(this, CONTENT_RESTRICTION_SAVE
|
1056 CONTENT_RESTRICTION_PRINT
);
1059 return CreateURLLoaderInternal();
1062 void OutOfProcessInstance::ScheduleCallback(int id
, int delay_in_ms
) {
1063 pp::CompletionCallback callback
=
1064 timer_factory_
.NewCallback(&OutOfProcessInstance::OnClientTimerFired
);
1065 pp::Module::Get()->core()->CallOnMainThread(delay_in_ms
, callback
, id
);
1068 void OutOfProcessInstance::SearchString(const base::char16
* string
,
1069 const base::char16
* term
,
1070 bool case_sensitive
,
1071 std::vector
<SearchStringResult
>* results
) {
1072 PP_PrivateFindResult
* pp_results
;
1074 pp::PDF::SearchString(
1076 reinterpret_cast<const unsigned short*>(string
),
1077 reinterpret_cast<const unsigned short*>(term
),
1082 results
->resize(count
);
1083 for (int i
= 0; i
< count
; ++i
) {
1084 (*results
)[i
].start_index
= pp_results
[i
].start_index
;
1085 (*results
)[i
].length
= pp_results
[i
].length
;
1088 pp::Memory_Dev memory
;
1089 memory
.MemFree(pp_results
);
1092 void OutOfProcessInstance::DocumentPaintOccurred() {
1095 void OutOfProcessInstance::DocumentLoadComplete(int page_count
) {
1096 // Clear focus state for OSK.
1097 FormTextFieldFocusChange(false);
1099 DCHECK(document_load_state_
== LOAD_STATE_LOADING
);
1100 document_load_state_
= LOAD_STATE_COMPLETE
;
1101 UserMetricsRecordAction("PDF.LoadSuccess");
1103 // Note: If we are in print preview mode the scroll location is retained
1104 // across document loads so we don't want to scroll again and override it.
1105 if (IsPrintPreview()) {
1106 AppendBlankPrintPreviewPages();
1107 OnGeometryChanged(0, 0);
1110 pp::VarDictionary bookmarks_message
;
1111 bookmarks_message
.Set(pp::Var(kType
), pp::Var(kJSBookmarksType
));
1112 bookmarks_message
.Set(pp::Var(kJSBookmarks
), engine_
->GetBookmarks());
1113 PostMessage(bookmarks_message
);
1115 pp::VarDictionary progress_message
;
1116 progress_message
.Set(pp::Var(kType
), pp::Var(kJSLoadProgressType
));
1117 progress_message
.Set(pp::Var(kJSProgressPercentage
), pp::Var(100));
1118 PostMessage(progress_message
);
1123 if (did_call_start_loading_
) {
1124 pp::PDF::DidStopLoading(this);
1125 did_call_start_loading_
= false;
1128 int content_restrictions
=
1129 CONTENT_RESTRICTION_CUT
| CONTENT_RESTRICTION_PASTE
;
1130 if (!engine_
->HasPermission(PDFEngine::PERMISSION_COPY
))
1131 content_restrictions
|= CONTENT_RESTRICTION_COPY
;
1133 pp::PDF::SetContentRestriction(this, content_restrictions
);
1135 uma_
.HistogramCustomCounts("PDF.PageCount", page_count
,
1139 void OutOfProcessInstance::RotateClockwise() {
1140 engine_
->RotateClockwise();
1143 void OutOfProcessInstance::RotateCounterclockwise() {
1144 engine_
->RotateCounterclockwise();
1147 void OutOfProcessInstance::PreviewDocumentLoadComplete() {
1148 if (preview_document_load_state_
!= LOAD_STATE_LOADING
||
1149 preview_pages_info_
.empty()) {
1153 preview_document_load_state_
= LOAD_STATE_COMPLETE
;
1155 int dest_page_index
= preview_pages_info_
.front().second
;
1156 int src_page_index
=
1157 ExtractPrintPreviewPageIndex(preview_pages_info_
.front().first
);
1158 if (src_page_index
> 0 && dest_page_index
> -1 && preview_engine_
.get())
1159 engine_
->AppendPage(preview_engine_
.get(), dest_page_index
);
1161 preview_pages_info_
.pop();
1162 // |print_preview_page_count_| is not updated yet. Do not load any
1163 // other preview pages till we get this information.
1164 if (print_preview_page_count_
== 0)
1167 if (preview_pages_info_
.size())
1168 LoadAvailablePreviewPage();
1171 void OutOfProcessInstance::DocumentLoadFailed() {
1172 DCHECK(document_load_state_
== LOAD_STATE_LOADING
);
1173 UserMetricsRecordAction("PDF.LoadFailure");
1175 if (did_call_start_loading_
) {
1176 pp::PDF::DidStopLoading(this);
1177 did_call_start_loading_
= false;
1180 document_load_state_
= LOAD_STATE_FAILED
;
1181 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
1183 // Send a progress value of -1 to indicate a failure.
1184 pp::VarDictionary message
;
1185 message
.Set(pp::Var(kType
), pp::Var(kJSLoadProgressType
));
1186 message
.Set(pp::Var(kJSProgressPercentage
), pp::Var(-1)) ;
1187 PostMessage(message
);
1190 void OutOfProcessInstance::PreviewDocumentLoadFailed() {
1191 UserMetricsRecordAction("PDF.PreviewDocumentLoadFailure");
1192 if (preview_document_load_state_
!= LOAD_STATE_LOADING
||
1193 preview_pages_info_
.empty()) {
1197 preview_document_load_state_
= LOAD_STATE_FAILED
;
1198 preview_pages_info_
.pop();
1200 if (preview_pages_info_
.size())
1201 LoadAvailablePreviewPage();
1204 pp::Instance
* OutOfProcessInstance::GetPluginInstance() {
1208 void OutOfProcessInstance::DocumentHasUnsupportedFeature(
1209 const std::string
& feature
) {
1210 std::string
metric("PDF_Unsupported_");
1212 if (!unsupported_features_reported_
.count(metric
)) {
1213 unsupported_features_reported_
.insert(metric
);
1214 UserMetricsRecordAction(metric
);
1217 // Since we use an info bar, only do this for full frame plugins..
1221 if (told_browser_about_unsupported_feature_
)
1223 told_browser_about_unsupported_feature_
= true;
1225 pp::PDF::HasUnsupportedFeature(this);
1228 void OutOfProcessInstance::DocumentLoadProgress(uint32 available
,
1230 double progress
= 0.0;
1231 if (doc_size
== 0) {
1232 // Document size is unknown. Use heuristics.
1233 // We'll make progress logarithmic from 0 to 100M.
1234 static const double kFactor
= log(100000000.0) / 100.0;
1235 if (available
> 0) {
1236 progress
= log(static_cast<double>(available
)) / kFactor
;
1237 if (progress
> 100.0)
1241 progress
= 100.0 * static_cast<double>(available
) / doc_size
;
1244 // We send 100% load progress in DocumentLoadComplete.
1245 if (progress
>= 100)
1248 // Avoid sending too many progress messages over PostMessage.
1249 if (progress
> last_progress_sent_
+ 1) {
1250 last_progress_sent_
= progress
;
1251 pp::VarDictionary message
;
1252 message
.Set(pp::Var(kType
), pp::Var(kJSLoadProgressType
));
1253 message
.Set(pp::Var(kJSProgressPercentage
), pp::Var(progress
)) ;
1254 PostMessage(message
);
1258 void OutOfProcessInstance::FormTextFieldFocusChange(bool in_focus
) {
1259 if (!text_input_
.get())
1262 text_input_
->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_TEXT
);
1264 text_input_
->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_NONE
);
1267 void OutOfProcessInstance::ResetRecentlySentFindUpdate(int32_t /* unused */) {
1268 recently_sent_find_update_
= false;
1271 void OutOfProcessInstance::OnGeometryChanged(double old_zoom
,
1272 float old_device_scale
) {
1273 if (zoom_
!= old_zoom
|| device_scale_
!= old_device_scale
)
1274 engine_
->ZoomUpdated(zoom_
* device_scale_
);
1276 available_area_
= pp::Rect(plugin_size_
);
1277 int doc_width
= GetDocumentPixelWidth();
1278 if (doc_width
< available_area_
.width()) {
1279 available_area_
.Offset((available_area_
.width() - doc_width
) / 2, 0);
1280 available_area_
.set_width(doc_width
);
1282 int doc_height
= GetDocumentPixelHeight();
1283 if (doc_height
< available_area_
.height()) {
1284 available_area_
.set_height(doc_height
);
1287 CalculateBackgroundParts();
1288 engine_
->PageOffsetUpdated(available_area_
.point());
1289 engine_
->PluginSizeUpdated(available_area_
.size());
1291 if (!document_size_
.GetArea())
1293 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
1296 void OutOfProcessInstance::LoadUrl(const std::string
& url
) {
1297 LoadUrlInternal(url
, &embed_loader_
, &OutOfProcessInstance::DidOpen
);
1300 void OutOfProcessInstance::LoadPreviewUrl(const std::string
& url
) {
1301 LoadUrlInternal(url
, &embed_preview_loader_
,
1302 &OutOfProcessInstance::DidOpenPreview
);
1305 void OutOfProcessInstance::LoadUrlInternal(
1306 const std::string
& url
,
1307 pp::URLLoader
* loader
,
1308 void (OutOfProcessInstance::* method
)(int32_t)) {
1309 pp::URLRequestInfo
request(this);
1310 request
.SetURL(url
);
1311 request
.SetMethod("GET");
1313 *loader
= CreateURLLoaderInternal();
1314 pp::CompletionCallback callback
= loader_factory_
.NewCallback(method
);
1315 int rv
= loader
->Open(request
, callback
);
1316 if (rv
!= PP_OK_COMPLETIONPENDING
)
1320 pp::URLLoader
OutOfProcessInstance::CreateURLLoaderInternal() {
1321 pp::URLLoader
loader(this);
1323 const PPB_URLLoaderTrusted
* trusted_interface
=
1324 reinterpret_cast<const PPB_URLLoaderTrusted
*>(
1325 pp::Module::Get()->GetBrowserInterface(
1326 PPB_URLLOADERTRUSTED_INTERFACE
));
1327 if (trusted_interface
)
1328 trusted_interface
->GrantUniversalAccess(loader
.pp_resource());
1332 void OutOfProcessInstance::SetZoom(double scale
) {
1333 double old_zoom
= zoom_
;
1335 OnGeometryChanged(old_zoom
, device_scale_
);
1338 std::string
OutOfProcessInstance::GetLocalizedString(PP_ResourceString id
) {
1339 pp::Var
rv(pp::PDF::GetLocalizedString(this, id
));
1340 if (!rv
.is_string())
1341 return std::string();
1343 return rv
.AsString();
1346 void OutOfProcessInstance::AppendBlankPrintPreviewPages() {
1347 if (print_preview_page_count_
== 0)
1349 engine_
->AppendBlankPages(print_preview_page_count_
);
1350 if (preview_pages_info_
.size() > 0)
1351 LoadAvailablePreviewPage();
1354 bool OutOfProcessInstance::IsPrintPreview() {
1355 return IsPrintPreviewUrl(url_
);
1358 uint32
OutOfProcessInstance::GetBackgroundColor() {
1359 return background_color_
;
1362 void OutOfProcessInstance::IsSelectingChanged(bool is_selecting
) {
1363 pp::VarDictionary message
;
1364 message
.Set(kType
, kJSSetIsSelectingType
);
1365 message
.Set(kJSIsSelecting
, pp::Var(is_selecting
));
1366 PostMessage(message
);
1369 void OutOfProcessInstance::ProcessPreviewPageInfo(const std::string
& url
,
1370 int dst_page_index
) {
1371 if (!IsPrintPreview())
1374 int src_page_index
= ExtractPrintPreviewPageIndex(url
);
1375 if (src_page_index
< 1)
1378 preview_pages_info_
.push(std::make_pair(url
, dst_page_index
));
1379 LoadAvailablePreviewPage();
1382 void OutOfProcessInstance::LoadAvailablePreviewPage() {
1383 if (preview_pages_info_
.size() <= 0 ||
1384 document_load_state_
!= LOAD_STATE_COMPLETE
) {
1388 std::string url
= preview_pages_info_
.front().first
;
1389 int dst_page_index
= preview_pages_info_
.front().second
;
1390 int src_page_index
= ExtractPrintPreviewPageIndex(url
);
1391 if (src_page_index
< 1 ||
1392 dst_page_index
>= print_preview_page_count_
||
1393 preview_document_load_state_
== LOAD_STATE_LOADING
) {
1397 preview_document_load_state_
= LOAD_STATE_LOADING
;
1398 LoadPreviewUrl(url
);
1401 void OutOfProcessInstance::UserMetricsRecordAction(
1402 const std::string
& action
) {
1403 // TODO(raymes): Move this function to PPB_UMA_Private.
1404 pp::PDF::UserMetricsRecordAction(this, pp::Var(action
));
1407 pp::FloatPoint
OutOfProcessInstance::BoundScrollOffsetToDocument(
1408 const pp::FloatPoint
& scroll_offset
) {
1409 float max_x
= document_size_
.width() * zoom_
- plugin_dip_size_
.width();
1410 float x
= std::max(std::min(scroll_offset
.x(), max_x
), 0.0f
);
1411 float max_y
= document_size_
.height() * zoom_
- plugin_dip_size_
.height();
1412 float y
= std::max(std::min(scroll_offset
.y(), max_y
), 0.0f
);
1413 return pp::FloatPoint(x
, y
);
1416 } // namespace chrome_pdf