[M108 Migration][HBBTV] Implement ewk_context_register_jsplugin_mime_types API
[platform/framework/web/chromium-efl.git] / pdf / pdf_view_web_plugin.h
1 // Copyright 2020 The Chromium Authors
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_PDF_VIEW_WEB_PLUGIN_H_
6 #define PDF_PDF_VIEW_WEB_PLUGIN_H_
7
8 #include <stdint.h>
9
10 #include <memory>
11 #include <string>
12 #include <vector>
13
14 #include "base/callback_forward.h"
15 #include "base/containers/flat_set.h"
16 #include "base/containers/queue.h"
17 #include "base/i18n/rtl.h"
18 #include "base/memory/raw_ptr.h"
19 #include "base/memory/weak_ptr.h"
20 #include "base/strings/string_piece_forward.h"
21 #include "base/values.h"
22 #include "cc/paint/paint_image.h"
23 #include "mojo/public/cpp/bindings/associated_remote.h"
24 #include "mojo/public/cpp/bindings/receiver.h"
25 #include "pdf/loader/url_loader.h"
26 #include "pdf/mojom/pdf.mojom.h"
27 #include "pdf/pdf_accessibility_action_handler.h"
28 #include "pdf/pdf_engine.h"
29 #include "pdf/pdf_view_plugin_base.h"
30 #include "pdf/pdfium/pdfium_form_filler.h"
31 #include "pdf/post_message_receiver.h"
32 #include "pdf/preview_mode_client.h"
33 #include "pdf/v8_value_converter.h"
34 #include "third_party/blink/public/platform/web_string.h"
35 #include "third_party/blink/public/platform/web_text_input_type.h"
36 #include "third_party/blink/public/web/web_plugin.h"
37 #include "third_party/blink/public/web/web_plugin_container.h"
38 #include "third_party/blink/public/web/web_plugin_params.h"
39 #include "third_party/blink/public/web/web_print_params.h"
40 #include "third_party/skia/include/core/SkColor.h"
41 #include "ui/base/cursor/mojom/cursor_type.mojom-shared.h"
42 #include "ui/gfx/geometry/rect.h"
43 #include "ui/gfx/geometry/size.h"
44 #include "ui/gfx/geometry/vector2d_f.h"
45 #include "v8/include/v8.h"
46
47 namespace blink {
48 class WebAssociatedURLLoader;
49 class WebInputEvent;
50 class WebURL;
51 class WebURLRequest;
52 struct WebAssociatedURLLoaderOptions;
53 struct WebPrintPresetOptions;
54 }  // namespace blink
55
56 namespace gfx {
57 class PointF;
58 class Range;
59 }  // namespace gfx
60
61 namespace net {
62 class SiteForCookies;
63 }  // namespace net
64
65 namespace printing {
66 class MetafileSkia;
67 }  // namespace printing
68
69 namespace chrome_pdf {
70
71 class MetricsHandler;
72 class PDFiumEngine;
73 class PdfAccessibilityDataHandler;
74 class Thumbnail;
75
76 class PdfViewWebPlugin final : public PdfViewPluginBase,
77                                public blink::WebPlugin,
78                                public pdf::mojom::PdfListener,
79                                public UrlLoader::Client,
80                                public PostMessageReceiver::Client,
81                                public PaintManager::Client,
82                                public PdfAccessibilityActionHandler,
83                                public PreviewModeClient::Client {
84  public:
85   // Do not save files larger than 100 MB. This cap should be kept in sync with
86   // and is also enforced in chrome/browser/resources/pdf/pdf_viewer.ts.
87   static constexpr size_t kMaximumSavedFileSize = 100 * 1000 * 1000;
88
89   // Must match `SaveRequestType` in chrome/browser/resources/pdf/constants.ts.
90   enum class SaveRequestType {
91     kAnnotation = 0,
92     kOriginal = 1,
93     kEdited = 2,
94   };
95
96   // Provides services from the plugin's container.
97   class Client : public V8ValueConverter {
98    public:
99     virtual ~Client() = default;
100
101     virtual base::WeakPtr<Client> GetWeakPtr() = 0;
102
103     // Creates a new `PDFiumEngine`.
104     virtual std::unique_ptr<PDFiumEngine> CreateEngine(
105         PDFEngine::Client* client,
106         PDFiumFormFiller::ScriptOption script_option);
107
108     // Passes the plugin container to the client. This is first called in
109     // `Initialize()`, and cleared to null in `Destroy()`. The container may
110     // also be null for testing.
111     virtual void SetPluginContainer(blink::WebPluginContainer* container) = 0;
112
113     // Returns the plugin container set by `SetPluginContainer()`.
114     virtual blink::WebPluginContainer* PluginContainer() = 0;
115
116     // Returrns the document's site for cookies.
117     virtual net::SiteForCookies SiteForCookies() const = 0;
118
119     // Resolves `partial_url` relative to the document's base URL.
120     virtual blink::WebURL CompleteURL(
121         const blink::WebString& partial_url) const = 0;
122
123     // Enqueues a "message" event carrying `message` to the embedder.
124     // Messages are guaranteed to be received in the order that they are sent.
125     // This method is non-blocking.
126     virtual void PostMessage(base::Value::Dict message) {}
127
128     // Invalidates the entire web plugin container and schedules a paint of the
129     // page in it.
130     virtual void Invalidate() = 0;
131
132     // Notifies the container about which touch events the plugin accepts.
133     virtual void RequestTouchEventType(
134         blink::WebPluginContainer::TouchEventRequestType request_type) = 0;
135
136     // Notify the web plugin container about the total matches of a find
137     // request.
138     virtual void ReportFindInPageMatchCount(int identifier,
139                                             int total,
140                                             bool final_update) = 0;
141
142     // Notify the web plugin container about the selected find result in plugin.
143     virtual void ReportFindInPageSelection(int identifier,
144                                            int index,
145                                            bool final_update) = 0;
146
147     // Notify the web plugin container about find result tickmarks.
148     virtual void ReportFindInPageTickmarks(
149         const std::vector<gfx::Rect>& tickmarks) = 0;
150
151     // Returns the device scale factor.
152     virtual float DeviceScaleFactor() = 0;
153
154     // Gets the scroll position.
155     virtual gfx::PointF GetScrollPosition() = 0;
156
157     // Tells the embedder to allow the plugin to handle find requests.
158     virtual void UsePluginAsFindHandler() = 0;
159
160     // Calls underlying WebLocalFrame::SetReferrerForRequest().
161     virtual void SetReferrerForRequest(blink::WebURLRequest& request,
162                                        const blink::WebURL& referrer_url) = 0;
163
164     // Calls underlying WebLocalFrame::Alert().
165     virtual void Alert(const blink::WebString& message) = 0;
166
167     // Calls underlying WebLocalFrame::Confirm().
168     virtual bool Confirm(const blink::WebString& message) = 0;
169
170     // Calls underlying WebLocalFrame::Prompt().
171     virtual blink::WebString Prompt(const blink::WebString& message,
172                                     const blink::WebString& default_value) = 0;
173
174     // Calls underlying WebLocalFrame::TextSelectionChanged().
175     virtual void TextSelectionChanged(const blink::WebString& selection_text,
176                                       uint32_t offset,
177                                       const gfx::Range& range) = 0;
178
179     // Calls underlying WebLocalFrame::CreateAssociatedURLLoader().
180     virtual std::unique_ptr<blink::WebAssociatedURLLoader>
181     CreateAssociatedURLLoader(
182         const blink::WebAssociatedURLLoaderOptions& options) = 0;
183
184     // Notifies the frame widget about the text input type change.
185     virtual void UpdateTextInputState() = 0;
186
187     // Notifies the frame widget about the selection bound change.
188     virtual void UpdateSelectionBounds() = 0;
189
190     // Gets the embedder's origin as a serialized string.
191     virtual std::string GetEmbedderOriginString() = 0;
192
193     // Returns whether the plugin container's frame exists.
194     virtual bool HasFrame() const = 0;
195
196     // Notifies the frame's client that the plugin started loading.
197     virtual void DidStartLoading() = 0;
198
199     // Notifies the frame's client that the plugin stopped loading.
200     virtual void DidStopLoading() = 0;
201
202     // Prints the plugin element.
203     virtual void Print() {}
204
205     // Sends over a string to be recorded by user metrics as a computed action.
206     // When you use this, you need to also update the rules for extracting known
207     // actions in tools/metrics/actions/extract_actions.py.
208     virtual void RecordComputedAction(const std::string& action) {}
209
210     // Creates an implementation of `PdfAccessibilityDataHandler` catered to the
211     // client.
212     virtual std::unique_ptr<PdfAccessibilityDataHandler>
213     CreateAccessibilityDataHandler(
214         PdfAccessibilityActionHandler* action_handler);
215   };
216
217   PdfViewWebPlugin(std::unique_ptr<Client> client,
218                    mojo::AssociatedRemote<pdf::mojom::PdfService> pdf_service,
219                    const blink::WebPluginParams& params);
220   PdfViewWebPlugin(const PdfViewWebPlugin& other) = delete;
221   PdfViewWebPlugin& operator=(const PdfViewWebPlugin& other) = delete;
222
223   // blink::WebPlugin:
224   bool Initialize(blink::WebPluginContainer* container) override;
225   void Destroy() override;
226   blink::WebPluginContainer* Container() const override;
227   v8::Local<v8::Object> V8ScriptableObject(v8::Isolate* isolate) override;
228   bool SupportsKeyboardFocus() const override;
229   void UpdateAllLifecyclePhases(blink::DocumentUpdateReason reason) override;
230   void Paint(cc::PaintCanvas* canvas, const gfx::Rect& rect) override;
231   void UpdateGeometry(const gfx::Rect& window_rect,
232                       const gfx::Rect& clip_rect,
233                       const gfx::Rect& unobscured_rect,
234                       bool is_visible) override;
235   void UpdateFocus(bool focused, blink::mojom::FocusType focus_type) override;
236   void UpdateVisibility(bool visibility) override;
237   blink::WebInputEventResult HandleInputEvent(
238       const blink::WebCoalescedInputEvent& event,
239       ui::Cursor* cursor) override;
240   void DidReceiveResponse(const blink::WebURLResponse& response) override;
241   void DidReceiveData(const char* data, size_t data_length) override;
242   void DidFinishLoading() override;
243   void DidFailLoading(const blink::WebURLError& error) override;
244   bool SupportsPaginatedPrint() override;
245   bool GetPrintPresetOptionsFromDocument(
246       blink::WebPrintPresetOptions* print_preset_options) override;
247   int PrintBegin(const blink::WebPrintParams& print_params) override;
248   void PrintPage(int page_number, cc::PaintCanvas* canvas) override;
249   void PrintEnd() override;
250   bool HasSelection() const override;
251   blink::WebString SelectionAsText() const override;
252   blink::WebString SelectionAsMarkup() const override;
253   bool CanEditText() const override;
254   bool HasEditableText() const override;
255   bool CanUndo() const override;
256   bool CanRedo() const override;
257   bool CanCopy() const override;
258   bool ExecuteEditCommand(const blink::WebString& name,
259                           const blink::WebString& value) override;
260   blink::WebURL LinkAtPosition(const gfx::Point& /*position*/) const override;
261   bool StartFind(const blink::WebString& search_text,
262                  bool case_sensitive,
263                  int identifier) override;
264   void SelectFindResult(bool forward, int identifier) override;
265   void StopFind() override;
266   bool CanRotateView() override;
267   void RotateView(blink::WebPlugin::RotationType type) override;
268
269   bool ShouldDispatchImeEventsToPlugin() override;
270   blink::WebTextInputType GetPluginTextInputType() override;
271   gfx::Rect GetPluginCaretBounds() override;
272   void ImeSetCompositionForPlugin(
273       const blink::WebString& text,
274       const std::vector<ui::ImeTextSpan>& ime_text_spans,
275       const gfx::Range& replacement_range,
276       int selection_start,
277       int selection_end) override;
278   void ImeCommitTextForPlugin(
279       const blink::WebString& text,
280       const std::vector<ui::ImeTextSpan>& ime_text_spans,
281       const gfx::Range& replacement_range,
282       int relative_cursor_pos) override;
283   void ImeFinishComposingTextForPlugin(bool keep_selection) override;
284
285   // PDFEngine::Client:
286   void ProposeDocumentLayout(const DocumentLayout& layout) override;
287   void Invalidate(const gfx::Rect& rect) override;
288   void DidScroll(const gfx::Vector2d& offset) override;
289   void ScrollToX(int x_screen_coords) override;
290   void ScrollToY(int y_screen_coords) override;
291   void ScrollBy(const gfx::Vector2d& delta) override;
292   void ScrollToPage(int page) override;
293   void NavigateTo(const std::string& url,
294                   WindowOpenDisposition disposition) override;
295   void NavigateToDestination(int page,
296                              const float* x,
297                              const float* y,
298                              const float* zoom) override;
299   void UpdateCursor(ui::mojom::CursorType new_cursor_type) override;
300   void UpdateTickMarks(const std::vector<gfx::Rect>& tickmarks) override;
301   void NotifyNumberOfFindResultsChanged(int total, bool final_result) override;
302   void NotifySelectedFindResultChanged(int current_find_index,
303                                        bool final_result) override;
304   void NotifyTouchSelectionOccurred() override;
305   void GetDocumentPassword(
306       base::OnceCallback<void(const std::string&)> callback) override;
307   void Beep() override;
308   void Alert(const std::string& message) override;
309   bool Confirm(const std::string& message) override;
310   std::string Prompt(const std::string& question,
311                      const std::string& default_answer) override;
312   std::string GetURL() override;
313   void Email(const std::string& to,
314              const std::string& cc,
315              const std::string& bcc,
316              const std::string& subject,
317              const std::string& body) override;
318   void Print() override;
319   void SubmitForm(const std::string& url,
320                   const void* data,
321                   int length) override;
322   std::unique_ptr<UrlLoader> CreateUrlLoader() override;
323   std::vector<SearchStringResult> SearchString(const char16_t* string,
324                                                const char16_t* term,
325                                                bool case_sensitive) override;
326   void DocumentHasUnsupportedFeature(const std::string& feature) override;
327   void DocumentLoadProgress(uint32_t available, uint32_t doc_size) override;
328   void FormFieldFocusChange(PDFEngine::FocusFieldType type) override;
329   bool IsPrintPreview() const override;
330   SkColor GetBackgroundColor() const override;
331   void SetIsSelecting(bool is_selecting) override;
332   void CaretChanged(const gfx::Rect& caret_rect) override;
333   void EnteredEditMode() override;
334   void DocumentFocusChanged(bool document_has_focus) override;
335   void SetSelectedText(const std::string& selected_text) override;
336   void SetLinkUnderCursor(const std::string& link_under_cursor) override;
337   bool IsValidLink(const std::string& url) override;
338
339   // pdf::mojom::PdfListener:
340   void SetCaretPosition(const gfx::PointF& position) override;
341   void MoveRangeSelectionExtent(const gfx::PointF& extent) override;
342   void SetSelectionBounds(const gfx::PointF& base,
343                           const gfx::PointF& extent) override;
344
345   // UrlLoader::Client:
346   bool IsValid() const override;
347   blink::WebURL CompleteURL(const blink::WebString& partial_url) const override;
348   net::SiteForCookies SiteForCookies() const override;
349   void SetReferrerForRequest(blink::WebURLRequest& request,
350                              const blink::WebURL& referrer_url) override;
351   std::unique_ptr<blink::WebAssociatedURLLoader> CreateAssociatedURLLoader(
352       const blink::WebAssociatedURLLoaderOptions& options) override;
353
354   // PostMessageReceiver::Client:
355   void OnMessage(const base::Value::Dict& message) override;
356
357   // PaintManager::Client:
358   void InvalidatePluginContainer() override;
359   void OnPaint(const std::vector<gfx::Rect>& paint_rects,
360                std::vector<PaintReadyRect>& ready,
361                std::vector<gfx::Rect>& pending) override;
362   void UpdateSnapshot(sk_sp<SkImage> snapshot) override;
363   void UpdateScale(float scale) override;
364   void UpdateLayerTransform(float scale,
365                             const gfx::Vector2dF& translate) override;
366
367   // PdfAccessibilityActionHandler:
368   void EnableAccessibility() override;
369   void HandleAccessibilityAction(
370       const AccessibilityActionData& action_data) override;
371
372   // PreviewModeClient::Client:
373   void PreviewDocumentLoadComplete() override;
374   void PreviewDocumentLoadFailed() override;
375
376   // Initializes the plugin for testing, bypassing certain consistency checks.
377   bool InitializeForTesting();
378
379   const gfx::Rect& GetPluginRectForTesting() const { return plugin_rect_; }
380
381   float GetDeviceScaleForTesting() const { return device_scale_; }
382
383   DocumentLoadState document_load_state_for_testing() const {
384     return document_load_state_;
385   }
386
387   int GetContentRestrictionsForTesting() const {
388     return GetContentRestrictions();
389   }
390
391   AccessibilityDocInfo GetAccessibilityDocInfoForTesting() const {
392     return GetAccessibilityDocInfo();
393   }
394
395  protected:
396   // PdfViewPluginBase:
397   const PDFiumEngine* engine() const override;
398   PDFiumEngine* engine() override;
399   base::WeakPtr<PdfViewPluginBase> GetWeakPtr() override;
400   void OnPrintPreviewLoaded() override;
401   void OnDocumentLoadComplete() override;
402   void SendLoadingProgress(double percentage) override;
403   void SetAccessibilityDocInfo(AccessibilityDocInfo doc_info) override;
404   void SetAccessibilityPageInfo(AccessibilityPageInfo page_info,
405                                 std::vector<AccessibilityTextRunInfo> text_runs,
406                                 std::vector<AccessibilityCharInfo> chars,
407                                 AccessibilityPageObjects page_objects) override;
408   void SetAccessibilityViewportInfo(
409       AccessibilityViewportInfo viewport_info) override;
410   void SetContentRestrictions(int content_restrictions) override;
411   void DidStartLoading() override;
412   void DidStopLoading() override;
413   void NotifySelectionChanged(const gfx::PointF& left,
414                               int left_height,
415                               const gfx::PointF& right,
416                               int right_height) override;
417   void UserMetricsRecordAction(const std::string& action) override;
418   PaintManager& paint_manager() override;
419   const gfx::Rect& available_area() const override;
420   double zoom() const override;
421   bool full_frame() const override;
422   const gfx::Rect& plugin_rect() const override;
423   float device_scale() const override;
424   DocumentLoadState document_load_state() const override;
425   void set_document_load_state(DocumentLoadState state) override;
426   AccessibilityState accessibility_state() const override;
427   void set_accessibility_state(AccessibilityState state) override;
428   int32_t next_accessibility_page_index() const override;
429   void increment_next_accessibility_page_index() override;
430   void reset_next_accessibility_page_index() override;
431
432  private:
433   // Callback that runs after `LoadUrl()`. The `loader` is the loader used to
434   // load the URL, and `result` is the result code for the load.
435   using LoadUrlCallback =
436       base::OnceCallback<void(std::unique_ptr<UrlLoader> loader,
437                               int32_t result)>;
438
439   struct BackgroundPart {
440     gfx::Rect location;
441     uint32_t color;
442   };
443
444   // Metadata about an available preview page.
445   struct PreviewPageInfo {
446     // Data source URL.
447     std::string url;
448
449     // Page index in destination document.
450     int dest_page_index = -1;
451   };
452
453   // Call `Destroy()` instead.
454   ~PdfViewWebPlugin() override;
455
456   bool InitializeCommon();
457
458   // Sends whether to do smooth scrolling.
459   void SendSetSmoothScrolling();
460
461   // Handles `LoadUrl()` result for the main document.
462   void DidOpen(std::unique_ptr<UrlLoader> loader, int32_t result);
463
464   // Updates the scroll position, which is in CSS pixels relative to the
465   // top-left corner.
466   void UpdateScroll(const gfx::PointF& scroll_position);
467
468   // Loads `url`, invoking `callback` on receiving the initial response.
469   void LoadUrl(base::StringPiece url, LoadUrlCallback callback);
470
471   // Handles `Open()` result for `form_loader_`.
472   void DidFormOpen(int32_t result);
473
474   // Message handlers.
475   void HandleDisplayAnnotationsMessage(const base::Value::Dict& message);
476   void HandleGetNamedDestinationMessage(const base::Value::Dict& message);
477   void HandleGetPasswordCompleteMessage(const base::Value::Dict& message);
478   void HandleGetSelectedTextMessage(const base::Value::Dict& message);
479   void HandleGetThumbnailMessage(const base::Value::Dict& message);
480   void HandlePrintMessage(const base::Value::Dict& /*message*/);
481   void HandleRotateClockwiseMessage(const base::Value::Dict& /*message*/);
482   void HandleRotateCounterclockwiseMessage(
483       const base::Value::Dict& /*message*/);
484   void HandleSaveAttachmentMessage(const base::Value::Dict& message);
485   void HandleSaveMessage(const base::Value::Dict& message);
486   void HandleSelectAllMessage(const base::Value::Dict& /*message*/);
487   void HandleSetBackgroundColorMessage(const base::Value::Dict& message);
488   void HandleSetPresentationModeMessage(const base::Value::Dict& message);
489   void HandleSetTwoUpViewMessage(const base::Value::Dict& message);
490   void HandleStopScrollingMessage(const base::Value::Dict& message);
491   void HandleViewportMessage(const base::Value::Dict& message);
492
493   void SaveToBuffer(const std::string& token);
494   void SaveToFile(const std::string& token);
495
496   // Converts a scroll offset (which is relative to a UI direction-dependent
497   // scroll origin) to a scroll position (which is always relative to the
498   // top-left corner).
499   gfx::PointF GetScrollPositionFromOffset(
500       const gfx::Vector2dF& scroll_offset) const;
501
502   // Paints the given invalid area of the plugin to the given graphics device.
503   // PaintManager::Client::OnPaint() should be its only caller.
504   void DoPaint(const std::vector<gfx::Rect>& paint_rects,
505                std::vector<PaintReadyRect>& ready,
506                std::vector<gfx::Rect>& pending);
507
508   // The preparation when painting on the image data buffer for the first
509   // time.
510   void PrepareForFirstPaint(std::vector<PaintReadyRect>& ready);
511
512   // Updates the available area and the background parts, notifies the PDF
513   // engine, and updates the accessibility information.
514   void OnGeometryChanged(double old_zoom, float old_device_scale);
515
516   // A helper of OnGeometryChanged() which updates the available area and
517   // the background parts, and notifies the PDF engine of geometry changes.
518   void RecalculateAreas(double old_zoom, float old_device_scale);
519
520   // Figures out the location of any background rectangles (i.e. those that
521   // aren't painted by the PDF engine).
522   void CalculateBackgroundParts();
523
524   // Computes document width/height in device pixels, based on current zoom and
525   // device scale
526   int GetDocumentPixelWidth() const;
527   int GetDocumentPixelHeight() const;
528
529   // Schedules invalidation tasks after painting finishes.
530   void InvalidateAfterPaintDone();
531
532   // Callback to clear deferred invalidates after painting finishes.
533   void ClearDeferredInvalidates();
534
535   // Recalculates values that depend on scale factors.
536   void UpdateScaledValues();
537
538   void OnViewportChanged(const gfx::Rect& new_plugin_rect_in_css_pixel,
539                          float new_device_scale);
540
541   // Text editing methods.
542   bool SelectAll();
543   bool Cut();
544   bool Paste(const blink::WebString& value);
545   bool Undo();
546   bool Redo();
547
548   bool HandleWebInputEvent(const blink::WebInputEvent& event);
549
550   // Helper method for converting IME text to input events.
551   // TODO(crbug.com/1253665): Consider handling composition events.
552   void HandleImeCommit(const blink::WebString& text);
553
554   // Callback to print without re-entrancy issues. The callback prevents the
555   // invocation of printing in the middle of an event handler, which is risky;
556   // see crbug.com/66334.
557   // TODO(crbug.com/1217012): Re-evaluate the need for a callback when parts of
558   // the plugin are moved off the main thread.
559   void OnInvokePrintDialog();
560
561   void ResetRecentlySentFindUpdate();
562
563   // Records metrics about the document metadata.
564   void RecordDocumentMetrics();
565
566   // Sends the attachments data.
567   void SendAttachments();
568
569   // Sends the bookmarks data.
570   void SendBookmarks();
571
572   // Send document metadata data.
573   void SendMetadata();
574
575   // Handles message for resetting Print Preview.
576   void HandleResetPrintPreviewModeMessage(const base::Value::Dict& message);
577
578   // Handles message for loading a preview page.
579   void HandleLoadPreviewPageMessage(const base::Value::Dict& message);
580
581   // Starts loading the next available preview page into a blank page.
582   void LoadAvailablePreviewPage();
583
584   // Handles `LoadUrl()` result for a preview page.
585   void DidOpenPreview(std::unique_ptr<UrlLoader> loader, int32_t result);
586
587   // Continues loading the next preview page.
588   void LoadNextPreviewPage();
589
590   // Sends a notification that the print preview has loaded.
591   void SendPrintPreviewLoadedNotification();
592
593   // Sends the thumbnail image data.
594   void SendThumbnail(base::Value::Dict reply, Thumbnail thumbnail);
595
596   // Converts `frame_coordinates` to PDF coordinates.
597   gfx::Point FrameToPdfCoordinates(const gfx::PointF& frame_coordinates) const;
598
599   blink::WebString selected_text_;
600
601   std::unique_ptr<Client> const client_;
602
603   // Used to access the services provided by the browser.
604   mojo::AssociatedRemote<pdf::mojom::PdfService> const pdf_service_;
605
606   mojo::Receiver<pdf::mojom::PdfListener> listener_receiver_{this};
607
608   std::unique_ptr<PDFiumEngine> engine_;
609
610   // The URL of the PDF document.
611   std::string url_;
612
613   // The callback for receiving the password from the page.
614   base::OnceCallback<void(const std::string&)> password_callback_;
615
616   // The current cursor type.
617   ui::mojom::CursorType cursor_type_ = ui::mojom::CursorType::kPointer;
618
619   blink::WebTextInputType text_input_type_ =
620       blink::WebTextInputType::kWebTextInputTypeNone;
621
622   gfx::Rect caret_rect_;
623
624   blink::WebString composition_text_;
625
626   // Whether the plugin element currently has focus.
627   bool has_focus_ = false;
628
629   blink::WebPluginParams initial_params_;
630
631   v8::Persistent<v8::Object> scriptable_receiver_;
632
633   PaintManager paint_manager_{this};
634
635   // Image data buffer for painting.
636   SkBitmap image_data_;
637
638   // The current image snapshot.
639   cc::PaintImage snapshot_;
640
641   // Translate from snapshot to device pixels.
642   gfx::Vector2dF snapshot_translate_;
643
644   // Scale from snapshot to device pixels.
645   float snapshot_scale_ = 1.0f;
646
647   // The viewport coordinates to DIP (device-independent pixel) ratio.
648   float viewport_to_dip_scale_ = 1.0f;
649
650   // The device pixel to CSS pixel ratio.
651   float device_to_css_scale_ = 1.0f;
652
653   // Combined translate from snapshot to device to CSS pixels.
654   gfx::Vector2dF total_translate_;
655
656   // The plugin rect in CSS pixels.
657   gfx::Rect css_plugin_rect_;
658
659   // True if the plugin occupies the entire frame (not embedded).
660   bool full_frame_ = false;
661
662   // The background color of the PDF viewer.
663   SkColor background_color_ = SK_ColorTRANSPARENT;
664
665   // Size, in DIPs, of plugin rectangle.
666   gfx::Size plugin_dip_size_;
667
668   // The plugin rectangle in device pixels.
669   gfx::Rect plugin_rect_;
670
671   // Remaining area, in pixels, to render the PDF in after accounting for
672   // horizontal centering.
673   gfx::Rect available_area_;
674
675   // Current zoom factor.
676   double zoom_ = 1.0;
677
678   // Current device scale factor. Multiply by `device_scale_` to convert from
679   // viewport to screen coordinates. Divide by `device_scale_` to convert from
680   // screen to viewport coordinates.
681   float device_scale_ = 1.0f;
682
683   // True if we haven't painted the plugin viewport yet.
684   bool first_paint_ = true;
685
686   // Whether OnPaint() is in progress or not.
687   bool in_paint_ = false;
688
689   // True if last bitmap was smaller than the screen.
690   bool last_bitmap_smaller_ = false;
691
692   // True if we request a new bitmap rendering.
693   bool needs_reraster_ = true;
694
695   // The size of the entire document in pixels (i.e. if each page is 800 pixels
696   // high and there are 10 pages, the height will be 8000).
697   gfx::Size document_size_;
698
699   std::vector<BackgroundPart> background_parts_;
700
701   // Deferred invalidates while `in_paint_` is true.
702   std::vector<gfx::Rect> deferred_invalidates_;
703
704   // The UI direction.
705   base::i18n::TextDirection ui_direction_ = base::i18n::UNKNOWN_DIRECTION;
706
707   // The scroll offset for the last raster in CSS pixels, before any
708   // transformations are applied.
709   gfx::Vector2dF scroll_offset_at_last_raster_;
710
711   // If this is true, then don't scroll the plugin in response to calls to
712   // `UpdateScroll()`. This will be true when the extension page is in the
713   // process of zooming the plugin so that flickering doesn't occur while
714   // zooming.
715   bool stop_scrolling_ = false;
716
717   // Whether the plugin has received a viewport changed message. Nothing should
718   // be painted until this is received.
719   bool received_viewport_message_ = false;
720
721   // If true, the render frame has been notified that we're starting a network
722   // request so that it can start the throbber. It will be notified again once
723   // the document finishes loading.
724   bool did_call_start_loading_ = false;
725
726   // The last document load progress value sent to the web page.
727   double last_progress_sent_ = 0.0;
728
729   // The current state of document load.
730   DocumentLoadState document_load_state_ = DocumentLoadState::kLoading;
731
732   // The current state of accessibility.
733   AccessibilityState accessibility_state_ = AccessibilityState::kOff;
734
735   // The next accessibility page index, used to track interprocess calls when
736   // reconstructing the tree for new document layouts.
737   int32_t next_accessibility_page_index_ = 0;
738
739   // Used for submitting forms.
740   std::unique_ptr<UrlLoader> form_loader_;
741
742   // Handler for accessibility data updates.
743   std::unique_ptr<PdfAccessibilityDataHandler> const
744       pdf_accessibility_data_handler_;
745
746   // The URL currently under the cursor.
747   std::string link_under_cursor_;
748
749   // The ID of the current find operation, or -1 if no current operation is
750   // present.
751   int find_identifier_ = -1;
752
753   // Whether an update to the number of find results found was sent less than
754   // `kFindResultCooldown` TimeDelta ago.
755   bool recently_sent_find_update_ = false;
756
757   // Stores the tickmarks to be shown for the current find results.
758   std::vector<gfx::Rect> tickmarks_;
759
760   // Whether the document is in edit mode.
761   bool edit_mode_ = false;
762
763   // Only instantiated when not print previewing.
764   std::unique_ptr<MetricsHandler> metrics_handler_;
765
766   // Keeps track of which unsupported features have been reported to avoid
767   // spamming the metrics if a feature shows up many times per document.
768   base::flat_set<std::string> unsupported_features_reported_;
769
770   // Indicates whether the browser has been notified about an unsupported
771   // feature once, which helps prevent the infobar from going up more than once.
772   bool notified_browser_about_unsupported_feature_ = false;
773
774   // The metafile in which to save the printed output. Assigned a value only
775   // between `PrintBegin()` and `PrintEnd()` calls.
776   raw_ptr<printing::MetafileSkia> printing_metafile_ = nullptr;
777
778   // The indices of pages to print.
779   std::vector<int> pages_to_print_;
780
781   // Assigned a value only between `PrintBegin()` and `PrintEnd()` calls.
782   absl::optional<blink::WebPrintParams> print_params_;
783
784   // For identifying actual print operations to avoid double logging of UMA.
785   bool print_pages_called_;
786
787   // Whether the plugin is loaded in Print Preview.
788   bool is_print_preview_ = false;
789
790   // Number of pages in Print Preview (non-PDF). 0 if previewing a PDF, and -1
791   // if not in Print Preview.
792   int print_preview_page_count_ = -1;
793
794   // Number of pages loaded in Print Preview (non-PDF). Always less than or
795   // equal to `print_preview_page_count_`.
796   int print_preview_loaded_page_count_ = -1;
797
798   // The PreviewModeClient used for print preview. Will be passed to
799   // `preview_engine_`.
800   std::unique_ptr<PreviewModeClient> preview_client_;
801
802   // Engine used to render individual preview pages. This will use the
803   // `PreviewModeClient` interface.
804   std::unique_ptr<PDFiumEngine> preview_engine_;
805
806   // Document load state for the Print Preview engine.
807   DocumentLoadState preview_document_load_state_ = DocumentLoadState::kComplete;
808
809   // Queue of available preview pages to load next.
810   base::queue<PreviewPageInfo> preview_pages_info_;
811
812   base::WeakPtrFactory<PdfViewWebPlugin> weak_factory_{this};
813 };
814
815 }  // namespace chrome_pdf
816
817 #endif  // PDF_PDF_VIEW_WEB_PLUGIN_H_