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 #if defined(OS_MACOSX)
45 #include "base/mac/mac_util.h"
48 namespace chrome_pdf
{
50 const char kChromePrint
[] = "chrome://print/";
51 const char kChromeExtension
[] =
52 "chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai";
54 // Dictionary Value key names for the document accessibility info
55 const char kAccessibleNumberOfPages
[] = "numberOfPages";
56 const char kAccessibleLoaded
[] = "loaded";
57 const char kAccessibleCopyable
[] = "copyable";
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";
80 // Get password arguments (Plugin -> Page)
81 const char kJSGetPasswordType
[] = "getPassword";
82 // Get password complete arguments (Page -> Plugin)
83 const char kJSGetPasswordCompleteType
[] = "getPasswordComplete";
84 const char kJSPassword
[] = "password";
85 // Print (Page -> Plugin)
86 const char kJSPrintType
[] = "print";
87 // Go to page (Plugin -> Page)
88 const char kJSGoToPageType
[] = "goToPage";
89 const char kJSPageNumber
[] = "page";
90 // Reset print preview mode (Page -> Plugin)
91 const char kJSResetPrintPreviewModeType
[] = "resetPrintPreviewMode";
92 const char kJSPrintPreviewUrl
[] = "url";
93 const char kJSPrintPreviewGrayscale
[] = "grayscale";
94 const char kJSPrintPreviewPageCount
[] = "pageCount";
95 // Load preview page (Page -> Plugin)
96 const char kJSLoadPreviewPageType
[] = "loadPreviewPage";
97 const char kJSPreviewPageUrl
[] = "url";
98 const char kJSPreviewPageIndex
[] = "index";
99 // Set scroll position (Plugin -> Page)
100 const char kJSSetScrollPositionType
[] = "setScrollPosition";
101 const char kJSPositionX
[] = "x";
102 const char kJSPositionY
[] = "y";
103 // Set translated strings (Plugin -> Page)
104 const char kJSSetTranslatedStringsType
[] = "setTranslatedStrings";
105 const char kJSGetPasswordString
[] = "getPasswordString";
106 const char kJSLoadingString
[] = "loadingString";
107 const char kJSLoadFailedString
[] = "loadFailedString";
108 // Request accessibility JSON data (Page -> Plugin)
109 const char kJSGetAccessibilityJSONType
[] = "getAccessibilityJSON";
110 const char kJSAccessibilityPageNumber
[] = "page";
111 // Reply with accessibility JSON data (Plugin -> Page)
112 const char kJSGetAccessibilityJSONReplyType
[] = "getAccessibilityJSONReply";
113 const char kJSAccessibilityJSON
[] = "json";
114 // Cancel the stream URL request (Plugin -> Page)
115 const char kJSCancelStreamUrlType
[] = "cancelStreamUrl";
116 // Navigate to the given URL (Plugin -> Page)
117 const char kJSNavigateType
[] = "navigate";
118 const char kJSNavigateUrl
[] = "url";
119 const char kJSNavigateNewTab
[] = "newTab";
120 // Open the email editor with the given parameters (Plugin -> Page)
121 const char kJSEmailType
[] = "email";
122 const char kJSEmailTo
[] = "to";
123 const char kJSEmailCc
[] = "cc";
124 const char kJSEmailBcc
[] = "bcc";
125 const char kJSEmailSubject
[] = "subject";
126 const char kJSEmailBody
[] = "body";
128 const int kFindResultCooldownMs
= 100;
130 const double kMinZoom
= 0.01;
134 static const char kPPPPdfInterface
[] = PPP_PDF_INTERFACE_1
;
136 PP_Var
GetLinkAtPosition(PP_Instance instance
, PP_Point point
) {
138 void* object
= pp::Instance::GetPerInstanceObject(instance
, kPPPPdfInterface
);
140 var
= static_cast<OutOfProcessInstance
*>(object
)->GetLinkAtPosition(
146 void Transform(PP_Instance instance
, PP_PrivatePageTransformType type
) {
148 pp::Instance::GetPerInstanceObject(instance
, kPPPPdfInterface
);
150 OutOfProcessInstance
* obj_instance
=
151 static_cast<OutOfProcessInstance
*>(object
);
153 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CW
:
154 obj_instance
->RotateClockwise();
156 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CCW
:
157 obj_instance
->RotateCounterclockwise();
163 const PPP_Pdf ppp_private
= {
168 int ExtractPrintPreviewPageIndex(const std::string
& src_url
) {
169 // Sample |src_url| format: chrome://print/id/page_index/print.pdf
170 std::vector
<std::string
> url_substr
;
171 base::SplitString(src_url
.substr(strlen(kChromePrint
)), '/', &url_substr
);
172 if (url_substr
.size() != 3)
175 if (url_substr
[2] != "print.pdf")
179 if (!base::StringToInt(url_substr
[1], &page_index
))
184 bool IsPrintPreviewUrl(const std::string
& url
) {
185 return url
.substr(0, strlen(kChromePrint
)) == kChromePrint
;
188 void ScalePoint(float scale
, pp::Point
* point
) {
189 point
->set_x(static_cast<int>(point
->x() * scale
));
190 point
->set_y(static_cast<int>(point
->y() * scale
));
193 void ScaleRect(float scale
, pp::Rect
* rect
) {
194 int left
= static_cast<int>(floorf(rect
->x() * scale
));
195 int top
= static_cast<int>(floorf(rect
->y() * scale
));
196 int right
= static_cast<int>(ceilf((rect
->x() + rect
->width()) * scale
));
197 int bottom
= static_cast<int>(ceilf((rect
->y() + rect
->height()) * scale
));
198 rect
->SetRect(left
, top
, right
- left
, bottom
- top
);
201 // TODO(raymes): Remove this dependency on VarPrivate/InstancePrivate. It's
202 // needed right now to do a synchronous call to JavaScript, but we could easily
203 // replace this with a custom PPB_PDF function.
204 pp::Var
ModalDialog(const pp::Instance
* instance
,
205 const std::string
& type
,
206 const std::string
& message
,
207 const std::string
& default_answer
) {
208 const PPB_Instance_Private
* interface
=
209 reinterpret_cast<const PPB_Instance_Private
*>(
210 pp::Module::Get()->GetBrowserInterface(
211 PPB_INSTANCE_PRIVATE_INTERFACE
));
212 pp::VarPrivate
window(pp::PASS_REF
,
213 interface
->GetWindowObject(instance
->pp_instance()));
214 if (default_answer
.empty())
215 return window
.Call(type
, message
);
217 return window
.Call(type
, message
, default_answer
);
222 OutOfProcessInstance::OutOfProcessInstance(PP_Instance instance
)
223 : pp::Instance(instance
),
224 pp::Find_Private(this),
225 pp::Printing_Dev(this),
226 pp::Selection_Dev(this),
227 cursor_(PP_CURSORTYPE_POINTER
),
230 printing_enabled_(true),
232 paint_manager_(this, this, true),
234 document_load_state_(LOAD_STATE_LOADING
),
235 preview_document_load_state_(LOAD_STATE_COMPLETE
),
237 told_browser_about_unsupported_feature_(false),
238 print_preview_page_count_(0),
239 last_progress_sent_(0),
240 recently_sent_find_update_(false),
241 received_viewport_message_(false),
242 did_call_start_loading_(false),
243 stop_scrolling_(false) {
244 loader_factory_
.Initialize(this);
245 timer_factory_
.Initialize(this);
246 form_factory_
.Initialize(this);
247 print_callback_factory_
.Initialize(this);
248 engine_
.reset(PDFEngine::Create(this));
249 pp::Module::Get()->AddPluginInterface(kPPPPdfInterface
, &ppp_private
);
250 AddPerInstanceObject(kPPPPdfInterface
, this);
252 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_MOUSE
);
253 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_KEYBOARD
);
254 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_TOUCH
);
257 OutOfProcessInstance::~OutOfProcessInstance() {
258 RemovePerInstanceObject(kPPPPdfInterface
, this);
261 bool OutOfProcessInstance::Init(uint32_t argc
,
263 const char* argv
[]) {
264 // Check if the PDF is being loaded in the PDF chrome extension. We only allow
265 // the plugin to be put into "full frame" mode when it is being loaded in the
266 // extension because this enables some features that we don't want pages
267 // abusing outside of the extension.
268 pp::Var document_url_var
= pp::URLUtil_Dev::Get()->GetDocumentURL(this);
269 std::string document_url
= document_url_var
.is_string() ?
270 document_url_var
.AsString() : std::string();
271 std::string extension_url
= std::string(kChromeExtension
);
273 !document_url
.compare(0, extension_url
.size(), extension_url
);
276 // Check if the plugin is full frame. This is passed in from JS.
277 for (uint32_t i
= 0; i
< argc
; ++i
) {
278 if (strcmp(argn
[i
], "full-frame") == 0) {
285 // Only allow the plugin to handle find requests if it is full frame.
287 SetPluginToHandleFindRequests();
289 // Send translated strings to the extension where they will be displayed.
290 // TODO(raymes): It would be better to get these in the extension directly
291 // through an API but no such API currently exists.
292 pp::VarDictionary translated_strings
;
293 translated_strings
.Set(kType
, kJSSetTranslatedStringsType
);
294 translated_strings
.Set(kJSGetPasswordString
,
295 GetLocalizedString(PP_RESOURCESTRING_PDFGETPASSWORD
));
296 translated_strings
.Set(kJSLoadingString
,
297 GetLocalizedString(PP_RESOURCESTRING_PDFLOADING
));
298 translated_strings
.Set(kJSLoadFailedString
,
299 GetLocalizedString(PP_RESOURCESTRING_PDFLOAD_FAILED
));
300 PostMessage(translated_strings
);
302 text_input_
.reset(new pp::TextInput_Dev(this));
304 const char* stream_url
= NULL
;
305 const char* original_url
= NULL
;
306 const char* headers
= NULL
;
307 for (uint32_t i
= 0; i
< argc
; ++i
) {
308 if (strcmp(argn
[i
], "src") == 0)
309 original_url
= argv
[i
];
310 else if (strcmp(argn
[i
], "stream-url") == 0)
311 stream_url
= argv
[i
];
312 else if (strcmp(argn
[i
], "headers") == 0)
316 // TODO(raymes): This is a hack to ensure that if no headers are passed in
317 // then we get the right MIME type. When the in process plugin is removed we
318 // can fix the document loader properly and remove this hack.
319 if (!headers
|| strcmp(headers
, "") == 0)
320 headers
= "content-type: application/pdf";
326 stream_url
= original_url
;
328 // If we're in print preview mode we don't need to load the document yet.
329 // A |kJSResetPrintPreviewModeType| message will be sent to the plugin letting
330 // it know the url to load. By not loading here we avoid loading the same
332 if (IsPrintPreviewUrl(original_url
))
337 return engine_
->New(original_url
, headers
);
340 void OutOfProcessInstance::HandleMessage(const pp::Var
& message
) {
341 pp::VarDictionary
dict(message
);
342 if (!dict
.Get(kType
).is_string()) {
347 std::string type
= dict
.Get(kType
).AsString();
349 if (type
== kJSViewportType
&&
350 dict
.Get(pp::Var(kJSXOffset
)).is_int() &&
351 dict
.Get(pp::Var(kJSYOffset
)).is_int() &&
352 dict
.Get(pp::Var(kJSZoom
)).is_number()) {
353 received_viewport_message_
= true;
354 stop_scrolling_
= false;
355 double zoom
= dict
.Get(pp::Var(kJSZoom
)).AsDouble();
356 pp::Point
scroll_offset(dict
.Get(pp::Var(kJSXOffset
)).AsInt(),
357 dict
.Get(pp::Var(kJSYOffset
)).AsInt());
359 // Bound the input parameters.
360 zoom
= std::max(kMinZoom
, zoom
);
362 scroll_offset
= BoundScrollOffsetToDocument(scroll_offset
);
363 engine_
->ScrolledToXPosition(scroll_offset
.x() * device_scale_
);
364 engine_
->ScrolledToYPosition(scroll_offset
.y() * device_scale_
);
365 } else if (type
== kJSGetPasswordCompleteType
&&
366 dict
.Get(pp::Var(kJSPassword
)).is_string()) {
367 if (password_callback_
) {
368 pp::CompletionCallbackWithOutput
<pp::Var
> callback
= *password_callback_
;
369 password_callback_
.reset();
370 *callback
.output() = dict
.Get(pp::Var(kJSPassword
)).pp_var();
375 } else if (type
== kJSPrintType
) {
377 } else if (type
== kJSResetPrintPreviewModeType
&&
378 dict
.Get(pp::Var(kJSPrintPreviewUrl
)).is_string() &&
379 dict
.Get(pp::Var(kJSPrintPreviewGrayscale
)).is_bool() &&
380 dict
.Get(pp::Var(kJSPrintPreviewPageCount
)).is_int()) {
381 url_
= dict
.Get(pp::Var(kJSPrintPreviewUrl
)).AsString();
382 preview_pages_info_
= std::queue
<PreviewPageInfo
>();
383 preview_document_load_state_
= LOAD_STATE_COMPLETE
;
384 document_load_state_
= LOAD_STATE_LOADING
;
386 preview_engine_
.reset();
387 engine_
.reset(PDFEngine::Create(this));
388 engine_
->SetGrayscale(dict
.Get(pp::Var(kJSPrintPreviewGrayscale
)).AsBool());
389 engine_
->New(url_
.c_str());
391 print_preview_page_count_
=
392 std::max(dict
.Get(pp::Var(kJSPrintPreviewPageCount
)).AsInt(), 0);
394 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
395 } else if (type
== kJSLoadPreviewPageType
&&
396 dict
.Get(pp::Var(kJSPreviewPageUrl
)).is_string() &&
397 dict
.Get(pp::Var(kJSPreviewPageIndex
)).is_int()) {
398 ProcessPreviewPageInfo(dict
.Get(pp::Var(kJSPreviewPageUrl
)).AsString(),
399 dict
.Get(pp::Var(kJSPreviewPageIndex
)).AsInt());
400 } else if (type
== kJSGetAccessibilityJSONType
) {
401 pp::VarDictionary reply
;
402 reply
.Set(pp::Var(kType
), pp::Var(kJSGetAccessibilityJSONReplyType
));
403 if (dict
.Get(pp::Var(kJSAccessibilityPageNumber
)).is_int()) {
404 int page
= dict
.Get(pp::Var(kJSAccessibilityPageNumber
)).AsInt();
405 reply
.Set(pp::Var(kJSAccessibilityJSON
),
406 pp::Var(engine_
->GetPageAsJSON(page
)));
408 base::DictionaryValue node
;
409 node
.SetInteger(kAccessibleNumberOfPages
, engine_
->GetNumberOfPages());
410 node
.SetBoolean(kAccessibleLoaded
,
411 document_load_state_
!= LOAD_STATE_LOADING
);
412 bool has_permissions
=
413 engine_
->HasPermission(PDFEngine::PERMISSION_COPY
) ||
414 engine_
->HasPermission(PDFEngine::PERMISSION_COPY_ACCESSIBLE
);
415 node
.SetBoolean(kAccessibleCopyable
, has_permissions
);
417 base::JSONWriter::Write(&node
, &json
);
418 reply
.Set(pp::Var(kJSAccessibilityJSON
), pp::Var(json
));
421 } else if (type
== kJSStopScrollingType
) {
422 stop_scrolling_
= true;
428 bool OutOfProcessInstance::HandleInputEvent(
429 const pp::InputEvent
& event
) {
430 // To simplify things, convert the event into device coordinates if it is
432 pp::InputEvent
event_device_res(event
);
434 pp::MouseInputEvent
mouse_event(event
);
435 if (!mouse_event
.is_null()) {
436 pp::Point point
= mouse_event
.GetPosition();
437 pp::Point movement
= mouse_event
.GetMovement();
438 ScalePoint(device_scale_
, &point
);
439 ScalePoint(device_scale_
, &movement
);
440 mouse_event
= pp::MouseInputEvent(
443 event
.GetTimeStamp(),
444 event
.GetModifiers(),
445 mouse_event
.GetButton(),
447 mouse_event
.GetClickCount(),
449 event_device_res
= mouse_event
;
453 pp::InputEvent
offset_event(event_device_res
);
454 switch (offset_event
.GetType()) {
455 case PP_INPUTEVENT_TYPE_MOUSEDOWN
:
456 case PP_INPUTEVENT_TYPE_MOUSEUP
:
457 case PP_INPUTEVENT_TYPE_MOUSEMOVE
:
458 case PP_INPUTEVENT_TYPE_MOUSEENTER
:
459 case PP_INPUTEVENT_TYPE_MOUSELEAVE
: {
460 pp::MouseInputEvent
mouse_event(event_device_res
);
461 pp::MouseInputEvent
mouse_event_dip(event
);
462 pp::Point point
= mouse_event
.GetPosition();
463 point
.set_x(point
.x() - available_area_
.x());
464 offset_event
= pp::MouseInputEvent(
467 event
.GetTimeStamp(),
468 event
.GetModifiers(),
469 mouse_event
.GetButton(),
471 mouse_event
.GetClickCount(),
472 mouse_event
.GetMovement());
478 if (engine_
->HandleEvent(offset_event
))
481 // TODO(raymes): Implement this scroll behavior in JS:
482 // When click+dragging, scroll the document correctly.
484 if (event
.GetType() == PP_INPUTEVENT_TYPE_KEYDOWN
&&
485 event
.GetModifiers() & kDefaultKeyModifier
) {
486 pp::KeyboardInputEvent
keyboard_event(event
);
487 switch (keyboard_event
.GetKeyCode()) {
489 engine_
->SelectAll();
494 // Return true for unhandled clicks so the plugin takes focus.
495 return (event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN
);
498 void OutOfProcessInstance::DidChangeView(const pp::View
& view
) {
499 pp::Rect
view_rect(view
.GetRect());
500 float old_device_scale
= device_scale_
;
501 float device_scale
= view
.GetDeviceScale();
502 pp::Size
view_device_size(view_rect
.width() * device_scale
,
503 view_rect
.height() * device_scale
);
505 if (view_device_size
!= plugin_size_
|| device_scale
!= device_scale_
) {
506 device_scale_
= device_scale
;
507 plugin_dip_size_
= view_rect
.size();
508 plugin_size_
= view_device_size
;
510 paint_manager_
.SetSize(view_device_size
, device_scale_
);
512 pp::Size new_image_data_size
= PaintManager::GetNewContextSize(
515 if (new_image_data_size
!= image_data_
.size()) {
516 image_data_
= pp::ImageData(this,
517 PP_IMAGEDATAFORMAT_BGRA_PREMUL
,
523 if (image_data_
.is_null()) {
524 DCHECK(plugin_size_
.IsEmpty());
528 OnGeometryChanged(zoom_
, old_device_scale
);
531 if (!stop_scrolling_
) {
532 pp::Point
scroll_offset(
533 BoundScrollOffsetToDocument(view
.GetScrollOffset()));
534 engine_
->ScrolledToXPosition(scroll_offset
.x() * device_scale_
);
535 engine_
->ScrolledToYPosition(scroll_offset
.y() * device_scale_
);
539 pp::Var
OutOfProcessInstance::GetLinkAtPosition(
540 const pp::Point
& point
) {
541 pp::Point
offset_point(point
);
542 ScalePoint(device_scale_
, &offset_point
);
543 offset_point
.set_x(offset_point
.x() - available_area_
.x());
544 return engine_
->GetLinkAtPosition(offset_point
);
547 pp::Var
OutOfProcessInstance::GetSelectedText(bool html
) {
548 if (html
|| !engine_
->HasPermission(PDFEngine::PERMISSION_COPY
))
550 return engine_
->GetSelectedText();
553 uint32_t OutOfProcessInstance::QuerySupportedPrintOutputFormats() {
554 return engine_
->QuerySupportedPrintOutputFormats();
557 int32_t OutOfProcessInstance::PrintBegin(
558 const PP_PrintSettings_Dev
& print_settings
) {
559 // For us num_pages is always equal to the number of pages in the PDF
560 // document irrespective of the printable area.
561 int32_t ret
= engine_
->GetNumberOfPages();
565 uint32_t supported_formats
= engine_
->QuerySupportedPrintOutputFormats();
566 if ((print_settings
.format
& supported_formats
) == 0)
569 print_settings_
.is_printing
= true;
570 print_settings_
.pepper_print_settings
= print_settings
;
571 engine_
->PrintBegin();
575 pp::Resource
OutOfProcessInstance::PrintPages(
576 const PP_PrintPageNumberRange_Dev
* page_ranges
,
577 uint32_t page_range_count
) {
578 if (!print_settings_
.is_printing
)
579 return pp::Resource();
581 print_settings_
.print_pages_called_
= true;
582 return engine_
->PrintPages(page_ranges
, page_range_count
,
583 print_settings_
.pepper_print_settings
);
586 void OutOfProcessInstance::PrintEnd() {
587 if (print_settings_
.print_pages_called_
)
588 UserMetricsRecordAction("PDF.PrintPage");
589 print_settings_
.Clear();
593 bool OutOfProcessInstance::IsPrintScalingDisabled() {
594 return !engine_
->GetPrintScaling();
597 bool OutOfProcessInstance::StartFind(const std::string
& text
,
598 bool case_sensitive
) {
599 engine_
->StartFind(text
.c_str(), case_sensitive
);
603 void OutOfProcessInstance::SelectFindResult(bool forward
) {
604 engine_
->SelectFindResult(forward
);
607 void OutOfProcessInstance::StopFind() {
610 SetTickmarks(tickmarks_
);
613 void OutOfProcessInstance::OnPaint(
614 const std::vector
<pp::Rect
>& paint_rects
,
615 std::vector
<PaintManager::ReadyRect
>* ready
,
616 std::vector
<pp::Rect
>* pending
) {
617 if (image_data_
.is_null()) {
618 DCHECK(plugin_size_
.IsEmpty());
622 first_paint_
= false;
623 pp::Rect rect
= pp::Rect(pp::Point(), image_data_
.size());
624 FillRect(rect
, kBackgroundColor
);
625 ready
->push_back(PaintManager::ReadyRect(rect
, image_data_
, true));
628 if (!received_viewport_message_
)
633 for (size_t i
= 0; i
< paint_rects
.size(); i
++) {
634 // Intersect with plugin area since there could be pending invalidates from
635 // when the plugin area was larger.
637 paint_rects
[i
].Intersect(pp::Rect(pp::Point(), plugin_size_
));
641 pp::Rect pdf_rect
= available_area_
.Intersect(rect
);
642 if (!pdf_rect
.IsEmpty()) {
643 pdf_rect
.Offset(available_area_
.x() * -1, 0);
645 std::vector
<pp::Rect
> pdf_ready
;
646 std::vector
<pp::Rect
> pdf_pending
;
647 engine_
->Paint(pdf_rect
, &image_data_
, &pdf_ready
, &pdf_pending
);
648 for (size_t j
= 0; j
< pdf_ready
.size(); ++j
) {
649 pdf_ready
[j
].Offset(available_area_
.point());
651 PaintManager::ReadyRect(pdf_ready
[j
], image_data_
, false));
653 for (size_t j
= 0; j
< pdf_pending
.size(); ++j
) {
654 pdf_pending
[j
].Offset(available_area_
.point());
655 pending
->push_back(pdf_pending
[j
]);
659 for (size_t j
= 0; j
< background_parts_
.size(); ++j
) {
660 pp::Rect intersection
= background_parts_
[j
].location
.Intersect(rect
);
661 if (!intersection
.IsEmpty()) {
662 FillRect(intersection
, background_parts_
[j
].color
);
664 PaintManager::ReadyRect(intersection
, image_data_
, false));
669 engine_
->PostPaint();
672 void OutOfProcessInstance::DidOpen(int32_t result
) {
673 if (result
== PP_OK
) {
674 if (!engine_
->HandleDocumentLoad(embed_loader_
)) {
675 document_load_state_
= LOAD_STATE_LOADING
;
676 DocumentLoadFailed();
678 } else if (result
!= PP_ERROR_ABORTED
) { // Can happen in tests.
680 DocumentLoadFailed();
683 // If it's a progressive load, cancel the stream URL request so that requests
684 // can be made on the original URL.
685 // TODO(raymes): Make this clearer once the in-process plugin is deleted.
686 if (engine_
->IsProgressiveLoad()) {
687 pp::VarDictionary message
;
688 message
.Set(kType
, kJSCancelStreamUrlType
);
689 PostMessage(message
);
693 void OutOfProcessInstance::DidOpenPreview(int32_t result
) {
694 if (result
== PP_OK
) {
695 preview_engine_
.reset(PDFEngine::Create(new PreviewModeClient(this)));
696 preview_engine_
->HandleDocumentLoad(embed_preview_loader_
);
702 void OutOfProcessInstance::OnClientTimerFired(int32_t id
) {
703 engine_
->OnCallback(id
);
706 void OutOfProcessInstance::CalculateBackgroundParts() {
707 background_parts_
.clear();
708 int left_width
= available_area_
.x();
709 int right_start
= available_area_
.right();
710 int right_width
= abs(plugin_size_
.width() - available_area_
.right());
711 int bottom
= std::min(available_area_
.bottom(), plugin_size_
.height());
713 // Add the left, right, and bottom rectangles. Note: we assume only
714 // horizontal centering.
715 BackgroundPart part
= {
716 pp::Rect(0, 0, left_width
, bottom
),
719 if (!part
.location
.IsEmpty())
720 background_parts_
.push_back(part
);
721 part
.location
= pp::Rect(right_start
, 0, right_width
, bottom
);
722 if (!part
.location
.IsEmpty())
723 background_parts_
.push_back(part
);
724 part
.location
= pp::Rect(
725 0, bottom
, plugin_size_
.width(), plugin_size_
.height() - bottom
);
726 if (!part
.location
.IsEmpty())
727 background_parts_
.push_back(part
);
730 int OutOfProcessInstance::GetDocumentPixelWidth() const {
731 return static_cast<int>(ceil(document_size_
.width() * zoom_
* device_scale_
));
734 int OutOfProcessInstance::GetDocumentPixelHeight() const {
735 return static_cast<int>(
736 ceil(document_size_
.height() * zoom_
* device_scale_
));
739 void OutOfProcessInstance::FillRect(const pp::Rect
& rect
, uint32 color
) {
740 DCHECK(!image_data_
.is_null() || rect
.IsEmpty());
741 uint32
* buffer_start
= static_cast<uint32
*>(image_data_
.data());
742 int stride
= image_data_
.stride();
743 uint32
* ptr
= buffer_start
+ rect
.y() * stride
/ 4 + rect
.x();
744 int height
= rect
.height();
745 int width
= rect
.width();
746 for (int y
= 0; y
< height
; ++y
) {
747 for (int x
= 0; x
< width
; ++x
)
753 void OutOfProcessInstance::DocumentSizeUpdated(const pp::Size
& size
) {
754 document_size_
= size
;
756 pp::VarDictionary dimensions
;
757 dimensions
.Set(kType
, kJSDocumentDimensionsType
);
758 dimensions
.Set(kJSDocumentWidth
, pp::Var(document_size_
.width()));
759 dimensions
.Set(kJSDocumentHeight
, pp::Var(document_size_
.height()));
760 pp::VarArray page_dimensions_array
;
761 int num_pages
= engine_
->GetNumberOfPages();
762 for (int i
= 0; i
< num_pages
; ++i
) {
763 pp::Rect page_rect
= engine_
->GetPageRect(i
);
764 pp::VarDictionary page_dimensions
;
765 page_dimensions
.Set(kJSPageX
, pp::Var(page_rect
.x()));
766 page_dimensions
.Set(kJSPageY
, pp::Var(page_rect
.y()));
767 page_dimensions
.Set(kJSPageWidth
, pp::Var(page_rect
.width()));
768 page_dimensions
.Set(kJSPageHeight
, pp::Var(page_rect
.height()));
769 page_dimensions_array
.Set(i
, page_dimensions
);
771 dimensions
.Set(kJSPageDimensions
, page_dimensions_array
);
772 PostMessage(dimensions
);
774 OnGeometryChanged(zoom_
, device_scale_
);
777 void OutOfProcessInstance::Invalidate(const pp::Rect
& rect
) {
778 pp::Rect
offset_rect(rect
);
779 offset_rect
.Offset(available_area_
.point());
780 paint_manager_
.InvalidateRect(offset_rect
);
783 void OutOfProcessInstance::Scroll(const pp::Point
& point
) {
784 if (!image_data_
.is_null())
785 paint_manager_
.ScrollRect(available_area_
, point
);
788 void OutOfProcessInstance::ScrollToX(int x
) {
789 pp::VarDictionary position
;
790 position
.Set(kType
, kJSSetScrollPositionType
);
791 position
.Set(kJSPositionX
, pp::Var(x
/ device_scale_
));
792 PostMessage(position
);
795 void OutOfProcessInstance::ScrollToY(int y
) {
796 pp::VarDictionary position
;
797 position
.Set(kType
, kJSSetScrollPositionType
);
798 position
.Set(kJSPositionY
, pp::Var(y
/ device_scale_
));
799 PostMessage(position
);
802 void OutOfProcessInstance::ScrollToPage(int page
) {
803 if (engine_
->GetNumberOfPages() == 0)
806 pp::VarDictionary message
;
807 message
.Set(kType
, kJSGoToPageType
);
808 message
.Set(kJSPageNumber
, pp::Var(page
));
809 PostMessage(message
);
812 void OutOfProcessInstance::NavigateTo(const std::string
& url
,
813 bool open_in_new_tab
) {
814 std::string
url_copy(url
);
816 // Empty |url_copy| is ok, and will effectively be a reload.
817 // Skip the code below so an empty URL does not turn into "http://", which
818 // will cause GURL to fail a DCHECK.
819 if (!url_copy
.empty()) {
820 // If |url_copy| starts with '#', then it's for the same URL with a
821 // different URL fragment.
822 if (url_copy
[0] == '#') {
823 url_copy
= url_
+ url_copy
;
825 // If there's no scheme, add http.
826 if (url_copy
.find("://") == std::string::npos
&&
827 url_copy
.find("mailto:") == std::string::npos
) {
828 url_copy
= std::string("http://") + url_copy
;
830 // Make sure |url_copy| starts with a valid scheme.
831 if (url_copy
.find("http://") != 0 &&
832 url_copy
.find("https://") != 0 &&
833 url_copy
.find("ftp://") != 0 &&
834 url_copy
.find("file://") != 0 &&
835 url_copy
.find("mailto:") != 0) {
838 // Make sure |url_copy| is not only a scheme.
839 if (url_copy
== "http://" ||
840 url_copy
== "https://" ||
841 url_copy
== "ftp://" ||
842 url_copy
== "file://" ||
843 url_copy
== "mailto:") {
847 pp::VarDictionary message
;
848 message
.Set(kType
, kJSNavigateType
);
849 message
.Set(kJSNavigateUrl
, url_copy
);
850 message
.Set(kJSNavigateNewTab
, open_in_new_tab
);
851 PostMessage(message
);
854 void OutOfProcessInstance::UpdateCursor(PP_CursorType_Dev cursor
) {
855 if (cursor
== cursor_
)
859 const PPB_CursorControl_Dev
* cursor_interface
=
860 reinterpret_cast<const PPB_CursorControl_Dev
*>(
861 pp::Module::Get()->GetBrowserInterface(PPB_CURSOR_CONTROL_DEV_INTERFACE
));
862 if (!cursor_interface
) {
867 cursor_interface
->SetCursor(
868 pp_instance(), cursor_
, pp::ImageData().pp_resource(), NULL
);
871 void OutOfProcessInstance::UpdateTickMarks(
872 const std::vector
<pp::Rect
>& tickmarks
) {
873 float inverse_scale
= 1.0f
/ device_scale_
;
874 std::vector
<pp::Rect
> scaled_tickmarks
= tickmarks
;
875 for (size_t i
= 0; i
< scaled_tickmarks
.size(); i
++)
876 ScaleRect(inverse_scale
, &scaled_tickmarks
[i
]);
877 tickmarks_
= scaled_tickmarks
;
880 void OutOfProcessInstance::NotifyNumberOfFindResultsChanged(int total
,
882 // We don't want to spam the renderer with too many updates to the number of
883 // find results. Don't send an update if we sent one too recently. If it's the
884 // final update, we always send it though.
886 NumberOfFindResultsChanged(total
, final_result
);
887 SetTickmarks(tickmarks_
);
891 if (recently_sent_find_update_
)
894 NumberOfFindResultsChanged(total
, final_result
);
895 SetTickmarks(tickmarks_
);
896 recently_sent_find_update_
= true;
897 pp::CompletionCallback callback
=
898 timer_factory_
.NewCallback(
899 &OutOfProcessInstance::ResetRecentlySentFindUpdate
);
900 pp::Module::Get()->core()->CallOnMainThread(kFindResultCooldownMs
,
904 void OutOfProcessInstance::NotifySelectedFindResultChanged(
905 int current_find_index
) {
906 SelectedFindResultChanged(current_find_index
);
909 void OutOfProcessInstance::GetDocumentPassword(
910 pp::CompletionCallbackWithOutput
<pp::Var
> callback
) {
911 if (password_callback_
) {
916 password_callback_
.reset(
917 new pp::CompletionCallbackWithOutput
<pp::Var
>(callback
));
918 pp::VarDictionary message
;
919 message
.Set(pp::Var(kType
), pp::Var(kJSGetPasswordType
));
920 PostMessage(message
);
923 void OutOfProcessInstance::Alert(const std::string
& message
) {
924 ModalDialog(this, "alert", message
, std::string());
927 bool OutOfProcessInstance::Confirm(const std::string
& message
) {
928 pp::Var result
= ModalDialog(this, "confirm", message
, std::string());
929 return result
.is_bool() ? result
.AsBool() : false;
932 std::string
OutOfProcessInstance::Prompt(const std::string
& question
,
933 const std::string
& default_answer
) {
934 pp::Var result
= ModalDialog(this, "prompt", question
, default_answer
);
935 return result
.is_string() ? result
.AsString() : std::string();
938 std::string
OutOfProcessInstance::GetURL() {
942 void OutOfProcessInstance::Email(const std::string
& to
,
943 const std::string
& cc
,
944 const std::string
& bcc
,
945 const std::string
& subject
,
946 const std::string
& body
) {
947 pp::VarDictionary message
;
948 message
.Set(pp::Var(kType
), pp::Var(kJSEmailType
));
949 message
.Set(pp::Var(kJSEmailTo
),
950 pp::Var(net::EscapeUrlEncodedData(to
, false)));
951 message
.Set(pp::Var(kJSEmailCc
),
952 pp::Var(net::EscapeUrlEncodedData(cc
, false)));
953 message
.Set(pp::Var(kJSEmailBcc
),
954 pp::Var(net::EscapeUrlEncodedData(bcc
, false)));
955 message
.Set(pp::Var(kJSEmailSubject
),
956 pp::Var(net::EscapeUrlEncodedData(subject
, false)));
957 message
.Set(pp::Var(kJSEmailBody
),
958 pp::Var(net::EscapeUrlEncodedData(body
, false)));
959 PostMessage(message
);
962 void OutOfProcessInstance::Print() {
963 if (!printing_enabled_
||
964 (!engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
) &&
965 !engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY
))) {
969 pp::CompletionCallback callback
=
970 print_callback_factory_
.NewCallback(&OutOfProcessInstance::OnPrint
);
971 pp::Module::Get()->core()->CallOnMainThread(0, callback
);
974 void OutOfProcessInstance::OnPrint(int32_t) {
975 pp::PDF::Print(this);
978 void OutOfProcessInstance::SubmitForm(const std::string
& url
,
981 pp::URLRequestInfo
request(this);
983 request
.SetMethod("POST");
984 request
.AppendDataToBody(reinterpret_cast<const char*>(data
), length
);
986 pp::CompletionCallback callback
=
987 form_factory_
.NewCallback(&OutOfProcessInstance::FormDidOpen
);
988 form_loader_
= CreateURLLoaderInternal();
989 int rv
= form_loader_
.Open(request
, callback
);
990 if (rv
!= PP_OK_COMPLETIONPENDING
)
994 void OutOfProcessInstance::FormDidOpen(int32_t result
) {
995 // TODO: inform the user of success/failure.
996 if (result
!= PP_OK
) {
1001 std::string
OutOfProcessInstance::ShowFileSelectionDialog() {
1002 // Seems like very low priority to implement, since the pdf has no way to get
1003 // the file data anyways. Javascript doesn't let you do this synchronously.
1005 return std::string();
1008 pp::URLLoader
OutOfProcessInstance::CreateURLLoader() {
1010 if (!did_call_start_loading_
) {
1011 did_call_start_loading_
= true;
1012 pp::PDF::DidStartLoading(this);
1015 // Disable save and print until the document is fully loaded, since they
1016 // would generate an incomplete document. Need to do this each time we
1017 // call DidStartLoading since that resets the content restrictions.
1018 pp::PDF::SetContentRestriction(this, CONTENT_RESTRICTION_SAVE
|
1019 CONTENT_RESTRICTION_PRINT
);
1022 return CreateURLLoaderInternal();
1025 void OutOfProcessInstance::ScheduleCallback(int id
, int delay_in_ms
) {
1026 pp::CompletionCallback callback
=
1027 timer_factory_
.NewCallback(&OutOfProcessInstance::OnClientTimerFired
);
1028 pp::Module::Get()->core()->CallOnMainThread(delay_in_ms
, callback
, id
);
1031 void OutOfProcessInstance::SearchString(const base::char16
* string
,
1032 const base::char16
* term
,
1033 bool case_sensitive
,
1034 std::vector
<SearchStringResult
>* results
) {
1035 PP_PrivateFindResult
* pp_results
;
1037 pp::PDF::SearchString(
1039 reinterpret_cast<const unsigned short*>(string
),
1040 reinterpret_cast<const unsigned short*>(term
),
1045 results
->resize(count
);
1046 for (int i
= 0; i
< count
; ++i
) {
1047 (*results
)[i
].start_index
= pp_results
[i
].start_index
;
1048 (*results
)[i
].length
= pp_results
[i
].length
;
1051 pp::Memory_Dev memory
;
1052 memory
.MemFree(pp_results
);
1055 void OutOfProcessInstance::DocumentPaintOccurred() {
1058 void OutOfProcessInstance::DocumentLoadComplete(int page_count
) {
1059 // Clear focus state for OSK.
1060 FormTextFieldFocusChange(false);
1062 DCHECK(document_load_state_
== LOAD_STATE_LOADING
);
1063 document_load_state_
= LOAD_STATE_COMPLETE
;
1064 UserMetricsRecordAction("PDF.LoadSuccess");
1066 // Note: If we are in print preview mode the scroll location is retained
1067 // across document loads so we don't want to scroll again and override it.
1068 if (IsPrintPreview()) {
1069 AppendBlankPrintPreviewPages();
1070 OnGeometryChanged(0, 0);
1073 pp::VarDictionary message
;
1074 message
.Set(pp::Var(kType
), pp::Var(kJSLoadProgressType
));
1075 message
.Set(pp::Var(kJSProgressPercentage
), pp::Var(100)) ;
1076 PostMessage(message
);
1081 if (did_call_start_loading_
) {
1082 pp::PDF::DidStopLoading(this);
1083 did_call_start_loading_
= false;
1086 int content_restrictions
=
1087 CONTENT_RESTRICTION_CUT
| CONTENT_RESTRICTION_PASTE
;
1088 if (!engine_
->HasPermission(PDFEngine::PERMISSION_COPY
))
1089 content_restrictions
|= CONTENT_RESTRICTION_COPY
;
1091 if (!engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
) &&
1092 !engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY
)) {
1093 printing_enabled_
= false;
1096 pp::PDF::SetContentRestriction(this, content_restrictions
);
1098 uma_
.HistogramCustomCounts("PDF.PageCount", page_count
,
1102 void OutOfProcessInstance::RotateClockwise() {
1103 engine_
->RotateClockwise();
1106 void OutOfProcessInstance::RotateCounterclockwise() {
1107 engine_
->RotateCounterclockwise();
1110 void OutOfProcessInstance::PreviewDocumentLoadComplete() {
1111 if (preview_document_load_state_
!= LOAD_STATE_LOADING
||
1112 preview_pages_info_
.empty()) {
1116 preview_document_load_state_
= LOAD_STATE_COMPLETE
;
1118 int dest_page_index
= preview_pages_info_
.front().second
;
1119 int src_page_index
=
1120 ExtractPrintPreviewPageIndex(preview_pages_info_
.front().first
);
1121 if (src_page_index
> 0 && dest_page_index
> -1 && preview_engine_
.get())
1122 engine_
->AppendPage(preview_engine_
.get(), dest_page_index
);
1124 preview_pages_info_
.pop();
1125 // |print_preview_page_count_| is not updated yet. Do not load any
1126 // other preview pages till we get this information.
1127 if (print_preview_page_count_
== 0)
1130 if (preview_pages_info_
.size())
1131 LoadAvailablePreviewPage();
1134 void OutOfProcessInstance::DocumentLoadFailed() {
1135 DCHECK(document_load_state_
== LOAD_STATE_LOADING
);
1136 UserMetricsRecordAction("PDF.LoadFailure");
1138 if (did_call_start_loading_
) {
1139 pp::PDF::DidStopLoading(this);
1140 did_call_start_loading_
= false;
1143 document_load_state_
= LOAD_STATE_FAILED
;
1144 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
1146 // Send a progress value of -1 to indicate a failure.
1147 pp::VarDictionary message
;
1148 message
.Set(pp::Var(kType
), pp::Var(kJSLoadProgressType
));
1149 message
.Set(pp::Var(kJSProgressPercentage
), pp::Var(-1)) ;
1150 PostMessage(message
);
1153 void OutOfProcessInstance::PreviewDocumentLoadFailed() {
1154 UserMetricsRecordAction("PDF.PreviewDocumentLoadFailure");
1155 if (preview_document_load_state_
!= LOAD_STATE_LOADING
||
1156 preview_pages_info_
.empty()) {
1160 preview_document_load_state_
= LOAD_STATE_FAILED
;
1161 preview_pages_info_
.pop();
1163 if (preview_pages_info_
.size())
1164 LoadAvailablePreviewPage();
1167 pp::Instance
* OutOfProcessInstance::GetPluginInstance() {
1171 void OutOfProcessInstance::DocumentHasUnsupportedFeature(
1172 const std::string
& feature
) {
1173 std::string
metric("PDF_Unsupported_");
1175 if (!unsupported_features_reported_
.count(metric
)) {
1176 unsupported_features_reported_
.insert(metric
);
1177 UserMetricsRecordAction(metric
);
1180 // Since we use an info bar, only do this for full frame plugins..
1184 if (told_browser_about_unsupported_feature_
)
1186 told_browser_about_unsupported_feature_
= true;
1188 pp::PDF::HasUnsupportedFeature(this);
1191 void OutOfProcessInstance::DocumentLoadProgress(uint32 available
,
1193 double progress
= 0.0;
1194 if (doc_size
== 0) {
1195 // Document size is unknown. Use heuristics.
1196 // We'll make progress logarithmic from 0 to 100M.
1197 static const double kFactor
= log(100000000.0) / 100.0;
1198 if (available
> 0) {
1199 progress
= log(static_cast<double>(available
)) / kFactor
;
1200 if (progress
> 100.0)
1204 progress
= 100.0 * static_cast<double>(available
) / doc_size
;
1207 // We send 100% load progress in DocumentLoadComplete.
1208 if (progress
>= 100)
1211 // Avoid sending too many progress messages over PostMessage.
1212 if (progress
> last_progress_sent_
+ 1) {
1213 last_progress_sent_
= progress
;
1214 pp::VarDictionary message
;
1215 message
.Set(pp::Var(kType
), pp::Var(kJSLoadProgressType
));
1216 message
.Set(pp::Var(kJSProgressPercentage
), pp::Var(progress
)) ;
1217 PostMessage(message
);
1221 void OutOfProcessInstance::FormTextFieldFocusChange(bool in_focus
) {
1222 if (!text_input_
.get())
1225 text_input_
->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_TEXT
);
1227 text_input_
->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_NONE
);
1230 void OutOfProcessInstance::ResetRecentlySentFindUpdate(int32_t /* unused */) {
1231 recently_sent_find_update_
= false;
1234 void OutOfProcessInstance::OnGeometryChanged(double old_zoom
,
1235 float old_device_scale
) {
1236 if (zoom_
!= old_zoom
|| device_scale_
!= old_device_scale
)
1237 engine_
->ZoomUpdated(zoom_
* device_scale_
);
1239 available_area_
= pp::Rect(plugin_size_
);
1240 int doc_width
= GetDocumentPixelWidth();
1241 if (doc_width
< available_area_
.width()) {
1242 available_area_
.Offset((available_area_
.width() - doc_width
) / 2, 0);
1243 available_area_
.set_width(doc_width
);
1245 int doc_height
= GetDocumentPixelHeight();
1246 if (doc_height
< available_area_
.height()) {
1247 available_area_
.set_height(doc_height
);
1250 CalculateBackgroundParts();
1251 engine_
->PageOffsetUpdated(available_area_
.point());
1252 engine_
->PluginSizeUpdated(available_area_
.size());
1254 if (!document_size_
.GetArea())
1256 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
1259 void OutOfProcessInstance::LoadUrl(const std::string
& url
) {
1260 LoadUrlInternal(url
, &embed_loader_
, &OutOfProcessInstance::DidOpen
);
1263 void OutOfProcessInstance::LoadPreviewUrl(const std::string
& url
) {
1264 LoadUrlInternal(url
, &embed_preview_loader_
,
1265 &OutOfProcessInstance::DidOpenPreview
);
1268 void OutOfProcessInstance::LoadUrlInternal(
1269 const std::string
& url
,
1270 pp::URLLoader
* loader
,
1271 void (OutOfProcessInstance::* method
)(int32_t)) {
1272 pp::URLRequestInfo
request(this);
1273 request
.SetURL(url
);
1274 request
.SetMethod("GET");
1276 *loader
= CreateURLLoaderInternal();
1277 pp::CompletionCallback callback
= loader_factory_
.NewCallback(method
);
1278 int rv
= loader
->Open(request
, callback
);
1279 if (rv
!= PP_OK_COMPLETIONPENDING
)
1283 pp::URLLoader
OutOfProcessInstance::CreateURLLoaderInternal() {
1284 pp::URLLoader
loader(this);
1286 const PPB_URLLoaderTrusted
* trusted_interface
=
1287 reinterpret_cast<const PPB_URLLoaderTrusted
*>(
1288 pp::Module::Get()->GetBrowserInterface(
1289 PPB_URLLOADERTRUSTED_INTERFACE
));
1290 if (trusted_interface
)
1291 trusted_interface
->GrantUniversalAccess(loader
.pp_resource());
1295 void OutOfProcessInstance::SetZoom(double scale
) {
1296 double old_zoom
= zoom_
;
1298 OnGeometryChanged(old_zoom
, device_scale_
);
1301 std::string
OutOfProcessInstance::GetLocalizedString(PP_ResourceString id
) {
1302 pp::Var
rv(pp::PDF::GetLocalizedString(this, id
));
1303 if (!rv
.is_string())
1304 return std::string();
1306 return rv
.AsString();
1309 void OutOfProcessInstance::AppendBlankPrintPreviewPages() {
1310 if (print_preview_page_count_
== 0)
1312 engine_
->AppendBlankPages(print_preview_page_count_
);
1313 if (preview_pages_info_
.size() > 0)
1314 LoadAvailablePreviewPage();
1317 bool OutOfProcessInstance::IsPrintPreview() {
1318 return IsPrintPreviewUrl(url_
);
1321 void OutOfProcessInstance::ProcessPreviewPageInfo(const std::string
& url
,
1322 int dst_page_index
) {
1323 if (!IsPrintPreview())
1326 int src_page_index
= ExtractPrintPreviewPageIndex(url
);
1327 if (src_page_index
< 1)
1330 preview_pages_info_
.push(std::make_pair(url
, dst_page_index
));
1331 LoadAvailablePreviewPage();
1334 void OutOfProcessInstance::LoadAvailablePreviewPage() {
1335 if (preview_pages_info_
.size() <= 0 ||
1336 document_load_state_
!= LOAD_STATE_COMPLETE
) {
1340 std::string url
= preview_pages_info_
.front().first
;
1341 int dst_page_index
= preview_pages_info_
.front().second
;
1342 int src_page_index
= ExtractPrintPreviewPageIndex(url
);
1343 if (src_page_index
< 1 ||
1344 dst_page_index
>= print_preview_page_count_
||
1345 preview_document_load_state_
== LOAD_STATE_LOADING
) {
1349 preview_document_load_state_
= LOAD_STATE_LOADING
;
1350 LoadPreviewUrl(url
);
1353 void OutOfProcessInstance::UserMetricsRecordAction(
1354 const std::string
& action
) {
1355 // TODO(raymes): Move this function to PPB_UMA_Private.
1356 pp::PDF::UserMetricsRecordAction(this, pp::Var(action
));
1359 pp::Point
OutOfProcessInstance::BoundScrollOffsetToDocument(
1360 const pp::Point
& scroll_offset
) {
1361 int max_x
= document_size_
.width() * zoom_
- plugin_dip_size_
.width();
1362 int x
= std::max(std::min(scroll_offset
.x(), max_x
), 0);
1363 int max_y
= document_size_
.height() * zoom_
- plugin_dip_size_
.height();
1364 int y
= std::max(std::min(scroll_offset
.y(), max_y
), 0);
1365 return pp::Point(x
, y
);
1368 } // namespace chrome_pdf