Supervised User block interstitial: change strings for child accounts
[chromium-blink-merge.git] / pdf / out_of_process_instance.cc
blob9dcf4d9aa33833643d0b9a219f3e4df1287013d2
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"
43 #include "v8/include/v8.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 // Save (Page -> Plugin)
89 const char kJSSaveType[] = "save";
90 // Go to page (Plugin -> Page)
91 const char kJSGoToPageType[] = "goToPage";
92 const char kJSPageNumber[] = "page";
93 // Reset print preview mode (Page -> Plugin)
94 const char kJSResetPrintPreviewModeType[] = "resetPrintPreviewMode";
95 const char kJSPrintPreviewUrl[] = "url";
96 const char kJSPrintPreviewGrayscale[] = "grayscale";
97 const char kJSPrintPreviewPageCount[] = "pageCount";
98 // Load preview page (Page -> Plugin)
99 const char kJSLoadPreviewPageType[] = "loadPreviewPage";
100 const char kJSPreviewPageUrl[] = "url";
101 const char kJSPreviewPageIndex[] = "index";
102 // Set scroll position (Plugin -> Page)
103 const char kJSSetScrollPositionType[] = "setScrollPosition";
104 const char kJSPositionX[] = "x";
105 const char kJSPositionY[] = "y";
106 // Set translated strings (Plugin -> Page)
107 const char kJSSetTranslatedStringsType[] = "setTranslatedStrings";
108 const char kJSGetPasswordString[] = "getPasswordString";
109 const char kJSLoadingString[] = "loadingString";
110 const char kJSLoadFailedString[] = "loadFailedString";
111 // Request accessibility JSON data (Page -> Plugin)
112 const char kJSGetAccessibilityJSONType[] = "getAccessibilityJSON";
113 const char kJSAccessibilityPageNumber[] = "page";
114 // Reply with accessibility JSON data (Plugin -> Page)
115 const char kJSGetAccessibilityJSONReplyType[] = "getAccessibilityJSONReply";
116 const char kJSAccessibilityJSON[] = "json";
117 // Cancel the stream URL request (Plugin -> Page)
118 const char kJSCancelStreamUrlType[] = "cancelStreamUrl";
119 // Navigate to the given URL (Plugin -> Page)
120 const char kJSNavigateType[] = "navigate";
121 const char kJSNavigateUrl[] = "url";
122 const char kJSNavigateNewTab[] = "newTab";
123 // Open the email editor with the given parameters (Plugin -> Page)
124 const char kJSEmailType[] = "email";
125 const char kJSEmailTo[] = "to";
126 const char kJSEmailCc[] = "cc";
127 const char kJSEmailBcc[] = "bcc";
128 const char kJSEmailSubject[] = "subject";
129 const char kJSEmailBody[] = "body";
130 // Rotation (Page -> Plugin)
131 const char kJSRotateClockwiseType[] = "rotateClockwise";
132 const char kJSRotateCounterclockwiseType[] = "rotateCounterclockwise";
133 // Select all text in the document (Page -> Plugin)
134 const char kJSSelectAllType[] = "selectAll";
136 const int kFindResultCooldownMs = 100;
138 const double kMinZoom = 0.01;
140 namespace {
142 static const char kPPPPdfInterface[] = PPP_PDF_INTERFACE_1;
144 PP_Var GetLinkAtPosition(PP_Instance instance, PP_Point point) {
145 pp::Var var;
146 void* object = pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
147 if (object) {
148 var = static_cast<OutOfProcessInstance*>(object)->GetLinkAtPosition(
149 pp::Point(point));
151 return var.Detach();
154 void Transform(PP_Instance instance, PP_PrivatePageTransformType type) {
155 void* object =
156 pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
157 if (object) {
158 OutOfProcessInstance* obj_instance =
159 static_cast<OutOfProcessInstance*>(object);
160 switch (type) {
161 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CW:
162 obj_instance->RotateClockwise();
163 break;
164 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CCW:
165 obj_instance->RotateCounterclockwise();
166 break;
171 PP_Bool GetPrintPresetOptionsFromDocument(
172 PP_Instance instance,
173 PP_PdfPrintPresetOptions_Dev* options) {
174 void* object = pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
175 if (object) {
176 OutOfProcessInstance* obj_instance =
177 static_cast<OutOfProcessInstance*>(object);
178 obj_instance->GetPrintPresetOptionsFromDocument(options);
180 return PP_TRUE;
183 const PPP_Pdf ppp_private = {
184 &GetLinkAtPosition,
185 &Transform,
186 &GetPrintPresetOptionsFromDocument
189 int ExtractPrintPreviewPageIndex(const std::string& src_url) {
190 // Sample |src_url| format: chrome://print/id/page_index/print.pdf
191 std::vector<std::string> url_substr;
192 base::SplitString(src_url.substr(strlen(kChromePrint)), '/', &url_substr);
193 if (url_substr.size() != 3)
194 return -1;
196 if (url_substr[2] != "print.pdf")
197 return -1;
199 int page_index = 0;
200 if (!base::StringToInt(url_substr[1], &page_index))
201 return -1;
202 return page_index;
205 bool IsPrintPreviewUrl(const std::string& url) {
206 return url.substr(0, strlen(kChromePrint)) == kChromePrint;
209 void ScalePoint(float scale, pp::Point* point) {
210 point->set_x(static_cast<int>(point->x() * scale));
211 point->set_y(static_cast<int>(point->y() * scale));
214 void ScaleRect(float scale, pp::Rect* rect) {
215 int left = static_cast<int>(floorf(rect->x() * scale));
216 int top = static_cast<int>(floorf(rect->y() * scale));
217 int right = static_cast<int>(ceilf((rect->x() + rect->width()) * scale));
218 int bottom = static_cast<int>(ceilf((rect->y() + rect->height()) * scale));
219 rect->SetRect(left, top, right - left, bottom - top);
222 // TODO(raymes): Remove this dependency on VarPrivate/InstancePrivate. It's
223 // needed right now to do a synchronous call to JavaScript, but we could easily
224 // replace this with a custom PPB_PDF function.
225 pp::Var ModalDialog(const pp::Instance* instance,
226 const std::string& type,
227 const std::string& message,
228 const std::string& default_answer) {
229 const PPB_Instance_Private* interface =
230 reinterpret_cast<const PPB_Instance_Private*>(
231 pp::Module::Get()->GetBrowserInterface(
232 PPB_INSTANCE_PRIVATE_INTERFACE));
233 pp::VarPrivate window(pp::PASS_REF,
234 interface->GetWindowObject(instance->pp_instance()));
235 if (default_answer.empty())
236 return window.Call(type, message);
237 else
238 return window.Call(type, message, default_answer);
241 } // namespace
243 OutOfProcessInstance::OutOfProcessInstance(PP_Instance instance)
244 : pp::Instance(instance),
245 pp::Find_Private(this),
246 pp::Printing_Dev(this),
247 pp::Selection_Dev(this),
248 cursor_(PP_CURSORTYPE_POINTER),
249 zoom_(1.0),
250 device_scale_(1.0),
251 printing_enabled_(true),
252 full_(false),
253 paint_manager_(this, this, true),
254 first_paint_(true),
255 document_load_state_(LOAD_STATE_LOADING),
256 preview_document_load_state_(LOAD_STATE_COMPLETE),
257 uma_(this),
258 told_browser_about_unsupported_feature_(false),
259 print_preview_page_count_(0),
260 last_progress_sent_(0),
261 recently_sent_find_update_(false),
262 received_viewport_message_(false),
263 did_call_start_loading_(false),
264 stop_scrolling_(false) {
265 loader_factory_.Initialize(this);
266 timer_factory_.Initialize(this);
267 form_factory_.Initialize(this);
268 print_callback_factory_.Initialize(this);
269 engine_.reset(PDFEngine::Create(this));
270 pp::Module::Get()->AddPluginInterface(kPPPPdfInterface, &ppp_private);
271 AddPerInstanceObject(kPPPPdfInterface, this);
273 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_MOUSE);
274 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_KEYBOARD);
275 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_TOUCH);
278 OutOfProcessInstance::~OutOfProcessInstance() {
279 RemovePerInstanceObject(kPPPPdfInterface, this);
282 bool OutOfProcessInstance::Init(uint32_t argc,
283 const char* argn[],
284 const char* argv[]) {
285 v8::StartupData natives;
286 v8::StartupData snapshot;
287 pp::PDF::GetV8ExternalSnapshotData(this, &natives.data, &natives.raw_size,
288 &snapshot.data, &snapshot.raw_size);
289 if (natives.data) {
290 v8::V8::SetNativesDataBlob(&natives);
291 v8::V8::SetSnapshotDataBlob(&snapshot);
294 // Check if the PDF is being loaded in the PDF chrome extension. We only allow
295 // the plugin to be put into "full frame" mode when it is being loaded in the
296 // extension because this enables some features that we don't want pages
297 // abusing outside of the extension.
298 pp::Var document_url_var = pp::URLUtil_Dev::Get()->GetDocumentURL(this);
299 std::string document_url = document_url_var.is_string() ?
300 document_url_var.AsString() : std::string();
301 std::string extension_url = std::string(kChromeExtension);
302 bool in_extension =
303 !document_url.compare(0, extension_url.size(), extension_url);
305 if (in_extension) {
306 // Check if the plugin is full frame. This is passed in from JS.
307 for (uint32_t i = 0; i < argc; ++i) {
308 if (strcmp(argn[i], "full-frame") == 0) {
309 full_ = true;
310 break;
315 // Only allow the plugin to handle find requests if it is full frame.
316 if (full_)
317 SetPluginToHandleFindRequests();
319 // Send translated strings to the extension where they will be displayed.
320 // TODO(raymes): It would be better to get these in the extension directly
321 // through an API but no such API currently exists.
322 pp::VarDictionary translated_strings;
323 translated_strings.Set(kType, kJSSetTranslatedStringsType);
324 translated_strings.Set(kJSGetPasswordString,
325 GetLocalizedString(PP_RESOURCESTRING_PDFGETPASSWORD));
326 translated_strings.Set(kJSLoadingString,
327 GetLocalizedString(PP_RESOURCESTRING_PDFLOADING));
328 translated_strings.Set(kJSLoadFailedString,
329 GetLocalizedString(PP_RESOURCESTRING_PDFLOAD_FAILED));
330 PostMessage(translated_strings);
332 text_input_.reset(new pp::TextInput_Dev(this));
334 const char* stream_url = NULL;
335 const char* original_url = NULL;
336 const char* headers = NULL;
337 for (uint32_t i = 0; i < argc; ++i) {
338 if (strcmp(argn[i], "src") == 0)
339 original_url = argv[i];
340 else if (strcmp(argn[i], "stream-url") == 0)
341 stream_url = argv[i];
342 else if (strcmp(argn[i], "headers") == 0)
343 headers = argv[i];
346 // TODO(raymes): This is a hack to ensure that if no headers are passed in
347 // then we get the right MIME type. When the in process plugin is removed we
348 // can fix the document loader properly and remove this hack.
349 if (!headers || strcmp(headers, "") == 0)
350 headers = "content-type: application/pdf";
352 if (!original_url)
353 return false;
355 if (!stream_url)
356 stream_url = original_url;
358 // If we're in print preview mode we don't need to load the document yet.
359 // A |kJSResetPrintPreviewModeType| message will be sent to the plugin letting
360 // it know the url to load. By not loading here we avoid loading the same
361 // document twice.
362 if (IsPrintPreviewUrl(original_url))
363 return true;
365 LoadUrl(stream_url);
366 url_ = original_url;
367 return engine_->New(original_url, headers);
370 void OutOfProcessInstance::HandleMessage(const pp::Var& message) {
371 pp::VarDictionary dict(message);
372 if (!dict.Get(kType).is_string()) {
373 NOTREACHED();
374 return;
377 std::string type = dict.Get(kType).AsString();
379 if (type == kJSViewportType &&
380 dict.Get(pp::Var(kJSXOffset)).is_number() &&
381 dict.Get(pp::Var(kJSYOffset)).is_number() &&
382 dict.Get(pp::Var(kJSZoom)).is_number()) {
383 received_viewport_message_ = true;
384 stop_scrolling_ = false;
385 double zoom = dict.Get(pp::Var(kJSZoom)).AsDouble();
386 pp::FloatPoint scroll_offset(dict.Get(pp::Var(kJSXOffset)).AsDouble(),
387 dict.Get(pp::Var(kJSYOffset)).AsDouble());
389 // Bound the input parameters.
390 zoom = std::max(kMinZoom, zoom);
391 SetZoom(zoom);
392 scroll_offset = BoundScrollOffsetToDocument(scroll_offset);
393 engine_->ScrolledToXPosition(scroll_offset.x() * device_scale_);
394 engine_->ScrolledToYPosition(scroll_offset.y() * device_scale_);
395 } else if (type == kJSGetPasswordCompleteType &&
396 dict.Get(pp::Var(kJSPassword)).is_string()) {
397 if (password_callback_) {
398 pp::CompletionCallbackWithOutput<pp::Var> callback = *password_callback_;
399 password_callback_.reset();
400 *callback.output() = dict.Get(pp::Var(kJSPassword)).pp_var();
401 callback.Run(PP_OK);
402 } else {
403 NOTREACHED();
405 } else if (type == kJSPrintType) {
406 Print();
407 } else if (type == kJSSaveType) {
408 pp::PDF::SaveAs(this);
409 } else if (type == kJSRotateClockwiseType) {
410 RotateClockwise();
411 } else if (type == kJSRotateCounterclockwiseType) {
412 RotateCounterclockwise();
413 } else if (type == kJSSelectAllType) {
414 engine_->SelectAll();
415 } else if (type == kJSResetPrintPreviewModeType &&
416 dict.Get(pp::Var(kJSPrintPreviewUrl)).is_string() &&
417 dict.Get(pp::Var(kJSPrintPreviewGrayscale)).is_bool() &&
418 dict.Get(pp::Var(kJSPrintPreviewPageCount)).is_int()) {
419 url_ = dict.Get(pp::Var(kJSPrintPreviewUrl)).AsString();
420 preview_pages_info_ = std::queue<PreviewPageInfo>();
421 preview_document_load_state_ = LOAD_STATE_COMPLETE;
422 document_load_state_ = LOAD_STATE_LOADING;
423 LoadUrl(url_);
424 preview_engine_.reset();
425 engine_.reset(PDFEngine::Create(this));
426 engine_->SetGrayscale(dict.Get(pp::Var(kJSPrintPreviewGrayscale)).AsBool());
427 engine_->New(url_.c_str());
429 print_preview_page_count_ =
430 std::max(dict.Get(pp::Var(kJSPrintPreviewPageCount)).AsInt(), 0);
432 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
433 } else if (type == kJSLoadPreviewPageType &&
434 dict.Get(pp::Var(kJSPreviewPageUrl)).is_string() &&
435 dict.Get(pp::Var(kJSPreviewPageIndex)).is_int()) {
436 ProcessPreviewPageInfo(dict.Get(pp::Var(kJSPreviewPageUrl)).AsString(),
437 dict.Get(pp::Var(kJSPreviewPageIndex)).AsInt());
438 } else if (type == kJSGetAccessibilityJSONType) {
439 pp::VarDictionary reply;
440 reply.Set(pp::Var(kType), pp::Var(kJSGetAccessibilityJSONReplyType));
441 if (dict.Get(pp::Var(kJSAccessibilityPageNumber)).is_int()) {
442 int page = dict.Get(pp::Var(kJSAccessibilityPageNumber)).AsInt();
443 reply.Set(pp::Var(kJSAccessibilityJSON),
444 pp::Var(engine_->GetPageAsJSON(page)));
445 } else {
446 base::DictionaryValue node;
447 node.SetInteger(kAccessibleNumberOfPages, engine_->GetNumberOfPages());
448 node.SetBoolean(kAccessibleLoaded,
449 document_load_state_ != LOAD_STATE_LOADING);
450 bool has_permissions =
451 engine_->HasPermission(PDFEngine::PERMISSION_COPY) ||
452 engine_->HasPermission(PDFEngine::PERMISSION_COPY_ACCESSIBLE);
453 node.SetBoolean(kAccessibleCopyable, has_permissions);
454 std::string json;
455 base::JSONWriter::Write(&node, &json);
456 reply.Set(pp::Var(kJSAccessibilityJSON), pp::Var(json));
458 PostMessage(reply);
459 } else if (type == kJSStopScrollingType) {
460 stop_scrolling_ = true;
461 } else {
462 NOTREACHED();
466 bool OutOfProcessInstance::HandleInputEvent(
467 const pp::InputEvent& event) {
468 // To simplify things, convert the event into device coordinates if it is
469 // a mouse event.
470 pp::InputEvent event_device_res(event);
472 pp::MouseInputEvent mouse_event(event);
473 if (!mouse_event.is_null()) {
474 pp::Point point = mouse_event.GetPosition();
475 pp::Point movement = mouse_event.GetMovement();
476 ScalePoint(device_scale_, &point);
477 ScalePoint(device_scale_, &movement);
478 mouse_event = pp::MouseInputEvent(
479 this,
480 event.GetType(),
481 event.GetTimeStamp(),
482 event.GetModifiers(),
483 mouse_event.GetButton(),
484 point,
485 mouse_event.GetClickCount(),
486 movement);
487 event_device_res = mouse_event;
491 pp::InputEvent offset_event(event_device_res);
492 switch (offset_event.GetType()) {
493 case PP_INPUTEVENT_TYPE_MOUSEDOWN:
494 case PP_INPUTEVENT_TYPE_MOUSEUP:
495 case PP_INPUTEVENT_TYPE_MOUSEMOVE:
496 case PP_INPUTEVENT_TYPE_MOUSEENTER:
497 case PP_INPUTEVENT_TYPE_MOUSELEAVE: {
498 pp::MouseInputEvent mouse_event(event_device_res);
499 pp::MouseInputEvent mouse_event_dip(event);
500 pp::Point point = mouse_event.GetPosition();
501 point.set_x(point.x() - available_area_.x());
502 offset_event = pp::MouseInputEvent(
503 this,
504 event.GetType(),
505 event.GetTimeStamp(),
506 event.GetModifiers(),
507 mouse_event.GetButton(),
508 point,
509 mouse_event.GetClickCount(),
510 mouse_event.GetMovement());
511 break;
513 default:
514 break;
516 if (engine_->HandleEvent(offset_event))
517 return true;
519 // TODO(raymes): Implement this scroll behavior in JS:
520 // When click+dragging, scroll the document correctly.
522 // Return true for unhandled clicks so the plugin takes focus.
523 return (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN);
526 void OutOfProcessInstance::DidChangeView(const pp::View& view) {
527 pp::Rect view_rect(view.GetRect());
528 float old_device_scale = device_scale_;
529 float device_scale = view.GetDeviceScale();
530 pp::Size view_device_size(view_rect.width() * device_scale,
531 view_rect.height() * device_scale);
533 if (view_device_size != plugin_size_ || device_scale != device_scale_) {
534 device_scale_ = device_scale;
535 plugin_dip_size_ = view_rect.size();
536 plugin_size_ = view_device_size;
538 paint_manager_.SetSize(view_device_size, device_scale_);
540 pp::Size new_image_data_size = PaintManager::GetNewContextSize(
541 image_data_.size(),
542 plugin_size_);
543 if (new_image_data_size != image_data_.size()) {
544 image_data_ = pp::ImageData(this,
545 PP_IMAGEDATAFORMAT_BGRA_PREMUL,
546 new_image_data_size,
547 false);
548 first_paint_ = true;
551 if (image_data_.is_null()) {
552 DCHECK(plugin_size_.IsEmpty());
553 return;
556 OnGeometryChanged(zoom_, old_device_scale);
559 if (!stop_scrolling_) {
560 pp::Point scroll_offset(view.GetScrollOffset());
561 pp::FloatPoint scroll_offset_float(scroll_offset.x(),
562 scroll_offset.y());
563 scroll_offset_float = BoundScrollOffsetToDocument(scroll_offset_float);
564 engine_->ScrolledToXPosition(scroll_offset_float.x() * device_scale_);
565 engine_->ScrolledToYPosition(scroll_offset_float.y() * device_scale_);
569 void OutOfProcessInstance::GetPrintPresetOptionsFromDocument(
570 PP_PdfPrintPresetOptions_Dev* options) {
571 options->is_scaling_disabled = PP_FromBool(IsPrintScalingDisabled());
572 options->copies = engine_->GetCopiesToPrint();
575 pp::Var OutOfProcessInstance::GetLinkAtPosition(
576 const pp::Point& point) {
577 pp::Point offset_point(point);
578 ScalePoint(device_scale_, &offset_point);
579 offset_point.set_x(offset_point.x() - available_area_.x());
580 return engine_->GetLinkAtPosition(offset_point);
583 pp::Var OutOfProcessInstance::GetSelectedText(bool html) {
584 if (html || !engine_->HasPermission(PDFEngine::PERMISSION_COPY))
585 return pp::Var();
586 return engine_->GetSelectedText();
589 uint32_t OutOfProcessInstance::QuerySupportedPrintOutputFormats() {
590 return engine_->QuerySupportedPrintOutputFormats();
593 int32_t OutOfProcessInstance::PrintBegin(
594 const PP_PrintSettings_Dev& print_settings) {
595 // For us num_pages is always equal to the number of pages in the PDF
596 // document irrespective of the printable area.
597 int32_t ret = engine_->GetNumberOfPages();
598 if (!ret)
599 return 0;
601 uint32_t supported_formats = engine_->QuerySupportedPrintOutputFormats();
602 if ((print_settings.format & supported_formats) == 0)
603 return 0;
605 print_settings_.is_printing = true;
606 print_settings_.pepper_print_settings = print_settings;
607 engine_->PrintBegin();
608 return ret;
611 pp::Resource OutOfProcessInstance::PrintPages(
612 const PP_PrintPageNumberRange_Dev* page_ranges,
613 uint32_t page_range_count) {
614 if (!print_settings_.is_printing)
615 return pp::Resource();
617 print_settings_.print_pages_called_ = true;
618 return engine_->PrintPages(page_ranges, page_range_count,
619 print_settings_.pepper_print_settings);
622 void OutOfProcessInstance::PrintEnd() {
623 if (print_settings_.print_pages_called_)
624 UserMetricsRecordAction("PDF.PrintPage");
625 print_settings_.Clear();
626 engine_->PrintEnd();
629 bool OutOfProcessInstance::IsPrintScalingDisabled() {
630 return !engine_->GetPrintScaling();
633 bool OutOfProcessInstance::StartFind(const std::string& text,
634 bool case_sensitive) {
635 engine_->StartFind(text.c_str(), case_sensitive);
636 return true;
639 void OutOfProcessInstance::SelectFindResult(bool forward) {
640 engine_->SelectFindResult(forward);
643 void OutOfProcessInstance::StopFind() {
644 engine_->StopFind();
645 tickmarks_.clear();
646 SetTickmarks(tickmarks_);
649 void OutOfProcessInstance::OnPaint(
650 const std::vector<pp::Rect>& paint_rects,
651 std::vector<PaintManager::ReadyRect>* ready,
652 std::vector<pp::Rect>* pending) {
653 if (image_data_.is_null()) {
654 DCHECK(plugin_size_.IsEmpty());
655 return;
657 if (first_paint_) {
658 first_paint_ = false;
659 pp::Rect rect = pp::Rect(pp::Point(), image_data_.size());
660 FillRect(rect, kBackgroundColor);
661 ready->push_back(PaintManager::ReadyRect(rect, image_data_, true));
664 if (!received_viewport_message_)
665 return;
667 engine_->PrePaint();
669 for (size_t i = 0; i < paint_rects.size(); i++) {
670 // Intersect with plugin area since there could be pending invalidates from
671 // when the plugin area was larger.
672 pp::Rect rect =
673 paint_rects[i].Intersect(pp::Rect(pp::Point(), plugin_size_));
674 if (rect.IsEmpty())
675 continue;
677 pp::Rect pdf_rect = available_area_.Intersect(rect);
678 if (!pdf_rect.IsEmpty()) {
679 pdf_rect.Offset(available_area_.x() * -1, 0);
681 std::vector<pp::Rect> pdf_ready;
682 std::vector<pp::Rect> pdf_pending;
683 engine_->Paint(pdf_rect, &image_data_, &pdf_ready, &pdf_pending);
684 for (size_t j = 0; j < pdf_ready.size(); ++j) {
685 pdf_ready[j].Offset(available_area_.point());
686 ready->push_back(
687 PaintManager::ReadyRect(pdf_ready[j], image_data_, false));
689 for (size_t j = 0; j < pdf_pending.size(); ++j) {
690 pdf_pending[j].Offset(available_area_.point());
691 pending->push_back(pdf_pending[j]);
695 for (size_t j = 0; j < background_parts_.size(); ++j) {
696 pp::Rect intersection = background_parts_[j].location.Intersect(rect);
697 if (!intersection.IsEmpty()) {
698 FillRect(intersection, background_parts_[j].color);
699 ready->push_back(
700 PaintManager::ReadyRect(intersection, image_data_, false));
705 engine_->PostPaint();
708 void OutOfProcessInstance::DidOpen(int32_t result) {
709 if (result == PP_OK) {
710 if (!engine_->HandleDocumentLoad(embed_loader_)) {
711 document_load_state_ = LOAD_STATE_LOADING;
712 DocumentLoadFailed();
714 } else if (result != PP_ERROR_ABORTED) { // Can happen in tests.
715 NOTREACHED();
716 DocumentLoadFailed();
719 // If it's a progressive load, cancel the stream URL request so that requests
720 // can be made on the original URL.
721 // TODO(raymes): Make this clearer once the in-process plugin is deleted.
722 if (engine_->IsProgressiveLoad()) {
723 pp::VarDictionary message;
724 message.Set(kType, kJSCancelStreamUrlType);
725 PostMessage(message);
729 void OutOfProcessInstance::DidOpenPreview(int32_t result) {
730 if (result == PP_OK) {
731 preview_engine_.reset(PDFEngine::Create(new PreviewModeClient(this)));
732 preview_engine_->HandleDocumentLoad(embed_preview_loader_);
733 } else {
734 NOTREACHED();
738 void OutOfProcessInstance::OnClientTimerFired(int32_t id) {
739 engine_->OnCallback(id);
742 void OutOfProcessInstance::CalculateBackgroundParts() {
743 background_parts_.clear();
744 int left_width = available_area_.x();
745 int right_start = available_area_.right();
746 int right_width = abs(plugin_size_.width() - available_area_.right());
747 int bottom = std::min(available_area_.bottom(), plugin_size_.height());
749 // Add the left, right, and bottom rectangles. Note: we assume only
750 // horizontal centering.
751 BackgroundPart part = {
752 pp::Rect(0, 0, left_width, bottom),
753 kBackgroundColor
755 if (!part.location.IsEmpty())
756 background_parts_.push_back(part);
757 part.location = pp::Rect(right_start, 0, right_width, bottom);
758 if (!part.location.IsEmpty())
759 background_parts_.push_back(part);
760 part.location = pp::Rect(
761 0, bottom, plugin_size_.width(), plugin_size_.height() - bottom);
762 if (!part.location.IsEmpty())
763 background_parts_.push_back(part);
766 int OutOfProcessInstance::GetDocumentPixelWidth() const {
767 return static_cast<int>(ceil(document_size_.width() * zoom_ * device_scale_));
770 int OutOfProcessInstance::GetDocumentPixelHeight() const {
771 return static_cast<int>(
772 ceil(document_size_.height() * zoom_ * device_scale_));
775 void OutOfProcessInstance::FillRect(const pp::Rect& rect, uint32 color) {
776 DCHECK(!image_data_.is_null() || rect.IsEmpty());
777 uint32* buffer_start = static_cast<uint32*>(image_data_.data());
778 int stride = image_data_.stride();
779 uint32* ptr = buffer_start + rect.y() * stride / 4 + rect.x();
780 int height = rect.height();
781 int width = rect.width();
782 for (int y = 0; y < height; ++y) {
783 for (int x = 0; x < width; ++x)
784 *(ptr + x) = color;
785 ptr += stride /4;
789 void OutOfProcessInstance::DocumentSizeUpdated(const pp::Size& size) {
790 document_size_ = size;
792 pp::VarDictionary dimensions;
793 dimensions.Set(kType, kJSDocumentDimensionsType);
794 dimensions.Set(kJSDocumentWidth, pp::Var(document_size_.width()));
795 dimensions.Set(kJSDocumentHeight, pp::Var(document_size_.height()));
796 pp::VarArray page_dimensions_array;
797 int num_pages = engine_->GetNumberOfPages();
798 for (int i = 0; i < num_pages; ++i) {
799 pp::Rect page_rect = engine_->GetPageRect(i);
800 pp::VarDictionary page_dimensions;
801 page_dimensions.Set(kJSPageX, pp::Var(page_rect.x()));
802 page_dimensions.Set(kJSPageY, pp::Var(page_rect.y()));
803 page_dimensions.Set(kJSPageWidth, pp::Var(page_rect.width()));
804 page_dimensions.Set(kJSPageHeight, pp::Var(page_rect.height()));
805 page_dimensions_array.Set(i, page_dimensions);
807 dimensions.Set(kJSPageDimensions, page_dimensions_array);
808 PostMessage(dimensions);
810 OnGeometryChanged(zoom_, device_scale_);
813 void OutOfProcessInstance::Invalidate(const pp::Rect& rect) {
814 pp::Rect offset_rect(rect);
815 offset_rect.Offset(available_area_.point());
816 paint_manager_.InvalidateRect(offset_rect);
819 void OutOfProcessInstance::Scroll(const pp::Point& point) {
820 if (!image_data_.is_null())
821 paint_manager_.ScrollRect(available_area_, point);
824 void OutOfProcessInstance::ScrollToX(int x) {
825 pp::VarDictionary position;
826 position.Set(kType, kJSSetScrollPositionType);
827 position.Set(kJSPositionX, pp::Var(x / device_scale_));
828 PostMessage(position);
831 void OutOfProcessInstance::ScrollToY(int y) {
832 pp::VarDictionary position;
833 position.Set(kType, kJSSetScrollPositionType);
834 position.Set(kJSPositionY, pp::Var(y / device_scale_));
835 PostMessage(position);
838 void OutOfProcessInstance::ScrollToPage(int page) {
839 if (engine_->GetNumberOfPages() == 0)
840 return;
842 pp::VarDictionary message;
843 message.Set(kType, kJSGoToPageType);
844 message.Set(kJSPageNumber, pp::Var(page));
845 PostMessage(message);
848 void OutOfProcessInstance::NavigateTo(const std::string& url,
849 bool open_in_new_tab) {
850 std::string url_copy(url);
852 // Empty |url_copy| is ok, and will effectively be a reload.
853 // Skip the code below so an empty URL does not turn into "http://", which
854 // will cause GURL to fail a DCHECK.
855 if (!url_copy.empty()) {
856 // If |url_copy| starts with '#', then it's for the same URL with a
857 // different URL fragment.
858 if (url_copy[0] == '#') {
859 url_copy = url_ + url_copy;
861 // If there's no scheme, add http.
862 if (url_copy.find("://") == std::string::npos &&
863 url_copy.find("mailto:") == std::string::npos) {
864 url_copy = std::string("http://") + url_copy;
866 // Make sure |url_copy| starts with a valid scheme.
867 if (url_copy.find("http://") != 0 &&
868 url_copy.find("https://") != 0 &&
869 url_copy.find("ftp://") != 0 &&
870 url_copy.find("file://") != 0 &&
871 url_copy.find("mailto:") != 0) {
872 return;
874 // Make sure |url_copy| is not only a scheme.
875 if (url_copy == "http://" ||
876 url_copy == "https://" ||
877 url_copy == "ftp://" ||
878 url_copy == "file://" ||
879 url_copy == "mailto:") {
880 return;
883 pp::VarDictionary message;
884 message.Set(kType, kJSNavigateType);
885 message.Set(kJSNavigateUrl, url_copy);
886 message.Set(kJSNavigateNewTab, open_in_new_tab);
887 PostMessage(message);
890 void OutOfProcessInstance::UpdateCursor(PP_CursorType_Dev cursor) {
891 if (cursor == cursor_)
892 return;
893 cursor_ = cursor;
895 const PPB_CursorControl_Dev* cursor_interface =
896 reinterpret_cast<const PPB_CursorControl_Dev*>(
897 pp::Module::Get()->GetBrowserInterface(PPB_CURSOR_CONTROL_DEV_INTERFACE));
898 if (!cursor_interface) {
899 NOTREACHED();
900 return;
903 cursor_interface->SetCursor(
904 pp_instance(), cursor_, pp::ImageData().pp_resource(), NULL);
907 void OutOfProcessInstance::UpdateTickMarks(
908 const std::vector<pp::Rect>& tickmarks) {
909 float inverse_scale = 1.0f / device_scale_;
910 std::vector<pp::Rect> scaled_tickmarks = tickmarks;
911 for (size_t i = 0; i < scaled_tickmarks.size(); i++)
912 ScaleRect(inverse_scale, &scaled_tickmarks[i]);
913 tickmarks_ = scaled_tickmarks;
916 void OutOfProcessInstance::NotifyNumberOfFindResultsChanged(int total,
917 bool final_result) {
918 // We don't want to spam the renderer with too many updates to the number of
919 // find results. Don't send an update if we sent one too recently. If it's the
920 // final update, we always send it though.
921 if (final_result) {
922 NumberOfFindResultsChanged(total, final_result);
923 SetTickmarks(tickmarks_);
924 return;
927 if (recently_sent_find_update_)
928 return;
930 NumberOfFindResultsChanged(total, final_result);
931 SetTickmarks(tickmarks_);
932 recently_sent_find_update_ = true;
933 pp::CompletionCallback callback =
934 timer_factory_.NewCallback(
935 &OutOfProcessInstance::ResetRecentlySentFindUpdate);
936 pp::Module::Get()->core()->CallOnMainThread(kFindResultCooldownMs,
937 callback, 0);
940 void OutOfProcessInstance::NotifySelectedFindResultChanged(
941 int current_find_index) {
942 DCHECK_GE(current_find_index, 0);
943 SelectedFindResultChanged(current_find_index);
946 void OutOfProcessInstance::GetDocumentPassword(
947 pp::CompletionCallbackWithOutput<pp::Var> callback) {
948 if (password_callback_) {
949 NOTREACHED();
950 return;
953 password_callback_.reset(
954 new pp::CompletionCallbackWithOutput<pp::Var>(callback));
955 pp::VarDictionary message;
956 message.Set(pp::Var(kType), pp::Var(kJSGetPasswordType));
957 PostMessage(message);
960 void OutOfProcessInstance::Alert(const std::string& message) {
961 ModalDialog(this, "alert", message, std::string());
964 bool OutOfProcessInstance::Confirm(const std::string& message) {
965 pp::Var result = ModalDialog(this, "confirm", message, std::string());
966 return result.is_bool() ? result.AsBool() : false;
969 std::string OutOfProcessInstance::Prompt(const std::string& question,
970 const std::string& default_answer) {
971 pp::Var result = ModalDialog(this, "prompt", question, default_answer);
972 return result.is_string() ? result.AsString() : std::string();
975 std::string OutOfProcessInstance::GetURL() {
976 return url_;
979 void OutOfProcessInstance::Email(const std::string& to,
980 const std::string& cc,
981 const std::string& bcc,
982 const std::string& subject,
983 const std::string& body) {
984 pp::VarDictionary message;
985 message.Set(pp::Var(kType), pp::Var(kJSEmailType));
986 message.Set(pp::Var(kJSEmailTo),
987 pp::Var(net::EscapeUrlEncodedData(to, false)));
988 message.Set(pp::Var(kJSEmailCc),
989 pp::Var(net::EscapeUrlEncodedData(cc, false)));
990 message.Set(pp::Var(kJSEmailBcc),
991 pp::Var(net::EscapeUrlEncodedData(bcc, false)));
992 message.Set(pp::Var(kJSEmailSubject),
993 pp::Var(net::EscapeUrlEncodedData(subject, false)));
994 message.Set(pp::Var(kJSEmailBody),
995 pp::Var(net::EscapeUrlEncodedData(body, false)));
996 PostMessage(message);
999 void OutOfProcessInstance::Print() {
1000 if (!printing_enabled_ ||
1001 (!engine_->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY) &&
1002 !engine_->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY))) {
1003 return;
1006 pp::CompletionCallback callback =
1007 print_callback_factory_.NewCallback(&OutOfProcessInstance::OnPrint);
1008 pp::Module::Get()->core()->CallOnMainThread(0, callback);
1011 void OutOfProcessInstance::OnPrint(int32_t) {
1012 pp::PDF::Print(this);
1015 void OutOfProcessInstance::SubmitForm(const std::string& url,
1016 const void* data,
1017 int length) {
1018 pp::URLRequestInfo request(this);
1019 request.SetURL(url);
1020 request.SetMethod("POST");
1021 request.AppendDataToBody(reinterpret_cast<const char*>(data), length);
1023 pp::CompletionCallback callback =
1024 form_factory_.NewCallback(&OutOfProcessInstance::FormDidOpen);
1025 form_loader_ = CreateURLLoaderInternal();
1026 int rv = form_loader_.Open(request, callback);
1027 if (rv != PP_OK_COMPLETIONPENDING)
1028 callback.Run(rv);
1031 void OutOfProcessInstance::FormDidOpen(int32_t result) {
1032 // TODO: inform the user of success/failure.
1033 if (result != PP_OK) {
1034 NOTREACHED();
1038 std::string OutOfProcessInstance::ShowFileSelectionDialog() {
1039 // Seems like very low priority to implement, since the pdf has no way to get
1040 // the file data anyways. Javascript doesn't let you do this synchronously.
1041 NOTREACHED();
1042 return std::string();
1045 pp::URLLoader OutOfProcessInstance::CreateURLLoader() {
1046 if (full_) {
1047 if (!did_call_start_loading_) {
1048 did_call_start_loading_ = true;
1049 pp::PDF::DidStartLoading(this);
1052 // Disable save and print until the document is fully loaded, since they
1053 // would generate an incomplete document. Need to do this each time we
1054 // call DidStartLoading since that resets the content restrictions.
1055 pp::PDF::SetContentRestriction(this, CONTENT_RESTRICTION_SAVE |
1056 CONTENT_RESTRICTION_PRINT);
1059 return CreateURLLoaderInternal();
1062 void OutOfProcessInstance::ScheduleCallback(int id, int delay_in_ms) {
1063 pp::CompletionCallback callback =
1064 timer_factory_.NewCallback(&OutOfProcessInstance::OnClientTimerFired);
1065 pp::Module::Get()->core()->CallOnMainThread(delay_in_ms, callback, id);
1068 void OutOfProcessInstance::SearchString(const base::char16* string,
1069 const base::char16* term,
1070 bool case_sensitive,
1071 std::vector<SearchStringResult>* results) {
1072 PP_PrivateFindResult* pp_results;
1073 int count = 0;
1074 pp::PDF::SearchString(
1075 this,
1076 reinterpret_cast<const unsigned short*>(string),
1077 reinterpret_cast<const unsigned short*>(term),
1078 case_sensitive,
1079 &pp_results,
1080 &count);
1082 results->resize(count);
1083 for (int i = 0; i < count; ++i) {
1084 (*results)[i].start_index = pp_results[i].start_index;
1085 (*results)[i].length = pp_results[i].length;
1088 pp::Memory_Dev memory;
1089 memory.MemFree(pp_results);
1092 void OutOfProcessInstance::DocumentPaintOccurred() {
1095 void OutOfProcessInstance::DocumentLoadComplete(int page_count) {
1096 // Clear focus state for OSK.
1097 FormTextFieldFocusChange(false);
1099 DCHECK(document_load_state_ == LOAD_STATE_LOADING);
1100 document_load_state_ = LOAD_STATE_COMPLETE;
1101 UserMetricsRecordAction("PDF.LoadSuccess");
1103 // Note: If we are in print preview mode the scroll location is retained
1104 // across document loads so we don't want to scroll again and override it.
1105 if (IsPrintPreview()) {
1106 AppendBlankPrintPreviewPages();
1107 OnGeometryChanged(0, 0);
1110 pp::VarDictionary message;
1111 message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1112 message.Set(pp::Var(kJSProgressPercentage), pp::Var(100)) ;
1113 PostMessage(message);
1115 if (!full_)
1116 return;
1118 if (did_call_start_loading_) {
1119 pp::PDF::DidStopLoading(this);
1120 did_call_start_loading_ = false;
1123 int content_restrictions =
1124 CONTENT_RESTRICTION_CUT | CONTENT_RESTRICTION_PASTE;
1125 if (!engine_->HasPermission(PDFEngine::PERMISSION_COPY))
1126 content_restrictions |= CONTENT_RESTRICTION_COPY;
1128 if (!engine_->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY) &&
1129 !engine_->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY)) {
1130 printing_enabled_ = false;
1133 pp::PDF::SetContentRestriction(this, content_restrictions);
1135 uma_.HistogramCustomCounts("PDF.PageCount", page_count,
1136 1, 1000000, 50);
1139 void OutOfProcessInstance::RotateClockwise() {
1140 engine_->RotateClockwise();
1143 void OutOfProcessInstance::RotateCounterclockwise() {
1144 engine_->RotateCounterclockwise();
1147 void OutOfProcessInstance::PreviewDocumentLoadComplete() {
1148 if (preview_document_load_state_ != LOAD_STATE_LOADING ||
1149 preview_pages_info_.empty()) {
1150 return;
1153 preview_document_load_state_ = LOAD_STATE_COMPLETE;
1155 int dest_page_index = preview_pages_info_.front().second;
1156 int src_page_index =
1157 ExtractPrintPreviewPageIndex(preview_pages_info_.front().first);
1158 if (src_page_index > 0 && dest_page_index > -1 && preview_engine_.get())
1159 engine_->AppendPage(preview_engine_.get(), dest_page_index);
1161 preview_pages_info_.pop();
1162 // |print_preview_page_count_| is not updated yet. Do not load any
1163 // other preview pages till we get this information.
1164 if (print_preview_page_count_ == 0)
1165 return;
1167 if (preview_pages_info_.size())
1168 LoadAvailablePreviewPage();
1171 void OutOfProcessInstance::DocumentLoadFailed() {
1172 DCHECK(document_load_state_ == LOAD_STATE_LOADING);
1173 UserMetricsRecordAction("PDF.LoadFailure");
1175 if (did_call_start_loading_) {
1176 pp::PDF::DidStopLoading(this);
1177 did_call_start_loading_ = false;
1180 document_load_state_ = LOAD_STATE_FAILED;
1181 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
1183 // Send a progress value of -1 to indicate a failure.
1184 pp::VarDictionary message;
1185 message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1186 message.Set(pp::Var(kJSProgressPercentage), pp::Var(-1)) ;
1187 PostMessage(message);
1190 void OutOfProcessInstance::PreviewDocumentLoadFailed() {
1191 UserMetricsRecordAction("PDF.PreviewDocumentLoadFailure");
1192 if (preview_document_load_state_ != LOAD_STATE_LOADING ||
1193 preview_pages_info_.empty()) {
1194 return;
1197 preview_document_load_state_ = LOAD_STATE_FAILED;
1198 preview_pages_info_.pop();
1200 if (preview_pages_info_.size())
1201 LoadAvailablePreviewPage();
1204 pp::Instance* OutOfProcessInstance::GetPluginInstance() {
1205 return this;
1208 void OutOfProcessInstance::DocumentHasUnsupportedFeature(
1209 const std::string& feature) {
1210 std::string metric("PDF_Unsupported_");
1211 metric += feature;
1212 if (!unsupported_features_reported_.count(metric)) {
1213 unsupported_features_reported_.insert(metric);
1214 UserMetricsRecordAction(metric);
1217 // Since we use an info bar, only do this for full frame plugins..
1218 if (!full_)
1219 return;
1221 if (told_browser_about_unsupported_feature_)
1222 return;
1223 told_browser_about_unsupported_feature_ = true;
1225 pp::PDF::HasUnsupportedFeature(this);
1228 void OutOfProcessInstance::DocumentLoadProgress(uint32 available,
1229 uint32 doc_size) {
1230 double progress = 0.0;
1231 if (doc_size == 0) {
1232 // Document size is unknown. Use heuristics.
1233 // We'll make progress logarithmic from 0 to 100M.
1234 static const double kFactor = log(100000000.0) / 100.0;
1235 if (available > 0) {
1236 progress = log(static_cast<double>(available)) / kFactor;
1237 if (progress > 100.0)
1238 progress = 100.0;
1240 } else {
1241 progress = 100.0 * static_cast<double>(available) / doc_size;
1244 // We send 100% load progress in DocumentLoadComplete.
1245 if (progress >= 100)
1246 return;
1248 // Avoid sending too many progress messages over PostMessage.
1249 if (progress > last_progress_sent_ + 1) {
1250 last_progress_sent_ = progress;
1251 pp::VarDictionary message;
1252 message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1253 message.Set(pp::Var(kJSProgressPercentage), pp::Var(progress)) ;
1254 PostMessage(message);
1258 void OutOfProcessInstance::FormTextFieldFocusChange(bool in_focus) {
1259 if (!text_input_.get())
1260 return;
1261 if (in_focus)
1262 text_input_->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_TEXT);
1263 else
1264 text_input_->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_NONE);
1267 void OutOfProcessInstance::ResetRecentlySentFindUpdate(int32_t /* unused */) {
1268 recently_sent_find_update_ = false;
1271 void OutOfProcessInstance::OnGeometryChanged(double old_zoom,
1272 float old_device_scale) {
1273 if (zoom_ != old_zoom || device_scale_ != old_device_scale)
1274 engine_->ZoomUpdated(zoom_ * device_scale_);
1276 available_area_ = pp::Rect(plugin_size_);
1277 int doc_width = GetDocumentPixelWidth();
1278 if (doc_width < available_area_.width()) {
1279 available_area_.Offset((available_area_.width() - doc_width) / 2, 0);
1280 available_area_.set_width(doc_width);
1282 int doc_height = GetDocumentPixelHeight();
1283 if (doc_height < available_area_.height()) {
1284 available_area_.set_height(doc_height);
1287 CalculateBackgroundParts();
1288 engine_->PageOffsetUpdated(available_area_.point());
1289 engine_->PluginSizeUpdated(available_area_.size());
1291 if (!document_size_.GetArea())
1292 return;
1293 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
1296 void OutOfProcessInstance::LoadUrl(const std::string& url) {
1297 LoadUrlInternal(url, &embed_loader_, &OutOfProcessInstance::DidOpen);
1300 void OutOfProcessInstance::LoadPreviewUrl(const std::string& url) {
1301 LoadUrlInternal(url, &embed_preview_loader_,
1302 &OutOfProcessInstance::DidOpenPreview);
1305 void OutOfProcessInstance::LoadUrlInternal(
1306 const std::string& url,
1307 pp::URLLoader* loader,
1308 void (OutOfProcessInstance::* method)(int32_t)) {
1309 pp::URLRequestInfo request(this);
1310 request.SetURL(url);
1311 request.SetMethod("GET");
1313 *loader = CreateURLLoaderInternal();
1314 pp::CompletionCallback callback = loader_factory_.NewCallback(method);
1315 int rv = loader->Open(request, callback);
1316 if (rv != PP_OK_COMPLETIONPENDING)
1317 callback.Run(rv);
1320 pp::URLLoader OutOfProcessInstance::CreateURLLoaderInternal() {
1321 pp::URLLoader loader(this);
1323 const PPB_URLLoaderTrusted* trusted_interface =
1324 reinterpret_cast<const PPB_URLLoaderTrusted*>(
1325 pp::Module::Get()->GetBrowserInterface(
1326 PPB_URLLOADERTRUSTED_INTERFACE));
1327 if (trusted_interface)
1328 trusted_interface->GrantUniversalAccess(loader.pp_resource());
1329 return loader;
1332 void OutOfProcessInstance::SetZoom(double scale) {
1333 double old_zoom = zoom_;
1334 zoom_ = scale;
1335 OnGeometryChanged(old_zoom, device_scale_);
1338 std::string OutOfProcessInstance::GetLocalizedString(PP_ResourceString id) {
1339 pp::Var rv(pp::PDF::GetLocalizedString(this, id));
1340 if (!rv.is_string())
1341 return std::string();
1343 return rv.AsString();
1346 void OutOfProcessInstance::AppendBlankPrintPreviewPages() {
1347 if (print_preview_page_count_ == 0)
1348 return;
1349 engine_->AppendBlankPages(print_preview_page_count_);
1350 if (preview_pages_info_.size() > 0)
1351 LoadAvailablePreviewPage();
1354 bool OutOfProcessInstance::IsPrintPreview() {
1355 return IsPrintPreviewUrl(url_);
1358 void OutOfProcessInstance::ProcessPreviewPageInfo(const std::string& url,
1359 int dst_page_index) {
1360 if (!IsPrintPreview())
1361 return;
1363 int src_page_index = ExtractPrintPreviewPageIndex(url);
1364 if (src_page_index < 1)
1365 return;
1367 preview_pages_info_.push(std::make_pair(url, dst_page_index));
1368 LoadAvailablePreviewPage();
1371 void OutOfProcessInstance::LoadAvailablePreviewPage() {
1372 if (preview_pages_info_.size() <= 0 ||
1373 document_load_state_ != LOAD_STATE_COMPLETE) {
1374 return;
1377 std::string url = preview_pages_info_.front().first;
1378 int dst_page_index = preview_pages_info_.front().second;
1379 int src_page_index = ExtractPrintPreviewPageIndex(url);
1380 if (src_page_index < 1 ||
1381 dst_page_index >= print_preview_page_count_ ||
1382 preview_document_load_state_ == LOAD_STATE_LOADING) {
1383 return;
1386 preview_document_load_state_ = LOAD_STATE_LOADING;
1387 LoadPreviewUrl(url);
1390 void OutOfProcessInstance::UserMetricsRecordAction(
1391 const std::string& action) {
1392 // TODO(raymes): Move this function to PPB_UMA_Private.
1393 pp::PDF::UserMetricsRecordAction(this, pp::Var(action));
1396 pp::FloatPoint OutOfProcessInstance::BoundScrollOffsetToDocument(
1397 const pp::FloatPoint& scroll_offset) {
1398 float max_x = document_size_.width() * zoom_ - plugin_dip_size_.width();
1399 float x = std::max(std::min(scroll_offset.x(), max_x), 0.0f);
1400 float max_y = document_size_.height() * zoom_ - plugin_dip_size_.height();
1401 float y = std::max(std::min(scroll_offset.y(), max_y), 0.0f);
1402 return pp::FloatPoint(x, y);
1405 } // namespace chrome_pdf