Hotword: Fix more accessibility issues.
[chromium-blink-merge.git] / pdf / out_of_process_instance.cc
blob59b04394419410bc1eda3518839f2323169bbe94
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 // Constants used in handling postMessage() messages.
56 const char kType[] = "type";
57 // Viewport message arguments. (Page -> Plugin).
58 const char kJSViewportType[] = "viewport";
59 const char kJSXOffset[] = "xOffset";
60 const char kJSYOffset[] = "yOffset";
61 const char kJSZoom[] = "zoom";
62 // Stop scrolling message (Page -> Plugin)
63 const char kJSStopScrollingType[] = "stopScrolling";
64 // Document dimension arguments (Plugin -> Page).
65 const char kJSDocumentDimensionsType[] = "documentDimensions";
66 const char kJSDocumentWidth[] = "width";
67 const char kJSDocumentHeight[] = "height";
68 const char kJSPageDimensions[] = "pageDimensions";
69 const char kJSPageX[] = "x";
70 const char kJSPageY[] = "y";
71 const char kJSPageWidth[] = "width";
72 const char kJSPageHeight[] = "height";
73 // Document load progress arguments (Plugin -> Page)
74 const char kJSLoadProgressType[] = "loadProgress";
75 const char kJSProgressPercentage[] = "progress";
76 // Get password arguments (Plugin -> Page)
77 const char kJSGetPasswordType[] = "getPassword";
78 // Get password complete arguments (Page -> Plugin)
79 const char kJSGetPasswordCompleteType[] = "getPasswordComplete";
80 const char kJSPassword[] = "password";
81 // Print (Page -> Plugin)
82 const char kJSPrintType[] = "print";
83 // Save (Page -> Plugin)
84 const char kJSSaveType[] = "save";
85 // Go to page (Plugin -> Page)
86 const char kJSGoToPageType[] = "goToPage";
87 const char kJSPageNumber[] = "page";
88 // Reset print preview mode (Page -> Plugin)
89 const char kJSResetPrintPreviewModeType[] = "resetPrintPreviewMode";
90 const char kJSPrintPreviewUrl[] = "url";
91 const char kJSPrintPreviewGrayscale[] = "grayscale";
92 const char kJSPrintPreviewPageCount[] = "pageCount";
93 // Load preview page (Page -> Plugin)
94 const char kJSLoadPreviewPageType[] = "loadPreviewPage";
95 const char kJSPreviewPageUrl[] = "url";
96 const char kJSPreviewPageIndex[] = "index";
97 // Set scroll position (Plugin -> Page)
98 const char kJSSetScrollPositionType[] = "setScrollPosition";
99 const char kJSPositionX[] = "x";
100 const char kJSPositionY[] = "y";
101 // Set translated strings (Plugin -> Page)
102 const char kJSSetTranslatedStringsType[] = "setTranslatedStrings";
103 const char kJSGetPasswordString[] = "getPasswordString";
104 const char kJSLoadingString[] = "loadingString";
105 const char kJSLoadFailedString[] = "loadFailedString";
106 // Request accessibility JSON data (Page -> Plugin)
107 const char kJSGetAccessibilityJSONType[] = "getAccessibilityJSON";
108 const char kJSAccessibilityPageNumber[] = "page";
109 // Reply with accessibility JSON data (Plugin -> Page)
110 const char kJSGetAccessibilityJSONReplyType[] = "getAccessibilityJSONReply";
111 const char kJSAccessibilityJSON[] = "json";
112 // Cancel the stream URL request (Plugin -> Page)
113 const char kJSCancelStreamUrlType[] = "cancelStreamUrl";
114 // Navigate to the given URL (Plugin -> Page)
115 const char kJSNavigateType[] = "navigate";
116 const char kJSNavigateUrl[] = "url";
117 const char kJSNavigateNewTab[] = "newTab";
118 // Open the email editor with the given parameters (Plugin -> Page)
119 const char kJSEmailType[] = "email";
120 const char kJSEmailTo[] = "to";
121 const char kJSEmailCc[] = "cc";
122 const char kJSEmailBcc[] = "bcc";
123 const char kJSEmailSubject[] = "subject";
124 const char kJSEmailBody[] = "body";
125 // Rotation (Page -> Plugin)
126 const char kJSRotateClockwiseType[] = "rotateClockwise";
127 const char kJSRotateCounterclockwiseType[] = "rotateCounterclockwise";
128 // Select all text in the document (Page -> Plugin)
129 const char kJSSelectAllType[] = "selectAll";
131 const int kFindResultCooldownMs = 100;
133 const double kMinZoom = 0.01;
135 namespace {
137 static const char kPPPPdfInterface[] = PPP_PDF_INTERFACE_1;
139 PP_Var GetLinkAtPosition(PP_Instance instance, PP_Point point) {
140 pp::Var var;
141 void* object = pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
142 if (object) {
143 var = static_cast<OutOfProcessInstance*>(object)->GetLinkAtPosition(
144 pp::Point(point));
146 return var.Detach();
149 void Transform(PP_Instance instance, PP_PrivatePageTransformType type) {
150 void* object =
151 pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
152 if (object) {
153 OutOfProcessInstance* obj_instance =
154 static_cast<OutOfProcessInstance*>(object);
155 switch (type) {
156 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CW:
157 obj_instance->RotateClockwise();
158 break;
159 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CCW:
160 obj_instance->RotateCounterclockwise();
161 break;
166 PP_Bool GetPrintPresetOptionsFromDocument(
167 PP_Instance instance,
168 PP_PdfPrintPresetOptions_Dev* options) {
169 void* object = pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
170 if (object) {
171 OutOfProcessInstance* obj_instance =
172 static_cast<OutOfProcessInstance*>(object);
173 obj_instance->GetPrintPresetOptionsFromDocument(options);
175 return PP_TRUE;
178 const PPP_Pdf ppp_private = {
179 &GetLinkAtPosition,
180 &Transform,
181 &GetPrintPresetOptionsFromDocument
184 int ExtractPrintPreviewPageIndex(const std::string& src_url) {
185 // Sample |src_url| format: chrome://print/id/page_index/print.pdf
186 std::vector<std::string> url_substr;
187 base::SplitString(src_url.substr(strlen(kChromePrint)), '/', &url_substr);
188 if (url_substr.size() != 3)
189 return -1;
191 if (url_substr[2] != "print.pdf")
192 return -1;
194 int page_index = 0;
195 if (!base::StringToInt(url_substr[1], &page_index))
196 return -1;
197 return page_index;
200 bool IsPrintPreviewUrl(const std::string& url) {
201 return url.substr(0, strlen(kChromePrint)) == kChromePrint;
204 void ScalePoint(float scale, pp::Point* point) {
205 point->set_x(static_cast<int>(point->x() * scale));
206 point->set_y(static_cast<int>(point->y() * scale));
209 void ScaleRect(float scale, pp::Rect* rect) {
210 int left = static_cast<int>(floorf(rect->x() * scale));
211 int top = static_cast<int>(floorf(rect->y() * scale));
212 int right = static_cast<int>(ceilf((rect->x() + rect->width()) * scale));
213 int bottom = static_cast<int>(ceilf((rect->y() + rect->height()) * scale));
214 rect->SetRect(left, top, right - left, bottom - top);
217 // TODO(raymes): Remove this dependency on VarPrivate/InstancePrivate. It's
218 // needed right now to do a synchronous call to JavaScript, but we could easily
219 // replace this with a custom PPB_PDF function.
220 pp::Var ModalDialog(const pp::Instance* instance,
221 const std::string& type,
222 const std::string& message,
223 const std::string& default_answer) {
224 const PPB_Instance_Private* interface =
225 reinterpret_cast<const PPB_Instance_Private*>(
226 pp::Module::Get()->GetBrowserInterface(
227 PPB_INSTANCE_PRIVATE_INTERFACE));
228 pp::VarPrivate window(pp::PASS_REF,
229 interface->GetWindowObject(instance->pp_instance()));
230 if (default_answer.empty())
231 return window.Call(type, message);
232 else
233 return window.Call(type, message, default_answer);
236 } // namespace
238 OutOfProcessInstance::OutOfProcessInstance(PP_Instance instance)
239 : pp::Instance(instance),
240 pp::Find_Private(this),
241 pp::Printing_Dev(this),
242 pp::Selection_Dev(this),
243 cursor_(PP_CURSORTYPE_POINTER),
244 zoom_(1.0),
245 device_scale_(1.0),
246 printing_enabled_(true),
247 full_(false),
248 paint_manager_(this, this, true),
249 first_paint_(true),
250 document_load_state_(LOAD_STATE_LOADING),
251 preview_document_load_state_(LOAD_STATE_COMPLETE),
252 uma_(this),
253 told_browser_about_unsupported_feature_(false),
254 print_preview_page_count_(0),
255 last_progress_sent_(0),
256 recently_sent_find_update_(false),
257 received_viewport_message_(false),
258 did_call_start_loading_(false),
259 stop_scrolling_(false) {
260 loader_factory_.Initialize(this);
261 timer_factory_.Initialize(this);
262 form_factory_.Initialize(this);
263 print_callback_factory_.Initialize(this);
264 engine_.reset(PDFEngine::Create(this));
265 pp::Module::Get()->AddPluginInterface(kPPPPdfInterface, &ppp_private);
266 AddPerInstanceObject(kPPPPdfInterface, this);
268 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_MOUSE);
269 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_KEYBOARD);
270 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_TOUCH);
273 OutOfProcessInstance::~OutOfProcessInstance() {
274 RemovePerInstanceObject(kPPPPdfInterface, this);
277 bool OutOfProcessInstance::Init(uint32_t argc,
278 const char* argn[],
279 const char* argv[]) {
280 // Check if the PDF is being loaded in the PDF chrome extension. We only allow
281 // the plugin to be put into "full frame" mode when it is being loaded in the
282 // extension because this enables some features that we don't want pages
283 // abusing outside of the extension.
284 pp::Var document_url_var = pp::URLUtil_Dev::Get()->GetDocumentURL(this);
285 std::string document_url = document_url_var.is_string() ?
286 document_url_var.AsString() : std::string();
287 std::string extension_url = std::string(kChromeExtension);
288 bool in_extension =
289 !document_url.compare(0, extension_url.size(), extension_url);
291 if (in_extension) {
292 // Check if the plugin is full frame. This is passed in from JS.
293 for (uint32_t i = 0; i < argc; ++i) {
294 if (strcmp(argn[i], "full-frame") == 0) {
295 full_ = true;
296 break;
301 // Only allow the plugin to handle find requests if it is full frame.
302 if (full_)
303 SetPluginToHandleFindRequests();
305 // Send translated strings to the extension where they will be displayed.
306 // TODO(raymes): It would be better to get these in the extension directly
307 // through an API but no such API currently exists.
308 pp::VarDictionary translated_strings;
309 translated_strings.Set(kType, kJSSetTranslatedStringsType);
310 translated_strings.Set(kJSGetPasswordString,
311 GetLocalizedString(PP_RESOURCESTRING_PDFGETPASSWORD));
312 translated_strings.Set(kJSLoadingString,
313 GetLocalizedString(PP_RESOURCESTRING_PDFLOADING));
314 translated_strings.Set(kJSLoadFailedString,
315 GetLocalizedString(PP_RESOURCESTRING_PDFLOAD_FAILED));
316 PostMessage(translated_strings);
318 text_input_.reset(new pp::TextInput_Dev(this));
320 const char* stream_url = NULL;
321 const char* original_url = NULL;
322 const char* headers = NULL;
323 for (uint32_t i = 0; i < argc; ++i) {
324 if (strcmp(argn[i], "src") == 0)
325 original_url = argv[i];
326 else if (strcmp(argn[i], "stream-url") == 0)
327 stream_url = argv[i];
328 else if (strcmp(argn[i], "headers") == 0)
329 headers = argv[i];
332 // TODO(raymes): This is a hack to ensure that if no headers are passed in
333 // then we get the right MIME type. When the in process plugin is removed we
334 // can fix the document loader properly and remove this hack.
335 if (!headers || strcmp(headers, "") == 0)
336 headers = "content-type: application/pdf";
338 if (!original_url)
339 return false;
341 if (!stream_url)
342 stream_url = original_url;
344 // If we're in print preview mode we don't need to load the document yet.
345 // A |kJSResetPrintPreviewModeType| message will be sent to the plugin letting
346 // it know the url to load. By not loading here we avoid loading the same
347 // document twice.
348 if (IsPrintPreviewUrl(original_url))
349 return true;
351 LoadUrl(stream_url);
352 url_ = original_url;
353 return engine_->New(original_url, headers);
356 void OutOfProcessInstance::HandleMessage(const pp::Var& message) {
357 pp::VarDictionary dict(message);
358 if (!dict.Get(kType).is_string()) {
359 NOTREACHED();
360 return;
363 std::string type = dict.Get(kType).AsString();
365 if (type == kJSViewportType &&
366 dict.Get(pp::Var(kJSXOffset)).is_number() &&
367 dict.Get(pp::Var(kJSYOffset)).is_number() &&
368 dict.Get(pp::Var(kJSZoom)).is_number()) {
369 received_viewport_message_ = true;
370 stop_scrolling_ = false;
371 double zoom = dict.Get(pp::Var(kJSZoom)).AsDouble();
372 pp::FloatPoint scroll_offset(dict.Get(pp::Var(kJSXOffset)).AsDouble(),
373 dict.Get(pp::Var(kJSYOffset)).AsDouble());
375 // Bound the input parameters.
376 zoom = std::max(kMinZoom, zoom);
377 SetZoom(zoom);
378 scroll_offset = BoundScrollOffsetToDocument(scroll_offset);
379 engine_->ScrolledToXPosition(scroll_offset.x() * device_scale_);
380 engine_->ScrolledToYPosition(scroll_offset.y() * device_scale_);
381 } else if (type == kJSGetPasswordCompleteType &&
382 dict.Get(pp::Var(kJSPassword)).is_string()) {
383 if (password_callback_) {
384 pp::CompletionCallbackWithOutput<pp::Var> callback = *password_callback_;
385 password_callback_.reset();
386 *callback.output() = dict.Get(pp::Var(kJSPassword)).pp_var();
387 callback.Run(PP_OK);
388 } else {
389 NOTREACHED();
391 } else if (type == kJSPrintType) {
392 Print();
393 } else if (type == kJSSaveType) {
394 pp::PDF::SaveAs(this);
395 } else if (type == kJSRotateClockwiseType) {
396 RotateClockwise();
397 } else if (type == kJSRotateCounterclockwiseType) {
398 RotateCounterclockwise();
399 } else if (type == kJSSelectAllType) {
400 engine_->SelectAll();
401 } else if (type == kJSResetPrintPreviewModeType &&
402 dict.Get(pp::Var(kJSPrintPreviewUrl)).is_string() &&
403 dict.Get(pp::Var(kJSPrintPreviewGrayscale)).is_bool() &&
404 dict.Get(pp::Var(kJSPrintPreviewPageCount)).is_int()) {
405 url_ = dict.Get(pp::Var(kJSPrintPreviewUrl)).AsString();
406 preview_pages_info_ = std::queue<PreviewPageInfo>();
407 preview_document_load_state_ = LOAD_STATE_COMPLETE;
408 document_load_state_ = LOAD_STATE_LOADING;
409 LoadUrl(url_);
410 preview_engine_.reset();
411 engine_.reset(PDFEngine::Create(this));
412 engine_->SetGrayscale(dict.Get(pp::Var(kJSPrintPreviewGrayscale)).AsBool());
413 engine_->New(url_.c_str());
415 print_preview_page_count_ =
416 std::max(dict.Get(pp::Var(kJSPrintPreviewPageCount)).AsInt(), 0);
418 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
419 } else if (type == kJSLoadPreviewPageType &&
420 dict.Get(pp::Var(kJSPreviewPageUrl)).is_string() &&
421 dict.Get(pp::Var(kJSPreviewPageIndex)).is_int()) {
422 ProcessPreviewPageInfo(dict.Get(pp::Var(kJSPreviewPageUrl)).AsString(),
423 dict.Get(pp::Var(kJSPreviewPageIndex)).AsInt());
424 } else if (type == kJSGetAccessibilityJSONType) {
425 pp::VarDictionary reply;
426 reply.Set(pp::Var(kType), pp::Var(kJSGetAccessibilityJSONReplyType));
427 if (dict.Get(pp::Var(kJSAccessibilityPageNumber)).is_int()) {
428 int page = dict.Get(pp::Var(kJSAccessibilityPageNumber)).AsInt();
429 reply.Set(pp::Var(kJSAccessibilityJSON),
430 pp::Var(engine_->GetPageAsJSON(page)));
431 } else {
432 base::DictionaryValue node;
433 node.SetInteger(kAccessibleNumberOfPages, engine_->GetNumberOfPages());
434 node.SetBoolean(kAccessibleLoaded,
435 document_load_state_ != LOAD_STATE_LOADING);
436 bool has_permissions =
437 engine_->HasPermission(PDFEngine::PERMISSION_COPY) ||
438 engine_->HasPermission(PDFEngine::PERMISSION_COPY_ACCESSIBLE);
439 node.SetBoolean(kAccessibleCopyable, has_permissions);
440 std::string json;
441 base::JSONWriter::Write(&node, &json);
442 reply.Set(pp::Var(kJSAccessibilityJSON), pp::Var(json));
444 PostMessage(reply);
445 } else if (type == kJSStopScrollingType) {
446 stop_scrolling_ = true;
447 } else {
448 NOTREACHED();
452 bool OutOfProcessInstance::HandleInputEvent(
453 const pp::InputEvent& event) {
454 // To simplify things, convert the event into device coordinates if it is
455 // a mouse event.
456 pp::InputEvent event_device_res(event);
458 pp::MouseInputEvent mouse_event(event);
459 if (!mouse_event.is_null()) {
460 pp::Point point = mouse_event.GetPosition();
461 pp::Point movement = mouse_event.GetMovement();
462 ScalePoint(device_scale_, &point);
463 ScalePoint(device_scale_, &movement);
464 mouse_event = pp::MouseInputEvent(
465 this,
466 event.GetType(),
467 event.GetTimeStamp(),
468 event.GetModifiers(),
469 mouse_event.GetButton(),
470 point,
471 mouse_event.GetClickCount(),
472 movement);
473 event_device_res = mouse_event;
477 pp::InputEvent offset_event(event_device_res);
478 switch (offset_event.GetType()) {
479 case PP_INPUTEVENT_TYPE_MOUSEDOWN:
480 case PP_INPUTEVENT_TYPE_MOUSEUP:
481 case PP_INPUTEVENT_TYPE_MOUSEMOVE:
482 case PP_INPUTEVENT_TYPE_MOUSEENTER:
483 case PP_INPUTEVENT_TYPE_MOUSELEAVE: {
484 pp::MouseInputEvent mouse_event(event_device_res);
485 pp::MouseInputEvent mouse_event_dip(event);
486 pp::Point point = mouse_event.GetPosition();
487 point.set_x(point.x() - available_area_.x());
488 offset_event = pp::MouseInputEvent(
489 this,
490 event.GetType(),
491 event.GetTimeStamp(),
492 event.GetModifiers(),
493 mouse_event.GetButton(),
494 point,
495 mouse_event.GetClickCount(),
496 mouse_event.GetMovement());
497 break;
499 default:
500 break;
502 if (engine_->HandleEvent(offset_event))
503 return true;
505 // TODO(raymes): Implement this scroll behavior in JS:
506 // When click+dragging, scroll the document correctly.
508 // Return true for unhandled clicks so the plugin takes focus.
509 return (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN);
512 void OutOfProcessInstance::DidChangeView(const pp::View& view) {
513 pp::Rect view_rect(view.GetRect());
514 float old_device_scale = device_scale_;
515 float device_scale = view.GetDeviceScale();
516 pp::Size view_device_size(view_rect.width() * device_scale,
517 view_rect.height() * device_scale);
519 if (view_device_size != plugin_size_ || device_scale != device_scale_) {
520 device_scale_ = device_scale;
521 plugin_dip_size_ = view_rect.size();
522 plugin_size_ = view_device_size;
524 paint_manager_.SetSize(view_device_size, device_scale_);
526 pp::Size new_image_data_size = PaintManager::GetNewContextSize(
527 image_data_.size(),
528 plugin_size_);
529 if (new_image_data_size != image_data_.size()) {
530 image_data_ = pp::ImageData(this,
531 PP_IMAGEDATAFORMAT_BGRA_PREMUL,
532 new_image_data_size,
533 false);
534 first_paint_ = true;
537 if (image_data_.is_null()) {
538 DCHECK(plugin_size_.IsEmpty());
539 return;
542 OnGeometryChanged(zoom_, old_device_scale);
545 if (!stop_scrolling_) {
546 pp::Point scroll_offset(view.GetScrollOffset());
547 pp::FloatPoint scroll_offset_float(scroll_offset.x(),
548 scroll_offset.y());
549 scroll_offset_float = BoundScrollOffsetToDocument(scroll_offset_float);
550 engine_->ScrolledToXPosition(scroll_offset_float.x() * device_scale_);
551 engine_->ScrolledToYPosition(scroll_offset_float.y() * device_scale_);
555 void OutOfProcessInstance::GetPrintPresetOptionsFromDocument(
556 PP_PdfPrintPresetOptions_Dev* options) {
557 options->is_scaling_disabled = PP_FromBool(IsPrintScalingDisabled());
558 options->copies = engine_->GetCopiesToPrint();
561 pp::Var OutOfProcessInstance::GetLinkAtPosition(
562 const pp::Point& point) {
563 pp::Point offset_point(point);
564 ScalePoint(device_scale_, &offset_point);
565 offset_point.set_x(offset_point.x() - available_area_.x());
566 return engine_->GetLinkAtPosition(offset_point);
569 pp::Var OutOfProcessInstance::GetSelectedText(bool html) {
570 if (html || !engine_->HasPermission(PDFEngine::PERMISSION_COPY))
571 return pp::Var();
572 return engine_->GetSelectedText();
575 uint32_t OutOfProcessInstance::QuerySupportedPrintOutputFormats() {
576 return engine_->QuerySupportedPrintOutputFormats();
579 int32_t OutOfProcessInstance::PrintBegin(
580 const PP_PrintSettings_Dev& print_settings) {
581 // For us num_pages is always equal to the number of pages in the PDF
582 // document irrespective of the printable area.
583 int32_t ret = engine_->GetNumberOfPages();
584 if (!ret)
585 return 0;
587 uint32_t supported_formats = engine_->QuerySupportedPrintOutputFormats();
588 if ((print_settings.format & supported_formats) == 0)
589 return 0;
591 print_settings_.is_printing = true;
592 print_settings_.pepper_print_settings = print_settings;
593 engine_->PrintBegin();
594 return ret;
597 pp::Resource OutOfProcessInstance::PrintPages(
598 const PP_PrintPageNumberRange_Dev* page_ranges,
599 uint32_t page_range_count) {
600 if (!print_settings_.is_printing)
601 return pp::Resource();
603 print_settings_.print_pages_called_ = true;
604 return engine_->PrintPages(page_ranges, page_range_count,
605 print_settings_.pepper_print_settings);
608 void OutOfProcessInstance::PrintEnd() {
609 if (print_settings_.print_pages_called_)
610 UserMetricsRecordAction("PDF.PrintPage");
611 print_settings_.Clear();
612 engine_->PrintEnd();
615 bool OutOfProcessInstance::IsPrintScalingDisabled() {
616 return !engine_->GetPrintScaling();
619 bool OutOfProcessInstance::StartFind(const std::string& text,
620 bool case_sensitive) {
621 engine_->StartFind(text.c_str(), case_sensitive);
622 return true;
625 void OutOfProcessInstance::SelectFindResult(bool forward) {
626 engine_->SelectFindResult(forward);
629 void OutOfProcessInstance::StopFind() {
630 engine_->StopFind();
631 tickmarks_.clear();
632 SetTickmarks(tickmarks_);
635 void OutOfProcessInstance::OnPaint(
636 const std::vector<pp::Rect>& paint_rects,
637 std::vector<PaintManager::ReadyRect>* ready,
638 std::vector<pp::Rect>* pending) {
639 if (image_data_.is_null()) {
640 DCHECK(plugin_size_.IsEmpty());
641 return;
643 if (first_paint_) {
644 first_paint_ = false;
645 pp::Rect rect = pp::Rect(pp::Point(), image_data_.size());
646 FillRect(rect, kBackgroundColor);
647 ready->push_back(PaintManager::ReadyRect(rect, image_data_, true));
650 if (!received_viewport_message_)
651 return;
653 engine_->PrePaint();
655 for (size_t i = 0; i < paint_rects.size(); i++) {
656 // Intersect with plugin area since there could be pending invalidates from
657 // when the plugin area was larger.
658 pp::Rect rect =
659 paint_rects[i].Intersect(pp::Rect(pp::Point(), plugin_size_));
660 if (rect.IsEmpty())
661 continue;
663 pp::Rect pdf_rect = available_area_.Intersect(rect);
664 if (!pdf_rect.IsEmpty()) {
665 pdf_rect.Offset(available_area_.x() * -1, 0);
667 std::vector<pp::Rect> pdf_ready;
668 std::vector<pp::Rect> pdf_pending;
669 engine_->Paint(pdf_rect, &image_data_, &pdf_ready, &pdf_pending);
670 for (size_t j = 0; j < pdf_ready.size(); ++j) {
671 pdf_ready[j].Offset(available_area_.point());
672 ready->push_back(
673 PaintManager::ReadyRect(pdf_ready[j], image_data_, false));
675 for (size_t j = 0; j < pdf_pending.size(); ++j) {
676 pdf_pending[j].Offset(available_area_.point());
677 pending->push_back(pdf_pending[j]);
681 for (size_t j = 0; j < background_parts_.size(); ++j) {
682 pp::Rect intersection = background_parts_[j].location.Intersect(rect);
683 if (!intersection.IsEmpty()) {
684 FillRect(intersection, background_parts_[j].color);
685 ready->push_back(
686 PaintManager::ReadyRect(intersection, image_data_, false));
691 engine_->PostPaint();
694 void OutOfProcessInstance::DidOpen(int32_t result) {
695 if (result == PP_OK) {
696 if (!engine_->HandleDocumentLoad(embed_loader_)) {
697 document_load_state_ = LOAD_STATE_LOADING;
698 DocumentLoadFailed();
700 } else if (result != PP_ERROR_ABORTED) { // Can happen in tests.
701 NOTREACHED();
702 DocumentLoadFailed();
705 // If it's a progressive load, cancel the stream URL request so that requests
706 // can be made on the original URL.
707 // TODO(raymes): Make this clearer once the in-process plugin is deleted.
708 if (engine_->IsProgressiveLoad()) {
709 pp::VarDictionary message;
710 message.Set(kType, kJSCancelStreamUrlType);
711 PostMessage(message);
715 void OutOfProcessInstance::DidOpenPreview(int32_t result) {
716 if (result == PP_OK) {
717 preview_engine_.reset(PDFEngine::Create(new PreviewModeClient(this)));
718 preview_engine_->HandleDocumentLoad(embed_preview_loader_);
719 } else {
720 NOTREACHED();
724 void OutOfProcessInstance::OnClientTimerFired(int32_t id) {
725 engine_->OnCallback(id);
728 void OutOfProcessInstance::CalculateBackgroundParts() {
729 background_parts_.clear();
730 int left_width = available_area_.x();
731 int right_start = available_area_.right();
732 int right_width = abs(plugin_size_.width() - available_area_.right());
733 int bottom = std::min(available_area_.bottom(), plugin_size_.height());
735 // Add the left, right, and bottom rectangles. Note: we assume only
736 // horizontal centering.
737 BackgroundPart part = {
738 pp::Rect(0, 0, left_width, bottom),
739 kBackgroundColor
741 if (!part.location.IsEmpty())
742 background_parts_.push_back(part);
743 part.location = pp::Rect(right_start, 0, right_width, bottom);
744 if (!part.location.IsEmpty())
745 background_parts_.push_back(part);
746 part.location = pp::Rect(
747 0, bottom, plugin_size_.width(), plugin_size_.height() - bottom);
748 if (!part.location.IsEmpty())
749 background_parts_.push_back(part);
752 int OutOfProcessInstance::GetDocumentPixelWidth() const {
753 return static_cast<int>(ceil(document_size_.width() * zoom_ * device_scale_));
756 int OutOfProcessInstance::GetDocumentPixelHeight() const {
757 return static_cast<int>(
758 ceil(document_size_.height() * zoom_ * device_scale_));
761 void OutOfProcessInstance::FillRect(const pp::Rect& rect, uint32 color) {
762 DCHECK(!image_data_.is_null() || rect.IsEmpty());
763 uint32* buffer_start = static_cast<uint32*>(image_data_.data());
764 int stride = image_data_.stride();
765 uint32* ptr = buffer_start + rect.y() * stride / 4 + rect.x();
766 int height = rect.height();
767 int width = rect.width();
768 for (int y = 0; y < height; ++y) {
769 for (int x = 0; x < width; ++x)
770 *(ptr + x) = color;
771 ptr += stride /4;
775 void OutOfProcessInstance::DocumentSizeUpdated(const pp::Size& size) {
776 document_size_ = size;
778 pp::VarDictionary dimensions;
779 dimensions.Set(kType, kJSDocumentDimensionsType);
780 dimensions.Set(kJSDocumentWidth, pp::Var(document_size_.width()));
781 dimensions.Set(kJSDocumentHeight, pp::Var(document_size_.height()));
782 pp::VarArray page_dimensions_array;
783 int num_pages = engine_->GetNumberOfPages();
784 for (int i = 0; i < num_pages; ++i) {
785 pp::Rect page_rect = engine_->GetPageRect(i);
786 pp::VarDictionary page_dimensions;
787 page_dimensions.Set(kJSPageX, pp::Var(page_rect.x()));
788 page_dimensions.Set(kJSPageY, pp::Var(page_rect.y()));
789 page_dimensions.Set(kJSPageWidth, pp::Var(page_rect.width()));
790 page_dimensions.Set(kJSPageHeight, pp::Var(page_rect.height()));
791 page_dimensions_array.Set(i, page_dimensions);
793 dimensions.Set(kJSPageDimensions, page_dimensions_array);
794 PostMessage(dimensions);
796 OnGeometryChanged(zoom_, device_scale_);
799 void OutOfProcessInstance::Invalidate(const pp::Rect& rect) {
800 pp::Rect offset_rect(rect);
801 offset_rect.Offset(available_area_.point());
802 paint_manager_.InvalidateRect(offset_rect);
805 void OutOfProcessInstance::Scroll(const pp::Point& point) {
806 if (!image_data_.is_null())
807 paint_manager_.ScrollRect(available_area_, point);
810 void OutOfProcessInstance::ScrollToX(int x) {
811 pp::VarDictionary position;
812 position.Set(kType, kJSSetScrollPositionType);
813 position.Set(kJSPositionX, pp::Var(x / device_scale_));
814 PostMessage(position);
817 void OutOfProcessInstance::ScrollToY(int y) {
818 pp::VarDictionary position;
819 position.Set(kType, kJSSetScrollPositionType);
820 position.Set(kJSPositionY, pp::Var(y / device_scale_));
821 PostMessage(position);
824 void OutOfProcessInstance::ScrollToPage(int page) {
825 if (engine_->GetNumberOfPages() == 0)
826 return;
828 pp::VarDictionary message;
829 message.Set(kType, kJSGoToPageType);
830 message.Set(kJSPageNumber, pp::Var(page));
831 PostMessage(message);
834 void OutOfProcessInstance::NavigateTo(const std::string& url,
835 bool open_in_new_tab) {
836 std::string url_copy(url);
838 // Empty |url_copy| is ok, and will effectively be a reload.
839 // Skip the code below so an empty URL does not turn into "http://", which
840 // will cause GURL to fail a DCHECK.
841 if (!url_copy.empty()) {
842 // If |url_copy| starts with '#', then it's for the same URL with a
843 // different URL fragment.
844 if (url_copy[0] == '#') {
845 url_copy = url_ + url_copy;
847 // If there's no scheme, add http.
848 if (url_copy.find("://") == std::string::npos &&
849 url_copy.find("mailto:") == std::string::npos) {
850 url_copy = std::string("http://") + url_copy;
852 // Make sure |url_copy| starts with a valid scheme.
853 if (url_copy.find("http://") != 0 &&
854 url_copy.find("https://") != 0 &&
855 url_copy.find("ftp://") != 0 &&
856 url_copy.find("file://") != 0 &&
857 url_copy.find("mailto:") != 0) {
858 return;
860 // Make sure |url_copy| is not only a scheme.
861 if (url_copy == "http://" ||
862 url_copy == "https://" ||
863 url_copy == "ftp://" ||
864 url_copy == "file://" ||
865 url_copy == "mailto:") {
866 return;
869 pp::VarDictionary message;
870 message.Set(kType, kJSNavigateType);
871 message.Set(kJSNavigateUrl, url_copy);
872 message.Set(kJSNavigateNewTab, open_in_new_tab);
873 PostMessage(message);
876 void OutOfProcessInstance::UpdateCursor(PP_CursorType_Dev cursor) {
877 if (cursor == cursor_)
878 return;
879 cursor_ = cursor;
881 const PPB_CursorControl_Dev* cursor_interface =
882 reinterpret_cast<const PPB_CursorControl_Dev*>(
883 pp::Module::Get()->GetBrowserInterface(PPB_CURSOR_CONTROL_DEV_INTERFACE));
884 if (!cursor_interface) {
885 NOTREACHED();
886 return;
889 cursor_interface->SetCursor(
890 pp_instance(), cursor_, pp::ImageData().pp_resource(), NULL);
893 void OutOfProcessInstance::UpdateTickMarks(
894 const std::vector<pp::Rect>& tickmarks) {
895 float inverse_scale = 1.0f / device_scale_;
896 std::vector<pp::Rect> scaled_tickmarks = tickmarks;
897 for (size_t i = 0; i < scaled_tickmarks.size(); i++)
898 ScaleRect(inverse_scale, &scaled_tickmarks[i]);
899 tickmarks_ = scaled_tickmarks;
902 void OutOfProcessInstance::NotifyNumberOfFindResultsChanged(int total,
903 bool final_result) {
904 // We don't want to spam the renderer with too many updates to the number of
905 // find results. Don't send an update if we sent one too recently. If it's the
906 // final update, we always send it though.
907 if (final_result) {
908 NumberOfFindResultsChanged(total, final_result);
909 SetTickmarks(tickmarks_);
910 return;
913 if (recently_sent_find_update_)
914 return;
916 NumberOfFindResultsChanged(total, final_result);
917 SetTickmarks(tickmarks_);
918 recently_sent_find_update_ = true;
919 pp::CompletionCallback callback =
920 timer_factory_.NewCallback(
921 &OutOfProcessInstance::ResetRecentlySentFindUpdate);
922 pp::Module::Get()->core()->CallOnMainThread(kFindResultCooldownMs,
923 callback, 0);
926 void OutOfProcessInstance::NotifySelectedFindResultChanged(
927 int current_find_index) {
928 DCHECK_GE(current_find_index, 0);
929 SelectedFindResultChanged(current_find_index);
932 void OutOfProcessInstance::GetDocumentPassword(
933 pp::CompletionCallbackWithOutput<pp::Var> callback) {
934 if (password_callback_) {
935 NOTREACHED();
936 return;
939 password_callback_.reset(
940 new pp::CompletionCallbackWithOutput<pp::Var>(callback));
941 pp::VarDictionary message;
942 message.Set(pp::Var(kType), pp::Var(kJSGetPasswordType));
943 PostMessage(message);
946 void OutOfProcessInstance::Alert(const std::string& message) {
947 ModalDialog(this, "alert", message, std::string());
950 bool OutOfProcessInstance::Confirm(const std::string& message) {
951 pp::Var result = ModalDialog(this, "confirm", message, std::string());
952 return result.is_bool() ? result.AsBool() : false;
955 std::string OutOfProcessInstance::Prompt(const std::string& question,
956 const std::string& default_answer) {
957 pp::Var result = ModalDialog(this, "prompt", question, default_answer);
958 return result.is_string() ? result.AsString() : std::string();
961 std::string OutOfProcessInstance::GetURL() {
962 return url_;
965 void OutOfProcessInstance::Email(const std::string& to,
966 const std::string& cc,
967 const std::string& bcc,
968 const std::string& subject,
969 const std::string& body) {
970 pp::VarDictionary message;
971 message.Set(pp::Var(kType), pp::Var(kJSEmailType));
972 message.Set(pp::Var(kJSEmailTo),
973 pp::Var(net::EscapeUrlEncodedData(to, false)));
974 message.Set(pp::Var(kJSEmailCc),
975 pp::Var(net::EscapeUrlEncodedData(cc, false)));
976 message.Set(pp::Var(kJSEmailBcc),
977 pp::Var(net::EscapeUrlEncodedData(bcc, false)));
978 message.Set(pp::Var(kJSEmailSubject),
979 pp::Var(net::EscapeUrlEncodedData(subject, false)));
980 message.Set(pp::Var(kJSEmailBody),
981 pp::Var(net::EscapeUrlEncodedData(body, false)));
982 PostMessage(message);
985 void OutOfProcessInstance::Print() {
986 if (!printing_enabled_ ||
987 (!engine_->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY) &&
988 !engine_->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY))) {
989 return;
992 pp::CompletionCallback callback =
993 print_callback_factory_.NewCallback(&OutOfProcessInstance::OnPrint);
994 pp::Module::Get()->core()->CallOnMainThread(0, callback);
997 void OutOfProcessInstance::OnPrint(int32_t) {
998 pp::PDF::Print(this);
1001 void OutOfProcessInstance::SubmitForm(const std::string& url,
1002 const void* data,
1003 int length) {
1004 pp::URLRequestInfo request(this);
1005 request.SetURL(url);
1006 request.SetMethod("POST");
1007 request.AppendDataToBody(reinterpret_cast<const char*>(data), length);
1009 pp::CompletionCallback callback =
1010 form_factory_.NewCallback(&OutOfProcessInstance::FormDidOpen);
1011 form_loader_ = CreateURLLoaderInternal();
1012 int rv = form_loader_.Open(request, callback);
1013 if (rv != PP_OK_COMPLETIONPENDING)
1014 callback.Run(rv);
1017 void OutOfProcessInstance::FormDidOpen(int32_t result) {
1018 // TODO: inform the user of success/failure.
1019 if (result != PP_OK) {
1020 NOTREACHED();
1024 std::string OutOfProcessInstance::ShowFileSelectionDialog() {
1025 // Seems like very low priority to implement, since the pdf has no way to get
1026 // the file data anyways. Javascript doesn't let you do this synchronously.
1027 NOTREACHED();
1028 return std::string();
1031 pp::URLLoader OutOfProcessInstance::CreateURLLoader() {
1032 if (full_) {
1033 if (!did_call_start_loading_) {
1034 did_call_start_loading_ = true;
1035 pp::PDF::DidStartLoading(this);
1038 // Disable save and print until the document is fully loaded, since they
1039 // would generate an incomplete document. Need to do this each time we
1040 // call DidStartLoading since that resets the content restrictions.
1041 pp::PDF::SetContentRestriction(this, CONTENT_RESTRICTION_SAVE |
1042 CONTENT_RESTRICTION_PRINT);
1045 return CreateURLLoaderInternal();
1048 void OutOfProcessInstance::ScheduleCallback(int id, int delay_in_ms) {
1049 pp::CompletionCallback callback =
1050 timer_factory_.NewCallback(&OutOfProcessInstance::OnClientTimerFired);
1051 pp::Module::Get()->core()->CallOnMainThread(delay_in_ms, callback, id);
1054 void OutOfProcessInstance::SearchString(const base::char16* string,
1055 const base::char16* term,
1056 bool case_sensitive,
1057 std::vector<SearchStringResult>* results) {
1058 PP_PrivateFindResult* pp_results;
1059 int count = 0;
1060 pp::PDF::SearchString(
1061 this,
1062 reinterpret_cast<const unsigned short*>(string),
1063 reinterpret_cast<const unsigned short*>(term),
1064 case_sensitive,
1065 &pp_results,
1066 &count);
1068 results->resize(count);
1069 for (int i = 0; i < count; ++i) {
1070 (*results)[i].start_index = pp_results[i].start_index;
1071 (*results)[i].length = pp_results[i].length;
1074 pp::Memory_Dev memory;
1075 memory.MemFree(pp_results);
1078 void OutOfProcessInstance::DocumentPaintOccurred() {
1081 void OutOfProcessInstance::DocumentLoadComplete(int page_count) {
1082 // Clear focus state for OSK.
1083 FormTextFieldFocusChange(false);
1085 DCHECK(document_load_state_ == LOAD_STATE_LOADING);
1086 document_load_state_ = LOAD_STATE_COMPLETE;
1087 UserMetricsRecordAction("PDF.LoadSuccess");
1089 // Note: If we are in print preview mode the scroll location is retained
1090 // across document loads so we don't want to scroll again and override it.
1091 if (IsPrintPreview()) {
1092 AppendBlankPrintPreviewPages();
1093 OnGeometryChanged(0, 0);
1096 pp::VarDictionary message;
1097 message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1098 message.Set(pp::Var(kJSProgressPercentage), pp::Var(100)) ;
1099 PostMessage(message);
1101 if (!full_)
1102 return;
1104 if (did_call_start_loading_) {
1105 pp::PDF::DidStopLoading(this);
1106 did_call_start_loading_ = false;
1109 int content_restrictions =
1110 CONTENT_RESTRICTION_CUT | CONTENT_RESTRICTION_PASTE;
1111 if (!engine_->HasPermission(PDFEngine::PERMISSION_COPY))
1112 content_restrictions |= CONTENT_RESTRICTION_COPY;
1114 if (!engine_->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY) &&
1115 !engine_->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY)) {
1116 printing_enabled_ = false;
1119 pp::PDF::SetContentRestriction(this, content_restrictions);
1121 uma_.HistogramCustomCounts("PDF.PageCount", page_count,
1122 1, 1000000, 50);
1125 void OutOfProcessInstance::RotateClockwise() {
1126 engine_->RotateClockwise();
1129 void OutOfProcessInstance::RotateCounterclockwise() {
1130 engine_->RotateCounterclockwise();
1133 void OutOfProcessInstance::PreviewDocumentLoadComplete() {
1134 if (preview_document_load_state_ != LOAD_STATE_LOADING ||
1135 preview_pages_info_.empty()) {
1136 return;
1139 preview_document_load_state_ = LOAD_STATE_COMPLETE;
1141 int dest_page_index = preview_pages_info_.front().second;
1142 int src_page_index =
1143 ExtractPrintPreviewPageIndex(preview_pages_info_.front().first);
1144 if (src_page_index > 0 && dest_page_index > -1 && preview_engine_.get())
1145 engine_->AppendPage(preview_engine_.get(), dest_page_index);
1147 preview_pages_info_.pop();
1148 // |print_preview_page_count_| is not updated yet. Do not load any
1149 // other preview pages till we get this information.
1150 if (print_preview_page_count_ == 0)
1151 return;
1153 if (preview_pages_info_.size())
1154 LoadAvailablePreviewPage();
1157 void OutOfProcessInstance::DocumentLoadFailed() {
1158 DCHECK(document_load_state_ == LOAD_STATE_LOADING);
1159 UserMetricsRecordAction("PDF.LoadFailure");
1161 if (did_call_start_loading_) {
1162 pp::PDF::DidStopLoading(this);
1163 did_call_start_loading_ = false;
1166 document_load_state_ = LOAD_STATE_FAILED;
1167 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
1169 // Send a progress value of -1 to indicate a failure.
1170 pp::VarDictionary message;
1171 message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1172 message.Set(pp::Var(kJSProgressPercentage), pp::Var(-1)) ;
1173 PostMessage(message);
1176 void OutOfProcessInstance::PreviewDocumentLoadFailed() {
1177 UserMetricsRecordAction("PDF.PreviewDocumentLoadFailure");
1178 if (preview_document_load_state_ != LOAD_STATE_LOADING ||
1179 preview_pages_info_.empty()) {
1180 return;
1183 preview_document_load_state_ = LOAD_STATE_FAILED;
1184 preview_pages_info_.pop();
1186 if (preview_pages_info_.size())
1187 LoadAvailablePreviewPage();
1190 pp::Instance* OutOfProcessInstance::GetPluginInstance() {
1191 return this;
1194 void OutOfProcessInstance::DocumentHasUnsupportedFeature(
1195 const std::string& feature) {
1196 std::string metric("PDF_Unsupported_");
1197 metric += feature;
1198 if (!unsupported_features_reported_.count(metric)) {
1199 unsupported_features_reported_.insert(metric);
1200 UserMetricsRecordAction(metric);
1203 // Since we use an info bar, only do this for full frame plugins..
1204 if (!full_)
1205 return;
1207 if (told_browser_about_unsupported_feature_)
1208 return;
1209 told_browser_about_unsupported_feature_ = true;
1211 pp::PDF::HasUnsupportedFeature(this);
1214 void OutOfProcessInstance::DocumentLoadProgress(uint32 available,
1215 uint32 doc_size) {
1216 double progress = 0.0;
1217 if (doc_size == 0) {
1218 // Document size is unknown. Use heuristics.
1219 // We'll make progress logarithmic from 0 to 100M.
1220 static const double kFactor = log(100000000.0) / 100.0;
1221 if (available > 0) {
1222 progress = log(static_cast<double>(available)) / kFactor;
1223 if (progress > 100.0)
1224 progress = 100.0;
1226 } else {
1227 progress = 100.0 * static_cast<double>(available) / doc_size;
1230 // We send 100% load progress in DocumentLoadComplete.
1231 if (progress >= 100)
1232 return;
1234 // Avoid sending too many progress messages over PostMessage.
1235 if (progress > last_progress_sent_ + 1) {
1236 last_progress_sent_ = progress;
1237 pp::VarDictionary message;
1238 message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1239 message.Set(pp::Var(kJSProgressPercentage), pp::Var(progress)) ;
1240 PostMessage(message);
1244 void OutOfProcessInstance::FormTextFieldFocusChange(bool in_focus) {
1245 if (!text_input_.get())
1246 return;
1247 if (in_focus)
1248 text_input_->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_TEXT);
1249 else
1250 text_input_->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_NONE);
1253 void OutOfProcessInstance::ResetRecentlySentFindUpdate(int32_t /* unused */) {
1254 recently_sent_find_update_ = false;
1257 void OutOfProcessInstance::OnGeometryChanged(double old_zoom,
1258 float old_device_scale) {
1259 if (zoom_ != old_zoom || device_scale_ != old_device_scale)
1260 engine_->ZoomUpdated(zoom_ * device_scale_);
1262 available_area_ = pp::Rect(plugin_size_);
1263 int doc_width = GetDocumentPixelWidth();
1264 if (doc_width < available_area_.width()) {
1265 available_area_.Offset((available_area_.width() - doc_width) / 2, 0);
1266 available_area_.set_width(doc_width);
1268 int doc_height = GetDocumentPixelHeight();
1269 if (doc_height < available_area_.height()) {
1270 available_area_.set_height(doc_height);
1273 CalculateBackgroundParts();
1274 engine_->PageOffsetUpdated(available_area_.point());
1275 engine_->PluginSizeUpdated(available_area_.size());
1277 if (!document_size_.GetArea())
1278 return;
1279 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
1282 void OutOfProcessInstance::LoadUrl(const std::string& url) {
1283 LoadUrlInternal(url, &embed_loader_, &OutOfProcessInstance::DidOpen);
1286 void OutOfProcessInstance::LoadPreviewUrl(const std::string& url) {
1287 LoadUrlInternal(url, &embed_preview_loader_,
1288 &OutOfProcessInstance::DidOpenPreview);
1291 void OutOfProcessInstance::LoadUrlInternal(
1292 const std::string& url,
1293 pp::URLLoader* loader,
1294 void (OutOfProcessInstance::* method)(int32_t)) {
1295 pp::URLRequestInfo request(this);
1296 request.SetURL(url);
1297 request.SetMethod("GET");
1299 *loader = CreateURLLoaderInternal();
1300 pp::CompletionCallback callback = loader_factory_.NewCallback(method);
1301 int rv = loader->Open(request, callback);
1302 if (rv != PP_OK_COMPLETIONPENDING)
1303 callback.Run(rv);
1306 pp::URLLoader OutOfProcessInstance::CreateURLLoaderInternal() {
1307 pp::URLLoader loader(this);
1309 const PPB_URLLoaderTrusted* trusted_interface =
1310 reinterpret_cast<const PPB_URLLoaderTrusted*>(
1311 pp::Module::Get()->GetBrowserInterface(
1312 PPB_URLLOADERTRUSTED_INTERFACE));
1313 if (trusted_interface)
1314 trusted_interface->GrantUniversalAccess(loader.pp_resource());
1315 return loader;
1318 void OutOfProcessInstance::SetZoom(double scale) {
1319 double old_zoom = zoom_;
1320 zoom_ = scale;
1321 OnGeometryChanged(old_zoom, device_scale_);
1324 std::string OutOfProcessInstance::GetLocalizedString(PP_ResourceString id) {
1325 pp::Var rv(pp::PDF::GetLocalizedString(this, id));
1326 if (!rv.is_string())
1327 return std::string();
1329 return rv.AsString();
1332 void OutOfProcessInstance::AppendBlankPrintPreviewPages() {
1333 if (print_preview_page_count_ == 0)
1334 return;
1335 engine_->AppendBlankPages(print_preview_page_count_);
1336 if (preview_pages_info_.size() > 0)
1337 LoadAvailablePreviewPage();
1340 bool OutOfProcessInstance::IsPrintPreview() {
1341 return IsPrintPreviewUrl(url_);
1344 void OutOfProcessInstance::ProcessPreviewPageInfo(const std::string& url,
1345 int dst_page_index) {
1346 if (!IsPrintPreview())
1347 return;
1349 int src_page_index = ExtractPrintPreviewPageIndex(url);
1350 if (src_page_index < 1)
1351 return;
1353 preview_pages_info_.push(std::make_pair(url, dst_page_index));
1354 LoadAvailablePreviewPage();
1357 void OutOfProcessInstance::LoadAvailablePreviewPage() {
1358 if (preview_pages_info_.size() <= 0 ||
1359 document_load_state_ != LOAD_STATE_COMPLETE) {
1360 return;
1363 std::string url = preview_pages_info_.front().first;
1364 int dst_page_index = preview_pages_info_.front().second;
1365 int src_page_index = ExtractPrintPreviewPageIndex(url);
1366 if (src_page_index < 1 ||
1367 dst_page_index >= print_preview_page_count_ ||
1368 preview_document_load_state_ == LOAD_STATE_LOADING) {
1369 return;
1372 preview_document_load_state_ = LOAD_STATE_LOADING;
1373 LoadPreviewUrl(url);
1376 void OutOfProcessInstance::UserMetricsRecordAction(
1377 const std::string& action) {
1378 // TODO(raymes): Move this function to PPB_UMA_Private.
1379 pp::PDF::UserMetricsRecordAction(this, pp::Var(action));
1382 pp::FloatPoint OutOfProcessInstance::BoundScrollOffsetToDocument(
1383 const pp::FloatPoint& scroll_offset) {
1384 float max_x = document_size_.width() * zoom_ - plugin_dip_size_.width();
1385 float x = std::max(std::min(scroll_offset.x(), max_x), 0.0f);
1386 float max_y = document_size_.height() * zoom_ - plugin_dip_size_.height();
1387 float y = std::max(std::min(scroll_offset.y(), max_y), 0.0f);
1388 return pp::FloatPoint(x, y);
1391 } // namespace chrome_pdf