GPU workaround to simulate Out of Memory errors with large textures
[chromium-blink-merge.git] / pdf / out_of_process_instance.cc
blob87d45aa2cf0730a747e35f8625bb4a7231afc72c
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 = 0xFFEEEEEE;
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 pp::Selection_Dev(this),
266 cursor_(PP_CURSORTYPE_POINTER),
267 zoom_(1.0),
268 device_scale_(1.0),
269 full_(false),
270 paint_manager_(this, this, true),
271 first_paint_(true),
272 document_load_state_(LOAD_STATE_LOADING),
273 preview_document_load_state_(LOAD_STATE_COMPLETE),
274 uma_(this),
275 told_browser_about_unsupported_feature_(false),
276 print_preview_page_count_(0),
277 last_progress_sent_(0),
278 recently_sent_find_update_(false),
279 received_viewport_message_(false),
280 did_call_start_loading_(false),
281 stop_scrolling_(false),
282 background_color_(kBackgroundColor) {
283 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);
300 bool OutOfProcessInstance::Init(uint32_t argc,
301 const char* argn[],
302 const char* argv[]) {
303 // Check if the PDF is being loaded in the PDF chrome extension. We only allow
304 // the plugin to be put into "full frame" mode when it is being loaded in the
305 // extension because this enables some features that we don't want pages
306 // abusing outside of the extension.
307 pp::Var document_url_var = pp::URLUtil_Dev::Get()->GetDocumentURL(this);
308 std::string document_url = document_url_var.is_string() ?
309 document_url_var.AsString() : std::string();
310 std::string extension_url = std::string(kChromeExtension);
311 bool in_extension =
312 !document_url.compare(0, extension_url.size(), extension_url);
314 if (in_extension) {
315 // Check if the plugin is full frame. This is passed in from JS.
316 for (uint32_t i = 0; i < argc; ++i) {
317 if (strcmp(argn[i], "full-frame") == 0) {
318 full_ = true;
319 break;
324 // Only allow the plugin to handle find requests if it is full frame.
325 if (full_)
326 SetPluginToHandleFindRequests();
328 // Send translated strings to the extension where they will be displayed.
329 // TODO(raymes): It would be better to get these in the extension directly
330 // through an API but no such API currently exists.
331 pp::VarDictionary translated_strings;
332 translated_strings.Set(kType, kJSSetTranslatedStringsType);
333 translated_strings.Set(kJSGetPasswordString,
334 GetLocalizedString(PP_RESOURCESTRING_PDFGETPASSWORD));
335 translated_strings.Set(kJSLoadingString,
336 GetLocalizedString(PP_RESOURCESTRING_PDFLOADING));
337 translated_strings.Set(kJSLoadFailedString,
338 GetLocalizedString(PP_RESOURCESTRING_PDFLOAD_FAILED));
339 PostMessage(translated_strings);
341 text_input_.reset(new pp::TextInput_Dev(this));
343 const char* stream_url = NULL;
344 const char* original_url = NULL;
345 const char* headers = NULL;
346 bool is_material = false;
347 for (uint32_t i = 0; i < argc; ++i) {
348 if (strcmp(argn[i], "src") == 0)
349 original_url = argv[i];
350 else if (strcmp(argn[i], "stream-url") == 0)
351 stream_url = argv[i];
352 else if (strcmp(argn[i], "headers") == 0)
353 headers = argv[i];
354 else if (strcmp(argn[i], "is-material") == 0)
355 is_material = true;
358 if (is_material)
359 background_color_ = kBackgroundColorMaterial;
360 else
361 background_color_ = kBackgroundColor;
363 // TODO(raymes): This is a hack to ensure that if no headers are passed in
364 // then we get the right MIME type. When the in process plugin is removed we
365 // can fix the document loader properly and remove this hack.
366 if (!headers || strcmp(headers, "") == 0)
367 headers = "content-type: application/pdf";
369 if (!original_url)
370 return false;
372 if (!stream_url)
373 stream_url = original_url;
375 // If we're in print preview mode we don't need to load the document yet.
376 // A |kJSResetPrintPreviewModeType| message will be sent to the plugin letting
377 // it know the url to load. By not loading here we avoid loading the same
378 // document twice.
379 if (IsPrintPreviewUrl(original_url))
380 return true;
382 LoadUrl(stream_url);
383 url_ = original_url;
384 return engine_->New(original_url, headers);
387 void OutOfProcessInstance::HandleMessage(const pp::Var& message) {
388 pp::VarDictionary dict(message);
389 if (!dict.Get(kType).is_string()) {
390 NOTREACHED();
391 return;
394 std::string type = dict.Get(kType).AsString();
396 if (type == kJSViewportType &&
397 dict.Get(pp::Var(kJSXOffset)).is_number() &&
398 dict.Get(pp::Var(kJSYOffset)).is_number() &&
399 dict.Get(pp::Var(kJSZoom)).is_number()) {
400 received_viewport_message_ = true;
401 stop_scrolling_ = false;
402 double zoom = dict.Get(pp::Var(kJSZoom)).AsDouble();
403 pp::FloatPoint scroll_offset(dict.Get(pp::Var(kJSXOffset)).AsDouble(),
404 dict.Get(pp::Var(kJSYOffset)).AsDouble());
406 // Bound the input parameters.
407 zoom = std::max(kMinZoom, zoom);
408 SetZoom(zoom);
409 scroll_offset = BoundScrollOffsetToDocument(scroll_offset);
410 engine_->ScrolledToXPosition(scroll_offset.x() * device_scale_);
411 engine_->ScrolledToYPosition(scroll_offset.y() * device_scale_);
412 } else if (type == kJSGetPasswordCompleteType &&
413 dict.Get(pp::Var(kJSPassword)).is_string()) {
414 if (password_callback_) {
415 pp::CompletionCallbackWithOutput<pp::Var> callback = *password_callback_;
416 password_callback_.reset();
417 *callback.output() = dict.Get(pp::Var(kJSPassword)).pp_var();
418 callback.Run(PP_OK);
419 } else {
420 NOTREACHED();
422 } else if (type == kJSPrintType) {
423 Print();
424 } else if (type == kJSSaveType) {
425 pp::PDF::SaveAs(this);
426 } else if (type == kJSRotateClockwiseType) {
427 RotateClockwise();
428 } else if (type == kJSRotateCounterclockwiseType) {
429 RotateCounterclockwise();
430 } else if (type == kJSSelectAllType) {
431 engine_->SelectAll();
432 } else if (type == kJSResetPrintPreviewModeType &&
433 dict.Get(pp::Var(kJSPrintPreviewUrl)).is_string() &&
434 dict.Get(pp::Var(kJSPrintPreviewGrayscale)).is_bool() &&
435 dict.Get(pp::Var(kJSPrintPreviewPageCount)).is_int()) {
436 url_ = dict.Get(pp::Var(kJSPrintPreviewUrl)).AsString();
437 preview_pages_info_ = std::queue<PreviewPageInfo>();
438 preview_document_load_state_ = LOAD_STATE_COMPLETE;
439 document_load_state_ = LOAD_STATE_LOADING;
440 LoadUrl(url_);
441 preview_engine_.reset();
442 engine_.reset(PDFEngine::Create(this));
443 engine_->SetGrayscale(dict.Get(pp::Var(kJSPrintPreviewGrayscale)).AsBool());
444 engine_->New(url_.c_str());
446 print_preview_page_count_ =
447 std::max(dict.Get(pp::Var(kJSPrintPreviewPageCount)).AsInt(), 0);
449 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
450 } else if (type == kJSLoadPreviewPageType &&
451 dict.Get(pp::Var(kJSPreviewPageUrl)).is_string() &&
452 dict.Get(pp::Var(kJSPreviewPageIndex)).is_int()) {
453 ProcessPreviewPageInfo(dict.Get(pp::Var(kJSPreviewPageUrl)).AsString(),
454 dict.Get(pp::Var(kJSPreviewPageIndex)).AsInt());
455 } else if (type == kJSGetAccessibilityJSONType) {
456 pp::VarDictionary reply;
457 reply.Set(pp::Var(kType), pp::Var(kJSGetAccessibilityJSONReplyType));
458 if (dict.Get(pp::Var(kJSAccessibilityPageNumber)).is_int()) {
459 int page = dict.Get(pp::Var(kJSAccessibilityPageNumber)).AsInt();
460 reply.Set(pp::Var(kJSAccessibilityJSON),
461 pp::Var(engine_->GetPageAsJSON(page)));
462 } else {
463 base::DictionaryValue node;
464 node.SetInteger(kAccessibleNumberOfPages, engine_->GetNumberOfPages());
465 node.SetBoolean(kAccessibleLoaded,
466 document_load_state_ != LOAD_STATE_LOADING);
467 bool has_permissions =
468 engine_->HasPermission(PDFEngine::PERMISSION_COPY) ||
469 engine_->HasPermission(PDFEngine::PERMISSION_COPY_ACCESSIBLE);
470 node.SetBoolean(kAccessibleCopyable, has_permissions);
471 std::string json;
472 base::JSONWriter::Write(&node, &json);
473 reply.Set(pp::Var(kJSAccessibilityJSON), pp::Var(json));
475 PostMessage(reply);
476 } else if (type == kJSStopScrollingType) {
477 stop_scrolling_ = true;
478 } else if (type == kJSGetSelectedTextType) {
479 std::string selected_text = engine_->GetSelectedText();
480 // Always return unix newlines to JS.
481 base::ReplaceChars(selected_text, "\r", std::string(), &selected_text);
482 pp::VarDictionary reply;
483 reply.Set(pp::Var(kType), pp::Var(kJSGetSelectedTextReplyType));
484 reply.Set(pp::Var(kJSSelectedText), selected_text);
485 PostMessage(reply);
486 } else if (type == KJSGetNamedDestinationType &&
487 dict.Get(pp::Var(KJSGetNamedDestination)).is_string()) {
488 int page_number = engine_->GetNamedDestinationPage(
489 dict.Get(pp::Var(KJSGetNamedDestination)).AsString());
490 pp::VarDictionary reply;
491 reply.Set(pp::Var(kType), pp::Var(kJSGetNamedDestinationReplyType));
492 if (page_number >= 0)
493 reply.Set(pp::Var(kJSNamedDestinationPageNumber), page_number);
494 PostMessage(reply);
495 } else {
496 NOTREACHED();
500 bool OutOfProcessInstance::HandleInputEvent(
501 const pp::InputEvent& event) {
502 // To simplify things, convert the event into device coordinates if it is
503 // a mouse event.
504 pp::InputEvent event_device_res(event);
506 pp::MouseInputEvent mouse_event(event);
507 if (!mouse_event.is_null()) {
508 pp::Point point = mouse_event.GetPosition();
509 pp::Point movement = mouse_event.GetMovement();
510 ScalePoint(device_scale_, &point);
511 ScalePoint(device_scale_, &movement);
512 mouse_event = pp::MouseInputEvent(
513 this,
514 event.GetType(),
515 event.GetTimeStamp(),
516 event.GetModifiers(),
517 mouse_event.GetButton(),
518 point,
519 mouse_event.GetClickCount(),
520 movement);
521 event_device_res = mouse_event;
525 pp::InputEvent offset_event(event_device_res);
526 switch (offset_event.GetType()) {
527 case PP_INPUTEVENT_TYPE_MOUSEDOWN:
528 case PP_INPUTEVENT_TYPE_MOUSEUP:
529 case PP_INPUTEVENT_TYPE_MOUSEMOVE:
530 case PP_INPUTEVENT_TYPE_MOUSEENTER:
531 case PP_INPUTEVENT_TYPE_MOUSELEAVE: {
532 pp::MouseInputEvent mouse_event(event_device_res);
533 pp::MouseInputEvent mouse_event_dip(event);
534 pp::Point point = mouse_event.GetPosition();
535 point.set_x(point.x() - available_area_.x());
536 offset_event = pp::MouseInputEvent(
537 this,
538 event.GetType(),
539 event.GetTimeStamp(),
540 event.GetModifiers(),
541 mouse_event.GetButton(),
542 point,
543 mouse_event.GetClickCount(),
544 mouse_event.GetMovement());
545 break;
547 default:
548 break;
550 if (engine_->HandleEvent(offset_event))
551 return true;
553 // Middle click is used for scrolling and is handled by the container page.
554 pp::MouseInputEvent mouse_event(event_device_res);
555 if (!mouse_event.is_null() &&
556 mouse_event.GetButton() == PP_INPUTEVENT_MOUSEBUTTON_MIDDLE) {
557 return false;
560 // Return true for unhandled clicks so the plugin takes focus.
561 return (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN);
564 void OutOfProcessInstance::DidChangeView(const pp::View& view) {
565 pp::Rect view_rect(view.GetRect());
566 float old_device_scale = device_scale_;
567 float device_scale = view.GetDeviceScale();
568 pp::Size view_device_size(view_rect.width() * device_scale,
569 view_rect.height() * device_scale);
571 if (view_device_size != plugin_size_ || device_scale != device_scale_) {
572 device_scale_ = device_scale;
573 plugin_dip_size_ = view_rect.size();
574 plugin_size_ = view_device_size;
576 paint_manager_.SetSize(view_device_size, device_scale_);
578 pp::Size new_image_data_size = PaintManager::GetNewContextSize(
579 image_data_.size(),
580 plugin_size_);
581 if (new_image_data_size != image_data_.size()) {
582 image_data_ = pp::ImageData(this,
583 PP_IMAGEDATAFORMAT_BGRA_PREMUL,
584 new_image_data_size,
585 false);
586 first_paint_ = true;
589 if (image_data_.is_null()) {
590 DCHECK(plugin_size_.IsEmpty());
591 return;
594 OnGeometryChanged(zoom_, old_device_scale);
597 if (!stop_scrolling_) {
598 pp::Point scroll_offset(view.GetScrollOffset());
599 pp::FloatPoint scroll_offset_float(scroll_offset.x(),
600 scroll_offset.y());
601 scroll_offset_float = BoundScrollOffsetToDocument(scroll_offset_float);
602 engine_->ScrolledToXPosition(scroll_offset_float.x() * device_scale_);
603 engine_->ScrolledToYPosition(scroll_offset_float.y() * device_scale_);
607 void OutOfProcessInstance::GetPrintPresetOptionsFromDocument(
608 PP_PdfPrintPresetOptions_Dev* options) {
609 options->is_scaling_disabled = PP_FromBool(IsPrintScalingDisabled());
610 options->duplex =
611 static_cast<PP_PrivateDuplexMode_Dev>(engine_->GetDuplexType());
612 options->copies = engine_->GetCopiesToPrint();
613 pp::Size uniform_page_size;
614 options->is_page_size_uniform =
615 PP_FromBool(engine_->GetPageSizeAndUniformity(&uniform_page_size));
616 options->uniform_page_size = uniform_page_size;
619 pp::Var OutOfProcessInstance::GetLinkAtPosition(
620 const pp::Point& point) {
621 pp::Point offset_point(point);
622 ScalePoint(device_scale_, &offset_point);
623 offset_point.set_x(offset_point.x() - available_area_.x());
624 return engine_->GetLinkAtPosition(offset_point);
627 pp::Var OutOfProcessInstance::GetSelectedText(bool html) {
628 if (html)
629 return pp::Var();
630 return engine_->GetSelectedText();
633 uint32_t OutOfProcessInstance::QuerySupportedPrintOutputFormats() {
634 return engine_->QuerySupportedPrintOutputFormats();
637 int32_t OutOfProcessInstance::PrintBegin(
638 const PP_PrintSettings_Dev& print_settings) {
639 // For us num_pages is always equal to the number of pages in the PDF
640 // document irrespective of the printable area.
641 int32_t ret = engine_->GetNumberOfPages();
642 if (!ret)
643 return 0;
645 uint32_t supported_formats = engine_->QuerySupportedPrintOutputFormats();
646 if ((print_settings.format & supported_formats) == 0)
647 return 0;
649 print_settings_.is_printing = true;
650 print_settings_.pepper_print_settings = print_settings;
651 engine_->PrintBegin();
652 return ret;
655 pp::Resource OutOfProcessInstance::PrintPages(
656 const PP_PrintPageNumberRange_Dev* page_ranges,
657 uint32_t page_range_count) {
658 if (!print_settings_.is_printing)
659 return pp::Resource();
661 print_settings_.print_pages_called_ = true;
662 return engine_->PrintPages(page_ranges, page_range_count,
663 print_settings_.pepper_print_settings);
666 void OutOfProcessInstance::PrintEnd() {
667 if (print_settings_.print_pages_called_)
668 UserMetricsRecordAction("PDF.PrintPage");
669 print_settings_.Clear();
670 engine_->PrintEnd();
673 bool OutOfProcessInstance::IsPrintScalingDisabled() {
674 return !engine_->GetPrintScaling();
677 bool OutOfProcessInstance::StartFind(const std::string& text,
678 bool case_sensitive) {
679 engine_->StartFind(text.c_str(), case_sensitive);
680 return true;
683 void OutOfProcessInstance::SelectFindResult(bool forward) {
684 engine_->SelectFindResult(forward);
687 void OutOfProcessInstance::StopFind() {
688 engine_->StopFind();
689 tickmarks_.clear();
690 SetTickmarks(tickmarks_);
693 void OutOfProcessInstance::OnPaint(
694 const std::vector<pp::Rect>& paint_rects,
695 std::vector<PaintManager::ReadyRect>* ready,
696 std::vector<pp::Rect>* pending) {
697 if (image_data_.is_null()) {
698 DCHECK(plugin_size_.IsEmpty());
699 return;
701 if (first_paint_) {
702 first_paint_ = false;
703 pp::Rect rect = pp::Rect(pp::Point(), image_data_.size());
704 FillRect(rect, background_color_);
705 ready->push_back(PaintManager::ReadyRect(rect, image_data_, true));
708 if (!received_viewport_message_)
709 return;
711 engine_->PrePaint();
713 for (size_t i = 0; i < paint_rects.size(); i++) {
714 // Intersect with plugin area since there could be pending invalidates from
715 // when the plugin area was larger.
716 pp::Rect rect =
717 paint_rects[i].Intersect(pp::Rect(pp::Point(), plugin_size_));
718 if (rect.IsEmpty())
719 continue;
721 pp::Rect pdf_rect = available_area_.Intersect(rect);
722 if (!pdf_rect.IsEmpty()) {
723 pdf_rect.Offset(available_area_.x() * -1, 0);
725 std::vector<pp::Rect> pdf_ready;
726 std::vector<pp::Rect> pdf_pending;
727 engine_->Paint(pdf_rect, &image_data_, &pdf_ready, &pdf_pending);
728 for (size_t j = 0; j < pdf_ready.size(); ++j) {
729 pdf_ready[j].Offset(available_area_.point());
730 ready->push_back(
731 PaintManager::ReadyRect(pdf_ready[j], image_data_, false));
733 for (size_t j = 0; j < pdf_pending.size(); ++j) {
734 pdf_pending[j].Offset(available_area_.point());
735 pending->push_back(pdf_pending[j]);
739 for (size_t j = 0; j < background_parts_.size(); ++j) {
740 pp::Rect intersection = background_parts_[j].location.Intersect(rect);
741 if (!intersection.IsEmpty()) {
742 FillRect(intersection, background_parts_[j].color);
743 ready->push_back(
744 PaintManager::ReadyRect(intersection, image_data_, false));
749 engine_->PostPaint();
752 void OutOfProcessInstance::DidOpen(int32_t result) {
753 if (result == PP_OK) {
754 if (!engine_->HandleDocumentLoad(embed_loader_)) {
755 document_load_state_ = LOAD_STATE_LOADING;
756 DocumentLoadFailed();
758 } else if (result != PP_ERROR_ABORTED) { // Can happen in tests.
759 NOTREACHED();
760 DocumentLoadFailed();
763 // If it's a progressive load, cancel the stream URL request so that requests
764 // can be made on the original URL.
765 // TODO(raymes): Make this clearer once the in-process plugin is deleted.
766 if (engine_->IsProgressiveLoad()) {
767 pp::VarDictionary message;
768 message.Set(kType, kJSCancelStreamUrlType);
769 PostMessage(message);
773 void OutOfProcessInstance::DidOpenPreview(int32_t result) {
774 if (result == PP_OK) {
775 preview_engine_.reset(PDFEngine::Create(new PreviewModeClient(this)));
776 preview_engine_->HandleDocumentLoad(embed_preview_loader_);
777 } else {
778 NOTREACHED();
782 void OutOfProcessInstance::OnClientTimerFired(int32_t id) {
783 engine_->OnCallback(id);
786 void OutOfProcessInstance::CalculateBackgroundParts() {
787 background_parts_.clear();
788 int left_width = available_area_.x();
789 int right_start = available_area_.right();
790 int right_width = abs(plugin_size_.width() - available_area_.right());
791 int bottom = std::min(available_area_.bottom(), plugin_size_.height());
793 // Add the left, right, and bottom rectangles. Note: we assume only
794 // horizontal centering.
795 BackgroundPart part = {
796 pp::Rect(0, 0, left_width, bottom),
797 background_color_
799 if (!part.location.IsEmpty())
800 background_parts_.push_back(part);
801 part.location = pp::Rect(right_start, 0, right_width, bottom);
802 if (!part.location.IsEmpty())
803 background_parts_.push_back(part);
804 part.location = pp::Rect(
805 0, bottom, plugin_size_.width(), plugin_size_.height() - bottom);
806 if (!part.location.IsEmpty())
807 background_parts_.push_back(part);
810 int OutOfProcessInstance::GetDocumentPixelWidth() const {
811 return static_cast<int>(ceil(document_size_.width() * zoom_ * device_scale_));
814 int OutOfProcessInstance::GetDocumentPixelHeight() const {
815 return static_cast<int>(
816 ceil(document_size_.height() * zoom_ * device_scale_));
819 void OutOfProcessInstance::FillRect(const pp::Rect& rect, uint32 color) {
820 DCHECK(!image_data_.is_null() || rect.IsEmpty());
821 uint32* buffer_start = static_cast<uint32*>(image_data_.data());
822 int stride = image_data_.stride();
823 uint32* ptr = buffer_start + rect.y() * stride / 4 + rect.x();
824 int height = rect.height();
825 int width = rect.width();
826 for (int y = 0; y < height; ++y) {
827 for (int x = 0; x < width; ++x)
828 *(ptr + x) = color;
829 ptr += stride /4;
833 void OutOfProcessInstance::DocumentSizeUpdated(const pp::Size& size) {
834 document_size_ = size;
836 pp::VarDictionary dimensions;
837 dimensions.Set(kType, kJSDocumentDimensionsType);
838 dimensions.Set(kJSDocumentWidth, pp::Var(document_size_.width()));
839 dimensions.Set(kJSDocumentHeight, pp::Var(document_size_.height()));
840 pp::VarArray page_dimensions_array;
841 int num_pages = engine_->GetNumberOfPages();
842 for (int i = 0; i < num_pages; ++i) {
843 pp::Rect page_rect = engine_->GetPageRect(i);
844 pp::VarDictionary page_dimensions;
845 page_dimensions.Set(kJSPageX, pp::Var(page_rect.x()));
846 page_dimensions.Set(kJSPageY, pp::Var(page_rect.y()));
847 page_dimensions.Set(kJSPageWidth, pp::Var(page_rect.width()));
848 page_dimensions.Set(kJSPageHeight, pp::Var(page_rect.height()));
849 page_dimensions_array.Set(i, page_dimensions);
851 dimensions.Set(kJSPageDimensions, page_dimensions_array);
852 PostMessage(dimensions);
854 OnGeometryChanged(zoom_, device_scale_);
857 void OutOfProcessInstance::Invalidate(const pp::Rect& rect) {
858 pp::Rect offset_rect(rect);
859 offset_rect.Offset(available_area_.point());
860 paint_manager_.InvalidateRect(offset_rect);
863 void OutOfProcessInstance::Scroll(const pp::Point& point) {
864 if (!image_data_.is_null())
865 paint_manager_.ScrollRect(available_area_, point);
868 void OutOfProcessInstance::ScrollToX(int x) {
869 pp::VarDictionary position;
870 position.Set(kType, kJSSetScrollPositionType);
871 position.Set(kJSPositionX, pp::Var(x / device_scale_));
872 PostMessage(position);
875 void OutOfProcessInstance::ScrollToY(int y) {
876 pp::VarDictionary position;
877 position.Set(kType, kJSSetScrollPositionType);
878 position.Set(kJSPositionY, pp::Var(y / device_scale_));
879 PostMessage(position);
882 void OutOfProcessInstance::ScrollToPage(int page) {
883 if (engine_->GetNumberOfPages() == 0)
884 return;
886 pp::VarDictionary message;
887 message.Set(kType, kJSGoToPageType);
888 message.Set(kJSPageNumber, pp::Var(page));
889 PostMessage(message);
892 void OutOfProcessInstance::NavigateTo(const std::string& url,
893 bool open_in_new_tab) {
894 pp::VarDictionary message;
895 message.Set(kType, kJSNavigateType);
896 message.Set(kJSNavigateUrl, url);
897 message.Set(kJSNavigateNewTab, open_in_new_tab);
898 PostMessage(message);
901 void OutOfProcessInstance::UpdateCursor(PP_CursorType_Dev cursor) {
902 if (cursor == cursor_)
903 return;
904 cursor_ = cursor;
906 const PPB_CursorControl_Dev* cursor_interface =
907 reinterpret_cast<const PPB_CursorControl_Dev*>(
908 pp::Module::Get()->GetBrowserInterface(PPB_CURSOR_CONTROL_DEV_INTERFACE));
909 if (!cursor_interface) {
910 NOTREACHED();
911 return;
914 cursor_interface->SetCursor(
915 pp_instance(), cursor_, pp::ImageData().pp_resource(), NULL);
918 void OutOfProcessInstance::UpdateTickMarks(
919 const std::vector<pp::Rect>& tickmarks) {
920 float inverse_scale = 1.0f / device_scale_;
921 std::vector<pp::Rect> scaled_tickmarks = tickmarks;
922 for (size_t i = 0; i < scaled_tickmarks.size(); i++)
923 ScaleRect(inverse_scale, &scaled_tickmarks[i]);
924 tickmarks_ = scaled_tickmarks;
927 void OutOfProcessInstance::NotifyNumberOfFindResultsChanged(int total,
928 bool final_result) {
929 // We don't want to spam the renderer with too many updates to the number of
930 // find results. Don't send an update if we sent one too recently. If it's the
931 // final update, we always send it though.
932 if (final_result) {
933 NumberOfFindResultsChanged(total, final_result);
934 SetTickmarks(tickmarks_);
935 return;
938 if (recently_sent_find_update_)
939 return;
941 NumberOfFindResultsChanged(total, final_result);
942 SetTickmarks(tickmarks_);
943 recently_sent_find_update_ = true;
944 pp::CompletionCallback callback =
945 timer_factory_.NewCallback(
946 &OutOfProcessInstance::ResetRecentlySentFindUpdate);
947 pp::Module::Get()->core()->CallOnMainThread(kFindResultCooldownMs,
948 callback, 0);
951 void OutOfProcessInstance::NotifySelectedFindResultChanged(
952 int current_find_index) {
953 DCHECK_GE(current_find_index, 0);
954 SelectedFindResultChanged(current_find_index);
957 void OutOfProcessInstance::GetDocumentPassword(
958 pp::CompletionCallbackWithOutput<pp::Var> callback) {
959 if (password_callback_) {
960 NOTREACHED();
961 return;
964 password_callback_.reset(
965 new pp::CompletionCallbackWithOutput<pp::Var>(callback));
966 pp::VarDictionary message;
967 message.Set(pp::Var(kType), pp::Var(kJSGetPasswordType));
968 PostMessage(message);
971 void OutOfProcessInstance::Alert(const std::string& message) {
972 ModalDialog(this, "alert", message, std::string());
975 bool OutOfProcessInstance::Confirm(const std::string& message) {
976 pp::Var result = ModalDialog(this, "confirm", message, std::string());
977 return result.is_bool() ? result.AsBool() : false;
980 std::string OutOfProcessInstance::Prompt(const std::string& question,
981 const std::string& default_answer) {
982 pp::Var result = ModalDialog(this, "prompt", question, default_answer);
983 return result.is_string() ? result.AsString() : std::string();
986 std::string OutOfProcessInstance::GetURL() {
987 return url_;
990 void OutOfProcessInstance::Email(const std::string& to,
991 const std::string& cc,
992 const std::string& bcc,
993 const std::string& subject,
994 const std::string& body) {
995 pp::VarDictionary message;
996 message.Set(pp::Var(kType), pp::Var(kJSEmailType));
997 message.Set(pp::Var(kJSEmailTo),
998 pp::Var(net::EscapeUrlEncodedData(to, false)));
999 message.Set(pp::Var(kJSEmailCc),
1000 pp::Var(net::EscapeUrlEncodedData(cc, false)));
1001 message.Set(pp::Var(kJSEmailBcc),
1002 pp::Var(net::EscapeUrlEncodedData(bcc, false)));
1003 message.Set(pp::Var(kJSEmailSubject),
1004 pp::Var(net::EscapeUrlEncodedData(subject, false)));
1005 message.Set(pp::Var(kJSEmailBody),
1006 pp::Var(net::EscapeUrlEncodedData(body, false)));
1007 PostMessage(message);
1010 void OutOfProcessInstance::Print() {
1011 if (!engine_->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY) &&
1012 !engine_->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY)) {
1013 return;
1016 pp::CompletionCallback callback =
1017 print_callback_factory_.NewCallback(&OutOfProcessInstance::OnPrint);
1018 pp::Module::Get()->core()->CallOnMainThread(0, callback);
1021 void OutOfProcessInstance::OnPrint(int32_t) {
1022 pp::PDF::Print(this);
1025 void OutOfProcessInstance::SubmitForm(const std::string& url,
1026 const void* data,
1027 int length) {
1028 pp::URLRequestInfo request(this);
1029 request.SetURL(url);
1030 request.SetMethod("POST");
1031 request.AppendDataToBody(reinterpret_cast<const char*>(data), length);
1033 pp::CompletionCallback callback =
1034 form_factory_.NewCallback(&OutOfProcessInstance::FormDidOpen);
1035 form_loader_ = CreateURLLoaderInternal();
1036 int rv = form_loader_.Open(request, callback);
1037 if (rv != PP_OK_COMPLETIONPENDING)
1038 callback.Run(rv);
1041 void OutOfProcessInstance::FormDidOpen(int32_t result) {
1042 // TODO: inform the user of success/failure.
1043 if (result != PP_OK) {
1044 NOTREACHED();
1048 std::string OutOfProcessInstance::ShowFileSelectionDialog() {
1049 // Seems like very low priority to implement, since the pdf has no way to get
1050 // the file data anyways. Javascript doesn't let you do this synchronously.
1051 NOTREACHED();
1052 return std::string();
1055 pp::URLLoader OutOfProcessInstance::CreateURLLoader() {
1056 if (full_) {
1057 if (!did_call_start_loading_) {
1058 did_call_start_loading_ = true;
1059 pp::PDF::DidStartLoading(this);
1062 // Disable save and print until the document is fully loaded, since they
1063 // would generate an incomplete document. Need to do this each time we
1064 // call DidStartLoading since that resets the content restrictions.
1065 pp::PDF::SetContentRestriction(this, CONTENT_RESTRICTION_SAVE |
1066 CONTENT_RESTRICTION_PRINT);
1069 return CreateURLLoaderInternal();
1072 void OutOfProcessInstance::ScheduleCallback(int id, int delay_in_ms) {
1073 pp::CompletionCallback callback =
1074 timer_factory_.NewCallback(&OutOfProcessInstance::OnClientTimerFired);
1075 pp::Module::Get()->core()->CallOnMainThread(delay_in_ms, callback, id);
1078 void OutOfProcessInstance::SearchString(const base::char16* string,
1079 const base::char16* term,
1080 bool case_sensitive,
1081 std::vector<SearchStringResult>* results) {
1082 PP_PrivateFindResult* pp_results;
1083 int count = 0;
1084 pp::PDF::SearchString(
1085 this,
1086 reinterpret_cast<const unsigned short*>(string),
1087 reinterpret_cast<const unsigned short*>(term),
1088 case_sensitive,
1089 &pp_results,
1090 &count);
1092 results->resize(count);
1093 for (int i = 0; i < count; ++i) {
1094 (*results)[i].start_index = pp_results[i].start_index;
1095 (*results)[i].length = pp_results[i].length;
1098 pp::Memory_Dev memory;
1099 memory.MemFree(pp_results);
1102 void OutOfProcessInstance::DocumentPaintOccurred() {
1105 void OutOfProcessInstance::DocumentLoadComplete(int page_count) {
1106 // Clear focus state for OSK.
1107 FormTextFieldFocusChange(false);
1109 DCHECK(document_load_state_ == LOAD_STATE_LOADING);
1110 document_load_state_ = LOAD_STATE_COMPLETE;
1111 UserMetricsRecordAction("PDF.LoadSuccess");
1113 // Note: If we are in print preview mode the scroll location is retained
1114 // across document loads so we don't want to scroll again and override it.
1115 if (IsPrintPreview()) {
1116 AppendBlankPrintPreviewPages();
1117 OnGeometryChanged(0, 0);
1120 pp::VarDictionary bookmarks_message;
1121 bookmarks_message.Set(pp::Var(kType), pp::Var(kJSBookmarksType));
1122 bookmarks_message.Set(pp::Var(kJSBookmarks), engine_->GetBookmarks());
1123 PostMessage(bookmarks_message);
1125 pp::VarDictionary progress_message;
1126 progress_message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1127 progress_message.Set(pp::Var(kJSProgressPercentage), pp::Var(100));
1128 PostMessage(progress_message);
1130 if (!full_)
1131 return;
1133 if (did_call_start_loading_) {
1134 pp::PDF::DidStopLoading(this);
1135 did_call_start_loading_ = false;
1138 int content_restrictions =
1139 CONTENT_RESTRICTION_CUT | CONTENT_RESTRICTION_PASTE;
1140 if (!engine_->HasPermission(PDFEngine::PERMISSION_COPY))
1141 content_restrictions |= CONTENT_RESTRICTION_COPY;
1143 pp::PDF::SetContentRestriction(this, content_restrictions);
1145 uma_.HistogramCustomCounts("PDF.PageCount", page_count,
1146 1, 1000000, 50);
1149 void OutOfProcessInstance::RotateClockwise() {
1150 engine_->RotateClockwise();
1153 void OutOfProcessInstance::RotateCounterclockwise() {
1154 engine_->RotateCounterclockwise();
1157 void OutOfProcessInstance::PreviewDocumentLoadComplete() {
1158 if (preview_document_load_state_ != LOAD_STATE_LOADING ||
1159 preview_pages_info_.empty()) {
1160 return;
1163 preview_document_load_state_ = LOAD_STATE_COMPLETE;
1165 int dest_page_index = preview_pages_info_.front().second;
1166 int src_page_index =
1167 ExtractPrintPreviewPageIndex(preview_pages_info_.front().first);
1168 if (src_page_index > 0 && dest_page_index > -1 && preview_engine_.get())
1169 engine_->AppendPage(preview_engine_.get(), dest_page_index);
1171 preview_pages_info_.pop();
1172 // |print_preview_page_count_| is not updated yet. Do not load any
1173 // other preview pages till we get this information.
1174 if (print_preview_page_count_ == 0)
1175 return;
1177 if (preview_pages_info_.size())
1178 LoadAvailablePreviewPage();
1181 void OutOfProcessInstance::DocumentLoadFailed() {
1182 DCHECK(document_load_state_ == LOAD_STATE_LOADING);
1183 UserMetricsRecordAction("PDF.LoadFailure");
1185 if (did_call_start_loading_) {
1186 pp::PDF::DidStopLoading(this);
1187 did_call_start_loading_ = false;
1190 document_load_state_ = LOAD_STATE_FAILED;
1191 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
1193 // Send a progress value of -1 to indicate a failure.
1194 pp::VarDictionary message;
1195 message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1196 message.Set(pp::Var(kJSProgressPercentage), pp::Var(-1));
1197 PostMessage(message);
1200 void OutOfProcessInstance::PreviewDocumentLoadFailed() {
1201 UserMetricsRecordAction("PDF.PreviewDocumentLoadFailure");
1202 if (preview_document_load_state_ != LOAD_STATE_LOADING ||
1203 preview_pages_info_.empty()) {
1204 return;
1207 preview_document_load_state_ = LOAD_STATE_FAILED;
1208 preview_pages_info_.pop();
1210 if (preview_pages_info_.size())
1211 LoadAvailablePreviewPage();
1214 pp::Instance* OutOfProcessInstance::GetPluginInstance() {
1215 return this;
1218 void OutOfProcessInstance::DocumentHasUnsupportedFeature(
1219 const std::string& feature) {
1220 std::string metric("PDF_Unsupported_");
1221 metric += feature;
1222 if (!unsupported_features_reported_.count(metric)) {
1223 unsupported_features_reported_.insert(metric);
1224 UserMetricsRecordAction(metric);
1227 // Since we use an info bar, only do this for full frame plugins..
1228 if (!full_)
1229 return;
1231 if (told_browser_about_unsupported_feature_)
1232 return;
1233 told_browser_about_unsupported_feature_ = true;
1235 pp::PDF::HasUnsupportedFeature(this);
1238 void OutOfProcessInstance::DocumentLoadProgress(uint32 available,
1239 uint32 doc_size) {
1240 double progress = 0.0;
1241 if (doc_size == 0) {
1242 // Document size is unknown. Use heuristics.
1243 // We'll make progress logarithmic from 0 to 100M.
1244 static const double kFactor = log(100000000.0) / 100.0;
1245 if (available > 0) {
1246 progress = log(static_cast<double>(available)) / kFactor;
1247 if (progress > 100.0)
1248 progress = 100.0;
1250 } else {
1251 progress = 100.0 * static_cast<double>(available) / doc_size;
1254 // We send 100% load progress in DocumentLoadComplete.
1255 if (progress >= 100)
1256 return;
1258 // Avoid sending too many progress messages over PostMessage.
1259 if (progress > last_progress_sent_ + 1) {
1260 last_progress_sent_ = progress;
1261 pp::VarDictionary message;
1262 message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1263 message.Set(pp::Var(kJSProgressPercentage), pp::Var(progress));
1264 PostMessage(message);
1268 void OutOfProcessInstance::FormTextFieldFocusChange(bool in_focus) {
1269 if (!text_input_.get())
1270 return;
1271 if (in_focus)
1272 text_input_->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_TEXT);
1273 else
1274 text_input_->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_NONE);
1277 void OutOfProcessInstance::ResetRecentlySentFindUpdate(int32_t /* unused */) {
1278 recently_sent_find_update_ = false;
1281 void OutOfProcessInstance::OnGeometryChanged(double old_zoom,
1282 float old_device_scale) {
1283 if (zoom_ != old_zoom || device_scale_ != old_device_scale)
1284 engine_->ZoomUpdated(zoom_ * device_scale_);
1286 available_area_ = pp::Rect(plugin_size_);
1287 int doc_width = GetDocumentPixelWidth();
1288 if (doc_width < available_area_.width()) {
1289 available_area_.Offset((available_area_.width() - doc_width) / 2, 0);
1290 available_area_.set_width(doc_width);
1292 int doc_height = GetDocumentPixelHeight();
1293 if (doc_height < available_area_.height()) {
1294 available_area_.set_height(doc_height);
1297 CalculateBackgroundParts();
1298 engine_->PageOffsetUpdated(available_area_.point());
1299 engine_->PluginSizeUpdated(available_area_.size());
1301 if (!document_size_.GetArea())
1302 return;
1303 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
1306 void OutOfProcessInstance::LoadUrl(const std::string& url) {
1307 LoadUrlInternal(url, &embed_loader_, &OutOfProcessInstance::DidOpen);
1310 void OutOfProcessInstance::LoadPreviewUrl(const std::string& url) {
1311 LoadUrlInternal(url, &embed_preview_loader_,
1312 &OutOfProcessInstance::DidOpenPreview);
1315 void OutOfProcessInstance::LoadUrlInternal(
1316 const std::string& url,
1317 pp::URLLoader* loader,
1318 void (OutOfProcessInstance::* method)(int32_t)) {
1319 pp::URLRequestInfo request(this);
1320 request.SetURL(url);
1321 request.SetMethod("GET");
1323 *loader = CreateURLLoaderInternal();
1324 pp::CompletionCallback callback = loader_factory_.NewCallback(method);
1325 int rv = loader->Open(request, callback);
1326 if (rv != PP_OK_COMPLETIONPENDING)
1327 callback.Run(rv);
1330 pp::URLLoader OutOfProcessInstance::CreateURLLoaderInternal() {
1331 pp::URLLoader loader(this);
1333 const PPB_URLLoaderTrusted* trusted_interface =
1334 reinterpret_cast<const PPB_URLLoaderTrusted*>(
1335 pp::Module::Get()->GetBrowserInterface(
1336 PPB_URLLOADERTRUSTED_INTERFACE));
1337 if (trusted_interface)
1338 trusted_interface->GrantUniversalAccess(loader.pp_resource());
1339 return loader;
1342 void OutOfProcessInstance::SetZoom(double scale) {
1343 double old_zoom = zoom_;
1344 zoom_ = scale;
1345 OnGeometryChanged(old_zoom, device_scale_);
1348 std::string OutOfProcessInstance::GetLocalizedString(PP_ResourceString id) {
1349 pp::Var rv(pp::PDF::GetLocalizedString(this, id));
1350 if (!rv.is_string())
1351 return std::string();
1353 return rv.AsString();
1356 void OutOfProcessInstance::AppendBlankPrintPreviewPages() {
1357 if (print_preview_page_count_ == 0)
1358 return;
1359 engine_->AppendBlankPages(print_preview_page_count_);
1360 if (preview_pages_info_.size() > 0)
1361 LoadAvailablePreviewPage();
1364 bool OutOfProcessInstance::IsPrintPreview() {
1365 return IsPrintPreviewUrl(url_);
1368 uint32 OutOfProcessInstance::GetBackgroundColor() {
1369 return background_color_;
1372 void OutOfProcessInstance::IsSelectingChanged(bool is_selecting) {
1373 pp::VarDictionary message;
1374 message.Set(kType, kJSSetIsSelectingType);
1375 message.Set(kJSIsSelecting, pp::Var(is_selecting));
1376 PostMessage(message);
1379 void OutOfProcessInstance::ProcessPreviewPageInfo(const std::string& url,
1380 int dst_page_index) {
1381 if (!IsPrintPreview())
1382 return;
1384 int src_page_index = ExtractPrintPreviewPageIndex(url);
1385 if (src_page_index < 1)
1386 return;
1388 preview_pages_info_.push(std::make_pair(url, dst_page_index));
1389 LoadAvailablePreviewPage();
1392 void OutOfProcessInstance::LoadAvailablePreviewPage() {
1393 if (preview_pages_info_.size() <= 0 ||
1394 document_load_state_ != LOAD_STATE_COMPLETE) {
1395 return;
1398 std::string url = preview_pages_info_.front().first;
1399 int dst_page_index = preview_pages_info_.front().second;
1400 int src_page_index = ExtractPrintPreviewPageIndex(url);
1401 if (src_page_index < 1 ||
1402 dst_page_index >= print_preview_page_count_ ||
1403 preview_document_load_state_ == LOAD_STATE_LOADING) {
1404 return;
1407 preview_document_load_state_ = LOAD_STATE_LOADING;
1408 LoadPreviewUrl(url);
1411 void OutOfProcessInstance::UserMetricsRecordAction(
1412 const std::string& action) {
1413 // TODO(raymes): Move this function to PPB_UMA_Private.
1414 pp::PDF::UserMetricsRecordAction(this, pp::Var(action));
1417 pp::FloatPoint OutOfProcessInstance::BoundScrollOffsetToDocument(
1418 const pp::FloatPoint& scroll_offset) {
1419 float max_x = document_size_.width() * zoom_ - plugin_dip_size_.width();
1420 float x = std::max(std::min(scroll_offset.x(), max_x), 0.0f);
1421 float max_y = document_size_.height() * zoom_ - plugin_dip_size_.height();
1422 float y = std::max(std::min(scroll_offset.y(), max_y), 0.0f);
1423 return pp::FloatPoint(x, y);
1426 } // namespace chrome_pdf