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 // Constants used in handling postMessage() messages.
56 const char kType
[] = "type";
57 // Viewport message arguments. (Page -> Plugin).
58 const char kJSViewportType
[] = "viewport";
59 const char kJSXOffset
[] = "xOffset";
60 const char kJSYOffset
[] = "yOffset";
61 const char kJSZoom
[] = "zoom";
62 // Stop scrolling message (Page -> Plugin)
63 const char kJSStopScrollingType
[] = "stopScrolling";
64 // Document dimension arguments (Plugin -> Page).
65 const char kJSDocumentDimensionsType
[] = "documentDimensions";
66 const char kJSDocumentWidth
[] = "width";
67 const char kJSDocumentHeight
[] = "height";
68 const char kJSPageDimensions
[] = "pageDimensions";
69 const char kJSPageX
[] = "x";
70 const char kJSPageY
[] = "y";
71 const char kJSPageWidth
[] = "width";
72 const char kJSPageHeight
[] = "height";
73 // Document load progress arguments (Plugin -> Page)
74 const char kJSLoadProgressType
[] = "loadProgress";
75 const char kJSProgressPercentage
[] = "progress";
76 // Get password arguments (Plugin -> Page)
77 const char kJSGetPasswordType
[] = "getPassword";
78 // Get password complete arguments (Page -> Plugin)
79 const char kJSGetPasswordCompleteType
[] = "getPasswordComplete";
80 const char kJSPassword
[] = "password";
81 // Print (Page -> Plugin)
82 const char kJSPrintType
[] = "print";
83 // Save (Page -> Plugin)
84 const char kJSSaveType
[] = "save";
85 // Go to page (Plugin -> Page)
86 const char kJSGoToPageType
[] = "goToPage";
87 const char kJSPageNumber
[] = "page";
88 // Reset print preview mode (Page -> Plugin)
89 const char kJSResetPrintPreviewModeType
[] = "resetPrintPreviewMode";
90 const char kJSPrintPreviewUrl
[] = "url";
91 const char kJSPrintPreviewGrayscale
[] = "grayscale";
92 const char kJSPrintPreviewPageCount
[] = "pageCount";
93 // Load preview page (Page -> Plugin)
94 const char kJSLoadPreviewPageType
[] = "loadPreviewPage";
95 const char kJSPreviewPageUrl
[] = "url";
96 const char kJSPreviewPageIndex
[] = "index";
97 // Set scroll position (Plugin -> Page)
98 const char kJSSetScrollPositionType
[] = "setScrollPosition";
99 const char kJSPositionX
[] = "x";
100 const char kJSPositionY
[] = "y";
101 // Set translated strings (Plugin -> Page)
102 const char kJSSetTranslatedStringsType
[] = "setTranslatedStrings";
103 const char kJSGetPasswordString
[] = "getPasswordString";
104 const char kJSLoadingString
[] = "loadingString";
105 const char kJSLoadFailedString
[] = "loadFailedString";
106 // Request accessibility JSON data (Page -> Plugin)
107 const char kJSGetAccessibilityJSONType
[] = "getAccessibilityJSON";
108 const char kJSAccessibilityPageNumber
[] = "page";
109 // Reply with accessibility JSON data (Plugin -> Page)
110 const char kJSGetAccessibilityJSONReplyType
[] = "getAccessibilityJSONReply";
111 const char kJSAccessibilityJSON
[] = "json";
112 // Cancel the stream URL request (Plugin -> Page)
113 const char kJSCancelStreamUrlType
[] = "cancelStreamUrl";
114 // Navigate to the given URL (Plugin -> Page)
115 const char kJSNavigateType
[] = "navigate";
116 const char kJSNavigateUrl
[] = "url";
117 const char kJSNavigateNewTab
[] = "newTab";
118 // Open the email editor with the given parameters (Plugin -> Page)
119 const char kJSEmailType
[] = "email";
120 const char kJSEmailTo
[] = "to";
121 const char kJSEmailCc
[] = "cc";
122 const char kJSEmailBcc
[] = "bcc";
123 const char kJSEmailSubject
[] = "subject";
124 const char kJSEmailBody
[] = "body";
125 // Rotation (Page -> Plugin)
126 const char kJSRotateClockwiseType
[] = "rotateClockwise";
127 const char kJSRotateCounterclockwiseType
[] = "rotateCounterclockwise";
128 // Select all text in the document (Page -> Plugin)
129 const char kJSSelectAllType
[] = "selectAll";
130 // Get the selected text in the document (Page -> Plugin)
131 const char kJSGetSelectedTextType
[] = "getSelectedText";
132 // Reply with selected text (Plugin -> Page)
133 const char kJSGetSelectedTextReplyType
[] = "getSelectedTextReply";
134 const char kJSSelectedText
[] = "selectedText";
136 const int kFindResultCooldownMs
= 100;
138 const double kMinZoom
= 0.01;
142 static const char kPPPPdfInterface
[] = PPP_PDF_INTERFACE_1
;
144 PP_Var
GetLinkAtPosition(PP_Instance instance
, PP_Point point
) {
146 void* object
= pp::Instance::GetPerInstanceObject(instance
, kPPPPdfInterface
);
148 var
= static_cast<OutOfProcessInstance
*>(object
)->GetLinkAtPosition(
154 void Transform(PP_Instance instance
, PP_PrivatePageTransformType type
) {
156 pp::Instance::GetPerInstanceObject(instance
, kPPPPdfInterface
);
158 OutOfProcessInstance
* obj_instance
=
159 static_cast<OutOfProcessInstance
*>(object
);
161 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CW
:
162 obj_instance
->RotateClockwise();
164 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CCW
:
165 obj_instance
->RotateCounterclockwise();
171 PP_Bool
GetPrintPresetOptionsFromDocument(
172 PP_Instance instance
,
173 PP_PdfPrintPresetOptions_Dev
* options
) {
174 void* object
= pp::Instance::GetPerInstanceObject(instance
, kPPPPdfInterface
);
176 OutOfProcessInstance
* obj_instance
=
177 static_cast<OutOfProcessInstance
*>(object
);
178 obj_instance
->GetPrintPresetOptionsFromDocument(options
);
183 const PPP_Pdf ppp_private
= {
186 &GetPrintPresetOptionsFromDocument
189 int ExtractPrintPreviewPageIndex(const std::string
& src_url
) {
190 // Sample |src_url| format: chrome://print/id/page_index/print.pdf
191 std::vector
<std::string
> url_substr
;
192 base::SplitString(src_url
.substr(strlen(kChromePrint
)), '/', &url_substr
);
193 if (url_substr
.size() != 3)
196 if (url_substr
[2] != "print.pdf")
200 if (!base::StringToInt(url_substr
[1], &page_index
))
205 bool IsPrintPreviewUrl(const std::string
& url
) {
206 return url
.substr(0, strlen(kChromePrint
)) == kChromePrint
;
209 void ScalePoint(float scale
, pp::Point
* point
) {
210 point
->set_x(static_cast<int>(point
->x() * scale
));
211 point
->set_y(static_cast<int>(point
->y() * scale
));
214 void ScaleRect(float scale
, pp::Rect
* rect
) {
215 int left
= static_cast<int>(floorf(rect
->x() * scale
));
216 int top
= static_cast<int>(floorf(rect
->y() * scale
));
217 int right
= static_cast<int>(ceilf((rect
->x() + rect
->width()) * scale
));
218 int bottom
= static_cast<int>(ceilf((rect
->y() + rect
->height()) * scale
));
219 rect
->SetRect(left
, top
, right
- left
, bottom
- top
);
222 // TODO(raymes): Remove this dependency on VarPrivate/InstancePrivate. It's
223 // needed right now to do a synchronous call to JavaScript, but we could easily
224 // replace this with a custom PPB_PDF function.
225 pp::Var
ModalDialog(const pp::Instance
* instance
,
226 const std::string
& type
,
227 const std::string
& message
,
228 const std::string
& default_answer
) {
229 const PPB_Instance_Private
* interface
=
230 reinterpret_cast<const PPB_Instance_Private
*>(
231 pp::Module::Get()->GetBrowserInterface(
232 PPB_INSTANCE_PRIVATE_INTERFACE
));
233 pp::VarPrivate
window(pp::PASS_REF
,
234 interface
->GetWindowObject(instance
->pp_instance()));
235 if (default_answer
.empty())
236 return window
.Call(type
, message
);
238 return window
.Call(type
, message
, default_answer
);
243 OutOfProcessInstance::OutOfProcessInstance(PP_Instance instance
)
244 : pp::Instance(instance
),
245 pp::Find_Private(this),
246 pp::Printing_Dev(this),
247 pp::Selection_Dev(this),
248 cursor_(PP_CURSORTYPE_POINTER
),
251 printing_enabled_(true),
253 paint_manager_(this, this, true),
255 document_load_state_(LOAD_STATE_LOADING
),
256 preview_document_load_state_(LOAD_STATE_COMPLETE
),
258 told_browser_about_unsupported_feature_(false),
259 print_preview_page_count_(0),
260 last_progress_sent_(0),
261 recently_sent_find_update_(false),
262 received_viewport_message_(false),
263 did_call_start_loading_(false),
264 stop_scrolling_(false) {
265 loader_factory_
.Initialize(this);
266 timer_factory_
.Initialize(this);
267 form_factory_
.Initialize(this);
268 print_callback_factory_
.Initialize(this);
269 engine_
.reset(PDFEngine::Create(this));
270 pp::Module::Get()->AddPluginInterface(kPPPPdfInterface
, &ppp_private
);
271 AddPerInstanceObject(kPPPPdfInterface
, this);
273 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_MOUSE
);
274 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_KEYBOARD
);
275 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_TOUCH
);
278 OutOfProcessInstance::~OutOfProcessInstance() {
279 RemovePerInstanceObject(kPPPPdfInterface
, this);
282 bool OutOfProcessInstance::Init(uint32_t argc
,
284 const char* argv
[]) {
285 // Check if the PDF is being loaded in the PDF chrome extension. We only allow
286 // the plugin to be put into "full frame" mode when it is being loaded in the
287 // extension because this enables some features that we don't want pages
288 // abusing outside of the extension.
289 pp::Var document_url_var
= pp::URLUtil_Dev::Get()->GetDocumentURL(this);
290 std::string document_url
= document_url_var
.is_string() ?
291 document_url_var
.AsString() : std::string();
292 std::string extension_url
= std::string(kChromeExtension
);
294 !document_url
.compare(0, extension_url
.size(), extension_url
);
297 // Check if the plugin is full frame. This is passed in from JS.
298 for (uint32_t i
= 0; i
< argc
; ++i
) {
299 if (strcmp(argn
[i
], "full-frame") == 0) {
306 // Only allow the plugin to handle find requests if it is full frame.
308 SetPluginToHandleFindRequests();
310 // Send translated strings to the extension where they will be displayed.
311 // TODO(raymes): It would be better to get these in the extension directly
312 // through an API but no such API currently exists.
313 pp::VarDictionary translated_strings
;
314 translated_strings
.Set(kType
, kJSSetTranslatedStringsType
);
315 translated_strings
.Set(kJSGetPasswordString
,
316 GetLocalizedString(PP_RESOURCESTRING_PDFGETPASSWORD
));
317 translated_strings
.Set(kJSLoadingString
,
318 GetLocalizedString(PP_RESOURCESTRING_PDFLOADING
));
319 translated_strings
.Set(kJSLoadFailedString
,
320 GetLocalizedString(PP_RESOURCESTRING_PDFLOAD_FAILED
));
321 PostMessage(translated_strings
);
323 text_input_
.reset(new pp::TextInput_Dev(this));
325 const char* stream_url
= NULL
;
326 const char* original_url
= NULL
;
327 const char* headers
= NULL
;
328 for (uint32_t i
= 0; i
< argc
; ++i
) {
329 if (strcmp(argn
[i
], "src") == 0)
330 original_url
= argv
[i
];
331 else if (strcmp(argn
[i
], "stream-url") == 0)
332 stream_url
= argv
[i
];
333 else if (strcmp(argn
[i
], "headers") == 0)
337 // TODO(raymes): This is a hack to ensure that if no headers are passed in
338 // then we get the right MIME type. When the in process plugin is removed we
339 // can fix the document loader properly and remove this hack.
340 if (!headers
|| strcmp(headers
, "") == 0)
341 headers
= "content-type: application/pdf";
347 stream_url
= original_url
;
349 // If we're in print preview mode we don't need to load the document yet.
350 // A |kJSResetPrintPreviewModeType| message will be sent to the plugin letting
351 // it know the url to load. By not loading here we avoid loading the same
353 if (IsPrintPreviewUrl(original_url
))
358 return engine_
->New(original_url
, headers
);
361 void OutOfProcessInstance::HandleMessage(const pp::Var
& message
) {
362 pp::VarDictionary
dict(message
);
363 if (!dict
.Get(kType
).is_string()) {
368 std::string type
= dict
.Get(kType
).AsString();
370 if (type
== kJSViewportType
&&
371 dict
.Get(pp::Var(kJSXOffset
)).is_number() &&
372 dict
.Get(pp::Var(kJSYOffset
)).is_number() &&
373 dict
.Get(pp::Var(kJSZoom
)).is_number()) {
374 received_viewport_message_
= true;
375 stop_scrolling_
= false;
376 double zoom
= dict
.Get(pp::Var(kJSZoom
)).AsDouble();
377 pp::FloatPoint
scroll_offset(dict
.Get(pp::Var(kJSXOffset
)).AsDouble(),
378 dict
.Get(pp::Var(kJSYOffset
)).AsDouble());
380 // Bound the input parameters.
381 zoom
= std::max(kMinZoom
, zoom
);
383 scroll_offset
= BoundScrollOffsetToDocument(scroll_offset
);
384 engine_
->ScrolledToXPosition(scroll_offset
.x() * device_scale_
);
385 engine_
->ScrolledToYPosition(scroll_offset
.y() * device_scale_
);
386 } else if (type
== kJSGetPasswordCompleteType
&&
387 dict
.Get(pp::Var(kJSPassword
)).is_string()) {
388 if (password_callback_
) {
389 pp::CompletionCallbackWithOutput
<pp::Var
> callback
= *password_callback_
;
390 password_callback_
.reset();
391 *callback
.output() = dict
.Get(pp::Var(kJSPassword
)).pp_var();
396 } else if (type
== kJSPrintType
) {
398 } else if (type
== kJSSaveType
) {
399 pp::PDF::SaveAs(this);
400 } else if (type
== kJSRotateClockwiseType
) {
402 } else if (type
== kJSRotateCounterclockwiseType
) {
403 RotateCounterclockwise();
404 } else if (type
== kJSSelectAllType
) {
405 engine_
->SelectAll();
406 } else if (type
== kJSResetPrintPreviewModeType
&&
407 dict
.Get(pp::Var(kJSPrintPreviewUrl
)).is_string() &&
408 dict
.Get(pp::Var(kJSPrintPreviewGrayscale
)).is_bool() &&
409 dict
.Get(pp::Var(kJSPrintPreviewPageCount
)).is_int()) {
410 url_
= dict
.Get(pp::Var(kJSPrintPreviewUrl
)).AsString();
411 preview_pages_info_
= std::queue
<PreviewPageInfo
>();
412 preview_document_load_state_
= LOAD_STATE_COMPLETE
;
413 document_load_state_
= LOAD_STATE_LOADING
;
415 preview_engine_
.reset();
416 engine_
.reset(PDFEngine::Create(this));
417 engine_
->SetGrayscale(dict
.Get(pp::Var(kJSPrintPreviewGrayscale
)).AsBool());
418 engine_
->New(url_
.c_str());
420 print_preview_page_count_
=
421 std::max(dict
.Get(pp::Var(kJSPrintPreviewPageCount
)).AsInt(), 0);
423 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
424 } else if (type
== kJSLoadPreviewPageType
&&
425 dict
.Get(pp::Var(kJSPreviewPageUrl
)).is_string() &&
426 dict
.Get(pp::Var(kJSPreviewPageIndex
)).is_int()) {
427 ProcessPreviewPageInfo(dict
.Get(pp::Var(kJSPreviewPageUrl
)).AsString(),
428 dict
.Get(pp::Var(kJSPreviewPageIndex
)).AsInt());
429 } else if (type
== kJSGetAccessibilityJSONType
) {
430 pp::VarDictionary reply
;
431 reply
.Set(pp::Var(kType
), pp::Var(kJSGetAccessibilityJSONReplyType
));
432 if (dict
.Get(pp::Var(kJSAccessibilityPageNumber
)).is_int()) {
433 int page
= dict
.Get(pp::Var(kJSAccessibilityPageNumber
)).AsInt();
434 reply
.Set(pp::Var(kJSAccessibilityJSON
),
435 pp::Var(engine_
->GetPageAsJSON(page
)));
437 base::DictionaryValue node
;
438 node
.SetInteger(kAccessibleNumberOfPages
, engine_
->GetNumberOfPages());
439 node
.SetBoolean(kAccessibleLoaded
,
440 document_load_state_
!= LOAD_STATE_LOADING
);
441 bool has_permissions
=
442 engine_
->HasPermission(PDFEngine::PERMISSION_COPY
) ||
443 engine_
->HasPermission(PDFEngine::PERMISSION_COPY_ACCESSIBLE
);
444 node
.SetBoolean(kAccessibleCopyable
, has_permissions
);
446 base::JSONWriter::Write(&node
, &json
);
447 reply
.Set(pp::Var(kJSAccessibilityJSON
), pp::Var(json
));
450 } else if (type
== kJSStopScrollingType
) {
451 stop_scrolling_
= true;
452 } else if (type
== kJSGetSelectedTextType
) {
453 std::string selected_text
= engine_
->GetSelectedText();
454 // Always return unix newlines to JS.
455 base::ReplaceChars(selected_text
, "\r", std::string(), &selected_text
);
456 pp::VarDictionary reply
;
457 reply
.Set(pp::Var(kType
), pp::Var(kJSGetSelectedTextReplyType
));
458 reply
.Set(pp::Var(kJSSelectedText
), selected_text
);
465 bool OutOfProcessInstance::HandleInputEvent(
466 const pp::InputEvent
& event
) {
467 // To simplify things, convert the event into device coordinates if it is
469 pp::InputEvent
event_device_res(event
);
471 pp::MouseInputEvent
mouse_event(event
);
472 if (!mouse_event
.is_null()) {
473 pp::Point point
= mouse_event
.GetPosition();
474 pp::Point movement
= mouse_event
.GetMovement();
475 ScalePoint(device_scale_
, &point
);
476 ScalePoint(device_scale_
, &movement
);
477 mouse_event
= pp::MouseInputEvent(
480 event
.GetTimeStamp(),
481 event
.GetModifiers(),
482 mouse_event
.GetButton(),
484 mouse_event
.GetClickCount(),
486 event_device_res
= mouse_event
;
490 pp::InputEvent
offset_event(event_device_res
);
491 switch (offset_event
.GetType()) {
492 case PP_INPUTEVENT_TYPE_MOUSEDOWN
:
493 case PP_INPUTEVENT_TYPE_MOUSEUP
:
494 case PP_INPUTEVENT_TYPE_MOUSEMOVE
:
495 case PP_INPUTEVENT_TYPE_MOUSEENTER
:
496 case PP_INPUTEVENT_TYPE_MOUSELEAVE
: {
497 pp::MouseInputEvent
mouse_event(event_device_res
);
498 pp::MouseInputEvent
mouse_event_dip(event
);
499 pp::Point point
= mouse_event
.GetPosition();
500 point
.set_x(point
.x() - available_area_
.x());
501 offset_event
= pp::MouseInputEvent(
504 event
.GetTimeStamp(),
505 event
.GetModifiers(),
506 mouse_event
.GetButton(),
508 mouse_event
.GetClickCount(),
509 mouse_event
.GetMovement());
515 if (engine_
->HandleEvent(offset_event
))
518 // TODO(raymes): Implement this scroll behavior in JS:
519 // When click+dragging, scroll the document correctly.
521 // Return true for unhandled clicks so the plugin takes focus.
522 return (event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN
);
525 void OutOfProcessInstance::DidChangeView(const pp::View
& view
) {
526 pp::Rect
view_rect(view
.GetRect());
527 float old_device_scale
= device_scale_
;
528 float device_scale
= view
.GetDeviceScale();
529 pp::Size
view_device_size(view_rect
.width() * device_scale
,
530 view_rect
.height() * device_scale
);
532 if (view_device_size
!= plugin_size_
|| device_scale
!= device_scale_
) {
533 device_scale_
= device_scale
;
534 plugin_dip_size_
= view_rect
.size();
535 plugin_size_
= view_device_size
;
537 paint_manager_
.SetSize(view_device_size
, device_scale_
);
539 pp::Size new_image_data_size
= PaintManager::GetNewContextSize(
542 if (new_image_data_size
!= image_data_
.size()) {
543 image_data_
= pp::ImageData(this,
544 PP_IMAGEDATAFORMAT_BGRA_PREMUL
,
550 if (image_data_
.is_null()) {
551 DCHECK(plugin_size_
.IsEmpty());
555 OnGeometryChanged(zoom_
, old_device_scale
);
558 if (!stop_scrolling_
) {
559 pp::Point
scroll_offset(view
.GetScrollOffset());
560 pp::FloatPoint
scroll_offset_float(scroll_offset
.x(),
562 scroll_offset_float
= BoundScrollOffsetToDocument(scroll_offset_float
);
563 engine_
->ScrolledToXPosition(scroll_offset_float
.x() * device_scale_
);
564 engine_
->ScrolledToYPosition(scroll_offset_float
.y() * device_scale_
);
568 void OutOfProcessInstance::GetPrintPresetOptionsFromDocument(
569 PP_PdfPrintPresetOptions_Dev
* options
) {
570 options
->is_scaling_disabled
= PP_FromBool(IsPrintScalingDisabled());
571 options
->copies
= engine_
->GetCopiesToPrint();
574 pp::Var
OutOfProcessInstance::GetLinkAtPosition(
575 const pp::Point
& point
) {
576 pp::Point
offset_point(point
);
577 ScalePoint(device_scale_
, &offset_point
);
578 offset_point
.set_x(offset_point
.x() - available_area_
.x());
579 return engine_
->GetLinkAtPosition(offset_point
);
582 pp::Var
OutOfProcessInstance::GetSelectedText(bool html
) {
585 return engine_
->GetSelectedText();
588 uint32_t OutOfProcessInstance::QuerySupportedPrintOutputFormats() {
589 return engine_
->QuerySupportedPrintOutputFormats();
592 int32_t OutOfProcessInstance::PrintBegin(
593 const PP_PrintSettings_Dev
& print_settings
) {
594 // For us num_pages is always equal to the number of pages in the PDF
595 // document irrespective of the printable area.
596 int32_t ret
= engine_
->GetNumberOfPages();
600 uint32_t supported_formats
= engine_
->QuerySupportedPrintOutputFormats();
601 if ((print_settings
.format
& supported_formats
) == 0)
604 print_settings_
.is_printing
= true;
605 print_settings_
.pepper_print_settings
= print_settings
;
606 engine_
->PrintBegin();
610 pp::Resource
OutOfProcessInstance::PrintPages(
611 const PP_PrintPageNumberRange_Dev
* page_ranges
,
612 uint32_t page_range_count
) {
613 if (!print_settings_
.is_printing
)
614 return pp::Resource();
616 print_settings_
.print_pages_called_
= true;
617 return engine_
->PrintPages(page_ranges
, page_range_count
,
618 print_settings_
.pepper_print_settings
);
621 void OutOfProcessInstance::PrintEnd() {
622 if (print_settings_
.print_pages_called_
)
623 UserMetricsRecordAction("PDF.PrintPage");
624 print_settings_
.Clear();
628 bool OutOfProcessInstance::IsPrintScalingDisabled() {
629 return !engine_
->GetPrintScaling();
632 bool OutOfProcessInstance::StartFind(const std::string
& text
,
633 bool case_sensitive
) {
634 engine_
->StartFind(text
.c_str(), case_sensitive
);
638 void OutOfProcessInstance::SelectFindResult(bool forward
) {
639 engine_
->SelectFindResult(forward
);
642 void OutOfProcessInstance::StopFind() {
645 SetTickmarks(tickmarks_
);
648 void OutOfProcessInstance::OnPaint(
649 const std::vector
<pp::Rect
>& paint_rects
,
650 std::vector
<PaintManager::ReadyRect
>* ready
,
651 std::vector
<pp::Rect
>* pending
) {
652 if (image_data_
.is_null()) {
653 DCHECK(plugin_size_
.IsEmpty());
657 first_paint_
= false;
658 pp::Rect rect
= pp::Rect(pp::Point(), image_data_
.size());
659 FillRect(rect
, kBackgroundColor
);
660 ready
->push_back(PaintManager::ReadyRect(rect
, image_data_
, true));
663 if (!received_viewport_message_
)
668 for (size_t i
= 0; i
< paint_rects
.size(); i
++) {
669 // Intersect with plugin area since there could be pending invalidates from
670 // when the plugin area was larger.
672 paint_rects
[i
].Intersect(pp::Rect(pp::Point(), plugin_size_
));
676 pp::Rect pdf_rect
= available_area_
.Intersect(rect
);
677 if (!pdf_rect
.IsEmpty()) {
678 pdf_rect
.Offset(available_area_
.x() * -1, 0);
680 std::vector
<pp::Rect
> pdf_ready
;
681 std::vector
<pp::Rect
> pdf_pending
;
682 engine_
->Paint(pdf_rect
, &image_data_
, &pdf_ready
, &pdf_pending
);
683 for (size_t j
= 0; j
< pdf_ready
.size(); ++j
) {
684 pdf_ready
[j
].Offset(available_area_
.point());
686 PaintManager::ReadyRect(pdf_ready
[j
], image_data_
, false));
688 for (size_t j
= 0; j
< pdf_pending
.size(); ++j
) {
689 pdf_pending
[j
].Offset(available_area_
.point());
690 pending
->push_back(pdf_pending
[j
]);
694 for (size_t j
= 0; j
< background_parts_
.size(); ++j
) {
695 pp::Rect intersection
= background_parts_
[j
].location
.Intersect(rect
);
696 if (!intersection
.IsEmpty()) {
697 FillRect(intersection
, background_parts_
[j
].color
);
699 PaintManager::ReadyRect(intersection
, image_data_
, false));
704 engine_
->PostPaint();
707 void OutOfProcessInstance::DidOpen(int32_t result
) {
708 if (result
== PP_OK
) {
709 if (!engine_
->HandleDocumentLoad(embed_loader_
)) {
710 document_load_state_
= LOAD_STATE_LOADING
;
711 DocumentLoadFailed();
713 } else if (result
!= PP_ERROR_ABORTED
) { // Can happen in tests.
715 DocumentLoadFailed();
718 // If it's a progressive load, cancel the stream URL request so that requests
719 // can be made on the original URL.
720 // TODO(raymes): Make this clearer once the in-process plugin is deleted.
721 if (engine_
->IsProgressiveLoad()) {
722 pp::VarDictionary message
;
723 message
.Set(kType
, kJSCancelStreamUrlType
);
724 PostMessage(message
);
728 void OutOfProcessInstance::DidOpenPreview(int32_t result
) {
729 if (result
== PP_OK
) {
730 preview_engine_
.reset(PDFEngine::Create(new PreviewModeClient(this)));
731 preview_engine_
->HandleDocumentLoad(embed_preview_loader_
);
737 void OutOfProcessInstance::OnClientTimerFired(int32_t id
) {
738 engine_
->OnCallback(id
);
741 void OutOfProcessInstance::CalculateBackgroundParts() {
742 background_parts_
.clear();
743 int left_width
= available_area_
.x();
744 int right_start
= available_area_
.right();
745 int right_width
= abs(plugin_size_
.width() - available_area_
.right());
746 int bottom
= std::min(available_area_
.bottom(), plugin_size_
.height());
748 // Add the left, right, and bottom rectangles. Note: we assume only
749 // horizontal centering.
750 BackgroundPart part
= {
751 pp::Rect(0, 0, left_width
, bottom
),
754 if (!part
.location
.IsEmpty())
755 background_parts_
.push_back(part
);
756 part
.location
= pp::Rect(right_start
, 0, right_width
, bottom
);
757 if (!part
.location
.IsEmpty())
758 background_parts_
.push_back(part
);
759 part
.location
= pp::Rect(
760 0, bottom
, plugin_size_
.width(), plugin_size_
.height() - bottom
);
761 if (!part
.location
.IsEmpty())
762 background_parts_
.push_back(part
);
765 int OutOfProcessInstance::GetDocumentPixelWidth() const {
766 return static_cast<int>(ceil(document_size_
.width() * zoom_
* device_scale_
));
769 int OutOfProcessInstance::GetDocumentPixelHeight() const {
770 return static_cast<int>(
771 ceil(document_size_
.height() * zoom_
* device_scale_
));
774 void OutOfProcessInstance::FillRect(const pp::Rect
& rect
, uint32 color
) {
775 DCHECK(!image_data_
.is_null() || rect
.IsEmpty());
776 uint32
* buffer_start
= static_cast<uint32
*>(image_data_
.data());
777 int stride
= image_data_
.stride();
778 uint32
* ptr
= buffer_start
+ rect
.y() * stride
/ 4 + rect
.x();
779 int height
= rect
.height();
780 int width
= rect
.width();
781 for (int y
= 0; y
< height
; ++y
) {
782 for (int x
= 0; x
< width
; ++x
)
788 void OutOfProcessInstance::DocumentSizeUpdated(const pp::Size
& size
) {
789 document_size_
= size
;
791 pp::VarDictionary dimensions
;
792 dimensions
.Set(kType
, kJSDocumentDimensionsType
);
793 dimensions
.Set(kJSDocumentWidth
, pp::Var(document_size_
.width()));
794 dimensions
.Set(kJSDocumentHeight
, pp::Var(document_size_
.height()));
795 pp::VarArray page_dimensions_array
;
796 int num_pages
= engine_
->GetNumberOfPages();
797 for (int i
= 0; i
< num_pages
; ++i
) {
798 pp::Rect page_rect
= engine_
->GetPageRect(i
);
799 pp::VarDictionary page_dimensions
;
800 page_dimensions
.Set(kJSPageX
, pp::Var(page_rect
.x()));
801 page_dimensions
.Set(kJSPageY
, pp::Var(page_rect
.y()));
802 page_dimensions
.Set(kJSPageWidth
, pp::Var(page_rect
.width()));
803 page_dimensions
.Set(kJSPageHeight
, pp::Var(page_rect
.height()));
804 page_dimensions_array
.Set(i
, page_dimensions
);
806 dimensions
.Set(kJSPageDimensions
, page_dimensions_array
);
807 PostMessage(dimensions
);
809 OnGeometryChanged(zoom_
, device_scale_
);
812 void OutOfProcessInstance::Invalidate(const pp::Rect
& rect
) {
813 pp::Rect
offset_rect(rect
);
814 offset_rect
.Offset(available_area_
.point());
815 paint_manager_
.InvalidateRect(offset_rect
);
818 void OutOfProcessInstance::Scroll(const pp::Point
& point
) {
819 if (!image_data_
.is_null())
820 paint_manager_
.ScrollRect(available_area_
, point
);
823 void OutOfProcessInstance::ScrollToX(int x
) {
824 pp::VarDictionary position
;
825 position
.Set(kType
, kJSSetScrollPositionType
);
826 position
.Set(kJSPositionX
, pp::Var(x
/ device_scale_
));
827 PostMessage(position
);
830 void OutOfProcessInstance::ScrollToY(int y
) {
831 pp::VarDictionary position
;
832 position
.Set(kType
, kJSSetScrollPositionType
);
833 position
.Set(kJSPositionY
, pp::Var(y
/ device_scale_
));
834 PostMessage(position
);
837 void OutOfProcessInstance::ScrollToPage(int page
) {
838 if (engine_
->GetNumberOfPages() == 0)
841 pp::VarDictionary message
;
842 message
.Set(kType
, kJSGoToPageType
);
843 message
.Set(kJSPageNumber
, pp::Var(page
));
844 PostMessage(message
);
847 void OutOfProcessInstance::NavigateTo(const std::string
& url
,
848 bool open_in_new_tab
) {
849 std::string
url_copy(url
);
851 // Empty |url_copy| is ok, and will effectively be a reload.
852 // Skip the code below so an empty URL does not turn into "http://", which
853 // will cause GURL to fail a DCHECK.
854 if (!url_copy
.empty()) {
855 // If |url_copy| starts with '#', then it's for the same URL with a
856 // different URL fragment.
857 if (url_copy
[0] == '#') {
858 url_copy
= url_
+ url_copy
;
860 // If there's no scheme, add http.
861 if (url_copy
.find("://") == std::string::npos
&&
862 url_copy
.find("mailto:") == std::string::npos
) {
863 url_copy
= std::string("http://") + url_copy
;
865 // Make sure |url_copy| starts with a valid scheme.
866 if (url_copy
.find("http://") != 0 &&
867 url_copy
.find("https://") != 0 &&
868 url_copy
.find("ftp://") != 0 &&
869 url_copy
.find("file://") != 0 &&
870 url_copy
.find("mailto:") != 0) {
873 // Make sure |url_copy| is not only a scheme.
874 if (url_copy
== "http://" ||
875 url_copy
== "https://" ||
876 url_copy
== "ftp://" ||
877 url_copy
== "file://" ||
878 url_copy
== "mailto:") {
882 pp::VarDictionary message
;
883 message
.Set(kType
, kJSNavigateType
);
884 message
.Set(kJSNavigateUrl
, url_copy
);
885 message
.Set(kJSNavigateNewTab
, open_in_new_tab
);
886 PostMessage(message
);
889 void OutOfProcessInstance::UpdateCursor(PP_CursorType_Dev cursor
) {
890 if (cursor
== cursor_
)
894 const PPB_CursorControl_Dev
* cursor_interface
=
895 reinterpret_cast<const PPB_CursorControl_Dev
*>(
896 pp::Module::Get()->GetBrowserInterface(PPB_CURSOR_CONTROL_DEV_INTERFACE
));
897 if (!cursor_interface
) {
902 cursor_interface
->SetCursor(
903 pp_instance(), cursor_
, pp::ImageData().pp_resource(), NULL
);
906 void OutOfProcessInstance::UpdateTickMarks(
907 const std::vector
<pp::Rect
>& tickmarks
) {
908 float inverse_scale
= 1.0f
/ device_scale_
;
909 std::vector
<pp::Rect
> scaled_tickmarks
= tickmarks
;
910 for (size_t i
= 0; i
< scaled_tickmarks
.size(); i
++)
911 ScaleRect(inverse_scale
, &scaled_tickmarks
[i
]);
912 tickmarks_
= scaled_tickmarks
;
915 void OutOfProcessInstance::NotifyNumberOfFindResultsChanged(int total
,
917 // We don't want to spam the renderer with too many updates to the number of
918 // find results. Don't send an update if we sent one too recently. If it's the
919 // final update, we always send it though.
921 NumberOfFindResultsChanged(total
, final_result
);
922 SetTickmarks(tickmarks_
);
926 if (recently_sent_find_update_
)
929 NumberOfFindResultsChanged(total
, final_result
);
930 SetTickmarks(tickmarks_
);
931 recently_sent_find_update_
= true;
932 pp::CompletionCallback callback
=
933 timer_factory_
.NewCallback(
934 &OutOfProcessInstance::ResetRecentlySentFindUpdate
);
935 pp::Module::Get()->core()->CallOnMainThread(kFindResultCooldownMs
,
939 void OutOfProcessInstance::NotifySelectedFindResultChanged(
940 int current_find_index
) {
941 DCHECK_GE(current_find_index
, 0);
942 SelectedFindResultChanged(current_find_index
);
945 void OutOfProcessInstance::GetDocumentPassword(
946 pp::CompletionCallbackWithOutput
<pp::Var
> callback
) {
947 if (password_callback_
) {
952 password_callback_
.reset(
953 new pp::CompletionCallbackWithOutput
<pp::Var
>(callback
));
954 pp::VarDictionary message
;
955 message
.Set(pp::Var(kType
), pp::Var(kJSGetPasswordType
));
956 PostMessage(message
);
959 void OutOfProcessInstance::Alert(const std::string
& message
) {
960 ModalDialog(this, "alert", message
, std::string());
963 bool OutOfProcessInstance::Confirm(const std::string
& message
) {
964 pp::Var result
= ModalDialog(this, "confirm", message
, std::string());
965 return result
.is_bool() ? result
.AsBool() : false;
968 std::string
OutOfProcessInstance::Prompt(const std::string
& question
,
969 const std::string
& default_answer
) {
970 pp::Var result
= ModalDialog(this, "prompt", question
, default_answer
);
971 return result
.is_string() ? result
.AsString() : std::string();
974 std::string
OutOfProcessInstance::GetURL() {
978 void OutOfProcessInstance::Email(const std::string
& to
,
979 const std::string
& cc
,
980 const std::string
& bcc
,
981 const std::string
& subject
,
982 const std::string
& body
) {
983 pp::VarDictionary message
;
984 message
.Set(pp::Var(kType
), pp::Var(kJSEmailType
));
985 message
.Set(pp::Var(kJSEmailTo
),
986 pp::Var(net::EscapeUrlEncodedData(to
, false)));
987 message
.Set(pp::Var(kJSEmailCc
),
988 pp::Var(net::EscapeUrlEncodedData(cc
, false)));
989 message
.Set(pp::Var(kJSEmailBcc
),
990 pp::Var(net::EscapeUrlEncodedData(bcc
, false)));
991 message
.Set(pp::Var(kJSEmailSubject
),
992 pp::Var(net::EscapeUrlEncodedData(subject
, false)));
993 message
.Set(pp::Var(kJSEmailBody
),
994 pp::Var(net::EscapeUrlEncodedData(body
, false)));
995 PostMessage(message
);
998 void OutOfProcessInstance::Print() {
999 if (!printing_enabled_
||
1000 (!engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
) &&
1001 !engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY
))) {
1005 pp::CompletionCallback callback
=
1006 print_callback_factory_
.NewCallback(&OutOfProcessInstance::OnPrint
);
1007 pp::Module::Get()->core()->CallOnMainThread(0, callback
);
1010 void OutOfProcessInstance::OnPrint(int32_t) {
1011 pp::PDF::Print(this);
1014 void OutOfProcessInstance::SubmitForm(const std::string
& url
,
1017 pp::URLRequestInfo
request(this);
1018 request
.SetURL(url
);
1019 request
.SetMethod("POST");
1020 request
.AppendDataToBody(reinterpret_cast<const char*>(data
), length
);
1022 pp::CompletionCallback callback
=
1023 form_factory_
.NewCallback(&OutOfProcessInstance::FormDidOpen
);
1024 form_loader_
= CreateURLLoaderInternal();
1025 int rv
= form_loader_
.Open(request
, callback
);
1026 if (rv
!= PP_OK_COMPLETIONPENDING
)
1030 void OutOfProcessInstance::FormDidOpen(int32_t result
) {
1031 // TODO: inform the user of success/failure.
1032 if (result
!= PP_OK
) {
1037 std::string
OutOfProcessInstance::ShowFileSelectionDialog() {
1038 // Seems like very low priority to implement, since the pdf has no way to get
1039 // the file data anyways. Javascript doesn't let you do this synchronously.
1041 return std::string();
1044 pp::URLLoader
OutOfProcessInstance::CreateURLLoader() {
1046 if (!did_call_start_loading_
) {
1047 did_call_start_loading_
= true;
1048 pp::PDF::DidStartLoading(this);
1051 // Disable save and print until the document is fully loaded, since they
1052 // would generate an incomplete document. Need to do this each time we
1053 // call DidStartLoading since that resets the content restrictions.
1054 pp::PDF::SetContentRestriction(this, CONTENT_RESTRICTION_SAVE
|
1055 CONTENT_RESTRICTION_PRINT
);
1058 return CreateURLLoaderInternal();
1061 void OutOfProcessInstance::ScheduleCallback(int id
, int delay_in_ms
) {
1062 pp::CompletionCallback callback
=
1063 timer_factory_
.NewCallback(&OutOfProcessInstance::OnClientTimerFired
);
1064 pp::Module::Get()->core()->CallOnMainThread(delay_in_ms
, callback
, id
);
1067 void OutOfProcessInstance::SearchString(const base::char16
* string
,
1068 const base::char16
* term
,
1069 bool case_sensitive
,
1070 std::vector
<SearchStringResult
>* results
) {
1071 PP_PrivateFindResult
* pp_results
;
1073 pp::PDF::SearchString(
1075 reinterpret_cast<const unsigned short*>(string
),
1076 reinterpret_cast<const unsigned short*>(term
),
1081 results
->resize(count
);
1082 for (int i
= 0; i
< count
; ++i
) {
1083 (*results
)[i
].start_index
= pp_results
[i
].start_index
;
1084 (*results
)[i
].length
= pp_results
[i
].length
;
1087 pp::Memory_Dev memory
;
1088 memory
.MemFree(pp_results
);
1091 void OutOfProcessInstance::DocumentPaintOccurred() {
1094 void OutOfProcessInstance::DocumentLoadComplete(int page_count
) {
1095 // Clear focus state for OSK.
1096 FormTextFieldFocusChange(false);
1098 DCHECK(document_load_state_
== LOAD_STATE_LOADING
);
1099 document_load_state_
= LOAD_STATE_COMPLETE
;
1100 UserMetricsRecordAction("PDF.LoadSuccess");
1102 // Note: If we are in print preview mode the scroll location is retained
1103 // across document loads so we don't want to scroll again and override it.
1104 if (IsPrintPreview()) {
1105 AppendBlankPrintPreviewPages();
1106 OnGeometryChanged(0, 0);
1109 pp::VarDictionary message
;
1110 message
.Set(pp::Var(kType
), pp::Var(kJSLoadProgressType
));
1111 message
.Set(pp::Var(kJSProgressPercentage
), pp::Var(100)) ;
1112 PostMessage(message
);
1117 if (did_call_start_loading_
) {
1118 pp::PDF::DidStopLoading(this);
1119 did_call_start_loading_
= false;
1122 int content_restrictions
=
1123 CONTENT_RESTRICTION_CUT
| CONTENT_RESTRICTION_PASTE
;
1124 if (!engine_
->HasPermission(PDFEngine::PERMISSION_COPY
))
1125 content_restrictions
|= CONTENT_RESTRICTION_COPY
;
1127 if (!engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
) &&
1128 !engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY
)) {
1129 printing_enabled_
= false;
1132 pp::PDF::SetContentRestriction(this, content_restrictions
);
1134 uma_
.HistogramCustomCounts("PDF.PageCount", page_count
,
1138 void OutOfProcessInstance::RotateClockwise() {
1139 engine_
->RotateClockwise();
1142 void OutOfProcessInstance::RotateCounterclockwise() {
1143 engine_
->RotateCounterclockwise();
1146 void OutOfProcessInstance::PreviewDocumentLoadComplete() {
1147 if (preview_document_load_state_
!= LOAD_STATE_LOADING
||
1148 preview_pages_info_
.empty()) {
1152 preview_document_load_state_
= LOAD_STATE_COMPLETE
;
1154 int dest_page_index
= preview_pages_info_
.front().second
;
1155 int src_page_index
=
1156 ExtractPrintPreviewPageIndex(preview_pages_info_
.front().first
);
1157 if (src_page_index
> 0 && dest_page_index
> -1 && preview_engine_
.get())
1158 engine_
->AppendPage(preview_engine_
.get(), dest_page_index
);
1160 preview_pages_info_
.pop();
1161 // |print_preview_page_count_| is not updated yet. Do not load any
1162 // other preview pages till we get this information.
1163 if (print_preview_page_count_
== 0)
1166 if (preview_pages_info_
.size())
1167 LoadAvailablePreviewPage();
1170 void OutOfProcessInstance::DocumentLoadFailed() {
1171 DCHECK(document_load_state_
== LOAD_STATE_LOADING
);
1172 UserMetricsRecordAction("PDF.LoadFailure");
1174 if (did_call_start_loading_
) {
1175 pp::PDF::DidStopLoading(this);
1176 did_call_start_loading_
= false;
1179 document_load_state_
= LOAD_STATE_FAILED
;
1180 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
1182 // Send a progress value of -1 to indicate a failure.
1183 pp::VarDictionary message
;
1184 message
.Set(pp::Var(kType
), pp::Var(kJSLoadProgressType
));
1185 message
.Set(pp::Var(kJSProgressPercentage
), pp::Var(-1)) ;
1186 PostMessage(message
);
1189 void OutOfProcessInstance::PreviewDocumentLoadFailed() {
1190 UserMetricsRecordAction("PDF.PreviewDocumentLoadFailure");
1191 if (preview_document_load_state_
!= LOAD_STATE_LOADING
||
1192 preview_pages_info_
.empty()) {
1196 preview_document_load_state_
= LOAD_STATE_FAILED
;
1197 preview_pages_info_
.pop();
1199 if (preview_pages_info_
.size())
1200 LoadAvailablePreviewPage();
1203 pp::Instance
* OutOfProcessInstance::GetPluginInstance() {
1207 void OutOfProcessInstance::DocumentHasUnsupportedFeature(
1208 const std::string
& feature
) {
1209 std::string
metric("PDF_Unsupported_");
1211 if (!unsupported_features_reported_
.count(metric
)) {
1212 unsupported_features_reported_
.insert(metric
);
1213 UserMetricsRecordAction(metric
);
1216 // Since we use an info bar, only do this for full frame plugins..
1220 if (told_browser_about_unsupported_feature_
)
1222 told_browser_about_unsupported_feature_
= true;
1224 pp::PDF::HasUnsupportedFeature(this);
1227 void OutOfProcessInstance::DocumentLoadProgress(uint32 available
,
1229 double progress
= 0.0;
1230 if (doc_size
== 0) {
1231 // Document size is unknown. Use heuristics.
1232 // We'll make progress logarithmic from 0 to 100M.
1233 static const double kFactor
= log(100000000.0) / 100.0;
1234 if (available
> 0) {
1235 progress
= log(static_cast<double>(available
)) / kFactor
;
1236 if (progress
> 100.0)
1240 progress
= 100.0 * static_cast<double>(available
) / doc_size
;
1243 // We send 100% load progress in DocumentLoadComplete.
1244 if (progress
>= 100)
1247 // Avoid sending too many progress messages over PostMessage.
1248 if (progress
> last_progress_sent_
+ 1) {
1249 last_progress_sent_
= progress
;
1250 pp::VarDictionary message
;
1251 message
.Set(pp::Var(kType
), pp::Var(kJSLoadProgressType
));
1252 message
.Set(pp::Var(kJSProgressPercentage
), pp::Var(progress
)) ;
1253 PostMessage(message
);
1257 void OutOfProcessInstance::FormTextFieldFocusChange(bool in_focus
) {
1258 if (!text_input_
.get())
1261 text_input_
->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_TEXT
);
1263 text_input_
->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_NONE
);
1266 void OutOfProcessInstance::ResetRecentlySentFindUpdate(int32_t /* unused */) {
1267 recently_sent_find_update_
= false;
1270 void OutOfProcessInstance::OnGeometryChanged(double old_zoom
,
1271 float old_device_scale
) {
1272 if (zoom_
!= old_zoom
|| device_scale_
!= old_device_scale
)
1273 engine_
->ZoomUpdated(zoom_
* device_scale_
);
1275 available_area_
= pp::Rect(plugin_size_
);
1276 int doc_width
= GetDocumentPixelWidth();
1277 if (doc_width
< available_area_
.width()) {
1278 available_area_
.Offset((available_area_
.width() - doc_width
) / 2, 0);
1279 available_area_
.set_width(doc_width
);
1281 int doc_height
= GetDocumentPixelHeight();
1282 if (doc_height
< available_area_
.height()) {
1283 available_area_
.set_height(doc_height
);
1286 CalculateBackgroundParts();
1287 engine_
->PageOffsetUpdated(available_area_
.point());
1288 engine_
->PluginSizeUpdated(available_area_
.size());
1290 if (!document_size_
.GetArea())
1292 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
1295 void OutOfProcessInstance::LoadUrl(const std::string
& url
) {
1296 LoadUrlInternal(url
, &embed_loader_
, &OutOfProcessInstance::DidOpen
);
1299 void OutOfProcessInstance::LoadPreviewUrl(const std::string
& url
) {
1300 LoadUrlInternal(url
, &embed_preview_loader_
,
1301 &OutOfProcessInstance::DidOpenPreview
);
1304 void OutOfProcessInstance::LoadUrlInternal(
1305 const std::string
& url
,
1306 pp::URLLoader
* loader
,
1307 void (OutOfProcessInstance::* method
)(int32_t)) {
1308 pp::URLRequestInfo
request(this);
1309 request
.SetURL(url
);
1310 request
.SetMethod("GET");
1312 *loader
= CreateURLLoaderInternal();
1313 pp::CompletionCallback callback
= loader_factory_
.NewCallback(method
);
1314 int rv
= loader
->Open(request
, callback
);
1315 if (rv
!= PP_OK_COMPLETIONPENDING
)
1319 pp::URLLoader
OutOfProcessInstance::CreateURLLoaderInternal() {
1320 pp::URLLoader
loader(this);
1322 const PPB_URLLoaderTrusted
* trusted_interface
=
1323 reinterpret_cast<const PPB_URLLoaderTrusted
*>(
1324 pp::Module::Get()->GetBrowserInterface(
1325 PPB_URLLOADERTRUSTED_INTERFACE
));
1326 if (trusted_interface
)
1327 trusted_interface
->GrantUniversalAccess(loader
.pp_resource());
1331 void OutOfProcessInstance::SetZoom(double scale
) {
1332 double old_zoom
= zoom_
;
1334 OnGeometryChanged(old_zoom
, device_scale_
);
1337 std::string
OutOfProcessInstance::GetLocalizedString(PP_ResourceString id
) {
1338 pp::Var
rv(pp::PDF::GetLocalizedString(this, id
));
1339 if (!rv
.is_string())
1340 return std::string();
1342 return rv
.AsString();
1345 void OutOfProcessInstance::AppendBlankPrintPreviewPages() {
1346 if (print_preview_page_count_
== 0)
1348 engine_
->AppendBlankPages(print_preview_page_count_
);
1349 if (preview_pages_info_
.size() > 0)
1350 LoadAvailablePreviewPage();
1353 bool OutOfProcessInstance::IsPrintPreview() {
1354 return IsPrintPreviewUrl(url_
);
1357 void OutOfProcessInstance::ProcessPreviewPageInfo(const std::string
& url
,
1358 int dst_page_index
) {
1359 if (!IsPrintPreview())
1362 int src_page_index
= ExtractPrintPreviewPageIndex(url
);
1363 if (src_page_index
< 1)
1366 preview_pages_info_
.push(std::make_pair(url
, dst_page_index
));
1367 LoadAvailablePreviewPage();
1370 void OutOfProcessInstance::LoadAvailablePreviewPage() {
1371 if (preview_pages_info_
.size() <= 0 ||
1372 document_load_state_
!= LOAD_STATE_COMPLETE
) {
1376 std::string url
= preview_pages_info_
.front().first
;
1377 int dst_page_index
= preview_pages_info_
.front().second
;
1378 int src_page_index
= ExtractPrintPreviewPageIndex(url
);
1379 if (src_page_index
< 1 ||
1380 dst_page_index
>= print_preview_page_count_
||
1381 preview_document_load_state_
== LOAD_STATE_LOADING
) {
1385 preview_document_load_state_
= LOAD_STATE_LOADING
;
1386 LoadPreviewUrl(url
);
1389 void OutOfProcessInstance::UserMetricsRecordAction(
1390 const std::string
& action
) {
1391 // TODO(raymes): Move this function to PPB_UMA_Private.
1392 pp::PDF::UserMetricsRecordAction(this, pp::Var(action
));
1395 pp::FloatPoint
OutOfProcessInstance::BoundScrollOffsetToDocument(
1396 const pp::FloatPoint
& scroll_offset
) {
1397 float max_x
= document_size_
.width() * zoom_
- plugin_dip_size_
.width();
1398 float x
= std::max(std::min(scroll_offset
.x(), max_x
), 0.0f
);
1399 float max_y
= document_size_
.height() * zoom_
- plugin_dip_size_
.height();
1400 float y
= std::max(std::min(scroll_offset
.y(), max_y
), 0.0f
);
1401 return pp::FloatPoint(x
, y
);
1404 } // namespace chrome_pdf