Upload upstream chromium 67.0.3396
[platform/framework/web/chromium-efl.git] / pdf / out_of_process_instance.h
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.
4
5 #ifndef PDF_OUT_OF_PROCESS_INSTANCE_H_
6 #define PDF_OUT_OF_PROCESS_INSTANCE_H_
7
8 #include <stdint.h>
9 #include <string.h>
10
11 #include <memory>
12 #include <set>
13 #include <string>
14 #include <utility>
15 #include <vector>
16
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/ppb_pdf.h"
23 #include "ppapi/c/private/ppp_pdf.h"
24 #include "ppapi/cpp/dev/printing_dev.h"
25 #include "ppapi/cpp/dev/scriptable_object_deprecated.h"
26 #include "ppapi/cpp/graphics_2d.h"
27 #include "ppapi/cpp/image_data.h"
28 #include "ppapi/cpp/input_event.h"
29 #include "ppapi/cpp/instance.h"
30 #include "ppapi/cpp/private/find_private.h"
31 #include "ppapi/cpp/private/uma_private.h"
32 #include "ppapi/cpp/url_loader.h"
33 #include "ppapi/utility/completion_callback_factory.h"
34
35 namespace pp {
36 class TextInput_Dev;
37 }
38
39 namespace chrome_pdf {
40
41 class OutOfProcessInstance : public pp::Instance,
42                              public pp::Find_Private,
43                              public pp::Printing_Dev,
44                              public PaintManager::Client,
45                              public PDFEngine::Client,
46                              public PreviewModeClient::Client {
47  public:
48   explicit OutOfProcessInstance(PP_Instance instance);
49   ~OutOfProcessInstance() override;
50
51   // pp::Instance implementation.
52   bool Init(uint32_t argc, const char* argn[], const char* argv[]) override;
53   void HandleMessage(const pp::Var& message) override;
54   bool HandleInputEvent(const pp::InputEvent& event) override;
55   void DidChangeView(const pp::View& view) override;
56   void DidChangeFocus(bool has_focus) override;
57
58   // pp::Find_Private implementation.
59   bool StartFind(const std::string& text, bool case_sensitive) override;
60   void SelectFindResult(bool forward) override;
61   void StopFind() override;
62
63   // pp::PaintManager::Client implementation.
64   void OnPaint(const std::vector<pp::Rect>& paint_rects,
65                std::vector<PaintManager::ReadyRect>* ready,
66                std::vector<pp::Rect>* pending) override;
67
68   // pp::Printing_Dev implementation.
69   uint32_t QuerySupportedPrintOutputFormats() override;
70   int32_t PrintBegin(const PP_PrintSettings_Dev& print_settings) override;
71   pp::Resource PrintPages(const PP_PrintPageNumberRange_Dev* page_ranges,
72                           uint32_t page_range_count) override;
73   void PrintEnd() override;
74   bool IsPrintScalingDisabled() override;
75
76   // pp::Private implementation.
77   pp::Var GetLinkAtPosition(const pp::Point& point);
78   void GetPrintPresetOptionsFromDocument(PP_PdfPrintPresetOptions_Dev* options);
79   void EnableAccessibility();
80   void SetCaretPosition(const pp::FloatPoint& position);
81   void MoveRangeSelectionExtent(const pp::FloatPoint& extent);
82   void SetSelectionBounds(const pp::FloatPoint& base,
83                           const pp::FloatPoint& extent);
84   bool CanEditText();
85   void ReplaceSelection(const std::string& text);
86
87   void FlushCallback(int32_t result);
88   void DidOpen(int32_t result);
89   void DidOpenPreview(int32_t result);
90
91   // Called when the timer is fired.
92   void OnClientTimerFired(int32_t id);
93   void OnClientTouchTimerFired(int32_t id);
94
95   // Called to print without re-entrancy issues.
96   void OnPrint(int32_t);
97
98   // PDFEngine::Client implementation.
99   void DocumentSizeUpdated(const pp::Size& size) override;
100   void Invalidate(const pp::Rect& rect) override;
101   void DidScroll(const pp::Point& point) override;
102   void ScrollToX(int x_in_screen_coords) override;
103   void ScrollToY(int y_in_screen_coords, bool compensate_for_toolbar) override;
104   void ScrollBy(const pp::Point& point) override;
105   void ScrollToPage(int page) override;
106   void NavigateTo(const std::string& url,
107                   WindowOpenDisposition disposition) override;
108   void UpdateCursor(PP_CursorType_Dev cursor) override;
109   void UpdateTickMarks(const std::vector<pp::Rect>& tickmarks) override;
110   void NotifyNumberOfFindResultsChanged(int total, bool final_result) override;
111   void NotifySelectedFindResultChanged(int current_find_index) override;
112   void NotifyPageBecameVisible(
113       const PDFEngine::PageFeatures* page_features) override;
114   void GetDocumentPassword(
115       pp::CompletionCallbackWithOutput<pp::Var> callback) 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,
128                   const void* data,
129                   int length) override;
130   pp::URLLoader CreateURLLoader() override;
131   void ScheduleCallback(int id, base::TimeDelta delay) override;
132   void ScheduleTouchTimerCallback(int id, base::TimeDelta delay) override;
133   std::vector<SearchStringResult> SearchString(const base::char16* string,
134                                                const base::char16* term,
135                                                bool case_sensitive) override;
136   void DocumentPaintOccurred() override;
137   void DocumentLoadComplete(
138       const PDFEngine::DocumentFeatures& document_features,
139       uint32_t file_size) override;
140   void DocumentLoadFailed() override;
141   void FontSubstituted() override;
142   pp::Instance* GetPluginInstance() override;
143   void DocumentHasUnsupportedFeature(const std::string& feature) override;
144   void DocumentLoadProgress(uint32_t available, uint32_t doc_size) override;
145   void FormTextFieldFocusChange(bool in_focus) override;
146   bool IsPrintPreview() override;
147   uint32_t GetBackgroundColor() override;
148   void CancelBrowserDownload() override;
149   void IsSelectingChanged(bool is_selecting) override;
150   void SelectionChanged(const pp::Rect& left, const pp::Rect& right) override;
151   void IsEditModeChanged(bool is_edit_mode) override;
152   float GetToolbarHeightInScreenCoords() override;
153
154   // PreviewModeClient::Client implementation.
155   void PreviewDocumentLoadComplete() override;
156   void PreviewDocumentLoadFailed() override;
157
158   // Helper functions for implementing PPP_PDF.
159   void RotateClockwise();
160   void RotateCounterclockwise();
161
162  private:
163   void ResetRecentlySentFindUpdate(int32_t);
164
165   // Called whenever the plugin geometry changes to update the location of the
166   // background parts, and notifies the pdf engine.
167   void OnGeometryChanged(double old_zoom, float old_device_scale);
168
169   // Figures out the location of any background rectangles (i.e. those that
170   // aren't painted by the PDF engine).
171   void CalculateBackgroundParts();
172
173   // Computes document width/height in device pixels, based on current zoom and
174   // device scale
175   int GetDocumentPixelWidth() const;
176   int GetDocumentPixelHeight() const;
177
178   // Draws a rectangle with the specified dimensions and color in our buffer.
179   void FillRect(const pp::Rect& rect, uint32_t color);
180
181   void LoadUrl(const std::string& url, bool is_print_preview);
182
183   // Creates a URL loader and allows it to access all urls, i.e. not just the
184   // frame's origin.
185   pp::URLLoader CreateURLLoaderInternal();
186
187   void FormDidOpen(int32_t result);
188
189   void UserMetricsRecordAction(const std::string& action);
190
191   // Start loading accessibility information.
192   void LoadAccessibility();
193
194   // Send accessibility information about the given page index.
195   void SendNextAccessibilityPage(int32_t page_index);
196
197   // Send the accessibility information about the current viewport. This is
198   // done once when accessibility is first loaded and again when the geometry
199   // changes.
200   void SendAccessibilityViewportInfo();
201
202   enum DocumentLoadState {
203     LOAD_STATE_LOADING,
204     LOAD_STATE_COMPLETE,
205     LOAD_STATE_FAILED,
206   };
207
208   // Set new zoom scale.
209   void SetZoom(double scale);
210
211   // Reduces the document to 1 page and appends |print_preview_page_count_| - 1
212   // blank pages to the document for print preview.
213   void AppendBlankPrintPreviewPages();
214
215   // Process the preview page data information. |src_url| specifies the preview
216   // page data location. The |src_url| is in the format:
217   // chrome://print/id/page_number/print.pdf
218   // |dest_page_index| specifies the blank page index that needs to be replaced
219   // with the new page data.
220   void ProcessPreviewPageInfo(const std::string& src_url, int dest_page_index);
221   // Load the next available preview page into the blank page.
222   void LoadAvailablePreviewPage();
223
224   // Called after a preview page has loaded or failed to load.
225   void LoadNextPreviewPage();
226
227   // Send a notification that the print preview has loaded.
228   void SendPrintPreviewLoadedNotification();
229
230   // Bound the given scroll offset to the document.
231   pp::FloatPoint BoundScrollOffsetToDocument(
232       const pp::FloatPoint& scroll_offset);
233
234   // Wrappers for |uma_| so histogram reporting only occurs when the PDF Viewer
235   // is not being used for print preview.
236   void HistogramCustomCounts(const std::string& name,
237                              int32_t sample,
238                              int32_t min,
239                              int32_t max,
240                              uint32_t bucket_count);
241   void HistogramEnumeration(const std::string& name,
242                             int32_t sample,
243                             int32_t boundary_value);
244
245   // Wrapper for |uma_| so PrintPreview.PdfAction histogram reporting only
246   // occurs when the PDF Viewer is being used inside print preview.
247   void PrintPreviewHistogramEnumeration(int32_t sample);
248
249   pp::ImageData image_data_;
250   // Used when the plugin is embedded in a page and we have to create the loader
251   // ourself.
252   pp::URLLoader embed_loader_;
253   pp::URLLoader embed_preview_loader_;
254
255   PP_CursorType_Dev cursor_;  // The current cursor.
256
257   // Size, in pixels, of plugin rectangle.
258   pp::Size plugin_size_;
259   // Size, in DIPs, of plugin rectangle.
260   pp::Size plugin_dip_size_;
261   // Remaining area, in pixels, to render the pdf in after accounting for
262   // horizontal centering.
263   pp::Rect available_area_;
264   // Size of entire document in pixels (i.e. if each page is 800 pixels high and
265   // there are 10 pages, the height will be 8000).
266   pp::Size document_size_;
267   // The scroll offset in CSS pixels.
268   pp::Point scroll_offset_;
269
270   // Enumeration of pinch states.
271   // This should match PinchPhase enum in
272   // chrome/browser/resources/pdf/viewport.js
273   enum PinchPhase {
274     PINCH_NONE = 0,
275     PINCH_START = 1,
276     PINCH_UPDATE_ZOOM_OUT = 2,
277     PINCH_UPDATE_ZOOM_IN = 3,
278     PINCH_END = 4
279   };
280
281   // Current zoom factor.
282   double zoom_;
283   // True if we request a new bitmap rendering.
284   bool needs_reraster_;
285   // The scroll position for the last raster, before any transformations are
286   // applied.
287   pp::FloatPoint scroll_offset_at_last_raster_;
288   // True if last bitmap was smaller than screen.
289   bool last_bitmap_smaller_;
290   // Current device scale factor. Multiply by |device_scale_| to convert from
291   // viewport to screen coordinates. Divide by |device_scale_| to convert from
292   // screen to viewport coordinates.
293   float device_scale_;
294   // True if the plugin is full-page.
295   bool full_;
296
297   PaintManager paint_manager_;
298
299   struct BackgroundPart {
300     pp::Rect location;
301     uint32_t color;
302   };
303   std::vector<BackgroundPart> background_parts_;
304
305   struct PrintSettings {
306     PrintSettings() { Clear(); }
307     void Clear() {
308       is_printing = false;
309       print_pages_called_ = false;
310       memset(&pepper_print_settings, 0, sizeof(pepper_print_settings));
311     }
312     // This is set to true when PrintBegin is called and false when PrintEnd is
313     // called.
314     bool is_printing;
315     // To know whether this was an actual print operation, so we don't double
316     // count UMA logging.
317     bool print_pages_called_;
318     PP_PrintSettings_Dev pepper_print_settings;
319   };
320
321   PrintSettings print_settings_;
322
323   std::unique_ptr<PDFEngine> engine_;
324
325   // The PreviewModeClient used for print preview. Will be passed to
326   // |preview_engine_|.
327   std::unique_ptr<PreviewModeClient> preview_client_;
328
329   // This engine is used to render the individual preview page data. This is
330   // used only in print preview mode. This will use |PreviewModeClient|
331   // interface which has very limited access to the pp::Instance.
332   std::unique_ptr<PDFEngine> preview_engine_;
333
334   std::string url_;
335
336   // Used for submitting forms.
337   pp::URLLoader form_loader_;
338
339   pp::CompletionCallbackFactory<OutOfProcessInstance> callback_factory_;
340
341   // The callback for receiving the password from the page.
342   std::unique_ptr<pp::CompletionCallbackWithOutput<pp::Var>> password_callback_;
343
344   // True if we haven't painted the plugin viewport yet.
345   bool first_paint_;
346
347   DocumentLoadState document_load_state_;
348   DocumentLoadState preview_document_load_state_;
349
350   // A UMA resource for histogram reporting.
351   pp::UMAPrivate uma_;
352
353   // Used so that we only tell the browser once about an unsupported feature, to
354   // avoid the infobar going up more than once.
355   bool told_browser_about_unsupported_feature_;
356
357   // Keeps track of which unsupported features we reported, so we avoid spamming
358   // the stats if a feature shows up many times per document.
359   std::set<std::string> unsupported_features_reported_;
360
361   // Keeps track of whether font substitution has been reported, so we avoid
362   // spamming the stats if a document requested multiple substitutes.
363   bool font_substitution_reported_;
364
365   // Number of pages in print preview mode for non-PDF source, 0 if print
366   // previewing a PDF, and -1 if not in print preview mode.
367   int print_preview_page_count_;
368
369   // Number of pages loaded in print preview mode for non-PDF source. Always
370   // less than or equal to |print_preview_page_count_|.
371   int print_preview_loaded_page_count_;
372
373   // Used to manage loaded print preview page information. A |PreviewPageInfo|
374   // consists of data source URL string and the page index in the destination
375   // document.
376   // The URL string embeds a page number that can be found with
377   // ExtractPrintPreviewPageIndex(). This page number is always greater than 0.
378   // The page index is always in the range of [0, print_preview_page_count_).
379   using PreviewPageInfo = std::pair<std::string, int>;
380   base::queue<PreviewPageInfo> preview_pages_info_;
381
382   // Used to signal the browser about focus changes to trigger the OSK.
383   // TODO(abodenha@chromium.org) Implement full IME support in the plugin.
384   // http://crbug.com/132565
385   std::unique_ptr<pp::TextInput_Dev> text_input_;
386
387   // The last document load progress value sent to the web page.
388   double last_progress_sent_;
389
390   // Whether an update to the number of find results found was sent less than
391   // |kFindResultCooldownMs| milliseconds ago.
392   bool recently_sent_find_update_;
393
394   // The tickmarks.
395   std::vector<pp::Rect> tickmarks_;
396
397   // Whether the plugin has received a viewport changed message. Nothing should
398   // be painted until this is received.
399   bool received_viewport_message_;
400
401   // If true, this means we told the RenderView that we're starting a network
402   // request so that it can start the throbber. We will tell it again once the
403   // document finishes loading.
404   bool did_call_start_loading_;
405
406   // If this is true, then don't scroll the plugin in response to DidChangeView
407   // messages. This will be true when the extension page is in the process of
408   // zooming the plugin so that flickering doesn't occur while zooming.
409   bool stop_scrolling_;
410
411   // The background color of the PDF viewer.
412   uint32_t background_color_;
413
414   // The blank space above the first page of the document reserved for the
415   // toolbar.
416   int top_toolbar_height_in_viewport_coords_;
417
418   // Whether each page had its features processed.
419   std::vector<bool> page_is_processed_;
420
421   // Annotation types that were already counted for this document.
422   std::set<int> annotation_types_counted_;
423
424   // The current state of accessibility: either off, enabled but waiting
425   // for the document to load, or fully loaded.
426   enum AccessibilityState {
427     ACCESSIBILITY_STATE_OFF,
428     ACCESSIBILITY_STATE_PENDING,  // Enabled but waiting for doc to load.
429     ACCESSIBILITY_STATE_LOADED
430   } accessibility_state_;
431
432   // True if the plugin is loaded in print preview, otherwise false.
433   bool is_print_preview_;
434
435   // Used for UMA. Do not delete entries, and keep in sync with histograms.xml.
436   enum PdfActionBuckets {
437     PRINT_PREVIEW_SHOWN = 0,
438     ROTATE = 1,
439     SELECT_TEXT = 2,
440     UPDATE_ZOOM = 3,
441     PDFACTION_BUCKET_BOUNDARY,
442   };
443
444   // Array indicating what events have been recorded for print preview metrics.
445   bool preview_action_recorded_[PDFACTION_BUCKET_BOUNDARY];
446
447   DISALLOW_COPY_AND_ASSIGN(OutOfProcessInstance);
448 };
449
450 }  // namespace chrome_pdf
451
452 #endif  // PDF_OUT_OF_PROCESS_INSTANCE_H_