SetNeedsRedraw directly when updating a visible tile.
[chromium-blink-merge.git] / pdf / out_of_process_instance.cc
blobbfbcb93bc1255db0cab0cf177703ca89f1ed25c9
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 #if defined(OS_MACOSX)
45 #include "base/mac/mac_util.h"
46 #endif
48 namespace chrome_pdf {
50 const char kChromePrint[] = "chrome://print/";
51 const char kChromeExtension[] =
52 "chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai";
54 // Dictionary Value key names for the document accessibility info
55 const char kAccessibleNumberOfPages[] = "numberOfPages";
56 const char kAccessibleLoaded[] = "loaded";
57 const char kAccessibleCopyable[] = "copyable";
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 // Get password arguments (Plugin -> Page)
81 const char kJSGetPasswordType[] = "getPassword";
82 // Get password complete arguments (Page -> Plugin)
83 const char kJSGetPasswordCompleteType[] = "getPasswordComplete";
84 const char kJSPassword[] = "password";
85 // Print (Page -> Plugin)
86 const char kJSPrintType[] = "print";
87 // Go to page (Plugin -> Page)
88 const char kJSGoToPageType[] = "goToPage";
89 const char kJSPageNumber[] = "page";
90 // Reset print preview mode (Page -> Plugin)
91 const char kJSResetPrintPreviewModeType[] = "resetPrintPreviewMode";
92 const char kJSPrintPreviewUrl[] = "url";
93 const char kJSPrintPreviewGrayscale[] = "grayscale";
94 const char kJSPrintPreviewPageCount[] = "pageCount";
95 // Load preview page (Page -> Plugin)
96 const char kJSLoadPreviewPageType[] = "loadPreviewPage";
97 const char kJSPreviewPageUrl[] = "url";
98 const char kJSPreviewPageIndex[] = "index";
99 // Set scroll position (Plugin -> Page)
100 const char kJSSetScrollPositionType[] = "setScrollPosition";
101 const char kJSPositionX[] = "x";
102 const char kJSPositionY[] = "y";
103 // Set translated strings (Plugin -> Page)
104 const char kJSSetTranslatedStringsType[] = "setTranslatedStrings";
105 const char kJSGetPasswordString[] = "getPasswordString";
106 const char kJSLoadingString[] = "loadingString";
107 const char kJSLoadFailedString[] = "loadFailedString";
108 // Request accessibility JSON data (Page -> Plugin)
109 const char kJSGetAccessibilityJSONType[] = "getAccessibilityJSON";
110 const char kJSAccessibilityPageNumber[] = "page";
111 // Reply with accessibility JSON data (Plugin -> Page)
112 const char kJSGetAccessibilityJSONReplyType[] = "getAccessibilityJSONReply";
113 const char kJSAccessibilityJSON[] = "json";
114 // Cancel the stream URL request (Plugin -> Page)
115 const char kJSCancelStreamUrlType[] = "cancelStreamUrl";
116 // Navigate to the given URL (Plugin -> Page)
117 const char kJSNavigateType[] = "navigate";
118 const char kJSNavigateUrl[] = "url";
119 const char kJSNavigateNewTab[] = "newTab";
120 // Open the email editor with the given parameters (Plugin -> Page)
121 const char kJSEmailType[] = "email";
122 const char kJSEmailTo[] = "to";
123 const char kJSEmailCc[] = "cc";
124 const char kJSEmailBcc[] = "bcc";
125 const char kJSEmailSubject[] = "subject";
126 const char kJSEmailBody[] = "body";
127 // Rotation (Page -> Plugin)
128 const char kJSRotateClockwiseType[] = "rotateClockwise";
129 const char kJSRotateCounterclockwiseType[] = "rotateCounterclockwise";
130 // Select all text in the document (Page -> Plugin)
131 const char kJSSelectAllType[] = "selectAll";
133 const int kFindResultCooldownMs = 100;
135 const double kMinZoom = 0.01;
137 namespace {
139 static const char kPPPPdfInterface[] = PPP_PDF_INTERFACE_1;
141 PP_Var GetLinkAtPosition(PP_Instance instance, PP_Point point) {
142 pp::Var var;
143 void* object = pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
144 if (object) {
145 var = static_cast<OutOfProcessInstance*>(object)->GetLinkAtPosition(
146 pp::Point(point));
148 return var.Detach();
151 void Transform(PP_Instance instance, PP_PrivatePageTransformType type) {
152 void* object =
153 pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
154 if (object) {
155 OutOfProcessInstance* obj_instance =
156 static_cast<OutOfProcessInstance*>(object);
157 switch (type) {
158 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CW:
159 obj_instance->RotateClockwise();
160 break;
161 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CCW:
162 obj_instance->RotateCounterclockwise();
163 break;
168 const PPP_Pdf ppp_private = {
169 &GetLinkAtPosition,
170 &Transform
173 int ExtractPrintPreviewPageIndex(const std::string& src_url) {
174 // Sample |src_url| format: chrome://print/id/page_index/print.pdf
175 std::vector<std::string> url_substr;
176 base::SplitString(src_url.substr(strlen(kChromePrint)), '/', &url_substr);
177 if (url_substr.size() != 3)
178 return -1;
180 if (url_substr[2] != "print.pdf")
181 return -1;
183 int page_index = 0;
184 if (!base::StringToInt(url_substr[1], &page_index))
185 return -1;
186 return page_index;
189 bool IsPrintPreviewUrl(const std::string& url) {
190 return url.substr(0, strlen(kChromePrint)) == kChromePrint;
193 void ScalePoint(float scale, pp::Point* point) {
194 point->set_x(static_cast<int>(point->x() * scale));
195 point->set_y(static_cast<int>(point->y() * scale));
198 void ScaleRect(float scale, pp::Rect* rect) {
199 int left = static_cast<int>(floorf(rect->x() * scale));
200 int top = static_cast<int>(floorf(rect->y() * scale));
201 int right = static_cast<int>(ceilf((rect->x() + rect->width()) * scale));
202 int bottom = static_cast<int>(ceilf((rect->y() + rect->height()) * scale));
203 rect->SetRect(left, top, right - left, bottom - top);
206 // TODO(raymes): Remove this dependency on VarPrivate/InstancePrivate. It's
207 // needed right now to do a synchronous call to JavaScript, but we could easily
208 // replace this with a custom PPB_PDF function.
209 pp::Var ModalDialog(const pp::Instance* instance,
210 const std::string& type,
211 const std::string& message,
212 const std::string& default_answer) {
213 const PPB_Instance_Private* interface =
214 reinterpret_cast<const PPB_Instance_Private*>(
215 pp::Module::Get()->GetBrowserInterface(
216 PPB_INSTANCE_PRIVATE_INTERFACE));
217 pp::VarPrivate window(pp::PASS_REF,
218 interface->GetWindowObject(instance->pp_instance()));
219 if (default_answer.empty())
220 return window.Call(type, message);
221 else
222 return window.Call(type, message, default_answer);
225 } // namespace
227 OutOfProcessInstance::OutOfProcessInstance(PP_Instance instance)
228 : pp::Instance(instance),
229 pp::Find_Private(this),
230 pp::Printing_Dev(this),
231 pp::Selection_Dev(this),
232 cursor_(PP_CURSORTYPE_POINTER),
233 zoom_(1.0),
234 device_scale_(1.0),
235 printing_enabled_(true),
236 full_(false),
237 paint_manager_(this, this, true),
238 first_paint_(true),
239 document_load_state_(LOAD_STATE_LOADING),
240 preview_document_load_state_(LOAD_STATE_COMPLETE),
241 uma_(this),
242 told_browser_about_unsupported_feature_(false),
243 print_preview_page_count_(0),
244 last_progress_sent_(0),
245 recently_sent_find_update_(false),
246 received_viewport_message_(false),
247 did_call_start_loading_(false),
248 stop_scrolling_(false) {
249 loader_factory_.Initialize(this);
250 timer_factory_.Initialize(this);
251 form_factory_.Initialize(this);
252 print_callback_factory_.Initialize(this);
253 engine_.reset(PDFEngine::Create(this));
254 pp::Module::Get()->AddPluginInterface(kPPPPdfInterface, &ppp_private);
255 AddPerInstanceObject(kPPPPdfInterface, this);
257 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_MOUSE);
258 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_KEYBOARD);
259 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_TOUCH);
262 OutOfProcessInstance::~OutOfProcessInstance() {
263 RemovePerInstanceObject(kPPPPdfInterface, this);
266 bool OutOfProcessInstance::Init(uint32_t argc,
267 const char* argn[],
268 const char* argv[]) {
269 // Check if the PDF is being loaded in the PDF chrome extension. We only allow
270 // the plugin to be put into "full frame" mode when it is being loaded in the
271 // extension because this enables some features that we don't want pages
272 // abusing outside of the extension.
273 pp::Var document_url_var = pp::URLUtil_Dev::Get()->GetDocumentURL(this);
274 std::string document_url = document_url_var.is_string() ?
275 document_url_var.AsString() : std::string();
276 std::string extension_url = std::string(kChromeExtension);
277 bool in_extension =
278 !document_url.compare(0, extension_url.size(), extension_url);
280 if (in_extension) {
281 // Check if the plugin is full frame. This is passed in from JS.
282 for (uint32_t i = 0; i < argc; ++i) {
283 if (strcmp(argn[i], "full-frame") == 0) {
284 full_ = true;
285 break;
290 // Only allow the plugin to handle find requests if it is full frame.
291 if (full_)
292 SetPluginToHandleFindRequests();
294 // Send translated strings to the extension where they will be displayed.
295 // TODO(raymes): It would be better to get these in the extension directly
296 // through an API but no such API currently exists.
297 pp::VarDictionary translated_strings;
298 translated_strings.Set(kType, kJSSetTranslatedStringsType);
299 translated_strings.Set(kJSGetPasswordString,
300 GetLocalizedString(PP_RESOURCESTRING_PDFGETPASSWORD));
301 translated_strings.Set(kJSLoadingString,
302 GetLocalizedString(PP_RESOURCESTRING_PDFLOADING));
303 translated_strings.Set(kJSLoadFailedString,
304 GetLocalizedString(PP_RESOURCESTRING_PDFLOAD_FAILED));
305 PostMessage(translated_strings);
307 text_input_.reset(new pp::TextInput_Dev(this));
309 const char* stream_url = NULL;
310 const char* original_url = NULL;
311 const char* headers = NULL;
312 for (uint32_t i = 0; i < argc; ++i) {
313 if (strcmp(argn[i], "src") == 0)
314 original_url = argv[i];
315 else if (strcmp(argn[i], "stream-url") == 0)
316 stream_url = argv[i];
317 else if (strcmp(argn[i], "headers") == 0)
318 headers = argv[i];
321 // TODO(raymes): This is a hack to ensure that if no headers are passed in
322 // then we get the right MIME type. When the in process plugin is removed we
323 // can fix the document loader properly and remove this hack.
324 if (!headers || strcmp(headers, "") == 0)
325 headers = "content-type: application/pdf";
327 if (!original_url)
328 return false;
330 if (!stream_url)
331 stream_url = original_url;
333 // If we're in print preview mode we don't need to load the document yet.
334 // A |kJSResetPrintPreviewModeType| message will be sent to the plugin letting
335 // it know the url to load. By not loading here we avoid loading the same
336 // document twice.
337 if (IsPrintPreviewUrl(original_url))
338 return true;
340 LoadUrl(stream_url);
341 url_ = original_url;
342 return engine_->New(original_url, headers);
345 void OutOfProcessInstance::HandleMessage(const pp::Var& message) {
346 pp::VarDictionary dict(message);
347 if (!dict.Get(kType).is_string()) {
348 NOTREACHED();
349 return;
352 std::string type = dict.Get(kType).AsString();
354 if (type == kJSViewportType &&
355 dict.Get(pp::Var(kJSXOffset)).is_number() &&
356 dict.Get(pp::Var(kJSYOffset)).is_number() &&
357 dict.Get(pp::Var(kJSZoom)).is_number()) {
358 received_viewport_message_ = true;
359 stop_scrolling_ = false;
360 double zoom = dict.Get(pp::Var(kJSZoom)).AsDouble();
361 pp::FloatPoint scroll_offset(dict.Get(pp::Var(kJSXOffset)).AsDouble(),
362 dict.Get(pp::Var(kJSYOffset)).AsDouble());
364 // Bound the input parameters.
365 zoom = std::max(kMinZoom, zoom);
366 SetZoom(zoom);
367 scroll_offset = BoundScrollOffsetToDocument(scroll_offset);
368 engine_->ScrolledToXPosition(scroll_offset.x() * device_scale_);
369 engine_->ScrolledToYPosition(scroll_offset.y() * device_scale_);
370 } else if (type == kJSGetPasswordCompleteType &&
371 dict.Get(pp::Var(kJSPassword)).is_string()) {
372 if (password_callback_) {
373 pp::CompletionCallbackWithOutput<pp::Var> callback = *password_callback_;
374 password_callback_.reset();
375 *callback.output() = dict.Get(pp::Var(kJSPassword)).pp_var();
376 callback.Run(PP_OK);
377 } else {
378 NOTREACHED();
380 } else if (type == kJSPrintType) {
381 Print();
382 } else if (type == kJSRotateClockwiseType) {
383 RotateClockwise();
384 } else if (type == kJSRotateCounterclockwiseType) {
385 RotateCounterclockwise();
386 } else if (type == kJSSelectAllType) {
387 engine_->SelectAll();
388 } else if (type == kJSResetPrintPreviewModeType &&
389 dict.Get(pp::Var(kJSPrintPreviewUrl)).is_string() &&
390 dict.Get(pp::Var(kJSPrintPreviewGrayscale)).is_bool() &&
391 dict.Get(pp::Var(kJSPrintPreviewPageCount)).is_int()) {
392 url_ = dict.Get(pp::Var(kJSPrintPreviewUrl)).AsString();
393 preview_pages_info_ = std::queue<PreviewPageInfo>();
394 preview_document_load_state_ = LOAD_STATE_COMPLETE;
395 document_load_state_ = LOAD_STATE_LOADING;
396 LoadUrl(url_);
397 preview_engine_.reset();
398 engine_.reset(PDFEngine::Create(this));
399 engine_->SetGrayscale(dict.Get(pp::Var(kJSPrintPreviewGrayscale)).AsBool());
400 engine_->New(url_.c_str());
402 print_preview_page_count_ =
403 std::max(dict.Get(pp::Var(kJSPrintPreviewPageCount)).AsInt(), 0);
405 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
406 } else if (type == kJSLoadPreviewPageType &&
407 dict.Get(pp::Var(kJSPreviewPageUrl)).is_string() &&
408 dict.Get(pp::Var(kJSPreviewPageIndex)).is_int()) {
409 ProcessPreviewPageInfo(dict.Get(pp::Var(kJSPreviewPageUrl)).AsString(),
410 dict.Get(pp::Var(kJSPreviewPageIndex)).AsInt());
411 } else if (type == kJSGetAccessibilityJSONType) {
412 pp::VarDictionary reply;
413 reply.Set(pp::Var(kType), pp::Var(kJSGetAccessibilityJSONReplyType));
414 if (dict.Get(pp::Var(kJSAccessibilityPageNumber)).is_int()) {
415 int page = dict.Get(pp::Var(kJSAccessibilityPageNumber)).AsInt();
416 reply.Set(pp::Var(kJSAccessibilityJSON),
417 pp::Var(engine_->GetPageAsJSON(page)));
418 } else {
419 base::DictionaryValue node;
420 node.SetInteger(kAccessibleNumberOfPages, engine_->GetNumberOfPages());
421 node.SetBoolean(kAccessibleLoaded,
422 document_load_state_ != LOAD_STATE_LOADING);
423 bool has_permissions =
424 engine_->HasPermission(PDFEngine::PERMISSION_COPY) ||
425 engine_->HasPermission(PDFEngine::PERMISSION_COPY_ACCESSIBLE);
426 node.SetBoolean(kAccessibleCopyable, has_permissions);
427 std::string json;
428 base::JSONWriter::Write(&node, &json);
429 reply.Set(pp::Var(kJSAccessibilityJSON), pp::Var(json));
431 PostMessage(reply);
432 } else if (type == kJSStopScrollingType) {
433 stop_scrolling_ = true;
434 } else {
435 NOTREACHED();
439 bool OutOfProcessInstance::HandleInputEvent(
440 const pp::InputEvent& event) {
441 // To simplify things, convert the event into device coordinates if it is
442 // a mouse event.
443 pp::InputEvent event_device_res(event);
445 pp::MouseInputEvent mouse_event(event);
446 if (!mouse_event.is_null()) {
447 pp::Point point = mouse_event.GetPosition();
448 pp::Point movement = mouse_event.GetMovement();
449 ScalePoint(device_scale_, &point);
450 ScalePoint(device_scale_, &movement);
451 mouse_event = pp::MouseInputEvent(
452 this,
453 event.GetType(),
454 event.GetTimeStamp(),
455 event.GetModifiers(),
456 mouse_event.GetButton(),
457 point,
458 mouse_event.GetClickCount(),
459 movement);
460 event_device_res = mouse_event;
464 pp::InputEvent offset_event(event_device_res);
465 switch (offset_event.GetType()) {
466 case PP_INPUTEVENT_TYPE_MOUSEDOWN:
467 case PP_INPUTEVENT_TYPE_MOUSEUP:
468 case PP_INPUTEVENT_TYPE_MOUSEMOVE:
469 case PP_INPUTEVENT_TYPE_MOUSEENTER:
470 case PP_INPUTEVENT_TYPE_MOUSELEAVE: {
471 pp::MouseInputEvent mouse_event(event_device_res);
472 pp::MouseInputEvent mouse_event_dip(event);
473 pp::Point point = mouse_event.GetPosition();
474 point.set_x(point.x() - available_area_.x());
475 offset_event = pp::MouseInputEvent(
476 this,
477 event.GetType(),
478 event.GetTimeStamp(),
479 event.GetModifiers(),
480 mouse_event.GetButton(),
481 point,
482 mouse_event.GetClickCount(),
483 mouse_event.GetMovement());
484 break;
486 default:
487 break;
489 if (engine_->HandleEvent(offset_event))
490 return true;
492 // TODO(raymes): Implement this scroll behavior in JS:
493 // When click+dragging, scroll the document correctly.
495 // Return true for unhandled clicks so the plugin takes focus.
496 return (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN);
499 void OutOfProcessInstance::DidChangeView(const pp::View& view) {
500 pp::Rect view_rect(view.GetRect());
501 float old_device_scale = device_scale_;
502 float device_scale = view.GetDeviceScale();
503 pp::Size view_device_size(view_rect.width() * device_scale,
504 view_rect.height() * device_scale);
506 if (view_device_size != plugin_size_ || device_scale != device_scale_) {
507 device_scale_ = device_scale;
508 plugin_dip_size_ = view_rect.size();
509 plugin_size_ = view_device_size;
511 paint_manager_.SetSize(view_device_size, device_scale_);
513 pp::Size new_image_data_size = PaintManager::GetNewContextSize(
514 image_data_.size(),
515 plugin_size_);
516 if (new_image_data_size != image_data_.size()) {
517 image_data_ = pp::ImageData(this,
518 PP_IMAGEDATAFORMAT_BGRA_PREMUL,
519 new_image_data_size,
520 false);
521 first_paint_ = true;
524 if (image_data_.is_null()) {
525 DCHECK(plugin_size_.IsEmpty());
526 return;
529 OnGeometryChanged(zoom_, old_device_scale);
532 if (!stop_scrolling_) {
533 pp::Point scroll_offset(view.GetScrollOffset());
534 pp::FloatPoint scroll_offset_float(scroll_offset.x(),
535 scroll_offset.y());
536 scroll_offset_float = BoundScrollOffsetToDocument(scroll_offset_float);
537 engine_->ScrolledToXPosition(scroll_offset_float.x() * device_scale_);
538 engine_->ScrolledToYPosition(scroll_offset_float.y() * device_scale_);
542 pp::Var OutOfProcessInstance::GetLinkAtPosition(
543 const pp::Point& point) {
544 pp::Point offset_point(point);
545 ScalePoint(device_scale_, &offset_point);
546 offset_point.set_x(offset_point.x() - available_area_.x());
547 return engine_->GetLinkAtPosition(offset_point);
550 pp::Var OutOfProcessInstance::GetSelectedText(bool html) {
551 if (html || !engine_->HasPermission(PDFEngine::PERMISSION_COPY))
552 return pp::Var();
553 return engine_->GetSelectedText();
556 uint32_t OutOfProcessInstance::QuerySupportedPrintOutputFormats() {
557 return engine_->QuerySupportedPrintOutputFormats();
560 int32_t OutOfProcessInstance::PrintBegin(
561 const PP_PrintSettings_Dev& print_settings) {
562 // For us num_pages is always equal to the number of pages in the PDF
563 // document irrespective of the printable area.
564 int32_t ret = engine_->GetNumberOfPages();
565 if (!ret)
566 return 0;
568 uint32_t supported_formats = engine_->QuerySupportedPrintOutputFormats();
569 if ((print_settings.format & supported_formats) == 0)
570 return 0;
572 print_settings_.is_printing = true;
573 print_settings_.pepper_print_settings = print_settings;
574 engine_->PrintBegin();
575 return ret;
578 pp::Resource OutOfProcessInstance::PrintPages(
579 const PP_PrintPageNumberRange_Dev* page_ranges,
580 uint32_t page_range_count) {
581 if (!print_settings_.is_printing)
582 return pp::Resource();
584 print_settings_.print_pages_called_ = true;
585 return engine_->PrintPages(page_ranges, page_range_count,
586 print_settings_.pepper_print_settings);
589 void OutOfProcessInstance::PrintEnd() {
590 if (print_settings_.print_pages_called_)
591 UserMetricsRecordAction("PDF.PrintPage");
592 print_settings_.Clear();
593 engine_->PrintEnd();
596 bool OutOfProcessInstance::IsPrintScalingDisabled() {
597 return !engine_->GetPrintScaling();
600 bool OutOfProcessInstance::StartFind(const std::string& text,
601 bool case_sensitive) {
602 engine_->StartFind(text.c_str(), case_sensitive);
603 return true;
606 void OutOfProcessInstance::SelectFindResult(bool forward) {
607 engine_->SelectFindResult(forward);
610 void OutOfProcessInstance::StopFind() {
611 engine_->StopFind();
612 tickmarks_.clear();
613 SetTickmarks(tickmarks_);
616 void OutOfProcessInstance::OnPaint(
617 const std::vector<pp::Rect>& paint_rects,
618 std::vector<PaintManager::ReadyRect>* ready,
619 std::vector<pp::Rect>* pending) {
620 if (image_data_.is_null()) {
621 DCHECK(plugin_size_.IsEmpty());
622 return;
624 if (first_paint_) {
625 first_paint_ = false;
626 pp::Rect rect = pp::Rect(pp::Point(), image_data_.size());
627 FillRect(rect, kBackgroundColor);
628 ready->push_back(PaintManager::ReadyRect(rect, image_data_, true));
631 if (!received_viewport_message_)
632 return;
634 engine_->PrePaint();
636 for (size_t i = 0; i < paint_rects.size(); i++) {
637 // Intersect with plugin area since there could be pending invalidates from
638 // when the plugin area was larger.
639 pp::Rect rect =
640 paint_rects[i].Intersect(pp::Rect(pp::Point(), plugin_size_));
641 if (rect.IsEmpty())
642 continue;
644 pp::Rect pdf_rect = available_area_.Intersect(rect);
645 if (!pdf_rect.IsEmpty()) {
646 pdf_rect.Offset(available_area_.x() * -1, 0);
648 std::vector<pp::Rect> pdf_ready;
649 std::vector<pp::Rect> pdf_pending;
650 engine_->Paint(pdf_rect, &image_data_, &pdf_ready, &pdf_pending);
651 for (size_t j = 0; j < pdf_ready.size(); ++j) {
652 pdf_ready[j].Offset(available_area_.point());
653 ready->push_back(
654 PaintManager::ReadyRect(pdf_ready[j], image_data_, false));
656 for (size_t j = 0; j < pdf_pending.size(); ++j) {
657 pdf_pending[j].Offset(available_area_.point());
658 pending->push_back(pdf_pending[j]);
662 for (size_t j = 0; j < background_parts_.size(); ++j) {
663 pp::Rect intersection = background_parts_[j].location.Intersect(rect);
664 if (!intersection.IsEmpty()) {
665 FillRect(intersection, background_parts_[j].color);
666 ready->push_back(
667 PaintManager::ReadyRect(intersection, image_data_, false));
672 engine_->PostPaint();
675 void OutOfProcessInstance::DidOpen(int32_t result) {
676 if (result == PP_OK) {
677 if (!engine_->HandleDocumentLoad(embed_loader_)) {
678 document_load_state_ = LOAD_STATE_LOADING;
679 DocumentLoadFailed();
681 } else if (result != PP_ERROR_ABORTED) { // Can happen in tests.
682 NOTREACHED();
683 DocumentLoadFailed();
686 // If it's a progressive load, cancel the stream URL request so that requests
687 // can be made on the original URL.
688 // TODO(raymes): Make this clearer once the in-process plugin is deleted.
689 if (engine_->IsProgressiveLoad()) {
690 pp::VarDictionary message;
691 message.Set(kType, kJSCancelStreamUrlType);
692 PostMessage(message);
696 void OutOfProcessInstance::DidOpenPreview(int32_t result) {
697 if (result == PP_OK) {
698 preview_engine_.reset(PDFEngine::Create(new PreviewModeClient(this)));
699 preview_engine_->HandleDocumentLoad(embed_preview_loader_);
700 } else {
701 NOTREACHED();
705 void OutOfProcessInstance::OnClientTimerFired(int32_t id) {
706 engine_->OnCallback(id);
709 void OutOfProcessInstance::CalculateBackgroundParts() {
710 background_parts_.clear();
711 int left_width = available_area_.x();
712 int right_start = available_area_.right();
713 int right_width = abs(plugin_size_.width() - available_area_.right());
714 int bottom = std::min(available_area_.bottom(), plugin_size_.height());
716 // Add the left, right, and bottom rectangles. Note: we assume only
717 // horizontal centering.
718 BackgroundPart part = {
719 pp::Rect(0, 0, left_width, bottom),
720 kBackgroundColor
722 if (!part.location.IsEmpty())
723 background_parts_.push_back(part);
724 part.location = pp::Rect(right_start, 0, right_width, bottom);
725 if (!part.location.IsEmpty())
726 background_parts_.push_back(part);
727 part.location = pp::Rect(
728 0, bottom, plugin_size_.width(), plugin_size_.height() - bottom);
729 if (!part.location.IsEmpty())
730 background_parts_.push_back(part);
733 int OutOfProcessInstance::GetDocumentPixelWidth() const {
734 return static_cast<int>(ceil(document_size_.width() * zoom_ * device_scale_));
737 int OutOfProcessInstance::GetDocumentPixelHeight() const {
738 return static_cast<int>(
739 ceil(document_size_.height() * zoom_ * device_scale_));
742 void OutOfProcessInstance::FillRect(const pp::Rect& rect, uint32 color) {
743 DCHECK(!image_data_.is_null() || rect.IsEmpty());
744 uint32* buffer_start = static_cast<uint32*>(image_data_.data());
745 int stride = image_data_.stride();
746 uint32* ptr = buffer_start + rect.y() * stride / 4 + rect.x();
747 int height = rect.height();
748 int width = rect.width();
749 for (int y = 0; y < height; ++y) {
750 for (int x = 0; x < width; ++x)
751 *(ptr + x) = color;
752 ptr += stride /4;
756 void OutOfProcessInstance::DocumentSizeUpdated(const pp::Size& size) {
757 document_size_ = size;
759 pp::VarDictionary dimensions;
760 dimensions.Set(kType, kJSDocumentDimensionsType);
761 dimensions.Set(kJSDocumentWidth, pp::Var(document_size_.width()));
762 dimensions.Set(kJSDocumentHeight, pp::Var(document_size_.height()));
763 pp::VarArray page_dimensions_array;
764 int num_pages = engine_->GetNumberOfPages();
765 for (int i = 0; i < num_pages; ++i) {
766 pp::Rect page_rect = engine_->GetPageRect(i);
767 pp::VarDictionary page_dimensions;
768 page_dimensions.Set(kJSPageX, pp::Var(page_rect.x()));
769 page_dimensions.Set(kJSPageY, pp::Var(page_rect.y()));
770 page_dimensions.Set(kJSPageWidth, pp::Var(page_rect.width()));
771 page_dimensions.Set(kJSPageHeight, pp::Var(page_rect.height()));
772 page_dimensions_array.Set(i, page_dimensions);
774 dimensions.Set(kJSPageDimensions, page_dimensions_array);
775 PostMessage(dimensions);
777 OnGeometryChanged(zoom_, device_scale_);
780 void OutOfProcessInstance::Invalidate(const pp::Rect& rect) {
781 pp::Rect offset_rect(rect);
782 offset_rect.Offset(available_area_.point());
783 paint_manager_.InvalidateRect(offset_rect);
786 void OutOfProcessInstance::Scroll(const pp::Point& point) {
787 if (!image_data_.is_null())
788 paint_manager_.ScrollRect(available_area_, point);
791 void OutOfProcessInstance::ScrollToX(int x) {
792 pp::VarDictionary position;
793 position.Set(kType, kJSSetScrollPositionType);
794 position.Set(kJSPositionX, pp::Var(x / device_scale_));
795 PostMessage(position);
798 void OutOfProcessInstance::ScrollToY(int y) {
799 pp::VarDictionary position;
800 position.Set(kType, kJSSetScrollPositionType);
801 position.Set(kJSPositionY, pp::Var(y / device_scale_));
802 PostMessage(position);
805 void OutOfProcessInstance::ScrollToPage(int page) {
806 if (engine_->GetNumberOfPages() == 0)
807 return;
809 pp::VarDictionary message;
810 message.Set(kType, kJSGoToPageType);
811 message.Set(kJSPageNumber, pp::Var(page));
812 PostMessage(message);
815 void OutOfProcessInstance::NavigateTo(const std::string& url,
816 bool open_in_new_tab) {
817 std::string url_copy(url);
819 // Empty |url_copy| is ok, and will effectively be a reload.
820 // Skip the code below so an empty URL does not turn into "http://", which
821 // will cause GURL to fail a DCHECK.
822 if (!url_copy.empty()) {
823 // If |url_copy| starts with '#', then it's for the same URL with a
824 // different URL fragment.
825 if (url_copy[0] == '#') {
826 url_copy = url_ + url_copy;
828 // If there's no scheme, add http.
829 if (url_copy.find("://") == std::string::npos &&
830 url_copy.find("mailto:") == std::string::npos) {
831 url_copy = std::string("http://") + url_copy;
833 // Make sure |url_copy| starts with a valid scheme.
834 if (url_copy.find("http://") != 0 &&
835 url_copy.find("https://") != 0 &&
836 url_copy.find("ftp://") != 0 &&
837 url_copy.find("file://") != 0 &&
838 url_copy.find("mailto:") != 0) {
839 return;
841 // Make sure |url_copy| is not only a scheme.
842 if (url_copy == "http://" ||
843 url_copy == "https://" ||
844 url_copy == "ftp://" ||
845 url_copy == "file://" ||
846 url_copy == "mailto:") {
847 return;
850 pp::VarDictionary message;
851 message.Set(kType, kJSNavigateType);
852 message.Set(kJSNavigateUrl, url_copy);
853 message.Set(kJSNavigateNewTab, open_in_new_tab);
854 PostMessage(message);
857 void OutOfProcessInstance::UpdateCursor(PP_CursorType_Dev cursor) {
858 if (cursor == cursor_)
859 return;
860 cursor_ = cursor;
862 const PPB_CursorControl_Dev* cursor_interface =
863 reinterpret_cast<const PPB_CursorControl_Dev*>(
864 pp::Module::Get()->GetBrowserInterface(PPB_CURSOR_CONTROL_DEV_INTERFACE));
865 if (!cursor_interface) {
866 NOTREACHED();
867 return;
870 cursor_interface->SetCursor(
871 pp_instance(), cursor_, pp::ImageData().pp_resource(), NULL);
874 void OutOfProcessInstance::UpdateTickMarks(
875 const std::vector<pp::Rect>& tickmarks) {
876 float inverse_scale = 1.0f / device_scale_;
877 std::vector<pp::Rect> scaled_tickmarks = tickmarks;
878 for (size_t i = 0; i < scaled_tickmarks.size(); i++)
879 ScaleRect(inverse_scale, &scaled_tickmarks[i]);
880 tickmarks_ = scaled_tickmarks;
883 void OutOfProcessInstance::NotifyNumberOfFindResultsChanged(int total,
884 bool final_result) {
885 // We don't want to spam the renderer with too many updates to the number of
886 // find results. Don't send an update if we sent one too recently. If it's the
887 // final update, we always send it though.
888 if (final_result) {
889 NumberOfFindResultsChanged(total, final_result);
890 SetTickmarks(tickmarks_);
891 return;
894 if (recently_sent_find_update_)
895 return;
897 NumberOfFindResultsChanged(total, final_result);
898 SetTickmarks(tickmarks_);
899 recently_sent_find_update_ = true;
900 pp::CompletionCallback callback =
901 timer_factory_.NewCallback(
902 &OutOfProcessInstance::ResetRecentlySentFindUpdate);
903 pp::Module::Get()->core()->CallOnMainThread(kFindResultCooldownMs,
904 callback, 0);
907 void OutOfProcessInstance::NotifySelectedFindResultChanged(
908 int current_find_index) {
909 DCHECK_GE(current_find_index, 0);
910 SelectedFindResultChanged(current_find_index);
913 void OutOfProcessInstance::GetDocumentPassword(
914 pp::CompletionCallbackWithOutput<pp::Var> callback) {
915 if (password_callback_) {
916 NOTREACHED();
917 return;
920 password_callback_.reset(
921 new pp::CompletionCallbackWithOutput<pp::Var>(callback));
922 pp::VarDictionary message;
923 message.Set(pp::Var(kType), pp::Var(kJSGetPasswordType));
924 PostMessage(message);
927 void OutOfProcessInstance::Alert(const std::string& message) {
928 ModalDialog(this, "alert", message, std::string());
931 bool OutOfProcessInstance::Confirm(const std::string& message) {
932 pp::Var result = ModalDialog(this, "confirm", message, std::string());
933 return result.is_bool() ? result.AsBool() : false;
936 std::string OutOfProcessInstance::Prompt(const std::string& question,
937 const std::string& default_answer) {
938 pp::Var result = ModalDialog(this, "prompt", question, default_answer);
939 return result.is_string() ? result.AsString() : std::string();
942 std::string OutOfProcessInstance::GetURL() {
943 return url_;
946 void OutOfProcessInstance::Email(const std::string& to,
947 const std::string& cc,
948 const std::string& bcc,
949 const std::string& subject,
950 const std::string& body) {
951 pp::VarDictionary message;
952 message.Set(pp::Var(kType), pp::Var(kJSEmailType));
953 message.Set(pp::Var(kJSEmailTo),
954 pp::Var(net::EscapeUrlEncodedData(to, false)));
955 message.Set(pp::Var(kJSEmailCc),
956 pp::Var(net::EscapeUrlEncodedData(cc, false)));
957 message.Set(pp::Var(kJSEmailBcc),
958 pp::Var(net::EscapeUrlEncodedData(bcc, false)));
959 message.Set(pp::Var(kJSEmailSubject),
960 pp::Var(net::EscapeUrlEncodedData(subject, false)));
961 message.Set(pp::Var(kJSEmailBody),
962 pp::Var(net::EscapeUrlEncodedData(body, false)));
963 PostMessage(message);
966 void OutOfProcessInstance::Print() {
967 if (!printing_enabled_ ||
968 (!engine_->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY) &&
969 !engine_->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY))) {
970 return;
973 pp::CompletionCallback callback =
974 print_callback_factory_.NewCallback(&OutOfProcessInstance::OnPrint);
975 pp::Module::Get()->core()->CallOnMainThread(0, callback);
978 void OutOfProcessInstance::OnPrint(int32_t) {
979 pp::PDF::Print(this);
982 void OutOfProcessInstance::SubmitForm(const std::string& url,
983 const void* data,
984 int length) {
985 pp::URLRequestInfo request(this);
986 request.SetURL(url);
987 request.SetMethod("POST");
988 request.AppendDataToBody(reinterpret_cast<const char*>(data), length);
990 pp::CompletionCallback callback =
991 form_factory_.NewCallback(&OutOfProcessInstance::FormDidOpen);
992 form_loader_ = CreateURLLoaderInternal();
993 int rv = form_loader_.Open(request, callback);
994 if (rv != PP_OK_COMPLETIONPENDING)
995 callback.Run(rv);
998 void OutOfProcessInstance::FormDidOpen(int32_t result) {
999 // TODO: inform the user of success/failure.
1000 if (result != PP_OK) {
1001 NOTREACHED();
1005 std::string OutOfProcessInstance::ShowFileSelectionDialog() {
1006 // Seems like very low priority to implement, since the pdf has no way to get
1007 // the file data anyways. Javascript doesn't let you do this synchronously.
1008 NOTREACHED();
1009 return std::string();
1012 pp::URLLoader OutOfProcessInstance::CreateURLLoader() {
1013 if (full_) {
1014 if (!did_call_start_loading_) {
1015 did_call_start_loading_ = true;
1016 pp::PDF::DidStartLoading(this);
1019 // Disable save and print until the document is fully loaded, since they
1020 // would generate an incomplete document. Need to do this each time we
1021 // call DidStartLoading since that resets the content restrictions.
1022 pp::PDF::SetContentRestriction(this, CONTENT_RESTRICTION_SAVE |
1023 CONTENT_RESTRICTION_PRINT);
1026 return CreateURLLoaderInternal();
1029 void OutOfProcessInstance::ScheduleCallback(int id, int delay_in_ms) {
1030 pp::CompletionCallback callback =
1031 timer_factory_.NewCallback(&OutOfProcessInstance::OnClientTimerFired);
1032 pp::Module::Get()->core()->CallOnMainThread(delay_in_ms, callback, id);
1035 void OutOfProcessInstance::SearchString(const base::char16* string,
1036 const base::char16* term,
1037 bool case_sensitive,
1038 std::vector<SearchStringResult>* results) {
1039 PP_PrivateFindResult* pp_results;
1040 int count = 0;
1041 pp::PDF::SearchString(
1042 this,
1043 reinterpret_cast<const unsigned short*>(string),
1044 reinterpret_cast<const unsigned short*>(term),
1045 case_sensitive,
1046 &pp_results,
1047 &count);
1049 results->resize(count);
1050 for (int i = 0; i < count; ++i) {
1051 (*results)[i].start_index = pp_results[i].start_index;
1052 (*results)[i].length = pp_results[i].length;
1055 pp::Memory_Dev memory;
1056 memory.MemFree(pp_results);
1059 void OutOfProcessInstance::DocumentPaintOccurred() {
1062 void OutOfProcessInstance::DocumentLoadComplete(int page_count) {
1063 // Clear focus state for OSK.
1064 FormTextFieldFocusChange(false);
1066 DCHECK(document_load_state_ == LOAD_STATE_LOADING);
1067 document_load_state_ = LOAD_STATE_COMPLETE;
1068 UserMetricsRecordAction("PDF.LoadSuccess");
1070 // Note: If we are in print preview mode the scroll location is retained
1071 // across document loads so we don't want to scroll again and override it.
1072 if (IsPrintPreview()) {
1073 AppendBlankPrintPreviewPages();
1074 OnGeometryChanged(0, 0);
1077 pp::VarDictionary message;
1078 message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1079 message.Set(pp::Var(kJSProgressPercentage), pp::Var(100)) ;
1080 PostMessage(message);
1082 if (!full_)
1083 return;
1085 if (did_call_start_loading_) {
1086 pp::PDF::DidStopLoading(this);
1087 did_call_start_loading_ = false;
1090 int content_restrictions =
1091 CONTENT_RESTRICTION_CUT | CONTENT_RESTRICTION_PASTE;
1092 if (!engine_->HasPermission(PDFEngine::PERMISSION_COPY))
1093 content_restrictions |= CONTENT_RESTRICTION_COPY;
1095 if (!engine_->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY) &&
1096 !engine_->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY)) {
1097 printing_enabled_ = false;
1100 pp::PDF::SetContentRestriction(this, content_restrictions);
1102 uma_.HistogramCustomCounts("PDF.PageCount", page_count,
1103 1, 1000000, 50);
1106 void OutOfProcessInstance::RotateClockwise() {
1107 engine_->RotateClockwise();
1110 void OutOfProcessInstance::RotateCounterclockwise() {
1111 engine_->RotateCounterclockwise();
1114 void OutOfProcessInstance::PreviewDocumentLoadComplete() {
1115 if (preview_document_load_state_ != LOAD_STATE_LOADING ||
1116 preview_pages_info_.empty()) {
1117 return;
1120 preview_document_load_state_ = LOAD_STATE_COMPLETE;
1122 int dest_page_index = preview_pages_info_.front().second;
1123 int src_page_index =
1124 ExtractPrintPreviewPageIndex(preview_pages_info_.front().first);
1125 if (src_page_index > 0 && dest_page_index > -1 && preview_engine_.get())
1126 engine_->AppendPage(preview_engine_.get(), dest_page_index);
1128 preview_pages_info_.pop();
1129 // |print_preview_page_count_| is not updated yet. Do not load any
1130 // other preview pages till we get this information.
1131 if (print_preview_page_count_ == 0)
1132 return;
1134 if (preview_pages_info_.size())
1135 LoadAvailablePreviewPage();
1138 void OutOfProcessInstance::DocumentLoadFailed() {
1139 DCHECK(document_load_state_ == LOAD_STATE_LOADING);
1140 UserMetricsRecordAction("PDF.LoadFailure");
1142 if (did_call_start_loading_) {
1143 pp::PDF::DidStopLoading(this);
1144 did_call_start_loading_ = false;
1147 document_load_state_ = LOAD_STATE_FAILED;
1148 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
1150 // Send a progress value of -1 to indicate a failure.
1151 pp::VarDictionary message;
1152 message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1153 message.Set(pp::Var(kJSProgressPercentage), pp::Var(-1)) ;
1154 PostMessage(message);
1157 void OutOfProcessInstance::PreviewDocumentLoadFailed() {
1158 UserMetricsRecordAction("PDF.PreviewDocumentLoadFailure");
1159 if (preview_document_load_state_ != LOAD_STATE_LOADING ||
1160 preview_pages_info_.empty()) {
1161 return;
1164 preview_document_load_state_ = LOAD_STATE_FAILED;
1165 preview_pages_info_.pop();
1167 if (preview_pages_info_.size())
1168 LoadAvailablePreviewPage();
1171 pp::Instance* OutOfProcessInstance::GetPluginInstance() {
1172 return this;
1175 void OutOfProcessInstance::DocumentHasUnsupportedFeature(
1176 const std::string& feature) {
1177 std::string metric("PDF_Unsupported_");
1178 metric += feature;
1179 if (!unsupported_features_reported_.count(metric)) {
1180 unsupported_features_reported_.insert(metric);
1181 UserMetricsRecordAction(metric);
1184 // Since we use an info bar, only do this for full frame plugins..
1185 if (!full_)
1186 return;
1188 if (told_browser_about_unsupported_feature_)
1189 return;
1190 told_browser_about_unsupported_feature_ = true;
1192 pp::PDF::HasUnsupportedFeature(this);
1195 void OutOfProcessInstance::DocumentLoadProgress(uint32 available,
1196 uint32 doc_size) {
1197 double progress = 0.0;
1198 if (doc_size == 0) {
1199 // Document size is unknown. Use heuristics.
1200 // We'll make progress logarithmic from 0 to 100M.
1201 static const double kFactor = log(100000000.0) / 100.0;
1202 if (available > 0) {
1203 progress = log(static_cast<double>(available)) / kFactor;
1204 if (progress > 100.0)
1205 progress = 100.0;
1207 } else {
1208 progress = 100.0 * static_cast<double>(available) / doc_size;
1211 // We send 100% load progress in DocumentLoadComplete.
1212 if (progress >= 100)
1213 return;
1215 // Avoid sending too many progress messages over PostMessage.
1216 if (progress > last_progress_sent_ + 1) {
1217 last_progress_sent_ = progress;
1218 pp::VarDictionary message;
1219 message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1220 message.Set(pp::Var(kJSProgressPercentage), pp::Var(progress)) ;
1221 PostMessage(message);
1225 void OutOfProcessInstance::FormTextFieldFocusChange(bool in_focus) {
1226 if (!text_input_.get())
1227 return;
1228 if (in_focus)
1229 text_input_->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_TEXT);
1230 else
1231 text_input_->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_NONE);
1234 void OutOfProcessInstance::ResetRecentlySentFindUpdate(int32_t /* unused */) {
1235 recently_sent_find_update_ = false;
1238 void OutOfProcessInstance::OnGeometryChanged(double old_zoom,
1239 float old_device_scale) {
1240 if (zoom_ != old_zoom || device_scale_ != old_device_scale)
1241 engine_->ZoomUpdated(zoom_ * device_scale_);
1243 available_area_ = pp::Rect(plugin_size_);
1244 int doc_width = GetDocumentPixelWidth();
1245 if (doc_width < available_area_.width()) {
1246 available_area_.Offset((available_area_.width() - doc_width) / 2, 0);
1247 available_area_.set_width(doc_width);
1249 int doc_height = GetDocumentPixelHeight();
1250 if (doc_height < available_area_.height()) {
1251 available_area_.set_height(doc_height);
1254 CalculateBackgroundParts();
1255 engine_->PageOffsetUpdated(available_area_.point());
1256 engine_->PluginSizeUpdated(available_area_.size());
1258 if (!document_size_.GetArea())
1259 return;
1260 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
1263 void OutOfProcessInstance::LoadUrl(const std::string& url) {
1264 LoadUrlInternal(url, &embed_loader_, &OutOfProcessInstance::DidOpen);
1267 void OutOfProcessInstance::LoadPreviewUrl(const std::string& url) {
1268 LoadUrlInternal(url, &embed_preview_loader_,
1269 &OutOfProcessInstance::DidOpenPreview);
1272 void OutOfProcessInstance::LoadUrlInternal(
1273 const std::string& url,
1274 pp::URLLoader* loader,
1275 void (OutOfProcessInstance::* method)(int32_t)) {
1276 pp::URLRequestInfo request(this);
1277 request.SetURL(url);
1278 request.SetMethod("GET");
1280 *loader = CreateURLLoaderInternal();
1281 pp::CompletionCallback callback = loader_factory_.NewCallback(method);
1282 int rv = loader->Open(request, callback);
1283 if (rv != PP_OK_COMPLETIONPENDING)
1284 callback.Run(rv);
1287 pp::URLLoader OutOfProcessInstance::CreateURLLoaderInternal() {
1288 pp::URLLoader loader(this);
1290 const PPB_URLLoaderTrusted* trusted_interface =
1291 reinterpret_cast<const PPB_URLLoaderTrusted*>(
1292 pp::Module::Get()->GetBrowserInterface(
1293 PPB_URLLOADERTRUSTED_INTERFACE));
1294 if (trusted_interface)
1295 trusted_interface->GrantUniversalAccess(loader.pp_resource());
1296 return loader;
1299 void OutOfProcessInstance::SetZoom(double scale) {
1300 double old_zoom = zoom_;
1301 zoom_ = scale;
1302 OnGeometryChanged(old_zoom, device_scale_);
1305 std::string OutOfProcessInstance::GetLocalizedString(PP_ResourceString id) {
1306 pp::Var rv(pp::PDF::GetLocalizedString(this, id));
1307 if (!rv.is_string())
1308 return std::string();
1310 return rv.AsString();
1313 void OutOfProcessInstance::AppendBlankPrintPreviewPages() {
1314 if (print_preview_page_count_ == 0)
1315 return;
1316 engine_->AppendBlankPages(print_preview_page_count_);
1317 if (preview_pages_info_.size() > 0)
1318 LoadAvailablePreviewPage();
1321 bool OutOfProcessInstance::IsPrintPreview() {
1322 return IsPrintPreviewUrl(url_);
1325 void OutOfProcessInstance::ProcessPreviewPageInfo(const std::string& url,
1326 int dst_page_index) {
1327 if (!IsPrintPreview())
1328 return;
1330 int src_page_index = ExtractPrintPreviewPageIndex(url);
1331 if (src_page_index < 1)
1332 return;
1334 preview_pages_info_.push(std::make_pair(url, dst_page_index));
1335 LoadAvailablePreviewPage();
1338 void OutOfProcessInstance::LoadAvailablePreviewPage() {
1339 if (preview_pages_info_.size() <= 0 ||
1340 document_load_state_ != LOAD_STATE_COMPLETE) {
1341 return;
1344 std::string url = preview_pages_info_.front().first;
1345 int dst_page_index = preview_pages_info_.front().second;
1346 int src_page_index = ExtractPrintPreviewPageIndex(url);
1347 if (src_page_index < 1 ||
1348 dst_page_index >= print_preview_page_count_ ||
1349 preview_document_load_state_ == LOAD_STATE_LOADING) {
1350 return;
1353 preview_document_load_state_ = LOAD_STATE_LOADING;
1354 LoadPreviewUrl(url);
1357 void OutOfProcessInstance::UserMetricsRecordAction(
1358 const std::string& action) {
1359 // TODO(raymes): Move this function to PPB_UMA_Private.
1360 pp::PDF::UserMetricsRecordAction(this, pp::Var(action));
1363 pp::FloatPoint OutOfProcessInstance::BoundScrollOffsetToDocument(
1364 const pp::FloatPoint& scroll_offset) {
1365 float max_x = document_size_.width() * zoom_ - plugin_dip_size_.width();
1366 float x = std::max(std::min(scroll_offset.x(), max_x), 0.0f);
1367 float max_y = document_size_.height() * zoom_ - plugin_dip_size_.height();
1368 float y = std::max(std::min(scroll_offset.y(), max_y), 0.0f);
1369 return pp::FloatPoint(x, y);
1372 } // namespace chrome_pdf