Remove CHECK from createChildFrame
[chromium-blink-merge.git] / pdf / out_of_process_instance.cc
blob74544d90e2724c529408ae4f21d217e116c0e643
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "pdf/out_of_process_instance.h"
7 #include <algorithm> // for min/max()
8 #define _USE_MATH_DEFINES // for M_PI
9 #include <cmath> // for log() and pow()
10 #include <math.h>
11 #include <list>
13 #include "base/json/json_reader.h"
14 #include "base/json/json_writer.h"
15 #include "base/logging.h"
16 #include "base/strings/string_number_conversions.h"
17 #include "base/strings/string_split.h"
18 #include "base/strings/string_util.h"
19 #include "base/values.h"
20 #include "chrome/common/content_restriction.h"
21 #include "net/base/escape.h"
22 #include "pdf/pdf.h"
23 #include "ppapi/c/dev/ppb_cursor_control_dev.h"
24 #include "ppapi/c/pp_errors.h"
25 #include "ppapi/c/pp_rect.h"
26 #include "ppapi/c/private/ppb_instance_private.h"
27 #include "ppapi/c/private/ppp_pdf.h"
28 #include "ppapi/c/trusted/ppb_url_loader_trusted.h"
29 #include "ppapi/cpp/core.h"
30 #include "ppapi/cpp/dev/memory_dev.h"
31 #include "ppapi/cpp/dev/text_input_dev.h"
32 #include "ppapi/cpp/dev/url_util_dev.h"
33 #include "ppapi/cpp/module.h"
34 #include "ppapi/cpp/point.h"
35 #include "ppapi/cpp/private/pdf.h"
36 #include "ppapi/cpp/private/var_private.h"
37 #include "ppapi/cpp/rect.h"
38 #include "ppapi/cpp/resource.h"
39 #include "ppapi/cpp/url_request_info.h"
40 #include "ppapi/cpp/var_array.h"
41 #include "ppapi/cpp/var_dictionary.h"
42 #include "ui/events/keycodes/keyboard_codes.h"
44 namespace chrome_pdf {
46 const char kChromePrint[] = "chrome://print/";
47 const char kChromeExtension[] =
48 "chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai";
50 // Dictionary Value key names for the document accessibility info
51 const char kAccessibleNumberOfPages[] = "numberOfPages";
52 const char kAccessibleLoaded[] = "loaded";
53 const char kAccessibleCopyable[] = "copyable";
55 // PDF background colors.
56 const uint32 kBackgroundColor = 0xFFCCCCCC;
57 const uint32 kBackgroundColorMaterial = 0xFFEEEEEE;
59 // Constants used in handling postMessage() messages.
60 const char kType[] = "type";
61 // Viewport message arguments. (Page -> Plugin).
62 const char kJSViewportType[] = "viewport";
63 const char kJSXOffset[] = "xOffset";
64 const char kJSYOffset[] = "yOffset";
65 const char kJSZoom[] = "zoom";
66 // Stop scrolling message (Page -> Plugin)
67 const char kJSStopScrollingType[] = "stopScrolling";
68 // Document dimension arguments (Plugin -> Page).
69 const char kJSDocumentDimensionsType[] = "documentDimensions";
70 const char kJSDocumentWidth[] = "width";
71 const char kJSDocumentHeight[] = "height";
72 const char kJSPageDimensions[] = "pageDimensions";
73 const char kJSPageX[] = "x";
74 const char kJSPageY[] = "y";
75 const char kJSPageWidth[] = "width";
76 const char kJSPageHeight[] = "height";
77 // Document load progress arguments (Plugin -> Page)
78 const char kJSLoadProgressType[] = "loadProgress";
79 const char kJSProgressPercentage[] = "progress";
80 // Bookmarks
81 const char kJSBookmarksType[] = "bookmarks";
82 const char kJSBookmarks[] = "bookmarks";
83 // Get password arguments (Plugin -> Page)
84 const char kJSGetPasswordType[] = "getPassword";
85 // Get password complete arguments (Page -> Plugin)
86 const char kJSGetPasswordCompleteType[] = "getPasswordComplete";
87 const char kJSPassword[] = "password";
88 // Print (Page -> Plugin)
89 const char kJSPrintType[] = "print";
90 // Save (Page -> Plugin)
91 const char kJSSaveType[] = "save";
92 // Go to page (Plugin -> Page)
93 const char kJSGoToPageType[] = "goToPage";
94 const char kJSPageNumber[] = "page";
95 // Reset print preview mode (Page -> Plugin)
96 const char kJSResetPrintPreviewModeType[] = "resetPrintPreviewMode";
97 const char kJSPrintPreviewUrl[] = "url";
98 const char kJSPrintPreviewGrayscale[] = "grayscale";
99 const char kJSPrintPreviewPageCount[] = "pageCount";
100 // Load preview page (Page -> Plugin)
101 const char kJSLoadPreviewPageType[] = "loadPreviewPage";
102 const char kJSPreviewPageUrl[] = "url";
103 const char kJSPreviewPageIndex[] = "index";
104 // Set scroll position (Plugin -> Page)
105 const char kJSSetScrollPositionType[] = "setScrollPosition";
106 const char kJSPositionX[] = "x";
107 const char kJSPositionY[] = "y";
108 // Set translated strings (Plugin -> Page)
109 const char kJSSetTranslatedStringsType[] = "setTranslatedStrings";
110 const char kJSGetPasswordString[] = "getPasswordString";
111 const char kJSLoadingString[] = "loadingString";
112 const char kJSLoadFailedString[] = "loadFailedString";
113 // Request accessibility JSON data (Page -> Plugin)
114 const char kJSGetAccessibilityJSONType[] = "getAccessibilityJSON";
115 const char kJSAccessibilityPageNumber[] = "page";
116 // Reply with accessibility JSON data (Plugin -> Page)
117 const char kJSGetAccessibilityJSONReplyType[] = "getAccessibilityJSONReply";
118 const char kJSAccessibilityJSON[] = "json";
119 // Cancel the stream URL request (Plugin -> Page)
120 const char kJSCancelStreamUrlType[] = "cancelStreamUrl";
121 // Navigate to the given URL (Plugin -> Page)
122 const char kJSNavigateType[] = "navigate";
123 const char kJSNavigateUrl[] = "url";
124 const char kJSNavigateNewTab[] = "newTab";
125 // Open the email editor with the given parameters (Plugin -> Page)
126 const char kJSEmailType[] = "email";
127 const char kJSEmailTo[] = "to";
128 const char kJSEmailCc[] = "cc";
129 const char kJSEmailBcc[] = "bcc";
130 const char kJSEmailSubject[] = "subject";
131 const char kJSEmailBody[] = "body";
132 // Rotation (Page -> Plugin)
133 const char kJSRotateClockwiseType[] = "rotateClockwise";
134 const char kJSRotateCounterclockwiseType[] = "rotateCounterclockwise";
135 // Select all text in the document (Page -> Plugin)
136 const char kJSSelectAllType[] = "selectAll";
137 // Get the selected text in the document (Page -> Plugin)
138 const char kJSGetSelectedTextType[] = "getSelectedText";
139 // Reply with selected text (Plugin -> Page)
140 const char kJSGetSelectedTextReplyType[] = "getSelectedTextReply";
141 const char kJSSelectedText[] = "selectedText";
143 // List of named destinations (Plugin -> Page)
144 const char kJSSetNamedDestinationsType[] = "setNamedDestinations";
145 const char kJSNamedDestinations[] = "namedDestinations";
147 // Selecting text in document (Plugin -> Page)
148 const char kJSSetIsSelectingType[] = "setIsSelecting";
149 const char kJSIsSelecting[] = "isSelecting";
151 const int kFindResultCooldownMs = 100;
153 const double kMinZoom = 0.01;
155 namespace {
157 static const char kPPPPdfInterface[] = PPP_PDF_INTERFACE_1;
159 PP_Var GetLinkAtPosition(PP_Instance instance, PP_Point point) {
160 pp::Var var;
161 void* object = pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
162 if (object) {
163 var = static_cast<OutOfProcessInstance*>(object)->GetLinkAtPosition(
164 pp::Point(point));
166 return var.Detach();
169 void Transform(PP_Instance instance, PP_PrivatePageTransformType type) {
170 void* object =
171 pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
172 if (object) {
173 OutOfProcessInstance* obj_instance =
174 static_cast<OutOfProcessInstance*>(object);
175 switch (type) {
176 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CW:
177 obj_instance->RotateClockwise();
178 break;
179 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CCW:
180 obj_instance->RotateCounterclockwise();
181 break;
186 PP_Bool GetPrintPresetOptionsFromDocument(
187 PP_Instance instance,
188 PP_PdfPrintPresetOptions_Dev* options) {
189 void* object = pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
190 if (object) {
191 OutOfProcessInstance* obj_instance =
192 static_cast<OutOfProcessInstance*>(object);
193 obj_instance->GetPrintPresetOptionsFromDocument(options);
195 return PP_TRUE;
198 const PPP_Pdf ppp_private = {
199 &GetLinkAtPosition,
200 &Transform,
201 &GetPrintPresetOptionsFromDocument
204 int ExtractPrintPreviewPageIndex(const std::string& src_url) {
205 // Sample |src_url| format: chrome://print/id/page_index/print.pdf
206 std::vector<std::string> url_substr;
207 base::SplitString(src_url.substr(strlen(kChromePrint)), '/', &url_substr);
208 if (url_substr.size() != 3)
209 return -1;
211 if (url_substr[2] != "print.pdf")
212 return -1;
214 int page_index = 0;
215 if (!base::StringToInt(url_substr[1], &page_index))
216 return -1;
217 return page_index;
220 bool IsPrintPreviewUrl(const std::string& url) {
221 return url.substr(0, strlen(kChromePrint)) == kChromePrint;
224 void ScalePoint(float scale, pp::Point* point) {
225 point->set_x(static_cast<int>(point->x() * scale));
226 point->set_y(static_cast<int>(point->y() * scale));
229 void ScaleRect(float scale, pp::Rect* rect) {
230 int left = static_cast<int>(floorf(rect->x() * scale));
231 int top = static_cast<int>(floorf(rect->y() * scale));
232 int right = static_cast<int>(ceilf((rect->x() + rect->width()) * scale));
233 int bottom = static_cast<int>(ceilf((rect->y() + rect->height()) * scale));
234 rect->SetRect(left, top, right - left, bottom - top);
237 // TODO(raymes): Remove this dependency on VarPrivate/InstancePrivate. It's
238 // needed right now to do a synchronous call to JavaScript, but we could easily
239 // replace this with a custom PPB_PDF function.
240 pp::Var ModalDialog(const pp::Instance* instance,
241 const std::string& type,
242 const std::string& message,
243 const std::string& default_answer) {
244 const PPB_Instance_Private* interface =
245 reinterpret_cast<const PPB_Instance_Private*>(
246 pp::Module::Get()->GetBrowserInterface(
247 PPB_INSTANCE_PRIVATE_INTERFACE));
248 pp::VarPrivate window(pp::PASS_REF,
249 interface->GetWindowObject(instance->pp_instance()));
250 if (default_answer.empty())
251 return window.Call(type, message);
252 else
253 return window.Call(type, message, default_answer);
256 } // namespace
258 OutOfProcessInstance::OutOfProcessInstance(PP_Instance instance)
259 : pp::Instance(instance),
260 pp::Find_Private(this),
261 pp::Printing_Dev(this),
262 pp::Selection_Dev(this),
263 cursor_(PP_CURSORTYPE_POINTER),
264 zoom_(1.0),
265 device_scale_(1.0),
266 full_(false),
267 paint_manager_(this, this, true),
268 first_paint_(true),
269 document_load_state_(LOAD_STATE_LOADING),
270 preview_document_load_state_(LOAD_STATE_COMPLETE),
271 uma_(this),
272 told_browser_about_unsupported_feature_(false),
273 print_preview_page_count_(0),
274 last_progress_sent_(0),
275 recently_sent_find_update_(false),
276 received_viewport_message_(false),
277 did_call_start_loading_(false),
278 stop_scrolling_(false),
279 background_color_(kBackgroundColor) {
280 loader_factory_.Initialize(this);
281 timer_factory_.Initialize(this);
282 form_factory_.Initialize(this);
283 print_callback_factory_.Initialize(this);
284 engine_.reset(PDFEngine::Create(this));
285 pp::Module::Get()->AddPluginInterface(kPPPPdfInterface, &ppp_private);
286 AddPerInstanceObject(kPPPPdfInterface, this);
288 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_MOUSE);
289 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_KEYBOARD);
290 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_TOUCH);
293 OutOfProcessInstance::~OutOfProcessInstance() {
294 RemovePerInstanceObject(kPPPPdfInterface, this);
297 bool OutOfProcessInstance::Init(uint32_t argc,
298 const char* argn[],
299 const char* argv[]) {
300 // Check if the PDF is being loaded in the PDF chrome extension. We only allow
301 // the plugin to be put into "full frame" mode when it is being loaded in the
302 // extension because this enables some features that we don't want pages
303 // abusing outside of the extension.
304 pp::Var document_url_var = pp::URLUtil_Dev::Get()->GetDocumentURL(this);
305 std::string document_url = document_url_var.is_string() ?
306 document_url_var.AsString() : std::string();
307 std::string extension_url = std::string(kChromeExtension);
308 bool in_extension =
309 !document_url.compare(0, extension_url.size(), extension_url);
311 if (in_extension) {
312 // Check if the plugin is full frame. This is passed in from JS.
313 for (uint32_t i = 0; i < argc; ++i) {
314 if (strcmp(argn[i], "full-frame") == 0) {
315 full_ = true;
316 break;
321 // Only allow the plugin to handle find requests if it is full frame.
322 if (full_)
323 SetPluginToHandleFindRequests();
325 // Send translated strings to the extension where they will be displayed.
326 // TODO(raymes): It would be better to get these in the extension directly
327 // through an API but no such API currently exists.
328 pp::VarDictionary translated_strings;
329 translated_strings.Set(kType, kJSSetTranslatedStringsType);
330 translated_strings.Set(kJSGetPasswordString,
331 GetLocalizedString(PP_RESOURCESTRING_PDFGETPASSWORD));
332 translated_strings.Set(kJSLoadingString,
333 GetLocalizedString(PP_RESOURCESTRING_PDFLOADING));
334 translated_strings.Set(kJSLoadFailedString,
335 GetLocalizedString(PP_RESOURCESTRING_PDFLOAD_FAILED));
336 PostMessage(translated_strings);
338 text_input_.reset(new pp::TextInput_Dev(this));
340 const char* stream_url = NULL;
341 const char* original_url = NULL;
342 const char* headers = NULL;
343 bool is_material = false;
344 for (uint32_t i = 0; i < argc; ++i) {
345 if (strcmp(argn[i], "src") == 0)
346 original_url = argv[i];
347 else if (strcmp(argn[i], "stream-url") == 0)
348 stream_url = argv[i];
349 else if (strcmp(argn[i], "headers") == 0)
350 headers = argv[i];
351 else if (strcmp(argn[i], "is-material") == 0)
352 is_material = true;
355 if (is_material)
356 background_color_ = kBackgroundColorMaterial;
357 else
358 background_color_ = kBackgroundColor;
360 // TODO(raymes): This is a hack to ensure that if no headers are passed in
361 // then we get the right MIME type. When the in process plugin is removed we
362 // can fix the document loader properly and remove this hack.
363 if (!headers || strcmp(headers, "") == 0)
364 headers = "content-type: application/pdf";
366 if (!original_url)
367 return false;
369 if (!stream_url)
370 stream_url = original_url;
372 // If we're in print preview mode we don't need to load the document yet.
373 // A |kJSResetPrintPreviewModeType| message will be sent to the plugin letting
374 // it know the url to load. By not loading here we avoid loading the same
375 // document twice.
376 if (IsPrintPreviewUrl(original_url))
377 return true;
379 LoadUrl(stream_url);
380 url_ = original_url;
381 return engine_->New(original_url, headers);
384 void OutOfProcessInstance::HandleMessage(const pp::Var& message) {
385 pp::VarDictionary dict(message);
386 if (!dict.Get(kType).is_string()) {
387 NOTREACHED();
388 return;
391 std::string type = dict.Get(kType).AsString();
393 if (type == kJSViewportType &&
394 dict.Get(pp::Var(kJSXOffset)).is_number() &&
395 dict.Get(pp::Var(kJSYOffset)).is_number() &&
396 dict.Get(pp::Var(kJSZoom)).is_number()) {
397 received_viewport_message_ = true;
398 stop_scrolling_ = false;
399 double zoom = dict.Get(pp::Var(kJSZoom)).AsDouble();
400 pp::FloatPoint scroll_offset(dict.Get(pp::Var(kJSXOffset)).AsDouble(),
401 dict.Get(pp::Var(kJSYOffset)).AsDouble());
403 // Bound the input parameters.
404 zoom = std::max(kMinZoom, zoom);
405 SetZoom(zoom);
406 scroll_offset = BoundScrollOffsetToDocument(scroll_offset);
407 engine_->ScrolledToXPosition(scroll_offset.x() * device_scale_);
408 engine_->ScrolledToYPosition(scroll_offset.y() * device_scale_);
409 } else if (type == kJSGetPasswordCompleteType &&
410 dict.Get(pp::Var(kJSPassword)).is_string()) {
411 if (password_callback_) {
412 pp::CompletionCallbackWithOutput<pp::Var> callback = *password_callback_;
413 password_callback_.reset();
414 *callback.output() = dict.Get(pp::Var(kJSPassword)).pp_var();
415 callback.Run(PP_OK);
416 } else {
417 NOTREACHED();
419 } else if (type == kJSPrintType) {
420 Print();
421 } else if (type == kJSSaveType) {
422 pp::PDF::SaveAs(this);
423 } else if (type == kJSRotateClockwiseType) {
424 RotateClockwise();
425 } else if (type == kJSRotateCounterclockwiseType) {
426 RotateCounterclockwise();
427 } else if (type == kJSSelectAllType) {
428 engine_->SelectAll();
429 } else if (type == kJSResetPrintPreviewModeType &&
430 dict.Get(pp::Var(kJSPrintPreviewUrl)).is_string() &&
431 dict.Get(pp::Var(kJSPrintPreviewGrayscale)).is_bool() &&
432 dict.Get(pp::Var(kJSPrintPreviewPageCount)).is_int()) {
433 url_ = dict.Get(pp::Var(kJSPrintPreviewUrl)).AsString();
434 preview_pages_info_ = std::queue<PreviewPageInfo>();
435 preview_document_load_state_ = LOAD_STATE_COMPLETE;
436 document_load_state_ = LOAD_STATE_LOADING;
437 LoadUrl(url_);
438 preview_engine_.reset();
439 engine_.reset(PDFEngine::Create(this));
440 engine_->SetGrayscale(dict.Get(pp::Var(kJSPrintPreviewGrayscale)).AsBool());
441 engine_->New(url_.c_str());
443 print_preview_page_count_ =
444 std::max(dict.Get(pp::Var(kJSPrintPreviewPageCount)).AsInt(), 0);
446 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
447 } else if (type == kJSLoadPreviewPageType &&
448 dict.Get(pp::Var(kJSPreviewPageUrl)).is_string() &&
449 dict.Get(pp::Var(kJSPreviewPageIndex)).is_int()) {
450 ProcessPreviewPageInfo(dict.Get(pp::Var(kJSPreviewPageUrl)).AsString(),
451 dict.Get(pp::Var(kJSPreviewPageIndex)).AsInt());
452 } else if (type == kJSGetAccessibilityJSONType) {
453 pp::VarDictionary reply;
454 reply.Set(pp::Var(kType), pp::Var(kJSGetAccessibilityJSONReplyType));
455 if (dict.Get(pp::Var(kJSAccessibilityPageNumber)).is_int()) {
456 int page = dict.Get(pp::Var(kJSAccessibilityPageNumber)).AsInt();
457 reply.Set(pp::Var(kJSAccessibilityJSON),
458 pp::Var(engine_->GetPageAsJSON(page)));
459 } else {
460 base::DictionaryValue node;
461 node.SetInteger(kAccessibleNumberOfPages, engine_->GetNumberOfPages());
462 node.SetBoolean(kAccessibleLoaded,
463 document_load_state_ != LOAD_STATE_LOADING);
464 bool has_permissions =
465 engine_->HasPermission(PDFEngine::PERMISSION_COPY) ||
466 engine_->HasPermission(PDFEngine::PERMISSION_COPY_ACCESSIBLE);
467 node.SetBoolean(kAccessibleCopyable, has_permissions);
468 std::string json;
469 base::JSONWriter::Write(&node, &json);
470 reply.Set(pp::Var(kJSAccessibilityJSON), pp::Var(json));
472 PostMessage(reply);
473 } else if (type == kJSStopScrollingType) {
474 stop_scrolling_ = true;
475 } else if (type == kJSGetSelectedTextType) {
476 std::string selected_text = engine_->GetSelectedText();
477 // Always return unix newlines to JS.
478 base::ReplaceChars(selected_text, "\r", std::string(), &selected_text);
479 pp::VarDictionary reply;
480 reply.Set(pp::Var(kType), pp::Var(kJSGetSelectedTextReplyType));
481 reply.Set(pp::Var(kJSSelectedText), selected_text);
482 PostMessage(reply);
483 } else {
484 NOTREACHED();
488 bool OutOfProcessInstance::HandleInputEvent(
489 const pp::InputEvent& event) {
490 // To simplify things, convert the event into device coordinates if it is
491 // a mouse event.
492 pp::InputEvent event_device_res(event);
494 pp::MouseInputEvent mouse_event(event);
495 if (!mouse_event.is_null()) {
496 pp::Point point = mouse_event.GetPosition();
497 pp::Point movement = mouse_event.GetMovement();
498 ScalePoint(device_scale_, &point);
499 ScalePoint(device_scale_, &movement);
500 mouse_event = pp::MouseInputEvent(
501 this,
502 event.GetType(),
503 event.GetTimeStamp(),
504 event.GetModifiers(),
505 mouse_event.GetButton(),
506 point,
507 mouse_event.GetClickCount(),
508 movement);
509 event_device_res = mouse_event;
513 pp::InputEvent offset_event(event_device_res);
514 switch (offset_event.GetType()) {
515 case PP_INPUTEVENT_TYPE_MOUSEDOWN:
516 case PP_INPUTEVENT_TYPE_MOUSEUP:
517 case PP_INPUTEVENT_TYPE_MOUSEMOVE:
518 case PP_INPUTEVENT_TYPE_MOUSEENTER:
519 case PP_INPUTEVENT_TYPE_MOUSELEAVE: {
520 pp::MouseInputEvent mouse_event(event_device_res);
521 pp::MouseInputEvent mouse_event_dip(event);
522 pp::Point point = mouse_event.GetPosition();
523 point.set_x(point.x() - available_area_.x());
524 offset_event = pp::MouseInputEvent(
525 this,
526 event.GetType(),
527 event.GetTimeStamp(),
528 event.GetModifiers(),
529 mouse_event.GetButton(),
530 point,
531 mouse_event.GetClickCount(),
532 mouse_event.GetMovement());
533 break;
535 default:
536 break;
538 if (engine_->HandleEvent(offset_event))
539 return true;
541 // TODO(raymes): Implement this scroll behavior in JS:
542 // When click+dragging, scroll the document correctly.
544 // Return true for unhandled clicks so the plugin takes focus.
545 return (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN);
548 void OutOfProcessInstance::DidChangeView(const pp::View& view) {
549 pp::Rect view_rect(view.GetRect());
550 float old_device_scale = device_scale_;
551 float device_scale = view.GetDeviceScale();
552 pp::Size view_device_size(view_rect.width() * device_scale,
553 view_rect.height() * device_scale);
555 if (view_device_size != plugin_size_ || device_scale != device_scale_) {
556 device_scale_ = device_scale;
557 plugin_dip_size_ = view_rect.size();
558 plugin_size_ = view_device_size;
560 paint_manager_.SetSize(view_device_size, device_scale_);
562 pp::Size new_image_data_size = PaintManager::GetNewContextSize(
563 image_data_.size(),
564 plugin_size_);
565 if (new_image_data_size != image_data_.size()) {
566 image_data_ = pp::ImageData(this,
567 PP_IMAGEDATAFORMAT_BGRA_PREMUL,
568 new_image_data_size,
569 false);
570 first_paint_ = true;
573 if (image_data_.is_null()) {
574 DCHECK(plugin_size_.IsEmpty());
575 return;
578 OnGeometryChanged(zoom_, old_device_scale);
581 if (!stop_scrolling_) {
582 pp::Point scroll_offset(view.GetScrollOffset());
583 pp::FloatPoint scroll_offset_float(scroll_offset.x(),
584 scroll_offset.y());
585 scroll_offset_float = BoundScrollOffsetToDocument(scroll_offset_float);
586 engine_->ScrolledToXPosition(scroll_offset_float.x() * device_scale_);
587 engine_->ScrolledToYPosition(scroll_offset_float.y() * device_scale_);
591 void OutOfProcessInstance::GetPrintPresetOptionsFromDocument(
592 PP_PdfPrintPresetOptions_Dev* options) {
593 options->is_scaling_disabled = PP_FromBool(IsPrintScalingDisabled());
594 options->copies = engine_->GetCopiesToPrint();
597 pp::Var OutOfProcessInstance::GetLinkAtPosition(
598 const pp::Point& point) {
599 pp::Point offset_point(point);
600 ScalePoint(device_scale_, &offset_point);
601 offset_point.set_x(offset_point.x() - available_area_.x());
602 return engine_->GetLinkAtPosition(offset_point);
605 pp::Var OutOfProcessInstance::GetSelectedText(bool html) {
606 if (html)
607 return pp::Var();
608 return engine_->GetSelectedText();
611 uint32_t OutOfProcessInstance::QuerySupportedPrintOutputFormats() {
612 return engine_->QuerySupportedPrintOutputFormats();
615 int32_t OutOfProcessInstance::PrintBegin(
616 const PP_PrintSettings_Dev& print_settings) {
617 // For us num_pages is always equal to the number of pages in the PDF
618 // document irrespective of the printable area.
619 int32_t ret = engine_->GetNumberOfPages();
620 if (!ret)
621 return 0;
623 uint32_t supported_formats = engine_->QuerySupportedPrintOutputFormats();
624 if ((print_settings.format & supported_formats) == 0)
625 return 0;
627 print_settings_.is_printing = true;
628 print_settings_.pepper_print_settings = print_settings;
629 engine_->PrintBegin();
630 return ret;
633 pp::Resource OutOfProcessInstance::PrintPages(
634 const PP_PrintPageNumberRange_Dev* page_ranges,
635 uint32_t page_range_count) {
636 if (!print_settings_.is_printing)
637 return pp::Resource();
639 print_settings_.print_pages_called_ = true;
640 return engine_->PrintPages(page_ranges, page_range_count,
641 print_settings_.pepper_print_settings);
644 void OutOfProcessInstance::PrintEnd() {
645 if (print_settings_.print_pages_called_)
646 UserMetricsRecordAction("PDF.PrintPage");
647 print_settings_.Clear();
648 engine_->PrintEnd();
651 bool OutOfProcessInstance::IsPrintScalingDisabled() {
652 return !engine_->GetPrintScaling();
655 bool OutOfProcessInstance::StartFind(const std::string& text,
656 bool case_sensitive) {
657 engine_->StartFind(text.c_str(), case_sensitive);
658 return true;
661 void OutOfProcessInstance::SelectFindResult(bool forward) {
662 engine_->SelectFindResult(forward);
665 void OutOfProcessInstance::StopFind() {
666 engine_->StopFind();
667 tickmarks_.clear();
668 SetTickmarks(tickmarks_);
671 void OutOfProcessInstance::OnPaint(
672 const std::vector<pp::Rect>& paint_rects,
673 std::vector<PaintManager::ReadyRect>* ready,
674 std::vector<pp::Rect>* pending) {
675 if (image_data_.is_null()) {
676 DCHECK(plugin_size_.IsEmpty());
677 return;
679 if (first_paint_) {
680 first_paint_ = false;
681 pp::Rect rect = pp::Rect(pp::Point(), image_data_.size());
682 FillRect(rect, background_color_);
683 ready->push_back(PaintManager::ReadyRect(rect, image_data_, true));
686 if (!received_viewport_message_)
687 return;
689 engine_->PrePaint();
691 for (size_t i = 0; i < paint_rects.size(); i++) {
692 // Intersect with plugin area since there could be pending invalidates from
693 // when the plugin area was larger.
694 pp::Rect rect =
695 paint_rects[i].Intersect(pp::Rect(pp::Point(), plugin_size_));
696 if (rect.IsEmpty())
697 continue;
699 pp::Rect pdf_rect = available_area_.Intersect(rect);
700 if (!pdf_rect.IsEmpty()) {
701 pdf_rect.Offset(available_area_.x() * -1, 0);
703 std::vector<pp::Rect> pdf_ready;
704 std::vector<pp::Rect> pdf_pending;
705 engine_->Paint(pdf_rect, &image_data_, &pdf_ready, &pdf_pending);
706 for (size_t j = 0; j < pdf_ready.size(); ++j) {
707 pdf_ready[j].Offset(available_area_.point());
708 ready->push_back(
709 PaintManager::ReadyRect(pdf_ready[j], image_data_, false));
711 for (size_t j = 0; j < pdf_pending.size(); ++j) {
712 pdf_pending[j].Offset(available_area_.point());
713 pending->push_back(pdf_pending[j]);
717 for (size_t j = 0; j < background_parts_.size(); ++j) {
718 pp::Rect intersection = background_parts_[j].location.Intersect(rect);
719 if (!intersection.IsEmpty()) {
720 FillRect(intersection, background_parts_[j].color);
721 ready->push_back(
722 PaintManager::ReadyRect(intersection, image_data_, false));
727 engine_->PostPaint();
730 void OutOfProcessInstance::DidOpen(int32_t result) {
731 if (result == PP_OK) {
732 if (!engine_->HandleDocumentLoad(embed_loader_)) {
733 document_load_state_ = LOAD_STATE_LOADING;
734 DocumentLoadFailed();
736 } else if (result != PP_ERROR_ABORTED) { // Can happen in tests.
737 NOTREACHED();
738 DocumentLoadFailed();
741 // If it's a progressive load, cancel the stream URL request so that requests
742 // can be made on the original URL.
743 // TODO(raymes): Make this clearer once the in-process plugin is deleted.
744 if (engine_->IsProgressiveLoad()) {
745 pp::VarDictionary message;
746 message.Set(kType, kJSCancelStreamUrlType);
747 PostMessage(message);
751 void OutOfProcessInstance::DidOpenPreview(int32_t result) {
752 if (result == PP_OK) {
753 preview_engine_.reset(PDFEngine::Create(new PreviewModeClient(this)));
754 preview_engine_->HandleDocumentLoad(embed_preview_loader_);
755 } else {
756 NOTREACHED();
760 void OutOfProcessInstance::OnClientTimerFired(int32_t id) {
761 engine_->OnCallback(id);
764 void OutOfProcessInstance::CalculateBackgroundParts() {
765 background_parts_.clear();
766 int left_width = available_area_.x();
767 int right_start = available_area_.right();
768 int right_width = abs(plugin_size_.width() - available_area_.right());
769 int bottom = std::min(available_area_.bottom(), plugin_size_.height());
771 // Add the left, right, and bottom rectangles. Note: we assume only
772 // horizontal centering.
773 BackgroundPart part = {
774 pp::Rect(0, 0, left_width, bottom),
775 background_color_
777 if (!part.location.IsEmpty())
778 background_parts_.push_back(part);
779 part.location = pp::Rect(right_start, 0, right_width, bottom);
780 if (!part.location.IsEmpty())
781 background_parts_.push_back(part);
782 part.location = pp::Rect(
783 0, bottom, plugin_size_.width(), plugin_size_.height() - bottom);
784 if (!part.location.IsEmpty())
785 background_parts_.push_back(part);
788 int OutOfProcessInstance::GetDocumentPixelWidth() const {
789 return static_cast<int>(ceil(document_size_.width() * zoom_ * device_scale_));
792 int OutOfProcessInstance::GetDocumentPixelHeight() const {
793 return static_cast<int>(
794 ceil(document_size_.height() * zoom_ * device_scale_));
797 void OutOfProcessInstance::FillRect(const pp::Rect& rect, uint32 color) {
798 DCHECK(!image_data_.is_null() || rect.IsEmpty());
799 uint32* buffer_start = static_cast<uint32*>(image_data_.data());
800 int stride = image_data_.stride();
801 uint32* ptr = buffer_start + rect.y() * stride / 4 + rect.x();
802 int height = rect.height();
803 int width = rect.width();
804 for (int y = 0; y < height; ++y) {
805 for (int x = 0; x < width; ++x)
806 *(ptr + x) = color;
807 ptr += stride /4;
811 void OutOfProcessInstance::DocumentSizeUpdated(const pp::Size& size) {
812 document_size_ = size;
814 pp::VarDictionary dimensions;
815 dimensions.Set(kType, kJSDocumentDimensionsType);
816 dimensions.Set(kJSDocumentWidth, pp::Var(document_size_.width()));
817 dimensions.Set(kJSDocumentHeight, pp::Var(document_size_.height()));
818 pp::VarArray page_dimensions_array;
819 int num_pages = engine_->GetNumberOfPages();
820 for (int i = 0; i < num_pages; ++i) {
821 pp::Rect page_rect = engine_->GetPageRect(i);
822 pp::VarDictionary page_dimensions;
823 page_dimensions.Set(kJSPageX, pp::Var(page_rect.x()));
824 page_dimensions.Set(kJSPageY, pp::Var(page_rect.y()));
825 page_dimensions.Set(kJSPageWidth, pp::Var(page_rect.width()));
826 page_dimensions.Set(kJSPageHeight, pp::Var(page_rect.height()));
827 page_dimensions_array.Set(i, page_dimensions);
829 dimensions.Set(kJSPageDimensions, page_dimensions_array);
830 PostMessage(dimensions);
832 OnGeometryChanged(zoom_, device_scale_);
835 void OutOfProcessInstance::Invalidate(const pp::Rect& rect) {
836 pp::Rect offset_rect(rect);
837 offset_rect.Offset(available_area_.point());
838 paint_manager_.InvalidateRect(offset_rect);
841 void OutOfProcessInstance::Scroll(const pp::Point& point) {
842 if (!image_data_.is_null())
843 paint_manager_.ScrollRect(available_area_, point);
846 void OutOfProcessInstance::ScrollToX(int x) {
847 pp::VarDictionary position;
848 position.Set(kType, kJSSetScrollPositionType);
849 position.Set(kJSPositionX, pp::Var(x / device_scale_));
850 PostMessage(position);
853 void OutOfProcessInstance::ScrollToY(int y) {
854 pp::VarDictionary position;
855 position.Set(kType, kJSSetScrollPositionType);
856 position.Set(kJSPositionY, pp::Var(y / device_scale_));
857 PostMessage(position);
860 void OutOfProcessInstance::ScrollToPage(int page) {
861 if (engine_->GetNumberOfPages() == 0)
862 return;
864 pp::VarDictionary message;
865 message.Set(kType, kJSGoToPageType);
866 message.Set(kJSPageNumber, pp::Var(page));
867 PostMessage(message);
870 void OutOfProcessInstance::NavigateTo(const std::string& url,
871 bool open_in_new_tab) {
872 pp::VarDictionary message;
873 message.Set(kType, kJSNavigateType);
874 message.Set(kJSNavigateUrl, url);
875 message.Set(kJSNavigateNewTab, open_in_new_tab);
876 PostMessage(message);
879 void OutOfProcessInstance::UpdateCursor(PP_CursorType_Dev cursor) {
880 if (cursor == cursor_)
881 return;
882 cursor_ = cursor;
884 const PPB_CursorControl_Dev* cursor_interface =
885 reinterpret_cast<const PPB_CursorControl_Dev*>(
886 pp::Module::Get()->GetBrowserInterface(PPB_CURSOR_CONTROL_DEV_INTERFACE));
887 if (!cursor_interface) {
888 NOTREACHED();
889 return;
892 cursor_interface->SetCursor(
893 pp_instance(), cursor_, pp::ImageData().pp_resource(), NULL);
896 void OutOfProcessInstance::UpdateTickMarks(
897 const std::vector<pp::Rect>& tickmarks) {
898 float inverse_scale = 1.0f / device_scale_;
899 std::vector<pp::Rect> scaled_tickmarks = tickmarks;
900 for (size_t i = 0; i < scaled_tickmarks.size(); i++)
901 ScaleRect(inverse_scale, &scaled_tickmarks[i]);
902 tickmarks_ = scaled_tickmarks;
905 void OutOfProcessInstance::NotifyNumberOfFindResultsChanged(int total,
906 bool final_result) {
907 // We don't want to spam the renderer with too many updates to the number of
908 // find results. Don't send an update if we sent one too recently. If it's the
909 // final update, we always send it though.
910 if (final_result) {
911 NumberOfFindResultsChanged(total, final_result);
912 SetTickmarks(tickmarks_);
913 return;
916 if (recently_sent_find_update_)
917 return;
919 NumberOfFindResultsChanged(total, final_result);
920 SetTickmarks(tickmarks_);
921 recently_sent_find_update_ = true;
922 pp::CompletionCallback callback =
923 timer_factory_.NewCallback(
924 &OutOfProcessInstance::ResetRecentlySentFindUpdate);
925 pp::Module::Get()->core()->CallOnMainThread(kFindResultCooldownMs,
926 callback, 0);
929 void OutOfProcessInstance::NotifySelectedFindResultChanged(
930 int current_find_index) {
931 DCHECK_GE(current_find_index, 0);
932 SelectedFindResultChanged(current_find_index);
935 void OutOfProcessInstance::GetDocumentPassword(
936 pp::CompletionCallbackWithOutput<pp::Var> callback) {
937 if (password_callback_) {
938 NOTREACHED();
939 return;
942 password_callback_.reset(
943 new pp::CompletionCallbackWithOutput<pp::Var>(callback));
944 pp::VarDictionary message;
945 message.Set(pp::Var(kType), pp::Var(kJSGetPasswordType));
946 PostMessage(message);
949 void OutOfProcessInstance::Alert(const std::string& message) {
950 ModalDialog(this, "alert", message, std::string());
953 bool OutOfProcessInstance::Confirm(const std::string& message) {
954 pp::Var result = ModalDialog(this, "confirm", message, std::string());
955 return result.is_bool() ? result.AsBool() : false;
958 std::string OutOfProcessInstance::Prompt(const std::string& question,
959 const std::string& default_answer) {
960 pp::Var result = ModalDialog(this, "prompt", question, default_answer);
961 return result.is_string() ? result.AsString() : std::string();
964 std::string OutOfProcessInstance::GetURL() {
965 return url_;
968 void OutOfProcessInstance::Email(const std::string& to,
969 const std::string& cc,
970 const std::string& bcc,
971 const std::string& subject,
972 const std::string& body) {
973 pp::VarDictionary message;
974 message.Set(pp::Var(kType), pp::Var(kJSEmailType));
975 message.Set(pp::Var(kJSEmailTo),
976 pp::Var(net::EscapeUrlEncodedData(to, false)));
977 message.Set(pp::Var(kJSEmailCc),
978 pp::Var(net::EscapeUrlEncodedData(cc, false)));
979 message.Set(pp::Var(kJSEmailBcc),
980 pp::Var(net::EscapeUrlEncodedData(bcc, false)));
981 message.Set(pp::Var(kJSEmailSubject),
982 pp::Var(net::EscapeUrlEncodedData(subject, false)));
983 message.Set(pp::Var(kJSEmailBody),
984 pp::Var(net::EscapeUrlEncodedData(body, false)));
985 PostMessage(message);
988 void OutOfProcessInstance::Print() {
989 if (!engine_->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY) &&
990 !engine_->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY)) {
991 return;
994 pp::CompletionCallback callback =
995 print_callback_factory_.NewCallback(&OutOfProcessInstance::OnPrint);
996 pp::Module::Get()->core()->CallOnMainThread(0, callback);
999 void OutOfProcessInstance::OnPrint(int32_t) {
1000 pp::PDF::Print(this);
1003 void OutOfProcessInstance::SubmitForm(const std::string& url,
1004 const void* data,
1005 int length) {
1006 pp::URLRequestInfo request(this);
1007 request.SetURL(url);
1008 request.SetMethod("POST");
1009 request.AppendDataToBody(reinterpret_cast<const char*>(data), length);
1011 pp::CompletionCallback callback =
1012 form_factory_.NewCallback(&OutOfProcessInstance::FormDidOpen);
1013 form_loader_ = CreateURLLoaderInternal();
1014 int rv = form_loader_.Open(request, callback);
1015 if (rv != PP_OK_COMPLETIONPENDING)
1016 callback.Run(rv);
1019 void OutOfProcessInstance::FormDidOpen(int32_t result) {
1020 // TODO: inform the user of success/failure.
1021 if (result != PP_OK) {
1022 NOTREACHED();
1026 std::string OutOfProcessInstance::ShowFileSelectionDialog() {
1027 // Seems like very low priority to implement, since the pdf has no way to get
1028 // the file data anyways. Javascript doesn't let you do this synchronously.
1029 NOTREACHED();
1030 return std::string();
1033 pp::URLLoader OutOfProcessInstance::CreateURLLoader() {
1034 if (full_) {
1035 if (!did_call_start_loading_) {
1036 did_call_start_loading_ = true;
1037 pp::PDF::DidStartLoading(this);
1040 // Disable save and print until the document is fully loaded, since they
1041 // would generate an incomplete document. Need to do this each time we
1042 // call DidStartLoading since that resets the content restrictions.
1043 pp::PDF::SetContentRestriction(this, CONTENT_RESTRICTION_SAVE |
1044 CONTENT_RESTRICTION_PRINT);
1047 return CreateURLLoaderInternal();
1050 void OutOfProcessInstance::ScheduleCallback(int id, int delay_in_ms) {
1051 pp::CompletionCallback callback =
1052 timer_factory_.NewCallback(&OutOfProcessInstance::OnClientTimerFired);
1053 pp::Module::Get()->core()->CallOnMainThread(delay_in_ms, callback, id);
1056 void OutOfProcessInstance::SearchString(const base::char16* string,
1057 const base::char16* term,
1058 bool case_sensitive,
1059 std::vector<SearchStringResult>* results) {
1060 PP_PrivateFindResult* pp_results;
1061 int count = 0;
1062 pp::PDF::SearchString(
1063 this,
1064 reinterpret_cast<const unsigned short*>(string),
1065 reinterpret_cast<const unsigned short*>(term),
1066 case_sensitive,
1067 &pp_results,
1068 &count);
1070 results->resize(count);
1071 for (int i = 0; i < count; ++i) {
1072 (*results)[i].start_index = pp_results[i].start_index;
1073 (*results)[i].length = pp_results[i].length;
1076 pp::Memory_Dev memory;
1077 memory.MemFree(pp_results);
1080 void OutOfProcessInstance::DocumentPaintOccurred() {
1083 void OutOfProcessInstance::DocumentLoadComplete(int page_count) {
1084 // Clear focus state for OSK.
1085 FormTextFieldFocusChange(false);
1087 DCHECK(document_load_state_ == LOAD_STATE_LOADING);
1088 document_load_state_ = LOAD_STATE_COMPLETE;
1089 UserMetricsRecordAction("PDF.LoadSuccess");
1091 // Note: If we are in print preview mode the scroll location is retained
1092 // across document loads so we don't want to scroll again and override it.
1093 if (IsPrintPreview()) {
1094 AppendBlankPrintPreviewPages();
1095 OnGeometryChanged(0, 0);
1098 pp::VarDictionary named_destinations_message;
1099 pp::VarDictionary named_destinations = engine_->GetNamedDestinations();
1100 named_destinations_message.Set(pp::Var(kType),
1101 pp::Var(kJSSetNamedDestinationsType));
1102 named_destinations_message.Set(pp::Var(kJSNamedDestinations),
1103 pp::Var(named_destinations));
1104 PostMessage(named_destinations_message);
1106 pp::VarDictionary bookmarks_message;
1107 bookmarks_message.Set(pp::Var(kType), pp::Var(kJSBookmarksType));
1108 bookmarks_message.Set(pp::Var(kJSBookmarks), engine_->GetBookmarks());
1109 PostMessage(bookmarks_message);
1111 pp::VarDictionary progress_message;
1112 progress_message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1113 progress_message.Set(pp::Var(kJSProgressPercentage), pp::Var(100));
1114 PostMessage(progress_message);
1116 if (!full_)
1117 return;
1119 if (did_call_start_loading_) {
1120 pp::PDF::DidStopLoading(this);
1121 did_call_start_loading_ = false;
1124 int content_restrictions =
1125 CONTENT_RESTRICTION_CUT | CONTENT_RESTRICTION_PASTE;
1126 if (!engine_->HasPermission(PDFEngine::PERMISSION_COPY))
1127 content_restrictions |= CONTENT_RESTRICTION_COPY;
1129 pp::PDF::SetContentRestriction(this, content_restrictions);
1131 uma_.HistogramCustomCounts("PDF.PageCount", page_count,
1132 1, 1000000, 50);
1135 void OutOfProcessInstance::RotateClockwise() {
1136 engine_->RotateClockwise();
1139 void OutOfProcessInstance::RotateCounterclockwise() {
1140 engine_->RotateCounterclockwise();
1143 void OutOfProcessInstance::PreviewDocumentLoadComplete() {
1144 if (preview_document_load_state_ != LOAD_STATE_LOADING ||
1145 preview_pages_info_.empty()) {
1146 return;
1149 preview_document_load_state_ = LOAD_STATE_COMPLETE;
1151 int dest_page_index = preview_pages_info_.front().second;
1152 int src_page_index =
1153 ExtractPrintPreviewPageIndex(preview_pages_info_.front().first);
1154 if (src_page_index > 0 && dest_page_index > -1 && preview_engine_.get())
1155 engine_->AppendPage(preview_engine_.get(), dest_page_index);
1157 preview_pages_info_.pop();
1158 // |print_preview_page_count_| is not updated yet. Do not load any
1159 // other preview pages till we get this information.
1160 if (print_preview_page_count_ == 0)
1161 return;
1163 if (preview_pages_info_.size())
1164 LoadAvailablePreviewPage();
1167 void OutOfProcessInstance::DocumentLoadFailed() {
1168 DCHECK(document_load_state_ == LOAD_STATE_LOADING);
1169 UserMetricsRecordAction("PDF.LoadFailure");
1171 if (did_call_start_loading_) {
1172 pp::PDF::DidStopLoading(this);
1173 did_call_start_loading_ = false;
1176 document_load_state_ = LOAD_STATE_FAILED;
1177 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
1179 // Send a progress value of -1 to indicate a failure.
1180 pp::VarDictionary message;
1181 message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1182 message.Set(pp::Var(kJSProgressPercentage), pp::Var(-1)) ;
1183 PostMessage(message);
1186 void OutOfProcessInstance::PreviewDocumentLoadFailed() {
1187 UserMetricsRecordAction("PDF.PreviewDocumentLoadFailure");
1188 if (preview_document_load_state_ != LOAD_STATE_LOADING ||
1189 preview_pages_info_.empty()) {
1190 return;
1193 preview_document_load_state_ = LOAD_STATE_FAILED;
1194 preview_pages_info_.pop();
1196 if (preview_pages_info_.size())
1197 LoadAvailablePreviewPage();
1200 pp::Instance* OutOfProcessInstance::GetPluginInstance() {
1201 return this;
1204 void OutOfProcessInstance::DocumentHasUnsupportedFeature(
1205 const std::string& feature) {
1206 std::string metric("PDF_Unsupported_");
1207 metric += feature;
1208 if (!unsupported_features_reported_.count(metric)) {
1209 unsupported_features_reported_.insert(metric);
1210 UserMetricsRecordAction(metric);
1213 // Since we use an info bar, only do this for full frame plugins..
1214 if (!full_)
1215 return;
1217 if (told_browser_about_unsupported_feature_)
1218 return;
1219 told_browser_about_unsupported_feature_ = true;
1221 pp::PDF::HasUnsupportedFeature(this);
1224 void OutOfProcessInstance::DocumentLoadProgress(uint32 available,
1225 uint32 doc_size) {
1226 double progress = 0.0;
1227 if (doc_size == 0) {
1228 // Document size is unknown. Use heuristics.
1229 // We'll make progress logarithmic from 0 to 100M.
1230 static const double kFactor = log(100000000.0) / 100.0;
1231 if (available > 0) {
1232 progress = log(static_cast<double>(available)) / kFactor;
1233 if (progress > 100.0)
1234 progress = 100.0;
1236 } else {
1237 progress = 100.0 * static_cast<double>(available) / doc_size;
1240 // We send 100% load progress in DocumentLoadComplete.
1241 if (progress >= 100)
1242 return;
1244 // Avoid sending too many progress messages over PostMessage.
1245 if (progress > last_progress_sent_ + 1) {
1246 last_progress_sent_ = progress;
1247 pp::VarDictionary message;
1248 message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1249 message.Set(pp::Var(kJSProgressPercentage), pp::Var(progress)) ;
1250 PostMessage(message);
1254 void OutOfProcessInstance::FormTextFieldFocusChange(bool in_focus) {
1255 if (!text_input_.get())
1256 return;
1257 if (in_focus)
1258 text_input_->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_TEXT);
1259 else
1260 text_input_->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_NONE);
1263 void OutOfProcessInstance::ResetRecentlySentFindUpdate(int32_t /* unused */) {
1264 recently_sent_find_update_ = false;
1267 void OutOfProcessInstance::OnGeometryChanged(double old_zoom,
1268 float old_device_scale) {
1269 if (zoom_ != old_zoom || device_scale_ != old_device_scale)
1270 engine_->ZoomUpdated(zoom_ * device_scale_);
1272 available_area_ = pp::Rect(plugin_size_);
1273 int doc_width = GetDocumentPixelWidth();
1274 if (doc_width < available_area_.width()) {
1275 available_area_.Offset((available_area_.width() - doc_width) / 2, 0);
1276 available_area_.set_width(doc_width);
1278 int doc_height = GetDocumentPixelHeight();
1279 if (doc_height < available_area_.height()) {
1280 available_area_.set_height(doc_height);
1283 CalculateBackgroundParts();
1284 engine_->PageOffsetUpdated(available_area_.point());
1285 engine_->PluginSizeUpdated(available_area_.size());
1287 if (!document_size_.GetArea())
1288 return;
1289 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
1292 void OutOfProcessInstance::LoadUrl(const std::string& url) {
1293 LoadUrlInternal(url, &embed_loader_, &OutOfProcessInstance::DidOpen);
1296 void OutOfProcessInstance::LoadPreviewUrl(const std::string& url) {
1297 LoadUrlInternal(url, &embed_preview_loader_,
1298 &OutOfProcessInstance::DidOpenPreview);
1301 void OutOfProcessInstance::LoadUrlInternal(
1302 const std::string& url,
1303 pp::URLLoader* loader,
1304 void (OutOfProcessInstance::* method)(int32_t)) {
1305 pp::URLRequestInfo request(this);
1306 request.SetURL(url);
1307 request.SetMethod("GET");
1309 *loader = CreateURLLoaderInternal();
1310 pp::CompletionCallback callback = loader_factory_.NewCallback(method);
1311 int rv = loader->Open(request, callback);
1312 if (rv != PP_OK_COMPLETIONPENDING)
1313 callback.Run(rv);
1316 pp::URLLoader OutOfProcessInstance::CreateURLLoaderInternal() {
1317 pp::URLLoader loader(this);
1319 const PPB_URLLoaderTrusted* trusted_interface =
1320 reinterpret_cast<const PPB_URLLoaderTrusted*>(
1321 pp::Module::Get()->GetBrowserInterface(
1322 PPB_URLLOADERTRUSTED_INTERFACE));
1323 if (trusted_interface)
1324 trusted_interface->GrantUniversalAccess(loader.pp_resource());
1325 return loader;
1328 void OutOfProcessInstance::SetZoom(double scale) {
1329 double old_zoom = zoom_;
1330 zoom_ = scale;
1331 OnGeometryChanged(old_zoom, device_scale_);
1334 std::string OutOfProcessInstance::GetLocalizedString(PP_ResourceString id) {
1335 pp::Var rv(pp::PDF::GetLocalizedString(this, id));
1336 if (!rv.is_string())
1337 return std::string();
1339 return rv.AsString();
1342 void OutOfProcessInstance::AppendBlankPrintPreviewPages() {
1343 if (print_preview_page_count_ == 0)
1344 return;
1345 engine_->AppendBlankPages(print_preview_page_count_);
1346 if (preview_pages_info_.size() > 0)
1347 LoadAvailablePreviewPage();
1350 bool OutOfProcessInstance::IsPrintPreview() {
1351 return IsPrintPreviewUrl(url_);
1354 uint32 OutOfProcessInstance::GetBackgroundColor() {
1355 return background_color_;
1358 void OutOfProcessInstance::IsSelectingChanged(bool is_selecting) {
1359 pp::VarDictionary message;
1360 message.Set(kType, kJSSetIsSelectingType);
1361 message.Set(kJSIsSelecting, pp::Var(is_selecting));
1362 PostMessage(message);
1365 void OutOfProcessInstance::ProcessPreviewPageInfo(const std::string& url,
1366 int dst_page_index) {
1367 if (!IsPrintPreview())
1368 return;
1370 int src_page_index = ExtractPrintPreviewPageIndex(url);
1371 if (src_page_index < 1)
1372 return;
1374 preview_pages_info_.push(std::make_pair(url, dst_page_index));
1375 LoadAvailablePreviewPage();
1378 void OutOfProcessInstance::LoadAvailablePreviewPage() {
1379 if (preview_pages_info_.size() <= 0 ||
1380 document_load_state_ != LOAD_STATE_COMPLETE) {
1381 return;
1384 std::string url = preview_pages_info_.front().first;
1385 int dst_page_index = preview_pages_info_.front().second;
1386 int src_page_index = ExtractPrintPreviewPageIndex(url);
1387 if (src_page_index < 1 ||
1388 dst_page_index >= print_preview_page_count_ ||
1389 preview_document_load_state_ == LOAD_STATE_LOADING) {
1390 return;
1393 preview_document_load_state_ = LOAD_STATE_LOADING;
1394 LoadPreviewUrl(url);
1397 void OutOfProcessInstance::UserMetricsRecordAction(
1398 const std::string& action) {
1399 // TODO(raymes): Move this function to PPB_UMA_Private.
1400 pp::PDF::UserMetricsRecordAction(this, pp::Var(action));
1403 pp::FloatPoint OutOfProcessInstance::BoundScrollOffsetToDocument(
1404 const pp::FloatPoint& scroll_offset) {
1405 float max_x = document_size_.width() * zoom_ - plugin_dip_size_.width();
1406 float x = std::max(std::min(scroll_offset.x(), max_x), 0.0f);
1407 float max_y = document_size_.height() * zoom_ - plugin_dip_size_.height();
1408 float y = std::max(std::min(scroll_offset.y(), max_y), 0.0f);
1409 return pp::FloatPoint(x, y);
1412 } // namespace chrome_pdf