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