Fix telemetry_unittests and telemetry_perf_unittests so they are 2 steps.
[chromium-blink-merge.git] / pdf / out_of_process_instance.cc
blob48549611e83f6852207e884ce26db70c42b2360d
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 natives.compressed_size = natives.raw_size;
291 snapshot.compressed_size = snapshot.raw_size;
292 v8::V8::SetNativesDataBlob(&natives);
293 v8::V8::SetSnapshotDataBlob(&snapshot);
296 // Check if the PDF is being loaded in the PDF chrome extension. We only allow
297 // the plugin to be put into "full frame" mode when it is being loaded in the
298 // extension because this enables some features that we don't want pages
299 // abusing outside of the extension.
300 pp::Var document_url_var = pp::URLUtil_Dev::Get()->GetDocumentURL(this);
301 std::string document_url = document_url_var.is_string() ?
302 document_url_var.AsString() : std::string();
303 std::string extension_url = std::string(kChromeExtension);
304 bool in_extension =
305 !document_url.compare(0, extension_url.size(), extension_url);
307 if (in_extension) {
308 // Check if the plugin is full frame. This is passed in from JS.
309 for (uint32_t i = 0; i < argc; ++i) {
310 if (strcmp(argn[i], "full-frame") == 0) {
311 full_ = true;
312 break;
317 // Only allow the plugin to handle find requests if it is full frame.
318 if (full_)
319 SetPluginToHandleFindRequests();
321 // Send translated strings to the extension where they will be displayed.
322 // TODO(raymes): It would be better to get these in the extension directly
323 // through an API but no such API currently exists.
324 pp::VarDictionary translated_strings;
325 translated_strings.Set(kType, kJSSetTranslatedStringsType);
326 translated_strings.Set(kJSGetPasswordString,
327 GetLocalizedString(PP_RESOURCESTRING_PDFGETPASSWORD));
328 translated_strings.Set(kJSLoadingString,
329 GetLocalizedString(PP_RESOURCESTRING_PDFLOADING));
330 translated_strings.Set(kJSLoadFailedString,
331 GetLocalizedString(PP_RESOURCESTRING_PDFLOAD_FAILED));
332 PostMessage(translated_strings);
334 text_input_.reset(new pp::TextInput_Dev(this));
336 const char* stream_url = NULL;
337 const char* original_url = NULL;
338 const char* headers = NULL;
339 for (uint32_t i = 0; i < argc; ++i) {
340 if (strcmp(argn[i], "src") == 0)
341 original_url = argv[i];
342 else if (strcmp(argn[i], "stream-url") == 0)
343 stream_url = argv[i];
344 else if (strcmp(argn[i], "headers") == 0)
345 headers = argv[i];
348 // TODO(raymes): This is a hack to ensure that if no headers are passed in
349 // then we get the right MIME type. When the in process plugin is removed we
350 // can fix the document loader properly and remove this hack.
351 if (!headers || strcmp(headers, "") == 0)
352 headers = "content-type: application/pdf";
354 if (!original_url)
355 return false;
357 if (!stream_url)
358 stream_url = original_url;
360 // If we're in print preview mode we don't need to load the document yet.
361 // A |kJSResetPrintPreviewModeType| message will be sent to the plugin letting
362 // it know the url to load. By not loading here we avoid loading the same
363 // document twice.
364 if (IsPrintPreviewUrl(original_url))
365 return true;
367 LoadUrl(stream_url);
368 url_ = original_url;
369 return engine_->New(original_url, headers);
372 void OutOfProcessInstance::HandleMessage(const pp::Var& message) {
373 pp::VarDictionary dict(message);
374 if (!dict.Get(kType).is_string()) {
375 NOTREACHED();
376 return;
379 std::string type = dict.Get(kType).AsString();
381 if (type == kJSViewportType &&
382 dict.Get(pp::Var(kJSXOffset)).is_number() &&
383 dict.Get(pp::Var(kJSYOffset)).is_number() &&
384 dict.Get(pp::Var(kJSZoom)).is_number()) {
385 received_viewport_message_ = true;
386 stop_scrolling_ = false;
387 double zoom = dict.Get(pp::Var(kJSZoom)).AsDouble();
388 pp::FloatPoint scroll_offset(dict.Get(pp::Var(kJSXOffset)).AsDouble(),
389 dict.Get(pp::Var(kJSYOffset)).AsDouble());
391 // Bound the input parameters.
392 zoom = std::max(kMinZoom, zoom);
393 SetZoom(zoom);
394 scroll_offset = BoundScrollOffsetToDocument(scroll_offset);
395 engine_->ScrolledToXPosition(scroll_offset.x() * device_scale_);
396 engine_->ScrolledToYPosition(scroll_offset.y() * device_scale_);
397 } else if (type == kJSGetPasswordCompleteType &&
398 dict.Get(pp::Var(kJSPassword)).is_string()) {
399 if (password_callback_) {
400 pp::CompletionCallbackWithOutput<pp::Var> callback = *password_callback_;
401 password_callback_.reset();
402 *callback.output() = dict.Get(pp::Var(kJSPassword)).pp_var();
403 callback.Run(PP_OK);
404 } else {
405 NOTREACHED();
407 } else if (type == kJSPrintType) {
408 Print();
409 } else if (type == kJSSaveType) {
410 pp::PDF::SaveAs(this);
411 } else if (type == kJSRotateClockwiseType) {
412 RotateClockwise();
413 } else if (type == kJSRotateCounterclockwiseType) {
414 RotateCounterclockwise();
415 } else if (type == kJSSelectAllType) {
416 engine_->SelectAll();
417 } else if (type == kJSResetPrintPreviewModeType &&
418 dict.Get(pp::Var(kJSPrintPreviewUrl)).is_string() &&
419 dict.Get(pp::Var(kJSPrintPreviewGrayscale)).is_bool() &&
420 dict.Get(pp::Var(kJSPrintPreviewPageCount)).is_int()) {
421 url_ = dict.Get(pp::Var(kJSPrintPreviewUrl)).AsString();
422 preview_pages_info_ = std::queue<PreviewPageInfo>();
423 preview_document_load_state_ = LOAD_STATE_COMPLETE;
424 document_load_state_ = LOAD_STATE_LOADING;
425 LoadUrl(url_);
426 preview_engine_.reset();
427 engine_.reset(PDFEngine::Create(this));
428 engine_->SetGrayscale(dict.Get(pp::Var(kJSPrintPreviewGrayscale)).AsBool());
429 engine_->New(url_.c_str());
431 print_preview_page_count_ =
432 std::max(dict.Get(pp::Var(kJSPrintPreviewPageCount)).AsInt(), 0);
434 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
435 } else if (type == kJSLoadPreviewPageType &&
436 dict.Get(pp::Var(kJSPreviewPageUrl)).is_string() &&
437 dict.Get(pp::Var(kJSPreviewPageIndex)).is_int()) {
438 ProcessPreviewPageInfo(dict.Get(pp::Var(kJSPreviewPageUrl)).AsString(),
439 dict.Get(pp::Var(kJSPreviewPageIndex)).AsInt());
440 } else if (type == kJSGetAccessibilityJSONType) {
441 pp::VarDictionary reply;
442 reply.Set(pp::Var(kType), pp::Var(kJSGetAccessibilityJSONReplyType));
443 if (dict.Get(pp::Var(kJSAccessibilityPageNumber)).is_int()) {
444 int page = dict.Get(pp::Var(kJSAccessibilityPageNumber)).AsInt();
445 reply.Set(pp::Var(kJSAccessibilityJSON),
446 pp::Var(engine_->GetPageAsJSON(page)));
447 } else {
448 base::DictionaryValue node;
449 node.SetInteger(kAccessibleNumberOfPages, engine_->GetNumberOfPages());
450 node.SetBoolean(kAccessibleLoaded,
451 document_load_state_ != LOAD_STATE_LOADING);
452 bool has_permissions =
453 engine_->HasPermission(PDFEngine::PERMISSION_COPY) ||
454 engine_->HasPermission(PDFEngine::PERMISSION_COPY_ACCESSIBLE);
455 node.SetBoolean(kAccessibleCopyable, has_permissions);
456 std::string json;
457 base::JSONWriter::Write(&node, &json);
458 reply.Set(pp::Var(kJSAccessibilityJSON), pp::Var(json));
460 PostMessage(reply);
461 } else if (type == kJSStopScrollingType) {
462 stop_scrolling_ = true;
463 } else {
464 NOTREACHED();
468 bool OutOfProcessInstance::HandleInputEvent(
469 const pp::InputEvent& event) {
470 // To simplify things, convert the event into device coordinates if it is
471 // a mouse event.
472 pp::InputEvent event_device_res(event);
474 pp::MouseInputEvent mouse_event(event);
475 if (!mouse_event.is_null()) {
476 pp::Point point = mouse_event.GetPosition();
477 pp::Point movement = mouse_event.GetMovement();
478 ScalePoint(device_scale_, &point);
479 ScalePoint(device_scale_, &movement);
480 mouse_event = pp::MouseInputEvent(
481 this,
482 event.GetType(),
483 event.GetTimeStamp(),
484 event.GetModifiers(),
485 mouse_event.GetButton(),
486 point,
487 mouse_event.GetClickCount(),
488 movement);
489 event_device_res = mouse_event;
493 pp::InputEvent offset_event(event_device_res);
494 switch (offset_event.GetType()) {
495 case PP_INPUTEVENT_TYPE_MOUSEDOWN:
496 case PP_INPUTEVENT_TYPE_MOUSEUP:
497 case PP_INPUTEVENT_TYPE_MOUSEMOVE:
498 case PP_INPUTEVENT_TYPE_MOUSEENTER:
499 case PP_INPUTEVENT_TYPE_MOUSELEAVE: {
500 pp::MouseInputEvent mouse_event(event_device_res);
501 pp::MouseInputEvent mouse_event_dip(event);
502 pp::Point point = mouse_event.GetPosition();
503 point.set_x(point.x() - available_area_.x());
504 offset_event = pp::MouseInputEvent(
505 this,
506 event.GetType(),
507 event.GetTimeStamp(),
508 event.GetModifiers(),
509 mouse_event.GetButton(),
510 point,
511 mouse_event.GetClickCount(),
512 mouse_event.GetMovement());
513 break;
515 default:
516 break;
518 if (engine_->HandleEvent(offset_event))
519 return true;
521 // TODO(raymes): Implement this scroll behavior in JS:
522 // When click+dragging, scroll the document correctly.
524 // Return true for unhandled clicks so the plugin takes focus.
525 return (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN);
528 void OutOfProcessInstance::DidChangeView(const pp::View& view) {
529 pp::Rect view_rect(view.GetRect());
530 float old_device_scale = device_scale_;
531 float device_scale = view.GetDeviceScale();
532 pp::Size view_device_size(view_rect.width() * device_scale,
533 view_rect.height() * device_scale);
535 if (view_device_size != plugin_size_ || device_scale != device_scale_) {
536 device_scale_ = device_scale;
537 plugin_dip_size_ = view_rect.size();
538 plugin_size_ = view_device_size;
540 paint_manager_.SetSize(view_device_size, device_scale_);
542 pp::Size new_image_data_size = PaintManager::GetNewContextSize(
543 image_data_.size(),
544 plugin_size_);
545 if (new_image_data_size != image_data_.size()) {
546 image_data_ = pp::ImageData(this,
547 PP_IMAGEDATAFORMAT_BGRA_PREMUL,
548 new_image_data_size,
549 false);
550 first_paint_ = true;
553 if (image_data_.is_null()) {
554 DCHECK(plugin_size_.IsEmpty());
555 return;
558 OnGeometryChanged(zoom_, old_device_scale);
561 if (!stop_scrolling_) {
562 pp::Point scroll_offset(view.GetScrollOffset());
563 pp::FloatPoint scroll_offset_float(scroll_offset.x(),
564 scroll_offset.y());
565 scroll_offset_float = BoundScrollOffsetToDocument(scroll_offset_float);
566 engine_->ScrolledToXPosition(scroll_offset_float.x() * device_scale_);
567 engine_->ScrolledToYPosition(scroll_offset_float.y() * device_scale_);
571 void OutOfProcessInstance::GetPrintPresetOptionsFromDocument(
572 PP_PdfPrintPresetOptions_Dev* options) {
573 options->is_scaling_disabled = PP_FromBool(IsPrintScalingDisabled());
574 options->copies = engine_->GetCopiesToPrint();
577 pp::Var OutOfProcessInstance::GetLinkAtPosition(
578 const pp::Point& point) {
579 pp::Point offset_point(point);
580 ScalePoint(device_scale_, &offset_point);
581 offset_point.set_x(offset_point.x() - available_area_.x());
582 return engine_->GetLinkAtPosition(offset_point);
585 pp::Var OutOfProcessInstance::GetSelectedText(bool html) {
586 if (html || !engine_->HasPermission(PDFEngine::PERMISSION_COPY))
587 return pp::Var();
588 return engine_->GetSelectedText();
591 uint32_t OutOfProcessInstance::QuerySupportedPrintOutputFormats() {
592 return engine_->QuerySupportedPrintOutputFormats();
595 int32_t OutOfProcessInstance::PrintBegin(
596 const PP_PrintSettings_Dev& print_settings) {
597 // For us num_pages is always equal to the number of pages in the PDF
598 // document irrespective of the printable area.
599 int32_t ret = engine_->GetNumberOfPages();
600 if (!ret)
601 return 0;
603 uint32_t supported_formats = engine_->QuerySupportedPrintOutputFormats();
604 if ((print_settings.format & supported_formats) == 0)
605 return 0;
607 print_settings_.is_printing = true;
608 print_settings_.pepper_print_settings = print_settings;
609 engine_->PrintBegin();
610 return ret;
613 pp::Resource OutOfProcessInstance::PrintPages(
614 const PP_PrintPageNumberRange_Dev* page_ranges,
615 uint32_t page_range_count) {
616 if (!print_settings_.is_printing)
617 return pp::Resource();
619 print_settings_.print_pages_called_ = true;
620 return engine_->PrintPages(page_ranges, page_range_count,
621 print_settings_.pepper_print_settings);
624 void OutOfProcessInstance::PrintEnd() {
625 if (print_settings_.print_pages_called_)
626 UserMetricsRecordAction("PDF.PrintPage");
627 print_settings_.Clear();
628 engine_->PrintEnd();
631 bool OutOfProcessInstance::IsPrintScalingDisabled() {
632 return !engine_->GetPrintScaling();
635 bool OutOfProcessInstance::StartFind(const std::string& text,
636 bool case_sensitive) {
637 engine_->StartFind(text.c_str(), case_sensitive);
638 return true;
641 void OutOfProcessInstance::SelectFindResult(bool forward) {
642 engine_->SelectFindResult(forward);
645 void OutOfProcessInstance::StopFind() {
646 engine_->StopFind();
647 tickmarks_.clear();
648 SetTickmarks(tickmarks_);
651 void OutOfProcessInstance::OnPaint(
652 const std::vector<pp::Rect>& paint_rects,
653 std::vector<PaintManager::ReadyRect>* ready,
654 std::vector<pp::Rect>* pending) {
655 if (image_data_.is_null()) {
656 DCHECK(plugin_size_.IsEmpty());
657 return;
659 if (first_paint_) {
660 first_paint_ = false;
661 pp::Rect rect = pp::Rect(pp::Point(), image_data_.size());
662 FillRect(rect, kBackgroundColor);
663 ready->push_back(PaintManager::ReadyRect(rect, image_data_, true));
666 if (!received_viewport_message_)
667 return;
669 engine_->PrePaint();
671 for (size_t i = 0; i < paint_rects.size(); i++) {
672 // Intersect with plugin area since there could be pending invalidates from
673 // when the plugin area was larger.
674 pp::Rect rect =
675 paint_rects[i].Intersect(pp::Rect(pp::Point(), plugin_size_));
676 if (rect.IsEmpty())
677 continue;
679 pp::Rect pdf_rect = available_area_.Intersect(rect);
680 if (!pdf_rect.IsEmpty()) {
681 pdf_rect.Offset(available_area_.x() * -1, 0);
683 std::vector<pp::Rect> pdf_ready;
684 std::vector<pp::Rect> pdf_pending;
685 engine_->Paint(pdf_rect, &image_data_, &pdf_ready, &pdf_pending);
686 for (size_t j = 0; j < pdf_ready.size(); ++j) {
687 pdf_ready[j].Offset(available_area_.point());
688 ready->push_back(
689 PaintManager::ReadyRect(pdf_ready[j], image_data_, false));
691 for (size_t j = 0; j < pdf_pending.size(); ++j) {
692 pdf_pending[j].Offset(available_area_.point());
693 pending->push_back(pdf_pending[j]);
697 for (size_t j = 0; j < background_parts_.size(); ++j) {
698 pp::Rect intersection = background_parts_[j].location.Intersect(rect);
699 if (!intersection.IsEmpty()) {
700 FillRect(intersection, background_parts_[j].color);
701 ready->push_back(
702 PaintManager::ReadyRect(intersection, image_data_, false));
707 engine_->PostPaint();
710 void OutOfProcessInstance::DidOpen(int32_t result) {
711 if (result == PP_OK) {
712 if (!engine_->HandleDocumentLoad(embed_loader_)) {
713 document_load_state_ = LOAD_STATE_LOADING;
714 DocumentLoadFailed();
716 } else if (result != PP_ERROR_ABORTED) { // Can happen in tests.
717 NOTREACHED();
718 DocumentLoadFailed();
721 // If it's a progressive load, cancel the stream URL request so that requests
722 // can be made on the original URL.
723 // TODO(raymes): Make this clearer once the in-process plugin is deleted.
724 if (engine_->IsProgressiveLoad()) {
725 pp::VarDictionary message;
726 message.Set(kType, kJSCancelStreamUrlType);
727 PostMessage(message);
731 void OutOfProcessInstance::DidOpenPreview(int32_t result) {
732 if (result == PP_OK) {
733 preview_engine_.reset(PDFEngine::Create(new PreviewModeClient(this)));
734 preview_engine_->HandleDocumentLoad(embed_preview_loader_);
735 } else {
736 NOTREACHED();
740 void OutOfProcessInstance::OnClientTimerFired(int32_t id) {
741 engine_->OnCallback(id);
744 void OutOfProcessInstance::CalculateBackgroundParts() {
745 background_parts_.clear();
746 int left_width = available_area_.x();
747 int right_start = available_area_.right();
748 int right_width = abs(plugin_size_.width() - available_area_.right());
749 int bottom = std::min(available_area_.bottom(), plugin_size_.height());
751 // Add the left, right, and bottom rectangles. Note: we assume only
752 // horizontal centering.
753 BackgroundPart part = {
754 pp::Rect(0, 0, left_width, bottom),
755 kBackgroundColor
757 if (!part.location.IsEmpty())
758 background_parts_.push_back(part);
759 part.location = pp::Rect(right_start, 0, right_width, bottom);
760 if (!part.location.IsEmpty())
761 background_parts_.push_back(part);
762 part.location = pp::Rect(
763 0, bottom, plugin_size_.width(), plugin_size_.height() - bottom);
764 if (!part.location.IsEmpty())
765 background_parts_.push_back(part);
768 int OutOfProcessInstance::GetDocumentPixelWidth() const {
769 return static_cast<int>(ceil(document_size_.width() * zoom_ * device_scale_));
772 int OutOfProcessInstance::GetDocumentPixelHeight() const {
773 return static_cast<int>(
774 ceil(document_size_.height() * zoom_ * device_scale_));
777 void OutOfProcessInstance::FillRect(const pp::Rect& rect, uint32 color) {
778 DCHECK(!image_data_.is_null() || rect.IsEmpty());
779 uint32* buffer_start = static_cast<uint32*>(image_data_.data());
780 int stride = image_data_.stride();
781 uint32* ptr = buffer_start + rect.y() * stride / 4 + rect.x();
782 int height = rect.height();
783 int width = rect.width();
784 for (int y = 0; y < height; ++y) {
785 for (int x = 0; x < width; ++x)
786 *(ptr + x) = color;
787 ptr += stride /4;
791 void OutOfProcessInstance::DocumentSizeUpdated(const pp::Size& size) {
792 document_size_ = size;
794 pp::VarDictionary dimensions;
795 dimensions.Set(kType, kJSDocumentDimensionsType);
796 dimensions.Set(kJSDocumentWidth, pp::Var(document_size_.width()));
797 dimensions.Set(kJSDocumentHeight, pp::Var(document_size_.height()));
798 pp::VarArray page_dimensions_array;
799 int num_pages = engine_->GetNumberOfPages();
800 for (int i = 0; i < num_pages; ++i) {
801 pp::Rect page_rect = engine_->GetPageRect(i);
802 pp::VarDictionary page_dimensions;
803 page_dimensions.Set(kJSPageX, pp::Var(page_rect.x()));
804 page_dimensions.Set(kJSPageY, pp::Var(page_rect.y()));
805 page_dimensions.Set(kJSPageWidth, pp::Var(page_rect.width()));
806 page_dimensions.Set(kJSPageHeight, pp::Var(page_rect.height()));
807 page_dimensions_array.Set(i, page_dimensions);
809 dimensions.Set(kJSPageDimensions, page_dimensions_array);
810 PostMessage(dimensions);
812 OnGeometryChanged(zoom_, device_scale_);
815 void OutOfProcessInstance::Invalidate(const pp::Rect& rect) {
816 pp::Rect offset_rect(rect);
817 offset_rect.Offset(available_area_.point());
818 paint_manager_.InvalidateRect(offset_rect);
821 void OutOfProcessInstance::Scroll(const pp::Point& point) {
822 if (!image_data_.is_null())
823 paint_manager_.ScrollRect(available_area_, point);
826 void OutOfProcessInstance::ScrollToX(int x) {
827 pp::VarDictionary position;
828 position.Set(kType, kJSSetScrollPositionType);
829 position.Set(kJSPositionX, pp::Var(x / device_scale_));
830 PostMessage(position);
833 void OutOfProcessInstance::ScrollToY(int y) {
834 pp::VarDictionary position;
835 position.Set(kType, kJSSetScrollPositionType);
836 position.Set(kJSPositionY, pp::Var(y / device_scale_));
837 PostMessage(position);
840 void OutOfProcessInstance::ScrollToPage(int page) {
841 if (engine_->GetNumberOfPages() == 0)
842 return;
844 pp::VarDictionary message;
845 message.Set(kType, kJSGoToPageType);
846 message.Set(kJSPageNumber, pp::Var(page));
847 PostMessage(message);
850 void OutOfProcessInstance::NavigateTo(const std::string& url,
851 bool open_in_new_tab) {
852 std::string url_copy(url);
854 // Empty |url_copy| is ok, and will effectively be a reload.
855 // Skip the code below so an empty URL does not turn into "http://", which
856 // will cause GURL to fail a DCHECK.
857 if (!url_copy.empty()) {
858 // If |url_copy| starts with '#', then it's for the same URL with a
859 // different URL fragment.
860 if (url_copy[0] == '#') {
861 url_copy = url_ + url_copy;
863 // If there's no scheme, add http.
864 if (url_copy.find("://") == std::string::npos &&
865 url_copy.find("mailto:") == std::string::npos) {
866 url_copy = std::string("http://") + url_copy;
868 // Make sure |url_copy| starts with a valid scheme.
869 if (url_copy.find("http://") != 0 &&
870 url_copy.find("https://") != 0 &&
871 url_copy.find("ftp://") != 0 &&
872 url_copy.find("file://") != 0 &&
873 url_copy.find("mailto:") != 0) {
874 return;
876 // Make sure |url_copy| is not only a scheme.
877 if (url_copy == "http://" ||
878 url_copy == "https://" ||
879 url_copy == "ftp://" ||
880 url_copy == "file://" ||
881 url_copy == "mailto:") {
882 return;
885 pp::VarDictionary message;
886 message.Set(kType, kJSNavigateType);
887 message.Set(kJSNavigateUrl, url_copy);
888 message.Set(kJSNavigateNewTab, open_in_new_tab);
889 PostMessage(message);
892 void OutOfProcessInstance::UpdateCursor(PP_CursorType_Dev cursor) {
893 if (cursor == cursor_)
894 return;
895 cursor_ = cursor;
897 const PPB_CursorControl_Dev* cursor_interface =
898 reinterpret_cast<const PPB_CursorControl_Dev*>(
899 pp::Module::Get()->GetBrowserInterface(PPB_CURSOR_CONTROL_DEV_INTERFACE));
900 if (!cursor_interface) {
901 NOTREACHED();
902 return;
905 cursor_interface->SetCursor(
906 pp_instance(), cursor_, pp::ImageData().pp_resource(), NULL);
909 void OutOfProcessInstance::UpdateTickMarks(
910 const std::vector<pp::Rect>& tickmarks) {
911 float inverse_scale = 1.0f / device_scale_;
912 std::vector<pp::Rect> scaled_tickmarks = tickmarks;
913 for (size_t i = 0; i < scaled_tickmarks.size(); i++)
914 ScaleRect(inverse_scale, &scaled_tickmarks[i]);
915 tickmarks_ = scaled_tickmarks;
918 void OutOfProcessInstance::NotifyNumberOfFindResultsChanged(int total,
919 bool final_result) {
920 // We don't want to spam the renderer with too many updates to the number of
921 // find results. Don't send an update if we sent one too recently. If it's the
922 // final update, we always send it though.
923 if (final_result) {
924 NumberOfFindResultsChanged(total, final_result);
925 SetTickmarks(tickmarks_);
926 return;
929 if (recently_sent_find_update_)
930 return;
932 NumberOfFindResultsChanged(total, final_result);
933 SetTickmarks(tickmarks_);
934 recently_sent_find_update_ = true;
935 pp::CompletionCallback callback =
936 timer_factory_.NewCallback(
937 &OutOfProcessInstance::ResetRecentlySentFindUpdate);
938 pp::Module::Get()->core()->CallOnMainThread(kFindResultCooldownMs,
939 callback, 0);
942 void OutOfProcessInstance::NotifySelectedFindResultChanged(
943 int current_find_index) {
944 DCHECK_GE(current_find_index, 0);
945 SelectedFindResultChanged(current_find_index);
948 void OutOfProcessInstance::GetDocumentPassword(
949 pp::CompletionCallbackWithOutput<pp::Var> callback) {
950 if (password_callback_) {
951 NOTREACHED();
952 return;
955 password_callback_.reset(
956 new pp::CompletionCallbackWithOutput<pp::Var>(callback));
957 pp::VarDictionary message;
958 message.Set(pp::Var(kType), pp::Var(kJSGetPasswordType));
959 PostMessage(message);
962 void OutOfProcessInstance::Alert(const std::string& message) {
963 ModalDialog(this, "alert", message, std::string());
966 bool OutOfProcessInstance::Confirm(const std::string& message) {
967 pp::Var result = ModalDialog(this, "confirm", message, std::string());
968 return result.is_bool() ? result.AsBool() : false;
971 std::string OutOfProcessInstance::Prompt(const std::string& question,
972 const std::string& default_answer) {
973 pp::Var result = ModalDialog(this, "prompt", question, default_answer);
974 return result.is_string() ? result.AsString() : std::string();
977 std::string OutOfProcessInstance::GetURL() {
978 return url_;
981 void OutOfProcessInstance::Email(const std::string& to,
982 const std::string& cc,
983 const std::string& bcc,
984 const std::string& subject,
985 const std::string& body) {
986 pp::VarDictionary message;
987 message.Set(pp::Var(kType), pp::Var(kJSEmailType));
988 message.Set(pp::Var(kJSEmailTo),
989 pp::Var(net::EscapeUrlEncodedData(to, false)));
990 message.Set(pp::Var(kJSEmailCc),
991 pp::Var(net::EscapeUrlEncodedData(cc, false)));
992 message.Set(pp::Var(kJSEmailBcc),
993 pp::Var(net::EscapeUrlEncodedData(bcc, false)));
994 message.Set(pp::Var(kJSEmailSubject),
995 pp::Var(net::EscapeUrlEncodedData(subject, false)));
996 message.Set(pp::Var(kJSEmailBody),
997 pp::Var(net::EscapeUrlEncodedData(body, false)));
998 PostMessage(message);
1001 void OutOfProcessInstance::Print() {
1002 if (!printing_enabled_ ||
1003 (!engine_->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY) &&
1004 !engine_->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY))) {
1005 return;
1008 pp::CompletionCallback callback =
1009 print_callback_factory_.NewCallback(&OutOfProcessInstance::OnPrint);
1010 pp::Module::Get()->core()->CallOnMainThread(0, callback);
1013 void OutOfProcessInstance::OnPrint(int32_t) {
1014 pp::PDF::Print(this);
1017 void OutOfProcessInstance::SubmitForm(const std::string& url,
1018 const void* data,
1019 int length) {
1020 pp::URLRequestInfo request(this);
1021 request.SetURL(url);
1022 request.SetMethod("POST");
1023 request.AppendDataToBody(reinterpret_cast<const char*>(data), length);
1025 pp::CompletionCallback callback =
1026 form_factory_.NewCallback(&OutOfProcessInstance::FormDidOpen);
1027 form_loader_ = CreateURLLoaderInternal();
1028 int rv = form_loader_.Open(request, callback);
1029 if (rv != PP_OK_COMPLETIONPENDING)
1030 callback.Run(rv);
1033 void OutOfProcessInstance::FormDidOpen(int32_t result) {
1034 // TODO: inform the user of success/failure.
1035 if (result != PP_OK) {
1036 NOTREACHED();
1040 std::string OutOfProcessInstance::ShowFileSelectionDialog() {
1041 // Seems like very low priority to implement, since the pdf has no way to get
1042 // the file data anyways. Javascript doesn't let you do this synchronously.
1043 NOTREACHED();
1044 return std::string();
1047 pp::URLLoader OutOfProcessInstance::CreateURLLoader() {
1048 if (full_) {
1049 if (!did_call_start_loading_) {
1050 did_call_start_loading_ = true;
1051 pp::PDF::DidStartLoading(this);
1054 // Disable save and print until the document is fully loaded, since they
1055 // would generate an incomplete document. Need to do this each time we
1056 // call DidStartLoading since that resets the content restrictions.
1057 pp::PDF::SetContentRestriction(this, CONTENT_RESTRICTION_SAVE |
1058 CONTENT_RESTRICTION_PRINT);
1061 return CreateURLLoaderInternal();
1064 void OutOfProcessInstance::ScheduleCallback(int id, int delay_in_ms) {
1065 pp::CompletionCallback callback =
1066 timer_factory_.NewCallback(&OutOfProcessInstance::OnClientTimerFired);
1067 pp::Module::Get()->core()->CallOnMainThread(delay_in_ms, callback, id);
1070 void OutOfProcessInstance::SearchString(const base::char16* string,
1071 const base::char16* term,
1072 bool case_sensitive,
1073 std::vector<SearchStringResult>* results) {
1074 PP_PrivateFindResult* pp_results;
1075 int count = 0;
1076 pp::PDF::SearchString(
1077 this,
1078 reinterpret_cast<const unsigned short*>(string),
1079 reinterpret_cast<const unsigned short*>(term),
1080 case_sensitive,
1081 &pp_results,
1082 &count);
1084 results->resize(count);
1085 for (int i = 0; i < count; ++i) {
1086 (*results)[i].start_index = pp_results[i].start_index;
1087 (*results)[i].length = pp_results[i].length;
1090 pp::Memory_Dev memory;
1091 memory.MemFree(pp_results);
1094 void OutOfProcessInstance::DocumentPaintOccurred() {
1097 void OutOfProcessInstance::DocumentLoadComplete(int page_count) {
1098 // Clear focus state for OSK.
1099 FormTextFieldFocusChange(false);
1101 DCHECK(document_load_state_ == LOAD_STATE_LOADING);
1102 document_load_state_ = LOAD_STATE_COMPLETE;
1103 UserMetricsRecordAction("PDF.LoadSuccess");
1105 // Note: If we are in print preview mode the scroll location is retained
1106 // across document loads so we don't want to scroll again and override it.
1107 if (IsPrintPreview()) {
1108 AppendBlankPrintPreviewPages();
1109 OnGeometryChanged(0, 0);
1112 pp::VarDictionary message;
1113 message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1114 message.Set(pp::Var(kJSProgressPercentage), pp::Var(100)) ;
1115 PostMessage(message);
1117 if (!full_)
1118 return;
1120 if (did_call_start_loading_) {
1121 pp::PDF::DidStopLoading(this);
1122 did_call_start_loading_ = false;
1125 int content_restrictions =
1126 CONTENT_RESTRICTION_CUT | CONTENT_RESTRICTION_PASTE;
1127 if (!engine_->HasPermission(PDFEngine::PERMISSION_COPY))
1128 content_restrictions |= CONTENT_RESTRICTION_COPY;
1130 if (!engine_->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY) &&
1131 !engine_->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY)) {
1132 printing_enabled_ = false;
1135 pp::PDF::SetContentRestriction(this, content_restrictions);
1137 uma_.HistogramCustomCounts("PDF.PageCount", page_count,
1138 1, 1000000, 50);
1141 void OutOfProcessInstance::RotateClockwise() {
1142 engine_->RotateClockwise();
1145 void OutOfProcessInstance::RotateCounterclockwise() {
1146 engine_->RotateCounterclockwise();
1149 void OutOfProcessInstance::PreviewDocumentLoadComplete() {
1150 if (preview_document_load_state_ != LOAD_STATE_LOADING ||
1151 preview_pages_info_.empty()) {
1152 return;
1155 preview_document_load_state_ = LOAD_STATE_COMPLETE;
1157 int dest_page_index = preview_pages_info_.front().second;
1158 int src_page_index =
1159 ExtractPrintPreviewPageIndex(preview_pages_info_.front().first);
1160 if (src_page_index > 0 && dest_page_index > -1 && preview_engine_.get())
1161 engine_->AppendPage(preview_engine_.get(), dest_page_index);
1163 preview_pages_info_.pop();
1164 // |print_preview_page_count_| is not updated yet. Do not load any
1165 // other preview pages till we get this information.
1166 if (print_preview_page_count_ == 0)
1167 return;
1169 if (preview_pages_info_.size())
1170 LoadAvailablePreviewPage();
1173 void OutOfProcessInstance::DocumentLoadFailed() {
1174 DCHECK(document_load_state_ == LOAD_STATE_LOADING);
1175 UserMetricsRecordAction("PDF.LoadFailure");
1177 if (did_call_start_loading_) {
1178 pp::PDF::DidStopLoading(this);
1179 did_call_start_loading_ = false;
1182 document_load_state_ = LOAD_STATE_FAILED;
1183 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
1185 // Send a progress value of -1 to indicate a failure.
1186 pp::VarDictionary message;
1187 message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1188 message.Set(pp::Var(kJSProgressPercentage), pp::Var(-1)) ;
1189 PostMessage(message);
1192 void OutOfProcessInstance::PreviewDocumentLoadFailed() {
1193 UserMetricsRecordAction("PDF.PreviewDocumentLoadFailure");
1194 if (preview_document_load_state_ != LOAD_STATE_LOADING ||
1195 preview_pages_info_.empty()) {
1196 return;
1199 preview_document_load_state_ = LOAD_STATE_FAILED;
1200 preview_pages_info_.pop();
1202 if (preview_pages_info_.size())
1203 LoadAvailablePreviewPage();
1206 pp::Instance* OutOfProcessInstance::GetPluginInstance() {
1207 return this;
1210 void OutOfProcessInstance::DocumentHasUnsupportedFeature(
1211 const std::string& feature) {
1212 std::string metric("PDF_Unsupported_");
1213 metric += feature;
1214 if (!unsupported_features_reported_.count(metric)) {
1215 unsupported_features_reported_.insert(metric);
1216 UserMetricsRecordAction(metric);
1219 // Since we use an info bar, only do this for full frame plugins..
1220 if (!full_)
1221 return;
1223 if (told_browser_about_unsupported_feature_)
1224 return;
1225 told_browser_about_unsupported_feature_ = true;
1227 pp::PDF::HasUnsupportedFeature(this);
1230 void OutOfProcessInstance::DocumentLoadProgress(uint32 available,
1231 uint32 doc_size) {
1232 double progress = 0.0;
1233 if (doc_size == 0) {
1234 // Document size is unknown. Use heuristics.
1235 // We'll make progress logarithmic from 0 to 100M.
1236 static const double kFactor = log(100000000.0) / 100.0;
1237 if (available > 0) {
1238 progress = log(static_cast<double>(available)) / kFactor;
1239 if (progress > 100.0)
1240 progress = 100.0;
1242 } else {
1243 progress = 100.0 * static_cast<double>(available) / doc_size;
1246 // We send 100% load progress in DocumentLoadComplete.
1247 if (progress >= 100)
1248 return;
1250 // Avoid sending too many progress messages over PostMessage.
1251 if (progress > last_progress_sent_ + 1) {
1252 last_progress_sent_ = progress;
1253 pp::VarDictionary message;
1254 message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1255 message.Set(pp::Var(kJSProgressPercentage), pp::Var(progress)) ;
1256 PostMessage(message);
1260 void OutOfProcessInstance::FormTextFieldFocusChange(bool in_focus) {
1261 if (!text_input_.get())
1262 return;
1263 if (in_focus)
1264 text_input_->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_TEXT);
1265 else
1266 text_input_->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_NONE);
1269 void OutOfProcessInstance::ResetRecentlySentFindUpdate(int32_t /* unused */) {
1270 recently_sent_find_update_ = false;
1273 void OutOfProcessInstance::OnGeometryChanged(double old_zoom,
1274 float old_device_scale) {
1275 if (zoom_ != old_zoom || device_scale_ != old_device_scale)
1276 engine_->ZoomUpdated(zoom_ * device_scale_);
1278 available_area_ = pp::Rect(plugin_size_);
1279 int doc_width = GetDocumentPixelWidth();
1280 if (doc_width < available_area_.width()) {
1281 available_area_.Offset((available_area_.width() - doc_width) / 2, 0);
1282 available_area_.set_width(doc_width);
1284 int doc_height = GetDocumentPixelHeight();
1285 if (doc_height < available_area_.height()) {
1286 available_area_.set_height(doc_height);
1289 CalculateBackgroundParts();
1290 engine_->PageOffsetUpdated(available_area_.point());
1291 engine_->PluginSizeUpdated(available_area_.size());
1293 if (!document_size_.GetArea())
1294 return;
1295 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
1298 void OutOfProcessInstance::LoadUrl(const std::string& url) {
1299 LoadUrlInternal(url, &embed_loader_, &OutOfProcessInstance::DidOpen);
1302 void OutOfProcessInstance::LoadPreviewUrl(const std::string& url) {
1303 LoadUrlInternal(url, &embed_preview_loader_,
1304 &OutOfProcessInstance::DidOpenPreview);
1307 void OutOfProcessInstance::LoadUrlInternal(
1308 const std::string& url,
1309 pp::URLLoader* loader,
1310 void (OutOfProcessInstance::* method)(int32_t)) {
1311 pp::URLRequestInfo request(this);
1312 request.SetURL(url);
1313 request.SetMethod("GET");
1315 *loader = CreateURLLoaderInternal();
1316 pp::CompletionCallback callback = loader_factory_.NewCallback(method);
1317 int rv = loader->Open(request, callback);
1318 if (rv != PP_OK_COMPLETIONPENDING)
1319 callback.Run(rv);
1322 pp::URLLoader OutOfProcessInstance::CreateURLLoaderInternal() {
1323 pp::URLLoader loader(this);
1325 const PPB_URLLoaderTrusted* trusted_interface =
1326 reinterpret_cast<const PPB_URLLoaderTrusted*>(
1327 pp::Module::Get()->GetBrowserInterface(
1328 PPB_URLLOADERTRUSTED_INTERFACE));
1329 if (trusted_interface)
1330 trusted_interface->GrantUniversalAccess(loader.pp_resource());
1331 return loader;
1334 void OutOfProcessInstance::SetZoom(double scale) {
1335 double old_zoom = zoom_;
1336 zoom_ = scale;
1337 OnGeometryChanged(old_zoom, device_scale_);
1340 std::string OutOfProcessInstance::GetLocalizedString(PP_ResourceString id) {
1341 pp::Var rv(pp::PDF::GetLocalizedString(this, id));
1342 if (!rv.is_string())
1343 return std::string();
1345 return rv.AsString();
1348 void OutOfProcessInstance::AppendBlankPrintPreviewPages() {
1349 if (print_preview_page_count_ == 0)
1350 return;
1351 engine_->AppendBlankPages(print_preview_page_count_);
1352 if (preview_pages_info_.size() > 0)
1353 LoadAvailablePreviewPage();
1356 bool OutOfProcessInstance::IsPrintPreview() {
1357 return IsPrintPreviewUrl(url_);
1360 void OutOfProcessInstance::ProcessPreviewPageInfo(const std::string& url,
1361 int dst_page_index) {
1362 if (!IsPrintPreview())
1363 return;
1365 int src_page_index = ExtractPrintPreviewPageIndex(url);
1366 if (src_page_index < 1)
1367 return;
1369 preview_pages_info_.push(std::make_pair(url, dst_page_index));
1370 LoadAvailablePreviewPage();
1373 void OutOfProcessInstance::LoadAvailablePreviewPage() {
1374 if (preview_pages_info_.size() <= 0 ||
1375 document_load_state_ != LOAD_STATE_COMPLETE) {
1376 return;
1379 std::string url = preview_pages_info_.front().first;
1380 int dst_page_index = preview_pages_info_.front().second;
1381 int src_page_index = ExtractPrintPreviewPageIndex(url);
1382 if (src_page_index < 1 ||
1383 dst_page_index >= print_preview_page_count_ ||
1384 preview_document_load_state_ == LOAD_STATE_LOADING) {
1385 return;
1388 preview_document_load_state_ = LOAD_STATE_LOADING;
1389 LoadPreviewUrl(url);
1392 void OutOfProcessInstance::UserMetricsRecordAction(
1393 const std::string& action) {
1394 // TODO(raymes): Move this function to PPB_UMA_Private.
1395 pp::PDF::UserMetricsRecordAction(this, pp::Var(action));
1398 pp::FloatPoint OutOfProcessInstance::BoundScrollOffsetToDocument(
1399 const pp::FloatPoint& scroll_offset) {
1400 float max_x = document_size_.width() * zoom_ - plugin_dip_size_.width();
1401 float x = std::max(std::min(scroll_offset.x(), max_x), 0.0f);
1402 float max_y = document_size_.height() * zoom_ - plugin_dip_size_.height();
1403 float y = std::max(std::min(scroll_offset.y(), max_y), 0.0f);
1404 return pp::FloatPoint(x, y);
1407 } // namespace chrome_pdf