Gray horizontal keyboard accessory
[chromium-blink-merge.git] / pdf / out_of_process_instance.cc
blob1d782beb1b104c498a2dab0b4fb6869ed57e6f99
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;
210 base::SplitString(src_url.substr(strlen(kChromePrint)), '/', &url_substr);
211 if (url_substr.size() != 3)
212 return -1;
214 if (url_substr[2] != "print.pdf")
215 return -1;
217 int page_index = 0;
218 if (!base::StringToInt(url_substr[1], &page_index))
219 return -1;
220 return page_index;
223 bool IsPrintPreviewUrl(const std::string& url) {
224 return url.substr(0, strlen(kChromePrint)) == kChromePrint;
227 void ScalePoint(float scale, pp::Point* point) {
228 point->set_x(static_cast<int>(point->x() * scale));
229 point->set_y(static_cast<int>(point->y() * scale));
232 void ScaleRect(float scale, pp::Rect* rect) {
233 int left = static_cast<int>(floorf(rect->x() * scale));
234 int top = static_cast<int>(floorf(rect->y() * scale));
235 int right = static_cast<int>(ceilf((rect->x() + rect->width()) * scale));
236 int bottom = static_cast<int>(ceilf((rect->y() + rect->height()) * scale));
237 rect->SetRect(left, top, right - left, bottom - top);
240 // TODO(raymes): Remove this dependency on VarPrivate/InstancePrivate. It's
241 // needed right now to do a synchronous call to JavaScript, but we could easily
242 // replace this with a custom PPB_PDF function.
243 pp::Var ModalDialog(const pp::Instance* instance,
244 const std::string& type,
245 const std::string& message,
246 const std::string& default_answer) {
247 const PPB_Instance_Private* interface =
248 reinterpret_cast<const PPB_Instance_Private*>(
249 pp::Module::Get()->GetBrowserInterface(
250 PPB_INSTANCE_PRIVATE_INTERFACE));
251 pp::VarPrivate window(pp::PASS_REF,
252 interface->GetWindowObject(instance->pp_instance()));
253 if (default_answer.empty())
254 return window.Call(type, message);
255 else
256 return window.Call(type, message, default_answer);
259 } // namespace
261 OutOfProcessInstance::OutOfProcessInstance(PP_Instance instance)
262 : pp::Instance(instance),
263 pp::Find_Private(this),
264 pp::Printing_Dev(this),
265 cursor_(PP_CURSORTYPE_POINTER),
266 zoom_(1.0),
267 device_scale_(1.0),
268 full_(false),
269 paint_manager_(this, this, true),
270 first_paint_(true),
271 document_load_state_(LOAD_STATE_LOADING),
272 preview_document_load_state_(LOAD_STATE_COMPLETE),
273 uma_(this),
274 told_browser_about_unsupported_feature_(false),
275 print_preview_page_count_(0),
276 last_progress_sent_(0),
277 recently_sent_find_update_(false),
278 received_viewport_message_(false),
279 did_call_start_loading_(false),
280 stop_scrolling_(false),
281 background_color_(kBackgroundColor),
282 top_toolbar_height_(0) {
283 loader_factory_.Initialize(this);
284 timer_factory_.Initialize(this);
285 form_factory_.Initialize(this);
286 print_callback_factory_.Initialize(this);
287 engine_.reset(PDFEngine::Create(this));
288 pp::Module::Get()->AddPluginInterface(kPPPPdfInterface, &ppp_private);
289 AddPerInstanceObject(kPPPPdfInterface, this);
291 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_MOUSE);
292 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_KEYBOARD);
293 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_TOUCH);
296 OutOfProcessInstance::~OutOfProcessInstance() {
297 RemovePerInstanceObject(kPPPPdfInterface, this);
298 // Explicitly reset the PDFEngine during destruction as it may call back into
299 // this object.
300 engine_.reset();
303 bool OutOfProcessInstance::Init(uint32_t argc,
304 const char* argn[],
305 const char* argv[]) {
306 // Check if the PDF is being loaded in the PDF chrome extension. We only allow
307 // the plugin to be put into "full frame" mode when it is being loaded in the
308 // extension because this enables some features that we don't want pages
309 // abusing outside of the extension.
310 pp::Var document_url_var = pp::URLUtil_Dev::Get()->GetDocumentURL(this);
311 std::string document_url = document_url_var.is_string() ?
312 document_url_var.AsString() : std::string();
313 std::string extension_url = std::string(kChromeExtension);
314 bool in_extension =
315 !document_url.compare(0, extension_url.size(), extension_url);
317 if (in_extension) {
318 // Check if the plugin is full frame. This is passed in from JS.
319 for (uint32_t i = 0; i < argc; ++i) {
320 if (strcmp(argn[i], "full-frame") == 0) {
321 full_ = true;
322 break;
327 // Only allow the plugin to handle find requests if it is full frame.
328 if (full_)
329 SetPluginToHandleFindRequests();
331 // Send translated strings to the extension where they will be displayed.
332 // TODO(raymes): It would be better to get these in the extension directly
333 // through an API but no such API currently exists.
334 pp::VarDictionary translated_strings;
335 translated_strings.Set(kType, kJSSetTranslatedStringsType);
336 translated_strings.Set(kJSGetPasswordString,
337 GetLocalizedString(PP_RESOURCESTRING_PDFGETPASSWORD));
338 translated_strings.Set(kJSLoadingString,
339 GetLocalizedString(PP_RESOURCESTRING_PDFLOADING));
340 translated_strings.Set(kJSLoadFailedString,
341 GetLocalizedString(PP_RESOURCESTRING_PDFLOAD_FAILED));
342 PostMessage(translated_strings);
344 text_input_.reset(new pp::TextInput_Dev(this));
346 const char* stream_url = nullptr;
347 const char* original_url = nullptr;
348 const char* headers = nullptr;
349 bool is_material = false;
350 for (uint32_t i = 0; i < argc; ++i) {
351 if (strcmp(argn[i], "src") == 0)
352 original_url = argv[i];
353 else if (strcmp(argn[i], "stream-url") == 0)
354 stream_url = argv[i];
355 else if (strcmp(argn[i], "headers") == 0)
356 headers = argv[i];
357 else if (strcmp(argn[i], "is-material") == 0)
358 is_material = true;
359 else if (strcmp(argn[i], "top-toolbar-height") == 0)
360 base::StringToInt(argv[i], &top_toolbar_height_);
363 if (is_material)
364 background_color_ = kBackgroundColorMaterial;
365 else
366 background_color_ = kBackgroundColor;
368 if (!original_url)
369 return false;
371 if (!stream_url)
372 stream_url = original_url;
374 // If we're in print preview mode we don't need to load the document yet.
375 // A |kJSResetPrintPreviewModeType| message will be sent to the plugin letting
376 // it know the url to load. By not loading here we avoid loading the same
377 // document twice.
378 if (IsPrintPreviewUrl(original_url))
379 return true;
381 LoadUrl(stream_url);
382 url_ = original_url;
383 return engine_->New(original_url, headers);
386 void OutOfProcessInstance::HandleMessage(const pp::Var& message) {
387 pp::VarDictionary dict(message);
388 if (!dict.Get(kType).is_string()) {
389 NOTREACHED();
390 return;
393 std::string type = dict.Get(kType).AsString();
395 if (type == kJSViewportType &&
396 dict.Get(pp::Var(kJSXOffset)).is_number() &&
397 dict.Get(pp::Var(kJSYOffset)).is_number() &&
398 dict.Get(pp::Var(kJSZoom)).is_number()) {
399 received_viewport_message_ = true;
400 stop_scrolling_ = false;
401 double zoom = dict.Get(pp::Var(kJSZoom)).AsDouble();
402 pp::FloatPoint scroll_offset(dict.Get(pp::Var(kJSXOffset)).AsDouble(),
403 dict.Get(pp::Var(kJSYOffset)).AsDouble());
405 // Bound the input parameters.
406 zoom = std::max(kMinZoom, zoom);
407 SetZoom(zoom);
408 scroll_offset = BoundScrollOffsetToDocument(scroll_offset);
409 engine_->ScrolledToXPosition(scroll_offset.x() * device_scale_);
410 engine_->ScrolledToYPosition(scroll_offset.y() * device_scale_);
411 } else if (type == kJSGetPasswordCompleteType &&
412 dict.Get(pp::Var(kJSPassword)).is_string()) {
413 if (password_callback_) {
414 pp::CompletionCallbackWithOutput<pp::Var> callback = *password_callback_;
415 password_callback_.reset();
416 *callback.output() = dict.Get(pp::Var(kJSPassword)).pp_var();
417 callback.Run(PP_OK);
418 } else {
419 NOTREACHED();
421 } else if (type == kJSPrintType) {
422 Print();
423 } else if (type == kJSSaveType) {
424 pp::PDF::SaveAs(this);
425 } else if (type == kJSRotateClockwiseType) {
426 RotateClockwise();
427 } else if (type == kJSRotateCounterclockwiseType) {
428 RotateCounterclockwise();
429 } else if (type == kJSSelectAllType) {
430 engine_->SelectAll();
431 } else if (type == kJSResetPrintPreviewModeType &&
432 dict.Get(pp::Var(kJSPrintPreviewUrl)).is_string() &&
433 dict.Get(pp::Var(kJSPrintPreviewGrayscale)).is_bool() &&
434 dict.Get(pp::Var(kJSPrintPreviewPageCount)).is_int()) {
435 url_ = dict.Get(pp::Var(kJSPrintPreviewUrl)).AsString();
436 preview_pages_info_ = std::queue<PreviewPageInfo>();
437 preview_document_load_state_ = LOAD_STATE_COMPLETE;
438 document_load_state_ = LOAD_STATE_LOADING;
439 LoadUrl(url_);
440 preview_engine_.reset();
441 engine_.reset(PDFEngine::Create(this));
442 engine_->SetGrayscale(dict.Get(pp::Var(kJSPrintPreviewGrayscale)).AsBool());
443 engine_->New(url_.c_str(), nullptr /* empty header */);
445 print_preview_page_count_ =
446 std::max(dict.Get(pp::Var(kJSPrintPreviewPageCount)).AsInt(), 0);
448 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
449 } else if (type == kJSLoadPreviewPageType &&
450 dict.Get(pp::Var(kJSPreviewPageUrl)).is_string() &&
451 dict.Get(pp::Var(kJSPreviewPageIndex)).is_int()) {
452 ProcessPreviewPageInfo(dict.Get(pp::Var(kJSPreviewPageUrl)).AsString(),
453 dict.Get(pp::Var(kJSPreviewPageIndex)).AsInt());
454 } else if (type == kJSGetAccessibilityJSONType) {
455 pp::VarDictionary reply;
456 reply.Set(pp::Var(kType), pp::Var(kJSGetAccessibilityJSONReplyType));
457 if (dict.Get(pp::Var(kJSAccessibilityPageNumber)).is_int()) {
458 int page = dict.Get(pp::Var(kJSAccessibilityPageNumber)).AsInt();
459 reply.Set(pp::Var(kJSAccessibilityJSON),
460 pp::Var(engine_->GetPageAsJSON(page)));
461 } else {
462 base::DictionaryValue node;
463 node.SetInteger(kAccessibleNumberOfPages, engine_->GetNumberOfPages());
464 node.SetBoolean(kAccessibleLoaded,
465 document_load_state_ != LOAD_STATE_LOADING);
466 bool has_permissions =
467 engine_->HasPermission(PDFEngine::PERMISSION_COPY) ||
468 engine_->HasPermission(PDFEngine::PERMISSION_COPY_ACCESSIBLE);
469 node.SetBoolean(kAccessibleCopyable, has_permissions);
470 std::string json;
471 base::JSONWriter::Write(node, &json);
472 reply.Set(pp::Var(kJSAccessibilityJSON), pp::Var(json));
474 PostMessage(reply);
475 } else if (type == kJSStopScrollingType) {
476 stop_scrolling_ = true;
477 } else if (type == kJSGetSelectedTextType) {
478 std::string selected_text = engine_->GetSelectedText();
479 // Always return unix newlines to JS.
480 base::ReplaceChars(selected_text, "\r", std::string(), &selected_text);
481 pp::VarDictionary reply;
482 reply.Set(pp::Var(kType), pp::Var(kJSGetSelectedTextReplyType));
483 reply.Set(pp::Var(kJSSelectedText), selected_text);
484 PostMessage(reply);
485 } else if (type == KJSGetNamedDestinationType &&
486 dict.Get(pp::Var(KJSGetNamedDestination)).is_string()) {
487 int page_number = engine_->GetNamedDestinationPage(
488 dict.Get(pp::Var(KJSGetNamedDestination)).AsString());
489 pp::VarDictionary reply;
490 reply.Set(pp::Var(kType), pp::Var(kJSGetNamedDestinationReplyType));
491 if (page_number >= 0)
492 reply.Set(pp::Var(kJSNamedDestinationPageNumber), page_number);
493 PostMessage(reply);
494 } else {
495 NOTREACHED();
499 bool OutOfProcessInstance::HandleInputEvent(
500 const pp::InputEvent& event) {
501 // To simplify things, convert the event into device coordinates if it is
502 // a mouse event.
503 pp::InputEvent event_device_res(event);
505 pp::MouseInputEvent mouse_event(event);
506 if (!mouse_event.is_null()) {
507 pp::Point point = mouse_event.GetPosition();
508 pp::Point movement = mouse_event.GetMovement();
509 ScalePoint(device_scale_, &point);
510 ScalePoint(device_scale_, &movement);
511 mouse_event = pp::MouseInputEvent(
512 this,
513 event.GetType(),
514 event.GetTimeStamp(),
515 event.GetModifiers(),
516 mouse_event.GetButton(),
517 point,
518 mouse_event.GetClickCount(),
519 movement);
520 event_device_res = mouse_event;
524 pp::InputEvent offset_event(event_device_res);
525 switch (offset_event.GetType()) {
526 case PP_INPUTEVENT_TYPE_MOUSEDOWN:
527 case PP_INPUTEVENT_TYPE_MOUSEUP:
528 case PP_INPUTEVENT_TYPE_MOUSEMOVE:
529 case PP_INPUTEVENT_TYPE_MOUSEENTER:
530 case PP_INPUTEVENT_TYPE_MOUSELEAVE: {
531 pp::MouseInputEvent mouse_event(event_device_res);
532 pp::MouseInputEvent mouse_event_dip(event);
533 pp::Point point = mouse_event.GetPosition();
534 point.set_x(point.x() - available_area_.x());
535 offset_event = pp::MouseInputEvent(
536 this,
537 event.GetType(),
538 event.GetTimeStamp(),
539 event.GetModifiers(),
540 mouse_event.GetButton(),
541 point,
542 mouse_event.GetClickCount(),
543 mouse_event.GetMovement());
544 break;
546 default:
547 break;
549 if (engine_->HandleEvent(offset_event))
550 return true;
552 // Middle click is used for scrolling and is handled by the container page.
553 pp::MouseInputEvent mouse_event(event_device_res);
554 if (!mouse_event.is_null() &&
555 mouse_event.GetButton() == PP_INPUTEVENT_MOUSEBUTTON_MIDDLE) {
556 return false;
559 // Return true for unhandled clicks so the plugin takes focus.
560 return (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN);
563 void OutOfProcessInstance::DidChangeView(const pp::View& view) {
564 pp::Rect view_rect(view.GetRect());
565 float old_device_scale = device_scale_;
566 float device_scale = view.GetDeviceScale();
567 pp::Size view_device_size(view_rect.width() * device_scale,
568 view_rect.height() * device_scale);
570 if (view_device_size != plugin_size_ || device_scale != device_scale_) {
571 device_scale_ = device_scale;
572 plugin_dip_size_ = view_rect.size();
573 plugin_size_ = view_device_size;
575 paint_manager_.SetSize(view_device_size, device_scale_);
577 pp::Size new_image_data_size = PaintManager::GetNewContextSize(
578 image_data_.size(),
579 plugin_size_);
580 if (new_image_data_size != image_data_.size()) {
581 image_data_ = pp::ImageData(this,
582 PP_IMAGEDATAFORMAT_BGRA_PREMUL,
583 new_image_data_size,
584 false);
585 first_paint_ = true;
588 if (image_data_.is_null()) {
589 DCHECK(plugin_size_.IsEmpty());
590 return;
593 OnGeometryChanged(zoom_, old_device_scale);
596 if (!stop_scrolling_) {
597 pp::Point scroll_offset(view.GetScrollOffset());
598 // Because view messages come from the DOM, the coordinates of the viewport
599 // are 0-based (i.e. they do not correspond to the viewport's coordinates in
600 // JS), so we need to subtract the toolbar height to convert them into
601 // viewport coordinates.
602 pp::FloatPoint scroll_offset_float(scroll_offset.x(),
603 scroll_offset.y() - top_toolbar_height_);
604 scroll_offset_float = BoundScrollOffsetToDocument(scroll_offset_float);
605 engine_->ScrolledToXPosition(scroll_offset_float.x() * device_scale_);
606 engine_->ScrolledToYPosition(scroll_offset_float.y() * device_scale_);
610 void OutOfProcessInstance::GetPrintPresetOptionsFromDocument(
611 PP_PdfPrintPresetOptions_Dev* options) {
612 options->is_scaling_disabled = PP_FromBool(IsPrintScalingDisabled());
613 options->duplex =
614 static_cast<PP_PrivateDuplexMode_Dev>(engine_->GetDuplexType());
615 options->copies = engine_->GetCopiesToPrint();
616 pp::Size uniform_page_size;
617 options->is_page_size_uniform =
618 PP_FromBool(engine_->GetPageSizeAndUniformity(&uniform_page_size));
619 options->uniform_page_size = uniform_page_size;
622 pp::Var OutOfProcessInstance::GetLinkAtPosition(
623 const pp::Point& point) {
624 pp::Point offset_point(point);
625 ScalePoint(device_scale_, &offset_point);
626 offset_point.set_x(offset_point.x() - available_area_.x());
627 return engine_->GetLinkAtPosition(offset_point);
630 uint32_t OutOfProcessInstance::QuerySupportedPrintOutputFormats() {
631 return engine_->QuerySupportedPrintOutputFormats();
634 int32_t OutOfProcessInstance::PrintBegin(
635 const PP_PrintSettings_Dev& print_settings) {
636 // For us num_pages is always equal to the number of pages in the PDF
637 // document irrespective of the printable area.
638 int32_t ret = engine_->GetNumberOfPages();
639 if (!ret)
640 return 0;
642 uint32_t supported_formats = engine_->QuerySupportedPrintOutputFormats();
643 if ((print_settings.format & supported_formats) == 0)
644 return 0;
646 print_settings_.is_printing = true;
647 print_settings_.pepper_print_settings = print_settings;
648 engine_->PrintBegin();
649 return ret;
652 pp::Resource OutOfProcessInstance::PrintPages(
653 const PP_PrintPageNumberRange_Dev* page_ranges,
654 uint32_t page_range_count) {
655 if (!print_settings_.is_printing)
656 return pp::Resource();
658 print_settings_.print_pages_called_ = true;
659 return engine_->PrintPages(page_ranges, page_range_count,
660 print_settings_.pepper_print_settings);
663 void OutOfProcessInstance::PrintEnd() {
664 if (print_settings_.print_pages_called_)
665 UserMetricsRecordAction("PDF.PrintPage");
666 print_settings_.Clear();
667 engine_->PrintEnd();
670 bool OutOfProcessInstance::IsPrintScalingDisabled() {
671 return !engine_->GetPrintScaling();
674 bool OutOfProcessInstance::StartFind(const std::string& text,
675 bool case_sensitive) {
676 engine_->StartFind(text.c_str(), case_sensitive);
677 return true;
680 void OutOfProcessInstance::SelectFindResult(bool forward) {
681 engine_->SelectFindResult(forward);
684 void OutOfProcessInstance::StopFind() {
685 engine_->StopFind();
686 tickmarks_.clear();
687 SetTickmarks(tickmarks_);
690 void OutOfProcessInstance::OnPaint(
691 const std::vector<pp::Rect>& paint_rects,
692 std::vector<PaintManager::ReadyRect>* ready,
693 std::vector<pp::Rect>* pending) {
694 if (image_data_.is_null()) {
695 DCHECK(plugin_size_.IsEmpty());
696 return;
698 if (first_paint_) {
699 first_paint_ = false;
700 pp::Rect rect = pp::Rect(pp::Point(), image_data_.size());
701 FillRect(rect, background_color_);
702 ready->push_back(PaintManager::ReadyRect(rect, image_data_, true));
705 if (!received_viewport_message_)
706 return;
708 engine_->PrePaint();
710 for (size_t i = 0; i < paint_rects.size(); i++) {
711 // Intersect with plugin area since there could be pending invalidates from
712 // when the plugin area was larger.
713 pp::Rect rect =
714 paint_rects[i].Intersect(pp::Rect(pp::Point(), plugin_size_));
715 if (rect.IsEmpty())
716 continue;
718 pp::Rect pdf_rect = available_area_.Intersect(rect);
719 if (!pdf_rect.IsEmpty()) {
720 pdf_rect.Offset(available_area_.x() * -1, 0);
722 std::vector<pp::Rect> pdf_ready;
723 std::vector<pp::Rect> pdf_pending;
724 engine_->Paint(pdf_rect, &image_data_, &pdf_ready, &pdf_pending);
725 for (size_t j = 0; j < pdf_ready.size(); ++j) {
726 pdf_ready[j].Offset(available_area_.point());
727 ready->push_back(
728 PaintManager::ReadyRect(pdf_ready[j], image_data_, false));
730 for (size_t j = 0; j < pdf_pending.size(); ++j) {
731 pdf_pending[j].Offset(available_area_.point());
732 pending->push_back(pdf_pending[j]);
736 // Ensure the region above the first page (if any) is filled;
737 int32_t first_page_ypos = engine_->GetNumberOfPages() == 0 ?
738 0 : engine_->GetPageScreenRect(0).y();
739 if (rect.y() < first_page_ypos) {
740 pp::Rect region = rect.Intersect(pp::Rect(
741 pp::Point(), pp::Size(plugin_size_.width(), first_page_ypos)));
742 ready->push_back(PaintManager::ReadyRect(region, image_data_, false));
743 FillRect(region, background_color_);
746 for (size_t j = 0; j < background_parts_.size(); ++j) {
747 pp::Rect intersection = background_parts_[j].location.Intersect(rect);
748 if (!intersection.IsEmpty()) {
749 FillRect(intersection, background_parts_[j].color);
750 ready->push_back(
751 PaintManager::ReadyRect(intersection, image_data_, false));
756 engine_->PostPaint();
759 void OutOfProcessInstance::DidOpen(int32_t result) {
760 if (result == PP_OK) {
761 if (!engine_->HandleDocumentLoad(embed_loader_)) {
762 document_load_state_ = LOAD_STATE_LOADING;
763 DocumentLoadFailed();
765 } else if (result != PP_ERROR_ABORTED) { // Can happen in tests.
766 NOTREACHED();
767 DocumentLoadFailed();
770 // If it's a progressive load, cancel the stream URL request so that requests
771 // can be made on the original URL.
772 // TODO(raymes): Make this clearer once the in-process plugin is deleted.
773 if (engine_->IsProgressiveLoad()) {
774 pp::VarDictionary message;
775 message.Set(kType, kJSCancelStreamUrlType);
776 PostMessage(message);
780 void OutOfProcessInstance::DidOpenPreview(int32_t result) {
781 if (result == PP_OK) {
782 preview_engine_.reset(PDFEngine::Create(new PreviewModeClient(this)));
783 preview_engine_->HandleDocumentLoad(embed_preview_loader_);
784 } else {
785 NOTREACHED();
789 void OutOfProcessInstance::OnClientTimerFired(int32_t id) {
790 engine_->OnCallback(id);
793 void OutOfProcessInstance::CalculateBackgroundParts() {
794 background_parts_.clear();
795 int left_width = available_area_.x();
796 int right_start = available_area_.right();
797 int right_width = abs(plugin_size_.width() - available_area_.right());
798 int bottom = std::min(available_area_.bottom(), plugin_size_.height());
800 // Add the left, right, and bottom rectangles. Note: we assume only
801 // horizontal centering.
802 BackgroundPart part = {
803 pp::Rect(0, 0, left_width, bottom),
804 background_color_
806 if (!part.location.IsEmpty())
807 background_parts_.push_back(part);
808 part.location = pp::Rect(right_start, 0, right_width, bottom);
809 if (!part.location.IsEmpty())
810 background_parts_.push_back(part);
811 part.location = pp::Rect(
812 0, bottom, plugin_size_.width(), plugin_size_.height() - bottom);
813 if (!part.location.IsEmpty())
814 background_parts_.push_back(part);
817 int OutOfProcessInstance::GetDocumentPixelWidth() const {
818 return static_cast<int>(ceil(document_size_.width() * zoom_ * device_scale_));
821 int OutOfProcessInstance::GetDocumentPixelHeight() const {
822 return static_cast<int>(
823 ceil(document_size_.height() * zoom_ * device_scale_));
826 void OutOfProcessInstance::FillRect(const pp::Rect& rect, uint32 color) {
827 DCHECK(!image_data_.is_null() || rect.IsEmpty());
828 uint32* buffer_start = static_cast<uint32*>(image_data_.data());
829 int stride = image_data_.stride();
830 uint32* ptr = buffer_start + rect.y() * stride / 4 + rect.x();
831 int height = rect.height();
832 int width = rect.width();
833 for (int y = 0; y < height; ++y) {
834 for (int x = 0; x < width; ++x)
835 *(ptr + x) = color;
836 ptr += stride /4;
840 void OutOfProcessInstance::DocumentSizeUpdated(const pp::Size& size) {
841 document_size_ = size;
843 pp::VarDictionary dimensions;
844 dimensions.Set(kType, kJSDocumentDimensionsType);
845 dimensions.Set(kJSDocumentWidth, pp::Var(document_size_.width()));
846 dimensions.Set(kJSDocumentHeight, pp::Var(document_size_.height()));
847 pp::VarArray page_dimensions_array;
848 int num_pages = engine_->GetNumberOfPages();
849 for (int i = 0; i < num_pages; ++i) {
850 pp::Rect page_rect = engine_->GetPageRect(i);
851 pp::VarDictionary page_dimensions;
852 page_dimensions.Set(kJSPageX, pp::Var(page_rect.x()));
853 page_dimensions.Set(kJSPageY, pp::Var(page_rect.y()));
854 page_dimensions.Set(kJSPageWidth, pp::Var(page_rect.width()));
855 page_dimensions.Set(kJSPageHeight, pp::Var(page_rect.height()));
856 page_dimensions_array.Set(i, page_dimensions);
858 dimensions.Set(kJSPageDimensions, page_dimensions_array);
859 PostMessage(dimensions);
861 OnGeometryChanged(zoom_, device_scale_);
864 void OutOfProcessInstance::Invalidate(const pp::Rect& rect) {
865 pp::Rect offset_rect(rect);
866 offset_rect.Offset(available_area_.point());
867 paint_manager_.InvalidateRect(offset_rect);
870 void OutOfProcessInstance::Scroll(const pp::Point& point) {
871 if (!image_data_.is_null())
872 paint_manager_.ScrollRect(available_area_, point);
875 void OutOfProcessInstance::ScrollToX(int x) {
876 pp::VarDictionary position;
877 position.Set(kType, kJSSetScrollPositionType);
878 position.Set(kJSPositionX, pp::Var(x / device_scale_));
879 PostMessage(position);
882 void OutOfProcessInstance::ScrollToY(int y) {
883 pp::VarDictionary position;
884 position.Set(kType, kJSSetScrollPositionType);
885 position.Set(kJSPositionY, pp::Var(y / device_scale_));
886 PostMessage(position);
889 void OutOfProcessInstance::ScrollToPage(int page) {
890 if (engine_->GetNumberOfPages() == 0)
891 return;
893 pp::VarDictionary message;
894 message.Set(kType, kJSGoToPageType);
895 message.Set(kJSPageNumber, pp::Var(page));
896 PostMessage(message);
899 void OutOfProcessInstance::NavigateTo(const std::string& url,
900 bool open_in_new_tab) {
901 pp::VarDictionary message;
902 message.Set(kType, kJSNavigateType);
903 message.Set(kJSNavigateUrl, url);
904 message.Set(kJSNavigateNewTab, open_in_new_tab);
905 PostMessage(message);
908 void OutOfProcessInstance::UpdateCursor(PP_CursorType_Dev cursor) {
909 if (cursor == cursor_)
910 return;
911 cursor_ = cursor;
913 const PPB_CursorControl_Dev* cursor_interface =
914 reinterpret_cast<const PPB_CursorControl_Dev*>(
915 pp::Module::Get()->GetBrowserInterface(PPB_CURSOR_CONTROL_DEV_INTERFACE));
916 if (!cursor_interface) {
917 NOTREACHED();
918 return;
921 cursor_interface->SetCursor(
922 pp_instance(), cursor_, pp::ImageData().pp_resource(), nullptr);
925 void OutOfProcessInstance::UpdateTickMarks(
926 const std::vector<pp::Rect>& tickmarks) {
927 float inverse_scale = 1.0f / device_scale_;
928 std::vector<pp::Rect> scaled_tickmarks = tickmarks;
929 for (size_t i = 0; i < scaled_tickmarks.size(); i++)
930 ScaleRect(inverse_scale, &scaled_tickmarks[i]);
931 tickmarks_ = scaled_tickmarks;
934 void OutOfProcessInstance::NotifyNumberOfFindResultsChanged(int total,
935 bool final_result) {
936 // We don't want to spam the renderer with too many updates to the number of
937 // find results. Don't send an update if we sent one too recently. If it's the
938 // final update, we always send it though.
939 if (final_result) {
940 NumberOfFindResultsChanged(total, final_result);
941 SetTickmarks(tickmarks_);
942 return;
945 if (recently_sent_find_update_)
946 return;
948 NumberOfFindResultsChanged(total, final_result);
949 SetTickmarks(tickmarks_);
950 recently_sent_find_update_ = true;
951 pp::CompletionCallback callback =
952 timer_factory_.NewCallback(
953 &OutOfProcessInstance::ResetRecentlySentFindUpdate);
954 pp::Module::Get()->core()->CallOnMainThread(kFindResultCooldownMs,
955 callback, 0);
958 void OutOfProcessInstance::NotifySelectedFindResultChanged(
959 int current_find_index) {
960 DCHECK_GE(current_find_index, 0);
961 SelectedFindResultChanged(current_find_index);
964 void OutOfProcessInstance::GetDocumentPassword(
965 pp::CompletionCallbackWithOutput<pp::Var> callback) {
966 if (password_callback_) {
967 NOTREACHED();
968 return;
971 password_callback_.reset(
972 new pp::CompletionCallbackWithOutput<pp::Var>(callback));
973 pp::VarDictionary message;
974 message.Set(pp::Var(kType), pp::Var(kJSGetPasswordType));
975 PostMessage(message);
978 void OutOfProcessInstance::Alert(const std::string& message) {
979 ModalDialog(this, "alert", message, std::string());
982 bool OutOfProcessInstance::Confirm(const std::string& message) {
983 pp::Var result = ModalDialog(this, "confirm", message, std::string());
984 return result.is_bool() ? result.AsBool() : false;
987 std::string OutOfProcessInstance::Prompt(const std::string& question,
988 const std::string& default_answer) {
989 pp::Var result = ModalDialog(this, "prompt", question, default_answer);
990 return result.is_string() ? result.AsString() : std::string();
993 std::string OutOfProcessInstance::GetURL() {
994 return url_;
997 void OutOfProcessInstance::Email(const std::string& to,
998 const std::string& cc,
999 const std::string& bcc,
1000 const std::string& subject,
1001 const std::string& body) {
1002 pp::VarDictionary message;
1003 message.Set(pp::Var(kType), pp::Var(kJSEmailType));
1004 message.Set(pp::Var(kJSEmailTo),
1005 pp::Var(net::EscapeUrlEncodedData(to, false)));
1006 message.Set(pp::Var(kJSEmailCc),
1007 pp::Var(net::EscapeUrlEncodedData(cc, false)));
1008 message.Set(pp::Var(kJSEmailBcc),
1009 pp::Var(net::EscapeUrlEncodedData(bcc, false)));
1010 message.Set(pp::Var(kJSEmailSubject),
1011 pp::Var(net::EscapeUrlEncodedData(subject, false)));
1012 message.Set(pp::Var(kJSEmailBody),
1013 pp::Var(net::EscapeUrlEncodedData(body, false)));
1014 PostMessage(message);
1017 void OutOfProcessInstance::Print() {
1018 if (!engine_->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY) &&
1019 !engine_->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY)) {
1020 return;
1023 pp::CompletionCallback callback =
1024 print_callback_factory_.NewCallback(&OutOfProcessInstance::OnPrint);
1025 pp::Module::Get()->core()->CallOnMainThread(0, callback);
1028 void OutOfProcessInstance::OnPrint(int32_t) {
1029 pp::PDF::Print(this);
1032 void OutOfProcessInstance::SubmitForm(const std::string& url,
1033 const void* data,
1034 int length) {
1035 pp::URLRequestInfo request(this);
1036 request.SetURL(url);
1037 request.SetMethod("POST");
1038 request.AppendDataToBody(reinterpret_cast<const char*>(data), length);
1040 pp::CompletionCallback callback =
1041 form_factory_.NewCallback(&OutOfProcessInstance::FormDidOpen);
1042 form_loader_ = CreateURLLoaderInternal();
1043 int rv = form_loader_.Open(request, callback);
1044 if (rv != PP_OK_COMPLETIONPENDING)
1045 callback.Run(rv);
1048 void OutOfProcessInstance::FormDidOpen(int32_t result) {
1049 // TODO: inform the user of success/failure.
1050 if (result != PP_OK) {
1051 NOTREACHED();
1055 std::string OutOfProcessInstance::ShowFileSelectionDialog() {
1056 // Seems like very low priority to implement, since the pdf has no way to get
1057 // the file data anyways. Javascript doesn't let you do this synchronously.
1058 NOTREACHED();
1059 return std::string();
1062 pp::URLLoader OutOfProcessInstance::CreateURLLoader() {
1063 if (full_) {
1064 if (!did_call_start_loading_) {
1065 did_call_start_loading_ = true;
1066 pp::PDF::DidStartLoading(this);
1069 // Disable save and print until the document is fully loaded, since they
1070 // would generate an incomplete document. Need to do this each time we
1071 // call DidStartLoading since that resets the content restrictions.
1072 pp::PDF::SetContentRestriction(this, CONTENT_RESTRICTION_SAVE |
1073 CONTENT_RESTRICTION_PRINT);
1076 return CreateURLLoaderInternal();
1079 void OutOfProcessInstance::ScheduleCallback(int id, int delay_in_ms) {
1080 pp::CompletionCallback callback =
1081 timer_factory_.NewCallback(&OutOfProcessInstance::OnClientTimerFired);
1082 pp::Module::Get()->core()->CallOnMainThread(delay_in_ms, callback, id);
1085 void OutOfProcessInstance::SearchString(const base::char16* string,
1086 const base::char16* term,
1087 bool case_sensitive,
1088 std::vector<SearchStringResult>* results) {
1089 PP_PrivateFindResult* pp_results;
1090 int count = 0;
1091 pp::PDF::SearchString(
1092 this,
1093 reinterpret_cast<const unsigned short*>(string),
1094 reinterpret_cast<const unsigned short*>(term),
1095 case_sensitive,
1096 &pp_results,
1097 &count);
1099 results->resize(count);
1100 for (int i = 0; i < count; ++i) {
1101 (*results)[i].start_index = pp_results[i].start_index;
1102 (*results)[i].length = pp_results[i].length;
1105 pp::Memory_Dev memory;
1106 memory.MemFree(pp_results);
1109 void OutOfProcessInstance::DocumentPaintOccurred() {
1112 void OutOfProcessInstance::DocumentLoadComplete(int page_count) {
1113 // Clear focus state for OSK.
1114 FormTextFieldFocusChange(false);
1116 DCHECK(document_load_state_ == LOAD_STATE_LOADING);
1117 document_load_state_ = LOAD_STATE_COMPLETE;
1118 UserMetricsRecordAction("PDF.LoadSuccess");
1120 // Note: If we are in print preview mode the scroll location is retained
1121 // across document loads so we don't want to scroll again and override it.
1122 if (IsPrintPreview()) {
1123 AppendBlankPrintPreviewPages();
1124 OnGeometryChanged(0, 0);
1127 pp::VarDictionary bookmarks_message;
1128 bookmarks_message.Set(pp::Var(kType), pp::Var(kJSBookmarksType));
1129 bookmarks_message.Set(pp::Var(kJSBookmarks), engine_->GetBookmarks());
1130 PostMessage(bookmarks_message);
1132 pp::VarDictionary progress_message;
1133 progress_message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1134 progress_message.Set(pp::Var(kJSProgressPercentage), pp::Var(100));
1135 PostMessage(progress_message);
1137 if (!full_)
1138 return;
1140 if (did_call_start_loading_) {
1141 pp::PDF::DidStopLoading(this);
1142 did_call_start_loading_ = false;
1145 int content_restrictions =
1146 CONTENT_RESTRICTION_CUT | CONTENT_RESTRICTION_PASTE;
1147 if (!engine_->HasPermission(PDFEngine::PERMISSION_COPY))
1148 content_restrictions |= CONTENT_RESTRICTION_COPY;
1150 if (!engine_->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY) &&
1151 !engine_->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY)) {
1152 content_restrictions |= CONTENT_RESTRICTION_PRINT;
1155 pp::PDF::SetContentRestriction(this, content_restrictions);
1157 uma_.HistogramCustomCounts("PDF.PageCount", page_count, 1, 1000000, 50);
1160 void OutOfProcessInstance::RotateClockwise() {
1161 engine_->RotateClockwise();
1164 void OutOfProcessInstance::RotateCounterclockwise() {
1165 engine_->RotateCounterclockwise();
1168 void OutOfProcessInstance::PreviewDocumentLoadComplete() {
1169 if (preview_document_load_state_ != LOAD_STATE_LOADING ||
1170 preview_pages_info_.empty()) {
1171 return;
1174 preview_document_load_state_ = LOAD_STATE_COMPLETE;
1176 int dest_page_index = preview_pages_info_.front().second;
1177 int src_page_index =
1178 ExtractPrintPreviewPageIndex(preview_pages_info_.front().first);
1179 if (src_page_index > 0 && dest_page_index > -1 && preview_engine_.get())
1180 engine_->AppendPage(preview_engine_.get(), dest_page_index);
1182 preview_pages_info_.pop();
1183 // |print_preview_page_count_| is not updated yet. Do not load any
1184 // other preview pages till we get this information.
1185 if (print_preview_page_count_ == 0)
1186 return;
1188 if (!preview_pages_info_.empty())
1189 LoadAvailablePreviewPage();
1192 void OutOfProcessInstance::DocumentLoadFailed() {
1193 DCHECK(document_load_state_ == LOAD_STATE_LOADING);
1194 UserMetricsRecordAction("PDF.LoadFailure");
1196 if (did_call_start_loading_) {
1197 pp::PDF::DidStopLoading(this);
1198 did_call_start_loading_ = false;
1201 document_load_state_ = LOAD_STATE_FAILED;
1202 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
1204 // Send a progress value of -1 to indicate a failure.
1205 pp::VarDictionary message;
1206 message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1207 message.Set(pp::Var(kJSProgressPercentage), pp::Var(-1));
1208 PostMessage(message);
1211 void OutOfProcessInstance::PreviewDocumentLoadFailed() {
1212 UserMetricsRecordAction("PDF.PreviewDocumentLoadFailure");
1213 if (preview_document_load_state_ != LOAD_STATE_LOADING ||
1214 preview_pages_info_.empty()) {
1215 return;
1218 preview_document_load_state_ = LOAD_STATE_FAILED;
1219 preview_pages_info_.pop();
1221 if (!preview_pages_info_.empty())
1222 LoadAvailablePreviewPage();
1225 pp::Instance* OutOfProcessInstance::GetPluginInstance() {
1226 return this;
1229 void OutOfProcessInstance::DocumentHasUnsupportedFeature(
1230 const std::string& feature) {
1231 std::string metric("PDF_Unsupported_");
1232 metric += feature;
1233 if (!unsupported_features_reported_.count(metric)) {
1234 unsupported_features_reported_.insert(metric);
1235 UserMetricsRecordAction(metric);
1238 // Since we use an info bar, only do this for full frame plugins..
1239 if (!full_)
1240 return;
1242 if (told_browser_about_unsupported_feature_)
1243 return;
1244 told_browser_about_unsupported_feature_ = true;
1246 pp::PDF::HasUnsupportedFeature(this);
1249 void OutOfProcessInstance::DocumentLoadProgress(uint32 available,
1250 uint32 doc_size) {
1251 double progress = 0.0;
1252 if (doc_size == 0) {
1253 // Document size is unknown. Use heuristics.
1254 // We'll make progress logarithmic from 0 to 100M.
1255 static const double kFactor = log(100000000.0) / 100.0;
1256 if (available > 0) {
1257 progress = log(static_cast<double>(available)) / kFactor;
1258 if (progress > 100.0)
1259 progress = 100.0;
1261 } else {
1262 progress = 100.0 * static_cast<double>(available) / doc_size;
1265 // We send 100% load progress in DocumentLoadComplete.
1266 if (progress >= 100)
1267 return;
1269 // Avoid sending too many progress messages over PostMessage.
1270 if (progress > last_progress_sent_ + 1) {
1271 last_progress_sent_ = progress;
1272 pp::VarDictionary message;
1273 message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1274 message.Set(pp::Var(kJSProgressPercentage), pp::Var(progress));
1275 PostMessage(message);
1279 void OutOfProcessInstance::FormTextFieldFocusChange(bool in_focus) {
1280 if (!text_input_.get())
1281 return;
1282 if (in_focus)
1283 text_input_->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_TEXT);
1284 else
1285 text_input_->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_NONE);
1288 void OutOfProcessInstance::ResetRecentlySentFindUpdate(int32_t /* unused */) {
1289 recently_sent_find_update_ = false;
1292 void OutOfProcessInstance::OnGeometryChanged(double old_zoom,
1293 float old_device_scale) {
1294 if (zoom_ != old_zoom || device_scale_ != old_device_scale)
1295 engine_->ZoomUpdated(zoom_ * device_scale_);
1297 available_area_ = pp::Rect(plugin_size_);
1298 int doc_width = GetDocumentPixelWidth();
1299 if (doc_width < available_area_.width()) {
1300 available_area_.Offset((available_area_.width() - doc_width) / 2, 0);
1301 available_area_.set_width(doc_width);
1303 int bottom_of_document =
1304 GetDocumentPixelHeight() + (top_toolbar_height_ * device_scale_);
1305 if (bottom_of_document < available_area_.height())
1306 available_area_.set_height(bottom_of_document);
1308 CalculateBackgroundParts();
1309 engine_->PageOffsetUpdated(available_area_.point());
1310 engine_->PluginSizeUpdated(available_area_.size());
1312 if (!document_size_.GetArea())
1313 return;
1314 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
1317 void OutOfProcessInstance::LoadUrl(const std::string& url) {
1318 LoadUrlInternal(url, &embed_loader_, &OutOfProcessInstance::DidOpen);
1321 void OutOfProcessInstance::LoadPreviewUrl(const std::string& url) {
1322 LoadUrlInternal(url, &embed_preview_loader_,
1323 &OutOfProcessInstance::DidOpenPreview);
1326 void OutOfProcessInstance::LoadUrlInternal(
1327 const std::string& url,
1328 pp::URLLoader* loader,
1329 void (OutOfProcessInstance::* method)(int32_t)) {
1330 pp::URLRequestInfo request(this);
1331 request.SetURL(url);
1332 request.SetMethod("GET");
1334 *loader = CreateURLLoaderInternal();
1335 pp::CompletionCallback callback = loader_factory_.NewCallback(method);
1336 int rv = loader->Open(request, callback);
1337 if (rv != PP_OK_COMPLETIONPENDING)
1338 callback.Run(rv);
1341 pp::URLLoader OutOfProcessInstance::CreateURLLoaderInternal() {
1342 pp::URLLoader loader(this);
1344 const PPB_URLLoaderTrusted* trusted_interface =
1345 reinterpret_cast<const PPB_URLLoaderTrusted*>(
1346 pp::Module::Get()->GetBrowserInterface(
1347 PPB_URLLOADERTRUSTED_INTERFACE));
1348 if (trusted_interface)
1349 trusted_interface->GrantUniversalAccess(loader.pp_resource());
1350 return loader;
1353 void OutOfProcessInstance::SetZoom(double scale) {
1354 double old_zoom = zoom_;
1355 zoom_ = scale;
1356 OnGeometryChanged(old_zoom, device_scale_);
1359 std::string OutOfProcessInstance::GetLocalizedString(PP_ResourceString id) {
1360 pp::Var rv(pp::PDF::GetLocalizedString(this, id));
1361 if (!rv.is_string())
1362 return std::string();
1364 return rv.AsString();
1367 void OutOfProcessInstance::AppendBlankPrintPreviewPages() {
1368 if (print_preview_page_count_ == 0)
1369 return;
1370 engine_->AppendBlankPages(print_preview_page_count_);
1371 if (!preview_pages_info_.empty())
1372 LoadAvailablePreviewPage();
1375 bool OutOfProcessInstance::IsPrintPreview() {
1376 return IsPrintPreviewUrl(url_);
1379 uint32 OutOfProcessInstance::GetBackgroundColor() {
1380 return background_color_;
1383 void OutOfProcessInstance::IsSelectingChanged(bool is_selecting) {
1384 pp::VarDictionary message;
1385 message.Set(kType, kJSSetIsSelectingType);
1386 message.Set(kJSIsSelecting, pp::Var(is_selecting));
1387 PostMessage(message);
1390 void OutOfProcessInstance::ProcessPreviewPageInfo(const std::string& url,
1391 int dst_page_index) {
1392 if (!IsPrintPreview())
1393 return;
1395 int src_page_index = ExtractPrintPreviewPageIndex(url);
1396 if (src_page_index < 1)
1397 return;
1399 preview_pages_info_.push(std::make_pair(url, dst_page_index));
1400 LoadAvailablePreviewPage();
1403 void OutOfProcessInstance::LoadAvailablePreviewPage() {
1404 if (preview_pages_info_.empty() ||
1405 document_load_state_ != LOAD_STATE_COMPLETE) {
1406 return;
1409 std::string url = preview_pages_info_.front().first;
1410 int dst_page_index = preview_pages_info_.front().second;
1411 int src_page_index = ExtractPrintPreviewPageIndex(url);
1412 if (src_page_index < 1 ||
1413 dst_page_index >= print_preview_page_count_ ||
1414 preview_document_load_state_ == LOAD_STATE_LOADING) {
1415 return;
1418 preview_document_load_state_ = LOAD_STATE_LOADING;
1419 LoadPreviewUrl(url);
1422 void OutOfProcessInstance::UserMetricsRecordAction(
1423 const std::string& action) {
1424 // TODO(raymes): Move this function to PPB_UMA_Private.
1425 pp::PDF::UserMetricsRecordAction(this, pp::Var(action));
1428 pp::FloatPoint OutOfProcessInstance::BoundScrollOffsetToDocument(
1429 const pp::FloatPoint& scroll_offset) {
1430 float max_x = document_size_.width() * zoom_ - plugin_dip_size_.width();
1431 float x = std::max(std::min(scroll_offset.x(), max_x), 0.0f);
1432 float min_y = -top_toolbar_height_;
1433 float max_y = document_size_.height() * zoom_ - plugin_dip_size_.height();
1434 float y = std::max(std::min(scroll_offset.y(), max_y), min_y);
1435 return pp::FloatPoint(x, y);
1438 } // namespace chrome_pdf