Add RemoteDeviceLifeCycle to manage the life cycle of a remote Smart Lock phone.
[chromium-blink-merge.git] / pdf / out_of_process_instance.cc
blob3478b78b7935717fc2c04f101f96283013905ce6
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/strings/utf_string_conversions.h"
20 #include "base/values.h"
21 #include "chrome/common/content_restriction.h"
22 #include "net/base/escape.h"
23 #include "pdf/pdf.h"
24 #include "ppapi/c/dev/ppb_cursor_control_dev.h"
25 #include "ppapi/c/pp_errors.h"
26 #include "ppapi/c/pp_rect.h"
27 #include "ppapi/c/private/ppb_instance_private.h"
28 #include "ppapi/c/private/ppp_pdf.h"
29 #include "ppapi/c/trusted/ppb_url_loader_trusted.h"
30 #include "ppapi/cpp/core.h"
31 #include "ppapi/cpp/dev/memory_dev.h"
32 #include "ppapi/cpp/dev/text_input_dev.h"
33 #include "ppapi/cpp/dev/url_util_dev.h"
34 #include "ppapi/cpp/module.h"
35 #include "ppapi/cpp/point.h"
36 #include "ppapi/cpp/private/pdf.h"
37 #include "ppapi/cpp/private/var_private.h"
38 #include "ppapi/cpp/rect.h"
39 #include "ppapi/cpp/resource.h"
40 #include "ppapi/cpp/url_request_info.h"
41 #include "ppapi/cpp/var_array.h"
42 #include "ppapi/cpp/var_dictionary.h"
43 #include "ui/events/keycodes/keyboard_codes.h"
45 namespace chrome_pdf {
47 const char kChromePrint[] = "chrome://print/";
48 const char kChromeExtension[] =
49 "chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai";
51 // Dictionary Value key names for the document accessibility info
52 const char kAccessibleNumberOfPages[] = "numberOfPages";
53 const char kAccessibleLoaded[] = "loaded";
54 const char kAccessibleCopyable[] = "copyable";
56 // Constants used in handling postMessage() messages.
57 const char kType[] = "type";
58 // Viewport message arguments. (Page -> Plugin).
59 const char kJSViewportType[] = "viewport";
60 const char kJSXOffset[] = "xOffset";
61 const char kJSYOffset[] = "yOffset";
62 const char kJSZoom[] = "zoom";
63 // Stop scrolling message (Page -> Plugin)
64 const char kJSStopScrollingType[] = "stopScrolling";
65 // Document dimension arguments (Plugin -> Page).
66 const char kJSDocumentDimensionsType[] = "documentDimensions";
67 const char kJSDocumentWidth[] = "width";
68 const char kJSDocumentHeight[] = "height";
69 const char kJSPageDimensions[] = "pageDimensions";
70 const char kJSPageX[] = "x";
71 const char kJSPageY[] = "y";
72 const char kJSPageWidth[] = "width";
73 const char kJSPageHeight[] = "height";
74 // Document load progress arguments (Plugin -> Page)
75 const char kJSLoadProgressType[] = "loadProgress";
76 const char kJSProgressPercentage[] = "progress";
77 // Metadata
78 const char kJSMetadataType[] = "metadata";
79 const char kJSBookmarks[] = "bookmarks";
80 const char kJSTitle[] = "title";
81 // Get password arguments (Plugin -> Page)
82 const char kJSGetPasswordType[] = "getPassword";
83 // Get password complete arguments (Page -> Plugin)
84 const char kJSGetPasswordCompleteType[] = "getPasswordComplete";
85 const char kJSPassword[] = "password";
86 // Print (Page -> Plugin)
87 const char kJSPrintType[] = "print";
88 // Save (Page -> Plugin)
89 const char kJSSaveType[] = "save";
90 // Go to page (Plugin -> Page)
91 const char kJSGoToPageType[] = "goToPage";
92 const char kJSPageNumber[] = "page";
93 // Reset print preview mode (Page -> Plugin)
94 const char kJSResetPrintPreviewModeType[] = "resetPrintPreviewMode";
95 const char kJSPrintPreviewUrl[] = "url";
96 const char kJSPrintPreviewGrayscale[] = "grayscale";
97 const char kJSPrintPreviewPageCount[] = "pageCount";
98 // Load preview page (Page -> Plugin)
99 const char kJSLoadPreviewPageType[] = "loadPreviewPage";
100 const char kJSPreviewPageUrl[] = "url";
101 const char kJSPreviewPageIndex[] = "index";
102 // Set scroll position (Plugin -> Page)
103 const char kJSSetScrollPositionType[] = "setScrollPosition";
104 const char kJSPositionX[] = "x";
105 const char kJSPositionY[] = "y";
106 // Request accessibility JSON data (Page -> Plugin)
107 const char kJSGetAccessibilityJSONType[] = "getAccessibilityJSON";
108 const char kJSAccessibilityPageNumber[] = "page";
109 // Reply with accessibility JSON data (Plugin -> Page)
110 const char kJSGetAccessibilityJSONReplyType[] = "getAccessibilityJSONReply";
111 const char kJSAccessibilityJSON[] = "json";
112 // Cancel the stream URL request (Plugin -> Page)
113 const char kJSCancelStreamUrlType[] = "cancelStreamUrl";
114 // Navigate to the given URL (Plugin -> Page)
115 const char kJSNavigateType[] = "navigate";
116 const char kJSNavigateUrl[] = "url";
117 const char kJSNavigateNewTab[] = "newTab";
118 // Open the email editor with the given parameters (Plugin -> Page)
119 const char kJSEmailType[] = "email";
120 const char kJSEmailTo[] = "to";
121 const char kJSEmailCc[] = "cc";
122 const char kJSEmailBcc[] = "bcc";
123 const char kJSEmailSubject[] = "subject";
124 const char kJSEmailBody[] = "body";
125 // Rotation (Page -> Plugin)
126 const char kJSRotateClockwiseType[] = "rotateClockwise";
127 const char kJSRotateCounterclockwiseType[] = "rotateCounterclockwise";
128 // Select all text in the document (Page -> Plugin)
129 const char kJSSelectAllType[] = "selectAll";
130 // Get the selected text in the document (Page -> Plugin)
131 const char kJSGetSelectedTextType[] = "getSelectedText";
132 // Reply with selected text (Plugin -> Page)
133 const char kJSGetSelectedTextReplyType[] = "getSelectedTextReply";
134 const char kJSSelectedText[] = "selectedText";
136 // Get the named destination with the given name (Page -> Plugin)
137 const char KJSGetNamedDestinationType[] = "getNamedDestination";
138 const char KJSGetNamedDestination[] = "namedDestination";
139 // Reply with the page number of the named destination (Plugin -> Page)
140 const char kJSGetNamedDestinationReplyType[] = "getNamedDestinationReply";
141 const char kJSNamedDestinationPageNumber[] = "pageNumber";
143 // Selecting text in document (Plugin -> Page)
144 const char kJSSetIsSelectingType[] = "setIsSelecting";
145 const char kJSIsSelecting[] = "isSelecting";
147 const int kFindResultCooldownMs = 100;
149 const double kMinZoom = 0.01;
151 namespace {
153 static const char kPPPPdfInterface[] = PPP_PDF_INTERFACE_1;
155 PP_Var GetLinkAtPosition(PP_Instance instance, PP_Point point) {
156 pp::Var var;
157 void* object = pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
158 if (object) {
159 var = static_cast<OutOfProcessInstance*>(object)->GetLinkAtPosition(
160 pp::Point(point));
162 return var.Detach();
165 void Transform(PP_Instance instance, PP_PrivatePageTransformType type) {
166 void* object =
167 pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
168 if (object) {
169 OutOfProcessInstance* obj_instance =
170 static_cast<OutOfProcessInstance*>(object);
171 switch (type) {
172 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CW:
173 obj_instance->RotateClockwise();
174 break;
175 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CCW:
176 obj_instance->RotateCounterclockwise();
177 break;
182 PP_Bool GetPrintPresetOptionsFromDocument(
183 PP_Instance instance,
184 PP_PdfPrintPresetOptions_Dev* options) {
185 void* object = pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
186 if (object) {
187 OutOfProcessInstance* obj_instance =
188 static_cast<OutOfProcessInstance*>(object);
189 obj_instance->GetPrintPresetOptionsFromDocument(options);
191 return PP_TRUE;
194 const PPP_Pdf ppp_private = {
195 &GetLinkAtPosition,
196 &Transform,
197 &GetPrintPresetOptionsFromDocument
200 int ExtractPrintPreviewPageIndex(const std::string& src_url) {
201 // Sample |src_url| format: chrome://print/id/page_index/print.pdf
202 std::vector<std::string> url_substr = base::SplitString(
203 src_url.substr(strlen(kChromePrint)), "/",
204 base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
205 if (url_substr.size() != 3)
206 return -1;
208 if (url_substr[2] != "print.pdf")
209 return -1;
211 int page_index = 0;
212 if (!base::StringToInt(url_substr[1], &page_index))
213 return -1;
214 return page_index;
217 bool IsPrintPreviewUrl(const std::string& url) {
218 return url.substr(0, strlen(kChromePrint)) == kChromePrint;
221 void ScalePoint(float scale, pp::Point* point) {
222 point->set_x(static_cast<int>(point->x() * scale));
223 point->set_y(static_cast<int>(point->y() * scale));
226 void ScaleRect(float scale, pp::Rect* rect) {
227 int left = static_cast<int>(floorf(rect->x() * scale));
228 int top = static_cast<int>(floorf(rect->y() * scale));
229 int right = static_cast<int>(ceilf((rect->x() + rect->width()) * scale));
230 int bottom = static_cast<int>(ceilf((rect->y() + rect->height()) * scale));
231 rect->SetRect(left, top, right - left, bottom - top);
234 // TODO(raymes): Remove this dependency on VarPrivate/InstancePrivate. It's
235 // needed right now to do a synchronous call to JavaScript, but we could easily
236 // replace this with a custom PPB_PDF function.
237 pp::Var ModalDialog(const pp::Instance* instance,
238 const std::string& type,
239 const std::string& message,
240 const std::string& default_answer) {
241 const PPB_Instance_Private* interface =
242 reinterpret_cast<const PPB_Instance_Private*>(
243 pp::Module::Get()->GetBrowserInterface(
244 PPB_INSTANCE_PRIVATE_INTERFACE));
245 pp::VarPrivate window(pp::PASS_REF,
246 interface->GetWindowObject(instance->pp_instance()));
247 if (default_answer.empty())
248 return window.Call(type, message);
249 else
250 return window.Call(type, message, default_answer);
253 } // namespace
255 OutOfProcessInstance::OutOfProcessInstance(PP_Instance instance)
256 : pp::Instance(instance),
257 pp::Find_Private(this),
258 pp::Printing_Dev(this),
259 cursor_(PP_CURSORTYPE_POINTER),
260 zoom_(1.0),
261 device_scale_(1.0),
262 full_(false),
263 paint_manager_(this, this, true),
264 first_paint_(true),
265 document_load_state_(LOAD_STATE_LOADING),
266 preview_document_load_state_(LOAD_STATE_COMPLETE),
267 uma_(this),
268 told_browser_about_unsupported_feature_(false),
269 print_preview_page_count_(0),
270 last_progress_sent_(0),
271 recently_sent_find_update_(false),
272 received_viewport_message_(false),
273 did_call_start_loading_(false),
274 stop_scrolling_(false),
275 background_color_(0),
276 top_toolbar_height_(0) {
277 loader_factory_.Initialize(this);
278 timer_factory_.Initialize(this);
279 form_factory_.Initialize(this);
280 print_callback_factory_.Initialize(this);
281 engine_.reset(PDFEngine::Create(this));
282 pp::Module::Get()->AddPluginInterface(kPPPPdfInterface, &ppp_private);
283 AddPerInstanceObject(kPPPPdfInterface, this);
285 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_MOUSE);
286 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_KEYBOARD);
287 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_TOUCH);
290 OutOfProcessInstance::~OutOfProcessInstance() {
291 RemovePerInstanceObject(kPPPPdfInterface, this);
292 // Explicitly reset the PDFEngine during destruction as it may call back into
293 // this object.
294 engine_.reset();
297 bool OutOfProcessInstance::Init(uint32_t argc,
298 const char* argn[],
299 const char* argv[]) {
300 // Check if the PDF is being loaded in the PDF chrome extension. We only allow
301 // the plugin to be loaded in the extension and print preview to avoid
302 // exposing sensitive APIs directly to external websites.
303 pp::Var document_url_var = pp::URLUtil_Dev::Get()->GetDocumentURL(this);
304 if (!document_url_var.is_string())
305 return false;
306 std::string document_url = document_url_var.AsString();
307 std::string extension_url = std::string(kChromeExtension);
308 std::string print_preview_url = std::string(kChromePrint);
309 if (!base::StringPiece(document_url).starts_with(kChromeExtension) &&
310 !base::StringPiece(document_url).starts_with(kChromePrint)) {
311 return false;
314 // Check if the plugin is full frame. This is passed in from JS.
315 for (uint32_t i = 0; i < argc; ++i) {
316 if (strcmp(argn[i], "full-frame") == 0) {
317 full_ = true;
318 break;
322 // Only allow the plugin to handle find requests if it is full frame.
323 if (full_)
324 SetPluginToHandleFindRequests();
326 text_input_.reset(new pp::TextInput_Dev(this));
328 const char* stream_url = nullptr;
329 const char* original_url = nullptr;
330 const char* headers = nullptr;
331 for (uint32_t i = 0; i < argc; ++i) {
332 bool success = true;
333 if (strcmp(argn[i], "src") == 0)
334 original_url = argv[i];
335 else if (strcmp(argn[i], "stream-url") == 0)
336 stream_url = argv[i];
337 else if (strcmp(argn[i], "headers") == 0)
338 headers = argv[i];
339 else if (strcmp(argn[i], "background-color") == 0)
340 success = base::HexStringToUInt(argv[i], &background_color_);
341 else if (strcmp(argn[i], "top-toolbar-height") == 0)
342 success = base::StringToInt(argv[i], &top_toolbar_height_);
344 if (!success)
345 return false;
348 if (!original_url)
349 return false;
351 if (!stream_url)
352 stream_url = original_url;
354 // If we're in print preview mode we don't need to load the document yet.
355 // A |kJSResetPrintPreviewModeType| message will be sent to the plugin letting
356 // it know the url to load. By not loading here we avoid loading the same
357 // document twice.
358 if (IsPrintPreviewUrl(original_url))
359 return true;
361 LoadUrl(stream_url);
362 url_ = original_url;
363 return engine_->New(original_url, headers);
366 void OutOfProcessInstance::HandleMessage(const pp::Var& message) {
367 pp::VarDictionary dict(message);
368 if (!dict.Get(kType).is_string()) {
369 NOTREACHED();
370 return;
373 std::string type = dict.Get(kType).AsString();
375 if (type == kJSViewportType &&
376 dict.Get(pp::Var(kJSXOffset)).is_number() &&
377 dict.Get(pp::Var(kJSYOffset)).is_number() &&
378 dict.Get(pp::Var(kJSZoom)).is_number()) {
379 received_viewport_message_ = true;
380 stop_scrolling_ = false;
381 double zoom = dict.Get(pp::Var(kJSZoom)).AsDouble();
382 pp::FloatPoint scroll_offset(dict.Get(pp::Var(kJSXOffset)).AsDouble(),
383 dict.Get(pp::Var(kJSYOffset)).AsDouble());
385 // Bound the input parameters.
386 zoom = std::max(kMinZoom, zoom);
387 SetZoom(zoom);
388 scroll_offset = BoundScrollOffsetToDocument(scroll_offset);
389 engine_->ScrolledToXPosition(scroll_offset.x() * device_scale_);
390 engine_->ScrolledToYPosition(scroll_offset.y() * device_scale_);
391 } else if (type == kJSGetPasswordCompleteType &&
392 dict.Get(pp::Var(kJSPassword)).is_string()) {
393 if (password_callback_) {
394 pp::CompletionCallbackWithOutput<pp::Var> callback = *password_callback_;
395 password_callback_.reset();
396 *callback.output() = dict.Get(pp::Var(kJSPassword)).pp_var();
397 callback.Run(PP_OK);
398 } else {
399 NOTREACHED();
401 } else if (type == kJSPrintType) {
402 Print();
403 } else if (type == kJSSaveType) {
404 pp::PDF::SaveAs(this);
405 } else if (type == kJSRotateClockwiseType) {
406 RotateClockwise();
407 } else if (type == kJSRotateCounterclockwiseType) {
408 RotateCounterclockwise();
409 } else if (type == kJSSelectAllType) {
410 engine_->SelectAll();
411 } else if (type == kJSResetPrintPreviewModeType &&
412 dict.Get(pp::Var(kJSPrintPreviewUrl)).is_string() &&
413 dict.Get(pp::Var(kJSPrintPreviewGrayscale)).is_bool() &&
414 dict.Get(pp::Var(kJSPrintPreviewPageCount)).is_int()) {
415 url_ = dict.Get(pp::Var(kJSPrintPreviewUrl)).AsString();
416 preview_pages_info_ = std::queue<PreviewPageInfo>();
417 preview_document_load_state_ = LOAD_STATE_COMPLETE;
418 document_load_state_ = LOAD_STATE_LOADING;
419 LoadUrl(url_);
420 preview_engine_.reset();
421 engine_.reset(PDFEngine::Create(this));
422 engine_->SetGrayscale(dict.Get(pp::Var(kJSPrintPreviewGrayscale)).AsBool());
423 engine_->New(url_.c_str(), nullptr /* empty header */);
425 print_preview_page_count_ =
426 std::max(dict.Get(pp::Var(kJSPrintPreviewPageCount)).AsInt(), 0);
428 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
429 } else if (type == kJSLoadPreviewPageType &&
430 dict.Get(pp::Var(kJSPreviewPageUrl)).is_string() &&
431 dict.Get(pp::Var(kJSPreviewPageIndex)).is_int()) {
432 ProcessPreviewPageInfo(dict.Get(pp::Var(kJSPreviewPageUrl)).AsString(),
433 dict.Get(pp::Var(kJSPreviewPageIndex)).AsInt());
434 } else if (type == kJSGetAccessibilityJSONType) {
435 pp::VarDictionary reply;
436 reply.Set(pp::Var(kType), pp::Var(kJSGetAccessibilityJSONReplyType));
437 if (dict.Get(pp::Var(kJSAccessibilityPageNumber)).is_int()) {
438 int page = dict.Get(pp::Var(kJSAccessibilityPageNumber)).AsInt();
439 reply.Set(pp::Var(kJSAccessibilityJSON),
440 pp::Var(engine_->GetPageAsJSON(page)));
441 } else {
442 base::DictionaryValue node;
443 node.SetInteger(kAccessibleNumberOfPages, engine_->GetNumberOfPages());
444 node.SetBoolean(kAccessibleLoaded,
445 document_load_state_ != LOAD_STATE_LOADING);
446 bool has_permissions =
447 engine_->HasPermission(PDFEngine::PERMISSION_COPY) ||
448 engine_->HasPermission(PDFEngine::PERMISSION_COPY_ACCESSIBLE);
449 node.SetBoolean(kAccessibleCopyable, has_permissions);
450 std::string json;
451 base::JSONWriter::Write(node, &json);
452 reply.Set(pp::Var(kJSAccessibilityJSON), pp::Var(json));
454 PostMessage(reply);
455 } else if (type == kJSStopScrollingType) {
456 stop_scrolling_ = true;
457 } else if (type == kJSGetSelectedTextType) {
458 std::string selected_text = engine_->GetSelectedText();
459 // Always return unix newlines to JS.
460 base::ReplaceChars(selected_text, "\r", std::string(), &selected_text);
461 pp::VarDictionary reply;
462 reply.Set(pp::Var(kType), pp::Var(kJSGetSelectedTextReplyType));
463 reply.Set(pp::Var(kJSSelectedText), selected_text);
464 PostMessage(reply);
465 } else if (type == KJSGetNamedDestinationType &&
466 dict.Get(pp::Var(KJSGetNamedDestination)).is_string()) {
467 int page_number = engine_->GetNamedDestinationPage(
468 dict.Get(pp::Var(KJSGetNamedDestination)).AsString());
469 pp::VarDictionary reply;
470 reply.Set(pp::Var(kType), pp::Var(kJSGetNamedDestinationReplyType));
471 if (page_number >= 0)
472 reply.Set(pp::Var(kJSNamedDestinationPageNumber), page_number);
473 PostMessage(reply);
474 } else {
475 NOTREACHED();
479 bool OutOfProcessInstance::HandleInputEvent(
480 const pp::InputEvent& event) {
481 // To simplify things, convert the event into device coordinates if it is
482 // a mouse event.
483 pp::InputEvent event_device_res(event);
485 pp::MouseInputEvent mouse_event(event);
486 if (!mouse_event.is_null()) {
487 pp::Point point = mouse_event.GetPosition();
488 pp::Point movement = mouse_event.GetMovement();
489 ScalePoint(device_scale_, &point);
490 ScalePoint(device_scale_, &movement);
491 mouse_event = pp::MouseInputEvent(
492 this,
493 event.GetType(),
494 event.GetTimeStamp(),
495 event.GetModifiers(),
496 mouse_event.GetButton(),
497 point,
498 mouse_event.GetClickCount(),
499 movement);
500 event_device_res = mouse_event;
504 pp::InputEvent offset_event(event_device_res);
505 switch (offset_event.GetType()) {
506 case PP_INPUTEVENT_TYPE_MOUSEDOWN:
507 case PP_INPUTEVENT_TYPE_MOUSEUP:
508 case PP_INPUTEVENT_TYPE_MOUSEMOVE:
509 case PP_INPUTEVENT_TYPE_MOUSEENTER:
510 case PP_INPUTEVENT_TYPE_MOUSELEAVE: {
511 pp::MouseInputEvent mouse_event(event_device_res);
512 pp::MouseInputEvent mouse_event_dip(event);
513 pp::Point point = mouse_event.GetPosition();
514 point.set_x(point.x() - available_area_.x());
515 offset_event = pp::MouseInputEvent(
516 this,
517 event.GetType(),
518 event.GetTimeStamp(),
519 event.GetModifiers(),
520 mouse_event.GetButton(),
521 point,
522 mouse_event.GetClickCount(),
523 mouse_event.GetMovement());
524 break;
526 default:
527 break;
529 if (engine_->HandleEvent(offset_event))
530 return true;
532 // Middle click is used for scrolling and is handled by the container page.
533 pp::MouseInputEvent mouse_event(event_device_res);
534 if (!mouse_event.is_null() &&
535 mouse_event.GetButton() == PP_INPUTEVENT_MOUSEBUTTON_MIDDLE) {
536 return false;
539 // Return true for unhandled clicks so the plugin takes focus.
540 return (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN);
543 void OutOfProcessInstance::DidChangeView(const pp::View& view) {
544 pp::Rect view_rect(view.GetRect());
545 float old_device_scale = device_scale_;
546 float device_scale = view.GetDeviceScale();
547 pp::Size view_device_size(view_rect.width() * device_scale,
548 view_rect.height() * device_scale);
550 if (view_device_size != plugin_size_ || device_scale != device_scale_) {
551 device_scale_ = device_scale;
552 plugin_dip_size_ = view_rect.size();
553 plugin_size_ = view_device_size;
555 paint_manager_.SetSize(view_device_size, device_scale_);
557 pp::Size new_image_data_size = PaintManager::GetNewContextSize(
558 image_data_.size(),
559 plugin_size_);
560 if (new_image_data_size != image_data_.size()) {
561 image_data_ = pp::ImageData(this,
562 PP_IMAGEDATAFORMAT_BGRA_PREMUL,
563 new_image_data_size,
564 false);
565 first_paint_ = true;
568 if (image_data_.is_null()) {
569 DCHECK(plugin_size_.IsEmpty());
570 return;
573 OnGeometryChanged(zoom_, old_device_scale);
576 if (!stop_scrolling_) {
577 pp::Point scroll_offset(view.GetScrollOffset());
578 // Because view messages come from the DOM, the coordinates of the viewport
579 // are 0-based (i.e. they do not correspond to the viewport's coordinates in
580 // JS), so we need to subtract the toolbar height to convert them into
581 // viewport coordinates.
582 pp::FloatPoint scroll_offset_float(scroll_offset.x(),
583 scroll_offset.y() - top_toolbar_height_);
584 scroll_offset_float = BoundScrollOffsetToDocument(scroll_offset_float);
585 engine_->ScrolledToXPosition(scroll_offset_float.x() * device_scale_);
586 engine_->ScrolledToYPosition(scroll_offset_float.y() * device_scale_);
590 void OutOfProcessInstance::GetPrintPresetOptionsFromDocument(
591 PP_PdfPrintPresetOptions_Dev* options) {
592 options->is_scaling_disabled = PP_FromBool(IsPrintScalingDisabled());
593 options->duplex =
594 static_cast<PP_PrivateDuplexMode_Dev>(engine_->GetDuplexType());
595 options->copies = engine_->GetCopiesToPrint();
596 pp::Size uniform_page_size;
597 options->is_page_size_uniform =
598 PP_FromBool(engine_->GetPageSizeAndUniformity(&uniform_page_size));
599 options->uniform_page_size = uniform_page_size;
602 pp::Var OutOfProcessInstance::GetLinkAtPosition(
603 const pp::Point& point) {
604 pp::Point offset_point(point);
605 ScalePoint(device_scale_, &offset_point);
606 offset_point.set_x(offset_point.x() - available_area_.x());
607 return engine_->GetLinkAtPosition(offset_point);
610 uint32_t OutOfProcessInstance::QuerySupportedPrintOutputFormats() {
611 return engine_->QuerySupportedPrintOutputFormats();
614 int32_t OutOfProcessInstance::PrintBegin(
615 const PP_PrintSettings_Dev& print_settings) {
616 // For us num_pages is always equal to the number of pages in the PDF
617 // document irrespective of the printable area.
618 int32_t ret = engine_->GetNumberOfPages();
619 if (!ret)
620 return 0;
622 uint32_t supported_formats = engine_->QuerySupportedPrintOutputFormats();
623 if ((print_settings.format & supported_formats) == 0)
624 return 0;
626 print_settings_.is_printing = true;
627 print_settings_.pepper_print_settings = print_settings;
628 engine_->PrintBegin();
629 return ret;
632 pp::Resource OutOfProcessInstance::PrintPages(
633 const PP_PrintPageNumberRange_Dev* page_ranges,
634 uint32_t page_range_count) {
635 if (!print_settings_.is_printing)
636 return pp::Resource();
638 print_settings_.print_pages_called_ = true;
639 return engine_->PrintPages(page_ranges, page_range_count,
640 print_settings_.pepper_print_settings);
643 void OutOfProcessInstance::PrintEnd() {
644 if (print_settings_.print_pages_called_)
645 UserMetricsRecordAction("PDF.PrintPage");
646 print_settings_.Clear();
647 engine_->PrintEnd();
650 bool OutOfProcessInstance::IsPrintScalingDisabled() {
651 return !engine_->GetPrintScaling();
654 bool OutOfProcessInstance::StartFind(const std::string& text,
655 bool case_sensitive) {
656 engine_->StartFind(text.c_str(), case_sensitive);
657 return true;
660 void OutOfProcessInstance::SelectFindResult(bool forward) {
661 engine_->SelectFindResult(forward);
664 void OutOfProcessInstance::StopFind() {
665 engine_->StopFind();
666 tickmarks_.clear();
667 SetTickmarks(tickmarks_);
670 void OutOfProcessInstance::OnPaint(
671 const std::vector<pp::Rect>& paint_rects,
672 std::vector<PaintManager::ReadyRect>* ready,
673 std::vector<pp::Rect>* pending) {
674 if (image_data_.is_null()) {
675 DCHECK(plugin_size_.IsEmpty());
676 return;
678 if (first_paint_) {
679 first_paint_ = false;
680 pp::Rect rect = pp::Rect(pp::Point(), image_data_.size());
681 FillRect(rect, background_color_);
682 ready->push_back(PaintManager::ReadyRect(rect, image_data_, true));
685 if (!received_viewport_message_)
686 return;
688 engine_->PrePaint();
690 for (size_t i = 0; i < paint_rects.size(); i++) {
691 // Intersect with plugin area since there could be pending invalidates from
692 // when the plugin area was larger.
693 pp::Rect rect =
694 paint_rects[i].Intersect(pp::Rect(pp::Point(), plugin_size_));
695 if (rect.IsEmpty())
696 continue;
698 pp::Rect pdf_rect = available_area_.Intersect(rect);
699 if (!pdf_rect.IsEmpty()) {
700 pdf_rect.Offset(available_area_.x() * -1, 0);
702 std::vector<pp::Rect> pdf_ready;
703 std::vector<pp::Rect> pdf_pending;
704 engine_->Paint(pdf_rect, &image_data_, &pdf_ready, &pdf_pending);
705 for (size_t j = 0; j < pdf_ready.size(); ++j) {
706 pdf_ready[j].Offset(available_area_.point());
707 ready->push_back(
708 PaintManager::ReadyRect(pdf_ready[j], image_data_, false));
710 for (size_t j = 0; j < pdf_pending.size(); ++j) {
711 pdf_pending[j].Offset(available_area_.point());
712 pending->push_back(pdf_pending[j]);
716 // Ensure the region above the first page (if any) is filled;
717 int32_t first_page_ypos = engine_->GetNumberOfPages() == 0 ?
718 0 : engine_->GetPageScreenRect(0).y();
719 if (rect.y() < first_page_ypos) {
720 pp::Rect region = rect.Intersect(pp::Rect(
721 pp::Point(), pp::Size(plugin_size_.width(), first_page_ypos)));
722 ready->push_back(PaintManager::ReadyRect(region, image_data_, false));
723 FillRect(region, background_color_);
726 for (size_t j = 0; j < background_parts_.size(); ++j) {
727 pp::Rect intersection = background_parts_[j].location.Intersect(rect);
728 if (!intersection.IsEmpty()) {
729 FillRect(intersection, background_parts_[j].color);
730 ready->push_back(
731 PaintManager::ReadyRect(intersection, image_data_, false));
736 engine_->PostPaint();
739 void OutOfProcessInstance::DidOpen(int32_t result) {
740 if (result == PP_OK) {
741 if (!engine_->HandleDocumentLoad(embed_loader_)) {
742 document_load_state_ = LOAD_STATE_LOADING;
743 DocumentLoadFailed();
745 } else if (result != PP_ERROR_ABORTED) { // Can happen in tests.
746 NOTREACHED();
747 DocumentLoadFailed();
750 // If it's a progressive load, cancel the stream URL request so that requests
751 // can be made on the original URL.
752 // TODO(raymes): Make this clearer once the in-process plugin is deleted.
753 if (engine_->IsProgressiveLoad()) {
754 pp::VarDictionary message;
755 message.Set(kType, kJSCancelStreamUrlType);
756 PostMessage(message);
760 void OutOfProcessInstance::DidOpenPreview(int32_t result) {
761 if (result == PP_OK) {
762 preview_client_.reset(new PreviewModeClient(this));
763 preview_engine_.reset(PDFEngine::Create(preview_client_.get()));
764 preview_engine_->HandleDocumentLoad(embed_preview_loader_);
765 } else {
766 NOTREACHED();
770 void OutOfProcessInstance::OnClientTimerFired(int32_t id) {
771 engine_->OnCallback(id);
774 void OutOfProcessInstance::CalculateBackgroundParts() {
775 background_parts_.clear();
776 int left_width = available_area_.x();
777 int right_start = available_area_.right();
778 int right_width = abs(plugin_size_.width() - available_area_.right());
779 int bottom = std::min(available_area_.bottom(), plugin_size_.height());
781 // Add the left, right, and bottom rectangles. Note: we assume only
782 // horizontal centering.
783 BackgroundPart part = {
784 pp::Rect(0, 0, left_width, bottom),
785 background_color_
787 if (!part.location.IsEmpty())
788 background_parts_.push_back(part);
789 part.location = pp::Rect(right_start, 0, right_width, bottom);
790 if (!part.location.IsEmpty())
791 background_parts_.push_back(part);
792 part.location = pp::Rect(
793 0, bottom, plugin_size_.width(), plugin_size_.height() - bottom);
794 if (!part.location.IsEmpty())
795 background_parts_.push_back(part);
798 int OutOfProcessInstance::GetDocumentPixelWidth() const {
799 return static_cast<int>(ceil(document_size_.width() * zoom_ * device_scale_));
802 int OutOfProcessInstance::GetDocumentPixelHeight() const {
803 return static_cast<int>(
804 ceil(document_size_.height() * zoom_ * device_scale_));
807 void OutOfProcessInstance::FillRect(const pp::Rect& rect, uint32 color) {
808 DCHECK(!image_data_.is_null() || rect.IsEmpty());
809 uint32* buffer_start = static_cast<uint32*>(image_data_.data());
810 int stride = image_data_.stride();
811 uint32* ptr = buffer_start + rect.y() * stride / 4 + rect.x();
812 int height = rect.height();
813 int width = rect.width();
814 for (int y = 0; y < height; ++y) {
815 for (int x = 0; x < width; ++x)
816 *(ptr + x) = color;
817 ptr += stride /4;
821 void OutOfProcessInstance::DocumentSizeUpdated(const pp::Size& size) {
822 document_size_ = size;
824 pp::VarDictionary dimensions;
825 dimensions.Set(kType, kJSDocumentDimensionsType);
826 dimensions.Set(kJSDocumentWidth, pp::Var(document_size_.width()));
827 dimensions.Set(kJSDocumentHeight, pp::Var(document_size_.height()));
828 pp::VarArray page_dimensions_array;
829 int num_pages = engine_->GetNumberOfPages();
830 for (int i = 0; i < num_pages; ++i) {
831 pp::Rect page_rect = engine_->GetPageRect(i);
832 pp::VarDictionary page_dimensions;
833 page_dimensions.Set(kJSPageX, pp::Var(page_rect.x()));
834 page_dimensions.Set(kJSPageY, pp::Var(page_rect.y()));
835 page_dimensions.Set(kJSPageWidth, pp::Var(page_rect.width()));
836 page_dimensions.Set(kJSPageHeight, pp::Var(page_rect.height()));
837 page_dimensions_array.Set(i, page_dimensions);
839 dimensions.Set(kJSPageDimensions, page_dimensions_array);
840 PostMessage(dimensions);
842 OnGeometryChanged(zoom_, device_scale_);
845 void OutOfProcessInstance::Invalidate(const pp::Rect& rect) {
846 pp::Rect offset_rect(rect);
847 offset_rect.Offset(available_area_.point());
848 paint_manager_.InvalidateRect(offset_rect);
851 void OutOfProcessInstance::Scroll(const pp::Point& point) {
852 if (!image_data_.is_null())
853 paint_manager_.ScrollRect(available_area_, point);
856 void OutOfProcessInstance::ScrollToX(int x) {
857 pp::VarDictionary position;
858 position.Set(kType, kJSSetScrollPositionType);
859 position.Set(kJSPositionX, pp::Var(x / device_scale_));
860 PostMessage(position);
863 void OutOfProcessInstance::ScrollToY(int y) {
864 pp::VarDictionary position;
865 position.Set(kType, kJSSetScrollPositionType);
866 position.Set(kJSPositionY, pp::Var(y / device_scale_));
867 PostMessage(position);
870 void OutOfProcessInstance::ScrollToPage(int page) {
871 if (engine_->GetNumberOfPages() == 0)
872 return;
874 pp::VarDictionary message;
875 message.Set(kType, kJSGoToPageType);
876 message.Set(kJSPageNumber, pp::Var(page));
877 PostMessage(message);
880 void OutOfProcessInstance::NavigateTo(const std::string& url,
881 bool open_in_new_tab) {
882 pp::VarDictionary message;
883 message.Set(kType, kJSNavigateType);
884 message.Set(kJSNavigateUrl, url);
885 message.Set(kJSNavigateNewTab, open_in_new_tab);
886 PostMessage(message);
889 void OutOfProcessInstance::UpdateCursor(PP_CursorType_Dev cursor) {
890 if (cursor == cursor_)
891 return;
892 cursor_ = cursor;
894 const PPB_CursorControl_Dev* cursor_interface =
895 reinterpret_cast<const PPB_CursorControl_Dev*>(
896 pp::Module::Get()->GetBrowserInterface(PPB_CURSOR_CONTROL_DEV_INTERFACE));
897 if (!cursor_interface) {
898 NOTREACHED();
899 return;
902 cursor_interface->SetCursor(
903 pp_instance(), cursor_, pp::ImageData().pp_resource(), nullptr);
906 void OutOfProcessInstance::UpdateTickMarks(
907 const std::vector<pp::Rect>& tickmarks) {
908 float inverse_scale = 1.0f / device_scale_;
909 std::vector<pp::Rect> scaled_tickmarks = tickmarks;
910 for (size_t i = 0; i < scaled_tickmarks.size(); i++)
911 ScaleRect(inverse_scale, &scaled_tickmarks[i]);
912 tickmarks_ = scaled_tickmarks;
915 void OutOfProcessInstance::NotifyNumberOfFindResultsChanged(int total,
916 bool final_result) {
917 // We don't want to spam the renderer with too many updates to the number of
918 // find results. Don't send an update if we sent one too recently. If it's the
919 // final update, we always send it though.
920 if (final_result) {
921 NumberOfFindResultsChanged(total, final_result);
922 SetTickmarks(tickmarks_);
923 return;
926 if (recently_sent_find_update_)
927 return;
929 NumberOfFindResultsChanged(total, final_result);
930 SetTickmarks(tickmarks_);
931 recently_sent_find_update_ = true;
932 pp::CompletionCallback callback =
933 timer_factory_.NewCallback(
934 &OutOfProcessInstance::ResetRecentlySentFindUpdate);
935 pp::Module::Get()->core()->CallOnMainThread(kFindResultCooldownMs,
936 callback, 0);
939 void OutOfProcessInstance::NotifySelectedFindResultChanged(
940 int current_find_index) {
941 DCHECK_GE(current_find_index, 0);
942 SelectedFindResultChanged(current_find_index);
945 void OutOfProcessInstance::GetDocumentPassword(
946 pp::CompletionCallbackWithOutput<pp::Var> callback) {
947 if (password_callback_) {
948 NOTREACHED();
949 return;
952 password_callback_.reset(
953 new pp::CompletionCallbackWithOutput<pp::Var>(callback));
954 pp::VarDictionary message;
955 message.Set(pp::Var(kType), pp::Var(kJSGetPasswordType));
956 PostMessage(message);
959 void OutOfProcessInstance::Alert(const std::string& message) {
960 ModalDialog(this, "alert", message, std::string());
963 bool OutOfProcessInstance::Confirm(const std::string& message) {
964 pp::Var result = ModalDialog(this, "confirm", message, std::string());
965 return result.is_bool() ? result.AsBool() : false;
968 std::string OutOfProcessInstance::Prompt(const std::string& question,
969 const std::string& default_answer) {
970 pp::Var result = ModalDialog(this, "prompt", question, default_answer);
971 return result.is_string() ? result.AsString() : std::string();
974 std::string OutOfProcessInstance::GetURL() {
975 return url_;
978 void OutOfProcessInstance::Email(const std::string& to,
979 const std::string& cc,
980 const std::string& bcc,
981 const std::string& subject,
982 const std::string& body) {
983 pp::VarDictionary message;
984 message.Set(pp::Var(kType), pp::Var(kJSEmailType));
985 message.Set(pp::Var(kJSEmailTo),
986 pp::Var(net::EscapeUrlEncodedData(to, false)));
987 message.Set(pp::Var(kJSEmailCc),
988 pp::Var(net::EscapeUrlEncodedData(cc, false)));
989 message.Set(pp::Var(kJSEmailBcc),
990 pp::Var(net::EscapeUrlEncodedData(bcc, false)));
991 message.Set(pp::Var(kJSEmailSubject),
992 pp::Var(net::EscapeUrlEncodedData(subject, false)));
993 message.Set(pp::Var(kJSEmailBody),
994 pp::Var(net::EscapeUrlEncodedData(body, false)));
995 PostMessage(message);
998 void OutOfProcessInstance::Print() {
999 if (!engine_->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY) &&
1000 !engine_->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY)) {
1001 return;
1004 pp::CompletionCallback callback =
1005 print_callback_factory_.NewCallback(&OutOfProcessInstance::OnPrint);
1006 pp::Module::Get()->core()->CallOnMainThread(0, callback);
1009 void OutOfProcessInstance::OnPrint(int32_t) {
1010 pp::PDF::Print(this);
1013 void OutOfProcessInstance::SubmitForm(const std::string& url,
1014 const void* data,
1015 int length) {
1016 pp::URLRequestInfo request(this);
1017 request.SetURL(url);
1018 request.SetMethod("POST");
1019 request.AppendDataToBody(reinterpret_cast<const char*>(data), length);
1021 pp::CompletionCallback callback =
1022 form_factory_.NewCallback(&OutOfProcessInstance::FormDidOpen);
1023 form_loader_ = CreateURLLoaderInternal();
1024 int rv = form_loader_.Open(request, callback);
1025 if (rv != PP_OK_COMPLETIONPENDING)
1026 callback.Run(rv);
1029 void OutOfProcessInstance::FormDidOpen(int32_t result) {
1030 // TODO: inform the user of success/failure.
1031 if (result != PP_OK) {
1032 NOTREACHED();
1036 std::string OutOfProcessInstance::ShowFileSelectionDialog() {
1037 // Seems like very low priority to implement, since the pdf has no way to get
1038 // the file data anyways. Javascript doesn't let you do this synchronously.
1039 NOTREACHED();
1040 return std::string();
1043 pp::URLLoader OutOfProcessInstance::CreateURLLoader() {
1044 if (full_) {
1045 if (!did_call_start_loading_) {
1046 did_call_start_loading_ = true;
1047 pp::PDF::DidStartLoading(this);
1050 // Disable save and print until the document is fully loaded, since they
1051 // would generate an incomplete document. Need to do this each time we
1052 // call DidStartLoading since that resets the content restrictions.
1053 pp::PDF::SetContentRestriction(this, CONTENT_RESTRICTION_SAVE |
1054 CONTENT_RESTRICTION_PRINT);
1057 return CreateURLLoaderInternal();
1060 void OutOfProcessInstance::ScheduleCallback(int id, int delay_in_ms) {
1061 pp::CompletionCallback callback =
1062 timer_factory_.NewCallback(&OutOfProcessInstance::OnClientTimerFired);
1063 pp::Module::Get()->core()->CallOnMainThread(delay_in_ms, callback, id);
1066 void OutOfProcessInstance::SearchString(const base::char16* string,
1067 const base::char16* term,
1068 bool case_sensitive,
1069 std::vector<SearchStringResult>* results) {
1070 PP_PrivateFindResult* pp_results;
1071 int count = 0;
1072 pp::PDF::SearchString(
1073 this,
1074 reinterpret_cast<const unsigned short*>(string),
1075 reinterpret_cast<const unsigned short*>(term),
1076 case_sensitive,
1077 &pp_results,
1078 &count);
1080 results->resize(count);
1081 for (int i = 0; i < count; ++i) {
1082 (*results)[i].start_index = pp_results[i].start_index;
1083 (*results)[i].length = pp_results[i].length;
1086 pp::Memory_Dev memory;
1087 memory.MemFree(pp_results);
1090 void OutOfProcessInstance::DocumentPaintOccurred() {
1093 void OutOfProcessInstance::DocumentLoadComplete(int page_count) {
1094 // Clear focus state for OSK.
1095 FormTextFieldFocusChange(false);
1097 DCHECK(document_load_state_ == LOAD_STATE_LOADING);
1098 document_load_state_ = LOAD_STATE_COMPLETE;
1099 UserMetricsRecordAction("PDF.LoadSuccess");
1101 // Note: If we are in print preview mode the scroll location is retained
1102 // across document loads so we don't want to scroll again and override it.
1103 if (IsPrintPreview()) {
1104 AppendBlankPrintPreviewPages();
1105 OnGeometryChanged(0, 0);
1108 pp::VarDictionary metadata_message;
1109 metadata_message.Set(pp::Var(kType), pp::Var(kJSMetadataType));
1110 std::string title = engine_->GetMetadata("Title");
1111 if (!base::TrimWhitespace(base::UTF8ToUTF16(title), base::TRIM_ALL).empty())
1112 metadata_message.Set(pp::Var(kJSTitle), pp::Var(title));
1114 metadata_message.Set(pp::Var(kJSBookmarks), engine_->GetBookmarks());
1115 PostMessage(metadata_message);
1117 pp::VarDictionary progress_message;
1118 progress_message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1119 progress_message.Set(pp::Var(kJSProgressPercentage), pp::Var(100));
1120 PostMessage(progress_message);
1122 if (!full_)
1123 return;
1125 if (did_call_start_loading_) {
1126 pp::PDF::DidStopLoading(this);
1127 did_call_start_loading_ = false;
1130 int content_restrictions =
1131 CONTENT_RESTRICTION_CUT | CONTENT_RESTRICTION_PASTE;
1132 if (!engine_->HasPermission(PDFEngine::PERMISSION_COPY))
1133 content_restrictions |= CONTENT_RESTRICTION_COPY;
1135 if (!engine_->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY) &&
1136 !engine_->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY)) {
1137 content_restrictions |= CONTENT_RESTRICTION_PRINT;
1140 pp::PDF::SetContentRestriction(this, content_restrictions);
1142 uma_.HistogramCustomCounts("PDF.PageCount", page_count, 1, 1000000, 50);
1145 void OutOfProcessInstance::RotateClockwise() {
1146 engine_->RotateClockwise();
1149 void OutOfProcessInstance::RotateCounterclockwise() {
1150 engine_->RotateCounterclockwise();
1153 void OutOfProcessInstance::PreviewDocumentLoadComplete() {
1154 if (preview_document_load_state_ != LOAD_STATE_LOADING ||
1155 preview_pages_info_.empty()) {
1156 return;
1159 preview_document_load_state_ = LOAD_STATE_COMPLETE;
1161 int dest_page_index = preview_pages_info_.front().second;
1162 int src_page_index =
1163 ExtractPrintPreviewPageIndex(preview_pages_info_.front().first);
1164 if (src_page_index > 0 && dest_page_index > -1 && preview_engine_.get())
1165 engine_->AppendPage(preview_engine_.get(), dest_page_index);
1167 preview_pages_info_.pop();
1168 // |print_preview_page_count_| is not updated yet. Do not load any
1169 // other preview pages till we get this information.
1170 if (print_preview_page_count_ == 0)
1171 return;
1173 if (!preview_pages_info_.empty())
1174 LoadAvailablePreviewPage();
1177 void OutOfProcessInstance::DocumentLoadFailed() {
1178 DCHECK(document_load_state_ == LOAD_STATE_LOADING);
1179 UserMetricsRecordAction("PDF.LoadFailure");
1181 if (did_call_start_loading_) {
1182 pp::PDF::DidStopLoading(this);
1183 did_call_start_loading_ = false;
1186 document_load_state_ = LOAD_STATE_FAILED;
1187 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
1189 // Send a progress value of -1 to indicate a failure.
1190 pp::VarDictionary message;
1191 message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1192 message.Set(pp::Var(kJSProgressPercentage), pp::Var(-1));
1193 PostMessage(message);
1196 void OutOfProcessInstance::PreviewDocumentLoadFailed() {
1197 UserMetricsRecordAction("PDF.PreviewDocumentLoadFailure");
1198 if (preview_document_load_state_ != LOAD_STATE_LOADING ||
1199 preview_pages_info_.empty()) {
1200 return;
1203 preview_document_load_state_ = LOAD_STATE_FAILED;
1204 preview_pages_info_.pop();
1206 if (!preview_pages_info_.empty())
1207 LoadAvailablePreviewPage();
1210 pp::Instance* OutOfProcessInstance::GetPluginInstance() {
1211 return this;
1214 void OutOfProcessInstance::DocumentHasUnsupportedFeature(
1215 const std::string& feature) {
1216 std::string metric("PDF_Unsupported_");
1217 metric += feature;
1218 if (!unsupported_features_reported_.count(metric)) {
1219 unsupported_features_reported_.insert(metric);
1220 UserMetricsRecordAction(metric);
1223 // Since we use an info bar, only do this for full frame plugins..
1224 if (!full_)
1225 return;
1227 if (told_browser_about_unsupported_feature_)
1228 return;
1229 told_browser_about_unsupported_feature_ = true;
1231 pp::PDF::HasUnsupportedFeature(this);
1234 void OutOfProcessInstance::DocumentLoadProgress(uint32 available,
1235 uint32 doc_size) {
1236 double progress = 0.0;
1237 if (doc_size == 0) {
1238 // Document size is unknown. Use heuristics.
1239 // We'll make progress logarithmic from 0 to 100M.
1240 static const double kFactor = log(100000000.0) / 100.0;
1241 if (available > 0) {
1242 progress = log(static_cast<double>(available)) / kFactor;
1243 if (progress > 100.0)
1244 progress = 100.0;
1246 } else {
1247 progress = 100.0 * static_cast<double>(available) / doc_size;
1250 // We send 100% load progress in DocumentLoadComplete.
1251 if (progress >= 100)
1252 return;
1254 // Avoid sending too many progress messages over PostMessage.
1255 if (progress > last_progress_sent_ + 1) {
1256 last_progress_sent_ = progress;
1257 pp::VarDictionary message;
1258 message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1259 message.Set(pp::Var(kJSProgressPercentage), pp::Var(progress));
1260 PostMessage(message);
1264 void OutOfProcessInstance::FormTextFieldFocusChange(bool in_focus) {
1265 if (!text_input_.get())
1266 return;
1267 if (in_focus)
1268 text_input_->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_TEXT);
1269 else
1270 text_input_->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_NONE);
1273 void OutOfProcessInstance::ResetRecentlySentFindUpdate(int32_t /* unused */) {
1274 recently_sent_find_update_ = false;
1277 void OutOfProcessInstance::OnGeometryChanged(double old_zoom,
1278 float old_device_scale) {
1279 if (zoom_ != old_zoom || device_scale_ != old_device_scale)
1280 engine_->ZoomUpdated(zoom_ * device_scale_);
1282 available_area_ = pp::Rect(plugin_size_);
1283 int doc_width = GetDocumentPixelWidth();
1284 if (doc_width < available_area_.width()) {
1285 available_area_.Offset((available_area_.width() - doc_width) / 2, 0);
1286 available_area_.set_width(doc_width);
1288 int bottom_of_document =
1289 GetDocumentPixelHeight() + (top_toolbar_height_ * device_scale_);
1290 if (bottom_of_document < available_area_.height())
1291 available_area_.set_height(bottom_of_document);
1293 CalculateBackgroundParts();
1294 engine_->PageOffsetUpdated(available_area_.point());
1295 engine_->PluginSizeUpdated(available_area_.size());
1297 if (!document_size_.GetArea())
1298 return;
1299 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
1302 void OutOfProcessInstance::LoadUrl(const std::string& url) {
1303 LoadUrlInternal(url, &embed_loader_, &OutOfProcessInstance::DidOpen);
1306 void OutOfProcessInstance::LoadPreviewUrl(const std::string& url) {
1307 LoadUrlInternal(url, &embed_preview_loader_,
1308 &OutOfProcessInstance::DidOpenPreview);
1311 void OutOfProcessInstance::LoadUrlInternal(
1312 const std::string& url,
1313 pp::URLLoader* loader,
1314 void (OutOfProcessInstance::* method)(int32_t)) {
1315 pp::URLRequestInfo request(this);
1316 request.SetURL(url);
1317 request.SetMethod("GET");
1319 *loader = CreateURLLoaderInternal();
1320 pp::CompletionCallback callback = loader_factory_.NewCallback(method);
1321 int rv = loader->Open(request, callback);
1322 if (rv != PP_OK_COMPLETIONPENDING)
1323 callback.Run(rv);
1326 pp::URLLoader OutOfProcessInstance::CreateURLLoaderInternal() {
1327 pp::URLLoader loader(this);
1329 const PPB_URLLoaderTrusted* trusted_interface =
1330 reinterpret_cast<const PPB_URLLoaderTrusted*>(
1331 pp::Module::Get()->GetBrowserInterface(
1332 PPB_URLLOADERTRUSTED_INTERFACE));
1333 if (trusted_interface)
1334 trusted_interface->GrantUniversalAccess(loader.pp_resource());
1335 return loader;
1338 void OutOfProcessInstance::SetZoom(double scale) {
1339 double old_zoom = zoom_;
1340 zoom_ = scale;
1341 OnGeometryChanged(old_zoom, device_scale_);
1344 void OutOfProcessInstance::AppendBlankPrintPreviewPages() {
1345 if (print_preview_page_count_ == 0)
1346 return;
1347 engine_->AppendBlankPages(print_preview_page_count_);
1348 if (!preview_pages_info_.empty())
1349 LoadAvailablePreviewPage();
1352 bool OutOfProcessInstance::IsPrintPreview() {
1353 return IsPrintPreviewUrl(url_);
1356 uint32 OutOfProcessInstance::GetBackgroundColor() {
1357 return background_color_;
1360 void OutOfProcessInstance::IsSelectingChanged(bool is_selecting) {
1361 pp::VarDictionary message;
1362 message.Set(kType, kJSSetIsSelectingType);
1363 message.Set(kJSIsSelecting, pp::Var(is_selecting));
1364 PostMessage(message);
1367 void OutOfProcessInstance::ProcessPreviewPageInfo(const std::string& url,
1368 int dst_page_index) {
1369 if (!IsPrintPreview())
1370 return;
1372 int src_page_index = ExtractPrintPreviewPageIndex(url);
1373 if (src_page_index < 1)
1374 return;
1376 preview_pages_info_.push(std::make_pair(url, dst_page_index));
1377 LoadAvailablePreviewPage();
1380 void OutOfProcessInstance::LoadAvailablePreviewPage() {
1381 if (preview_pages_info_.empty() ||
1382 document_load_state_ != LOAD_STATE_COMPLETE) {
1383 return;
1386 std::string url = preview_pages_info_.front().first;
1387 int dst_page_index = preview_pages_info_.front().second;
1388 int src_page_index = ExtractPrintPreviewPageIndex(url);
1389 if (src_page_index < 1 ||
1390 dst_page_index >= print_preview_page_count_ ||
1391 preview_document_load_state_ == LOAD_STATE_LOADING) {
1392 return;
1395 preview_document_load_state_ = LOAD_STATE_LOADING;
1396 LoadPreviewUrl(url);
1399 void OutOfProcessInstance::UserMetricsRecordAction(
1400 const std::string& action) {
1401 // TODO(raymes): Move this function to PPB_UMA_Private.
1402 pp::PDF::UserMetricsRecordAction(this, pp::Var(action));
1405 pp::FloatPoint OutOfProcessInstance::BoundScrollOffsetToDocument(
1406 const pp::FloatPoint& scroll_offset) {
1407 float max_x = document_size_.width() * zoom_ - plugin_dip_size_.width();
1408 float x = std::max(std::min(scroll_offset.x(), max_x), 0.0f);
1409 float min_y = -top_toolbar_height_;
1410 float max_y = document_size_.height() * zoom_ - plugin_dip_size_.height();
1411 float y = std::max(std::min(scroll_offset.y(), max_y), min_y);
1412 return pp::FloatPoint(x, y);
1415 } // namespace chrome_pdf