Revert of Add support for escaped target names in isolate driver. (patchset #6 id...
[chromium-blink-merge.git] / pdf / out_of_process_instance.cc
blobf40582d65dcd6ee21b51a64c76a4d37123625693
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();
615 pp::Var OutOfProcessInstance::GetLinkAtPosition(
616 const pp::Point& point) {
617 pp::Point offset_point(point);
618 ScalePoint(device_scale_, &offset_point);
619 offset_point.set_x(offset_point.x() - available_area_.x());
620 return engine_->GetLinkAtPosition(offset_point);
623 pp::Var OutOfProcessInstance::GetSelectedText(bool html) {
624 if (html)
625 return pp::Var();
626 return engine_->GetSelectedText();
629 uint32_t OutOfProcessInstance::QuerySupportedPrintOutputFormats() {
630 return engine_->QuerySupportedPrintOutputFormats();
633 int32_t OutOfProcessInstance::PrintBegin(
634 const PP_PrintSettings_Dev& print_settings) {
635 // For us num_pages is always equal to the number of pages in the PDF
636 // document irrespective of the printable area.
637 int32_t ret = engine_->GetNumberOfPages();
638 if (!ret)
639 return 0;
641 uint32_t supported_formats = engine_->QuerySupportedPrintOutputFormats();
642 if ((print_settings.format & supported_formats) == 0)
643 return 0;
645 print_settings_.is_printing = true;
646 print_settings_.pepper_print_settings = print_settings;
647 engine_->PrintBegin();
648 return ret;
651 pp::Resource OutOfProcessInstance::PrintPages(
652 const PP_PrintPageNumberRange_Dev* page_ranges,
653 uint32_t page_range_count) {
654 if (!print_settings_.is_printing)
655 return pp::Resource();
657 print_settings_.print_pages_called_ = true;
658 return engine_->PrintPages(page_ranges, page_range_count,
659 print_settings_.pepper_print_settings);
662 void OutOfProcessInstance::PrintEnd() {
663 if (print_settings_.print_pages_called_)
664 UserMetricsRecordAction("PDF.PrintPage");
665 print_settings_.Clear();
666 engine_->PrintEnd();
669 bool OutOfProcessInstance::IsPrintScalingDisabled() {
670 return !engine_->GetPrintScaling();
673 bool OutOfProcessInstance::StartFind(const std::string& text,
674 bool case_sensitive) {
675 engine_->StartFind(text.c_str(), case_sensitive);
676 return true;
679 void OutOfProcessInstance::SelectFindResult(bool forward) {
680 engine_->SelectFindResult(forward);
683 void OutOfProcessInstance::StopFind() {
684 engine_->StopFind();
685 tickmarks_.clear();
686 SetTickmarks(tickmarks_);
689 void OutOfProcessInstance::OnPaint(
690 const std::vector<pp::Rect>& paint_rects,
691 std::vector<PaintManager::ReadyRect>* ready,
692 std::vector<pp::Rect>* pending) {
693 if (image_data_.is_null()) {
694 DCHECK(plugin_size_.IsEmpty());
695 return;
697 if (first_paint_) {
698 first_paint_ = false;
699 pp::Rect rect = pp::Rect(pp::Point(), image_data_.size());
700 FillRect(rect, background_color_);
701 ready->push_back(PaintManager::ReadyRect(rect, image_data_, true));
704 if (!received_viewport_message_)
705 return;
707 engine_->PrePaint();
709 for (size_t i = 0; i < paint_rects.size(); i++) {
710 // Intersect with plugin area since there could be pending invalidates from
711 // when the plugin area was larger.
712 pp::Rect rect =
713 paint_rects[i].Intersect(pp::Rect(pp::Point(), plugin_size_));
714 if (rect.IsEmpty())
715 continue;
717 pp::Rect pdf_rect = available_area_.Intersect(rect);
718 if (!pdf_rect.IsEmpty()) {
719 pdf_rect.Offset(available_area_.x() * -1, 0);
721 std::vector<pp::Rect> pdf_ready;
722 std::vector<pp::Rect> pdf_pending;
723 engine_->Paint(pdf_rect, &image_data_, &pdf_ready, &pdf_pending);
724 for (size_t j = 0; j < pdf_ready.size(); ++j) {
725 pdf_ready[j].Offset(available_area_.point());
726 ready->push_back(
727 PaintManager::ReadyRect(pdf_ready[j], image_data_, false));
729 for (size_t j = 0; j < pdf_pending.size(); ++j) {
730 pdf_pending[j].Offset(available_area_.point());
731 pending->push_back(pdf_pending[j]);
735 for (size_t j = 0; j < background_parts_.size(); ++j) {
736 pp::Rect intersection = background_parts_[j].location.Intersect(rect);
737 if (!intersection.IsEmpty()) {
738 FillRect(intersection, background_parts_[j].color);
739 ready->push_back(
740 PaintManager::ReadyRect(intersection, image_data_, false));
745 engine_->PostPaint();
748 void OutOfProcessInstance::DidOpen(int32_t result) {
749 if (result == PP_OK) {
750 if (!engine_->HandleDocumentLoad(embed_loader_)) {
751 document_load_state_ = LOAD_STATE_LOADING;
752 DocumentLoadFailed();
754 } else if (result != PP_ERROR_ABORTED) { // Can happen in tests.
755 NOTREACHED();
756 DocumentLoadFailed();
759 // If it's a progressive load, cancel the stream URL request so that requests
760 // can be made on the original URL.
761 // TODO(raymes): Make this clearer once the in-process plugin is deleted.
762 if (engine_->IsProgressiveLoad()) {
763 pp::VarDictionary message;
764 message.Set(kType, kJSCancelStreamUrlType);
765 PostMessage(message);
769 void OutOfProcessInstance::DidOpenPreview(int32_t result) {
770 if (result == PP_OK) {
771 preview_engine_.reset(PDFEngine::Create(new PreviewModeClient(this)));
772 preview_engine_->HandleDocumentLoad(embed_preview_loader_);
773 } else {
774 NOTREACHED();
778 void OutOfProcessInstance::OnClientTimerFired(int32_t id) {
779 engine_->OnCallback(id);
782 void OutOfProcessInstance::CalculateBackgroundParts() {
783 background_parts_.clear();
784 int left_width = available_area_.x();
785 int right_start = available_area_.right();
786 int right_width = abs(plugin_size_.width() - available_area_.right());
787 int bottom = std::min(available_area_.bottom(), plugin_size_.height());
789 // Add the left, right, and bottom rectangles. Note: we assume only
790 // horizontal centering.
791 BackgroundPart part = {
792 pp::Rect(0, 0, left_width, bottom),
793 background_color_
795 if (!part.location.IsEmpty())
796 background_parts_.push_back(part);
797 part.location = pp::Rect(right_start, 0, right_width, bottom);
798 if (!part.location.IsEmpty())
799 background_parts_.push_back(part);
800 part.location = pp::Rect(
801 0, bottom, plugin_size_.width(), plugin_size_.height() - bottom);
802 if (!part.location.IsEmpty())
803 background_parts_.push_back(part);
806 int OutOfProcessInstance::GetDocumentPixelWidth() const {
807 return static_cast<int>(ceil(document_size_.width() * zoom_ * device_scale_));
810 int OutOfProcessInstance::GetDocumentPixelHeight() const {
811 return static_cast<int>(
812 ceil(document_size_.height() * zoom_ * device_scale_));
815 void OutOfProcessInstance::FillRect(const pp::Rect& rect, uint32 color) {
816 DCHECK(!image_data_.is_null() || rect.IsEmpty());
817 uint32* buffer_start = static_cast<uint32*>(image_data_.data());
818 int stride = image_data_.stride();
819 uint32* ptr = buffer_start + rect.y() * stride / 4 + rect.x();
820 int height = rect.height();
821 int width = rect.width();
822 for (int y = 0; y < height; ++y) {
823 for (int x = 0; x < width; ++x)
824 *(ptr + x) = color;
825 ptr += stride /4;
829 void OutOfProcessInstance::DocumentSizeUpdated(const pp::Size& size) {
830 document_size_ = size;
832 pp::VarDictionary dimensions;
833 dimensions.Set(kType, kJSDocumentDimensionsType);
834 dimensions.Set(kJSDocumentWidth, pp::Var(document_size_.width()));
835 dimensions.Set(kJSDocumentHeight, pp::Var(document_size_.height()));
836 pp::VarArray page_dimensions_array;
837 int num_pages = engine_->GetNumberOfPages();
838 for (int i = 0; i < num_pages; ++i) {
839 pp::Rect page_rect = engine_->GetPageRect(i);
840 pp::VarDictionary page_dimensions;
841 page_dimensions.Set(kJSPageX, pp::Var(page_rect.x()));
842 page_dimensions.Set(kJSPageY, pp::Var(page_rect.y()));
843 page_dimensions.Set(kJSPageWidth, pp::Var(page_rect.width()));
844 page_dimensions.Set(kJSPageHeight, pp::Var(page_rect.height()));
845 page_dimensions_array.Set(i, page_dimensions);
847 dimensions.Set(kJSPageDimensions, page_dimensions_array);
848 PostMessage(dimensions);
850 OnGeometryChanged(zoom_, device_scale_);
853 void OutOfProcessInstance::Invalidate(const pp::Rect& rect) {
854 pp::Rect offset_rect(rect);
855 offset_rect.Offset(available_area_.point());
856 paint_manager_.InvalidateRect(offset_rect);
859 void OutOfProcessInstance::Scroll(const pp::Point& point) {
860 if (!image_data_.is_null())
861 paint_manager_.ScrollRect(available_area_, point);
864 void OutOfProcessInstance::ScrollToX(int x) {
865 pp::VarDictionary position;
866 position.Set(kType, kJSSetScrollPositionType);
867 position.Set(kJSPositionX, pp::Var(x / device_scale_));
868 PostMessage(position);
871 void OutOfProcessInstance::ScrollToY(int y) {
872 pp::VarDictionary position;
873 position.Set(kType, kJSSetScrollPositionType);
874 position.Set(kJSPositionY, pp::Var(y / device_scale_));
875 PostMessage(position);
878 void OutOfProcessInstance::ScrollToPage(int page) {
879 if (engine_->GetNumberOfPages() == 0)
880 return;
882 pp::VarDictionary message;
883 message.Set(kType, kJSGoToPageType);
884 message.Set(kJSPageNumber, pp::Var(page));
885 PostMessage(message);
888 void OutOfProcessInstance::NavigateTo(const std::string& url,
889 bool open_in_new_tab) {
890 pp::VarDictionary message;
891 message.Set(kType, kJSNavigateType);
892 message.Set(kJSNavigateUrl, url);
893 message.Set(kJSNavigateNewTab, open_in_new_tab);
894 PostMessage(message);
897 void OutOfProcessInstance::UpdateCursor(PP_CursorType_Dev cursor) {
898 if (cursor == cursor_)
899 return;
900 cursor_ = cursor;
902 const PPB_CursorControl_Dev* cursor_interface =
903 reinterpret_cast<const PPB_CursorControl_Dev*>(
904 pp::Module::Get()->GetBrowserInterface(PPB_CURSOR_CONTROL_DEV_INTERFACE));
905 if (!cursor_interface) {
906 NOTREACHED();
907 return;
910 cursor_interface->SetCursor(
911 pp_instance(), cursor_, pp::ImageData().pp_resource(), NULL);
914 void OutOfProcessInstance::UpdateTickMarks(
915 const std::vector<pp::Rect>& tickmarks) {
916 float inverse_scale = 1.0f / device_scale_;
917 std::vector<pp::Rect> scaled_tickmarks = tickmarks;
918 for (size_t i = 0; i < scaled_tickmarks.size(); i++)
919 ScaleRect(inverse_scale, &scaled_tickmarks[i]);
920 tickmarks_ = scaled_tickmarks;
923 void OutOfProcessInstance::NotifyNumberOfFindResultsChanged(int total,
924 bool final_result) {
925 // We don't want to spam the renderer with too many updates to the number of
926 // find results. Don't send an update if we sent one too recently. If it's the
927 // final update, we always send it though.
928 if (final_result) {
929 NumberOfFindResultsChanged(total, final_result);
930 SetTickmarks(tickmarks_);
931 return;
934 if (recently_sent_find_update_)
935 return;
937 NumberOfFindResultsChanged(total, final_result);
938 SetTickmarks(tickmarks_);
939 recently_sent_find_update_ = true;
940 pp::CompletionCallback callback =
941 timer_factory_.NewCallback(
942 &OutOfProcessInstance::ResetRecentlySentFindUpdate);
943 pp::Module::Get()->core()->CallOnMainThread(kFindResultCooldownMs,
944 callback, 0);
947 void OutOfProcessInstance::NotifySelectedFindResultChanged(
948 int current_find_index) {
949 DCHECK_GE(current_find_index, 0);
950 SelectedFindResultChanged(current_find_index);
953 void OutOfProcessInstance::GetDocumentPassword(
954 pp::CompletionCallbackWithOutput<pp::Var> callback) {
955 if (password_callback_) {
956 NOTREACHED();
957 return;
960 password_callback_.reset(
961 new pp::CompletionCallbackWithOutput<pp::Var>(callback));
962 pp::VarDictionary message;
963 message.Set(pp::Var(kType), pp::Var(kJSGetPasswordType));
964 PostMessage(message);
967 void OutOfProcessInstance::Alert(const std::string& message) {
968 ModalDialog(this, "alert", message, std::string());
971 bool OutOfProcessInstance::Confirm(const std::string& message) {
972 pp::Var result = ModalDialog(this, "confirm", message, std::string());
973 return result.is_bool() ? result.AsBool() : false;
976 std::string OutOfProcessInstance::Prompt(const std::string& question,
977 const std::string& default_answer) {
978 pp::Var result = ModalDialog(this, "prompt", question, default_answer);
979 return result.is_string() ? result.AsString() : std::string();
982 std::string OutOfProcessInstance::GetURL() {
983 return url_;
986 void OutOfProcessInstance::Email(const std::string& to,
987 const std::string& cc,
988 const std::string& bcc,
989 const std::string& subject,
990 const std::string& body) {
991 pp::VarDictionary message;
992 message.Set(pp::Var(kType), pp::Var(kJSEmailType));
993 message.Set(pp::Var(kJSEmailTo),
994 pp::Var(net::EscapeUrlEncodedData(to, false)));
995 message.Set(pp::Var(kJSEmailCc),
996 pp::Var(net::EscapeUrlEncodedData(cc, false)));
997 message.Set(pp::Var(kJSEmailBcc),
998 pp::Var(net::EscapeUrlEncodedData(bcc, false)));
999 message.Set(pp::Var(kJSEmailSubject),
1000 pp::Var(net::EscapeUrlEncodedData(subject, false)));
1001 message.Set(pp::Var(kJSEmailBody),
1002 pp::Var(net::EscapeUrlEncodedData(body, false)));
1003 PostMessage(message);
1006 void OutOfProcessInstance::Print() {
1007 if (!engine_->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY) &&
1008 !engine_->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY)) {
1009 return;
1012 pp::CompletionCallback callback =
1013 print_callback_factory_.NewCallback(&OutOfProcessInstance::OnPrint);
1014 pp::Module::Get()->core()->CallOnMainThread(0, callback);
1017 void OutOfProcessInstance::OnPrint(int32_t) {
1018 pp::PDF::Print(this);
1021 void OutOfProcessInstance::SubmitForm(const std::string& url,
1022 const void* data,
1023 int length) {
1024 pp::URLRequestInfo request(this);
1025 request.SetURL(url);
1026 request.SetMethod("POST");
1027 request.AppendDataToBody(reinterpret_cast<const char*>(data), length);
1029 pp::CompletionCallback callback =
1030 form_factory_.NewCallback(&OutOfProcessInstance::FormDidOpen);
1031 form_loader_ = CreateURLLoaderInternal();
1032 int rv = form_loader_.Open(request, callback);
1033 if (rv != PP_OK_COMPLETIONPENDING)
1034 callback.Run(rv);
1037 void OutOfProcessInstance::FormDidOpen(int32_t result) {
1038 // TODO: inform the user of success/failure.
1039 if (result != PP_OK) {
1040 NOTREACHED();
1044 std::string OutOfProcessInstance::ShowFileSelectionDialog() {
1045 // Seems like very low priority to implement, since the pdf has no way to get
1046 // the file data anyways. Javascript doesn't let you do this synchronously.
1047 NOTREACHED();
1048 return std::string();
1051 pp::URLLoader OutOfProcessInstance::CreateURLLoader() {
1052 if (full_) {
1053 if (!did_call_start_loading_) {
1054 did_call_start_loading_ = true;
1055 pp::PDF::DidStartLoading(this);
1058 // Disable save and print until the document is fully loaded, since they
1059 // would generate an incomplete document. Need to do this each time we
1060 // call DidStartLoading since that resets the content restrictions.
1061 pp::PDF::SetContentRestriction(this, CONTENT_RESTRICTION_SAVE |
1062 CONTENT_RESTRICTION_PRINT);
1065 return CreateURLLoaderInternal();
1068 void OutOfProcessInstance::ScheduleCallback(int id, int delay_in_ms) {
1069 pp::CompletionCallback callback =
1070 timer_factory_.NewCallback(&OutOfProcessInstance::OnClientTimerFired);
1071 pp::Module::Get()->core()->CallOnMainThread(delay_in_ms, callback, id);
1074 void OutOfProcessInstance::SearchString(const base::char16* string,
1075 const base::char16* term,
1076 bool case_sensitive,
1077 std::vector<SearchStringResult>* results) {
1078 PP_PrivateFindResult* pp_results;
1079 int count = 0;
1080 pp::PDF::SearchString(
1081 this,
1082 reinterpret_cast<const unsigned short*>(string),
1083 reinterpret_cast<const unsigned short*>(term),
1084 case_sensitive,
1085 &pp_results,
1086 &count);
1088 results->resize(count);
1089 for (int i = 0; i < count; ++i) {
1090 (*results)[i].start_index = pp_results[i].start_index;
1091 (*results)[i].length = pp_results[i].length;
1094 pp::Memory_Dev memory;
1095 memory.MemFree(pp_results);
1098 void OutOfProcessInstance::DocumentPaintOccurred() {
1101 void OutOfProcessInstance::DocumentLoadComplete(int page_count) {
1102 // Clear focus state for OSK.
1103 FormTextFieldFocusChange(false);
1105 DCHECK(document_load_state_ == LOAD_STATE_LOADING);
1106 document_load_state_ = LOAD_STATE_COMPLETE;
1107 UserMetricsRecordAction("PDF.LoadSuccess");
1109 // Note: If we are in print preview mode the scroll location is retained
1110 // across document loads so we don't want to scroll again and override it.
1111 if (IsPrintPreview()) {
1112 AppendBlankPrintPreviewPages();
1113 OnGeometryChanged(0, 0);
1116 pp::VarDictionary bookmarks_message;
1117 bookmarks_message.Set(pp::Var(kType), pp::Var(kJSBookmarksType));
1118 bookmarks_message.Set(pp::Var(kJSBookmarks), engine_->GetBookmarks());
1119 PostMessage(bookmarks_message);
1121 pp::VarDictionary progress_message;
1122 progress_message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1123 progress_message.Set(pp::Var(kJSProgressPercentage), pp::Var(100));
1124 PostMessage(progress_message);
1126 if (!full_)
1127 return;
1129 if (did_call_start_loading_) {
1130 pp::PDF::DidStopLoading(this);
1131 did_call_start_loading_ = false;
1134 int content_restrictions =
1135 CONTENT_RESTRICTION_CUT | CONTENT_RESTRICTION_PASTE;
1136 if (!engine_->HasPermission(PDFEngine::PERMISSION_COPY))
1137 content_restrictions |= CONTENT_RESTRICTION_COPY;
1139 pp::PDF::SetContentRestriction(this, content_restrictions);
1141 uma_.HistogramCustomCounts("PDF.PageCount", page_count,
1142 1, 1000000, 50);
1145 void OutOfProcessInstance::RotateClockwise() {
1146 engine_->RotateClockwise();
1149 void OutOfProcessInstance::RotateCounterclockwise() {
1150 engine_->RotateCounterclockwise();
1153 void OutOfProcessInstance::PreviewDocumentLoadComplete() {
1154 if (preview_document_load_state_ != LOAD_STATE_LOADING ||
1155 preview_pages_info_.empty()) {
1156 return;
1159 preview_document_load_state_ = LOAD_STATE_COMPLETE;
1161 int dest_page_index = preview_pages_info_.front().second;
1162 int src_page_index =
1163 ExtractPrintPreviewPageIndex(preview_pages_info_.front().first);
1164 if (src_page_index > 0 && dest_page_index > -1 && preview_engine_.get())
1165 engine_->AppendPage(preview_engine_.get(), dest_page_index);
1167 preview_pages_info_.pop();
1168 // |print_preview_page_count_| is not updated yet. Do not load any
1169 // other preview pages till we get this information.
1170 if (print_preview_page_count_ == 0)
1171 return;
1173 if (preview_pages_info_.size())
1174 LoadAvailablePreviewPage();
1177 void OutOfProcessInstance::DocumentLoadFailed() {
1178 DCHECK(document_load_state_ == LOAD_STATE_LOADING);
1179 UserMetricsRecordAction("PDF.LoadFailure");
1181 if (did_call_start_loading_) {
1182 pp::PDF::DidStopLoading(this);
1183 did_call_start_loading_ = false;
1186 document_load_state_ = LOAD_STATE_FAILED;
1187 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
1189 // Send a progress value of -1 to indicate a failure.
1190 pp::VarDictionary message;
1191 message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1192 message.Set(pp::Var(kJSProgressPercentage), pp::Var(-1));
1193 PostMessage(message);
1196 void OutOfProcessInstance::PreviewDocumentLoadFailed() {
1197 UserMetricsRecordAction("PDF.PreviewDocumentLoadFailure");
1198 if (preview_document_load_state_ != LOAD_STATE_LOADING ||
1199 preview_pages_info_.empty()) {
1200 return;
1203 preview_document_load_state_ = LOAD_STATE_FAILED;
1204 preview_pages_info_.pop();
1206 if (preview_pages_info_.size())
1207 LoadAvailablePreviewPage();
1210 pp::Instance* OutOfProcessInstance::GetPluginInstance() {
1211 return this;
1214 void OutOfProcessInstance::DocumentHasUnsupportedFeature(
1215 const std::string& feature) {
1216 std::string metric("PDF_Unsupported_");
1217 metric += feature;
1218 if (!unsupported_features_reported_.count(metric)) {
1219 unsupported_features_reported_.insert(metric);
1220 UserMetricsRecordAction(metric);
1223 // Since we use an info bar, only do this for full frame plugins..
1224 if (!full_)
1225 return;
1227 if (told_browser_about_unsupported_feature_)
1228 return;
1229 told_browser_about_unsupported_feature_ = true;
1231 pp::PDF::HasUnsupportedFeature(this);
1234 void OutOfProcessInstance::DocumentLoadProgress(uint32 available,
1235 uint32 doc_size) {
1236 double progress = 0.0;
1237 if (doc_size == 0) {
1238 // Document size is unknown. Use heuristics.
1239 // We'll make progress logarithmic from 0 to 100M.
1240 static const double kFactor = log(100000000.0) / 100.0;
1241 if (available > 0) {
1242 progress = log(static_cast<double>(available)) / kFactor;
1243 if (progress > 100.0)
1244 progress = 100.0;
1246 } else {
1247 progress = 100.0 * static_cast<double>(available) / doc_size;
1250 // We send 100% load progress in DocumentLoadComplete.
1251 if (progress >= 100)
1252 return;
1254 // Avoid sending too many progress messages over PostMessage.
1255 if (progress > last_progress_sent_ + 1) {
1256 last_progress_sent_ = progress;
1257 pp::VarDictionary message;
1258 message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1259 message.Set(pp::Var(kJSProgressPercentage), pp::Var(progress));
1260 PostMessage(message);
1264 void OutOfProcessInstance::FormTextFieldFocusChange(bool in_focus) {
1265 if (!text_input_.get())
1266 return;
1267 if (in_focus)
1268 text_input_->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_TEXT);
1269 else
1270 text_input_->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_NONE);
1273 void OutOfProcessInstance::ResetRecentlySentFindUpdate(int32_t /* unused */) {
1274 recently_sent_find_update_ = false;
1277 void OutOfProcessInstance::OnGeometryChanged(double old_zoom,
1278 float old_device_scale) {
1279 if (zoom_ != old_zoom || device_scale_ != old_device_scale)
1280 engine_->ZoomUpdated(zoom_ * device_scale_);
1282 available_area_ = pp::Rect(plugin_size_);
1283 int doc_width = GetDocumentPixelWidth();
1284 if (doc_width < available_area_.width()) {
1285 available_area_.Offset((available_area_.width() - doc_width) / 2, 0);
1286 available_area_.set_width(doc_width);
1288 int doc_height = GetDocumentPixelHeight();
1289 if (doc_height < available_area_.height()) {
1290 available_area_.set_height(doc_height);
1293 CalculateBackgroundParts();
1294 engine_->PageOffsetUpdated(available_area_.point());
1295 engine_->PluginSizeUpdated(available_area_.size());
1297 if (!document_size_.GetArea())
1298 return;
1299 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
1302 void OutOfProcessInstance::LoadUrl(const std::string& url) {
1303 LoadUrlInternal(url, &embed_loader_, &OutOfProcessInstance::DidOpen);
1306 void OutOfProcessInstance::LoadPreviewUrl(const std::string& url) {
1307 LoadUrlInternal(url, &embed_preview_loader_,
1308 &OutOfProcessInstance::DidOpenPreview);
1311 void OutOfProcessInstance::LoadUrlInternal(
1312 const std::string& url,
1313 pp::URLLoader* loader,
1314 void (OutOfProcessInstance::* method)(int32_t)) {
1315 pp::URLRequestInfo request(this);
1316 request.SetURL(url);
1317 request.SetMethod("GET");
1319 *loader = CreateURLLoaderInternal();
1320 pp::CompletionCallback callback = loader_factory_.NewCallback(method);
1321 int rv = loader->Open(request, callback);
1322 if (rv != PP_OK_COMPLETIONPENDING)
1323 callback.Run(rv);
1326 pp::URLLoader OutOfProcessInstance::CreateURLLoaderInternal() {
1327 pp::URLLoader loader(this);
1329 const PPB_URLLoaderTrusted* trusted_interface =
1330 reinterpret_cast<const PPB_URLLoaderTrusted*>(
1331 pp::Module::Get()->GetBrowserInterface(
1332 PPB_URLLOADERTRUSTED_INTERFACE));
1333 if (trusted_interface)
1334 trusted_interface->GrantUniversalAccess(loader.pp_resource());
1335 return loader;
1338 void OutOfProcessInstance::SetZoom(double scale) {
1339 double old_zoom = zoom_;
1340 zoom_ = scale;
1341 OnGeometryChanged(old_zoom, device_scale_);
1344 std::string OutOfProcessInstance::GetLocalizedString(PP_ResourceString id) {
1345 pp::Var rv(pp::PDF::GetLocalizedString(this, id));
1346 if (!rv.is_string())
1347 return std::string();
1349 return rv.AsString();
1352 void OutOfProcessInstance::AppendBlankPrintPreviewPages() {
1353 if (print_preview_page_count_ == 0)
1354 return;
1355 engine_->AppendBlankPages(print_preview_page_count_);
1356 if (preview_pages_info_.size() > 0)
1357 LoadAvailablePreviewPage();
1360 bool OutOfProcessInstance::IsPrintPreview() {
1361 return IsPrintPreviewUrl(url_);
1364 uint32 OutOfProcessInstance::GetBackgroundColor() {
1365 return background_color_;
1368 void OutOfProcessInstance::IsSelectingChanged(bool is_selecting) {
1369 pp::VarDictionary message;
1370 message.Set(kType, kJSSetIsSelectingType);
1371 message.Set(kJSIsSelecting, pp::Var(is_selecting));
1372 PostMessage(message);
1375 void OutOfProcessInstance::ProcessPreviewPageInfo(const std::string& url,
1376 int dst_page_index) {
1377 if (!IsPrintPreview())
1378 return;
1380 int src_page_index = ExtractPrintPreviewPageIndex(url);
1381 if (src_page_index < 1)
1382 return;
1384 preview_pages_info_.push(std::make_pair(url, dst_page_index));
1385 LoadAvailablePreviewPage();
1388 void OutOfProcessInstance::LoadAvailablePreviewPage() {
1389 if (preview_pages_info_.size() <= 0 ||
1390 document_load_state_ != LOAD_STATE_COMPLETE) {
1391 return;
1394 std::string url = preview_pages_info_.front().first;
1395 int dst_page_index = preview_pages_info_.front().second;
1396 int src_page_index = ExtractPrintPreviewPageIndex(url);
1397 if (src_page_index < 1 ||
1398 dst_page_index >= print_preview_page_count_ ||
1399 preview_document_load_state_ == LOAD_STATE_LOADING) {
1400 return;
1403 preview_document_load_state_ = LOAD_STATE_LOADING;
1404 LoadPreviewUrl(url);
1407 void OutOfProcessInstance::UserMetricsRecordAction(
1408 const std::string& action) {
1409 // TODO(raymes): Move this function to PPB_UMA_Private.
1410 pp::PDF::UserMetricsRecordAction(this, pp::Var(action));
1413 pp::FloatPoint OutOfProcessInstance::BoundScrollOffsetToDocument(
1414 const pp::FloatPoint& scroll_offset) {
1415 float max_x = document_size_.width() * zoom_ - plugin_dip_size_.width();
1416 float x = std::max(std::min(scroll_offset.x(), max_x), 0.0f);
1417 float max_y = document_size_.height() * zoom_ - plugin_dip_size_.height();
1418 float y = std::max(std::min(scroll_offset.y(), max_y), 0.0f);
1419 return pp::FloatPoint(x, y);
1422 } // namespace chrome_pdf