Fix nullptr crash in OnEmbed
[chromium-blink-merge.git] / pdf / out_of_process_instance.cc
blobdbe3968d0ca2d116c0def6159261ed5cf228447c
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 loaded in the extension and print preview to avoid
309 // exposing sensitive APIs directly to external websites.
310 pp::Var document_url_var = pp::URLUtil_Dev::Get()->GetDocumentURL(this);
311 if (!document_url_var.is_string())
312 return false;
313 std::string document_url = document_url_var.AsString();
314 std::string extension_url = std::string(kChromeExtension);
315 std::string print_preview_url = std::string(kChromePrint);
316 if (!base::StringPiece(document_url).starts_with(kChromeExtension) &&
317 !base::StringPiece(document_url).starts_with(kChromePrint)) {
318 return false;
321 // Check if the plugin is full frame. This is passed in from JS.
322 for (uint32_t i = 0; i < argc; ++i) {
323 if (strcmp(argn[i], "full-frame") == 0) {
324 full_ = true;
325 break;
329 // Only allow the plugin to handle find requests if it is full frame.
330 if (full_)
331 SetPluginToHandleFindRequests();
333 // Send translated strings to the extension where they will be displayed.
334 // TODO(raymes): It would be better to get these in the extension directly
335 // through an API but no such API currently exists.
336 pp::VarDictionary translated_strings;
337 translated_strings.Set(kType, kJSSetTranslatedStringsType);
338 translated_strings.Set(kJSGetPasswordString,
339 GetLocalizedString(PP_RESOURCESTRING_PDFGETPASSWORD));
340 translated_strings.Set(kJSLoadingString,
341 GetLocalizedString(PP_RESOURCESTRING_PDFLOADING));
342 translated_strings.Set(kJSLoadFailedString,
343 GetLocalizedString(PP_RESOURCESTRING_PDFLOAD_FAILED));
344 PostMessage(translated_strings);
346 text_input_.reset(new pp::TextInput_Dev(this));
348 const char* stream_url = nullptr;
349 const char* original_url = nullptr;
350 const char* headers = nullptr;
351 bool is_material = false;
352 for (uint32_t i = 0; i < argc; ++i) {
353 if (strcmp(argn[i], "src") == 0)
354 original_url = argv[i];
355 else if (strcmp(argn[i], "stream-url") == 0)
356 stream_url = argv[i];
357 else if (strcmp(argn[i], "headers") == 0)
358 headers = argv[i];
359 else if (strcmp(argn[i], "is-material") == 0)
360 is_material = true;
361 else if (strcmp(argn[i], "top-toolbar-height") == 0)
362 base::StringToInt(argv[i], &top_toolbar_height_);
365 if (is_material)
366 background_color_ = kBackgroundColorMaterial;
367 else
368 background_color_ = kBackgroundColor;
370 if (!original_url)
371 return false;
373 if (!stream_url)
374 stream_url = original_url;
376 // If we're in print preview mode we don't need to load the document yet.
377 // A |kJSResetPrintPreviewModeType| message will be sent to the plugin letting
378 // it know the url to load. By not loading here we avoid loading the same
379 // document twice.
380 if (IsPrintPreviewUrl(original_url))
381 return true;
383 LoadUrl(stream_url);
384 url_ = original_url;
385 return engine_->New(original_url, headers);
388 void OutOfProcessInstance::HandleMessage(const pp::Var& message) {
389 pp::VarDictionary dict(message);
390 if (!dict.Get(kType).is_string()) {
391 NOTREACHED();
392 return;
395 std::string type = dict.Get(kType).AsString();
397 if (type == kJSViewportType &&
398 dict.Get(pp::Var(kJSXOffset)).is_number() &&
399 dict.Get(pp::Var(kJSYOffset)).is_number() &&
400 dict.Get(pp::Var(kJSZoom)).is_number()) {
401 received_viewport_message_ = true;
402 stop_scrolling_ = false;
403 double zoom = dict.Get(pp::Var(kJSZoom)).AsDouble();
404 pp::FloatPoint scroll_offset(dict.Get(pp::Var(kJSXOffset)).AsDouble(),
405 dict.Get(pp::Var(kJSYOffset)).AsDouble());
407 // Bound the input parameters.
408 zoom = std::max(kMinZoom, zoom);
409 SetZoom(zoom);
410 scroll_offset = BoundScrollOffsetToDocument(scroll_offset);
411 engine_->ScrolledToXPosition(scroll_offset.x() * device_scale_);
412 engine_->ScrolledToYPosition(scroll_offset.y() * device_scale_);
413 } else if (type == kJSGetPasswordCompleteType &&
414 dict.Get(pp::Var(kJSPassword)).is_string()) {
415 if (password_callback_) {
416 pp::CompletionCallbackWithOutput<pp::Var> callback = *password_callback_;
417 password_callback_.reset();
418 *callback.output() = dict.Get(pp::Var(kJSPassword)).pp_var();
419 callback.Run(PP_OK);
420 } else {
421 NOTREACHED();
423 } else if (type == kJSPrintType) {
424 Print();
425 } else if (type == kJSSaveType) {
426 pp::PDF::SaveAs(this);
427 } else if (type == kJSRotateClockwiseType) {
428 RotateClockwise();
429 } else if (type == kJSRotateCounterclockwiseType) {
430 RotateCounterclockwise();
431 } else if (type == kJSSelectAllType) {
432 engine_->SelectAll();
433 } else if (type == kJSResetPrintPreviewModeType &&
434 dict.Get(pp::Var(kJSPrintPreviewUrl)).is_string() &&
435 dict.Get(pp::Var(kJSPrintPreviewGrayscale)).is_bool() &&
436 dict.Get(pp::Var(kJSPrintPreviewPageCount)).is_int()) {
437 url_ = dict.Get(pp::Var(kJSPrintPreviewUrl)).AsString();
438 preview_pages_info_ = std::queue<PreviewPageInfo>();
439 preview_document_load_state_ = LOAD_STATE_COMPLETE;
440 document_load_state_ = LOAD_STATE_LOADING;
441 LoadUrl(url_);
442 preview_engine_.reset();
443 engine_.reset(PDFEngine::Create(this));
444 engine_->SetGrayscale(dict.Get(pp::Var(kJSPrintPreviewGrayscale)).AsBool());
445 engine_->New(url_.c_str(), nullptr /* empty header */);
447 print_preview_page_count_ =
448 std::max(dict.Get(pp::Var(kJSPrintPreviewPageCount)).AsInt(), 0);
450 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
451 } else if (type == kJSLoadPreviewPageType &&
452 dict.Get(pp::Var(kJSPreviewPageUrl)).is_string() &&
453 dict.Get(pp::Var(kJSPreviewPageIndex)).is_int()) {
454 ProcessPreviewPageInfo(dict.Get(pp::Var(kJSPreviewPageUrl)).AsString(),
455 dict.Get(pp::Var(kJSPreviewPageIndex)).AsInt());
456 } else if (type == kJSGetAccessibilityJSONType) {
457 pp::VarDictionary reply;
458 reply.Set(pp::Var(kType), pp::Var(kJSGetAccessibilityJSONReplyType));
459 if (dict.Get(pp::Var(kJSAccessibilityPageNumber)).is_int()) {
460 int page = dict.Get(pp::Var(kJSAccessibilityPageNumber)).AsInt();
461 reply.Set(pp::Var(kJSAccessibilityJSON),
462 pp::Var(engine_->GetPageAsJSON(page)));
463 } else {
464 base::DictionaryValue node;
465 node.SetInteger(kAccessibleNumberOfPages, engine_->GetNumberOfPages());
466 node.SetBoolean(kAccessibleLoaded,
467 document_load_state_ != LOAD_STATE_LOADING);
468 bool has_permissions =
469 engine_->HasPermission(PDFEngine::PERMISSION_COPY) ||
470 engine_->HasPermission(PDFEngine::PERMISSION_COPY_ACCESSIBLE);
471 node.SetBoolean(kAccessibleCopyable, has_permissions);
472 std::string json;
473 base::JSONWriter::Write(node, &json);
474 reply.Set(pp::Var(kJSAccessibilityJSON), pp::Var(json));
476 PostMessage(reply);
477 } else if (type == kJSStopScrollingType) {
478 stop_scrolling_ = true;
479 } else if (type == kJSGetSelectedTextType) {
480 std::string selected_text = engine_->GetSelectedText();
481 // Always return unix newlines to JS.
482 base::ReplaceChars(selected_text, "\r", std::string(), &selected_text);
483 pp::VarDictionary reply;
484 reply.Set(pp::Var(kType), pp::Var(kJSGetSelectedTextReplyType));
485 reply.Set(pp::Var(kJSSelectedText), selected_text);
486 PostMessage(reply);
487 } else if (type == KJSGetNamedDestinationType &&
488 dict.Get(pp::Var(KJSGetNamedDestination)).is_string()) {
489 int page_number = engine_->GetNamedDestinationPage(
490 dict.Get(pp::Var(KJSGetNamedDestination)).AsString());
491 pp::VarDictionary reply;
492 reply.Set(pp::Var(kType), pp::Var(kJSGetNamedDestinationReplyType));
493 if (page_number >= 0)
494 reply.Set(pp::Var(kJSNamedDestinationPageNumber), page_number);
495 PostMessage(reply);
496 } else {
497 NOTREACHED();
501 bool OutOfProcessInstance::HandleInputEvent(
502 const pp::InputEvent& event) {
503 // To simplify things, convert the event into device coordinates if it is
504 // a mouse event.
505 pp::InputEvent event_device_res(event);
507 pp::MouseInputEvent mouse_event(event);
508 if (!mouse_event.is_null()) {
509 pp::Point point = mouse_event.GetPosition();
510 pp::Point movement = mouse_event.GetMovement();
511 ScalePoint(device_scale_, &point);
512 ScalePoint(device_scale_, &movement);
513 mouse_event = pp::MouseInputEvent(
514 this,
515 event.GetType(),
516 event.GetTimeStamp(),
517 event.GetModifiers(),
518 mouse_event.GetButton(),
519 point,
520 mouse_event.GetClickCount(),
521 movement);
522 event_device_res = mouse_event;
526 pp::InputEvent offset_event(event_device_res);
527 switch (offset_event.GetType()) {
528 case PP_INPUTEVENT_TYPE_MOUSEDOWN:
529 case PP_INPUTEVENT_TYPE_MOUSEUP:
530 case PP_INPUTEVENT_TYPE_MOUSEMOVE:
531 case PP_INPUTEVENT_TYPE_MOUSEENTER:
532 case PP_INPUTEVENT_TYPE_MOUSELEAVE: {
533 pp::MouseInputEvent mouse_event(event_device_res);
534 pp::MouseInputEvent mouse_event_dip(event);
535 pp::Point point = mouse_event.GetPosition();
536 point.set_x(point.x() - available_area_.x());
537 offset_event = pp::MouseInputEvent(
538 this,
539 event.GetType(),
540 event.GetTimeStamp(),
541 event.GetModifiers(),
542 mouse_event.GetButton(),
543 point,
544 mouse_event.GetClickCount(),
545 mouse_event.GetMovement());
546 break;
548 default:
549 break;
551 if (engine_->HandleEvent(offset_event))
552 return true;
554 // Middle click is used for scrolling and is handled by the container page.
555 pp::MouseInputEvent mouse_event(event_device_res);
556 if (!mouse_event.is_null() &&
557 mouse_event.GetButton() == PP_INPUTEVENT_MOUSEBUTTON_MIDDLE) {
558 return false;
561 // Return true for unhandled clicks so the plugin takes focus.
562 return (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN);
565 void OutOfProcessInstance::DidChangeView(const pp::View& view) {
566 pp::Rect view_rect(view.GetRect());
567 float old_device_scale = device_scale_;
568 float device_scale = view.GetDeviceScale();
569 pp::Size view_device_size(view_rect.width() * device_scale,
570 view_rect.height() * device_scale);
572 if (view_device_size != plugin_size_ || device_scale != device_scale_) {
573 device_scale_ = device_scale;
574 plugin_dip_size_ = view_rect.size();
575 plugin_size_ = view_device_size;
577 paint_manager_.SetSize(view_device_size, device_scale_);
579 pp::Size new_image_data_size = PaintManager::GetNewContextSize(
580 image_data_.size(),
581 plugin_size_);
582 if (new_image_data_size != image_data_.size()) {
583 image_data_ = pp::ImageData(this,
584 PP_IMAGEDATAFORMAT_BGRA_PREMUL,
585 new_image_data_size,
586 false);
587 first_paint_ = true;
590 if (image_data_.is_null()) {
591 DCHECK(plugin_size_.IsEmpty());
592 return;
595 OnGeometryChanged(zoom_, old_device_scale);
598 if (!stop_scrolling_) {
599 pp::Point scroll_offset(view.GetScrollOffset());
600 // Because view messages come from the DOM, the coordinates of the viewport
601 // are 0-based (i.e. they do not correspond to the viewport's coordinates in
602 // JS), so we need to subtract the toolbar height to convert them into
603 // viewport coordinates.
604 pp::FloatPoint scroll_offset_float(scroll_offset.x(),
605 scroll_offset.y() - top_toolbar_height_);
606 scroll_offset_float = BoundScrollOffsetToDocument(scroll_offset_float);
607 engine_->ScrolledToXPosition(scroll_offset_float.x() * device_scale_);
608 engine_->ScrolledToYPosition(scroll_offset_float.y() * device_scale_);
612 void OutOfProcessInstance::GetPrintPresetOptionsFromDocument(
613 PP_PdfPrintPresetOptions_Dev* options) {
614 options->is_scaling_disabled = PP_FromBool(IsPrintScalingDisabled());
615 options->duplex =
616 static_cast<PP_PrivateDuplexMode_Dev>(engine_->GetDuplexType());
617 options->copies = engine_->GetCopiesToPrint();
618 pp::Size uniform_page_size;
619 options->is_page_size_uniform =
620 PP_FromBool(engine_->GetPageSizeAndUniformity(&uniform_page_size));
621 options->uniform_page_size = uniform_page_size;
624 pp::Var OutOfProcessInstance::GetLinkAtPosition(
625 const pp::Point& point) {
626 pp::Point offset_point(point);
627 ScalePoint(device_scale_, &offset_point);
628 offset_point.set_x(offset_point.x() - available_area_.x());
629 return engine_->GetLinkAtPosition(offset_point);
632 uint32_t OutOfProcessInstance::QuerySupportedPrintOutputFormats() {
633 return engine_->QuerySupportedPrintOutputFormats();
636 int32_t OutOfProcessInstance::PrintBegin(
637 const PP_PrintSettings_Dev& print_settings) {
638 // For us num_pages is always equal to the number of pages in the PDF
639 // document irrespective of the printable area.
640 int32_t ret = engine_->GetNumberOfPages();
641 if (!ret)
642 return 0;
644 uint32_t supported_formats = engine_->QuerySupportedPrintOutputFormats();
645 if ((print_settings.format & supported_formats) == 0)
646 return 0;
648 print_settings_.is_printing = true;
649 print_settings_.pepper_print_settings = print_settings;
650 engine_->PrintBegin();
651 return ret;
654 pp::Resource OutOfProcessInstance::PrintPages(
655 const PP_PrintPageNumberRange_Dev* page_ranges,
656 uint32_t page_range_count) {
657 if (!print_settings_.is_printing)
658 return pp::Resource();
660 print_settings_.print_pages_called_ = true;
661 return engine_->PrintPages(page_ranges, page_range_count,
662 print_settings_.pepper_print_settings);
665 void OutOfProcessInstance::PrintEnd() {
666 if (print_settings_.print_pages_called_)
667 UserMetricsRecordAction("PDF.PrintPage");
668 print_settings_.Clear();
669 engine_->PrintEnd();
672 bool OutOfProcessInstance::IsPrintScalingDisabled() {
673 return !engine_->GetPrintScaling();
676 bool OutOfProcessInstance::StartFind(const std::string& text,
677 bool case_sensitive) {
678 engine_->StartFind(text.c_str(), case_sensitive);
679 return true;
682 void OutOfProcessInstance::SelectFindResult(bool forward) {
683 engine_->SelectFindResult(forward);
686 void OutOfProcessInstance::StopFind() {
687 engine_->StopFind();
688 tickmarks_.clear();
689 SetTickmarks(tickmarks_);
692 void OutOfProcessInstance::OnPaint(
693 const std::vector<pp::Rect>& paint_rects,
694 std::vector<PaintManager::ReadyRect>* ready,
695 std::vector<pp::Rect>* pending) {
696 if (image_data_.is_null()) {
697 DCHECK(plugin_size_.IsEmpty());
698 return;
700 if (first_paint_) {
701 first_paint_ = false;
702 pp::Rect rect = pp::Rect(pp::Point(), image_data_.size());
703 FillRect(rect, background_color_);
704 ready->push_back(PaintManager::ReadyRect(rect, image_data_, true));
707 if (!received_viewport_message_)
708 return;
710 engine_->PrePaint();
712 for (size_t i = 0; i < paint_rects.size(); i++) {
713 // Intersect with plugin area since there could be pending invalidates from
714 // when the plugin area was larger.
715 pp::Rect rect =
716 paint_rects[i].Intersect(pp::Rect(pp::Point(), plugin_size_));
717 if (rect.IsEmpty())
718 continue;
720 pp::Rect pdf_rect = available_area_.Intersect(rect);
721 if (!pdf_rect.IsEmpty()) {
722 pdf_rect.Offset(available_area_.x() * -1, 0);
724 std::vector<pp::Rect> pdf_ready;
725 std::vector<pp::Rect> pdf_pending;
726 engine_->Paint(pdf_rect, &image_data_, &pdf_ready, &pdf_pending);
727 for (size_t j = 0; j < pdf_ready.size(); ++j) {
728 pdf_ready[j].Offset(available_area_.point());
729 ready->push_back(
730 PaintManager::ReadyRect(pdf_ready[j], image_data_, false));
732 for (size_t j = 0; j < pdf_pending.size(); ++j) {
733 pdf_pending[j].Offset(available_area_.point());
734 pending->push_back(pdf_pending[j]);
738 // Ensure the region above the first page (if any) is filled;
739 int32_t first_page_ypos = engine_->GetNumberOfPages() == 0 ?
740 0 : engine_->GetPageScreenRect(0).y();
741 if (rect.y() < first_page_ypos) {
742 pp::Rect region = rect.Intersect(pp::Rect(
743 pp::Point(), pp::Size(plugin_size_.width(), first_page_ypos)));
744 ready->push_back(PaintManager::ReadyRect(region, image_data_, false));
745 FillRect(region, background_color_);
748 for (size_t j = 0; j < background_parts_.size(); ++j) {
749 pp::Rect intersection = background_parts_[j].location.Intersect(rect);
750 if (!intersection.IsEmpty()) {
751 FillRect(intersection, background_parts_[j].color);
752 ready->push_back(
753 PaintManager::ReadyRect(intersection, image_data_, false));
758 engine_->PostPaint();
761 void OutOfProcessInstance::DidOpen(int32_t result) {
762 if (result == PP_OK) {
763 if (!engine_->HandleDocumentLoad(embed_loader_)) {
764 document_load_state_ = LOAD_STATE_LOADING;
765 DocumentLoadFailed();
767 } else if (result != PP_ERROR_ABORTED) { // Can happen in tests.
768 NOTREACHED();
769 DocumentLoadFailed();
772 // If it's a progressive load, cancel the stream URL request so that requests
773 // can be made on the original URL.
774 // TODO(raymes): Make this clearer once the in-process plugin is deleted.
775 if (engine_->IsProgressiveLoad()) {
776 pp::VarDictionary message;
777 message.Set(kType, kJSCancelStreamUrlType);
778 PostMessage(message);
782 void OutOfProcessInstance::DidOpenPreview(int32_t result) {
783 if (result == PP_OK) {
784 preview_engine_.reset(PDFEngine::Create(new PreviewModeClient(this)));
785 preview_engine_->HandleDocumentLoad(embed_preview_loader_);
786 } else {
787 NOTREACHED();
791 void OutOfProcessInstance::OnClientTimerFired(int32_t id) {
792 engine_->OnCallback(id);
795 void OutOfProcessInstance::CalculateBackgroundParts() {
796 background_parts_.clear();
797 int left_width = available_area_.x();
798 int right_start = available_area_.right();
799 int right_width = abs(plugin_size_.width() - available_area_.right());
800 int bottom = std::min(available_area_.bottom(), plugin_size_.height());
802 // Add the left, right, and bottom rectangles. Note: we assume only
803 // horizontal centering.
804 BackgroundPart part = {
805 pp::Rect(0, 0, left_width, bottom),
806 background_color_
808 if (!part.location.IsEmpty())
809 background_parts_.push_back(part);
810 part.location = pp::Rect(right_start, 0, right_width, bottom);
811 if (!part.location.IsEmpty())
812 background_parts_.push_back(part);
813 part.location = pp::Rect(
814 0, bottom, plugin_size_.width(), plugin_size_.height() - bottom);
815 if (!part.location.IsEmpty())
816 background_parts_.push_back(part);
819 int OutOfProcessInstance::GetDocumentPixelWidth() const {
820 return static_cast<int>(ceil(document_size_.width() * zoom_ * device_scale_));
823 int OutOfProcessInstance::GetDocumentPixelHeight() const {
824 return static_cast<int>(
825 ceil(document_size_.height() * zoom_ * device_scale_));
828 void OutOfProcessInstance::FillRect(const pp::Rect& rect, uint32 color) {
829 DCHECK(!image_data_.is_null() || rect.IsEmpty());
830 uint32* buffer_start = static_cast<uint32*>(image_data_.data());
831 int stride = image_data_.stride();
832 uint32* ptr = buffer_start + rect.y() * stride / 4 + rect.x();
833 int height = rect.height();
834 int width = rect.width();
835 for (int y = 0; y < height; ++y) {
836 for (int x = 0; x < width; ++x)
837 *(ptr + x) = color;
838 ptr += stride /4;
842 void OutOfProcessInstance::DocumentSizeUpdated(const pp::Size& size) {
843 document_size_ = size;
845 pp::VarDictionary dimensions;
846 dimensions.Set(kType, kJSDocumentDimensionsType);
847 dimensions.Set(kJSDocumentWidth, pp::Var(document_size_.width()));
848 dimensions.Set(kJSDocumentHeight, pp::Var(document_size_.height()));
849 pp::VarArray page_dimensions_array;
850 int num_pages = engine_->GetNumberOfPages();
851 for (int i = 0; i < num_pages; ++i) {
852 pp::Rect page_rect = engine_->GetPageRect(i);
853 pp::VarDictionary page_dimensions;
854 page_dimensions.Set(kJSPageX, pp::Var(page_rect.x()));
855 page_dimensions.Set(kJSPageY, pp::Var(page_rect.y()));
856 page_dimensions.Set(kJSPageWidth, pp::Var(page_rect.width()));
857 page_dimensions.Set(kJSPageHeight, pp::Var(page_rect.height()));
858 page_dimensions_array.Set(i, page_dimensions);
860 dimensions.Set(kJSPageDimensions, page_dimensions_array);
861 PostMessage(dimensions);
863 OnGeometryChanged(zoom_, device_scale_);
866 void OutOfProcessInstance::Invalidate(const pp::Rect& rect) {
867 pp::Rect offset_rect(rect);
868 offset_rect.Offset(available_area_.point());
869 paint_manager_.InvalidateRect(offset_rect);
872 void OutOfProcessInstance::Scroll(const pp::Point& point) {
873 if (!image_data_.is_null())
874 paint_manager_.ScrollRect(available_area_, point);
877 void OutOfProcessInstance::ScrollToX(int x) {
878 pp::VarDictionary position;
879 position.Set(kType, kJSSetScrollPositionType);
880 position.Set(kJSPositionX, pp::Var(x / device_scale_));
881 PostMessage(position);
884 void OutOfProcessInstance::ScrollToY(int y) {
885 pp::VarDictionary position;
886 position.Set(kType, kJSSetScrollPositionType);
887 position.Set(kJSPositionY, pp::Var(y / device_scale_));
888 PostMessage(position);
891 void OutOfProcessInstance::ScrollToPage(int page) {
892 if (engine_->GetNumberOfPages() == 0)
893 return;
895 pp::VarDictionary message;
896 message.Set(kType, kJSGoToPageType);
897 message.Set(kJSPageNumber, pp::Var(page));
898 PostMessage(message);
901 void OutOfProcessInstance::NavigateTo(const std::string& url,
902 bool open_in_new_tab) {
903 pp::VarDictionary message;
904 message.Set(kType, kJSNavigateType);
905 message.Set(kJSNavigateUrl, url);
906 message.Set(kJSNavigateNewTab, open_in_new_tab);
907 PostMessage(message);
910 void OutOfProcessInstance::UpdateCursor(PP_CursorType_Dev cursor) {
911 if (cursor == cursor_)
912 return;
913 cursor_ = cursor;
915 const PPB_CursorControl_Dev* cursor_interface =
916 reinterpret_cast<const PPB_CursorControl_Dev*>(
917 pp::Module::Get()->GetBrowserInterface(PPB_CURSOR_CONTROL_DEV_INTERFACE));
918 if (!cursor_interface) {
919 NOTREACHED();
920 return;
923 cursor_interface->SetCursor(
924 pp_instance(), cursor_, pp::ImageData().pp_resource(), nullptr);
927 void OutOfProcessInstance::UpdateTickMarks(
928 const std::vector<pp::Rect>& tickmarks) {
929 float inverse_scale = 1.0f / device_scale_;
930 std::vector<pp::Rect> scaled_tickmarks = tickmarks;
931 for (size_t i = 0; i < scaled_tickmarks.size(); i++)
932 ScaleRect(inverse_scale, &scaled_tickmarks[i]);
933 tickmarks_ = scaled_tickmarks;
936 void OutOfProcessInstance::NotifyNumberOfFindResultsChanged(int total,
937 bool final_result) {
938 // We don't want to spam the renderer with too many updates to the number of
939 // find results. Don't send an update if we sent one too recently. If it's the
940 // final update, we always send it though.
941 if (final_result) {
942 NumberOfFindResultsChanged(total, final_result);
943 SetTickmarks(tickmarks_);
944 return;
947 if (recently_sent_find_update_)
948 return;
950 NumberOfFindResultsChanged(total, final_result);
951 SetTickmarks(tickmarks_);
952 recently_sent_find_update_ = true;
953 pp::CompletionCallback callback =
954 timer_factory_.NewCallback(
955 &OutOfProcessInstance::ResetRecentlySentFindUpdate);
956 pp::Module::Get()->core()->CallOnMainThread(kFindResultCooldownMs,
957 callback, 0);
960 void OutOfProcessInstance::NotifySelectedFindResultChanged(
961 int current_find_index) {
962 DCHECK_GE(current_find_index, 0);
963 SelectedFindResultChanged(current_find_index);
966 void OutOfProcessInstance::GetDocumentPassword(
967 pp::CompletionCallbackWithOutput<pp::Var> callback) {
968 if (password_callback_) {
969 NOTREACHED();
970 return;
973 password_callback_.reset(
974 new pp::CompletionCallbackWithOutput<pp::Var>(callback));
975 pp::VarDictionary message;
976 message.Set(pp::Var(kType), pp::Var(kJSGetPasswordType));
977 PostMessage(message);
980 void OutOfProcessInstance::Alert(const std::string& message) {
981 ModalDialog(this, "alert", message, std::string());
984 bool OutOfProcessInstance::Confirm(const std::string& message) {
985 pp::Var result = ModalDialog(this, "confirm", message, std::string());
986 return result.is_bool() ? result.AsBool() : false;
989 std::string OutOfProcessInstance::Prompt(const std::string& question,
990 const std::string& default_answer) {
991 pp::Var result = ModalDialog(this, "prompt", question, default_answer);
992 return result.is_string() ? result.AsString() : std::string();
995 std::string OutOfProcessInstance::GetURL() {
996 return url_;
999 void OutOfProcessInstance::Email(const std::string& to,
1000 const std::string& cc,
1001 const std::string& bcc,
1002 const std::string& subject,
1003 const std::string& body) {
1004 pp::VarDictionary message;
1005 message.Set(pp::Var(kType), pp::Var(kJSEmailType));
1006 message.Set(pp::Var(kJSEmailTo),
1007 pp::Var(net::EscapeUrlEncodedData(to, false)));
1008 message.Set(pp::Var(kJSEmailCc),
1009 pp::Var(net::EscapeUrlEncodedData(cc, false)));
1010 message.Set(pp::Var(kJSEmailBcc),
1011 pp::Var(net::EscapeUrlEncodedData(bcc, false)));
1012 message.Set(pp::Var(kJSEmailSubject),
1013 pp::Var(net::EscapeUrlEncodedData(subject, false)));
1014 message.Set(pp::Var(kJSEmailBody),
1015 pp::Var(net::EscapeUrlEncodedData(body, false)));
1016 PostMessage(message);
1019 void OutOfProcessInstance::Print() {
1020 if (!engine_->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY) &&
1021 !engine_->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY)) {
1022 return;
1025 pp::CompletionCallback callback =
1026 print_callback_factory_.NewCallback(&OutOfProcessInstance::OnPrint);
1027 pp::Module::Get()->core()->CallOnMainThread(0, callback);
1030 void OutOfProcessInstance::OnPrint(int32_t) {
1031 pp::PDF::Print(this);
1034 void OutOfProcessInstance::SubmitForm(const std::string& url,
1035 const void* data,
1036 int length) {
1037 pp::URLRequestInfo request(this);
1038 request.SetURL(url);
1039 request.SetMethod("POST");
1040 request.AppendDataToBody(reinterpret_cast<const char*>(data), length);
1042 pp::CompletionCallback callback =
1043 form_factory_.NewCallback(&OutOfProcessInstance::FormDidOpen);
1044 form_loader_ = CreateURLLoaderInternal();
1045 int rv = form_loader_.Open(request, callback);
1046 if (rv != PP_OK_COMPLETIONPENDING)
1047 callback.Run(rv);
1050 void OutOfProcessInstance::FormDidOpen(int32_t result) {
1051 // TODO: inform the user of success/failure.
1052 if (result != PP_OK) {
1053 NOTREACHED();
1057 std::string OutOfProcessInstance::ShowFileSelectionDialog() {
1058 // Seems like very low priority to implement, since the pdf has no way to get
1059 // the file data anyways. Javascript doesn't let you do this synchronously.
1060 NOTREACHED();
1061 return std::string();
1064 pp::URLLoader OutOfProcessInstance::CreateURLLoader() {
1065 if (full_) {
1066 if (!did_call_start_loading_) {
1067 did_call_start_loading_ = true;
1068 pp::PDF::DidStartLoading(this);
1071 // Disable save and print until the document is fully loaded, since they
1072 // would generate an incomplete document. Need to do this each time we
1073 // call DidStartLoading since that resets the content restrictions.
1074 pp::PDF::SetContentRestriction(this, CONTENT_RESTRICTION_SAVE |
1075 CONTENT_RESTRICTION_PRINT);
1078 return CreateURLLoaderInternal();
1081 void OutOfProcessInstance::ScheduleCallback(int id, int delay_in_ms) {
1082 pp::CompletionCallback callback =
1083 timer_factory_.NewCallback(&OutOfProcessInstance::OnClientTimerFired);
1084 pp::Module::Get()->core()->CallOnMainThread(delay_in_ms, callback, id);
1087 void OutOfProcessInstance::SearchString(const base::char16* string,
1088 const base::char16* term,
1089 bool case_sensitive,
1090 std::vector<SearchStringResult>* results) {
1091 PP_PrivateFindResult* pp_results;
1092 int count = 0;
1093 pp::PDF::SearchString(
1094 this,
1095 reinterpret_cast<const unsigned short*>(string),
1096 reinterpret_cast<const unsigned short*>(term),
1097 case_sensitive,
1098 &pp_results,
1099 &count);
1101 results->resize(count);
1102 for (int i = 0; i < count; ++i) {
1103 (*results)[i].start_index = pp_results[i].start_index;
1104 (*results)[i].length = pp_results[i].length;
1107 pp::Memory_Dev memory;
1108 memory.MemFree(pp_results);
1111 void OutOfProcessInstance::DocumentPaintOccurred() {
1114 void OutOfProcessInstance::DocumentLoadComplete(int page_count) {
1115 // Clear focus state for OSK.
1116 FormTextFieldFocusChange(false);
1118 DCHECK(document_load_state_ == LOAD_STATE_LOADING);
1119 document_load_state_ = LOAD_STATE_COMPLETE;
1120 UserMetricsRecordAction("PDF.LoadSuccess");
1122 // Note: If we are in print preview mode the scroll location is retained
1123 // across document loads so we don't want to scroll again and override it.
1124 if (IsPrintPreview()) {
1125 AppendBlankPrintPreviewPages();
1126 OnGeometryChanged(0, 0);
1129 pp::VarDictionary bookmarks_message;
1130 bookmarks_message.Set(pp::Var(kType), pp::Var(kJSBookmarksType));
1131 bookmarks_message.Set(pp::Var(kJSBookmarks), engine_->GetBookmarks());
1132 PostMessage(bookmarks_message);
1134 pp::VarDictionary progress_message;
1135 progress_message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1136 progress_message.Set(pp::Var(kJSProgressPercentage), pp::Var(100));
1137 PostMessage(progress_message);
1139 if (!full_)
1140 return;
1142 if (did_call_start_loading_) {
1143 pp::PDF::DidStopLoading(this);
1144 did_call_start_loading_ = false;
1147 int content_restrictions =
1148 CONTENT_RESTRICTION_CUT | CONTENT_RESTRICTION_PASTE;
1149 if (!engine_->HasPermission(PDFEngine::PERMISSION_COPY))
1150 content_restrictions |= CONTENT_RESTRICTION_COPY;
1152 if (!engine_->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY) &&
1153 !engine_->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY)) {
1154 content_restrictions |= CONTENT_RESTRICTION_PRINT;
1157 pp::PDF::SetContentRestriction(this, content_restrictions);
1159 uma_.HistogramCustomCounts("PDF.PageCount", page_count, 1, 1000000, 50);
1162 void OutOfProcessInstance::RotateClockwise() {
1163 engine_->RotateClockwise();
1166 void OutOfProcessInstance::RotateCounterclockwise() {
1167 engine_->RotateCounterclockwise();
1170 void OutOfProcessInstance::PreviewDocumentLoadComplete() {
1171 if (preview_document_load_state_ != LOAD_STATE_LOADING ||
1172 preview_pages_info_.empty()) {
1173 return;
1176 preview_document_load_state_ = LOAD_STATE_COMPLETE;
1178 int dest_page_index = preview_pages_info_.front().second;
1179 int src_page_index =
1180 ExtractPrintPreviewPageIndex(preview_pages_info_.front().first);
1181 if (src_page_index > 0 && dest_page_index > -1 && preview_engine_.get())
1182 engine_->AppendPage(preview_engine_.get(), dest_page_index);
1184 preview_pages_info_.pop();
1185 // |print_preview_page_count_| is not updated yet. Do not load any
1186 // other preview pages till we get this information.
1187 if (print_preview_page_count_ == 0)
1188 return;
1190 if (!preview_pages_info_.empty())
1191 LoadAvailablePreviewPage();
1194 void OutOfProcessInstance::DocumentLoadFailed() {
1195 DCHECK(document_load_state_ == LOAD_STATE_LOADING);
1196 UserMetricsRecordAction("PDF.LoadFailure");
1198 if (did_call_start_loading_) {
1199 pp::PDF::DidStopLoading(this);
1200 did_call_start_loading_ = false;
1203 document_load_state_ = LOAD_STATE_FAILED;
1204 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
1206 // Send a progress value of -1 to indicate a failure.
1207 pp::VarDictionary message;
1208 message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1209 message.Set(pp::Var(kJSProgressPercentage), pp::Var(-1));
1210 PostMessage(message);
1213 void OutOfProcessInstance::PreviewDocumentLoadFailed() {
1214 UserMetricsRecordAction("PDF.PreviewDocumentLoadFailure");
1215 if (preview_document_load_state_ != LOAD_STATE_LOADING ||
1216 preview_pages_info_.empty()) {
1217 return;
1220 preview_document_load_state_ = LOAD_STATE_FAILED;
1221 preview_pages_info_.pop();
1223 if (!preview_pages_info_.empty())
1224 LoadAvailablePreviewPage();
1227 pp::Instance* OutOfProcessInstance::GetPluginInstance() {
1228 return this;
1231 void OutOfProcessInstance::DocumentHasUnsupportedFeature(
1232 const std::string& feature) {
1233 std::string metric("PDF_Unsupported_");
1234 metric += feature;
1235 if (!unsupported_features_reported_.count(metric)) {
1236 unsupported_features_reported_.insert(metric);
1237 UserMetricsRecordAction(metric);
1240 // Since we use an info bar, only do this for full frame plugins..
1241 if (!full_)
1242 return;
1244 if (told_browser_about_unsupported_feature_)
1245 return;
1246 told_browser_about_unsupported_feature_ = true;
1248 pp::PDF::HasUnsupportedFeature(this);
1251 void OutOfProcessInstance::DocumentLoadProgress(uint32 available,
1252 uint32 doc_size) {
1253 double progress = 0.0;
1254 if (doc_size == 0) {
1255 // Document size is unknown. Use heuristics.
1256 // We'll make progress logarithmic from 0 to 100M.
1257 static const double kFactor = log(100000000.0) / 100.0;
1258 if (available > 0) {
1259 progress = log(static_cast<double>(available)) / kFactor;
1260 if (progress > 100.0)
1261 progress = 100.0;
1263 } else {
1264 progress = 100.0 * static_cast<double>(available) / doc_size;
1267 // We send 100% load progress in DocumentLoadComplete.
1268 if (progress >= 100)
1269 return;
1271 // Avoid sending too many progress messages over PostMessage.
1272 if (progress > last_progress_sent_ + 1) {
1273 last_progress_sent_ = progress;
1274 pp::VarDictionary message;
1275 message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1276 message.Set(pp::Var(kJSProgressPercentage), pp::Var(progress));
1277 PostMessage(message);
1281 void OutOfProcessInstance::FormTextFieldFocusChange(bool in_focus) {
1282 if (!text_input_.get())
1283 return;
1284 if (in_focus)
1285 text_input_->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_TEXT);
1286 else
1287 text_input_->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_NONE);
1290 void OutOfProcessInstance::ResetRecentlySentFindUpdate(int32_t /* unused */) {
1291 recently_sent_find_update_ = false;
1294 void OutOfProcessInstance::OnGeometryChanged(double old_zoom,
1295 float old_device_scale) {
1296 if (zoom_ != old_zoom || device_scale_ != old_device_scale)
1297 engine_->ZoomUpdated(zoom_ * device_scale_);
1299 available_area_ = pp::Rect(plugin_size_);
1300 int doc_width = GetDocumentPixelWidth();
1301 if (doc_width < available_area_.width()) {
1302 available_area_.Offset((available_area_.width() - doc_width) / 2, 0);
1303 available_area_.set_width(doc_width);
1305 int bottom_of_document =
1306 GetDocumentPixelHeight() + (top_toolbar_height_ * device_scale_);
1307 if (bottom_of_document < available_area_.height())
1308 available_area_.set_height(bottom_of_document);
1310 CalculateBackgroundParts();
1311 engine_->PageOffsetUpdated(available_area_.point());
1312 engine_->PluginSizeUpdated(available_area_.size());
1314 if (!document_size_.GetArea())
1315 return;
1316 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
1319 void OutOfProcessInstance::LoadUrl(const std::string& url) {
1320 LoadUrlInternal(url, &embed_loader_, &OutOfProcessInstance::DidOpen);
1323 void OutOfProcessInstance::LoadPreviewUrl(const std::string& url) {
1324 LoadUrlInternal(url, &embed_preview_loader_,
1325 &OutOfProcessInstance::DidOpenPreview);
1328 void OutOfProcessInstance::LoadUrlInternal(
1329 const std::string& url,
1330 pp::URLLoader* loader,
1331 void (OutOfProcessInstance::* method)(int32_t)) {
1332 pp::URLRequestInfo request(this);
1333 request.SetURL(url);
1334 request.SetMethod("GET");
1336 *loader = CreateURLLoaderInternal();
1337 pp::CompletionCallback callback = loader_factory_.NewCallback(method);
1338 int rv = loader->Open(request, callback);
1339 if (rv != PP_OK_COMPLETIONPENDING)
1340 callback.Run(rv);
1343 pp::URLLoader OutOfProcessInstance::CreateURLLoaderInternal() {
1344 pp::URLLoader loader(this);
1346 const PPB_URLLoaderTrusted* trusted_interface =
1347 reinterpret_cast<const PPB_URLLoaderTrusted*>(
1348 pp::Module::Get()->GetBrowserInterface(
1349 PPB_URLLOADERTRUSTED_INTERFACE));
1350 if (trusted_interface)
1351 trusted_interface->GrantUniversalAccess(loader.pp_resource());
1352 return loader;
1355 void OutOfProcessInstance::SetZoom(double scale) {
1356 double old_zoom = zoom_;
1357 zoom_ = scale;
1358 OnGeometryChanged(old_zoom, device_scale_);
1361 std::string OutOfProcessInstance::GetLocalizedString(PP_ResourceString id) {
1362 pp::Var rv(pp::PDF::GetLocalizedString(this, id));
1363 if (!rv.is_string())
1364 return std::string();
1366 return rv.AsString();
1369 void OutOfProcessInstance::AppendBlankPrintPreviewPages() {
1370 if (print_preview_page_count_ == 0)
1371 return;
1372 engine_->AppendBlankPages(print_preview_page_count_);
1373 if (!preview_pages_info_.empty())
1374 LoadAvailablePreviewPage();
1377 bool OutOfProcessInstance::IsPrintPreview() {
1378 return IsPrintPreviewUrl(url_);
1381 uint32 OutOfProcessInstance::GetBackgroundColor() {
1382 return background_color_;
1385 void OutOfProcessInstance::IsSelectingChanged(bool is_selecting) {
1386 pp::VarDictionary message;
1387 message.Set(kType, kJSSetIsSelectingType);
1388 message.Set(kJSIsSelecting, pp::Var(is_selecting));
1389 PostMessage(message);
1392 void OutOfProcessInstance::ProcessPreviewPageInfo(const std::string& url,
1393 int dst_page_index) {
1394 if (!IsPrintPreview())
1395 return;
1397 int src_page_index = ExtractPrintPreviewPageIndex(url);
1398 if (src_page_index < 1)
1399 return;
1401 preview_pages_info_.push(std::make_pair(url, dst_page_index));
1402 LoadAvailablePreviewPage();
1405 void OutOfProcessInstance::LoadAvailablePreviewPage() {
1406 if (preview_pages_info_.empty() ||
1407 document_load_state_ != LOAD_STATE_COMPLETE) {
1408 return;
1411 std::string url = preview_pages_info_.front().first;
1412 int dst_page_index = preview_pages_info_.front().second;
1413 int src_page_index = ExtractPrintPreviewPageIndex(url);
1414 if (src_page_index < 1 ||
1415 dst_page_index >= print_preview_page_count_ ||
1416 preview_document_load_state_ == LOAD_STATE_LOADING) {
1417 return;
1420 preview_document_load_state_ = LOAD_STATE_LOADING;
1421 LoadPreviewUrl(url);
1424 void OutOfProcessInstance::UserMetricsRecordAction(
1425 const std::string& action) {
1426 // TODO(raymes): Move this function to PPB_UMA_Private.
1427 pp::PDF::UserMetricsRecordAction(this, pp::Var(action));
1430 pp::FloatPoint OutOfProcessInstance::BoundScrollOffsetToDocument(
1431 const pp::FloatPoint& scroll_offset) {
1432 float max_x = document_size_.width() * zoom_ - plugin_dip_size_.width();
1433 float x = std::max(std::min(scroll_offset.x(), max_x), 0.0f);
1434 float min_y = -top_toolbar_height_;
1435 float max_y = document_size_.height() * zoom_ - plugin_dip_size_.height();
1436 float y = std::max(std::min(scroll_offset.y(), max_y), min_y);
1437 return pp::FloatPoint(x, y);
1440 } // namespace chrome_pdf