[Storage] Blob Storage Refactoring pt 1:
[chromium-blink-merge.git] / pdf / out_of_process_instance.cc
blobd6ad71adb6724a9ac7ac9a622c22e612de183aff
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 // Constants used in handling postMessage() messages.
56 const char kType[] = "type";
57 // Viewport message arguments. (Page -> Plugin).
58 const char kJSViewportType[] = "viewport";
59 const char kJSXOffset[] = "xOffset";
60 const char kJSYOffset[] = "yOffset";
61 const char kJSZoom[] = "zoom";
62 // Stop scrolling message (Page -> Plugin)
63 const char kJSStopScrollingType[] = "stopScrolling";
64 // Document dimension arguments (Plugin -> Page).
65 const char kJSDocumentDimensionsType[] = "documentDimensions";
66 const char kJSDocumentWidth[] = "width";
67 const char kJSDocumentHeight[] = "height";
68 const char kJSPageDimensions[] = "pageDimensions";
69 const char kJSPageX[] = "x";
70 const char kJSPageY[] = "y";
71 const char kJSPageWidth[] = "width";
72 const char kJSPageHeight[] = "height";
73 // Document load progress arguments (Plugin -> Page)
74 const char kJSLoadProgressType[] = "loadProgress";
75 const char kJSProgressPercentage[] = "progress";
76 // Bookmarks
77 const char kJSBookmarksType[] = "bookmarks";
78 const char kJSBookmarks[] = "bookmarks";
79 // Get password arguments (Plugin -> Page)
80 const char kJSGetPasswordType[] = "getPassword";
81 // Get password complete arguments (Page -> Plugin)
82 const char kJSGetPasswordCompleteType[] = "getPasswordComplete";
83 const char kJSPassword[] = "password";
84 // Print (Page -> Plugin)
85 const char kJSPrintType[] = "print";
86 // Save (Page -> Plugin)
87 const char kJSSaveType[] = "save";
88 // Go to page (Plugin -> Page)
89 const char kJSGoToPageType[] = "goToPage";
90 const char kJSPageNumber[] = "page";
91 // Reset print preview mode (Page -> Plugin)
92 const char kJSResetPrintPreviewModeType[] = "resetPrintPreviewMode";
93 const char kJSPrintPreviewUrl[] = "url";
94 const char kJSPrintPreviewGrayscale[] = "grayscale";
95 const char kJSPrintPreviewPageCount[] = "pageCount";
96 // Load preview page (Page -> Plugin)
97 const char kJSLoadPreviewPageType[] = "loadPreviewPage";
98 const char kJSPreviewPageUrl[] = "url";
99 const char kJSPreviewPageIndex[] = "index";
100 // Set scroll position (Plugin -> Page)
101 const char kJSSetScrollPositionType[] = "setScrollPosition";
102 const char kJSPositionX[] = "x";
103 const char kJSPositionY[] = "y";
104 // Set translated strings (Plugin -> Page)
105 const char kJSSetTranslatedStringsType[] = "setTranslatedStrings";
106 const char kJSGetPasswordString[] = "getPasswordString";
107 const char kJSLoadingString[] = "loadingString";
108 const char kJSLoadFailedString[] = "loadFailedString";
109 // Request accessibility JSON data (Page -> Plugin)
110 const char kJSGetAccessibilityJSONType[] = "getAccessibilityJSON";
111 const char kJSAccessibilityPageNumber[] = "page";
112 // Reply with accessibility JSON data (Plugin -> Page)
113 const char kJSGetAccessibilityJSONReplyType[] = "getAccessibilityJSONReply";
114 const char kJSAccessibilityJSON[] = "json";
115 // Cancel the stream URL request (Plugin -> Page)
116 const char kJSCancelStreamUrlType[] = "cancelStreamUrl";
117 // Navigate to the given URL (Plugin -> Page)
118 const char kJSNavigateType[] = "navigate";
119 const char kJSNavigateUrl[] = "url";
120 const char kJSNavigateNewTab[] = "newTab";
121 // Open the email editor with the given parameters (Plugin -> Page)
122 const char kJSEmailType[] = "email";
123 const char kJSEmailTo[] = "to";
124 const char kJSEmailCc[] = "cc";
125 const char kJSEmailBcc[] = "bcc";
126 const char kJSEmailSubject[] = "subject";
127 const char kJSEmailBody[] = "body";
128 // Rotation (Page -> Plugin)
129 const char kJSRotateClockwiseType[] = "rotateClockwise";
130 const char kJSRotateCounterclockwiseType[] = "rotateCounterclockwise";
131 // Select all text in the document (Page -> Plugin)
132 const char kJSSelectAllType[] = "selectAll";
133 // Get the selected text in the document (Page -> Plugin)
134 const char kJSGetSelectedTextType[] = "getSelectedText";
135 // Reply with selected text (Plugin -> Page)
136 const char kJSGetSelectedTextReplyType[] = "getSelectedTextReply";
137 const char kJSSelectedText[] = "selectedText";
139 // List of named destinations (Plugin -> Page)
140 const char kJSSetNamedDestinationsType[] = "setNamedDestinations";
141 const char kJSNamedDestinations[] = "namedDestinations";
143 const int kFindResultCooldownMs = 100;
145 const double kMinZoom = 0.01;
147 namespace {
149 static const char kPPPPdfInterface[] = PPP_PDF_INTERFACE_1;
151 PP_Var GetLinkAtPosition(PP_Instance instance, PP_Point point) {
152 pp::Var var;
153 void* object = pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
154 if (object) {
155 var = static_cast<OutOfProcessInstance*>(object)->GetLinkAtPosition(
156 pp::Point(point));
158 return var.Detach();
161 void Transform(PP_Instance instance, PP_PrivatePageTransformType type) {
162 void* object =
163 pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
164 if (object) {
165 OutOfProcessInstance* obj_instance =
166 static_cast<OutOfProcessInstance*>(object);
167 switch (type) {
168 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CW:
169 obj_instance->RotateClockwise();
170 break;
171 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CCW:
172 obj_instance->RotateCounterclockwise();
173 break;
178 PP_Bool GetPrintPresetOptionsFromDocument(
179 PP_Instance instance,
180 PP_PdfPrintPresetOptions_Dev* options) {
181 void* object = pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
182 if (object) {
183 OutOfProcessInstance* obj_instance =
184 static_cast<OutOfProcessInstance*>(object);
185 obj_instance->GetPrintPresetOptionsFromDocument(options);
187 return PP_TRUE;
190 const PPP_Pdf ppp_private = {
191 &GetLinkAtPosition,
192 &Transform,
193 &GetPrintPresetOptionsFromDocument
196 int ExtractPrintPreviewPageIndex(const std::string& src_url) {
197 // Sample |src_url| format: chrome://print/id/page_index/print.pdf
198 std::vector<std::string> url_substr;
199 base::SplitString(src_url.substr(strlen(kChromePrint)), '/', &url_substr);
200 if (url_substr.size() != 3)
201 return -1;
203 if (url_substr[2] != "print.pdf")
204 return -1;
206 int page_index = 0;
207 if (!base::StringToInt(url_substr[1], &page_index))
208 return -1;
209 return page_index;
212 bool IsPrintPreviewUrl(const std::string& url) {
213 return url.substr(0, strlen(kChromePrint)) == kChromePrint;
216 void ScalePoint(float scale, pp::Point* point) {
217 point->set_x(static_cast<int>(point->x() * scale));
218 point->set_y(static_cast<int>(point->y() * scale));
221 void ScaleRect(float scale, pp::Rect* rect) {
222 int left = static_cast<int>(floorf(rect->x() * scale));
223 int top = static_cast<int>(floorf(rect->y() * scale));
224 int right = static_cast<int>(ceilf((rect->x() + rect->width()) * scale));
225 int bottom = static_cast<int>(ceilf((rect->y() + rect->height()) * scale));
226 rect->SetRect(left, top, right - left, bottom - top);
229 // TODO(raymes): Remove this dependency on VarPrivate/InstancePrivate. It's
230 // needed right now to do a synchronous call to JavaScript, but we could easily
231 // replace this with a custom PPB_PDF function.
232 pp::Var ModalDialog(const pp::Instance* instance,
233 const std::string& type,
234 const std::string& message,
235 const std::string& default_answer) {
236 const PPB_Instance_Private* interface =
237 reinterpret_cast<const PPB_Instance_Private*>(
238 pp::Module::Get()->GetBrowserInterface(
239 PPB_INSTANCE_PRIVATE_INTERFACE));
240 pp::VarPrivate window(pp::PASS_REF,
241 interface->GetWindowObject(instance->pp_instance()));
242 if (default_answer.empty())
243 return window.Call(type, message);
244 else
245 return window.Call(type, message, default_answer);
248 } // namespace
250 OutOfProcessInstance::OutOfProcessInstance(PP_Instance instance)
251 : pp::Instance(instance),
252 pp::Find_Private(this),
253 pp::Printing_Dev(this),
254 pp::Selection_Dev(this),
255 cursor_(PP_CURSORTYPE_POINTER),
256 zoom_(1.0),
257 device_scale_(1.0),
258 full_(false),
259 paint_manager_(this, this, true),
260 first_paint_(true),
261 document_load_state_(LOAD_STATE_LOADING),
262 preview_document_load_state_(LOAD_STATE_COMPLETE),
263 uma_(this),
264 told_browser_about_unsupported_feature_(false),
265 print_preview_page_count_(0),
266 last_progress_sent_(0),
267 recently_sent_find_update_(false),
268 received_viewport_message_(false),
269 did_call_start_loading_(false),
270 stop_scrolling_(false) {
271 loader_factory_.Initialize(this);
272 timer_factory_.Initialize(this);
273 form_factory_.Initialize(this);
274 print_callback_factory_.Initialize(this);
275 engine_.reset(PDFEngine::Create(this));
276 pp::Module::Get()->AddPluginInterface(kPPPPdfInterface, &ppp_private);
277 AddPerInstanceObject(kPPPPdfInterface, this);
279 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_MOUSE);
280 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_KEYBOARD);
281 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_TOUCH);
284 OutOfProcessInstance::~OutOfProcessInstance() {
285 RemovePerInstanceObject(kPPPPdfInterface, this);
288 bool OutOfProcessInstance::Init(uint32_t argc,
289 const char* argn[],
290 const char* argv[]) {
291 // Check if the PDF is being loaded in the PDF chrome extension. We only allow
292 // the plugin to be put into "full frame" mode when it is being loaded in the
293 // extension because this enables some features that we don't want pages
294 // abusing outside of the extension.
295 pp::Var document_url_var = pp::URLUtil_Dev::Get()->GetDocumentURL(this);
296 std::string document_url = document_url_var.is_string() ?
297 document_url_var.AsString() : std::string();
298 std::string extension_url = std::string(kChromeExtension);
299 bool in_extension =
300 !document_url.compare(0, extension_url.size(), extension_url);
302 if (in_extension) {
303 // Check if the plugin is full frame. This is passed in from JS.
304 for (uint32_t i = 0; i < argc; ++i) {
305 if (strcmp(argn[i], "full-frame") == 0) {
306 full_ = true;
307 break;
312 // Only allow the plugin to handle find requests if it is full frame.
313 if (full_)
314 SetPluginToHandleFindRequests();
316 // Send translated strings to the extension where they will be displayed.
317 // TODO(raymes): It would be better to get these in the extension directly
318 // through an API but no such API currently exists.
319 pp::VarDictionary translated_strings;
320 translated_strings.Set(kType, kJSSetTranslatedStringsType);
321 translated_strings.Set(kJSGetPasswordString,
322 GetLocalizedString(PP_RESOURCESTRING_PDFGETPASSWORD));
323 translated_strings.Set(kJSLoadingString,
324 GetLocalizedString(PP_RESOURCESTRING_PDFLOADING));
325 translated_strings.Set(kJSLoadFailedString,
326 GetLocalizedString(PP_RESOURCESTRING_PDFLOAD_FAILED));
327 PostMessage(translated_strings);
329 text_input_.reset(new pp::TextInput_Dev(this));
331 const char* stream_url = NULL;
332 const char* original_url = NULL;
333 const char* headers = NULL;
334 for (uint32_t i = 0; i < argc; ++i) {
335 if (strcmp(argn[i], "src") == 0)
336 original_url = argv[i];
337 else if (strcmp(argn[i], "stream-url") == 0)
338 stream_url = argv[i];
339 else if (strcmp(argn[i], "headers") == 0)
340 headers = argv[i];
343 // TODO(raymes): This is a hack to ensure that if no headers are passed in
344 // then we get the right MIME type. When the in process plugin is removed we
345 // can fix the document loader properly and remove this hack.
346 if (!headers || strcmp(headers, "") == 0)
347 headers = "content-type: application/pdf";
349 if (!original_url)
350 return false;
352 if (!stream_url)
353 stream_url = original_url;
355 // If we're in print preview mode we don't need to load the document yet.
356 // A |kJSResetPrintPreviewModeType| message will be sent to the plugin letting
357 // it know the url to load. By not loading here we avoid loading the same
358 // document twice.
359 if (IsPrintPreviewUrl(original_url))
360 return true;
362 LoadUrl(stream_url);
363 url_ = original_url;
364 return engine_->New(original_url, headers);
367 void OutOfProcessInstance::HandleMessage(const pp::Var& message) {
368 pp::VarDictionary dict(message);
369 if (!dict.Get(kType).is_string()) {
370 NOTREACHED();
371 return;
374 std::string type = dict.Get(kType).AsString();
376 if (type == kJSViewportType &&
377 dict.Get(pp::Var(kJSXOffset)).is_number() &&
378 dict.Get(pp::Var(kJSYOffset)).is_number() &&
379 dict.Get(pp::Var(kJSZoom)).is_number()) {
380 received_viewport_message_ = true;
381 stop_scrolling_ = false;
382 double zoom = dict.Get(pp::Var(kJSZoom)).AsDouble();
383 pp::FloatPoint scroll_offset(dict.Get(pp::Var(kJSXOffset)).AsDouble(),
384 dict.Get(pp::Var(kJSYOffset)).AsDouble());
386 // Bound the input parameters.
387 zoom = std::max(kMinZoom, zoom);
388 SetZoom(zoom);
389 scroll_offset = BoundScrollOffsetToDocument(scroll_offset);
390 engine_->ScrolledToXPosition(scroll_offset.x() * device_scale_);
391 engine_->ScrolledToYPosition(scroll_offset.y() * device_scale_);
392 } else if (type == kJSGetPasswordCompleteType &&
393 dict.Get(pp::Var(kJSPassword)).is_string()) {
394 if (password_callback_) {
395 pp::CompletionCallbackWithOutput<pp::Var> callback = *password_callback_;
396 password_callback_.reset();
397 *callback.output() = dict.Get(pp::Var(kJSPassword)).pp_var();
398 callback.Run(PP_OK);
399 } else {
400 NOTREACHED();
402 } else if (type == kJSPrintType) {
403 Print();
404 } else if (type == kJSSaveType) {
405 pp::PDF::SaveAs(this);
406 } else if (type == kJSRotateClockwiseType) {
407 RotateClockwise();
408 } else if (type == kJSRotateCounterclockwiseType) {
409 RotateCounterclockwise();
410 } else if (type == kJSSelectAllType) {
411 engine_->SelectAll();
412 } else if (type == kJSResetPrintPreviewModeType &&
413 dict.Get(pp::Var(kJSPrintPreviewUrl)).is_string() &&
414 dict.Get(pp::Var(kJSPrintPreviewGrayscale)).is_bool() &&
415 dict.Get(pp::Var(kJSPrintPreviewPageCount)).is_int()) {
416 url_ = dict.Get(pp::Var(kJSPrintPreviewUrl)).AsString();
417 preview_pages_info_ = std::queue<PreviewPageInfo>();
418 preview_document_load_state_ = LOAD_STATE_COMPLETE;
419 document_load_state_ = LOAD_STATE_LOADING;
420 LoadUrl(url_);
421 preview_engine_.reset();
422 engine_.reset(PDFEngine::Create(this));
423 engine_->SetGrayscale(dict.Get(pp::Var(kJSPrintPreviewGrayscale)).AsBool());
424 engine_->New(url_.c_str());
426 print_preview_page_count_ =
427 std::max(dict.Get(pp::Var(kJSPrintPreviewPageCount)).AsInt(), 0);
429 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
430 } else if (type == kJSLoadPreviewPageType &&
431 dict.Get(pp::Var(kJSPreviewPageUrl)).is_string() &&
432 dict.Get(pp::Var(kJSPreviewPageIndex)).is_int()) {
433 ProcessPreviewPageInfo(dict.Get(pp::Var(kJSPreviewPageUrl)).AsString(),
434 dict.Get(pp::Var(kJSPreviewPageIndex)).AsInt());
435 } else if (type == kJSGetAccessibilityJSONType) {
436 pp::VarDictionary reply;
437 reply.Set(pp::Var(kType), pp::Var(kJSGetAccessibilityJSONReplyType));
438 if (dict.Get(pp::Var(kJSAccessibilityPageNumber)).is_int()) {
439 int page = dict.Get(pp::Var(kJSAccessibilityPageNumber)).AsInt();
440 reply.Set(pp::Var(kJSAccessibilityJSON),
441 pp::Var(engine_->GetPageAsJSON(page)));
442 } else {
443 base::DictionaryValue node;
444 node.SetInteger(kAccessibleNumberOfPages, engine_->GetNumberOfPages());
445 node.SetBoolean(kAccessibleLoaded,
446 document_load_state_ != LOAD_STATE_LOADING);
447 bool has_permissions =
448 engine_->HasPermission(PDFEngine::PERMISSION_COPY) ||
449 engine_->HasPermission(PDFEngine::PERMISSION_COPY_ACCESSIBLE);
450 node.SetBoolean(kAccessibleCopyable, has_permissions);
451 std::string json;
452 base::JSONWriter::Write(&node, &json);
453 reply.Set(pp::Var(kJSAccessibilityJSON), pp::Var(json));
455 PostMessage(reply);
456 } else if (type == kJSStopScrollingType) {
457 stop_scrolling_ = true;
458 } else if (type == kJSGetSelectedTextType) {
459 std::string selected_text = engine_->GetSelectedText();
460 // Always return unix newlines to JS.
461 base::ReplaceChars(selected_text, "\r", std::string(), &selected_text);
462 pp::VarDictionary reply;
463 reply.Set(pp::Var(kType), pp::Var(kJSGetSelectedTextReplyType));
464 reply.Set(pp::Var(kJSSelectedText), selected_text);
465 PostMessage(reply);
466 } else {
467 NOTREACHED();
471 bool OutOfProcessInstance::HandleInputEvent(
472 const pp::InputEvent& event) {
473 // To simplify things, convert the event into device coordinates if it is
474 // a mouse event.
475 pp::InputEvent event_device_res(event);
477 pp::MouseInputEvent mouse_event(event);
478 if (!mouse_event.is_null()) {
479 pp::Point point = mouse_event.GetPosition();
480 pp::Point movement = mouse_event.GetMovement();
481 ScalePoint(device_scale_, &point);
482 ScalePoint(device_scale_, &movement);
483 mouse_event = pp::MouseInputEvent(
484 this,
485 event.GetType(),
486 event.GetTimeStamp(),
487 event.GetModifiers(),
488 mouse_event.GetButton(),
489 point,
490 mouse_event.GetClickCount(),
491 movement);
492 event_device_res = mouse_event;
496 pp::InputEvent offset_event(event_device_res);
497 switch (offset_event.GetType()) {
498 case PP_INPUTEVENT_TYPE_MOUSEDOWN:
499 case PP_INPUTEVENT_TYPE_MOUSEUP:
500 case PP_INPUTEVENT_TYPE_MOUSEMOVE:
501 case PP_INPUTEVENT_TYPE_MOUSEENTER:
502 case PP_INPUTEVENT_TYPE_MOUSELEAVE: {
503 pp::MouseInputEvent mouse_event(event_device_res);
504 pp::MouseInputEvent mouse_event_dip(event);
505 pp::Point point = mouse_event.GetPosition();
506 point.set_x(point.x() - available_area_.x());
507 offset_event = pp::MouseInputEvent(
508 this,
509 event.GetType(),
510 event.GetTimeStamp(),
511 event.GetModifiers(),
512 mouse_event.GetButton(),
513 point,
514 mouse_event.GetClickCount(),
515 mouse_event.GetMovement());
516 break;
518 default:
519 break;
521 if (engine_->HandleEvent(offset_event))
522 return true;
524 // TODO(raymes): Implement this scroll behavior in JS:
525 // When click+dragging, scroll the document correctly.
527 // Return true for unhandled clicks so the plugin takes focus.
528 return (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN);
531 void OutOfProcessInstance::DidChangeView(const pp::View& view) {
532 pp::Rect view_rect(view.GetRect());
533 float old_device_scale = device_scale_;
534 float device_scale = view.GetDeviceScale();
535 pp::Size view_device_size(view_rect.width() * device_scale,
536 view_rect.height() * device_scale);
538 if (view_device_size != plugin_size_ || device_scale != device_scale_) {
539 device_scale_ = device_scale;
540 plugin_dip_size_ = view_rect.size();
541 plugin_size_ = view_device_size;
543 paint_manager_.SetSize(view_device_size, device_scale_);
545 pp::Size new_image_data_size = PaintManager::GetNewContextSize(
546 image_data_.size(),
547 plugin_size_);
548 if (new_image_data_size != image_data_.size()) {
549 image_data_ = pp::ImageData(this,
550 PP_IMAGEDATAFORMAT_BGRA_PREMUL,
551 new_image_data_size,
552 false);
553 first_paint_ = true;
556 if (image_data_.is_null()) {
557 DCHECK(plugin_size_.IsEmpty());
558 return;
561 OnGeometryChanged(zoom_, old_device_scale);
564 if (!stop_scrolling_) {
565 pp::Point scroll_offset(view.GetScrollOffset());
566 pp::FloatPoint scroll_offset_float(scroll_offset.x(),
567 scroll_offset.y());
568 scroll_offset_float = BoundScrollOffsetToDocument(scroll_offset_float);
569 engine_->ScrolledToXPosition(scroll_offset_float.x() * device_scale_);
570 engine_->ScrolledToYPosition(scroll_offset_float.y() * device_scale_);
574 void OutOfProcessInstance::GetPrintPresetOptionsFromDocument(
575 PP_PdfPrintPresetOptions_Dev* options) {
576 options->is_scaling_disabled = PP_FromBool(IsPrintScalingDisabled());
577 options->copies = engine_->GetCopiesToPrint();
580 pp::Var OutOfProcessInstance::GetLinkAtPosition(
581 const pp::Point& point) {
582 pp::Point offset_point(point);
583 ScalePoint(device_scale_, &offset_point);
584 offset_point.set_x(offset_point.x() - available_area_.x());
585 return engine_->GetLinkAtPosition(offset_point);
588 pp::Var OutOfProcessInstance::GetSelectedText(bool html) {
589 if (html)
590 return pp::Var();
591 return engine_->GetSelectedText();
594 uint32_t OutOfProcessInstance::QuerySupportedPrintOutputFormats() {
595 return engine_->QuerySupportedPrintOutputFormats();
598 int32_t OutOfProcessInstance::PrintBegin(
599 const PP_PrintSettings_Dev& print_settings) {
600 // For us num_pages is always equal to the number of pages in the PDF
601 // document irrespective of the printable area.
602 int32_t ret = engine_->GetNumberOfPages();
603 if (!ret)
604 return 0;
606 uint32_t supported_formats = engine_->QuerySupportedPrintOutputFormats();
607 if ((print_settings.format & supported_formats) == 0)
608 return 0;
610 print_settings_.is_printing = true;
611 print_settings_.pepper_print_settings = print_settings;
612 engine_->PrintBegin();
613 return ret;
616 pp::Resource OutOfProcessInstance::PrintPages(
617 const PP_PrintPageNumberRange_Dev* page_ranges,
618 uint32_t page_range_count) {
619 if (!print_settings_.is_printing)
620 return pp::Resource();
622 print_settings_.print_pages_called_ = true;
623 return engine_->PrintPages(page_ranges, page_range_count,
624 print_settings_.pepper_print_settings);
627 void OutOfProcessInstance::PrintEnd() {
628 if (print_settings_.print_pages_called_)
629 UserMetricsRecordAction("PDF.PrintPage");
630 print_settings_.Clear();
631 engine_->PrintEnd();
634 bool OutOfProcessInstance::IsPrintScalingDisabled() {
635 return !engine_->GetPrintScaling();
638 bool OutOfProcessInstance::StartFind(const std::string& text,
639 bool case_sensitive) {
640 engine_->StartFind(text.c_str(), case_sensitive);
641 return true;
644 void OutOfProcessInstance::SelectFindResult(bool forward) {
645 engine_->SelectFindResult(forward);
648 void OutOfProcessInstance::StopFind() {
649 engine_->StopFind();
650 tickmarks_.clear();
651 SetTickmarks(tickmarks_);
654 void OutOfProcessInstance::OnPaint(
655 const std::vector<pp::Rect>& paint_rects,
656 std::vector<PaintManager::ReadyRect>* ready,
657 std::vector<pp::Rect>* pending) {
658 if (image_data_.is_null()) {
659 DCHECK(plugin_size_.IsEmpty());
660 return;
662 if (first_paint_) {
663 first_paint_ = false;
664 pp::Rect rect = pp::Rect(pp::Point(), image_data_.size());
665 FillRect(rect, kBackgroundColor);
666 ready->push_back(PaintManager::ReadyRect(rect, image_data_, true));
669 if (!received_viewport_message_)
670 return;
672 engine_->PrePaint();
674 for (size_t i = 0; i < paint_rects.size(); i++) {
675 // Intersect with plugin area since there could be pending invalidates from
676 // when the plugin area was larger.
677 pp::Rect rect =
678 paint_rects[i].Intersect(pp::Rect(pp::Point(), plugin_size_));
679 if (rect.IsEmpty())
680 continue;
682 pp::Rect pdf_rect = available_area_.Intersect(rect);
683 if (!pdf_rect.IsEmpty()) {
684 pdf_rect.Offset(available_area_.x() * -1, 0);
686 std::vector<pp::Rect> pdf_ready;
687 std::vector<pp::Rect> pdf_pending;
688 engine_->Paint(pdf_rect, &image_data_, &pdf_ready, &pdf_pending);
689 for (size_t j = 0; j < pdf_ready.size(); ++j) {
690 pdf_ready[j].Offset(available_area_.point());
691 ready->push_back(
692 PaintManager::ReadyRect(pdf_ready[j], image_data_, false));
694 for (size_t j = 0; j < pdf_pending.size(); ++j) {
695 pdf_pending[j].Offset(available_area_.point());
696 pending->push_back(pdf_pending[j]);
700 for (size_t j = 0; j < background_parts_.size(); ++j) {
701 pp::Rect intersection = background_parts_[j].location.Intersect(rect);
702 if (!intersection.IsEmpty()) {
703 FillRect(intersection, background_parts_[j].color);
704 ready->push_back(
705 PaintManager::ReadyRect(intersection, image_data_, false));
710 engine_->PostPaint();
713 void OutOfProcessInstance::DidOpen(int32_t result) {
714 if (result == PP_OK) {
715 if (!engine_->HandleDocumentLoad(embed_loader_)) {
716 document_load_state_ = LOAD_STATE_LOADING;
717 DocumentLoadFailed();
719 } else if (result != PP_ERROR_ABORTED) { // Can happen in tests.
720 NOTREACHED();
721 DocumentLoadFailed();
724 // If it's a progressive load, cancel the stream URL request so that requests
725 // can be made on the original URL.
726 // TODO(raymes): Make this clearer once the in-process plugin is deleted.
727 if (engine_->IsProgressiveLoad()) {
728 pp::VarDictionary message;
729 message.Set(kType, kJSCancelStreamUrlType);
730 PostMessage(message);
734 void OutOfProcessInstance::DidOpenPreview(int32_t result) {
735 if (result == PP_OK) {
736 preview_engine_.reset(PDFEngine::Create(new PreviewModeClient(this)));
737 preview_engine_->HandleDocumentLoad(embed_preview_loader_);
738 } else {
739 NOTREACHED();
743 void OutOfProcessInstance::OnClientTimerFired(int32_t id) {
744 engine_->OnCallback(id);
747 void OutOfProcessInstance::CalculateBackgroundParts() {
748 background_parts_.clear();
749 int left_width = available_area_.x();
750 int right_start = available_area_.right();
751 int right_width = abs(plugin_size_.width() - available_area_.right());
752 int bottom = std::min(available_area_.bottom(), plugin_size_.height());
754 // Add the left, right, and bottom rectangles. Note: we assume only
755 // horizontal centering.
756 BackgroundPart part = {
757 pp::Rect(0, 0, left_width, bottom),
758 kBackgroundColor
760 if (!part.location.IsEmpty())
761 background_parts_.push_back(part);
762 part.location = pp::Rect(right_start, 0, right_width, bottom);
763 if (!part.location.IsEmpty())
764 background_parts_.push_back(part);
765 part.location = pp::Rect(
766 0, bottom, plugin_size_.width(), plugin_size_.height() - bottom);
767 if (!part.location.IsEmpty())
768 background_parts_.push_back(part);
771 int OutOfProcessInstance::GetDocumentPixelWidth() const {
772 return static_cast<int>(ceil(document_size_.width() * zoom_ * device_scale_));
775 int OutOfProcessInstance::GetDocumentPixelHeight() const {
776 return static_cast<int>(
777 ceil(document_size_.height() * zoom_ * device_scale_));
780 void OutOfProcessInstance::FillRect(const pp::Rect& rect, uint32 color) {
781 DCHECK(!image_data_.is_null() || rect.IsEmpty());
782 uint32* buffer_start = static_cast<uint32*>(image_data_.data());
783 int stride = image_data_.stride();
784 uint32* ptr = buffer_start + rect.y() * stride / 4 + rect.x();
785 int height = rect.height();
786 int width = rect.width();
787 for (int y = 0; y < height; ++y) {
788 for (int x = 0; x < width; ++x)
789 *(ptr + x) = color;
790 ptr += stride /4;
794 void OutOfProcessInstance::DocumentSizeUpdated(const pp::Size& size) {
795 document_size_ = size;
797 pp::VarDictionary dimensions;
798 dimensions.Set(kType, kJSDocumentDimensionsType);
799 dimensions.Set(kJSDocumentWidth, pp::Var(document_size_.width()));
800 dimensions.Set(kJSDocumentHeight, pp::Var(document_size_.height()));
801 pp::VarArray page_dimensions_array;
802 int num_pages = engine_->GetNumberOfPages();
803 for (int i = 0; i < num_pages; ++i) {
804 pp::Rect page_rect = engine_->GetPageRect(i);
805 pp::VarDictionary page_dimensions;
806 page_dimensions.Set(kJSPageX, pp::Var(page_rect.x()));
807 page_dimensions.Set(kJSPageY, pp::Var(page_rect.y()));
808 page_dimensions.Set(kJSPageWidth, pp::Var(page_rect.width()));
809 page_dimensions.Set(kJSPageHeight, pp::Var(page_rect.height()));
810 page_dimensions_array.Set(i, page_dimensions);
812 dimensions.Set(kJSPageDimensions, page_dimensions_array);
813 PostMessage(dimensions);
815 OnGeometryChanged(zoom_, device_scale_);
818 void OutOfProcessInstance::Invalidate(const pp::Rect& rect) {
819 pp::Rect offset_rect(rect);
820 offset_rect.Offset(available_area_.point());
821 paint_manager_.InvalidateRect(offset_rect);
824 void OutOfProcessInstance::Scroll(const pp::Point& point) {
825 if (!image_data_.is_null())
826 paint_manager_.ScrollRect(available_area_, point);
829 void OutOfProcessInstance::ScrollToX(int x) {
830 pp::VarDictionary position;
831 position.Set(kType, kJSSetScrollPositionType);
832 position.Set(kJSPositionX, pp::Var(x / device_scale_));
833 PostMessage(position);
836 void OutOfProcessInstance::ScrollToY(int y) {
837 pp::VarDictionary position;
838 position.Set(kType, kJSSetScrollPositionType);
839 position.Set(kJSPositionY, pp::Var(y / device_scale_));
840 PostMessage(position);
843 void OutOfProcessInstance::ScrollToPage(int page) {
844 if (engine_->GetNumberOfPages() == 0)
845 return;
847 pp::VarDictionary message;
848 message.Set(kType, kJSGoToPageType);
849 message.Set(kJSPageNumber, pp::Var(page));
850 PostMessage(message);
853 void OutOfProcessInstance::NavigateTo(const std::string& url,
854 bool open_in_new_tab) {
855 pp::VarDictionary message;
856 message.Set(kType, kJSNavigateType);
857 message.Set(kJSNavigateUrl, url);
858 message.Set(kJSNavigateNewTab, open_in_new_tab);
859 PostMessage(message);
862 void OutOfProcessInstance::UpdateCursor(PP_CursorType_Dev cursor) {
863 if (cursor == cursor_)
864 return;
865 cursor_ = cursor;
867 const PPB_CursorControl_Dev* cursor_interface =
868 reinterpret_cast<const PPB_CursorControl_Dev*>(
869 pp::Module::Get()->GetBrowserInterface(PPB_CURSOR_CONTROL_DEV_INTERFACE));
870 if (!cursor_interface) {
871 NOTREACHED();
872 return;
875 cursor_interface->SetCursor(
876 pp_instance(), cursor_, pp::ImageData().pp_resource(), NULL);
879 void OutOfProcessInstance::UpdateTickMarks(
880 const std::vector<pp::Rect>& tickmarks) {
881 float inverse_scale = 1.0f / device_scale_;
882 std::vector<pp::Rect> scaled_tickmarks = tickmarks;
883 for (size_t i = 0; i < scaled_tickmarks.size(); i++)
884 ScaleRect(inverse_scale, &scaled_tickmarks[i]);
885 tickmarks_ = scaled_tickmarks;
888 void OutOfProcessInstance::NotifyNumberOfFindResultsChanged(int total,
889 bool final_result) {
890 // We don't want to spam the renderer with too many updates to the number of
891 // find results. Don't send an update if we sent one too recently. If it's the
892 // final update, we always send it though.
893 if (final_result) {
894 NumberOfFindResultsChanged(total, final_result);
895 SetTickmarks(tickmarks_);
896 return;
899 if (recently_sent_find_update_)
900 return;
902 NumberOfFindResultsChanged(total, final_result);
903 SetTickmarks(tickmarks_);
904 recently_sent_find_update_ = true;
905 pp::CompletionCallback callback =
906 timer_factory_.NewCallback(
907 &OutOfProcessInstance::ResetRecentlySentFindUpdate);
908 pp::Module::Get()->core()->CallOnMainThread(kFindResultCooldownMs,
909 callback, 0);
912 void OutOfProcessInstance::NotifySelectedFindResultChanged(
913 int current_find_index) {
914 DCHECK_GE(current_find_index, 0);
915 SelectedFindResultChanged(current_find_index);
918 void OutOfProcessInstance::GetDocumentPassword(
919 pp::CompletionCallbackWithOutput<pp::Var> callback) {
920 if (password_callback_) {
921 NOTREACHED();
922 return;
925 password_callback_.reset(
926 new pp::CompletionCallbackWithOutput<pp::Var>(callback));
927 pp::VarDictionary message;
928 message.Set(pp::Var(kType), pp::Var(kJSGetPasswordType));
929 PostMessage(message);
932 void OutOfProcessInstance::Alert(const std::string& message) {
933 ModalDialog(this, "alert", message, std::string());
936 bool OutOfProcessInstance::Confirm(const std::string& message) {
937 pp::Var result = ModalDialog(this, "confirm", message, std::string());
938 return result.is_bool() ? result.AsBool() : false;
941 std::string OutOfProcessInstance::Prompt(const std::string& question,
942 const std::string& default_answer) {
943 pp::Var result = ModalDialog(this, "prompt", question, default_answer);
944 return result.is_string() ? result.AsString() : std::string();
947 std::string OutOfProcessInstance::GetURL() {
948 return url_;
951 void OutOfProcessInstance::Email(const std::string& to,
952 const std::string& cc,
953 const std::string& bcc,
954 const std::string& subject,
955 const std::string& body) {
956 pp::VarDictionary message;
957 message.Set(pp::Var(kType), pp::Var(kJSEmailType));
958 message.Set(pp::Var(kJSEmailTo),
959 pp::Var(net::EscapeUrlEncodedData(to, false)));
960 message.Set(pp::Var(kJSEmailCc),
961 pp::Var(net::EscapeUrlEncodedData(cc, false)));
962 message.Set(pp::Var(kJSEmailBcc),
963 pp::Var(net::EscapeUrlEncodedData(bcc, false)));
964 message.Set(pp::Var(kJSEmailSubject),
965 pp::Var(net::EscapeUrlEncodedData(subject, false)));
966 message.Set(pp::Var(kJSEmailBody),
967 pp::Var(net::EscapeUrlEncodedData(body, false)));
968 PostMessage(message);
971 void OutOfProcessInstance::Print() {
972 if (!engine_->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY) &&
973 !engine_->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY)) {
974 return;
977 pp::CompletionCallback callback =
978 print_callback_factory_.NewCallback(&OutOfProcessInstance::OnPrint);
979 pp::Module::Get()->core()->CallOnMainThread(0, callback);
982 void OutOfProcessInstance::OnPrint(int32_t) {
983 pp::PDF::Print(this);
986 void OutOfProcessInstance::SubmitForm(const std::string& url,
987 const void* data,
988 int length) {
989 pp::URLRequestInfo request(this);
990 request.SetURL(url);
991 request.SetMethod("POST");
992 request.AppendDataToBody(reinterpret_cast<const char*>(data), length);
994 pp::CompletionCallback callback =
995 form_factory_.NewCallback(&OutOfProcessInstance::FormDidOpen);
996 form_loader_ = CreateURLLoaderInternal();
997 int rv = form_loader_.Open(request, callback);
998 if (rv != PP_OK_COMPLETIONPENDING)
999 callback.Run(rv);
1002 void OutOfProcessInstance::FormDidOpen(int32_t result) {
1003 // TODO: inform the user of success/failure.
1004 if (result != PP_OK) {
1005 NOTREACHED();
1009 std::string OutOfProcessInstance::ShowFileSelectionDialog() {
1010 // Seems like very low priority to implement, since the pdf has no way to get
1011 // the file data anyways. Javascript doesn't let you do this synchronously.
1012 NOTREACHED();
1013 return std::string();
1016 pp::URLLoader OutOfProcessInstance::CreateURLLoader() {
1017 if (full_) {
1018 if (!did_call_start_loading_) {
1019 did_call_start_loading_ = true;
1020 pp::PDF::DidStartLoading(this);
1023 // Disable save and print until the document is fully loaded, since they
1024 // would generate an incomplete document. Need to do this each time we
1025 // call DidStartLoading since that resets the content restrictions.
1026 pp::PDF::SetContentRestriction(this, CONTENT_RESTRICTION_SAVE |
1027 CONTENT_RESTRICTION_PRINT);
1030 return CreateURLLoaderInternal();
1033 void OutOfProcessInstance::ScheduleCallback(int id, int delay_in_ms) {
1034 pp::CompletionCallback callback =
1035 timer_factory_.NewCallback(&OutOfProcessInstance::OnClientTimerFired);
1036 pp::Module::Get()->core()->CallOnMainThread(delay_in_ms, callback, id);
1039 void OutOfProcessInstance::SearchString(const base::char16* string,
1040 const base::char16* term,
1041 bool case_sensitive,
1042 std::vector<SearchStringResult>* results) {
1043 PP_PrivateFindResult* pp_results;
1044 int count = 0;
1045 pp::PDF::SearchString(
1046 this,
1047 reinterpret_cast<const unsigned short*>(string),
1048 reinterpret_cast<const unsigned short*>(term),
1049 case_sensitive,
1050 &pp_results,
1051 &count);
1053 results->resize(count);
1054 for (int i = 0; i < count; ++i) {
1055 (*results)[i].start_index = pp_results[i].start_index;
1056 (*results)[i].length = pp_results[i].length;
1059 pp::Memory_Dev memory;
1060 memory.MemFree(pp_results);
1063 void OutOfProcessInstance::DocumentPaintOccurred() {
1066 void OutOfProcessInstance::DocumentLoadComplete(int page_count) {
1067 // Clear focus state for OSK.
1068 FormTextFieldFocusChange(false);
1070 DCHECK(document_load_state_ == LOAD_STATE_LOADING);
1071 document_load_state_ = LOAD_STATE_COMPLETE;
1072 UserMetricsRecordAction("PDF.LoadSuccess");
1074 // Note: If we are in print preview mode the scroll location is retained
1075 // across document loads so we don't want to scroll again and override it.
1076 if (IsPrintPreview()) {
1077 AppendBlankPrintPreviewPages();
1078 OnGeometryChanged(0, 0);
1081 pp::VarDictionary named_destinations_message;
1082 pp::VarDictionary named_destinations = engine_->GetNamedDestinations();
1083 named_destinations_message.Set(pp::Var(kType),
1084 pp::Var(kJSSetNamedDestinationsType));
1085 named_destinations_message.Set(pp::Var(kJSNamedDestinations),
1086 pp::Var(named_destinations));
1087 PostMessage(named_destinations_message);
1089 pp::VarDictionary bookmarks_message;
1090 bookmarks_message.Set(pp::Var(kType), pp::Var(kJSBookmarksType));
1091 bookmarks_message.Set(pp::Var(kJSBookmarks), engine_->GetBookmarks());
1092 PostMessage(bookmarks_message);
1094 pp::VarDictionary progress_message;
1095 progress_message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1096 progress_message.Set(pp::Var(kJSProgressPercentage), pp::Var(100));
1097 PostMessage(progress_message);
1099 if (!full_)
1100 return;
1102 if (did_call_start_loading_) {
1103 pp::PDF::DidStopLoading(this);
1104 did_call_start_loading_ = false;
1107 int content_restrictions =
1108 CONTENT_RESTRICTION_CUT | CONTENT_RESTRICTION_PASTE;
1109 if (!engine_->HasPermission(PDFEngine::PERMISSION_COPY))
1110 content_restrictions |= CONTENT_RESTRICTION_COPY;
1112 pp::PDF::SetContentRestriction(this, content_restrictions);
1114 uma_.HistogramCustomCounts("PDF.PageCount", page_count,
1115 1, 1000000, 50);
1118 void OutOfProcessInstance::RotateClockwise() {
1119 engine_->RotateClockwise();
1122 void OutOfProcessInstance::RotateCounterclockwise() {
1123 engine_->RotateCounterclockwise();
1126 void OutOfProcessInstance::PreviewDocumentLoadComplete() {
1127 if (preview_document_load_state_ != LOAD_STATE_LOADING ||
1128 preview_pages_info_.empty()) {
1129 return;
1132 preview_document_load_state_ = LOAD_STATE_COMPLETE;
1134 int dest_page_index = preview_pages_info_.front().second;
1135 int src_page_index =
1136 ExtractPrintPreviewPageIndex(preview_pages_info_.front().first);
1137 if (src_page_index > 0 && dest_page_index > -1 && preview_engine_.get())
1138 engine_->AppendPage(preview_engine_.get(), dest_page_index);
1140 preview_pages_info_.pop();
1141 // |print_preview_page_count_| is not updated yet. Do not load any
1142 // other preview pages till we get this information.
1143 if (print_preview_page_count_ == 0)
1144 return;
1146 if (preview_pages_info_.size())
1147 LoadAvailablePreviewPage();
1150 void OutOfProcessInstance::DocumentLoadFailed() {
1151 DCHECK(document_load_state_ == LOAD_STATE_LOADING);
1152 UserMetricsRecordAction("PDF.LoadFailure");
1154 if (did_call_start_loading_) {
1155 pp::PDF::DidStopLoading(this);
1156 did_call_start_loading_ = false;
1159 document_load_state_ = LOAD_STATE_FAILED;
1160 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
1162 // Send a progress value of -1 to indicate a failure.
1163 pp::VarDictionary message;
1164 message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1165 message.Set(pp::Var(kJSProgressPercentage), pp::Var(-1)) ;
1166 PostMessage(message);
1169 void OutOfProcessInstance::PreviewDocumentLoadFailed() {
1170 UserMetricsRecordAction("PDF.PreviewDocumentLoadFailure");
1171 if (preview_document_load_state_ != LOAD_STATE_LOADING ||
1172 preview_pages_info_.empty()) {
1173 return;
1176 preview_document_load_state_ = LOAD_STATE_FAILED;
1177 preview_pages_info_.pop();
1179 if (preview_pages_info_.size())
1180 LoadAvailablePreviewPage();
1183 pp::Instance* OutOfProcessInstance::GetPluginInstance() {
1184 return this;
1187 void OutOfProcessInstance::DocumentHasUnsupportedFeature(
1188 const std::string& feature) {
1189 std::string metric("PDF_Unsupported_");
1190 metric += feature;
1191 if (!unsupported_features_reported_.count(metric)) {
1192 unsupported_features_reported_.insert(metric);
1193 UserMetricsRecordAction(metric);
1196 // Since we use an info bar, only do this for full frame plugins..
1197 if (!full_)
1198 return;
1200 if (told_browser_about_unsupported_feature_)
1201 return;
1202 told_browser_about_unsupported_feature_ = true;
1204 pp::PDF::HasUnsupportedFeature(this);
1207 void OutOfProcessInstance::DocumentLoadProgress(uint32 available,
1208 uint32 doc_size) {
1209 double progress = 0.0;
1210 if (doc_size == 0) {
1211 // Document size is unknown. Use heuristics.
1212 // We'll make progress logarithmic from 0 to 100M.
1213 static const double kFactor = log(100000000.0) / 100.0;
1214 if (available > 0) {
1215 progress = log(static_cast<double>(available)) / kFactor;
1216 if (progress > 100.0)
1217 progress = 100.0;
1219 } else {
1220 progress = 100.0 * static_cast<double>(available) / doc_size;
1223 // We send 100% load progress in DocumentLoadComplete.
1224 if (progress >= 100)
1225 return;
1227 // Avoid sending too many progress messages over PostMessage.
1228 if (progress > last_progress_sent_ + 1) {
1229 last_progress_sent_ = progress;
1230 pp::VarDictionary message;
1231 message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1232 message.Set(pp::Var(kJSProgressPercentage), pp::Var(progress)) ;
1233 PostMessage(message);
1237 void OutOfProcessInstance::FormTextFieldFocusChange(bool in_focus) {
1238 if (!text_input_.get())
1239 return;
1240 if (in_focus)
1241 text_input_->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_TEXT);
1242 else
1243 text_input_->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_NONE);
1246 void OutOfProcessInstance::ResetRecentlySentFindUpdate(int32_t /* unused */) {
1247 recently_sent_find_update_ = false;
1250 void OutOfProcessInstance::OnGeometryChanged(double old_zoom,
1251 float old_device_scale) {
1252 if (zoom_ != old_zoom || device_scale_ != old_device_scale)
1253 engine_->ZoomUpdated(zoom_ * device_scale_);
1255 available_area_ = pp::Rect(plugin_size_);
1256 int doc_width = GetDocumentPixelWidth();
1257 if (doc_width < available_area_.width()) {
1258 available_area_.Offset((available_area_.width() - doc_width) / 2, 0);
1259 available_area_.set_width(doc_width);
1261 int doc_height = GetDocumentPixelHeight();
1262 if (doc_height < available_area_.height()) {
1263 available_area_.set_height(doc_height);
1266 CalculateBackgroundParts();
1267 engine_->PageOffsetUpdated(available_area_.point());
1268 engine_->PluginSizeUpdated(available_area_.size());
1270 if (!document_size_.GetArea())
1271 return;
1272 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
1275 void OutOfProcessInstance::LoadUrl(const std::string& url) {
1276 LoadUrlInternal(url, &embed_loader_, &OutOfProcessInstance::DidOpen);
1279 void OutOfProcessInstance::LoadPreviewUrl(const std::string& url) {
1280 LoadUrlInternal(url, &embed_preview_loader_,
1281 &OutOfProcessInstance::DidOpenPreview);
1284 void OutOfProcessInstance::LoadUrlInternal(
1285 const std::string& url,
1286 pp::URLLoader* loader,
1287 void (OutOfProcessInstance::* method)(int32_t)) {
1288 pp::URLRequestInfo request(this);
1289 request.SetURL(url);
1290 request.SetMethod("GET");
1292 *loader = CreateURLLoaderInternal();
1293 pp::CompletionCallback callback = loader_factory_.NewCallback(method);
1294 int rv = loader->Open(request, callback);
1295 if (rv != PP_OK_COMPLETIONPENDING)
1296 callback.Run(rv);
1299 pp::URLLoader OutOfProcessInstance::CreateURLLoaderInternal() {
1300 pp::URLLoader loader(this);
1302 const PPB_URLLoaderTrusted* trusted_interface =
1303 reinterpret_cast<const PPB_URLLoaderTrusted*>(
1304 pp::Module::Get()->GetBrowserInterface(
1305 PPB_URLLOADERTRUSTED_INTERFACE));
1306 if (trusted_interface)
1307 trusted_interface->GrantUniversalAccess(loader.pp_resource());
1308 return loader;
1311 void OutOfProcessInstance::SetZoom(double scale) {
1312 double old_zoom = zoom_;
1313 zoom_ = scale;
1314 OnGeometryChanged(old_zoom, device_scale_);
1317 std::string OutOfProcessInstance::GetLocalizedString(PP_ResourceString id) {
1318 pp::Var rv(pp::PDF::GetLocalizedString(this, id));
1319 if (!rv.is_string())
1320 return std::string();
1322 return rv.AsString();
1325 void OutOfProcessInstance::AppendBlankPrintPreviewPages() {
1326 if (print_preview_page_count_ == 0)
1327 return;
1328 engine_->AppendBlankPages(print_preview_page_count_);
1329 if (preview_pages_info_.size() > 0)
1330 LoadAvailablePreviewPage();
1333 bool OutOfProcessInstance::IsPrintPreview() {
1334 return IsPrintPreviewUrl(url_);
1337 void OutOfProcessInstance::ProcessPreviewPageInfo(const std::string& url,
1338 int dst_page_index) {
1339 if (!IsPrintPreview())
1340 return;
1342 int src_page_index = ExtractPrintPreviewPageIndex(url);
1343 if (src_page_index < 1)
1344 return;
1346 preview_pages_info_.push(std::make_pair(url, dst_page_index));
1347 LoadAvailablePreviewPage();
1350 void OutOfProcessInstance::LoadAvailablePreviewPage() {
1351 if (preview_pages_info_.size() <= 0 ||
1352 document_load_state_ != LOAD_STATE_COMPLETE) {
1353 return;
1356 std::string url = preview_pages_info_.front().first;
1357 int dst_page_index = preview_pages_info_.front().second;
1358 int src_page_index = ExtractPrintPreviewPageIndex(url);
1359 if (src_page_index < 1 ||
1360 dst_page_index >= print_preview_page_count_ ||
1361 preview_document_load_state_ == LOAD_STATE_LOADING) {
1362 return;
1365 preview_document_load_state_ = LOAD_STATE_LOADING;
1366 LoadPreviewUrl(url);
1369 void OutOfProcessInstance::UserMetricsRecordAction(
1370 const std::string& action) {
1371 // TODO(raymes): Move this function to PPB_UMA_Private.
1372 pp::PDF::UserMetricsRecordAction(this, pp::Var(action));
1375 pp::FloatPoint OutOfProcessInstance::BoundScrollOffsetToDocument(
1376 const pp::FloatPoint& scroll_offset) {
1377 float max_x = document_size_.width() * zoom_ - plugin_dip_size_.width();
1378 float x = std::max(std::min(scroll_offset.x(), max_x), 0.0f);
1379 float max_y = document_size_.height() * zoom_ - plugin_dip_size_.height();
1380 float y = std::max(std::min(scroll_offset.y(), max_y), 0.0f);
1381 return pp::FloatPoint(x, y);
1384 } // namespace chrome_pdf