Clear GCMProfileService::account_id_ in when signing out
[chromium-blink-merge.git] / pdf / out_of_process_instance.cc
blob6a3a5181974977defb78713bc667e9171dd491f1
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/draw_utils.h"
23 #include "pdf/pdf.h"
24 #include "ppapi/c/dev/ppb_cursor_control_dev.h"
25 #include "ppapi/c/pp_errors.h"
26 #include "ppapi/c/pp_rect.h"
27 #include "ppapi/c/private/ppb_instance_private.h"
28 #include "ppapi/c/private/ppp_pdf.h"
29 #include "ppapi/c/trusted/ppb_url_loader_trusted.h"
30 #include "ppapi/cpp/core.h"
31 #include "ppapi/cpp/dev/memory_dev.h"
32 #include "ppapi/cpp/dev/text_input_dev.h"
33 #include "ppapi/cpp/dev/url_util_dev.h"
34 #include "ppapi/cpp/module.h"
35 #include "ppapi/cpp/point.h"
36 #include "ppapi/cpp/private/pdf.h"
37 #include "ppapi/cpp/private/var_private.h"
38 #include "ppapi/cpp/rect.h"
39 #include "ppapi/cpp/resource.h"
40 #include "ppapi/cpp/url_request_info.h"
41 #include "ppapi/cpp/var_array.h"
42 #include "ppapi/cpp/var_dictionary.h"
43 #include "ui/events/keycodes/keyboard_codes.h"
45 #if defined(OS_MACOSX)
46 #include "base/mac/mac_util.h"
47 #endif
49 namespace chrome_pdf {
51 const char kChromePrint[] = "chrome://print/";
52 const char kChromeExtension[] =
53 "chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai";
55 // Dictionary Value key names for the document accessibility info
56 const char kAccessibleNumberOfPages[] = "numberOfPages";
57 const char kAccessibleLoaded[] = "loaded";
58 const char kAccessibleCopyable[] = "copyable";
60 // Constants used in handling postMessage() messages.
61 const char kType[] = "type";
62 // Viewport message arguments. (Page -> Plugin).
63 const char kJSViewportType[] = "viewport";
64 const char kJSXOffset[] = "xOffset";
65 const char kJSYOffset[] = "yOffset";
66 const char kJSZoom[] = "zoom";
67 // Stop scrolling message (Page -> Plugin)
68 const char kJSStopScrollingType[] = "stopScrolling";
69 // Document dimension arguments (Plugin -> Page).
70 const char kJSDocumentDimensionsType[] = "documentDimensions";
71 const char kJSDocumentWidth[] = "width";
72 const char kJSDocumentHeight[] = "height";
73 const char kJSPageDimensions[] = "pageDimensions";
74 const char kJSPageX[] = "x";
75 const char kJSPageY[] = "y";
76 const char kJSPageWidth[] = "width";
77 const char kJSPageHeight[] = "height";
78 // Document load progress arguments (Plugin -> Page)
79 const char kJSLoadProgressType[] = "loadProgress";
80 const char kJSProgressPercentage[] = "progress";
81 // Get password arguments (Plugin -> Page)
82 const char kJSGetPasswordType[] = "getPassword";
83 // Get password complete arguments (Page -> Plugin)
84 const char kJSGetPasswordCompleteType[] = "getPasswordComplete";
85 const char kJSPassword[] = "password";
86 // Print (Page -> Plugin)
87 const char kJSPrintType[] = "print";
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";
129 const int kFindResultCooldownMs = 100;
131 const double kMinZoom = 0.01;
133 namespace {
135 static const char kPPPPdfInterface[] = PPP_PDF_INTERFACE_1;
137 PP_Var GetLinkAtPosition(PP_Instance instance, PP_Point point) {
138 pp::Var var;
139 void* object = pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
140 if (object) {
141 var = static_cast<OutOfProcessInstance*>(object)->GetLinkAtPosition(
142 pp::Point(point));
144 return var.Detach();
147 void Transform(PP_Instance instance, PP_PrivatePageTransformType type) {
148 void* object =
149 pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
150 if (object) {
151 OutOfProcessInstance* obj_instance =
152 static_cast<OutOfProcessInstance*>(object);
153 switch (type) {
154 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CW:
155 obj_instance->RotateClockwise();
156 break;
157 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CCW:
158 obj_instance->RotateCounterclockwise();
159 break;
164 const PPP_Pdf ppp_private = {
165 &GetLinkAtPosition,
166 &Transform
169 int ExtractPrintPreviewPageIndex(const std::string& src_url) {
170 // Sample |src_url| format: chrome://print/id/page_index/print.pdf
171 std::vector<std::string> url_substr;
172 base::SplitString(src_url.substr(strlen(kChromePrint)), '/', &url_substr);
173 if (url_substr.size() != 3)
174 return -1;
176 if (url_substr[2] != "print.pdf")
177 return -1;
179 int page_index = 0;
180 if (!base::StringToInt(url_substr[1], &page_index))
181 return -1;
182 return page_index;
185 bool IsPrintPreviewUrl(const std::string& url) {
186 return url.substr(0, strlen(kChromePrint)) == kChromePrint;
189 void ScalePoint(float scale, pp::Point* point) {
190 point->set_x(static_cast<int>(point->x() * scale));
191 point->set_y(static_cast<int>(point->y() * scale));
194 void ScaleRect(float scale, pp::Rect* rect) {
195 int left = static_cast<int>(floorf(rect->x() * scale));
196 int top = static_cast<int>(floorf(rect->y() * scale));
197 int right = static_cast<int>(ceilf((rect->x() + rect->width()) * scale));
198 int bottom = static_cast<int>(ceilf((rect->y() + rect->height()) * scale));
199 rect->SetRect(left, top, right - left, bottom - top);
202 // TODO(raymes): Remove this dependency on VarPrivate/InstancePrivate. It's
203 // needed right now to do a synchronous call to JavaScript, but we could easily
204 // replace this with a custom PPB_PDF function.
205 pp::Var ModalDialog(const pp::Instance* instance,
206 const std::string& type,
207 const std::string& message,
208 const std::string& default_answer) {
209 const PPB_Instance_Private* interface =
210 reinterpret_cast<const PPB_Instance_Private*>(
211 pp::Module::Get()->GetBrowserInterface(
212 PPB_INSTANCE_PRIVATE_INTERFACE));
213 pp::VarPrivate window(pp::PASS_REF,
214 interface->GetWindowObject(instance->pp_instance()));
215 if (default_answer.empty())
216 return window.Call(type, message);
217 else
218 return window.Call(type, message, default_answer);
221 } // namespace
223 OutOfProcessInstance::OutOfProcessInstance(PP_Instance instance)
224 : pp::Instance(instance),
225 pp::Find_Private(this),
226 pp::Printing_Dev(this),
227 pp::Selection_Dev(this),
228 cursor_(PP_CURSORTYPE_POINTER),
229 zoom_(1.0),
230 device_scale_(1.0),
231 printing_enabled_(true),
232 full_(false),
233 paint_manager_(this, this, true),
234 first_paint_(true),
235 document_load_state_(LOAD_STATE_LOADING),
236 preview_document_load_state_(LOAD_STATE_COMPLETE),
237 uma_(this),
238 told_browser_about_unsupported_feature_(false),
239 print_preview_page_count_(0),
240 last_progress_sent_(0),
241 recently_sent_find_update_(false),
242 received_viewport_message_(false),
243 did_call_start_loading_(false),
244 stop_scrolling_(false) {
245 loader_factory_.Initialize(this);
246 timer_factory_.Initialize(this);
247 form_factory_.Initialize(this);
248 print_callback_factory_.Initialize(this);
249 engine_.reset(PDFEngine::Create(this));
250 pp::Module::Get()->AddPluginInterface(kPPPPdfInterface, &ppp_private);
251 AddPerInstanceObject(kPPPPdfInterface, this);
253 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_MOUSE);
254 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_KEYBOARD);
255 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_TOUCH);
258 OutOfProcessInstance::~OutOfProcessInstance() {
259 RemovePerInstanceObject(kPPPPdfInterface, this);
262 bool OutOfProcessInstance::Init(uint32_t argc,
263 const char* argn[],
264 const char* argv[]) {
265 // Check if the PDF is being loaded in the PDF chrome extension. We only allow
266 // the plugin to be put into "full frame" mode when it is being loaded in the
267 // extension because this enables some features that we don't want pages
268 // abusing outside of the extension.
269 pp::Var document_url_var = pp::URLUtil_Dev::Get()->GetDocumentURL(this);
270 std::string document_url = document_url_var.is_string() ?
271 document_url_var.AsString() : std::string();
272 std::string extension_url = std::string(kChromeExtension);
273 bool in_extension =
274 !document_url.compare(0, extension_url.size(), extension_url);
276 if (in_extension) {
277 // Check if the plugin is full frame. This is passed in from JS.
278 for (uint32_t i = 0; i < argc; ++i) {
279 if (strcmp(argn[i], "full-frame") == 0) {
280 full_ = true;
281 break;
286 // Only allow the plugin to handle find requests if it is full frame.
287 if (full_)
288 SetPluginToHandleFindRequests();
290 // Send translated strings to the extension where they will be displayed.
291 // TODO(raymes): It would be better to get these in the extension directly
292 // through an API but no such API currently exists.
293 pp::VarDictionary translated_strings;
294 translated_strings.Set(kType, kJSSetTranslatedStringsType);
295 translated_strings.Set(kJSGetPasswordString,
296 GetLocalizedString(PP_RESOURCESTRING_PDFGETPASSWORD));
297 translated_strings.Set(kJSLoadingString,
298 GetLocalizedString(PP_RESOURCESTRING_PDFLOADING));
299 translated_strings.Set(kJSLoadFailedString,
300 GetLocalizedString(PP_RESOURCESTRING_PDFLOAD_FAILED));
301 PostMessage(translated_strings);
303 text_input_.reset(new pp::TextInput_Dev(this));
305 const char* stream_url = NULL;
306 const char* original_url = NULL;
307 const char* headers = NULL;
308 for (uint32_t i = 0; i < argc; ++i) {
309 if (strcmp(argn[i], "src") == 0)
310 original_url = argv[i];
311 else if (strcmp(argn[i], "stream-url") == 0)
312 stream_url = argv[i];
313 else if (strcmp(argn[i], "headers") == 0)
314 headers = argv[i];
317 // TODO(raymes): This is a hack to ensure that if no headers are passed in
318 // then we get the right MIME type. When the in process plugin is removed we
319 // can fix the document loader properly and remove this hack.
320 if (!headers || strcmp(headers, "") == 0)
321 headers = "content-type: application/pdf";
323 if (!original_url)
324 return false;
326 if (!stream_url)
327 stream_url = original_url;
329 // If we're in print preview mode we don't need to load the document yet.
330 // A |kJSResetPrintPreviewModeType| message will be sent to the plugin letting
331 // it know the url to load. By not loading here we avoid loading the same
332 // document twice.
333 if (IsPrintPreviewUrl(original_url))
334 return true;
336 LoadUrl(stream_url);
337 url_ = original_url;
338 return engine_->New(original_url, headers);
341 void OutOfProcessInstance::HandleMessage(const pp::Var& message) {
342 pp::VarDictionary dict(message);
343 if (!dict.Get(kType).is_string()) {
344 NOTREACHED();
345 return;
348 std::string type = dict.Get(kType).AsString();
350 if (type == kJSViewportType &&
351 dict.Get(pp::Var(kJSXOffset)).is_int() &&
352 dict.Get(pp::Var(kJSYOffset)).is_int() &&
353 dict.Get(pp::Var(kJSZoom)).is_number()) {
354 received_viewport_message_ = true;
355 stop_scrolling_ = false;
356 double zoom = dict.Get(pp::Var(kJSZoom)).AsDouble();
357 pp::Point scroll_offset(dict.Get(pp::Var(kJSXOffset)).AsInt(),
358 dict.Get(pp::Var(kJSYOffset)).AsInt());
360 // Bound the input parameters.
361 zoom = std::max(kMinZoom, zoom);
362 SetZoom(zoom);
363 scroll_offset = BoundScrollOffsetToDocument(scroll_offset);
364 engine_->ScrolledToXPosition(scroll_offset.x() * device_scale_);
365 engine_->ScrolledToYPosition(scroll_offset.y() * device_scale_);
366 } else if (type == kJSGetPasswordCompleteType &&
367 dict.Get(pp::Var(kJSPassword)).is_string()) {
368 if (password_callback_) {
369 pp::CompletionCallbackWithOutput<pp::Var> callback = *password_callback_;
370 password_callback_.reset();
371 *callback.output() = dict.Get(pp::Var(kJSPassword)).pp_var();
372 callback.Run(PP_OK);
373 } else {
374 NOTREACHED();
376 } else if (type == kJSPrintType) {
377 Print();
378 } else if (type == kJSResetPrintPreviewModeType &&
379 dict.Get(pp::Var(kJSPrintPreviewUrl)).is_string() &&
380 dict.Get(pp::Var(kJSPrintPreviewGrayscale)).is_bool() &&
381 dict.Get(pp::Var(kJSPrintPreviewPageCount)).is_int()) {
382 url_ = dict.Get(pp::Var(kJSPrintPreviewUrl)).AsString();
383 preview_pages_info_ = std::queue<PreviewPageInfo>();
384 preview_document_load_state_ = LOAD_STATE_COMPLETE;
385 document_load_state_ = LOAD_STATE_LOADING;
386 LoadUrl(url_);
387 preview_engine_.reset();
388 engine_.reset(PDFEngine::Create(this));
389 engine_->SetGrayscale(dict.Get(pp::Var(kJSPrintPreviewGrayscale)).AsBool());
390 engine_->New(url_.c_str());
392 print_preview_page_count_ =
393 std::max(dict.Get(pp::Var(kJSPrintPreviewPageCount)).AsInt(), 0);
395 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
396 } else if (type == kJSLoadPreviewPageType &&
397 dict.Get(pp::Var(kJSPreviewPageUrl)).is_string() &&
398 dict.Get(pp::Var(kJSPreviewPageIndex)).is_int()) {
399 ProcessPreviewPageInfo(dict.Get(pp::Var(kJSPreviewPageUrl)).AsString(),
400 dict.Get(pp::Var(kJSPreviewPageIndex)).AsInt());
401 } else if (type == kJSGetAccessibilityJSONType) {
402 pp::VarDictionary reply;
403 reply.Set(pp::Var(kType), pp::Var(kJSGetAccessibilityJSONReplyType));
404 if (dict.Get(pp::Var(kJSAccessibilityPageNumber)).is_int()) {
405 int page = dict.Get(pp::Var(kJSAccessibilityPageNumber)).AsInt();
406 reply.Set(pp::Var(kJSAccessibilityJSON),
407 pp::Var(engine_->GetPageAsJSON(page)));
408 } else {
409 base::DictionaryValue node;
410 node.SetInteger(kAccessibleNumberOfPages, engine_->GetNumberOfPages());
411 node.SetBoolean(kAccessibleLoaded,
412 document_load_state_ != LOAD_STATE_LOADING);
413 bool has_permissions =
414 engine_->HasPermission(PDFEngine::PERMISSION_COPY) ||
415 engine_->HasPermission(PDFEngine::PERMISSION_COPY_ACCESSIBLE);
416 node.SetBoolean(kAccessibleCopyable, has_permissions);
417 std::string json;
418 base::JSONWriter::Write(&node, &json);
419 reply.Set(pp::Var(kJSAccessibilityJSON), pp::Var(json));
421 PostMessage(reply);
422 } else if (type == kJSStopScrollingType) {
423 stop_scrolling_ = true;
424 } else {
425 NOTREACHED();
429 bool OutOfProcessInstance::HandleInputEvent(
430 const pp::InputEvent& event) {
431 // To simplify things, convert the event into device coordinates if it is
432 // a mouse event.
433 pp::InputEvent event_device_res(event);
435 pp::MouseInputEvent mouse_event(event);
436 if (!mouse_event.is_null()) {
437 pp::Point point = mouse_event.GetPosition();
438 pp::Point movement = mouse_event.GetMovement();
439 ScalePoint(device_scale_, &point);
440 ScalePoint(device_scale_, &movement);
441 mouse_event = pp::MouseInputEvent(
442 this,
443 event.GetType(),
444 event.GetTimeStamp(),
445 event.GetModifiers(),
446 mouse_event.GetButton(),
447 point,
448 mouse_event.GetClickCount(),
449 movement);
450 event_device_res = mouse_event;
454 pp::InputEvent offset_event(event_device_res);
455 switch (offset_event.GetType()) {
456 case PP_INPUTEVENT_TYPE_MOUSEDOWN:
457 case PP_INPUTEVENT_TYPE_MOUSEUP:
458 case PP_INPUTEVENT_TYPE_MOUSEMOVE:
459 case PP_INPUTEVENT_TYPE_MOUSEENTER:
460 case PP_INPUTEVENT_TYPE_MOUSELEAVE: {
461 pp::MouseInputEvent mouse_event(event_device_res);
462 pp::MouseInputEvent mouse_event_dip(event);
463 pp::Point point = mouse_event.GetPosition();
464 point.set_x(point.x() - available_area_.x());
465 offset_event = pp::MouseInputEvent(
466 this,
467 event.GetType(),
468 event.GetTimeStamp(),
469 event.GetModifiers(),
470 mouse_event.GetButton(),
471 point,
472 mouse_event.GetClickCount(),
473 mouse_event.GetMovement());
474 break;
476 default:
477 break;
479 if (engine_->HandleEvent(offset_event))
480 return true;
482 // TODO(raymes): Implement this scroll behavior in JS:
483 // When click+dragging, scroll the document correctly.
485 if (event.GetType() == PP_INPUTEVENT_TYPE_KEYDOWN &&
486 event.GetModifiers() & kDefaultKeyModifier) {
487 pp::KeyboardInputEvent keyboard_event(event);
488 switch (keyboard_event.GetKeyCode()) {
489 case 'A':
490 engine_->SelectAll();
491 return true;
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(
534 BoundScrollOffsetToDocument(view.GetScrollOffset()));
535 engine_->ScrolledToXPosition(scroll_offset.x() * device_scale_);
536 engine_->ScrolledToYPosition(scroll_offset.y() * device_scale_);
540 pp::Var OutOfProcessInstance::GetLinkAtPosition(
541 const pp::Point& point) {
542 pp::Point offset_point(point);
543 ScalePoint(device_scale_, &offset_point);
544 offset_point.set_x(offset_point.x() - available_area_.x());
545 return engine_->GetLinkAtPosition(offset_point);
548 pp::Var OutOfProcessInstance::GetSelectedText(bool html) {
549 if (html || !engine_->HasPermission(PDFEngine::PERMISSION_COPY))
550 return pp::Var();
551 return engine_->GetSelectedText();
554 uint32_t OutOfProcessInstance::QuerySupportedPrintOutputFormats() {
555 return engine_->QuerySupportedPrintOutputFormats();
558 int32_t OutOfProcessInstance::PrintBegin(
559 const PP_PrintSettings_Dev& print_settings) {
560 // For us num_pages is always equal to the number of pages in the PDF
561 // document irrespective of the printable area.
562 int32_t ret = engine_->GetNumberOfPages();
563 if (!ret)
564 return 0;
566 uint32_t supported_formats = engine_->QuerySupportedPrintOutputFormats();
567 if ((print_settings.format & supported_formats) == 0)
568 return 0;
570 print_settings_.is_printing = true;
571 print_settings_.pepper_print_settings = print_settings;
572 engine_->PrintBegin();
573 return ret;
576 pp::Resource OutOfProcessInstance::PrintPages(
577 const PP_PrintPageNumberRange_Dev* page_ranges,
578 uint32_t page_range_count) {
579 if (!print_settings_.is_printing)
580 return pp::Resource();
582 print_settings_.print_pages_called_ = true;
583 return engine_->PrintPages(page_ranges, page_range_count,
584 print_settings_.pepper_print_settings);
587 void OutOfProcessInstance::PrintEnd() {
588 if (print_settings_.print_pages_called_)
589 UserMetricsRecordAction("PDF.PrintPage");
590 print_settings_.Clear();
591 engine_->PrintEnd();
594 bool OutOfProcessInstance::IsPrintScalingDisabled() {
595 return !engine_->GetPrintScaling();
598 bool OutOfProcessInstance::StartFind(const std::string& text,
599 bool case_sensitive) {
600 engine_->StartFind(text.c_str(), case_sensitive);
601 return true;
604 void OutOfProcessInstance::SelectFindResult(bool forward) {
605 engine_->SelectFindResult(forward);
608 void OutOfProcessInstance::StopFind() {
609 engine_->StopFind();
610 tickmarks_.clear();
611 SetTickmarks(tickmarks_);
614 void OutOfProcessInstance::OnPaint(
615 const std::vector<pp::Rect>& paint_rects,
616 std::vector<PaintManager::ReadyRect>* ready,
617 std::vector<pp::Rect>* pending) {
618 if (image_data_.is_null()) {
619 DCHECK(plugin_size_.IsEmpty());
620 return;
622 if (first_paint_) {
623 first_paint_ = false;
624 pp::Rect rect = pp::Rect(pp::Point(), image_data_.size());
625 FillRect(rect, kBackgroundColor);
626 ready->push_back(PaintManager::ReadyRect(rect, image_data_, true));
629 if (!received_viewport_message_)
630 return;
632 engine_->PrePaint();
634 for (size_t i = 0; i < paint_rects.size(); i++) {
635 // Intersect with plugin area since there could be pending invalidates from
636 // when the plugin area was larger.
637 pp::Rect rect =
638 paint_rects[i].Intersect(pp::Rect(pp::Point(), plugin_size_));
639 if (rect.IsEmpty())
640 continue;
642 pp::Rect pdf_rect = available_area_.Intersect(rect);
643 if (!pdf_rect.IsEmpty()) {
644 pdf_rect.Offset(available_area_.x() * -1, 0);
646 std::vector<pp::Rect> pdf_ready;
647 std::vector<pp::Rect> pdf_pending;
648 engine_->Paint(pdf_rect, &image_data_, &pdf_ready, &pdf_pending);
649 for (size_t j = 0; j < pdf_ready.size(); ++j) {
650 pdf_ready[j].Offset(available_area_.point());
651 ready->push_back(
652 PaintManager::ReadyRect(pdf_ready[j], image_data_, false));
654 for (size_t j = 0; j < pdf_pending.size(); ++j) {
655 pdf_pending[j].Offset(available_area_.point());
656 pending->push_back(pdf_pending[j]);
660 for (size_t j = 0; j < background_parts_.size(); ++j) {
661 pp::Rect intersection = background_parts_[j].location.Intersect(rect);
662 if (!intersection.IsEmpty()) {
663 FillRect(intersection, background_parts_[j].color);
664 ready->push_back(
665 PaintManager::ReadyRect(intersection, image_data_, false));
670 engine_->PostPaint();
673 void OutOfProcessInstance::DidOpen(int32_t result) {
674 if (result == PP_OK) {
675 if (!engine_->HandleDocumentLoad(embed_loader_)) {
676 document_load_state_ = LOAD_STATE_LOADING;
677 DocumentLoadFailed();
679 } else if (result != PP_ERROR_ABORTED) { // Can happen in tests.
680 NOTREACHED();
681 DocumentLoadFailed();
684 // If it's a progressive load, cancel the stream URL request so that requests
685 // can be made on the original URL.
686 // TODO(raymes): Make this clearer once the in-process plugin is deleted.
687 if (engine_->IsProgressiveLoad()) {
688 pp::VarDictionary message;
689 message.Set(kType, kJSCancelStreamUrlType);
690 PostMessage(message);
694 void OutOfProcessInstance::DidOpenPreview(int32_t result) {
695 if (result == PP_OK) {
696 preview_engine_.reset(PDFEngine::Create(new PreviewModeClient(this)));
697 preview_engine_->HandleDocumentLoad(embed_preview_loader_);
698 } else {
699 NOTREACHED();
703 void OutOfProcessInstance::OnClientTimerFired(int32_t id) {
704 engine_->OnCallback(id);
707 void OutOfProcessInstance::CalculateBackgroundParts() {
708 background_parts_.clear();
709 int left_width = available_area_.x();
710 int right_start = available_area_.right();
711 int right_width = abs(plugin_size_.width() - available_area_.right());
712 int bottom = std::min(available_area_.bottom(), plugin_size_.height());
714 // Add the left, right, and bottom rectangles. Note: we assume only
715 // horizontal centering.
716 BackgroundPart part = {
717 pp::Rect(0, 0, left_width, bottom),
718 kBackgroundColor
720 if (!part.location.IsEmpty())
721 background_parts_.push_back(part);
722 part.location = pp::Rect(right_start, 0, right_width, bottom);
723 if (!part.location.IsEmpty())
724 background_parts_.push_back(part);
725 part.location = pp::Rect(
726 0, bottom, plugin_size_.width(), plugin_size_.height() - bottom);
727 if (!part.location.IsEmpty())
728 background_parts_.push_back(part);
731 int OutOfProcessInstance::GetDocumentPixelWidth() const {
732 return static_cast<int>(ceil(document_size_.width() * zoom_ * device_scale_));
735 int OutOfProcessInstance::GetDocumentPixelHeight() const {
736 return static_cast<int>(
737 ceil(document_size_.height() * zoom_ * device_scale_));
740 void OutOfProcessInstance::FillRect(const pp::Rect& rect, uint32 color) {
741 DCHECK(!image_data_.is_null() || rect.IsEmpty());
742 uint32* buffer_start = static_cast<uint32*>(image_data_.data());
743 int stride = image_data_.stride();
744 uint32* ptr = buffer_start + rect.y() * stride / 4 + rect.x();
745 int height = rect.height();
746 int width = rect.width();
747 for (int y = 0; y < height; ++y) {
748 for (int x = 0; x < width; ++x)
749 *(ptr + x) = color;
750 ptr += stride /4;
754 void OutOfProcessInstance::DocumentSizeUpdated(const pp::Size& size) {
755 document_size_ = size;
757 pp::VarDictionary dimensions;
758 dimensions.Set(kType, kJSDocumentDimensionsType);
759 dimensions.Set(kJSDocumentWidth, pp::Var(document_size_.width()));
760 dimensions.Set(kJSDocumentHeight, pp::Var(document_size_.height()));
761 pp::VarArray page_dimensions_array;
762 int num_pages = engine_->GetNumberOfPages();
763 for (int i = 0; i < num_pages; ++i) {
764 pp::Rect page_rect = engine_->GetPageRect(i);
765 pp::VarDictionary page_dimensions;
766 page_dimensions.Set(kJSPageX, pp::Var(page_rect.x()));
767 page_dimensions.Set(kJSPageY, pp::Var(page_rect.y()));
768 page_dimensions.Set(kJSPageWidth, pp::Var(page_rect.width()));
769 page_dimensions.Set(kJSPageHeight, pp::Var(page_rect.height()));
770 page_dimensions_array.Set(i, page_dimensions);
772 dimensions.Set(kJSPageDimensions, page_dimensions_array);
773 PostMessage(dimensions);
775 OnGeometryChanged(zoom_, device_scale_);
778 void OutOfProcessInstance::Invalidate(const pp::Rect& rect) {
779 pp::Rect offset_rect(rect);
780 offset_rect.Offset(available_area_.point());
781 paint_manager_.InvalidateRect(offset_rect);
784 void OutOfProcessInstance::Scroll(const pp::Point& point) {
785 if (!image_data_.is_null())
786 paint_manager_.ScrollRect(available_area_, point);
789 void OutOfProcessInstance::ScrollToX(int x) {
790 pp::VarDictionary position;
791 position.Set(kType, kJSSetScrollPositionType);
792 position.Set(kJSPositionX, pp::Var(x / device_scale_));
793 PostMessage(position);
796 void OutOfProcessInstance::ScrollToY(int y) {
797 pp::VarDictionary position;
798 position.Set(kType, kJSSetScrollPositionType);
799 position.Set(kJSPositionY, pp::Var(y / device_scale_));
800 PostMessage(position);
803 void OutOfProcessInstance::ScrollToPage(int page) {
804 if (engine_->GetNumberOfPages() == 0)
805 return;
807 pp::VarDictionary message;
808 message.Set(kType, kJSGoToPageType);
809 message.Set(kJSPageNumber, pp::Var(page));
810 PostMessage(message);
813 void OutOfProcessInstance::NavigateTo(const std::string& url,
814 bool open_in_new_tab) {
815 std::string url_copy(url);
817 // Empty |url_copy| is ok, and will effectively be a reload.
818 // Skip the code below so an empty URL does not turn into "http://", which
819 // will cause GURL to fail a DCHECK.
820 if (!url_copy.empty()) {
821 // If |url_copy| starts with '#', then it's for the same URL with a
822 // different URL fragment.
823 if (url_copy[0] == '#') {
824 url_copy = url_ + url_copy;
826 // If there's no scheme, add http.
827 if (url_copy.find("://") == std::string::npos &&
828 url_copy.find("mailto:") == std::string::npos) {
829 url_copy = std::string("http://") + url_copy;
831 // Make sure |url_copy| starts with a valid scheme.
832 if (url_copy.find("http://") != 0 &&
833 url_copy.find("https://") != 0 &&
834 url_copy.find("ftp://") != 0 &&
835 url_copy.find("file://") != 0 &&
836 url_copy.find("mailto:") != 0) {
837 return;
839 // Make sure |url_copy| is not only a scheme.
840 if (url_copy == "http://" ||
841 url_copy == "https://" ||
842 url_copy == "ftp://" ||
843 url_copy == "file://" ||
844 url_copy == "mailto:") {
845 return;
848 pp::VarDictionary message;
849 message.Set(kType, kJSNavigateType);
850 message.Set(kJSNavigateUrl, url_copy);
851 message.Set(kJSNavigateNewTab, open_in_new_tab);
852 PostMessage(message);
855 void OutOfProcessInstance::UpdateCursor(PP_CursorType_Dev cursor) {
856 if (cursor == cursor_)
857 return;
858 cursor_ = cursor;
860 const PPB_CursorControl_Dev* cursor_interface =
861 reinterpret_cast<const PPB_CursorControl_Dev*>(
862 pp::Module::Get()->GetBrowserInterface(PPB_CURSOR_CONTROL_DEV_INTERFACE));
863 if (!cursor_interface) {
864 NOTREACHED();
865 return;
868 cursor_interface->SetCursor(
869 pp_instance(), cursor_, pp::ImageData().pp_resource(), NULL);
872 void OutOfProcessInstance::UpdateTickMarks(
873 const std::vector<pp::Rect>& tickmarks) {
874 float inverse_scale = 1.0f / device_scale_;
875 std::vector<pp::Rect> scaled_tickmarks = tickmarks;
876 for (size_t i = 0; i < scaled_tickmarks.size(); i++)
877 ScaleRect(inverse_scale, &scaled_tickmarks[i]);
878 tickmarks_ = scaled_tickmarks;
881 void OutOfProcessInstance::NotifyNumberOfFindResultsChanged(int total,
882 bool final_result) {
883 // We don't want to spam the renderer with too many updates to the number of
884 // find results. Don't send an update if we sent one too recently. If it's the
885 // final update, we always send it though.
886 if (final_result) {
887 NumberOfFindResultsChanged(total, final_result);
888 SetTickmarks(tickmarks_);
889 return;
892 if (recently_sent_find_update_)
893 return;
895 NumberOfFindResultsChanged(total, final_result);
896 SetTickmarks(tickmarks_);
897 recently_sent_find_update_ = true;
898 pp::CompletionCallback callback =
899 timer_factory_.NewCallback(
900 &OutOfProcessInstance::ResetRecentlySentFindUpdate);
901 pp::Module::Get()->core()->CallOnMainThread(kFindResultCooldownMs,
902 callback, 0);
905 void OutOfProcessInstance::NotifySelectedFindResultChanged(
906 int current_find_index) {
907 SelectedFindResultChanged(current_find_index);
910 void OutOfProcessInstance::GetDocumentPassword(
911 pp::CompletionCallbackWithOutput<pp::Var> callback) {
912 if (password_callback_) {
913 NOTREACHED();
914 return;
917 password_callback_.reset(
918 new pp::CompletionCallbackWithOutput<pp::Var>(callback));
919 pp::VarDictionary message;
920 message.Set(pp::Var(kType), pp::Var(kJSGetPasswordType));
921 PostMessage(message);
924 void OutOfProcessInstance::Alert(const std::string& message) {
925 ModalDialog(this, "alert", message, std::string());
928 bool OutOfProcessInstance::Confirm(const std::string& message) {
929 pp::Var result = ModalDialog(this, "confirm", message, std::string());
930 return result.is_bool() ? result.AsBool() : false;
933 std::string OutOfProcessInstance::Prompt(const std::string& question,
934 const std::string& default_answer) {
935 pp::Var result = ModalDialog(this, "prompt", question, default_answer);
936 return result.is_string() ? result.AsString() : std::string();
939 std::string OutOfProcessInstance::GetURL() {
940 return url_;
943 void OutOfProcessInstance::Email(const std::string& to,
944 const std::string& cc,
945 const std::string& bcc,
946 const std::string& subject,
947 const std::string& body) {
948 pp::VarDictionary message;
949 message.Set(pp::Var(kType), pp::Var(kJSEmailType));
950 message.Set(pp::Var(kJSEmailTo),
951 pp::Var(net::EscapeUrlEncodedData(to, false)));
952 message.Set(pp::Var(kJSEmailCc),
953 pp::Var(net::EscapeUrlEncodedData(cc, false)));
954 message.Set(pp::Var(kJSEmailBcc),
955 pp::Var(net::EscapeUrlEncodedData(bcc, false)));
956 message.Set(pp::Var(kJSEmailSubject),
957 pp::Var(net::EscapeUrlEncodedData(subject, false)));
958 message.Set(pp::Var(kJSEmailBody),
959 pp::Var(net::EscapeUrlEncodedData(body, false)));
960 PostMessage(message);
963 void OutOfProcessInstance::Print() {
964 if (!printing_enabled_ ||
965 (!engine_->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY) &&
966 !engine_->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY))) {
967 return;
970 pp::CompletionCallback callback =
971 print_callback_factory_.NewCallback(&OutOfProcessInstance::OnPrint);
972 pp::Module::Get()->core()->CallOnMainThread(0, callback);
975 void OutOfProcessInstance::OnPrint(int32_t) {
976 pp::PDF::Print(this);
979 void OutOfProcessInstance::SubmitForm(const std::string& url,
980 const void* data,
981 int length) {
982 pp::URLRequestInfo request(this);
983 request.SetURL(url);
984 request.SetMethod("POST");
985 request.AppendDataToBody(reinterpret_cast<const char*>(data), length);
987 pp::CompletionCallback callback =
988 form_factory_.NewCallback(&OutOfProcessInstance::FormDidOpen);
989 form_loader_ = CreateURLLoaderInternal();
990 int rv = form_loader_.Open(request, callback);
991 if (rv != PP_OK_COMPLETIONPENDING)
992 callback.Run(rv);
995 void OutOfProcessInstance::FormDidOpen(int32_t result) {
996 // TODO: inform the user of success/failure.
997 if (result != PP_OK) {
998 NOTREACHED();
1002 std::string OutOfProcessInstance::ShowFileSelectionDialog() {
1003 // Seems like very low priority to implement, since the pdf has no way to get
1004 // the file data anyways. Javascript doesn't let you do this synchronously.
1005 NOTREACHED();
1006 return std::string();
1009 pp::URLLoader OutOfProcessInstance::CreateURLLoader() {
1010 if (full_) {
1011 if (!did_call_start_loading_) {
1012 did_call_start_loading_ = true;
1013 pp::PDF::DidStartLoading(this);
1016 // Disable save and print until the document is fully loaded, since they
1017 // would generate an incomplete document. Need to do this each time we
1018 // call DidStartLoading since that resets the content restrictions.
1019 pp::PDF::SetContentRestriction(this, CONTENT_RESTRICTION_SAVE |
1020 CONTENT_RESTRICTION_PRINT);
1023 return CreateURLLoaderInternal();
1026 void OutOfProcessInstance::ScheduleCallback(int id, int delay_in_ms) {
1027 pp::CompletionCallback callback =
1028 timer_factory_.NewCallback(&OutOfProcessInstance::OnClientTimerFired);
1029 pp::Module::Get()->core()->CallOnMainThread(delay_in_ms, callback, id);
1032 void OutOfProcessInstance::SearchString(const base::char16* string,
1033 const base::char16* term,
1034 bool case_sensitive,
1035 std::vector<SearchStringResult>* results) {
1036 PP_PrivateFindResult* pp_results;
1037 int count = 0;
1038 pp::PDF::SearchString(
1039 this,
1040 reinterpret_cast<const unsigned short*>(string),
1041 reinterpret_cast<const unsigned short*>(term),
1042 case_sensitive,
1043 &pp_results,
1044 &count);
1046 results->resize(count);
1047 for (int i = 0; i < count; ++i) {
1048 (*results)[i].start_index = pp_results[i].start_index;
1049 (*results)[i].length = pp_results[i].length;
1052 pp::Memory_Dev memory;
1053 memory.MemFree(pp_results);
1056 void OutOfProcessInstance::DocumentPaintOccurred() {
1059 void OutOfProcessInstance::DocumentLoadComplete(int page_count) {
1060 // Clear focus state for OSK.
1061 FormTextFieldFocusChange(false);
1063 DCHECK(document_load_state_ == LOAD_STATE_LOADING);
1064 document_load_state_ = LOAD_STATE_COMPLETE;
1065 UserMetricsRecordAction("PDF.LoadSuccess");
1067 // Note: If we are in print preview mode the scroll location is retained
1068 // across document loads so we don't want to scroll again and override it.
1069 if (IsPrintPreview()) {
1070 AppendBlankPrintPreviewPages();
1071 OnGeometryChanged(0, 0);
1074 pp::VarDictionary message;
1075 message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1076 message.Set(pp::Var(kJSProgressPercentage), pp::Var(100)) ;
1077 PostMessage(message);
1079 if (!full_)
1080 return;
1082 if (did_call_start_loading_) {
1083 pp::PDF::DidStopLoading(this);
1084 did_call_start_loading_ = false;
1087 int content_restrictions =
1088 CONTENT_RESTRICTION_CUT | CONTENT_RESTRICTION_PASTE;
1089 if (!engine_->HasPermission(PDFEngine::PERMISSION_COPY))
1090 content_restrictions |= CONTENT_RESTRICTION_COPY;
1092 if (!engine_->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY) &&
1093 !engine_->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY)) {
1094 printing_enabled_ = false;
1097 pp::PDF::SetContentRestriction(this, content_restrictions);
1099 uma_.HistogramCustomCounts("PDF.PageCount", page_count,
1100 1, 1000000, 50);
1103 void OutOfProcessInstance::RotateClockwise() {
1104 engine_->RotateClockwise();
1107 void OutOfProcessInstance::RotateCounterclockwise() {
1108 engine_->RotateCounterclockwise();
1111 void OutOfProcessInstance::PreviewDocumentLoadComplete() {
1112 if (preview_document_load_state_ != LOAD_STATE_LOADING ||
1113 preview_pages_info_.empty()) {
1114 return;
1117 preview_document_load_state_ = LOAD_STATE_COMPLETE;
1119 int dest_page_index = preview_pages_info_.front().second;
1120 int src_page_index =
1121 ExtractPrintPreviewPageIndex(preview_pages_info_.front().first);
1122 if (src_page_index > 0 && dest_page_index > -1 && preview_engine_.get())
1123 engine_->AppendPage(preview_engine_.get(), dest_page_index);
1125 preview_pages_info_.pop();
1126 // |print_preview_page_count_| is not updated yet. Do not load any
1127 // other preview pages till we get this information.
1128 if (print_preview_page_count_ == 0)
1129 return;
1131 if (preview_pages_info_.size())
1132 LoadAvailablePreviewPage();
1135 void OutOfProcessInstance::DocumentLoadFailed() {
1136 DCHECK(document_load_state_ == LOAD_STATE_LOADING);
1137 UserMetricsRecordAction("PDF.LoadFailure");
1139 if (did_call_start_loading_) {
1140 pp::PDF::DidStopLoading(this);
1141 did_call_start_loading_ = false;
1144 document_load_state_ = LOAD_STATE_FAILED;
1145 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
1147 // Send a progress value of -1 to indicate a failure.
1148 pp::VarDictionary message;
1149 message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1150 message.Set(pp::Var(kJSProgressPercentage), pp::Var(-1)) ;
1151 PostMessage(message);
1154 void OutOfProcessInstance::PreviewDocumentLoadFailed() {
1155 UserMetricsRecordAction("PDF.PreviewDocumentLoadFailure");
1156 if (preview_document_load_state_ != LOAD_STATE_LOADING ||
1157 preview_pages_info_.empty()) {
1158 return;
1161 preview_document_load_state_ = LOAD_STATE_FAILED;
1162 preview_pages_info_.pop();
1164 if (preview_pages_info_.size())
1165 LoadAvailablePreviewPage();
1168 pp::Instance* OutOfProcessInstance::GetPluginInstance() {
1169 return this;
1172 void OutOfProcessInstance::DocumentHasUnsupportedFeature(
1173 const std::string& feature) {
1174 std::string metric("PDF_Unsupported_");
1175 metric += feature;
1176 if (!unsupported_features_reported_.count(metric)) {
1177 unsupported_features_reported_.insert(metric);
1178 UserMetricsRecordAction(metric);
1181 // Since we use an info bar, only do this for full frame plugins..
1182 if (!full_)
1183 return;
1185 if (told_browser_about_unsupported_feature_)
1186 return;
1187 told_browser_about_unsupported_feature_ = true;
1189 pp::PDF::HasUnsupportedFeature(this);
1192 void OutOfProcessInstance::DocumentLoadProgress(uint32 available,
1193 uint32 doc_size) {
1194 double progress = 0.0;
1195 if (doc_size == 0) {
1196 // Document size is unknown. Use heuristics.
1197 // We'll make progress logarithmic from 0 to 100M.
1198 static const double kFactor = log(100000000.0) / 100.0;
1199 if (available > 0) {
1200 progress = log(static_cast<double>(available)) / kFactor;
1201 if (progress > 100.0)
1202 progress = 100.0;
1204 } else {
1205 progress = 100.0 * static_cast<double>(available) / doc_size;
1208 // We send 100% load progress in DocumentLoadComplete.
1209 if (progress >= 100)
1210 return;
1212 // Avoid sending too many progress messages over PostMessage.
1213 if (progress > last_progress_sent_ + 1) {
1214 last_progress_sent_ = progress;
1215 pp::VarDictionary message;
1216 message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1217 message.Set(pp::Var(kJSProgressPercentage), pp::Var(progress)) ;
1218 PostMessage(message);
1222 void OutOfProcessInstance::FormTextFieldFocusChange(bool in_focus) {
1223 if (!text_input_.get())
1224 return;
1225 if (in_focus)
1226 text_input_->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_TEXT);
1227 else
1228 text_input_->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_NONE);
1231 void OutOfProcessInstance::ResetRecentlySentFindUpdate(int32_t /* unused */) {
1232 recently_sent_find_update_ = false;
1235 void OutOfProcessInstance::OnGeometryChanged(double old_zoom,
1236 float old_device_scale) {
1237 if (zoom_ != old_zoom || device_scale_ != old_device_scale)
1238 engine_->ZoomUpdated(zoom_ * device_scale_);
1240 available_area_ = pp::Rect(plugin_size_);
1241 int doc_width = GetDocumentPixelWidth();
1242 if (doc_width < available_area_.width()) {
1243 available_area_.Offset((available_area_.width() - doc_width) / 2, 0);
1244 available_area_.set_width(doc_width);
1246 int doc_height = GetDocumentPixelHeight();
1247 if (doc_height < available_area_.height()) {
1248 available_area_.set_height(doc_height);
1251 CalculateBackgroundParts();
1252 engine_->PageOffsetUpdated(available_area_.point());
1253 engine_->PluginSizeUpdated(available_area_.size());
1255 if (!document_size_.GetArea())
1256 return;
1257 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
1260 void OutOfProcessInstance::LoadUrl(const std::string& url) {
1261 LoadUrlInternal(url, &embed_loader_, &OutOfProcessInstance::DidOpen);
1264 void OutOfProcessInstance::LoadPreviewUrl(const std::string& url) {
1265 LoadUrlInternal(url, &embed_preview_loader_,
1266 &OutOfProcessInstance::DidOpenPreview);
1269 void OutOfProcessInstance::LoadUrlInternal(
1270 const std::string& url,
1271 pp::URLLoader* loader,
1272 void (OutOfProcessInstance::* method)(int32_t)) {
1273 pp::URLRequestInfo request(this);
1274 request.SetURL(url);
1275 request.SetMethod("GET");
1277 *loader = CreateURLLoaderInternal();
1278 pp::CompletionCallback callback = loader_factory_.NewCallback(method);
1279 int rv = loader->Open(request, callback);
1280 if (rv != PP_OK_COMPLETIONPENDING)
1281 callback.Run(rv);
1284 pp::URLLoader OutOfProcessInstance::CreateURLLoaderInternal() {
1285 pp::URLLoader loader(this);
1287 const PPB_URLLoaderTrusted* trusted_interface =
1288 reinterpret_cast<const PPB_URLLoaderTrusted*>(
1289 pp::Module::Get()->GetBrowserInterface(
1290 PPB_URLLOADERTRUSTED_INTERFACE));
1291 if (trusted_interface)
1292 trusted_interface->GrantUniversalAccess(loader.pp_resource());
1293 return loader;
1296 void OutOfProcessInstance::SetZoom(double scale) {
1297 double old_zoom = zoom_;
1298 zoom_ = scale;
1299 OnGeometryChanged(old_zoom, device_scale_);
1302 std::string OutOfProcessInstance::GetLocalizedString(PP_ResourceString id) {
1303 pp::Var rv(pp::PDF::GetLocalizedString(this, id));
1304 if (!rv.is_string())
1305 return std::string();
1307 return rv.AsString();
1310 void OutOfProcessInstance::AppendBlankPrintPreviewPages() {
1311 if (print_preview_page_count_ == 0)
1312 return;
1313 engine_->AppendBlankPages(print_preview_page_count_);
1314 if (preview_pages_info_.size() > 0)
1315 LoadAvailablePreviewPage();
1318 bool OutOfProcessInstance::IsPrintPreview() {
1319 return IsPrintPreviewUrl(url_);
1322 void OutOfProcessInstance::ProcessPreviewPageInfo(const std::string& url,
1323 int dst_page_index) {
1324 if (!IsPrintPreview())
1325 return;
1327 int src_page_index = ExtractPrintPreviewPageIndex(url);
1328 if (src_page_index < 1)
1329 return;
1331 preview_pages_info_.push(std::make_pair(url, dst_page_index));
1332 LoadAvailablePreviewPage();
1335 void OutOfProcessInstance::LoadAvailablePreviewPage() {
1336 if (preview_pages_info_.size() <= 0 ||
1337 document_load_state_ != LOAD_STATE_COMPLETE) {
1338 return;
1341 std::string url = preview_pages_info_.front().first;
1342 int dst_page_index = preview_pages_info_.front().second;
1343 int src_page_index = ExtractPrintPreviewPageIndex(url);
1344 if (src_page_index < 1 ||
1345 dst_page_index >= print_preview_page_count_ ||
1346 preview_document_load_state_ == LOAD_STATE_LOADING) {
1347 return;
1350 preview_document_load_state_ = LOAD_STATE_LOADING;
1351 LoadPreviewUrl(url);
1354 void OutOfProcessInstance::UserMetricsRecordAction(
1355 const std::string& action) {
1356 // TODO(raymes): Move this function to PPB_UMA_Private.
1357 pp::PDF::UserMetricsRecordAction(this, pp::Var(action));
1360 pp::Point OutOfProcessInstance::BoundScrollOffsetToDocument(
1361 const pp::Point& scroll_offset) {
1362 int max_x = document_size_.width() * zoom_ - plugin_dip_size_.width();
1363 int x = std::max(std::min(scroll_offset.x(), max_x), 0);
1364 int max_y = document_size_.height() * zoom_ - plugin_dip_size_.height();
1365 int y = std::max(std::min(scroll_offset.y(), max_y), 0);
1366 return pp::Point(x, y);
1369 } // namespace chrome_pdf