Update V8 to version 4.6.72.
[chromium-blink-merge.git] / pdf / out_of_process_instance.cc
blob705da85ab7d9bf424d5a2a23b06568420d3c7405
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()
10 #include <math.h>
11 #include <list>
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/pdf.h"
23 #include "ppapi/c/dev/ppb_cursor_control_dev.h"
24 #include "ppapi/c/pp_errors.h"
25 #include "ppapi/c/pp_rect.h"
26 #include "ppapi/c/private/ppb_instance_private.h"
27 #include "ppapi/c/private/ppp_pdf.h"
28 #include "ppapi/c/trusted/ppb_url_loader_trusted.h"
29 #include "ppapi/cpp/core.h"
30 #include "ppapi/cpp/dev/memory_dev.h"
31 #include "ppapi/cpp/dev/text_input_dev.h"
32 #include "ppapi/cpp/dev/url_util_dev.h"
33 #include "ppapi/cpp/module.h"
34 #include "ppapi/cpp/point.h"
35 #include "ppapi/cpp/private/pdf.h"
36 #include "ppapi/cpp/private/var_private.h"
37 #include "ppapi/cpp/rect.h"
38 #include "ppapi/cpp/resource.h"
39 #include "ppapi/cpp/url_request_info.h"
40 #include "ppapi/cpp/var_array.h"
41 #include "ppapi/cpp/var_dictionary.h"
42 #include "ui/events/keycodes/keyboard_codes.h"
44 namespace chrome_pdf {
46 const char kChromePrint[] = "chrome://print/";
47 const char kChromeExtension[] =
48 "chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai";
50 // Dictionary Value key names for the document accessibility info
51 const char kAccessibleNumberOfPages[] = "numberOfPages";
52 const char kAccessibleLoaded[] = "loaded";
53 const char kAccessibleCopyable[] = "copyable";
55 // PDF background colors.
56 const uint32 kBackgroundColor = 0xFFCCCCCC;
57 const uint32 kBackgroundColorMaterial = 0xFF525659;
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 // Bookmarks
81 const char kJSBookmarksType[] = "bookmarks";
82 const char kJSBookmarks[] = "bookmarks";
83 // Get password arguments (Plugin -> Page)
84 const char kJSGetPasswordType[] = "getPassword";
85 // Get password complete arguments (Page -> Plugin)
86 const char kJSGetPasswordCompleteType[] = "getPasswordComplete";
87 const char kJSPassword[] = "password";
88 // Print (Page -> Plugin)
89 const char kJSPrintType[] = "print";
90 // Save (Page -> Plugin)
91 const char kJSSaveType[] = "save";
92 // Go to page (Plugin -> Page)
93 const char kJSGoToPageType[] = "goToPage";
94 const char kJSPageNumber[] = "page";
95 // Reset print preview mode (Page -> Plugin)
96 const char kJSResetPrintPreviewModeType[] = "resetPrintPreviewMode";
97 const char kJSPrintPreviewUrl[] = "url";
98 const char kJSPrintPreviewGrayscale[] = "grayscale";
99 const char kJSPrintPreviewPageCount[] = "pageCount";
100 // Load preview page (Page -> Plugin)
101 const char kJSLoadPreviewPageType[] = "loadPreviewPage";
102 const char kJSPreviewPageUrl[] = "url";
103 const char kJSPreviewPageIndex[] = "index";
104 // Set scroll position (Plugin -> Page)
105 const char kJSSetScrollPositionType[] = "setScrollPosition";
106 const char kJSPositionX[] = "x";
107 const char kJSPositionY[] = "y";
108 // Set translated strings (Plugin -> Page)
109 const char kJSSetTranslatedStringsType[] = "setTranslatedStrings";
110 const char kJSGetPasswordString[] = "getPasswordString";
111 const char kJSLoadingString[] = "loadingString";
112 const char kJSLoadFailedString[] = "loadFailedString";
113 // Request accessibility JSON data (Page -> Plugin)
114 const char kJSGetAccessibilityJSONType[] = "getAccessibilityJSON";
115 const char kJSAccessibilityPageNumber[] = "page";
116 // Reply with accessibility JSON data (Plugin -> Page)
117 const char kJSGetAccessibilityJSONReplyType[] = "getAccessibilityJSONReply";
118 const char kJSAccessibilityJSON[] = "json";
119 // Cancel the stream URL request (Plugin -> Page)
120 const char kJSCancelStreamUrlType[] = "cancelStreamUrl";
121 // Navigate to the given URL (Plugin -> Page)
122 const char kJSNavigateType[] = "navigate";
123 const char kJSNavigateUrl[] = "url";
124 const char kJSNavigateNewTab[] = "newTab";
125 // Open the email editor with the given parameters (Plugin -> Page)
126 const char kJSEmailType[] = "email";
127 const char kJSEmailTo[] = "to";
128 const char kJSEmailCc[] = "cc";
129 const char kJSEmailBcc[] = "bcc";
130 const char kJSEmailSubject[] = "subject";
131 const char kJSEmailBody[] = "body";
132 // Rotation (Page -> Plugin)
133 const char kJSRotateClockwiseType[] = "rotateClockwise";
134 const char kJSRotateCounterclockwiseType[] = "rotateCounterclockwise";
135 // Select all text in the document (Page -> Plugin)
136 const char kJSSelectAllType[] = "selectAll";
137 // Get the selected text in the document (Page -> Plugin)
138 const char kJSGetSelectedTextType[] = "getSelectedText";
139 // Reply with selected text (Plugin -> Page)
140 const char kJSGetSelectedTextReplyType[] = "getSelectedTextReply";
141 const char kJSSelectedText[] = "selectedText";
143 // Get the named destination with the given name (Page -> Plugin)
144 const char KJSGetNamedDestinationType[] = "getNamedDestination";
145 const char KJSGetNamedDestination[] = "namedDestination";
146 // Reply with the page number of the named destination (Plugin -> Page)
147 const char kJSGetNamedDestinationReplyType[] = "getNamedDestinationReply";
148 const char kJSNamedDestinationPageNumber[] = "pageNumber";
150 // Selecting text in document (Plugin -> Page)
151 const char kJSSetIsSelectingType[] = "setIsSelecting";
152 const char kJSIsSelecting[] = "isSelecting";
154 const int kFindResultCooldownMs = 100;
156 const double kMinZoom = 0.01;
158 namespace {
160 static const char kPPPPdfInterface[] = PPP_PDF_INTERFACE_1;
162 PP_Var GetLinkAtPosition(PP_Instance instance, PP_Point point) {
163 pp::Var var;
164 void* object = pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
165 if (object) {
166 var = static_cast<OutOfProcessInstance*>(object)->GetLinkAtPosition(
167 pp::Point(point));
169 return var.Detach();
172 void Transform(PP_Instance instance, PP_PrivatePageTransformType type) {
173 void* object =
174 pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
175 if (object) {
176 OutOfProcessInstance* obj_instance =
177 static_cast<OutOfProcessInstance*>(object);
178 switch (type) {
179 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CW:
180 obj_instance->RotateClockwise();
181 break;
182 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CCW:
183 obj_instance->RotateCounterclockwise();
184 break;
189 PP_Bool GetPrintPresetOptionsFromDocument(
190 PP_Instance instance,
191 PP_PdfPrintPresetOptions_Dev* options) {
192 void* object = pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
193 if (object) {
194 OutOfProcessInstance* obj_instance =
195 static_cast<OutOfProcessInstance*>(object);
196 obj_instance->GetPrintPresetOptionsFromDocument(options);
198 return PP_TRUE;
201 const PPP_Pdf ppp_private = {
202 &GetLinkAtPosition,
203 &Transform,
204 &GetPrintPresetOptionsFromDocument
207 int ExtractPrintPreviewPageIndex(const std::string& src_url) {
208 // Sample |src_url| format: chrome://print/id/page_index/print.pdf
209 std::vector<std::string> url_substr = base::SplitString(
210 src_url.substr(strlen(kChromePrint)), "/",
211 base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
212 if (url_substr.size() != 3)
213 return -1;
215 if (url_substr[2] != "print.pdf")
216 return -1;
218 int page_index = 0;
219 if (!base::StringToInt(url_substr[1], &page_index))
220 return -1;
221 return page_index;
224 bool IsPrintPreviewUrl(const std::string& url) {
225 return url.substr(0, strlen(kChromePrint)) == kChromePrint;
228 void ScalePoint(float scale, pp::Point* point) {
229 point->set_x(static_cast<int>(point->x() * scale));
230 point->set_y(static_cast<int>(point->y() * scale));
233 void ScaleRect(float scale, pp::Rect* rect) {
234 int left = static_cast<int>(floorf(rect->x() * scale));
235 int top = static_cast<int>(floorf(rect->y() * scale));
236 int right = static_cast<int>(ceilf((rect->x() + rect->width()) * scale));
237 int bottom = static_cast<int>(ceilf((rect->y() + rect->height()) * scale));
238 rect->SetRect(left, top, right - left, bottom - top);
241 // TODO(raymes): Remove this dependency on VarPrivate/InstancePrivate. It's
242 // needed right now to do a synchronous call to JavaScript, but we could easily
243 // replace this with a custom PPB_PDF function.
244 pp::Var ModalDialog(const pp::Instance* instance,
245 const std::string& type,
246 const std::string& message,
247 const std::string& default_answer) {
248 const PPB_Instance_Private* interface =
249 reinterpret_cast<const PPB_Instance_Private*>(
250 pp::Module::Get()->GetBrowserInterface(
251 PPB_INSTANCE_PRIVATE_INTERFACE));
252 pp::VarPrivate window(pp::PASS_REF,
253 interface->GetWindowObject(instance->pp_instance()));
254 if (default_answer.empty())
255 return window.Call(type, message);
256 else
257 return window.Call(type, message, default_answer);
260 } // namespace
262 OutOfProcessInstance::OutOfProcessInstance(PP_Instance instance)
263 : pp::Instance(instance),
264 pp::Find_Private(this),
265 pp::Printing_Dev(this),
266 cursor_(PP_CURSORTYPE_POINTER),
267 zoom_(1.0),
268 device_scale_(1.0),
269 full_(false),
270 paint_manager_(this, this, true),
271 first_paint_(true),
272 document_load_state_(LOAD_STATE_LOADING),
273 preview_document_load_state_(LOAD_STATE_COMPLETE),
274 uma_(this),
275 told_browser_about_unsupported_feature_(false),
276 print_preview_page_count_(0),
277 last_progress_sent_(0),
278 recently_sent_find_update_(false),
279 received_viewport_message_(false),
280 did_call_start_loading_(false),
281 stop_scrolling_(false),
282 background_color_(kBackgroundColor),
283 top_toolbar_height_(0) {
284 loader_factory_.Initialize(this);
285 timer_factory_.Initialize(this);
286 form_factory_.Initialize(this);
287 print_callback_factory_.Initialize(this);
288 engine_.reset(PDFEngine::Create(this));
289 pp::Module::Get()->AddPluginInterface(kPPPPdfInterface, &ppp_private);
290 AddPerInstanceObject(kPPPPdfInterface, this);
292 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_MOUSE);
293 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_KEYBOARD);
294 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_TOUCH);
297 OutOfProcessInstance::~OutOfProcessInstance() {
298 RemovePerInstanceObject(kPPPPdfInterface, this);
299 // Explicitly reset the PDFEngine during destruction as it may call back into
300 // this object.
301 engine_.reset();
304 bool OutOfProcessInstance::Init(uint32_t argc,
305 const char* argn[],
306 const char* argv[]) {
307 // Check if the PDF is being loaded in the PDF chrome extension. We only allow
308 // the plugin to be put into "full frame" mode when it is being loaded in the
309 // extension because this enables some features that we don't want pages
310 // abusing outside of the extension.
311 pp::Var document_url_var = pp::URLUtil_Dev::Get()->GetDocumentURL(this);
312 std::string document_url = document_url_var.is_string() ?
313 document_url_var.AsString() : std::string();
314 std::string extension_url = std::string(kChromeExtension);
315 bool in_extension =
316 !document_url.compare(0, extension_url.size(), extension_url);
318 if (in_extension) {
319 // Check if the plugin is full frame. This is passed in from JS.
320 for (uint32_t i = 0; i < argc; ++i) {
321 if (strcmp(argn[i], "full-frame") == 0) {
322 full_ = true;
323 break;
328 // Only allow the plugin to handle find requests if it is full frame.
329 if (full_)
330 SetPluginToHandleFindRequests();
332 // Send translated strings to the extension where they will be displayed.
333 // TODO(raymes): It would be better to get these in the extension directly
334 // through an API but no such API currently exists.
335 pp::VarDictionary translated_strings;
336 translated_strings.Set(kType, kJSSetTranslatedStringsType);
337 translated_strings.Set(kJSGetPasswordString,
338 GetLocalizedString(PP_RESOURCESTRING_PDFGETPASSWORD));
339 translated_strings.Set(kJSLoadingString,
340 GetLocalizedString(PP_RESOURCESTRING_PDFLOADING));
341 translated_strings.Set(kJSLoadFailedString,
342 GetLocalizedString(PP_RESOURCESTRING_PDFLOAD_FAILED));
343 PostMessage(translated_strings);
345 text_input_.reset(new pp::TextInput_Dev(this));
347 const char* stream_url = nullptr;
348 const char* original_url = nullptr;
349 const char* headers = nullptr;
350 bool is_material = false;
351 for (uint32_t i = 0; i < argc; ++i) {
352 if (strcmp(argn[i], "src") == 0)
353 original_url = argv[i];
354 else if (strcmp(argn[i], "stream-url") == 0)
355 stream_url = argv[i];
356 else if (strcmp(argn[i], "headers") == 0)
357 headers = argv[i];
358 else if (strcmp(argn[i], "is-material") == 0)
359 is_material = true;
360 else if (strcmp(argn[i], "top-toolbar-height") == 0)
361 base::StringToInt(argv[i], &top_toolbar_height_);
364 if (is_material)
365 background_color_ = kBackgroundColorMaterial;
366 else
367 background_color_ = kBackgroundColor;
369 if (!original_url)
370 return false;
372 if (!stream_url)
373 stream_url = original_url;
375 // If we're in print preview mode we don't need to load the document yet.
376 // A |kJSResetPrintPreviewModeType| message will be sent to the plugin letting
377 // it know the url to load. By not loading here we avoid loading the same
378 // document twice.
379 if (IsPrintPreviewUrl(original_url))
380 return true;
382 LoadUrl(stream_url);
383 url_ = original_url;
384 return engine_->New(original_url, headers);
387 void OutOfProcessInstance::HandleMessage(const pp::Var& message) {
388 pp::VarDictionary dict(message);
389 if (!dict.Get(kType).is_string()) {
390 NOTREACHED();
391 return;
394 std::string type = dict.Get(kType).AsString();
396 if (type == kJSViewportType &&
397 dict.Get(pp::Var(kJSXOffset)).is_number() &&
398 dict.Get(pp::Var(kJSYOffset)).is_number() &&
399 dict.Get(pp::Var(kJSZoom)).is_number()) {
400 received_viewport_message_ = true;
401 stop_scrolling_ = false;
402 double zoom = dict.Get(pp::Var(kJSZoom)).AsDouble();
403 pp::FloatPoint scroll_offset(dict.Get(pp::Var(kJSXOffset)).AsDouble(),
404 dict.Get(pp::Var(kJSYOffset)).AsDouble());
406 // Bound the input parameters.
407 zoom = std::max(kMinZoom, zoom);
408 SetZoom(zoom);
409 scroll_offset = BoundScrollOffsetToDocument(scroll_offset);
410 engine_->ScrolledToXPosition(scroll_offset.x() * device_scale_);
411 engine_->ScrolledToYPosition(scroll_offset.y() * device_scale_);
412 } else if (type == kJSGetPasswordCompleteType &&
413 dict.Get(pp::Var(kJSPassword)).is_string()) {
414 if (password_callback_) {
415 pp::CompletionCallbackWithOutput<pp::Var> callback = *password_callback_;
416 password_callback_.reset();
417 *callback.output() = dict.Get(pp::Var(kJSPassword)).pp_var();
418 callback.Run(PP_OK);
419 } else {
420 NOTREACHED();
422 } else if (type == kJSPrintType) {
423 Print();
424 } else if (type == kJSSaveType) {
425 pp::PDF::SaveAs(this);
426 } else if (type == kJSRotateClockwiseType) {
427 RotateClockwise();
428 } else if (type == kJSRotateCounterclockwiseType) {
429 RotateCounterclockwise();
430 } else if (type == kJSSelectAllType) {
431 engine_->SelectAll();
432 } else if (type == kJSResetPrintPreviewModeType &&
433 dict.Get(pp::Var(kJSPrintPreviewUrl)).is_string() &&
434 dict.Get(pp::Var(kJSPrintPreviewGrayscale)).is_bool() &&
435 dict.Get(pp::Var(kJSPrintPreviewPageCount)).is_int()) {
436 url_ = dict.Get(pp::Var(kJSPrintPreviewUrl)).AsString();
437 preview_pages_info_ = std::queue<PreviewPageInfo>();
438 preview_document_load_state_ = LOAD_STATE_COMPLETE;
439 document_load_state_ = LOAD_STATE_LOADING;
440 LoadUrl(url_);
441 preview_engine_.reset();
442 engine_.reset(PDFEngine::Create(this));
443 engine_->SetGrayscale(dict.Get(pp::Var(kJSPrintPreviewGrayscale)).AsBool());
444 engine_->New(url_.c_str(), nullptr /* empty header */);
446 print_preview_page_count_ =
447 std::max(dict.Get(pp::Var(kJSPrintPreviewPageCount)).AsInt(), 0);
449 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
450 } else if (type == kJSLoadPreviewPageType &&
451 dict.Get(pp::Var(kJSPreviewPageUrl)).is_string() &&
452 dict.Get(pp::Var(kJSPreviewPageIndex)).is_int()) {
453 ProcessPreviewPageInfo(dict.Get(pp::Var(kJSPreviewPageUrl)).AsString(),
454 dict.Get(pp::Var(kJSPreviewPageIndex)).AsInt());
455 } else if (type == kJSGetAccessibilityJSONType) {
456 pp::VarDictionary reply;
457 reply.Set(pp::Var(kType), pp::Var(kJSGetAccessibilityJSONReplyType));
458 if (dict.Get(pp::Var(kJSAccessibilityPageNumber)).is_int()) {
459 int page = dict.Get(pp::Var(kJSAccessibilityPageNumber)).AsInt();
460 reply.Set(pp::Var(kJSAccessibilityJSON),
461 pp::Var(engine_->GetPageAsJSON(page)));
462 } else {
463 base::DictionaryValue node;
464 node.SetInteger(kAccessibleNumberOfPages, engine_->GetNumberOfPages());
465 node.SetBoolean(kAccessibleLoaded,
466 document_load_state_ != LOAD_STATE_LOADING);
467 bool has_permissions =
468 engine_->HasPermission(PDFEngine::PERMISSION_COPY) ||
469 engine_->HasPermission(PDFEngine::PERMISSION_COPY_ACCESSIBLE);
470 node.SetBoolean(kAccessibleCopyable, has_permissions);
471 std::string json;
472 base::JSONWriter::Write(node, &json);
473 reply.Set(pp::Var(kJSAccessibilityJSON), pp::Var(json));
475 PostMessage(reply);
476 } else if (type == kJSStopScrollingType) {
477 stop_scrolling_ = true;
478 } else if (type == kJSGetSelectedTextType) {
479 std::string selected_text = engine_->GetSelectedText();
480 // Always return unix newlines to JS.
481 base::ReplaceChars(selected_text, "\r", std::string(), &selected_text);
482 pp::VarDictionary reply;
483 reply.Set(pp::Var(kType), pp::Var(kJSGetSelectedTextReplyType));
484 reply.Set(pp::Var(kJSSelectedText), selected_text);
485 PostMessage(reply);
486 } else if (type == KJSGetNamedDestinationType &&
487 dict.Get(pp::Var(KJSGetNamedDestination)).is_string()) {
488 int page_number = engine_->GetNamedDestinationPage(
489 dict.Get(pp::Var(KJSGetNamedDestination)).AsString());
490 pp::VarDictionary reply;
491 reply.Set(pp::Var(kType), pp::Var(kJSGetNamedDestinationReplyType));
492 if (page_number >= 0)
493 reply.Set(pp::Var(kJSNamedDestinationPageNumber), page_number);
494 PostMessage(reply);
495 } else {
496 NOTREACHED();
500 bool OutOfProcessInstance::HandleInputEvent(
501 const pp::InputEvent& event) {
502 // To simplify things, convert the event into device coordinates if it is
503 // a mouse event.
504 pp::InputEvent event_device_res(event);
506 pp::MouseInputEvent mouse_event(event);
507 if (!mouse_event.is_null()) {
508 pp::Point point = mouse_event.GetPosition();
509 pp::Point movement = mouse_event.GetMovement();
510 ScalePoint(device_scale_, &point);
511 ScalePoint(device_scale_, &movement);
512 mouse_event = pp::MouseInputEvent(
513 this,
514 event.GetType(),
515 event.GetTimeStamp(),
516 event.GetModifiers(),
517 mouse_event.GetButton(),
518 point,
519 mouse_event.GetClickCount(),
520 movement);
521 event_device_res = mouse_event;
525 pp::InputEvent offset_event(event_device_res);
526 switch (offset_event.GetType()) {
527 case PP_INPUTEVENT_TYPE_MOUSEDOWN:
528 case PP_INPUTEVENT_TYPE_MOUSEUP:
529 case PP_INPUTEVENT_TYPE_MOUSEMOVE:
530 case PP_INPUTEVENT_TYPE_MOUSEENTER:
531 case PP_INPUTEVENT_TYPE_MOUSELEAVE: {
532 pp::MouseInputEvent mouse_event(event_device_res);
533 pp::MouseInputEvent mouse_event_dip(event);
534 pp::Point point = mouse_event.GetPosition();
535 point.set_x(point.x() - available_area_.x());
536 offset_event = pp::MouseInputEvent(
537 this,
538 event.GetType(),
539 event.GetTimeStamp(),
540 event.GetModifiers(),
541 mouse_event.GetButton(),
542 point,
543 mouse_event.GetClickCount(),
544 mouse_event.GetMovement());
545 break;
547 default:
548 break;
550 if (engine_->HandleEvent(offset_event))
551 return true;
553 // Middle click is used for scrolling and is handled by the container page.
554 pp::MouseInputEvent mouse_event(event_device_res);
555 if (!mouse_event.is_null() &&
556 mouse_event.GetButton() == PP_INPUTEVENT_MOUSEBUTTON_MIDDLE) {
557 return false;
560 // Return true for unhandled clicks so the plugin takes focus.
561 return (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN);
564 void OutOfProcessInstance::DidChangeView(const pp::View& view) {
565 pp::Rect view_rect(view.GetRect());
566 float old_device_scale = device_scale_;
567 float device_scale = view.GetDeviceScale();
568 pp::Size view_device_size(view_rect.width() * device_scale,
569 view_rect.height() * device_scale);
571 if (view_device_size != plugin_size_ || device_scale != device_scale_) {
572 device_scale_ = device_scale;
573 plugin_dip_size_ = view_rect.size();
574 plugin_size_ = view_device_size;
576 paint_manager_.SetSize(view_device_size, device_scale_);
578 pp::Size new_image_data_size = PaintManager::GetNewContextSize(
579 image_data_.size(),
580 plugin_size_);
581 if (new_image_data_size != image_data_.size()) {
582 image_data_ = pp::ImageData(this,
583 PP_IMAGEDATAFORMAT_BGRA_PREMUL,
584 new_image_data_size,
585 false);
586 first_paint_ = true;
589 if (image_data_.is_null()) {
590 DCHECK(plugin_size_.IsEmpty());
591 return;
594 OnGeometryChanged(zoom_, old_device_scale);
597 if (!stop_scrolling_) {
598 pp::Point scroll_offset(view.GetScrollOffset());
599 // Because view messages come from the DOM, the coordinates of the viewport
600 // are 0-based (i.e. they do not correspond to the viewport's coordinates in
601 // JS), so we need to subtract the toolbar height to convert them into
602 // viewport coordinates.
603 pp::FloatPoint scroll_offset_float(scroll_offset.x(),
604 scroll_offset.y() - top_toolbar_height_);
605 scroll_offset_float = BoundScrollOffsetToDocument(scroll_offset_float);
606 engine_->ScrolledToXPosition(scroll_offset_float.x() * device_scale_);
607 engine_->ScrolledToYPosition(scroll_offset_float.y() * device_scale_);
611 void OutOfProcessInstance::GetPrintPresetOptionsFromDocument(
612 PP_PdfPrintPresetOptions_Dev* options) {
613 options->is_scaling_disabled = PP_FromBool(IsPrintScalingDisabled());
614 options->duplex =
615 static_cast<PP_PrivateDuplexMode_Dev>(engine_->GetDuplexType());
616 options->copies = engine_->GetCopiesToPrint();
617 pp::Size uniform_page_size;
618 options->is_page_size_uniform =
619 PP_FromBool(engine_->GetPageSizeAndUniformity(&uniform_page_size));
620 options->uniform_page_size = uniform_page_size;
623 pp::Var OutOfProcessInstance::GetLinkAtPosition(
624 const pp::Point& point) {
625 pp::Point offset_point(point);
626 ScalePoint(device_scale_, &offset_point);
627 offset_point.set_x(offset_point.x() - available_area_.x());
628 return engine_->GetLinkAtPosition(offset_point);
631 uint32_t OutOfProcessInstance::QuerySupportedPrintOutputFormats() {
632 return engine_->QuerySupportedPrintOutputFormats();
635 int32_t OutOfProcessInstance::PrintBegin(
636 const PP_PrintSettings_Dev& print_settings) {
637 // For us num_pages is always equal to the number of pages in the PDF
638 // document irrespective of the printable area.
639 int32_t ret = engine_->GetNumberOfPages();
640 if (!ret)
641 return 0;
643 uint32_t supported_formats = engine_->QuerySupportedPrintOutputFormats();
644 if ((print_settings.format & supported_formats) == 0)
645 return 0;
647 print_settings_.is_printing = true;
648 print_settings_.pepper_print_settings = print_settings;
649 engine_->PrintBegin();
650 return ret;
653 pp::Resource OutOfProcessInstance::PrintPages(
654 const PP_PrintPageNumberRange_Dev* page_ranges,
655 uint32_t page_range_count) {
656 if (!print_settings_.is_printing)
657 return pp::Resource();
659 print_settings_.print_pages_called_ = true;
660 return engine_->PrintPages(page_ranges, page_range_count,
661 print_settings_.pepper_print_settings);
664 void OutOfProcessInstance::PrintEnd() {
665 if (print_settings_.print_pages_called_)
666 UserMetricsRecordAction("PDF.PrintPage");
667 print_settings_.Clear();
668 engine_->PrintEnd();
671 bool OutOfProcessInstance::IsPrintScalingDisabled() {
672 return !engine_->GetPrintScaling();
675 bool OutOfProcessInstance::StartFind(const std::string& text,
676 bool case_sensitive) {
677 engine_->StartFind(text.c_str(), case_sensitive);
678 return true;
681 void OutOfProcessInstance::SelectFindResult(bool forward) {
682 engine_->SelectFindResult(forward);
685 void OutOfProcessInstance::StopFind() {
686 engine_->StopFind();
687 tickmarks_.clear();
688 SetTickmarks(tickmarks_);
691 void OutOfProcessInstance::OnPaint(
692 const std::vector<pp::Rect>& paint_rects,
693 std::vector<PaintManager::ReadyRect>* ready,
694 std::vector<pp::Rect>* pending) {
695 if (image_data_.is_null()) {
696 DCHECK(plugin_size_.IsEmpty());
697 return;
699 if (first_paint_) {
700 first_paint_ = false;
701 pp::Rect rect = pp::Rect(pp::Point(), image_data_.size());
702 FillRect(rect, background_color_);
703 ready->push_back(PaintManager::ReadyRect(rect, image_data_, true));
706 if (!received_viewport_message_)
707 return;
709 engine_->PrePaint();
711 for (size_t i = 0; i < paint_rects.size(); i++) {
712 // Intersect with plugin area since there could be pending invalidates from
713 // when the plugin area was larger.
714 pp::Rect rect =
715 paint_rects[i].Intersect(pp::Rect(pp::Point(), plugin_size_));
716 if (rect.IsEmpty())
717 continue;
719 pp::Rect pdf_rect = available_area_.Intersect(rect);
720 if (!pdf_rect.IsEmpty()) {
721 pdf_rect.Offset(available_area_.x() * -1, 0);
723 std::vector<pp::Rect> pdf_ready;
724 std::vector<pp::Rect> pdf_pending;
725 engine_->Paint(pdf_rect, &image_data_, &pdf_ready, &pdf_pending);
726 for (size_t j = 0; j < pdf_ready.size(); ++j) {
727 pdf_ready[j].Offset(available_area_.point());
728 ready->push_back(
729 PaintManager::ReadyRect(pdf_ready[j], image_data_, false));
731 for (size_t j = 0; j < pdf_pending.size(); ++j) {
732 pdf_pending[j].Offset(available_area_.point());
733 pending->push_back(pdf_pending[j]);
737 // Ensure the region above the first page (if any) is filled;
738 int32_t first_page_ypos = engine_->GetNumberOfPages() == 0 ?
739 0 : engine_->GetPageScreenRect(0).y();
740 if (rect.y() < first_page_ypos) {
741 pp::Rect region = rect.Intersect(pp::Rect(
742 pp::Point(), pp::Size(plugin_size_.width(), first_page_ypos)));
743 ready->push_back(PaintManager::ReadyRect(region, image_data_, false));
744 FillRect(region, background_color_);
747 for (size_t j = 0; j < background_parts_.size(); ++j) {
748 pp::Rect intersection = background_parts_[j].location.Intersect(rect);
749 if (!intersection.IsEmpty()) {
750 FillRect(intersection, background_parts_[j].color);
751 ready->push_back(
752 PaintManager::ReadyRect(intersection, image_data_, false));
757 engine_->PostPaint();
760 void OutOfProcessInstance::DidOpen(int32_t result) {
761 if (result == PP_OK) {
762 if (!engine_->HandleDocumentLoad(embed_loader_)) {
763 document_load_state_ = LOAD_STATE_LOADING;
764 DocumentLoadFailed();
766 } else if (result != PP_ERROR_ABORTED) { // Can happen in tests.
767 NOTREACHED();
768 DocumentLoadFailed();
771 // If it's a progressive load, cancel the stream URL request so that requests
772 // can be made on the original URL.
773 // TODO(raymes): Make this clearer once the in-process plugin is deleted.
774 if (engine_->IsProgressiveLoad()) {
775 pp::VarDictionary message;
776 message.Set(kType, kJSCancelStreamUrlType);
777 PostMessage(message);
781 void OutOfProcessInstance::DidOpenPreview(int32_t result) {
782 if (result == PP_OK) {
783 preview_engine_.reset(PDFEngine::Create(new PreviewModeClient(this)));
784 preview_engine_->HandleDocumentLoad(embed_preview_loader_);
785 } else {
786 NOTREACHED();
790 void OutOfProcessInstance::OnClientTimerFired(int32_t id) {
791 engine_->OnCallback(id);
794 void OutOfProcessInstance::CalculateBackgroundParts() {
795 background_parts_.clear();
796 int left_width = available_area_.x();
797 int right_start = available_area_.right();
798 int right_width = abs(plugin_size_.width() - available_area_.right());
799 int bottom = std::min(available_area_.bottom(), plugin_size_.height());
801 // Add the left, right, and bottom rectangles. Note: we assume only
802 // horizontal centering.
803 BackgroundPart part = {
804 pp::Rect(0, 0, left_width, bottom),
805 background_color_
807 if (!part.location.IsEmpty())
808 background_parts_.push_back(part);
809 part.location = pp::Rect(right_start, 0, right_width, bottom);
810 if (!part.location.IsEmpty())
811 background_parts_.push_back(part);
812 part.location = pp::Rect(
813 0, bottom, plugin_size_.width(), plugin_size_.height() - bottom);
814 if (!part.location.IsEmpty())
815 background_parts_.push_back(part);
818 int OutOfProcessInstance::GetDocumentPixelWidth() const {
819 return static_cast<int>(ceil(document_size_.width() * zoom_ * device_scale_));
822 int OutOfProcessInstance::GetDocumentPixelHeight() const {
823 return static_cast<int>(
824 ceil(document_size_.height() * zoom_ * device_scale_));
827 void OutOfProcessInstance::FillRect(const pp::Rect& rect, uint32 color) {
828 DCHECK(!image_data_.is_null() || rect.IsEmpty());
829 uint32* buffer_start = static_cast<uint32*>(image_data_.data());
830 int stride = image_data_.stride();
831 uint32* ptr = buffer_start + rect.y() * stride / 4 + rect.x();
832 int height = rect.height();
833 int width = rect.width();
834 for (int y = 0; y < height; ++y) {
835 for (int x = 0; x < width; ++x)
836 *(ptr + x) = color;
837 ptr += stride /4;
841 void OutOfProcessInstance::DocumentSizeUpdated(const pp::Size& size) {
842 document_size_ = size;
844 pp::VarDictionary dimensions;
845 dimensions.Set(kType, kJSDocumentDimensionsType);
846 dimensions.Set(kJSDocumentWidth, pp::Var(document_size_.width()));
847 dimensions.Set(kJSDocumentHeight, pp::Var(document_size_.height()));
848 pp::VarArray page_dimensions_array;
849 int num_pages = engine_->GetNumberOfPages();
850 for (int i = 0; i < num_pages; ++i) {
851 pp::Rect page_rect = engine_->GetPageRect(i);
852 pp::VarDictionary page_dimensions;
853 page_dimensions.Set(kJSPageX, pp::Var(page_rect.x()));
854 page_dimensions.Set(kJSPageY, pp::Var(page_rect.y()));
855 page_dimensions.Set(kJSPageWidth, pp::Var(page_rect.width()));
856 page_dimensions.Set(kJSPageHeight, pp::Var(page_rect.height()));
857 page_dimensions_array.Set(i, page_dimensions);
859 dimensions.Set(kJSPageDimensions, page_dimensions_array);
860 PostMessage(dimensions);
862 OnGeometryChanged(zoom_, device_scale_);
865 void OutOfProcessInstance::Invalidate(const pp::Rect& rect) {
866 pp::Rect offset_rect(rect);
867 offset_rect.Offset(available_area_.point());
868 paint_manager_.InvalidateRect(offset_rect);
871 void OutOfProcessInstance::Scroll(const pp::Point& point) {
872 if (!image_data_.is_null())
873 paint_manager_.ScrollRect(available_area_, point);
876 void OutOfProcessInstance::ScrollToX(int x) {
877 pp::VarDictionary position;
878 position.Set(kType, kJSSetScrollPositionType);
879 position.Set(kJSPositionX, pp::Var(x / device_scale_));
880 PostMessage(position);
883 void OutOfProcessInstance::ScrollToY(int y) {
884 pp::VarDictionary position;
885 position.Set(kType, kJSSetScrollPositionType);
886 position.Set(kJSPositionY, pp::Var(y / device_scale_));
887 PostMessage(position);
890 void OutOfProcessInstance::ScrollToPage(int page) {
891 if (engine_->GetNumberOfPages() == 0)
892 return;
894 pp::VarDictionary message;
895 message.Set(kType, kJSGoToPageType);
896 message.Set(kJSPageNumber, pp::Var(page));
897 PostMessage(message);
900 void OutOfProcessInstance::NavigateTo(const std::string& url,
901 bool open_in_new_tab) {
902 pp::VarDictionary message;
903 message.Set(kType, kJSNavigateType);
904 message.Set(kJSNavigateUrl, url);
905 message.Set(kJSNavigateNewTab, open_in_new_tab);
906 PostMessage(message);
909 void OutOfProcessInstance::UpdateCursor(PP_CursorType_Dev cursor) {
910 if (cursor == cursor_)
911 return;
912 cursor_ = cursor;
914 const PPB_CursorControl_Dev* cursor_interface =
915 reinterpret_cast<const PPB_CursorControl_Dev*>(
916 pp::Module::Get()->GetBrowserInterface(PPB_CURSOR_CONTROL_DEV_INTERFACE));
917 if (!cursor_interface) {
918 NOTREACHED();
919 return;
922 cursor_interface->SetCursor(
923 pp_instance(), cursor_, pp::ImageData().pp_resource(), nullptr);
926 void OutOfProcessInstance::UpdateTickMarks(
927 const std::vector<pp::Rect>& tickmarks) {
928 float inverse_scale = 1.0f / device_scale_;
929 std::vector<pp::Rect> scaled_tickmarks = tickmarks;
930 for (size_t i = 0; i < scaled_tickmarks.size(); i++)
931 ScaleRect(inverse_scale, &scaled_tickmarks[i]);
932 tickmarks_ = scaled_tickmarks;
935 void OutOfProcessInstance::NotifyNumberOfFindResultsChanged(int total,
936 bool final_result) {
937 // We don't want to spam the renderer with too many updates to the number of
938 // find results. Don't send an update if we sent one too recently. If it's the
939 // final update, we always send it though.
940 if (final_result) {
941 NumberOfFindResultsChanged(total, final_result);
942 SetTickmarks(tickmarks_);
943 return;
946 if (recently_sent_find_update_)
947 return;
949 NumberOfFindResultsChanged(total, final_result);
950 SetTickmarks(tickmarks_);
951 recently_sent_find_update_ = true;
952 pp::CompletionCallback callback =
953 timer_factory_.NewCallback(
954 &OutOfProcessInstance::ResetRecentlySentFindUpdate);
955 pp::Module::Get()->core()->CallOnMainThread(kFindResultCooldownMs,
956 callback, 0);
959 void OutOfProcessInstance::NotifySelectedFindResultChanged(
960 int current_find_index) {
961 DCHECK_GE(current_find_index, 0);
962 SelectedFindResultChanged(current_find_index);
965 void OutOfProcessInstance::GetDocumentPassword(
966 pp::CompletionCallbackWithOutput<pp::Var> callback) {
967 if (password_callback_) {
968 NOTREACHED();
969 return;
972 password_callback_.reset(
973 new pp::CompletionCallbackWithOutput<pp::Var>(callback));
974 pp::VarDictionary message;
975 message.Set(pp::Var(kType), pp::Var(kJSGetPasswordType));
976 PostMessage(message);
979 void OutOfProcessInstance::Alert(const std::string& message) {
980 ModalDialog(this, "alert", message, std::string());
983 bool OutOfProcessInstance::Confirm(const std::string& message) {
984 pp::Var result = ModalDialog(this, "confirm", message, std::string());
985 return result.is_bool() ? result.AsBool() : false;
988 std::string OutOfProcessInstance::Prompt(const std::string& question,
989 const std::string& default_answer) {
990 pp::Var result = ModalDialog(this, "prompt", question, default_answer);
991 return result.is_string() ? result.AsString() : std::string();
994 std::string OutOfProcessInstance::GetURL() {
995 return url_;
998 void OutOfProcessInstance::Email(const std::string& to,
999 const std::string& cc,
1000 const std::string& bcc,
1001 const std::string& subject,
1002 const std::string& body) {
1003 pp::VarDictionary message;
1004 message.Set(pp::Var(kType), pp::Var(kJSEmailType));
1005 message.Set(pp::Var(kJSEmailTo),
1006 pp::Var(net::EscapeUrlEncodedData(to, false)));
1007 message.Set(pp::Var(kJSEmailCc),
1008 pp::Var(net::EscapeUrlEncodedData(cc, false)));
1009 message.Set(pp::Var(kJSEmailBcc),
1010 pp::Var(net::EscapeUrlEncodedData(bcc, false)));
1011 message.Set(pp::Var(kJSEmailSubject),
1012 pp::Var(net::EscapeUrlEncodedData(subject, false)));
1013 message.Set(pp::Var(kJSEmailBody),
1014 pp::Var(net::EscapeUrlEncodedData(body, false)));
1015 PostMessage(message);
1018 void OutOfProcessInstance::Print() {
1019 if (!engine_->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY) &&
1020 !engine_->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY)) {
1021 return;
1024 pp::CompletionCallback callback =
1025 print_callback_factory_.NewCallback(&OutOfProcessInstance::OnPrint);
1026 pp::Module::Get()->core()->CallOnMainThread(0, callback);
1029 void OutOfProcessInstance::OnPrint(int32_t) {
1030 pp::PDF::Print(this);
1033 void OutOfProcessInstance::SubmitForm(const std::string& url,
1034 const void* data,
1035 int length) {
1036 pp::URLRequestInfo request(this);
1037 request.SetURL(url);
1038 request.SetMethod("POST");
1039 request.AppendDataToBody(reinterpret_cast<const char*>(data), length);
1041 pp::CompletionCallback callback =
1042 form_factory_.NewCallback(&OutOfProcessInstance::FormDidOpen);
1043 form_loader_ = CreateURLLoaderInternal();
1044 int rv = form_loader_.Open(request, callback);
1045 if (rv != PP_OK_COMPLETIONPENDING)
1046 callback.Run(rv);
1049 void OutOfProcessInstance::FormDidOpen(int32_t result) {
1050 // TODO: inform the user of success/failure.
1051 if (result != PP_OK) {
1052 NOTREACHED();
1056 std::string OutOfProcessInstance::ShowFileSelectionDialog() {
1057 // Seems like very low priority to implement, since the pdf has no way to get
1058 // the file data anyways. Javascript doesn't let you do this synchronously.
1059 NOTREACHED();
1060 return std::string();
1063 pp::URLLoader OutOfProcessInstance::CreateURLLoader() {
1064 if (full_) {
1065 if (!did_call_start_loading_) {
1066 did_call_start_loading_ = true;
1067 pp::PDF::DidStartLoading(this);
1070 // Disable save and print until the document is fully loaded, since they
1071 // would generate an incomplete document. Need to do this each time we
1072 // call DidStartLoading since that resets the content restrictions.
1073 pp::PDF::SetContentRestriction(this, CONTENT_RESTRICTION_SAVE |
1074 CONTENT_RESTRICTION_PRINT);
1077 return CreateURLLoaderInternal();
1080 void OutOfProcessInstance::ScheduleCallback(int id, int delay_in_ms) {
1081 pp::CompletionCallback callback =
1082 timer_factory_.NewCallback(&OutOfProcessInstance::OnClientTimerFired);
1083 pp::Module::Get()->core()->CallOnMainThread(delay_in_ms, callback, id);
1086 void OutOfProcessInstance::SearchString(const base::char16* string,
1087 const base::char16* term,
1088 bool case_sensitive,
1089 std::vector<SearchStringResult>* results) {
1090 PP_PrivateFindResult* pp_results;
1091 int count = 0;
1092 pp::PDF::SearchString(
1093 this,
1094 reinterpret_cast<const unsigned short*>(string),
1095 reinterpret_cast<const unsigned short*>(term),
1096 case_sensitive,
1097 &pp_results,
1098 &count);
1100 results->resize(count);
1101 for (int i = 0; i < count; ++i) {
1102 (*results)[i].start_index = pp_results[i].start_index;
1103 (*results)[i].length = pp_results[i].length;
1106 pp::Memory_Dev memory;
1107 memory.MemFree(pp_results);
1110 void OutOfProcessInstance::DocumentPaintOccurred() {
1113 void OutOfProcessInstance::DocumentLoadComplete(int page_count) {
1114 // Clear focus state for OSK.
1115 FormTextFieldFocusChange(false);
1117 DCHECK(document_load_state_ == LOAD_STATE_LOADING);
1118 document_load_state_ = LOAD_STATE_COMPLETE;
1119 UserMetricsRecordAction("PDF.LoadSuccess");
1121 // Note: If we are in print preview mode the scroll location is retained
1122 // across document loads so we don't want to scroll again and override it.
1123 if (IsPrintPreview()) {
1124 AppendBlankPrintPreviewPages();
1125 OnGeometryChanged(0, 0);
1128 pp::VarDictionary bookmarks_message;
1129 bookmarks_message.Set(pp::Var(kType), pp::Var(kJSBookmarksType));
1130 bookmarks_message.Set(pp::Var(kJSBookmarks), engine_->GetBookmarks());
1131 PostMessage(bookmarks_message);
1133 pp::VarDictionary progress_message;
1134 progress_message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1135 progress_message.Set(pp::Var(kJSProgressPercentage), pp::Var(100));
1136 PostMessage(progress_message);
1138 if (!full_)
1139 return;
1141 if (did_call_start_loading_) {
1142 pp::PDF::DidStopLoading(this);
1143 did_call_start_loading_ = false;
1146 int content_restrictions =
1147 CONTENT_RESTRICTION_CUT | CONTENT_RESTRICTION_PASTE;
1148 if (!engine_->HasPermission(PDFEngine::PERMISSION_COPY))
1149 content_restrictions |= CONTENT_RESTRICTION_COPY;
1151 if (!engine_->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY) &&
1152 !engine_->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY)) {
1153 content_restrictions |= CONTENT_RESTRICTION_PRINT;
1156 pp::PDF::SetContentRestriction(this, content_restrictions);
1158 uma_.HistogramCustomCounts("PDF.PageCount", page_count, 1, 1000000, 50);
1161 void OutOfProcessInstance::RotateClockwise() {
1162 engine_->RotateClockwise();
1165 void OutOfProcessInstance::RotateCounterclockwise() {
1166 engine_->RotateCounterclockwise();
1169 void OutOfProcessInstance::PreviewDocumentLoadComplete() {
1170 if (preview_document_load_state_ != LOAD_STATE_LOADING ||
1171 preview_pages_info_.empty()) {
1172 return;
1175 preview_document_load_state_ = LOAD_STATE_COMPLETE;
1177 int dest_page_index = preview_pages_info_.front().second;
1178 int src_page_index =
1179 ExtractPrintPreviewPageIndex(preview_pages_info_.front().first);
1180 if (src_page_index > 0 && dest_page_index > -1 && preview_engine_.get())
1181 engine_->AppendPage(preview_engine_.get(), dest_page_index);
1183 preview_pages_info_.pop();
1184 // |print_preview_page_count_| is not updated yet. Do not load any
1185 // other preview pages till we get this information.
1186 if (print_preview_page_count_ == 0)
1187 return;
1189 if (!preview_pages_info_.empty())
1190 LoadAvailablePreviewPage();
1193 void OutOfProcessInstance::DocumentLoadFailed() {
1194 DCHECK(document_load_state_ == LOAD_STATE_LOADING);
1195 UserMetricsRecordAction("PDF.LoadFailure");
1197 if (did_call_start_loading_) {
1198 pp::PDF::DidStopLoading(this);
1199 did_call_start_loading_ = false;
1202 document_load_state_ = LOAD_STATE_FAILED;
1203 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
1205 // Send a progress value of -1 to indicate a failure.
1206 pp::VarDictionary message;
1207 message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1208 message.Set(pp::Var(kJSProgressPercentage), pp::Var(-1));
1209 PostMessage(message);
1212 void OutOfProcessInstance::PreviewDocumentLoadFailed() {
1213 UserMetricsRecordAction("PDF.PreviewDocumentLoadFailure");
1214 if (preview_document_load_state_ != LOAD_STATE_LOADING ||
1215 preview_pages_info_.empty()) {
1216 return;
1219 preview_document_load_state_ = LOAD_STATE_FAILED;
1220 preview_pages_info_.pop();
1222 if (!preview_pages_info_.empty())
1223 LoadAvailablePreviewPage();
1226 pp::Instance* OutOfProcessInstance::GetPluginInstance() {
1227 return this;
1230 void OutOfProcessInstance::DocumentHasUnsupportedFeature(
1231 const std::string& feature) {
1232 std::string metric("PDF_Unsupported_");
1233 metric += feature;
1234 if (!unsupported_features_reported_.count(metric)) {
1235 unsupported_features_reported_.insert(metric);
1236 UserMetricsRecordAction(metric);
1239 // Since we use an info bar, only do this for full frame plugins..
1240 if (!full_)
1241 return;
1243 if (told_browser_about_unsupported_feature_)
1244 return;
1245 told_browser_about_unsupported_feature_ = true;
1247 pp::PDF::HasUnsupportedFeature(this);
1250 void OutOfProcessInstance::DocumentLoadProgress(uint32 available,
1251 uint32 doc_size) {
1252 double progress = 0.0;
1253 if (doc_size == 0) {
1254 // Document size is unknown. Use heuristics.
1255 // We'll make progress logarithmic from 0 to 100M.
1256 static const double kFactor = log(100000000.0) / 100.0;
1257 if (available > 0) {
1258 progress = log(static_cast<double>(available)) / kFactor;
1259 if (progress > 100.0)
1260 progress = 100.0;
1262 } else {
1263 progress = 100.0 * static_cast<double>(available) / doc_size;
1266 // We send 100% load progress in DocumentLoadComplete.
1267 if (progress >= 100)
1268 return;
1270 // Avoid sending too many progress messages over PostMessage.
1271 if (progress > last_progress_sent_ + 1) {
1272 last_progress_sent_ = progress;
1273 pp::VarDictionary message;
1274 message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1275 message.Set(pp::Var(kJSProgressPercentage), pp::Var(progress));
1276 PostMessage(message);
1280 void OutOfProcessInstance::FormTextFieldFocusChange(bool in_focus) {
1281 if (!text_input_.get())
1282 return;
1283 if (in_focus)
1284 text_input_->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_TEXT);
1285 else
1286 text_input_->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_NONE);
1289 void OutOfProcessInstance::ResetRecentlySentFindUpdate(int32_t /* unused */) {
1290 recently_sent_find_update_ = false;
1293 void OutOfProcessInstance::OnGeometryChanged(double old_zoom,
1294 float old_device_scale) {
1295 if (zoom_ != old_zoom || device_scale_ != old_device_scale)
1296 engine_->ZoomUpdated(zoom_ * device_scale_);
1298 available_area_ = pp::Rect(plugin_size_);
1299 int doc_width = GetDocumentPixelWidth();
1300 if (doc_width < available_area_.width()) {
1301 available_area_.Offset((available_area_.width() - doc_width) / 2, 0);
1302 available_area_.set_width(doc_width);
1304 int bottom_of_document =
1305 GetDocumentPixelHeight() + (top_toolbar_height_ * device_scale_);
1306 if (bottom_of_document < available_area_.height())
1307 available_area_.set_height(bottom_of_document);
1309 CalculateBackgroundParts();
1310 engine_->PageOffsetUpdated(available_area_.point());
1311 engine_->PluginSizeUpdated(available_area_.size());
1313 if (!document_size_.GetArea())
1314 return;
1315 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
1318 void OutOfProcessInstance::LoadUrl(const std::string& url) {
1319 LoadUrlInternal(url, &embed_loader_, &OutOfProcessInstance::DidOpen);
1322 void OutOfProcessInstance::LoadPreviewUrl(const std::string& url) {
1323 LoadUrlInternal(url, &embed_preview_loader_,
1324 &OutOfProcessInstance::DidOpenPreview);
1327 void OutOfProcessInstance::LoadUrlInternal(
1328 const std::string& url,
1329 pp::URLLoader* loader,
1330 void (OutOfProcessInstance::* method)(int32_t)) {
1331 pp::URLRequestInfo request(this);
1332 request.SetURL(url);
1333 request.SetMethod("GET");
1335 *loader = CreateURLLoaderInternal();
1336 pp::CompletionCallback callback = loader_factory_.NewCallback(method);
1337 int rv = loader->Open(request, callback);
1338 if (rv != PP_OK_COMPLETIONPENDING)
1339 callback.Run(rv);
1342 pp::URLLoader OutOfProcessInstance::CreateURLLoaderInternal() {
1343 pp::URLLoader loader(this);
1345 const PPB_URLLoaderTrusted* trusted_interface =
1346 reinterpret_cast<const PPB_URLLoaderTrusted*>(
1347 pp::Module::Get()->GetBrowserInterface(
1348 PPB_URLLOADERTRUSTED_INTERFACE));
1349 if (trusted_interface)
1350 trusted_interface->GrantUniversalAccess(loader.pp_resource());
1351 return loader;
1354 void OutOfProcessInstance::SetZoom(double scale) {
1355 double old_zoom = zoom_;
1356 zoom_ = scale;
1357 OnGeometryChanged(old_zoom, device_scale_);
1360 std::string OutOfProcessInstance::GetLocalizedString(PP_ResourceString id) {
1361 pp::Var rv(pp::PDF::GetLocalizedString(this, id));
1362 if (!rv.is_string())
1363 return std::string();
1365 return rv.AsString();
1368 void OutOfProcessInstance::AppendBlankPrintPreviewPages() {
1369 if (print_preview_page_count_ == 0)
1370 return;
1371 engine_->AppendBlankPages(print_preview_page_count_);
1372 if (!preview_pages_info_.empty())
1373 LoadAvailablePreviewPage();
1376 bool OutOfProcessInstance::IsPrintPreview() {
1377 return IsPrintPreviewUrl(url_);
1380 uint32 OutOfProcessInstance::GetBackgroundColor() {
1381 return background_color_;
1384 void OutOfProcessInstance::IsSelectingChanged(bool is_selecting) {
1385 pp::VarDictionary message;
1386 message.Set(kType, kJSSetIsSelectingType);
1387 message.Set(kJSIsSelecting, pp::Var(is_selecting));
1388 PostMessage(message);
1391 void OutOfProcessInstance::ProcessPreviewPageInfo(const std::string& url,
1392 int dst_page_index) {
1393 if (!IsPrintPreview())
1394 return;
1396 int src_page_index = ExtractPrintPreviewPageIndex(url);
1397 if (src_page_index < 1)
1398 return;
1400 preview_pages_info_.push(std::make_pair(url, dst_page_index));
1401 LoadAvailablePreviewPage();
1404 void OutOfProcessInstance::LoadAvailablePreviewPage() {
1405 if (preview_pages_info_.empty() ||
1406 document_load_state_ != LOAD_STATE_COMPLETE) {
1407 return;
1410 std::string url = preview_pages_info_.front().first;
1411 int dst_page_index = preview_pages_info_.front().second;
1412 int src_page_index = ExtractPrintPreviewPageIndex(url);
1413 if (src_page_index < 1 ||
1414 dst_page_index >= print_preview_page_count_ ||
1415 preview_document_load_state_ == LOAD_STATE_LOADING) {
1416 return;
1419 preview_document_load_state_ = LOAD_STATE_LOADING;
1420 LoadPreviewUrl(url);
1423 void OutOfProcessInstance::UserMetricsRecordAction(
1424 const std::string& action) {
1425 // TODO(raymes): Move this function to PPB_UMA_Private.
1426 pp::PDF::UserMetricsRecordAction(this, pp::Var(action));
1429 pp::FloatPoint OutOfProcessInstance::BoundScrollOffsetToDocument(
1430 const pp::FloatPoint& scroll_offset) {
1431 float max_x = document_size_.width() * zoom_ - plugin_dip_size_.width();
1432 float x = std::max(std::min(scroll_offset.x(), max_x), 0.0f);
1433 float min_y = -top_toolbar_height_;
1434 float max_y = document_size_.height() * zoom_ - plugin_dip_size_.height();
1435 float y = std::max(std::min(scroll_offset.y(), max_y), min_y);
1436 return pp::FloatPoint(x, y);
1439 } // namespace chrome_pdf