Fix crash when calling getMsg with no options.
[chromium-blink-merge.git] / pdf / out_of_process_instance.cc
blob49b14ee1c9e913680da93394bccd107011c0aed1
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "pdf/out_of_process_instance.h"
7 #include <algorithm> // for min/max()
8 #define _USE_MATH_DEFINES // for M_PI
9 #include <cmath> // for log() and pow()
10 #include <math.h>
11 #include <list>
13 #include "base/json/json_reader.h"
14 #include "base/json/json_writer.h"
15 #include "base/logging.h"
16 #include "base/strings/string_number_conversions.h"
17 #include "base/strings/string_split.h"
18 #include "base/strings/string_util.h"
19 #include "base/values.h"
20 #include "chrome/common/content_restriction.h"
21 #include "net/base/escape.h"
22 #include "pdf/draw_utils.h"
23 #include "pdf/pdf.h"
24 #include "ppapi/c/dev/ppb_cursor_control_dev.h"
25 #include "ppapi/c/pp_errors.h"
26 #include "ppapi/c/pp_rect.h"
27 #include "ppapi/c/private/ppb_instance_private.h"
28 #include "ppapi/c/private/ppp_pdf.h"
29 #include "ppapi/c/trusted/ppb_url_loader_trusted.h"
30 #include "ppapi/cpp/core.h"
31 #include "ppapi/cpp/dev/memory_dev.h"
32 #include "ppapi/cpp/dev/text_input_dev.h"
33 #include "ppapi/cpp/dev/url_util_dev.h"
34 #include "ppapi/cpp/module.h"
35 #include "ppapi/cpp/point.h"
36 #include "ppapi/cpp/private/pdf.h"
37 #include "ppapi/cpp/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 #if defined(OS_MACOSX)
45 #include "base/mac/mac_util.h"
46 #endif
48 namespace chrome_pdf {
50 // URL reference parameters.
51 // For more possible parameters, see RFC 3778 and the "PDF Open Parameters"
52 // document from Adobe.
53 const char kDelimiters[] = "#&";
54 const char kNamedDest[] = "nameddest";
55 const char kPage[] = "page";
57 const char kChromePrint[] = "chrome://print/";
58 const char kChromeExtension[] =
59 "chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai";
61 // Dictionary Value key names for the document accessibility info
62 const char kAccessibleNumberOfPages[] = "numberOfPages";
63 const char kAccessibleLoaded[] = "loaded";
64 const char kAccessibleCopyable[] = "copyable";
66 // Constants used in handling postMessage() messages.
67 const char* kType = "type";
68 // Viewport message arguments. (Page -> Plugin).
69 const char* kJSViewportType = "viewport";
70 const char* kJSXOffset = "xOffset";
71 const char* kJSYOffset = "yOffset";
72 const char* kJSZoom = "zoom";
73 // Document dimension arguments (Plugin -> Page).
74 const char* kJSDocumentDimensionsType = "documentDimensions";
75 const char* kJSDocumentWidth = "width";
76 const char* kJSDocumentHeight = "height";
77 const char* kJSPageDimensions = "pageDimensions";
78 const char* kJSPageX = "x";
79 const char* kJSPageY = "y";
80 const char* kJSPageWidth = "width";
81 const char* kJSPageHeight = "height";
82 // Document load progress arguments (Plugin -> Page)
83 const char* kJSLoadProgressType = "loadProgress";
84 const char* kJSProgressPercentage = "progress";
85 // Get password arguments (Plugin -> Page)
86 const char* kJSGetPasswordType = "getPassword";
87 // Get password complete arguments (Page -> Plugin)
88 const char* kJSGetPasswordCompleteType = "getPasswordComplete";
89 const char* kJSPassword = "password";
90 // Print (Page -> Plugin)
91 const char* kJSPrintType = "print";
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";
133 const int kFindResultCooldownMs = 100;
135 const double kMinZoom = 0.01;
137 namespace {
139 static const char kPPPPdfInterface[] = PPP_PDF_INTERFACE_1;
141 PP_Var GetLinkAtPosition(PP_Instance instance, PP_Point point) {
142 pp::Var var;
143 void* object = pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
144 if (object) {
145 var = static_cast<OutOfProcessInstance*>(object)->GetLinkAtPosition(
146 pp::Point(point));
148 return var.Detach();
151 void Transform(PP_Instance instance, PP_PrivatePageTransformType type) {
152 void* object =
153 pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
154 if (object) {
155 OutOfProcessInstance* obj_instance =
156 static_cast<OutOfProcessInstance*>(object);
157 switch (type) {
158 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CW:
159 obj_instance->RotateClockwise();
160 break;
161 case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CCW:
162 obj_instance->RotateCounterclockwise();
163 break;
168 const PPP_Pdf ppp_private = {
169 &GetLinkAtPosition,
170 &Transform
173 int ExtractPrintPreviewPageIndex(const std::string& src_url) {
174 // Sample |src_url| format: chrome://print/id/page_index/print.pdf
175 std::vector<std::string> url_substr;
176 base::SplitString(src_url.substr(strlen(kChromePrint)), '/', &url_substr);
177 if (url_substr.size() != 3)
178 return -1;
180 if (url_substr[2] != "print.pdf")
181 return -1;
183 int page_index = 0;
184 if (!base::StringToInt(url_substr[1], &page_index))
185 return -1;
186 return page_index;
189 bool IsPrintPreviewUrl(const std::string& url) {
190 return url.substr(0, strlen(kChromePrint)) == kChromePrint;
193 void ScalePoint(float scale, pp::Point* point) {
194 point->set_x(static_cast<int>(point->x() * scale));
195 point->set_y(static_cast<int>(point->y() * scale));
198 void ScaleRect(float scale, pp::Rect* rect) {
199 int left = static_cast<int>(floorf(rect->x() * scale));
200 int top = static_cast<int>(floorf(rect->y() * scale));
201 int right = static_cast<int>(ceilf((rect->x() + rect->width()) * scale));
202 int bottom = static_cast<int>(ceilf((rect->y() + rect->height()) * scale));
203 rect->SetRect(left, top, right - left, bottom - top);
206 // TODO(raymes): Remove this dependency on VarPrivate/InstancePrivate. It's
207 // needed right now to do a synchronous call to JavaScript, but we could easily
208 // replace this with a custom PPB_PDF function.
209 pp::Var ModalDialog(const pp::Instance* instance,
210 const std::string& type,
211 const std::string& message,
212 const std::string& default_answer) {
213 const PPB_Instance_Private* interface =
214 reinterpret_cast<const PPB_Instance_Private*>(
215 pp::Module::Get()->GetBrowserInterface(
216 PPB_INSTANCE_PRIVATE_INTERFACE));
217 pp::VarPrivate window(pp::PASS_REF,
218 interface->GetWindowObject(instance->pp_instance()));
219 if (default_answer.empty())
220 return window.Call(type, message);
221 else
222 return window.Call(type, message, default_answer);
225 } // namespace
227 OutOfProcessInstance::OutOfProcessInstance(PP_Instance instance)
228 : pp::Instance(instance),
229 pp::Find_Private(this),
230 pp::Printing_Dev(this),
231 pp::Selection_Dev(this),
232 cursor_(PP_CURSORTYPE_POINTER),
233 zoom_(1.0),
234 device_scale_(1.0),
235 printing_enabled_(true),
236 full_(false),
237 paint_manager_(this, this, true),
238 first_paint_(true),
239 document_load_state_(LOAD_STATE_LOADING),
240 preview_document_load_state_(LOAD_STATE_COMPLETE),
241 uma_(this),
242 told_browser_about_unsupported_feature_(false),
243 print_preview_page_count_(0),
244 last_progress_sent_(0),
245 recently_sent_find_update_(false),
246 received_viewport_message_(false) {
247 loader_factory_.Initialize(this);
248 timer_factory_.Initialize(this);
249 form_factory_.Initialize(this);
250 print_callback_factory_.Initialize(this);
251 engine_.reset(PDFEngine::Create(this));
252 pp::Module::Get()->AddPluginInterface(kPPPPdfInterface, &ppp_private);
253 AddPerInstanceObject(kPPPPdfInterface, this);
255 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_MOUSE);
256 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_KEYBOARD);
257 RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_TOUCH);
260 OutOfProcessInstance::~OutOfProcessInstance() {
261 RemovePerInstanceObject(kPPPPdfInterface, this);
264 bool OutOfProcessInstance::Init(uint32_t argc,
265 const char* argn[],
266 const char* argv[]) {
267 // Check if the PDF is being loaded in the PDF chrome extension. We only allow
268 // the plugin to be put into "full frame" mode when it is being loaded in the
269 // extension because this enables some features that we don't want pages
270 // abusing outside of the extension.
271 pp::Var document_url_var = pp::URLUtil_Dev::Get()->GetDocumentURL(this);
272 std::string document_url = document_url_var.is_string() ?
273 document_url_var.AsString() : std::string();
274 std::string extension_url = std::string(kChromeExtension);
275 bool in_extension =
276 !document_url.compare(0, extension_url.size(), extension_url);
278 if (in_extension) {
279 // Check if the plugin is full frame. This is passed in from JS.
280 for (uint32_t i = 0; i < argc; ++i) {
281 if (strcmp(argn[i], "full-frame") == 0) {
282 full_ = true;
283 break;
288 // Only allow the plugin to handle find requests if it is full frame.
289 if (full_)
290 SetPluginToHandleFindRequests();
292 // Send translated strings to the extension where they will be displayed.
293 // TODO(raymes): It would be better to get these in the extension directly
294 // through an API but no such API currently exists.
295 pp::VarDictionary translated_strings;
296 translated_strings.Set(kType, kJSSetTranslatedStringsType);
297 translated_strings.Set(kJSGetPasswordString,
298 GetLocalizedString(PP_RESOURCESTRING_PDFGETPASSWORD));
299 translated_strings.Set(kJSLoadingString,
300 GetLocalizedString(PP_RESOURCESTRING_PDFLOADING));
301 translated_strings.Set(kJSLoadFailedString,
302 GetLocalizedString(PP_RESOURCESTRING_PDFLOAD_FAILED));
303 PostMessage(translated_strings);
305 text_input_.reset(new pp::TextInput_Dev(this));
307 const char* stream_url = NULL;
308 const char* original_url = NULL;
309 const char* headers = NULL;
310 for (uint32_t i = 0; i < argc; ++i) {
311 if (strcmp(argn[i], "src") == 0)
312 original_url = argv[i];
313 else if (strcmp(argn[i], "stream-url") == 0)
314 stream_url = argv[i];
315 else if (strcmp(argn[i], "headers") == 0)
316 headers = argv[i];
319 // TODO(raymes): This is a hack to ensure that if no headers are passed in
320 // then we get the right MIME type. When the in process plugin is removed we
321 // can fix the document loader properly and remove this hack.
322 if (!headers || strcmp(headers, "") == 0)
323 headers = "content-type: application/pdf";
325 if (!original_url)
326 return false;
328 if (!stream_url)
329 stream_url = original_url;
331 // If we're in print preview mode we don't need to load the document yet.
332 // A |kJSResetPrintPreviewModeType| message will be sent to the plugin letting
333 // it know the url to load. By not loading here we avoid loading the same
334 // document twice.
335 if (IsPrintPreviewUrl(original_url))
336 return true;
338 LoadUrl(stream_url);
339 url_ = original_url;
340 return engine_->New(original_url, headers);
343 void OutOfProcessInstance::HandleMessage(const pp::Var& message) {
344 pp::VarDictionary dict(message);
345 if (!dict.Get(kType).is_string()) {
346 NOTREACHED();
347 return;
350 std::string type = dict.Get(kType).AsString();
352 if (type == kJSViewportType &&
353 dict.Get(pp::Var(kJSXOffset)).is_int() &&
354 dict.Get(pp::Var(kJSYOffset)).is_int() &&
355 dict.Get(pp::Var(kJSZoom)).is_number()) {
356 received_viewport_message_ = true;
357 double zoom = dict.Get(pp::Var(kJSZoom)).AsDouble();
358 int x = dict.Get(pp::Var(kJSXOffset)).AsInt();
359 int y = dict.Get(pp::Var(kJSYOffset)).AsInt();
361 // Bound the input parameters.
362 zoom = std::max(kMinZoom, zoom);
363 int max_x = document_size_.width() * zoom - plugin_dip_size_.width();
364 x = std::max(std::min(x, max_x), 0);
365 int max_y = document_size_.height() * zoom - plugin_dip_size_.height();
366 y = std::max(std::min(y, max_y), 0);
368 SetZoom(zoom);
369 engine_->ScrolledToXPosition(x * device_scale_);
370 engine_->ScrolledToYPosition(y * device_scale_);
371 } else if (type == kJSGetPasswordCompleteType &&
372 dict.Get(pp::Var(kJSPassword)).is_string()) {
373 if (password_callback_) {
374 pp::CompletionCallbackWithOutput<pp::Var> callback = *password_callback_;
375 password_callback_.reset();
376 *callback.output() = dict.Get(pp::Var(kJSPassword)).pp_var();
377 callback.Run(PP_OK);
378 } else {
379 NOTREACHED();
381 } else if (type == kJSPrintType) {
382 Print();
383 } else if (type == kJSResetPrintPreviewModeType &&
384 dict.Get(pp::Var(kJSPrintPreviewUrl)).is_string() &&
385 dict.Get(pp::Var(kJSPrintPreviewGrayscale)).is_bool() &&
386 dict.Get(pp::Var(kJSPrintPreviewPageCount)).is_int()) {
387 url_ = dict.Get(pp::Var(kJSPrintPreviewUrl)).AsString();
388 preview_pages_info_ = std::queue<PreviewPageInfo>();
389 preview_document_load_state_ = LOAD_STATE_COMPLETE;
390 document_load_state_ = LOAD_STATE_LOADING;
391 LoadUrl(url_);
392 preview_engine_.reset();
393 engine_.reset(PDFEngine::Create(this));
394 engine_->SetGrayscale(dict.Get(pp::Var(kJSPrintPreviewGrayscale)).AsBool());
395 engine_->New(url_.c_str());
397 print_preview_page_count_ =
398 std::max(dict.Get(pp::Var(kJSPrintPreviewPageCount)).AsInt(), 0);
400 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
401 } else if (type == kJSLoadPreviewPageType &&
402 dict.Get(pp::Var(kJSPreviewPageUrl)).is_string() &&
403 dict.Get(pp::Var(kJSPreviewPageIndex)).is_int()) {
404 ProcessPreviewPageInfo(dict.Get(pp::Var(kJSPreviewPageUrl)).AsString(),
405 dict.Get(pp::Var(kJSPreviewPageIndex)).AsInt());
406 } else if (type == kJSGetAccessibilityJSONType) {
407 pp::VarDictionary reply;
408 reply.Set(pp::Var(kType), pp::Var(kJSGetAccessibilityJSONReplyType));
409 if (dict.Get(pp::Var(kJSAccessibilityPageNumber)).is_int()) {
410 int page = pp::Var(kJSAccessibilityPageNumber).AsInt();
411 reply.Set(pp::Var(kJSAccessibilityJSON),
412 pp::Var(engine_->GetPageAsJSON(page)));
413 } else {
414 base::DictionaryValue node;
415 node.SetInteger(kAccessibleNumberOfPages, engine_->GetNumberOfPages());
416 node.SetBoolean(kAccessibleLoaded,
417 document_load_state_ != LOAD_STATE_LOADING);
418 bool has_permissions =
419 engine_->HasPermission(PDFEngine::PERMISSION_COPY) ||
420 engine_->HasPermission(PDFEngine::PERMISSION_COPY_ACCESSIBLE);
421 node.SetBoolean(kAccessibleCopyable, has_permissions);
422 std::string json;
423 base::JSONWriter::Write(&node, &json);
424 reply.Set(pp::Var(kJSAccessibilityJSON), pp::Var(json));
426 PostMessage(reply);
427 } else {
428 NOTREACHED();
432 bool OutOfProcessInstance::HandleInputEvent(
433 const pp::InputEvent& event) {
434 // To simplify things, convert the event into device coordinates if it is
435 // a mouse event.
436 pp::InputEvent event_device_res(event);
438 pp::MouseInputEvent mouse_event(event);
439 if (!mouse_event.is_null()) {
440 pp::Point point = mouse_event.GetPosition();
441 pp::Point movement = mouse_event.GetMovement();
442 ScalePoint(device_scale_, &point);
443 ScalePoint(device_scale_, &movement);
444 mouse_event = pp::MouseInputEvent(
445 this,
446 event.GetType(),
447 event.GetTimeStamp(),
448 event.GetModifiers(),
449 mouse_event.GetButton(),
450 point,
451 mouse_event.GetClickCount(),
452 movement);
453 event_device_res = mouse_event;
457 pp::InputEvent offset_event(event_device_res);
458 switch (offset_event.GetType()) {
459 case PP_INPUTEVENT_TYPE_MOUSEDOWN:
460 case PP_INPUTEVENT_TYPE_MOUSEUP:
461 case PP_INPUTEVENT_TYPE_MOUSEMOVE:
462 case PP_INPUTEVENT_TYPE_MOUSEENTER:
463 case PP_INPUTEVENT_TYPE_MOUSELEAVE: {
464 pp::MouseInputEvent mouse_event(event_device_res);
465 pp::MouseInputEvent mouse_event_dip(event);
466 pp::Point point = mouse_event.GetPosition();
467 point.set_x(point.x() - available_area_.x());
468 offset_event = pp::MouseInputEvent(
469 this,
470 event.GetType(),
471 event.GetTimeStamp(),
472 event.GetModifiers(),
473 mouse_event.GetButton(),
474 point,
475 mouse_event.GetClickCount(),
476 mouse_event.GetMovement());
477 break;
479 default:
480 break;
482 if (engine_->HandleEvent(offset_event))
483 return true;
485 // TODO(raymes): Implement this scroll behavior in JS:
486 // When click+dragging, scroll the document correctly.
488 if (event.GetType() == PP_INPUTEVENT_TYPE_KEYDOWN &&
489 event.GetModifiers() & kDefaultKeyModifier) {
490 pp::KeyboardInputEvent keyboard_event(event);
491 switch (keyboard_event.GetKeyCode()) {
492 case 'A':
493 engine_->SelectAll();
494 return true;
498 // Return true for unhandled clicks so the plugin takes focus.
499 return (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN);
502 void OutOfProcessInstance::DidChangeView(const pp::View& view) {
503 pp::Rect view_rect(view.GetRect());
504 float old_device_scale = device_scale_;
505 float device_scale = view.GetDeviceScale();
506 pp::Size view_device_size(view_rect.width() * device_scale,
507 view_rect.height() * device_scale);
509 if (view_device_size == plugin_size_ && device_scale == device_scale_)
510 return; // We don't care about the position, only the size.
512 device_scale_ = device_scale;
513 plugin_dip_size_ = view_rect.size();
514 plugin_size_ = view_device_size;
516 paint_manager_.SetSize(view_device_size, device_scale_);
518 pp::Size new_image_data_size = PaintManager::GetNewContextSize(
519 image_data_.size(),
520 plugin_size_);
521 if (new_image_data_size != image_data_.size()) {
522 image_data_ = pp::ImageData(this,
523 PP_IMAGEDATAFORMAT_BGRA_PREMUL,
524 new_image_data_size,
525 false);
526 first_paint_ = true;
529 if (image_data_.is_null()) {
530 DCHECK(plugin_size_.IsEmpty());
531 return;
534 OnGeometryChanged(zoom_, old_device_scale);
537 pp::Var OutOfProcessInstance::GetLinkAtPosition(
538 const pp::Point& point) {
539 pp::Point offset_point(point);
540 ScalePoint(device_scale_, &offset_point);
541 offset_point.set_x(offset_point.x() - available_area_.x());
542 return engine_->GetLinkAtPosition(offset_point);
545 pp::Var OutOfProcessInstance::GetSelectedText(bool html) {
546 if (html || !engine_->HasPermission(PDFEngine::PERMISSION_COPY))
547 return pp::Var();
548 return engine_->GetSelectedText();
551 uint32_t OutOfProcessInstance::QuerySupportedPrintOutputFormats() {
552 return engine_->QuerySupportedPrintOutputFormats();
555 int32_t OutOfProcessInstance::PrintBegin(
556 const PP_PrintSettings_Dev& print_settings) {
557 // For us num_pages is always equal to the number of pages in the PDF
558 // document irrespective of the printable area.
559 int32_t ret = engine_->GetNumberOfPages();
560 if (!ret)
561 return 0;
563 uint32_t supported_formats = engine_->QuerySupportedPrintOutputFormats();
564 if ((print_settings.format & supported_formats) == 0)
565 return 0;
567 print_settings_.is_printing = true;
568 print_settings_.pepper_print_settings = print_settings;
569 engine_->PrintBegin();
570 return ret;
573 pp::Resource OutOfProcessInstance::PrintPages(
574 const PP_PrintPageNumberRange_Dev* page_ranges,
575 uint32_t page_range_count) {
576 if (!print_settings_.is_printing)
577 return pp::Resource();
579 print_settings_.print_pages_called_ = true;
580 return engine_->PrintPages(page_ranges, page_range_count,
581 print_settings_.pepper_print_settings);
584 void OutOfProcessInstance::PrintEnd() {
585 if (print_settings_.print_pages_called_)
586 UserMetricsRecordAction("PDF.PrintPage");
587 print_settings_.Clear();
588 engine_->PrintEnd();
591 bool OutOfProcessInstance::IsPrintScalingDisabled() {
592 return !engine_->GetPrintScaling();
595 bool OutOfProcessInstance::StartFind(const std::string& text,
596 bool case_sensitive) {
597 engine_->StartFind(text.c_str(), case_sensitive);
598 return true;
601 void OutOfProcessInstance::SelectFindResult(bool forward) {
602 engine_->SelectFindResult(forward);
605 void OutOfProcessInstance::StopFind() {
606 engine_->StopFind();
607 tickmarks_.clear();
608 SetTickmarks(tickmarks_);
611 void OutOfProcessInstance::OnPaint(
612 const std::vector<pp::Rect>& paint_rects,
613 std::vector<PaintManager::ReadyRect>* ready,
614 std::vector<pp::Rect>* pending) {
615 if (image_data_.is_null()) {
616 DCHECK(plugin_size_.IsEmpty());
617 return;
619 if (first_paint_) {
620 first_paint_ = false;
621 pp::Rect rect = pp::Rect(pp::Point(), image_data_.size());
622 unsigned int color = kBackgroundColorA << 24 |
623 kBackgroundColorR << 16 |
624 kBackgroundColorG << 8 |
625 kBackgroundColorB;
626 FillRect(rect, color);
627 ready->push_back(PaintManager::ReadyRect(rect, image_data_, true));
630 if (!received_viewport_message_)
631 return;
633 engine_->PrePaint();
635 for (size_t i = 0; i < paint_rects.size(); i++) {
636 // Intersect with plugin area since there could be pending invalidates from
637 // when the plugin area was larger.
638 pp::Rect rect =
639 paint_rects[i].Intersect(pp::Rect(pp::Point(), plugin_size_));
640 if (rect.IsEmpty())
641 continue;
643 pp::Rect pdf_rect = available_area_.Intersect(rect);
644 if (!pdf_rect.IsEmpty()) {
645 pdf_rect.Offset(available_area_.x() * -1, 0);
647 std::vector<pp::Rect> pdf_ready;
648 std::vector<pp::Rect> pdf_pending;
649 engine_->Paint(pdf_rect, &image_data_, &pdf_ready, &pdf_pending);
650 for (size_t j = 0; j < pdf_ready.size(); ++j) {
651 pdf_ready[j].Offset(available_area_.point());
652 ready->push_back(
653 PaintManager::ReadyRect(pdf_ready[j], image_data_, false));
655 for (size_t j = 0; j < pdf_pending.size(); ++j) {
656 pdf_pending[j].Offset(available_area_.point());
657 pending->push_back(pdf_pending[j]);
661 for (size_t j = 0; j < background_parts_.size(); ++j) {
662 pp::Rect intersection = background_parts_[j].location.Intersect(rect);
663 if (!intersection.IsEmpty()) {
664 FillRect(intersection, background_parts_[j].color);
665 ready->push_back(
666 PaintManager::ReadyRect(intersection, image_data_, false));
671 engine_->PostPaint();
674 void OutOfProcessInstance::DidOpen(int32_t result) {
675 if (result == PP_OK) {
676 if (!engine_->HandleDocumentLoad(embed_loader_)) {
677 document_load_state_ = LOAD_STATE_LOADING;
678 DocumentLoadFailed();
680 } else if (result != PP_ERROR_ABORTED) { // Can happen in tests.
681 NOTREACHED();
682 DocumentLoadFailed();
685 // If it's a progressive load, cancel the stream URL request so that requests
686 // can be made on the original URL.
687 // TODO(raymes): Make this clearer once the in-process plugin is deleted.
688 if (engine_->IsProgressiveLoad()) {
689 pp::VarDictionary message;
690 message.Set(kType, kJSCancelStreamUrlType);
691 PostMessage(message);
695 void OutOfProcessInstance::DidOpenPreview(int32_t result) {
696 if (result == PP_OK) {
697 preview_engine_.reset(PDFEngine::Create(new PreviewModeClient(this)));
698 preview_engine_->HandleDocumentLoad(embed_preview_loader_);
699 } else {
700 NOTREACHED();
704 void OutOfProcessInstance::OnClientTimerFired(int32_t id) {
705 engine_->OnCallback(id);
708 void OutOfProcessInstance::CalculateBackgroundParts() {
709 background_parts_.clear();
710 int left_width = available_area_.x();
711 int right_start = available_area_.right();
712 int right_width = abs(plugin_size_.width() - available_area_.right());
713 int bottom = std::min(available_area_.bottom(), plugin_size_.height());
715 // Add the left, right, and bottom rectangles. Note: we assume only
716 // horizontal centering.
717 BackgroundPart part;
718 part.color = kBackgroundColorA << 24 |
719 kBackgroundColorR << 16 |
720 kBackgroundColorG << 8 |
721 kBackgroundColorB;
722 part.location = pp::Rect(0, 0, left_width, bottom);
723 if (!part.location.IsEmpty())
724 background_parts_.push_back(part);
725 part.location = pp::Rect(right_start, 0, right_width, bottom);
726 if (!part.location.IsEmpty())
727 background_parts_.push_back(part);
728 part.location = pp::Rect(
729 0, bottom, plugin_size_.width(), plugin_size_.height() - bottom);
730 if (!part.location.IsEmpty())
731 background_parts_.push_back(part);
734 int OutOfProcessInstance::GetDocumentPixelWidth() const {
735 return static_cast<int>(ceil(document_size_.width() * zoom_ * device_scale_));
738 int OutOfProcessInstance::GetDocumentPixelHeight() const {
739 return static_cast<int>(
740 ceil(document_size_.height() * zoom_ * device_scale_));
743 void OutOfProcessInstance::FillRect(const pp::Rect& rect, unsigned int color) {
744 DCHECK(!image_data_.is_null() || rect.IsEmpty());
745 unsigned int* buffer_start = static_cast<unsigned int*>(image_data_.data());
746 int stride = image_data_.stride();
747 unsigned int* ptr = buffer_start + rect.y() * stride / 4 + rect.x();
748 int height = rect.height();
749 int width = rect.width();
750 for (int y = 0; y < height; ++y) {
751 for (int x = 0; x < width; ++x)
752 *(ptr + x) = color;
753 ptr += stride /4;
757 void OutOfProcessInstance::DocumentSizeUpdated(const pp::Size& size) {
758 document_size_ = size;
760 pp::VarDictionary dimensions;
761 dimensions.Set(kType, kJSDocumentDimensionsType);
762 dimensions.Set(kJSDocumentWidth, pp::Var(document_size_.width()));
763 dimensions.Set(kJSDocumentHeight, pp::Var(document_size_.height()));
764 pp::VarArray page_dimensions_array;
765 int num_pages = engine_->GetNumberOfPages();
766 for (int i = 0; i < num_pages; ++i) {
767 pp::Rect page_rect = engine_->GetPageRect(i);
768 pp::VarDictionary page_dimensions;
769 page_dimensions.Set(kJSPageX, pp::Var(page_rect.x()));
770 page_dimensions.Set(kJSPageY, pp::Var(page_rect.y()));
771 page_dimensions.Set(kJSPageWidth, pp::Var(page_rect.width()));
772 page_dimensions.Set(kJSPageHeight, pp::Var(page_rect.height()));
773 page_dimensions_array.Set(i, page_dimensions);
775 dimensions.Set(kJSPageDimensions, page_dimensions_array);
776 PostMessage(dimensions);
778 OnGeometryChanged(zoom_, device_scale_);
781 void OutOfProcessInstance::Invalidate(const pp::Rect& rect) {
782 pp::Rect offset_rect(rect);
783 offset_rect.Offset(available_area_.point());
784 paint_manager_.InvalidateRect(offset_rect);
787 void OutOfProcessInstance::Scroll(const pp::Point& point) {
788 paint_manager_.ScrollRect(available_area_, point);
791 void OutOfProcessInstance::ScrollToX(int x) {
792 pp::VarDictionary position;
793 position.Set(kType, kJSSetScrollPositionType);
794 position.Set(kJSPositionX, pp::Var(x / device_scale_));
795 PostMessage(position);
798 void OutOfProcessInstance::ScrollToY(int y) {
799 pp::VarDictionary position;
800 position.Set(kType, kJSSetScrollPositionType);
801 position.Set(kJSPositionY, pp::Var(y / device_scale_));
802 PostMessage(position);
805 void OutOfProcessInstance::ScrollToPage(int page) {
806 if (engine_->GetNumberOfPages() == 0)
807 return;
809 pp::VarDictionary message;
810 message.Set(kType, kJSGoToPageType);
811 message.Set(kJSPageNumber, pp::Var(page));
812 PostMessage(message);
815 void OutOfProcessInstance::NavigateTo(const std::string& url,
816 bool open_in_new_tab) {
817 std::string url_copy(url);
819 // Empty |url_copy| is ok, and will effectively be a reload.
820 // Skip the code below so an empty URL does not turn into "http://", which
821 // will cause GURL to fail a DCHECK.
822 if (!url_copy.empty()) {
823 // If there's no scheme, add http.
824 if (url_copy.find("://") == std::string::npos &&
825 url_copy.find("mailto:") == std::string::npos) {
826 url_copy = std::string("http://") + url_copy;
828 // Make sure |url_copy| starts with a valid scheme.
829 if (url_copy.find("http://") != 0 &&
830 url_copy.find("https://") != 0 &&
831 url_copy.find("ftp://") != 0 &&
832 url_copy.find("mailto:") != 0) {
833 return;
835 // Make sure |url_copy| is not only a scheme.
836 if (url_copy == "http://" ||
837 url_copy == "https://" ||
838 url_copy == "ftp://" ||
839 url_copy == "mailto:") {
840 return;
843 pp::VarDictionary message;
844 message.Set(kType, kJSNavigateType);
845 message.Set(kJSNavigateUrl, url_copy);
846 message.Set(kJSNavigateNewTab, open_in_new_tab);
847 PostMessage(message);
850 void OutOfProcessInstance::UpdateCursor(PP_CursorType_Dev cursor) {
851 if (cursor == cursor_)
852 return;
853 cursor_ = cursor;
855 const PPB_CursorControl_Dev* cursor_interface =
856 reinterpret_cast<const PPB_CursorControl_Dev*>(
857 pp::Module::Get()->GetBrowserInterface(PPB_CURSOR_CONTROL_DEV_INTERFACE));
858 if (!cursor_interface) {
859 NOTREACHED();
860 return;
863 cursor_interface->SetCursor(
864 pp_instance(), cursor_, pp::ImageData().pp_resource(), NULL);
867 void OutOfProcessInstance::UpdateTickMarks(
868 const std::vector<pp::Rect>& tickmarks) {
869 float inverse_scale = 1.0f / device_scale_;
870 std::vector<pp::Rect> scaled_tickmarks = tickmarks;
871 for (size_t i = 0; i < scaled_tickmarks.size(); i++)
872 ScaleRect(inverse_scale, &scaled_tickmarks[i]);
873 tickmarks_ = scaled_tickmarks;
876 void OutOfProcessInstance::NotifyNumberOfFindResultsChanged(int total,
877 bool final_result) {
878 // We don't want to spam the renderer with too many updates to the number of
879 // find results. Don't send an update if we sent one too recently. If it's the
880 // final update, we always send it though.
881 if (final_result) {
882 NumberOfFindResultsChanged(total, final_result);
883 SetTickmarks(tickmarks_);
884 return;
887 if (recently_sent_find_update_)
888 return;
890 NumberOfFindResultsChanged(total, final_result);
891 SetTickmarks(tickmarks_);
892 recently_sent_find_update_ = true;
893 pp::CompletionCallback callback =
894 timer_factory_.NewCallback(
895 &OutOfProcessInstance::ResetRecentlySentFindUpdate);
896 pp::Module::Get()->core()->CallOnMainThread(kFindResultCooldownMs,
897 callback, 0);
900 void OutOfProcessInstance::NotifySelectedFindResultChanged(
901 int current_find_index) {
902 SelectedFindResultChanged(current_find_index);
905 void OutOfProcessInstance::GetDocumentPassword(
906 pp::CompletionCallbackWithOutput<pp::Var> callback) {
907 if (password_callback_) {
908 NOTREACHED();
909 return;
912 password_callback_.reset(
913 new pp::CompletionCallbackWithOutput<pp::Var>(callback));
914 pp::VarDictionary message;
915 message.Set(pp::Var(kType), pp::Var(kJSGetPasswordType));
916 PostMessage(message);
919 void OutOfProcessInstance::Alert(const std::string& message) {
920 ModalDialog(this, "alert", message, std::string());
923 bool OutOfProcessInstance::Confirm(const std::string& message) {
924 pp::Var result = ModalDialog(this, "confirm", message, std::string());
925 return result.is_bool() ? result.AsBool() : false;
928 std::string OutOfProcessInstance::Prompt(const std::string& question,
929 const std::string& default_answer) {
930 pp::Var result = ModalDialog(this, "prompt", question, default_answer);
931 return result.is_string() ? result.AsString() : std::string();
934 std::string OutOfProcessInstance::GetURL() {
935 return url_;
938 void OutOfProcessInstance::Email(const std::string& to,
939 const std::string& cc,
940 const std::string& bcc,
941 const std::string& subject,
942 const std::string& body) {
943 pp::VarDictionary message;
944 message.Set(pp::Var(kType), pp::Var(kJSEmailType));
945 message.Set(pp::Var(kJSEmailTo),
946 pp::Var(net::EscapeUrlEncodedData(to, false)));
947 message.Set(pp::Var(kJSEmailCc),
948 pp::Var(net::EscapeUrlEncodedData(cc, false)));
949 message.Set(pp::Var(kJSEmailBcc),
950 pp::Var(net::EscapeUrlEncodedData(bcc, false)));
951 message.Set(pp::Var(kJSEmailSubject),
952 pp::Var(net::EscapeUrlEncodedData(subject, false)));
953 message.Set(pp::Var(kJSEmailBody),
954 pp::Var(net::EscapeUrlEncodedData(body, false)));
955 PostMessage(message);
958 void OutOfProcessInstance::Print() {
959 if (!printing_enabled_ ||
960 (!engine_->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY) &&
961 !engine_->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY))) {
962 return;
965 pp::CompletionCallback callback =
966 print_callback_factory_.NewCallback(&OutOfProcessInstance::OnPrint);
967 pp::Module::Get()->core()->CallOnMainThread(0, callback);
970 void OutOfProcessInstance::OnPrint(int32_t) {
971 pp::PDF::Print(this);
974 void OutOfProcessInstance::SubmitForm(const std::string& url,
975 const void* data,
976 int length) {
977 pp::URLRequestInfo request(this);
978 request.SetURL(url);
979 request.SetMethod("POST");
980 request.AppendDataToBody(reinterpret_cast<const char*>(data), length);
982 pp::CompletionCallback callback =
983 form_factory_.NewCallback(&OutOfProcessInstance::FormDidOpen);
984 form_loader_ = CreateURLLoaderInternal();
985 int rv = form_loader_.Open(request, callback);
986 if (rv != PP_OK_COMPLETIONPENDING)
987 callback.Run(rv);
990 void OutOfProcessInstance::FormDidOpen(int32_t result) {
991 // TODO: inform the user of success/failure.
992 if (result != PP_OK) {
993 NOTREACHED();
997 std::string OutOfProcessInstance::ShowFileSelectionDialog() {
998 // Seems like very low priority to implement, since the pdf has no way to get
999 // the file data anyways. Javascript doesn't let you do this synchronously.
1000 NOTREACHED();
1001 return std::string();
1004 pp::URLLoader OutOfProcessInstance::CreateURLLoader() {
1005 return CreateURLLoaderInternal();
1008 void OutOfProcessInstance::ScheduleCallback(int id, int delay_in_ms) {
1009 pp::CompletionCallback callback =
1010 timer_factory_.NewCallback(&OutOfProcessInstance::OnClientTimerFired);
1011 pp::Module::Get()->core()->CallOnMainThread(delay_in_ms, callback, id);
1014 void OutOfProcessInstance::SearchString(const base::char16* string,
1015 const base::char16* term,
1016 bool case_sensitive,
1017 std::vector<SearchStringResult>* results) {
1018 PP_PrivateFindResult* pp_results;
1019 int count = 0;
1020 pp::PDF::SearchString(
1021 this,
1022 reinterpret_cast<const unsigned short*>(string),
1023 reinterpret_cast<const unsigned short*>(term),
1024 case_sensitive,
1025 &pp_results,
1026 &count);
1028 results->resize(count);
1029 for (int i = 0; i < count; ++i) {
1030 (*results)[i].start_index = pp_results[i].start_index;
1031 (*results)[i].length = pp_results[i].length;
1034 pp::Memory_Dev memory;
1035 memory.MemFree(pp_results);
1038 void OutOfProcessInstance::DocumentPaintOccurred() {
1041 void OutOfProcessInstance::DocumentLoadComplete(int page_count) {
1042 // Clear focus state for OSK.
1043 FormTextFieldFocusChange(false);
1045 DCHECK(document_load_state_ == LOAD_STATE_LOADING);
1046 document_load_state_ = LOAD_STATE_COMPLETE;
1047 UserMetricsRecordAction("PDF.LoadSuccess");
1049 // Note: If we are in print preview mode the scroll location is retained
1050 // across document loads so we don't want to scroll again and override it.
1051 if (!IsPrintPreview()) {
1052 int initial_page = GetInitialPage(url_);
1053 if (initial_page >= 0)
1054 ScrollToPage(initial_page);
1055 } else {
1056 AppendBlankPrintPreviewPages();
1057 OnGeometryChanged(0, 0);
1060 pp::VarDictionary message;
1061 message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1062 message.Set(pp::Var(kJSProgressPercentage), pp::Var(100)) ;
1063 PostMessage(message);
1065 if (!full_)
1066 return;
1068 pp::PDF::DidStopLoading(this);
1070 int content_restrictions =
1071 CONTENT_RESTRICTION_CUT | CONTENT_RESTRICTION_PASTE;
1072 if (!engine_->HasPermission(PDFEngine::PERMISSION_COPY))
1073 content_restrictions |= CONTENT_RESTRICTION_COPY;
1075 if (!engine_->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY) &&
1076 !engine_->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY)) {
1077 printing_enabled_ = false;
1080 pp::PDF::SetContentRestriction(this, content_restrictions);
1082 uma_.HistogramCustomCounts("PDF.PageCount", page_count,
1083 1, 1000000, 50);
1086 void OutOfProcessInstance::RotateClockwise() {
1087 engine_->RotateClockwise();
1090 void OutOfProcessInstance::RotateCounterclockwise() {
1091 engine_->RotateCounterclockwise();
1094 void OutOfProcessInstance::PreviewDocumentLoadComplete() {
1095 if (preview_document_load_state_ != LOAD_STATE_LOADING ||
1096 preview_pages_info_.empty()) {
1097 return;
1100 preview_document_load_state_ = LOAD_STATE_COMPLETE;
1102 int dest_page_index = preview_pages_info_.front().second;
1103 int src_page_index =
1104 ExtractPrintPreviewPageIndex(preview_pages_info_.front().first);
1105 if (src_page_index > 0 && dest_page_index > -1 && preview_engine_.get())
1106 engine_->AppendPage(preview_engine_.get(), dest_page_index);
1108 preview_pages_info_.pop();
1109 // |print_preview_page_count_| is not updated yet. Do not load any
1110 // other preview pages till we get this information.
1111 if (print_preview_page_count_ == 0)
1112 return;
1114 if (preview_pages_info_.size())
1115 LoadAvailablePreviewPage();
1118 void OutOfProcessInstance::DocumentLoadFailed() {
1119 DCHECK(document_load_state_ == LOAD_STATE_LOADING);
1120 UserMetricsRecordAction("PDF.LoadFailure");
1122 if (full_)
1123 pp::PDF::DidStopLoading(this);
1124 document_load_state_ = LOAD_STATE_FAILED;
1126 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
1128 // Send a progress value of -1 to indicate a failure.
1129 pp::VarDictionary message;
1130 message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1131 message.Set(pp::Var(kJSProgressPercentage), pp::Var(-1)) ;
1132 PostMessage(message);
1135 void OutOfProcessInstance::PreviewDocumentLoadFailed() {
1136 UserMetricsRecordAction("PDF.PreviewDocumentLoadFailure");
1137 if (preview_document_load_state_ != LOAD_STATE_LOADING ||
1138 preview_pages_info_.empty()) {
1139 return;
1142 preview_document_load_state_ = LOAD_STATE_FAILED;
1143 preview_pages_info_.pop();
1145 if (preview_pages_info_.size())
1146 LoadAvailablePreviewPage();
1149 pp::Instance* OutOfProcessInstance::GetPluginInstance() {
1150 return this;
1153 void OutOfProcessInstance::DocumentHasUnsupportedFeature(
1154 const std::string& feature) {
1155 std::string metric("PDF_Unsupported_");
1156 metric += feature;
1157 if (!unsupported_features_reported_.count(metric)) {
1158 unsupported_features_reported_.insert(metric);
1159 UserMetricsRecordAction(metric);
1162 // Since we use an info bar, only do this for full frame plugins..
1163 if (!full_)
1164 return;
1166 if (told_browser_about_unsupported_feature_)
1167 return;
1168 told_browser_about_unsupported_feature_ = true;
1170 pp::PDF::HasUnsupportedFeature(this);
1173 void OutOfProcessInstance::DocumentLoadProgress(uint32 available,
1174 uint32 doc_size) {
1175 double progress = 0.0;
1176 if (doc_size == 0) {
1177 // Document size is unknown. Use heuristics.
1178 // We'll make progress logarithmic from 0 to 100M.
1179 static const double kFactor = log(100000000.0) / 100.0;
1180 if (available > 0) {
1181 progress = log(static_cast<double>(available)) / kFactor;
1182 if (progress > 100.0)
1183 progress = 100.0;
1185 } else {
1186 progress = 100.0 * static_cast<double>(available) / doc_size;
1189 // We send 100% load progress in DocumentLoadComplete.
1190 if (progress >= 100)
1191 return;
1193 // Avoid sending too many progress messages over PostMessage.
1194 if (progress > last_progress_sent_ + 1) {
1195 last_progress_sent_ = progress;
1196 pp::VarDictionary message;
1197 message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
1198 message.Set(pp::Var(kJSProgressPercentage), pp::Var(progress)) ;
1199 PostMessage(message);
1203 void OutOfProcessInstance::FormTextFieldFocusChange(bool in_focus) {
1204 if (!text_input_.get())
1205 return;
1206 if (in_focus)
1207 text_input_->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_TEXT);
1208 else
1209 text_input_->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_NONE);
1212 void OutOfProcessInstance::ResetRecentlySentFindUpdate(int32_t /* unused */) {
1213 recently_sent_find_update_ = false;
1216 void OutOfProcessInstance::OnGeometryChanged(double old_zoom,
1217 float old_device_scale) {
1218 if (zoom_ != old_zoom || device_scale_ != old_device_scale)
1219 engine_->ZoomUpdated(zoom_ * device_scale_);
1221 available_area_ = pp::Rect(plugin_size_);
1222 int doc_width = GetDocumentPixelWidth();
1223 if (doc_width < available_area_.width()) {
1224 available_area_.Offset((available_area_.width() - doc_width) / 2, 0);
1225 available_area_.set_width(doc_width);
1227 int doc_height = GetDocumentPixelHeight();
1228 if (doc_height < available_area_.height()) {
1229 available_area_.set_height(doc_height);
1232 CalculateBackgroundParts();
1233 engine_->PageOffsetUpdated(available_area_.point());
1234 engine_->PluginSizeUpdated(available_area_.size());
1236 if (!document_size_.GetArea())
1237 return;
1238 paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
1241 void OutOfProcessInstance::LoadUrl(const std::string& url) {
1242 LoadUrlInternal(url, &embed_loader_, &OutOfProcessInstance::DidOpen);
1245 void OutOfProcessInstance::LoadPreviewUrl(const std::string& url) {
1246 LoadUrlInternal(url, &embed_preview_loader_,
1247 &OutOfProcessInstance::DidOpenPreview);
1250 void OutOfProcessInstance::LoadUrlInternal(
1251 const std::string& url,
1252 pp::URLLoader* loader,
1253 void (OutOfProcessInstance::* method)(int32_t)) {
1254 pp::URLRequestInfo request(this);
1255 request.SetURL(url);
1256 request.SetMethod("GET");
1258 *loader = CreateURLLoaderInternal();
1259 pp::CompletionCallback callback = loader_factory_.NewCallback(method);
1260 int rv = loader->Open(request, callback);
1261 if (rv != PP_OK_COMPLETIONPENDING)
1262 callback.Run(rv);
1265 pp::URLLoader OutOfProcessInstance::CreateURLLoaderInternal() {
1266 if (full_) {
1267 pp::PDF::DidStartLoading(this);
1269 // Disable save and print until the document is fully loaded, since they
1270 // would generate an incomplete document. Need to do this each time we
1271 // call DidStartLoading since that resets the content restrictions.
1272 pp::PDF::SetContentRestriction(this, CONTENT_RESTRICTION_SAVE |
1273 CONTENT_RESTRICTION_PRINT);
1276 pp::URLLoader loader(this);
1278 const PPB_URLLoaderTrusted* trusted_interface =
1279 reinterpret_cast<const PPB_URLLoaderTrusted*>(
1280 pp::Module::Get()->GetBrowserInterface(
1281 PPB_URLLOADERTRUSTED_INTERFACE));
1282 if (trusted_interface)
1283 trusted_interface->GrantUniversalAccess(loader.pp_resource());
1284 return loader;
1287 int OutOfProcessInstance::GetInitialPage(const std::string& url) {
1288 #if defined(OS_NACL)
1289 return -1;
1290 #else
1291 size_t found_idx = url.find('#');
1292 if (found_idx == std::string::npos)
1293 return -1;
1295 const std::string& ref = url.substr(found_idx + 1);
1296 std::vector<std::string> fragments;
1297 Tokenize(ref, kDelimiters, &fragments);
1299 // Page number to return, zero-based.
1300 int page = -1;
1302 // Handle the case of http://foo.com/bar#NAMEDDEST. This is not explicitly
1303 // mentioned except by example in the Adobe "PDF Open Parameters" document.
1304 if ((fragments.size() == 1) && (fragments[0].find('=') == std::string::npos))
1305 return engine_->GetNamedDestinationPage(fragments[0]);
1307 for (size_t i = 0; i < fragments.size(); ++i) {
1308 std::vector<std::string> key_value;
1309 base::SplitString(fragments[i], '=', &key_value);
1310 if (key_value.size() != 2)
1311 continue;
1312 const std::string& key = key_value[0];
1313 const std::string& value = key_value[1];
1315 if (base::strcasecmp(kPage, key.c_str()) == 0) {
1316 // |page_value| is 1-based.
1317 int page_value = -1;
1318 if (base::StringToInt(value, &page_value) && page_value > 0)
1319 page = page_value - 1;
1320 continue;
1322 if (base::strcasecmp(kNamedDest, key.c_str()) == 0) {
1323 // |page_value| is 0-based.
1324 int page_value = engine_->GetNamedDestinationPage(value);
1325 if (page_value >= 0)
1326 page = page_value;
1327 continue;
1330 return page;
1331 #endif
1334 void OutOfProcessInstance::SetZoom(double scale) {
1335 double old_zoom = zoom_;
1336 zoom_ = scale;
1337 OnGeometryChanged(old_zoom, device_scale_);
1340 std::string OutOfProcessInstance::GetLocalizedString(PP_ResourceString id) {
1341 pp::Var rv(pp::PDF::GetLocalizedString(this, id));
1342 if (!rv.is_string())
1343 return std::string();
1345 return rv.AsString();
1348 void OutOfProcessInstance::AppendBlankPrintPreviewPages() {
1349 if (print_preview_page_count_ == 0)
1350 return;
1351 engine_->AppendBlankPages(print_preview_page_count_);
1352 if (preview_pages_info_.size() > 0)
1353 LoadAvailablePreviewPage();
1356 bool OutOfProcessInstance::IsPrintPreview() {
1357 return IsPrintPreviewUrl(url_);
1360 void OutOfProcessInstance::ProcessPreviewPageInfo(const std::string& url,
1361 int dst_page_index) {
1362 if (!IsPrintPreview())
1363 return;
1365 int src_page_index = ExtractPrintPreviewPageIndex(url);
1366 if (src_page_index < 1)
1367 return;
1369 preview_pages_info_.push(std::make_pair(url, dst_page_index));
1370 LoadAvailablePreviewPage();
1373 void OutOfProcessInstance::LoadAvailablePreviewPage() {
1374 if (preview_pages_info_.size() <= 0 ||
1375 document_load_state_ != LOAD_STATE_COMPLETE) {
1376 return;
1379 std::string url = preview_pages_info_.front().first;
1380 int dst_page_index = preview_pages_info_.front().second;
1381 int src_page_index = ExtractPrintPreviewPageIndex(url);
1382 if (src_page_index < 1 ||
1383 dst_page_index >= print_preview_page_count_ ||
1384 preview_document_load_state_ == LOAD_STATE_LOADING) {
1385 return;
1388 preview_document_load_state_ = LOAD_STATE_LOADING;
1389 LoadPreviewUrl(url);
1392 void OutOfProcessInstance::UserMetricsRecordAction(
1393 const std::string& action) {
1394 // TODO(raymes): Move this function to PPB_UMA_Private.
1395 pp::PDF::UserMetricsRecordAction(this, pp::Var(action));
1398 } // namespace chrome_pdf