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 #ifndef PDF_OUT_OF_PROCESS_INSTANCE_H_
6 #define PDF_OUT_OF_PROCESS_INSTANCE_H_
17 #include "base/containers/queue.h"
18 #include "base/macros.h"
19 #include "pdf/paint_manager.h"
20 #include "pdf/pdf_engine.h"
21 #include "pdf/preview_mode_client.h"
22 #include "ppapi/c/private/ppp_pdf.h"
23 #include "ppapi/cpp/dev/printing_dev.h"
24 #include "ppapi/cpp/image_data.h"
25 #include "ppapi/cpp/instance.h"
26 #include "ppapi/cpp/private/find_private.h"
27 #include "ppapi/cpp/private/uma_private.h"
28 #include "ppapi/cpp/url_loader.h"
29 #include "ppapi/utility/completion_callback_factory.h"
35 namespace chrome_pdf {
37 class OutOfProcessInstance : public pp::Instance,
38 public pp::Find_Private,
39 public pp::Printing_Dev,
40 public PaintManager::Client,
41 public PDFEngine::Client,
42 public PreviewModeClient::Client {
44 explicit OutOfProcessInstance(PP_Instance instance);
45 ~OutOfProcessInstance() override;
47 // pp::Instance implementation.
48 bool Init(uint32_t argc, const char* argn[], const char* argv[]) override;
49 void HandleMessage(const pp::Var& message) override;
50 bool HandleInputEvent(const pp::InputEvent& event) override;
51 void DidChangeView(const pp::View& view) override;
52 void DidChangeFocus(bool has_focus) override;
54 // pp::Find_Private implementation.
55 bool StartFind(const std::string& text, bool case_sensitive) override;
56 void SelectFindResult(bool forward) override;
57 void StopFind() override;
59 // pp::PaintManager::Client implementation.
60 void OnPaint(const std::vector<pp::Rect>& paint_rects,
61 std::vector<PaintManager::ReadyRect>* ready,
62 std::vector<pp::Rect>* pending) override;
64 // pp::Printing_Dev implementation.
65 uint32_t QuerySupportedPrintOutputFormats() override;
66 int32_t PrintBegin(const PP_PrintSettings_Dev& print_settings) override;
67 pp::Resource PrintPages(const PP_PrintPageNumberRange_Dev* page_ranges,
68 uint32_t page_range_count) override;
69 void PrintEnd() override;
70 bool IsPrintScalingDisabled() override;
72 // pp::Private implementation.
73 pp::Var GetLinkAtPosition(const pp::Point& point);
74 void GetPrintPresetOptionsFromDocument(PP_PdfPrintPresetOptions_Dev* options);
75 void EnableAccessibility();
76 void SetCaretPosition(const pp::FloatPoint& position);
77 void MoveRangeSelectionExtent(const pp::FloatPoint& extent);
78 void SetSelectionBounds(const pp::FloatPoint& base,
79 const pp::FloatPoint& extent);
81 bool HasEditableText();
82 void ReplaceSelection(const std::string& text);
87 int32_t PdfPrintBegin(const PP_PrintSettings_Dev* print_settings,
88 const PP_PdfPrintSettings_Dev* pdf_print_settings);
90 void FlushCallback(int32_t result);
91 void DidOpen(int32_t result);
92 void DidOpenPreview(int32_t result);
94 // Called to print without re-entrancy issues.
95 void OnPrint(int32_t);
97 // PDFEngine::Client implementation.
98 void DocumentSizeUpdated(const pp::Size& size) override;
99 void Invalidate(const pp::Rect& rect) override;
100 void DidScroll(const pp::Point& point) override;
101 void ScrollToX(int x_in_screen_coords) override;
102 void ScrollToY(int y_in_screen_coords, bool compensate_for_toolbar) override;
103 void ScrollBy(const pp::Point& point) override;
104 void ScrollToPage(int page) override;
105 void NavigateTo(const std::string& url,
106 WindowOpenDisposition disposition) override;
107 void UpdateCursor(PP_CursorType_Dev cursor) override;
108 void UpdateTickMarks(const std::vector<pp::Rect>& tickmarks) override;
109 void NotifyNumberOfFindResultsChanged(int total, bool final_result) override;
110 void NotifySelectedFindResultChanged(int current_find_index) override;
111 void NotifyPageBecameVisible(
112 const PDFEngine::PageFeatures* page_features) override;
113 void GetDocumentPassword(
114 pp::CompletionCallbackWithOutput<pp::Var> callback) override;
115 void Beep() override;
116 void Alert(const std::string& message) override;
117 bool Confirm(const std::string& message) override;
118 std::string Prompt(const std::string& question,
119 const std::string& default_answer) override;
120 std::string GetURL() override;
121 void Email(const std::string& to,
122 const std::string& cc,
123 const std::string& bcc,
124 const std::string& subject,
125 const std::string& body) override;
126 void Print() override;
127 void SubmitForm(const std::string& url,
129 int length) override;
130 pp::URLLoader CreateURLLoader() override;
131 std::vector<SearchStringResult> SearchString(const base::char16* string,
132 const base::char16* term,
133 bool case_sensitive) override;
134 void DocumentLoadComplete(
135 const PDFEngine::DocumentFeatures& document_features,
136 uint32_t file_size) override;
137 void DocumentLoadFailed() override;
138 void FontSubstituted() override;
139 pp::Instance* GetPluginInstance() override;
140 void DocumentHasUnsupportedFeature(const std::string& feature) override;
141 void DocumentLoadProgress(uint32_t available, uint32_t doc_size) override;
142 void FormTextFieldFocusChange(bool in_focus) override;
143 bool IsPrintPreview() override;
144 uint32_t GetBackgroundColor() override;
145 void CancelBrowserDownload() override;
146 void IsSelectingChanged(bool is_selecting) override;
147 void SelectionChanged(const pp::Rect& left, const pp::Rect& right) override;
148 void IsEditModeChanged(bool is_edit_mode) override;
149 float GetToolbarHeightInScreenCoords() override;
151 // PreviewModeClient::Client implementation.
152 void PreviewDocumentLoadComplete() override;
153 void PreviewDocumentLoadFailed() override;
155 // Helper functions for implementing PPP_PDF.
156 void RotateClockwise();
157 void RotateCounterclockwise();
159 // Creates a file name for saving a PDF file, given the source URL. Exposed
161 static std::string GetFileNameFromUrl(const std::string& url);
164 void ResetRecentlySentFindUpdate(int32_t);
166 // Called whenever the plugin geometry changes to update the location of the
167 // background parts, and notifies the pdf engine.
168 void OnGeometryChanged(double old_zoom, float old_device_scale);
170 // Figures out the location of any background rectangles (i.e. those that
171 // aren't painted by the PDF engine).
172 void CalculateBackgroundParts();
174 // Computes document width/height in device pixels, based on current zoom and
176 int GetDocumentPixelWidth() const;
177 int GetDocumentPixelHeight() const;
179 // Draws a rectangle with the specified dimensions and color in our buffer.
180 void FillRect(const pp::Rect& rect, uint32_t color);
182 void LoadUrl(const std::string& url, bool is_print_preview);
184 // Creates a URL loader and allows it to access all urls, i.e. not just the
186 pp::URLLoader CreateURLLoaderInternal();
188 bool ShouldSaveEdits() const;
189 void SaveToFile(const std::string& token);
190 void SaveToBuffer(const std::string& token);
191 void ConsumeSaveToken(const std::string& token);
193 void FormDidOpen(int32_t result);
195 void UserMetricsRecordAction(const std::string& action);
197 // Start loading accessibility information.
198 void LoadAccessibility();
200 // Send accessibility information about the given page index.
201 void SendNextAccessibilityPage(int32_t page_index);
203 // Send the accessibility information about the current viewport. This is
204 // done once when accessibility is first loaded and again when the geometry
206 void SendAccessibilityViewportInfo();
208 enum DocumentLoadState {
214 // Set new zoom scale.
215 void SetZoom(double scale);
217 // Reduces the document to 1 page and appends |print_preview_page_count_| - 1
218 // blank pages to the document for print preview.
219 void AppendBlankPrintPreviewPages();
221 // Process the preview page data information. |src_url| specifies the preview
222 // page data location. The |src_url| is in the format:
223 // chrome://print/id/page_number/print.pdf
224 // |dest_page_index| specifies the blank page index that needs to be replaced
225 // with the new page data.
226 void ProcessPreviewPageInfo(const std::string& src_url, int dest_page_index);
227 // Load the next available preview page into the blank page.
228 void LoadAvailablePreviewPage();
230 // Called after a preview page has loaded or failed to load.
231 void LoadNextPreviewPage();
233 // Send a notification that the print preview has loaded.
234 void SendPrintPreviewLoadedNotification();
236 // Bound the given scroll offset to the document.
237 pp::FloatPoint BoundScrollOffsetToDocument(
238 const pp::FloatPoint& scroll_offset);
240 // Wrappers for |uma_| so histogram reporting only occurs when the PDF Viewer
241 // is not being used for print preview.
242 void HistogramCustomCounts(const std::string& name,
246 uint32_t bucket_count);
247 void HistogramEnumeration(const std::string& name,
249 int32_t boundary_value);
251 // Wrapper for |uma_| so PrintPreview.PdfAction histogram reporting only
252 // occurs when the PDF Viewer is being used inside print preview.
253 void PrintPreviewHistogramEnumeration(int32_t sample);
255 pp::ImageData image_data_;
256 // Used when the plugin is embedded in a page and we have to create the loader
258 pp::URLLoader embed_loader_;
259 pp::URLLoader embed_preview_loader_;
261 PP_CursorType_Dev cursor_; // The current cursor.
263 // Size, in pixels, of plugin rectangle.
264 pp::Size plugin_size_;
265 // Size, in DIPs, of plugin rectangle.
266 pp::Size plugin_dip_size_;
267 // Remaining area, in pixels, to render the pdf in after accounting for
268 // horizontal centering.
269 pp::Rect available_area_;
270 // Size of entire document in pixels (i.e. if each page is 800 pixels high and
271 // there are 10 pages, the height will be 8000).
272 pp::Size document_size_;
273 // The scroll offset in CSS pixels.
274 pp::Point scroll_offset_;
276 // Enumeration of pinch states.
277 // This should match PinchPhase enum in
278 // chrome/browser/resources/pdf/viewport.js
282 PINCH_UPDATE_ZOOM_OUT = 2,
283 PINCH_UPDATE_ZOOM_IN = 3,
287 // Current zoom factor.
289 // True if we request a new bitmap rendering.
290 bool needs_reraster_;
291 // The scroll position for the last raster, before any transformations are
293 pp::FloatPoint scroll_offset_at_last_raster_;
294 // True if last bitmap was smaller than screen.
295 bool last_bitmap_smaller_;
296 // Current device scale factor. Multiply by |device_scale_| to convert from
297 // viewport to screen coordinates. Divide by |device_scale_| to convert from
298 // screen to viewport coordinates.
300 // True if the plugin is full-page.
303 PaintManager paint_manager_;
305 struct BackgroundPart {
309 std::vector<BackgroundPart> background_parts_;
311 struct PrintSettings {
312 PrintSettings() { Clear(); }
316 // This is set to true when PdfPrintBegin() is called and false when
317 // PrintEnd() is called.
320 // To know whether this was an actual print operation, so we don't double
321 // count UMA logging.
322 bool print_pages_called;
324 // Generic print settings.
325 PP_PrintSettings_Dev pepper_print_settings;
327 // PDF-specific print settings.
328 PP_PdfPrintSettings_Dev pdf_print_settings;
331 PrintSettings print_settings_;
333 std::unique_ptr<PDFEngine> engine_;
335 // The PreviewModeClient used for print preview. Will be passed to
336 // |preview_engine_|.
337 std::unique_ptr<PreviewModeClient> preview_client_;
339 // This engine is used to render the individual preview page data. This is
340 // used only in print preview mode. This will use |PreviewModeClient|
341 // interface which has very limited access to the pp::Instance.
342 std::unique_ptr<PDFEngine> preview_engine_;
346 // Used for submitting forms.
347 pp::URLLoader form_loader_;
349 pp::CompletionCallbackFactory<OutOfProcessInstance> callback_factory_;
351 // The callback for receiving the password from the page.
352 std::unique_ptr<pp::CompletionCallbackWithOutput<pp::Var>> password_callback_;
354 // True if we haven't painted the plugin viewport yet.
357 DocumentLoadState document_load_state_;
358 DocumentLoadState preview_document_load_state_;
360 // A UMA resource for histogram reporting.
363 // Used so that we only tell the browser once about an unsupported feature, to
364 // avoid the infobar going up more than once.
365 bool told_browser_about_unsupported_feature_;
367 // Keeps track of which unsupported features we reported, so we avoid spamming
368 // the stats if a feature shows up many times per document.
369 std::set<std::string> unsupported_features_reported_;
371 // Keeps track of whether font substitution has been reported, so we avoid
372 // spamming the stats if a document requested multiple substitutes.
373 bool font_substitution_reported_;
375 // Number of pages in print preview mode for non-PDF source, 0 if print
376 // previewing a PDF, and -1 if not in print preview mode.
377 int print_preview_page_count_;
379 // Number of pages loaded in print preview mode for non-PDF source. Always
380 // less than or equal to |print_preview_page_count_|.
381 int print_preview_loaded_page_count_;
383 // Used to manage loaded print preview page information. A |PreviewPageInfo|
384 // consists of data source URL string and the page index in the destination
386 // The URL string embeds a page number that can be found with
387 // ExtractPrintPreviewPageIndex(). This page number is always greater than 0.
388 // The page index is always in the range of [0, print_preview_page_count_).
389 using PreviewPageInfo = std::pair<std::string, int>;
390 base::queue<PreviewPageInfo> preview_pages_info_;
392 // Used to signal the browser about focus changes to trigger the OSK.
393 // TODO(abodenha@chromium.org) Implement full IME support in the plugin.
394 // http://crbug.com/132565
395 std::unique_ptr<pp::TextInput_Dev> text_input_;
397 // The last document load progress value sent to the web page.
398 double last_progress_sent_;
400 // Whether an update to the number of find results found was sent less than
401 // |kFindResultCooldownMs| milliseconds ago.
402 bool recently_sent_find_update_;
405 std::vector<pp::Rect> tickmarks_;
407 // Whether the plugin has received a viewport changed message. Nothing should
408 // be painted until this is received.
409 bool received_viewport_message_;
411 // If true, this means we told the RenderView that we're starting a network
412 // request so that it can start the throbber. We will tell it again once the
413 // document finishes loading.
414 bool did_call_start_loading_;
416 // If this is true, then don't scroll the plugin in response to DidChangeView
417 // messages. This will be true when the extension page is in the process of
418 // zooming the plugin so that flickering doesn't occur while zooming.
419 bool stop_scrolling_;
421 // The background color of the PDF viewer.
422 uint32_t background_color_;
424 // The blank space above the first page of the document reserved for the
426 int top_toolbar_height_in_viewport_coords_;
428 // Whether each page had its features processed.
429 std::vector<bool> page_is_processed_;
431 // Annotation types that were already counted for this document.
432 std::set<int> annotation_types_counted_;
434 bool edit_mode_ = false;
436 // The current state of accessibility: either off, enabled but waiting
437 // for the document to load, or fully loaded.
438 enum AccessibilityState {
439 ACCESSIBILITY_STATE_OFF,
440 ACCESSIBILITY_STATE_PENDING, // Enabled but waiting for doc to load.
441 ACCESSIBILITY_STATE_LOADED
442 } accessibility_state_;
444 // True if the plugin is loaded in print preview, otherwise false.
445 bool is_print_preview_;
447 // Used for UMA. Do not delete entries, and keep in sync with histograms.xml.
448 enum PdfActionBuckets {
449 PRINT_PREVIEW_SHOWN = 0,
453 PDFACTION_BUCKET_BOUNDARY,
456 // Array indicating what events have been recorded for print preview metrics.
457 bool preview_action_recorded_[PDFACTION_BUCKET_BOUNDARY];
459 DISALLOW_COPY_AND_ASSIGN(OutOfProcessInstance);
462 } // namespace chrome_pdf
464 #endif // PDF_OUT_OF_PROCESS_INSTANCE_H_