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"
22 #include "pdf/draw_utils.h"
24 #include "ppapi/c/dev/ppb_cursor_control_dev.h"
25 #include "ppapi/c/pp_errors.h"
26 #include "ppapi/c/pp_rect.h"
27 #include "ppapi/c/private/ppb_instance_private.h"
28 #include "ppapi/c/private/ppp_pdf.h"
29 #include "ppapi/c/trusted/ppb_url_loader_trusted.h"
30 #include "ppapi/cpp/core.h"
31 #include "ppapi/cpp/dev/memory_dev.h"
32 #include "ppapi/cpp/dev/text_input_dev.h"
33 #include "ppapi/cpp/dev/url_util_dev.h"
34 #include "ppapi/cpp/module.h"
35 #include "ppapi/cpp/point.h"
36 #include "ppapi/cpp/private/pdf.h"
37 #include "ppapi/cpp/private/var_private.h"
38 #include "ppapi/cpp/rect.h"
39 #include "ppapi/cpp/resource.h"
40 #include "ppapi/cpp/url_request_info.h"
41 #include "ppapi/cpp/var_array.h"
42 #include "ppapi/cpp/var_dictionary.h"
43 #include "ui/events/keycodes/keyboard_codes.h"
45 #if defined(OS_MACOSX)
46 #include "base/mac/mac_util.h"
49 namespace chrome_pdf
{
51 // URL reference parameters.
52 // For more possible parameters, see RFC 3778 and the "PDF Open Parameters"
53 // document from Adobe.
54 const char kDelimiters
[] = "#&";
55 const char kNamedDest
[] = "nameddest";
56 const char kPage
[] = "page";
58 const char kChromePrint
[] = "chrome://print/";
59 const char kChromeExtension
[] =
60 "chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai";
62 // Dictionary Value key names for the document accessibility info
63 const char kAccessibleNumberOfPages
[] = "numberOfPages";
64 const char kAccessibleLoaded
[] = "loaded";
65 const char kAccessibleCopyable
[] = "copyable";
67 // Constants used in handling postMessage() messages.
68 const char kType
[] = "type";
69 // Viewport message arguments. (Page -> Plugin).
70 const char kJSViewportType
[] = "viewport";
71 const char kJSXOffset
[] = "xOffset";
72 const char kJSYOffset
[] = "yOffset";
73 const char kJSZoom
[] = "zoom";
74 // Stop scrolling message (Page -> Plugin)
75 const char kJSStopScrollingType
[] = "stopScrolling";
76 // Document dimension arguments (Plugin -> Page).
77 const char kJSDocumentDimensionsType
[] = "documentDimensions";
78 const char kJSDocumentWidth
[] = "width";
79 const char kJSDocumentHeight
[] = "height";
80 const char kJSPageDimensions
[] = "pageDimensions";
81 const char kJSPageX
[] = "x";
82 const char kJSPageY
[] = "y";
83 const char kJSPageWidth
[] = "width";
84 const char kJSPageHeight
[] = "height";
85 // Document load progress arguments (Plugin -> Page)
86 const char kJSLoadProgressType
[] = "loadProgress";
87 const char kJSProgressPercentage
[] = "progress";
88 // Get password arguments (Plugin -> Page)
89 const char kJSGetPasswordType
[] = "getPassword";
90 // Get password complete arguments (Page -> Plugin)
91 const char kJSGetPasswordCompleteType
[] = "getPasswordComplete";
92 const char kJSPassword
[] = "password";
93 // Print (Page -> Plugin)
94 const char kJSPrintType
[] = "print";
95 // Go to page (Plugin -> Page)
96 const char kJSGoToPageType
[] = "goToPage";
97 const char kJSPageNumber
[] = "page";
98 // Reset print preview mode (Page -> Plugin)
99 const char kJSResetPrintPreviewModeType
[] = "resetPrintPreviewMode";
100 const char kJSPrintPreviewUrl
[] = "url";
101 const char kJSPrintPreviewGrayscale
[] = "grayscale";
102 const char kJSPrintPreviewPageCount
[] = "pageCount";
103 // Load preview page (Page -> Plugin)
104 const char kJSLoadPreviewPageType
[] = "loadPreviewPage";
105 const char kJSPreviewPageUrl
[] = "url";
106 const char kJSPreviewPageIndex
[] = "index";
107 // Set scroll position (Plugin -> Page)
108 const char kJSSetScrollPositionType
[] = "setScrollPosition";
109 const char kJSPositionX
[] = "x";
110 const char kJSPositionY
[] = "y";
111 // Set translated strings (Plugin -> Page)
112 const char kJSSetTranslatedStringsType
[] = "setTranslatedStrings";
113 const char kJSGetPasswordString
[] = "getPasswordString";
114 const char kJSLoadingString
[] = "loadingString";
115 const char kJSLoadFailedString
[] = "loadFailedString";
116 // Request accessibility JSON data (Page -> Plugin)
117 const char kJSGetAccessibilityJSONType
[] = "getAccessibilityJSON";
118 const char kJSAccessibilityPageNumber
[] = "page";
119 // Reply with accessibility JSON data (Plugin -> Page)
120 const char kJSGetAccessibilityJSONReplyType
[] = "getAccessibilityJSONReply";
121 const char kJSAccessibilityJSON
[] = "json";
122 // Cancel the stream URL request (Plugin -> Page)
123 const char kJSCancelStreamUrlType
[] = "cancelStreamUrl";
124 // Navigate to the given URL (Plugin -> Page)
125 const char kJSNavigateType
[] = "navigate";
126 const char kJSNavigateUrl
[] = "url";
127 const char kJSNavigateNewTab
[] = "newTab";
128 // Open the email editor with the given parameters (Plugin -> Page)
129 const char kJSEmailType
[] = "email";
130 const char kJSEmailTo
[] = "to";
131 const char kJSEmailCc
[] = "cc";
132 const char kJSEmailBcc
[] = "bcc";
133 const char kJSEmailSubject
[] = "subject";
134 const char kJSEmailBody
[] = "body";
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 const PPP_Pdf ppp_private
= {
176 int ExtractPrintPreviewPageIndex(const std::string
& src_url
) {
177 // Sample |src_url| format: chrome://print/id/page_index/print.pdf
178 std::vector
<std::string
> url_substr
;
179 base::SplitString(src_url
.substr(strlen(kChromePrint
)), '/', &url_substr
);
180 if (url_substr
.size() != 3)
183 if (url_substr
[2] != "print.pdf")
187 if (!base::StringToInt(url_substr
[1], &page_index
))
192 bool IsPrintPreviewUrl(const std::string
& url
) {
193 return url
.substr(0, strlen(kChromePrint
)) == kChromePrint
;
196 void ScalePoint(float scale
, pp::Point
* point
) {
197 point
->set_x(static_cast<int>(point
->x() * scale
));
198 point
->set_y(static_cast<int>(point
->y() * scale
));
201 void ScaleRect(float scale
, pp::Rect
* rect
) {
202 int left
= static_cast<int>(floorf(rect
->x() * scale
));
203 int top
= static_cast<int>(floorf(rect
->y() * scale
));
204 int right
= static_cast<int>(ceilf((rect
->x() + rect
->width()) * scale
));
205 int bottom
= static_cast<int>(ceilf((rect
->y() + rect
->height()) * scale
));
206 rect
->SetRect(left
, top
, right
- left
, bottom
- top
);
209 // TODO(raymes): Remove this dependency on VarPrivate/InstancePrivate. It's
210 // needed right now to do a synchronous call to JavaScript, but we could easily
211 // replace this with a custom PPB_PDF function.
212 pp::Var
ModalDialog(const pp::Instance
* instance
,
213 const std::string
& type
,
214 const std::string
& message
,
215 const std::string
& default_answer
) {
216 const PPB_Instance_Private
* interface
=
217 reinterpret_cast<const PPB_Instance_Private
*>(
218 pp::Module::Get()->GetBrowserInterface(
219 PPB_INSTANCE_PRIVATE_INTERFACE
));
220 pp::VarPrivate
window(pp::PASS_REF
,
221 interface
->GetWindowObject(instance
->pp_instance()));
222 if (default_answer
.empty())
223 return window
.Call(type
, message
);
225 return window
.Call(type
, message
, default_answer
);
230 OutOfProcessInstance::OutOfProcessInstance(PP_Instance instance
)
231 : pp::Instance(instance
),
232 pp::Find_Private(this),
233 pp::Printing_Dev(this),
234 pp::Selection_Dev(this),
235 cursor_(PP_CURSORTYPE_POINTER
),
238 printing_enabled_(true),
240 paint_manager_(this, this, true),
242 document_load_state_(LOAD_STATE_LOADING
),
243 preview_document_load_state_(LOAD_STATE_COMPLETE
),
245 told_browser_about_unsupported_feature_(false),
246 print_preview_page_count_(0),
247 last_progress_sent_(0),
248 recently_sent_find_update_(false),
249 received_viewport_message_(false),
250 did_call_start_loading_(false),
251 stop_scrolling_(false) {
252 loader_factory_
.Initialize(this);
253 timer_factory_
.Initialize(this);
254 form_factory_
.Initialize(this);
255 print_callback_factory_
.Initialize(this);
256 engine_
.reset(PDFEngine::Create(this));
257 pp::Module::Get()->AddPluginInterface(kPPPPdfInterface
, &ppp_private
);
258 AddPerInstanceObject(kPPPPdfInterface
, this);
260 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_MOUSE
);
261 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_KEYBOARD
);
262 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_TOUCH
);
265 OutOfProcessInstance::~OutOfProcessInstance() {
266 RemovePerInstanceObject(kPPPPdfInterface
, this);
269 bool OutOfProcessInstance::Init(uint32_t argc
,
271 const char* argv
[]) {
272 // Check if the PDF is being loaded in the PDF chrome extension. We only allow
273 // the plugin to be put into "full frame" mode when it is being loaded in the
274 // extension because this enables some features that we don't want pages
275 // abusing outside of the extension.
276 pp::Var document_url_var
= pp::URLUtil_Dev::Get()->GetDocumentURL(this);
277 std::string document_url
= document_url_var
.is_string() ?
278 document_url_var
.AsString() : std::string();
279 std::string extension_url
= std::string(kChromeExtension
);
281 !document_url
.compare(0, extension_url
.size(), extension_url
);
284 // Check if the plugin is full frame. This is passed in from JS.
285 for (uint32_t i
= 0; i
< argc
; ++i
) {
286 if (strcmp(argn
[i
], "full-frame") == 0) {
293 // Only allow the plugin to handle find requests if it is full frame.
295 SetPluginToHandleFindRequests();
297 // Send translated strings to the extension where they will be displayed.
298 // TODO(raymes): It would be better to get these in the extension directly
299 // through an API but no such API currently exists.
300 pp::VarDictionary translated_strings
;
301 translated_strings
.Set(kType
, kJSSetTranslatedStringsType
);
302 translated_strings
.Set(kJSGetPasswordString
,
303 GetLocalizedString(PP_RESOURCESTRING_PDFGETPASSWORD
));
304 translated_strings
.Set(kJSLoadingString
,
305 GetLocalizedString(PP_RESOURCESTRING_PDFLOADING
));
306 translated_strings
.Set(kJSLoadFailedString
,
307 GetLocalizedString(PP_RESOURCESTRING_PDFLOAD_FAILED
));
308 PostMessage(translated_strings
);
310 text_input_
.reset(new pp::TextInput_Dev(this));
312 const char* stream_url
= NULL
;
313 const char* original_url
= NULL
;
314 const char* headers
= NULL
;
315 for (uint32_t i
= 0; i
< argc
; ++i
) {
316 if (strcmp(argn
[i
], "src") == 0)
317 original_url
= argv
[i
];
318 else if (strcmp(argn
[i
], "stream-url") == 0)
319 stream_url
= argv
[i
];
320 else if (strcmp(argn
[i
], "headers") == 0)
324 // TODO(raymes): This is a hack to ensure that if no headers are passed in
325 // then we get the right MIME type. When the in process plugin is removed we
326 // can fix the document loader properly and remove this hack.
327 if (!headers
|| strcmp(headers
, "") == 0)
328 headers
= "content-type: application/pdf";
334 stream_url
= original_url
;
336 // If we're in print preview mode we don't need to load the document yet.
337 // A |kJSResetPrintPreviewModeType| message will be sent to the plugin letting
338 // it know the url to load. By not loading here we avoid loading the same
340 if (IsPrintPreviewUrl(original_url
))
345 return engine_
->New(original_url
, headers
);
348 void OutOfProcessInstance::HandleMessage(const pp::Var
& message
) {
349 pp::VarDictionary
dict(message
);
350 if (!dict
.Get(kType
).is_string()) {
355 std::string type
= dict
.Get(kType
).AsString();
357 if (type
== kJSViewportType
&&
358 dict
.Get(pp::Var(kJSXOffset
)).is_int() &&
359 dict
.Get(pp::Var(kJSYOffset
)).is_int() &&
360 dict
.Get(pp::Var(kJSZoom
)).is_number()) {
361 received_viewport_message_
= true;
362 stop_scrolling_
= false;
363 double zoom
= dict
.Get(pp::Var(kJSZoom
)).AsDouble();
364 pp::Point
scroll_offset(dict
.Get(pp::Var(kJSXOffset
)).AsInt(),
365 dict
.Get(pp::Var(kJSYOffset
)).AsInt());
367 // Bound the input parameters.
368 zoom
= std::max(kMinZoom
, zoom
);
370 scroll_offset
= BoundScrollOffsetToDocument(scroll_offset
);
371 engine_
->ScrolledToXPosition(scroll_offset
.x() * device_scale_
);
372 engine_
->ScrolledToYPosition(scroll_offset
.y() * device_scale_
);
373 } else if (type
== kJSGetPasswordCompleteType
&&
374 dict
.Get(pp::Var(kJSPassword
)).is_string()) {
375 if (password_callback_
) {
376 pp::CompletionCallbackWithOutput
<pp::Var
> callback
= *password_callback_
;
377 password_callback_
.reset();
378 *callback
.output() = dict
.Get(pp::Var(kJSPassword
)).pp_var();
383 } else if (type
== kJSPrintType
) {
385 } else if (type
== kJSResetPrintPreviewModeType
&&
386 dict
.Get(pp::Var(kJSPrintPreviewUrl
)).is_string() &&
387 dict
.Get(pp::Var(kJSPrintPreviewGrayscale
)).is_bool() &&
388 dict
.Get(pp::Var(kJSPrintPreviewPageCount
)).is_int()) {
389 url_
= dict
.Get(pp::Var(kJSPrintPreviewUrl
)).AsString();
390 preview_pages_info_
= std::queue
<PreviewPageInfo
>();
391 preview_document_load_state_
= LOAD_STATE_COMPLETE
;
392 document_load_state_
= LOAD_STATE_LOADING
;
394 preview_engine_
.reset();
395 engine_
.reset(PDFEngine::Create(this));
396 engine_
->SetGrayscale(dict
.Get(pp::Var(kJSPrintPreviewGrayscale
)).AsBool());
397 engine_
->New(url_
.c_str());
399 print_preview_page_count_
=
400 std::max(dict
.Get(pp::Var(kJSPrintPreviewPageCount
)).AsInt(), 0);
402 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
403 } else if (type
== kJSLoadPreviewPageType
&&
404 dict
.Get(pp::Var(kJSPreviewPageUrl
)).is_string() &&
405 dict
.Get(pp::Var(kJSPreviewPageIndex
)).is_int()) {
406 ProcessPreviewPageInfo(dict
.Get(pp::Var(kJSPreviewPageUrl
)).AsString(),
407 dict
.Get(pp::Var(kJSPreviewPageIndex
)).AsInt());
408 } else if (type
== kJSGetAccessibilityJSONType
) {
409 pp::VarDictionary reply
;
410 reply
.Set(pp::Var(kType
), pp::Var(kJSGetAccessibilityJSONReplyType
));
411 if (dict
.Get(pp::Var(kJSAccessibilityPageNumber
)).is_int()) {
412 int page
= dict
.Get(pp::Var(kJSAccessibilityPageNumber
)).AsInt();
413 reply
.Set(pp::Var(kJSAccessibilityJSON
),
414 pp::Var(engine_
->GetPageAsJSON(page
)));
416 base::DictionaryValue node
;
417 node
.SetInteger(kAccessibleNumberOfPages
, engine_
->GetNumberOfPages());
418 node
.SetBoolean(kAccessibleLoaded
,
419 document_load_state_
!= LOAD_STATE_LOADING
);
420 bool has_permissions
=
421 engine_
->HasPermission(PDFEngine::PERMISSION_COPY
) ||
422 engine_
->HasPermission(PDFEngine::PERMISSION_COPY_ACCESSIBLE
);
423 node
.SetBoolean(kAccessibleCopyable
, has_permissions
);
425 base::JSONWriter::Write(&node
, &json
);
426 reply
.Set(pp::Var(kJSAccessibilityJSON
), pp::Var(json
));
429 } else if (type
== kJSStopScrollingType
) {
430 stop_scrolling_
= true;
436 bool OutOfProcessInstance::HandleInputEvent(
437 const pp::InputEvent
& event
) {
438 // To simplify things, convert the event into device coordinates if it is
440 pp::InputEvent
event_device_res(event
);
442 pp::MouseInputEvent
mouse_event(event
);
443 if (!mouse_event
.is_null()) {
444 pp::Point point
= mouse_event
.GetPosition();
445 pp::Point movement
= mouse_event
.GetMovement();
446 ScalePoint(device_scale_
, &point
);
447 ScalePoint(device_scale_
, &movement
);
448 mouse_event
= pp::MouseInputEvent(
451 event
.GetTimeStamp(),
452 event
.GetModifiers(),
453 mouse_event
.GetButton(),
455 mouse_event
.GetClickCount(),
457 event_device_res
= mouse_event
;
461 pp::InputEvent
offset_event(event_device_res
);
462 switch (offset_event
.GetType()) {
463 case PP_INPUTEVENT_TYPE_MOUSEDOWN
:
464 case PP_INPUTEVENT_TYPE_MOUSEUP
:
465 case PP_INPUTEVENT_TYPE_MOUSEMOVE
:
466 case PP_INPUTEVENT_TYPE_MOUSEENTER
:
467 case PP_INPUTEVENT_TYPE_MOUSELEAVE
: {
468 pp::MouseInputEvent
mouse_event(event_device_res
);
469 pp::MouseInputEvent
mouse_event_dip(event
);
470 pp::Point point
= mouse_event
.GetPosition();
471 point
.set_x(point
.x() - available_area_
.x());
472 offset_event
= pp::MouseInputEvent(
475 event
.GetTimeStamp(),
476 event
.GetModifiers(),
477 mouse_event
.GetButton(),
479 mouse_event
.GetClickCount(),
480 mouse_event
.GetMovement());
486 if (engine_
->HandleEvent(offset_event
))
489 // TODO(raymes): Implement this scroll behavior in JS:
490 // When click+dragging, scroll the document correctly.
492 if (event
.GetType() == PP_INPUTEVENT_TYPE_KEYDOWN
&&
493 event
.GetModifiers() & kDefaultKeyModifier
) {
494 pp::KeyboardInputEvent
keyboard_event(event
);
495 switch (keyboard_event
.GetKeyCode()) {
497 engine_
->SelectAll();
502 // Return true for unhandled clicks so the plugin takes focus.
503 return (event
.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN
);
506 void OutOfProcessInstance::DidChangeView(const pp::View
& view
) {
507 pp::Rect
view_rect(view
.GetRect());
508 float old_device_scale
= device_scale_
;
509 float device_scale
= view
.GetDeviceScale();
510 pp::Size
view_device_size(view_rect
.width() * device_scale
,
511 view_rect
.height() * device_scale
);
513 if (view_device_size
!= plugin_size_
|| device_scale
!= device_scale_
) {
514 device_scale_
= device_scale
;
515 plugin_dip_size_
= view_rect
.size();
516 plugin_size_
= view_device_size
;
518 paint_manager_
.SetSize(view_device_size
, device_scale_
);
520 pp::Size new_image_data_size
= PaintManager::GetNewContextSize(
523 if (new_image_data_size
!= image_data_
.size()) {
524 image_data_
= pp::ImageData(this,
525 PP_IMAGEDATAFORMAT_BGRA_PREMUL
,
531 if (image_data_
.is_null()) {
532 DCHECK(plugin_size_
.IsEmpty());
536 OnGeometryChanged(zoom_
, old_device_scale
);
539 if (!stop_scrolling_
) {
540 pp::Point
scroll_offset(
541 BoundScrollOffsetToDocument(view
.GetScrollOffset()));
542 engine_
->ScrolledToXPosition(scroll_offset
.x() * device_scale_
);
543 engine_
->ScrolledToYPosition(scroll_offset
.y() * device_scale_
);
547 pp::Var
OutOfProcessInstance::GetLinkAtPosition(
548 const pp::Point
& point
) {
549 pp::Point
offset_point(point
);
550 ScalePoint(device_scale_
, &offset_point
);
551 offset_point
.set_x(offset_point
.x() - available_area_
.x());
552 return engine_
->GetLinkAtPosition(offset_point
);
555 pp::Var
OutOfProcessInstance::GetSelectedText(bool html
) {
556 if (html
|| !engine_
->HasPermission(PDFEngine::PERMISSION_COPY
))
558 return engine_
->GetSelectedText();
561 uint32_t OutOfProcessInstance::QuerySupportedPrintOutputFormats() {
562 return engine_
->QuerySupportedPrintOutputFormats();
565 int32_t OutOfProcessInstance::PrintBegin(
566 const PP_PrintSettings_Dev
& print_settings
) {
567 // For us num_pages is always equal to the number of pages in the PDF
568 // document irrespective of the printable area.
569 int32_t ret
= engine_
->GetNumberOfPages();
573 uint32_t supported_formats
= engine_
->QuerySupportedPrintOutputFormats();
574 if ((print_settings
.format
& supported_formats
) == 0)
577 print_settings_
.is_printing
= true;
578 print_settings_
.pepper_print_settings
= print_settings
;
579 engine_
->PrintBegin();
583 pp::Resource
OutOfProcessInstance::PrintPages(
584 const PP_PrintPageNumberRange_Dev
* page_ranges
,
585 uint32_t page_range_count
) {
586 if (!print_settings_
.is_printing
)
587 return pp::Resource();
589 print_settings_
.print_pages_called_
= true;
590 return engine_
->PrintPages(page_ranges
, page_range_count
,
591 print_settings_
.pepper_print_settings
);
594 void OutOfProcessInstance::PrintEnd() {
595 if (print_settings_
.print_pages_called_
)
596 UserMetricsRecordAction("PDF.PrintPage");
597 print_settings_
.Clear();
601 bool OutOfProcessInstance::IsPrintScalingDisabled() {
602 return !engine_
->GetPrintScaling();
605 bool OutOfProcessInstance::StartFind(const std::string
& text
,
606 bool case_sensitive
) {
607 engine_
->StartFind(text
.c_str(), case_sensitive
);
611 void OutOfProcessInstance::SelectFindResult(bool forward
) {
612 engine_
->SelectFindResult(forward
);
615 void OutOfProcessInstance::StopFind() {
618 SetTickmarks(tickmarks_
);
621 void OutOfProcessInstance::OnPaint(
622 const std::vector
<pp::Rect
>& paint_rects
,
623 std::vector
<PaintManager::ReadyRect
>* ready
,
624 std::vector
<pp::Rect
>* pending
) {
625 if (image_data_
.is_null()) {
626 DCHECK(plugin_size_
.IsEmpty());
630 first_paint_
= false;
631 pp::Rect rect
= pp::Rect(pp::Point(), image_data_
.size());
632 unsigned int color
= kBackgroundColorA
<< 24 |
633 kBackgroundColorR
<< 16 |
634 kBackgroundColorG
<< 8 |
636 FillRect(rect
, color
);
637 ready
->push_back(PaintManager::ReadyRect(rect
, image_data_
, true));
640 if (!received_viewport_message_
)
645 for (size_t i
= 0; i
< paint_rects
.size(); i
++) {
646 // Intersect with plugin area since there could be pending invalidates from
647 // when the plugin area was larger.
649 paint_rects
[i
].Intersect(pp::Rect(pp::Point(), plugin_size_
));
653 pp::Rect pdf_rect
= available_area_
.Intersect(rect
);
654 if (!pdf_rect
.IsEmpty()) {
655 pdf_rect
.Offset(available_area_
.x() * -1, 0);
657 std::vector
<pp::Rect
> pdf_ready
;
658 std::vector
<pp::Rect
> pdf_pending
;
659 engine_
->Paint(pdf_rect
, &image_data_
, &pdf_ready
, &pdf_pending
);
660 for (size_t j
= 0; j
< pdf_ready
.size(); ++j
) {
661 pdf_ready
[j
].Offset(available_area_
.point());
663 PaintManager::ReadyRect(pdf_ready
[j
], image_data_
, false));
665 for (size_t j
= 0; j
< pdf_pending
.size(); ++j
) {
666 pdf_pending
[j
].Offset(available_area_
.point());
667 pending
->push_back(pdf_pending
[j
]);
671 for (size_t j
= 0; j
< background_parts_
.size(); ++j
) {
672 pp::Rect intersection
= background_parts_
[j
].location
.Intersect(rect
);
673 if (!intersection
.IsEmpty()) {
674 FillRect(intersection
, background_parts_
[j
].color
);
676 PaintManager::ReadyRect(intersection
, image_data_
, false));
681 engine_
->PostPaint();
684 void OutOfProcessInstance::DidOpen(int32_t result
) {
685 if (result
== PP_OK
) {
686 if (!engine_
->HandleDocumentLoad(embed_loader_
)) {
687 document_load_state_
= LOAD_STATE_LOADING
;
688 DocumentLoadFailed();
690 } else if (result
!= PP_ERROR_ABORTED
) { // Can happen in tests.
692 DocumentLoadFailed();
695 // If it's a progressive load, cancel the stream URL request so that requests
696 // can be made on the original URL.
697 // TODO(raymes): Make this clearer once the in-process plugin is deleted.
698 if (engine_
->IsProgressiveLoad()) {
699 pp::VarDictionary message
;
700 message
.Set(kType
, kJSCancelStreamUrlType
);
701 PostMessage(message
);
705 void OutOfProcessInstance::DidOpenPreview(int32_t result
) {
706 if (result
== PP_OK
) {
707 preview_engine_
.reset(PDFEngine::Create(new PreviewModeClient(this)));
708 preview_engine_
->HandleDocumentLoad(embed_preview_loader_
);
714 void OutOfProcessInstance::OnClientTimerFired(int32_t id
) {
715 engine_
->OnCallback(id
);
718 void OutOfProcessInstance::CalculateBackgroundParts() {
719 background_parts_
.clear();
720 int left_width
= available_area_
.x();
721 int right_start
= available_area_
.right();
722 int right_width
= abs(plugin_size_
.width() - available_area_
.right());
723 int bottom
= std::min(available_area_
.bottom(), plugin_size_
.height());
725 // Add the left, right, and bottom rectangles. Note: we assume only
726 // horizontal centering.
728 part
.color
= kBackgroundColorA
<< 24 |
729 kBackgroundColorR
<< 16 |
730 kBackgroundColorG
<< 8 |
732 part
.location
= pp::Rect(0, 0, left_width
, bottom
);
733 if (!part
.location
.IsEmpty())
734 background_parts_
.push_back(part
);
735 part
.location
= pp::Rect(right_start
, 0, right_width
, bottom
);
736 if (!part
.location
.IsEmpty())
737 background_parts_
.push_back(part
);
738 part
.location
= pp::Rect(
739 0, bottom
, plugin_size_
.width(), plugin_size_
.height() - bottom
);
740 if (!part
.location
.IsEmpty())
741 background_parts_
.push_back(part
);
744 int OutOfProcessInstance::GetDocumentPixelWidth() const {
745 return static_cast<int>(ceil(document_size_
.width() * zoom_
* device_scale_
));
748 int OutOfProcessInstance::GetDocumentPixelHeight() const {
749 return static_cast<int>(
750 ceil(document_size_
.height() * zoom_
* device_scale_
));
753 void OutOfProcessInstance::FillRect(const pp::Rect
& rect
, unsigned int color
) {
754 DCHECK(!image_data_
.is_null() || rect
.IsEmpty());
755 unsigned int* buffer_start
= static_cast<unsigned int*>(image_data_
.data());
756 int stride
= image_data_
.stride();
757 unsigned int* ptr
= buffer_start
+ rect
.y() * stride
/ 4 + rect
.x();
758 int height
= rect
.height();
759 int width
= rect
.width();
760 for (int y
= 0; y
< height
; ++y
) {
761 for (int x
= 0; x
< width
; ++x
)
767 void OutOfProcessInstance::DocumentSizeUpdated(const pp::Size
& size
) {
768 document_size_
= size
;
770 pp::VarDictionary dimensions
;
771 dimensions
.Set(kType
, kJSDocumentDimensionsType
);
772 dimensions
.Set(kJSDocumentWidth
, pp::Var(document_size_
.width()));
773 dimensions
.Set(kJSDocumentHeight
, pp::Var(document_size_
.height()));
774 pp::VarArray page_dimensions_array
;
775 int num_pages
= engine_
->GetNumberOfPages();
776 for (int i
= 0; i
< num_pages
; ++i
) {
777 pp::Rect page_rect
= engine_
->GetPageRect(i
);
778 pp::VarDictionary page_dimensions
;
779 page_dimensions
.Set(kJSPageX
, pp::Var(page_rect
.x()));
780 page_dimensions
.Set(kJSPageY
, pp::Var(page_rect
.y()));
781 page_dimensions
.Set(kJSPageWidth
, pp::Var(page_rect
.width()));
782 page_dimensions
.Set(kJSPageHeight
, pp::Var(page_rect
.height()));
783 page_dimensions_array
.Set(i
, page_dimensions
);
785 dimensions
.Set(kJSPageDimensions
, page_dimensions_array
);
786 PostMessage(dimensions
);
788 OnGeometryChanged(zoom_
, device_scale_
);
791 void OutOfProcessInstance::Invalidate(const pp::Rect
& rect
) {
792 pp::Rect
offset_rect(rect
);
793 offset_rect
.Offset(available_area_
.point());
794 paint_manager_
.InvalidateRect(offset_rect
);
797 void OutOfProcessInstance::Scroll(const pp::Point
& point
) {
798 if (!image_data_
.is_null())
799 paint_manager_
.ScrollRect(available_area_
, point
);
802 void OutOfProcessInstance::ScrollToX(int x
) {
803 pp::VarDictionary position
;
804 position
.Set(kType
, kJSSetScrollPositionType
);
805 position
.Set(kJSPositionX
, pp::Var(x
/ device_scale_
));
806 PostMessage(position
);
809 void OutOfProcessInstance::ScrollToY(int y
) {
810 pp::VarDictionary position
;
811 position
.Set(kType
, kJSSetScrollPositionType
);
812 position
.Set(kJSPositionY
, pp::Var(y
/ device_scale_
));
813 PostMessage(position
);
816 void OutOfProcessInstance::ScrollToPage(int page
) {
817 if (engine_
->GetNumberOfPages() == 0)
820 pp::VarDictionary message
;
821 message
.Set(kType
, kJSGoToPageType
);
822 message
.Set(kJSPageNumber
, pp::Var(page
));
823 PostMessage(message
);
826 void OutOfProcessInstance::NavigateTo(const std::string
& url
,
827 bool open_in_new_tab
) {
828 std::string
url_copy(url
);
830 // Empty |url_copy| is ok, and will effectively be a reload.
831 // Skip the code below so an empty URL does not turn into "http://", which
832 // will cause GURL to fail a DCHECK.
833 if (!url_copy
.empty()) {
834 // If there's no scheme, add http.
835 if (url_copy
.find("://") == std::string::npos
&&
836 url_copy
.find("mailto:") == std::string::npos
) {
837 url_copy
= std::string("http://") + url_copy
;
839 // Make sure |url_copy| starts with a valid scheme.
840 if (url_copy
.find("http://") != 0 &&
841 url_copy
.find("https://") != 0 &&
842 url_copy
.find("ftp://") != 0 &&
843 url_copy
.find("mailto:") != 0) {
846 // Make sure |url_copy| is not only a scheme.
847 if (url_copy
== "http://" ||
848 url_copy
== "https://" ||
849 url_copy
== "ftp://" ||
850 url_copy
== "mailto:") {
854 pp::VarDictionary message
;
855 message
.Set(kType
, kJSNavigateType
);
856 message
.Set(kJSNavigateUrl
, url_copy
);
857 message
.Set(kJSNavigateNewTab
, open_in_new_tab
);
858 PostMessage(message
);
861 void OutOfProcessInstance::UpdateCursor(PP_CursorType_Dev cursor
) {
862 if (cursor
== cursor_
)
866 const PPB_CursorControl_Dev
* cursor_interface
=
867 reinterpret_cast<const PPB_CursorControl_Dev
*>(
868 pp::Module::Get()->GetBrowserInterface(PPB_CURSOR_CONTROL_DEV_INTERFACE
));
869 if (!cursor_interface
) {
874 cursor_interface
->SetCursor(
875 pp_instance(), cursor_
, pp::ImageData().pp_resource(), NULL
);
878 void OutOfProcessInstance::UpdateTickMarks(
879 const std::vector
<pp::Rect
>& tickmarks
) {
880 float inverse_scale
= 1.0f
/ device_scale_
;
881 std::vector
<pp::Rect
> scaled_tickmarks
= tickmarks
;
882 for (size_t i
= 0; i
< scaled_tickmarks
.size(); i
++)
883 ScaleRect(inverse_scale
, &scaled_tickmarks
[i
]);
884 tickmarks_
= scaled_tickmarks
;
887 void OutOfProcessInstance::NotifyNumberOfFindResultsChanged(int total
,
889 // We don't want to spam the renderer with too many updates to the number of
890 // find results. Don't send an update if we sent one too recently. If it's the
891 // final update, we always send it though.
893 NumberOfFindResultsChanged(total
, final_result
);
894 SetTickmarks(tickmarks_
);
898 if (recently_sent_find_update_
)
901 NumberOfFindResultsChanged(total
, final_result
);
902 SetTickmarks(tickmarks_
);
903 recently_sent_find_update_
= true;
904 pp::CompletionCallback callback
=
905 timer_factory_
.NewCallback(
906 &OutOfProcessInstance::ResetRecentlySentFindUpdate
);
907 pp::Module::Get()->core()->CallOnMainThread(kFindResultCooldownMs
,
911 void OutOfProcessInstance::NotifySelectedFindResultChanged(
912 int current_find_index
) {
913 SelectedFindResultChanged(current_find_index
);
916 void OutOfProcessInstance::GetDocumentPassword(
917 pp::CompletionCallbackWithOutput
<pp::Var
> callback
) {
918 if (password_callback_
) {
923 password_callback_
.reset(
924 new pp::CompletionCallbackWithOutput
<pp::Var
>(callback
));
925 pp::VarDictionary message
;
926 message
.Set(pp::Var(kType
), pp::Var(kJSGetPasswordType
));
927 PostMessage(message
);
930 void OutOfProcessInstance::Alert(const std::string
& message
) {
931 ModalDialog(this, "alert", message
, std::string());
934 bool OutOfProcessInstance::Confirm(const std::string
& message
) {
935 pp::Var result
= ModalDialog(this, "confirm", message
, std::string());
936 return result
.is_bool() ? result
.AsBool() : false;
939 std::string
OutOfProcessInstance::Prompt(const std::string
& question
,
940 const std::string
& default_answer
) {
941 pp::Var result
= ModalDialog(this, "prompt", question
, default_answer
);
942 return result
.is_string() ? result
.AsString() : std::string();
945 std::string
OutOfProcessInstance::GetURL() {
949 void OutOfProcessInstance::Email(const std::string
& to
,
950 const std::string
& cc
,
951 const std::string
& bcc
,
952 const std::string
& subject
,
953 const std::string
& body
) {
954 pp::VarDictionary message
;
955 message
.Set(pp::Var(kType
), pp::Var(kJSEmailType
));
956 message
.Set(pp::Var(kJSEmailTo
),
957 pp::Var(net::EscapeUrlEncodedData(to
, false)));
958 message
.Set(pp::Var(kJSEmailCc
),
959 pp::Var(net::EscapeUrlEncodedData(cc
, false)));
960 message
.Set(pp::Var(kJSEmailBcc
),
961 pp::Var(net::EscapeUrlEncodedData(bcc
, false)));
962 message
.Set(pp::Var(kJSEmailSubject
),
963 pp::Var(net::EscapeUrlEncodedData(subject
, false)));
964 message
.Set(pp::Var(kJSEmailBody
),
965 pp::Var(net::EscapeUrlEncodedData(body
, false)));
966 PostMessage(message
);
969 void OutOfProcessInstance::Print() {
970 if (!printing_enabled_
||
971 (!engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
) &&
972 !engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY
))) {
976 pp::CompletionCallback callback
=
977 print_callback_factory_
.NewCallback(&OutOfProcessInstance::OnPrint
);
978 pp::Module::Get()->core()->CallOnMainThread(0, callback
);
981 void OutOfProcessInstance::OnPrint(int32_t) {
982 pp::PDF::Print(this);
985 void OutOfProcessInstance::SubmitForm(const std::string
& url
,
988 pp::URLRequestInfo
request(this);
990 request
.SetMethod("POST");
991 request
.AppendDataToBody(reinterpret_cast<const char*>(data
), length
);
993 pp::CompletionCallback callback
=
994 form_factory_
.NewCallback(&OutOfProcessInstance::FormDidOpen
);
995 form_loader_
= CreateURLLoaderInternal();
996 int rv
= form_loader_
.Open(request
, callback
);
997 if (rv
!= PP_OK_COMPLETIONPENDING
)
1001 void OutOfProcessInstance::FormDidOpen(int32_t result
) {
1002 // TODO: inform the user of success/failure.
1003 if (result
!= PP_OK
) {
1008 std::string
OutOfProcessInstance::ShowFileSelectionDialog() {
1009 // Seems like very low priority to implement, since the pdf has no way to get
1010 // the file data anyways. Javascript doesn't let you do this synchronously.
1012 return std::string();
1015 pp::URLLoader
OutOfProcessInstance::CreateURLLoader() {
1017 if (!did_call_start_loading_
) {
1018 did_call_start_loading_
= true;
1019 pp::PDF::DidStartLoading(this);
1022 // Disable save and print until the document is fully loaded, since they
1023 // would generate an incomplete document. Need to do this each time we
1024 // call DidStartLoading since that resets the content restrictions.
1025 pp::PDF::SetContentRestriction(this, CONTENT_RESTRICTION_SAVE
|
1026 CONTENT_RESTRICTION_PRINT
);
1029 return CreateURLLoaderInternal();
1032 void OutOfProcessInstance::ScheduleCallback(int id
, int delay_in_ms
) {
1033 pp::CompletionCallback callback
=
1034 timer_factory_
.NewCallback(&OutOfProcessInstance::OnClientTimerFired
);
1035 pp::Module::Get()->core()->CallOnMainThread(delay_in_ms
, callback
, id
);
1038 void OutOfProcessInstance::SearchString(const base::char16
* string
,
1039 const base::char16
* term
,
1040 bool case_sensitive
,
1041 std::vector
<SearchStringResult
>* results
) {
1042 PP_PrivateFindResult
* pp_results
;
1044 pp::PDF::SearchString(
1046 reinterpret_cast<const unsigned short*>(string
),
1047 reinterpret_cast<const unsigned short*>(term
),
1052 results
->resize(count
);
1053 for (int i
= 0; i
< count
; ++i
) {
1054 (*results
)[i
].start_index
= pp_results
[i
].start_index
;
1055 (*results
)[i
].length
= pp_results
[i
].length
;
1058 pp::Memory_Dev memory
;
1059 memory
.MemFree(pp_results
);
1062 void OutOfProcessInstance::DocumentPaintOccurred() {
1065 void OutOfProcessInstance::DocumentLoadComplete(int page_count
) {
1066 // Clear focus state for OSK.
1067 FormTextFieldFocusChange(false);
1069 DCHECK(document_load_state_
== LOAD_STATE_LOADING
);
1070 document_load_state_
= LOAD_STATE_COMPLETE
;
1071 UserMetricsRecordAction("PDF.LoadSuccess");
1073 // Note: If we are in print preview mode the scroll location is retained
1074 // across document loads so we don't want to scroll again and override it.
1075 if (!IsPrintPreview()) {
1076 int initial_page
= GetInitialPage(url_
);
1077 if (initial_page
>= 0)
1078 ScrollToPage(initial_page
);
1080 AppendBlankPrintPreviewPages();
1081 OnGeometryChanged(0, 0);
1084 pp::VarDictionary message
;
1085 message
.Set(pp::Var(kType
), pp::Var(kJSLoadProgressType
));
1086 message
.Set(pp::Var(kJSProgressPercentage
), pp::Var(100)) ;
1087 PostMessage(message
);
1092 if (did_call_start_loading_
) {
1093 pp::PDF::DidStopLoading(this);
1094 did_call_start_loading_
= false;
1097 int content_restrictions
=
1098 CONTENT_RESTRICTION_CUT
| CONTENT_RESTRICTION_PASTE
;
1099 if (!engine_
->HasPermission(PDFEngine::PERMISSION_COPY
))
1100 content_restrictions
|= CONTENT_RESTRICTION_COPY
;
1102 if (!engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY
) &&
1103 !engine_
->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY
)) {
1104 printing_enabled_
= false;
1107 pp::PDF::SetContentRestriction(this, content_restrictions
);
1109 uma_
.HistogramCustomCounts("PDF.PageCount", page_count
,
1113 void OutOfProcessInstance::RotateClockwise() {
1114 engine_
->RotateClockwise();
1117 void OutOfProcessInstance::RotateCounterclockwise() {
1118 engine_
->RotateCounterclockwise();
1121 void OutOfProcessInstance::PreviewDocumentLoadComplete() {
1122 if (preview_document_load_state_
!= LOAD_STATE_LOADING
||
1123 preview_pages_info_
.empty()) {
1127 preview_document_load_state_
= LOAD_STATE_COMPLETE
;
1129 int dest_page_index
= preview_pages_info_
.front().second
;
1130 int src_page_index
=
1131 ExtractPrintPreviewPageIndex(preview_pages_info_
.front().first
);
1132 if (src_page_index
> 0 && dest_page_index
> -1 && preview_engine_
.get())
1133 engine_
->AppendPage(preview_engine_
.get(), dest_page_index
);
1135 preview_pages_info_
.pop();
1136 // |print_preview_page_count_| is not updated yet. Do not load any
1137 // other preview pages till we get this information.
1138 if (print_preview_page_count_
== 0)
1141 if (preview_pages_info_
.size())
1142 LoadAvailablePreviewPage();
1145 void OutOfProcessInstance::DocumentLoadFailed() {
1146 DCHECK(document_load_state_
== LOAD_STATE_LOADING
);
1147 UserMetricsRecordAction("PDF.LoadFailure");
1149 if (did_call_start_loading_
) {
1150 pp::PDF::DidStopLoading(this);
1151 did_call_start_loading_
= false;
1154 document_load_state_
= LOAD_STATE_FAILED
;
1155 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
1157 // Send a progress value of -1 to indicate a failure.
1158 pp::VarDictionary message
;
1159 message
.Set(pp::Var(kType
), pp::Var(kJSLoadProgressType
));
1160 message
.Set(pp::Var(kJSProgressPercentage
), pp::Var(-1)) ;
1161 PostMessage(message
);
1164 void OutOfProcessInstance::PreviewDocumentLoadFailed() {
1165 UserMetricsRecordAction("PDF.PreviewDocumentLoadFailure");
1166 if (preview_document_load_state_
!= LOAD_STATE_LOADING
||
1167 preview_pages_info_
.empty()) {
1171 preview_document_load_state_
= LOAD_STATE_FAILED
;
1172 preview_pages_info_
.pop();
1174 if (preview_pages_info_
.size())
1175 LoadAvailablePreviewPage();
1178 pp::Instance
* OutOfProcessInstance::GetPluginInstance() {
1182 void OutOfProcessInstance::DocumentHasUnsupportedFeature(
1183 const std::string
& feature
) {
1184 std::string
metric("PDF_Unsupported_");
1186 if (!unsupported_features_reported_
.count(metric
)) {
1187 unsupported_features_reported_
.insert(metric
);
1188 UserMetricsRecordAction(metric
);
1191 // Since we use an info bar, only do this for full frame plugins..
1195 if (told_browser_about_unsupported_feature_
)
1197 told_browser_about_unsupported_feature_
= true;
1199 pp::PDF::HasUnsupportedFeature(this);
1202 void OutOfProcessInstance::DocumentLoadProgress(uint32 available
,
1204 double progress
= 0.0;
1205 if (doc_size
== 0) {
1206 // Document size is unknown. Use heuristics.
1207 // We'll make progress logarithmic from 0 to 100M.
1208 static const double kFactor
= log(100000000.0) / 100.0;
1209 if (available
> 0) {
1210 progress
= log(static_cast<double>(available
)) / kFactor
;
1211 if (progress
> 100.0)
1215 progress
= 100.0 * static_cast<double>(available
) / doc_size
;
1218 // We send 100% load progress in DocumentLoadComplete.
1219 if (progress
>= 100)
1222 // Avoid sending too many progress messages over PostMessage.
1223 if (progress
> last_progress_sent_
+ 1) {
1224 last_progress_sent_
= progress
;
1225 pp::VarDictionary message
;
1226 message
.Set(pp::Var(kType
), pp::Var(kJSLoadProgressType
));
1227 message
.Set(pp::Var(kJSProgressPercentage
), pp::Var(progress
)) ;
1228 PostMessage(message
);
1232 void OutOfProcessInstance::FormTextFieldFocusChange(bool in_focus
) {
1233 if (!text_input_
.get())
1236 text_input_
->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_TEXT
);
1238 text_input_
->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_NONE
);
1241 void OutOfProcessInstance::ResetRecentlySentFindUpdate(int32_t /* unused */) {
1242 recently_sent_find_update_
= false;
1245 void OutOfProcessInstance::OnGeometryChanged(double old_zoom
,
1246 float old_device_scale
) {
1247 if (zoom_
!= old_zoom
|| device_scale_
!= old_device_scale
)
1248 engine_
->ZoomUpdated(zoom_
* device_scale_
);
1250 available_area_
= pp::Rect(plugin_size_
);
1251 int doc_width
= GetDocumentPixelWidth();
1252 if (doc_width
< available_area_
.width()) {
1253 available_area_
.Offset((available_area_
.width() - doc_width
) / 2, 0);
1254 available_area_
.set_width(doc_width
);
1256 int doc_height
= GetDocumentPixelHeight();
1257 if (doc_height
< available_area_
.height()) {
1258 available_area_
.set_height(doc_height
);
1261 CalculateBackgroundParts();
1262 engine_
->PageOffsetUpdated(available_area_
.point());
1263 engine_
->PluginSizeUpdated(available_area_
.size());
1265 if (!document_size_
.GetArea())
1267 paint_manager_
.InvalidateRect(pp::Rect(pp::Point(), plugin_size_
));
1270 void OutOfProcessInstance::LoadUrl(const std::string
& url
) {
1271 LoadUrlInternal(url
, &embed_loader_
, &OutOfProcessInstance::DidOpen
);
1274 void OutOfProcessInstance::LoadPreviewUrl(const std::string
& url
) {
1275 LoadUrlInternal(url
, &embed_preview_loader_
,
1276 &OutOfProcessInstance::DidOpenPreview
);
1279 void OutOfProcessInstance::LoadUrlInternal(
1280 const std::string
& url
,
1281 pp::URLLoader
* loader
,
1282 void (OutOfProcessInstance::* method
)(int32_t)) {
1283 pp::URLRequestInfo
request(this);
1284 request
.SetURL(url
);
1285 request
.SetMethod("GET");
1287 *loader
= CreateURLLoaderInternal();
1288 pp::CompletionCallback callback
= loader_factory_
.NewCallback(method
);
1289 int rv
= loader
->Open(request
, callback
);
1290 if (rv
!= PP_OK_COMPLETIONPENDING
)
1294 pp::URLLoader
OutOfProcessInstance::CreateURLLoaderInternal() {
1295 pp::URLLoader
loader(this);
1297 const PPB_URLLoaderTrusted
* trusted_interface
=
1298 reinterpret_cast<const PPB_URLLoaderTrusted
*>(
1299 pp::Module::Get()->GetBrowserInterface(
1300 PPB_URLLOADERTRUSTED_INTERFACE
));
1301 if (trusted_interface
)
1302 trusted_interface
->GrantUniversalAccess(loader
.pp_resource());
1306 int OutOfProcessInstance::GetInitialPage(const std::string
& url
) {
1307 #if defined(OS_NACL)
1310 size_t found_idx
= url
.find('#');
1311 if (found_idx
== std::string::npos
)
1314 const std::string
& ref
= url
.substr(found_idx
+ 1);
1315 std::vector
<std::string
> fragments
;
1316 Tokenize(ref
, kDelimiters
, &fragments
);
1318 // Page number to return, zero-based.
1321 // Handle the case of http://foo.com/bar#NAMEDDEST. This is not explicitly
1322 // mentioned except by example in the Adobe "PDF Open Parameters" document.
1323 if ((fragments
.size() == 1) && (fragments
[0].find('=') == std::string::npos
))
1324 return engine_
->GetNamedDestinationPage(fragments
[0]);
1326 for (size_t i
= 0; i
< fragments
.size(); ++i
) {
1327 std::vector
<std::string
> key_value
;
1328 base::SplitString(fragments
[i
], '=', &key_value
);
1329 if (key_value
.size() != 2)
1331 const std::string
& key
= key_value
[0];
1332 const std::string
& value
= key_value
[1];
1334 if (base::strcasecmp(kPage
, key
.c_str()) == 0) {
1335 // |page_value| is 1-based.
1336 int page_value
= -1;
1337 if (base::StringToInt(value
, &page_value
) && page_value
> 0)
1338 page
= page_value
- 1;
1341 if (base::strcasecmp(kNamedDest
, key
.c_str()) == 0) {
1342 // |page_value| is 0-based.
1343 int page_value
= engine_
->GetNamedDestinationPage(value
);
1344 if (page_value
>= 0)
1353 void OutOfProcessInstance::SetZoom(double scale
) {
1354 double old_zoom
= zoom_
;
1356 OnGeometryChanged(old_zoom
, device_scale_
);
1359 std::string
OutOfProcessInstance::GetLocalizedString(PP_ResourceString id
) {
1360 pp::Var
rv(pp::PDF::GetLocalizedString(this, id
));
1361 if (!rv
.is_string())
1362 return std::string();
1364 return rv
.AsString();
1367 void OutOfProcessInstance::AppendBlankPrintPreviewPages() {
1368 if (print_preview_page_count_
== 0)
1370 engine_
->AppendBlankPages(print_preview_page_count_
);
1371 if (preview_pages_info_
.size() > 0)
1372 LoadAvailablePreviewPage();
1375 bool OutOfProcessInstance::IsPrintPreview() {
1376 return IsPrintPreviewUrl(url_
);
1379 void OutOfProcessInstance::ProcessPreviewPageInfo(const std::string
& url
,
1380 int dst_page_index
) {
1381 if (!IsPrintPreview())
1384 int src_page_index
= ExtractPrintPreviewPageIndex(url
);
1385 if (src_page_index
< 1)
1388 preview_pages_info_
.push(std::make_pair(url
, dst_page_index
));
1389 LoadAvailablePreviewPage();
1392 void OutOfProcessInstance::LoadAvailablePreviewPage() {
1393 if (preview_pages_info_
.size() <= 0 ||
1394 document_load_state_
!= LOAD_STATE_COMPLETE
) {
1398 std::string url
= preview_pages_info_
.front().first
;
1399 int dst_page_index
= preview_pages_info_
.front().second
;
1400 int src_page_index
= ExtractPrintPreviewPageIndex(url
);
1401 if (src_page_index
< 1 ||
1402 dst_page_index
>= print_preview_page_count_
||
1403 preview_document_load_state_
== LOAD_STATE_LOADING
) {
1407 preview_document_load_state_
= LOAD_STATE_LOADING
;
1408 LoadPreviewUrl(url
);
1411 void OutOfProcessInstance::UserMetricsRecordAction(
1412 const std::string
& action
) {
1413 // TODO(raymes): Move this function to PPB_UMA_Private.
1414 pp::PDF::UserMetricsRecordAction(this, pp::Var(action
));
1417 pp::Point
OutOfProcessInstance::BoundScrollOffsetToDocument(
1418 const pp::Point
& scroll_offset
) {
1419 int max_x
= document_size_
.width() * zoom_
- plugin_dip_size_
.width();
1420 int x
= std::max(std::min(scroll_offset
.x(), max_x
), 0);
1421 int max_y
= document_size_
.height() * zoom_
- plugin_dip_size_
.height();
1422 int y
= std::max(std::min(scroll_offset
.y(), max_y
), 0);
1423 return pp::Point(x
, y
);
1426 } // namespace chrome_pdf