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.
5 #ifndef PDF_PDF_VIEW_WEB_PLUGIN_H_
6 #define PDF_PDF_VIEW_WEB_PLUGIN_H_
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"
51 class WebAssociatedURLLoader;
55 struct WebAssociatedURLLoaderOptions;
56 struct WebPrintPresetOptions;
70 } // namespace printing
72 namespace chrome_pdf {
76 class PdfAccessibilityDataHandler;
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 {
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;
93 enum class DocumentLoadState {
99 // Must match `SaveRequestType` in chrome/browser/resources/pdf/constants.ts.
100 enum class SaveRequestType {
106 // Provides services from the plugin's container.
107 class Client : public V8ValueConverter {
109 virtual ~Client() = default;
111 virtual base::WeakPtr<Client> GetWeakPtr() = 0;
113 // Creates a new `PDFiumEngine`.
114 virtual std::unique_ptr<PDFiumEngine> CreateEngine(
115 PDFEngine::Client* client,
116 PDFiumFormFiller::ScriptOption script_option);
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;
123 // Returns the plugin container set by `SetPluginContainer()`.
124 virtual blink::WebPluginContainer* PluginContainer() = 0;
126 // Returrns the document's site for cookies.
127 virtual net::SiteForCookies SiteForCookies() const = 0;
129 // Resolves `partial_url` relative to the document's base URL.
130 virtual blink::WebURL CompleteURL(
131 const blink::WebString& partial_url) const = 0;
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) {}
138 // Invalidates the entire web plugin container and schedules a paint of the
140 virtual void Invalidate() = 0;
142 // Notifies the container about which touch events the plugin accepts.
143 virtual void RequestTouchEventType(
144 blink::WebPluginContainer::TouchEventRequestType request_type) = 0;
146 // Notify the web plugin container about the total matches of a find
148 virtual void ReportFindInPageMatchCount(int identifier,
150 bool final_update) = 0;
152 // Notify the web plugin container about the selected find result in plugin.
153 virtual void ReportFindInPageSelection(int identifier,
155 bool final_update) = 0;
157 // Notify the web plugin container about find result tickmarks.
158 virtual void ReportFindInPageTickmarks(
159 const std::vector<gfx::Rect>& tickmarks) = 0;
161 // Returns the device scale factor.
162 virtual float DeviceScaleFactor() = 0;
164 // Gets the scroll position.
165 virtual gfx::PointF GetScrollPosition() = 0;
167 // Tells the embedder to allow the plugin to handle find requests.
168 virtual void UsePluginAsFindHandler() = 0;
170 // Calls underlying WebLocalFrame::SetReferrerForRequest().
171 virtual void SetReferrerForRequest(blink::WebURLRequest& request,
172 const blink::WebURL& referrer_url) = 0;
174 // Calls underlying WebLocalFrame::Alert().
175 virtual void Alert(const blink::WebString& message) = 0;
177 // Calls underlying WebLocalFrame::Confirm().
178 virtual bool Confirm(const blink::WebString& message) = 0;
180 // Calls underlying WebLocalFrame::Prompt().
181 virtual blink::WebString Prompt(const blink::WebString& message,
182 const blink::WebString& default_value) = 0;
184 // Calls underlying WebLocalFrame::TextSelectionChanged().
185 virtual void TextSelectionChanged(const blink::WebString& selection_text,
187 const gfx::Range& range) = 0;
189 // Calls underlying WebLocalFrame::CreateAssociatedURLLoader().
190 virtual std::unique_ptr<blink::WebAssociatedURLLoader>
191 CreateAssociatedURLLoader(
192 const blink::WebAssociatedURLLoaderOptions& options) = 0;
194 // Notifies the frame widget about the text input type change.
195 virtual void UpdateTextInputState() = 0;
197 // Notifies the frame widget about the selection bound change.
198 virtual void UpdateSelectionBounds() = 0;
200 // Gets the embedder's origin as a serialized string.
201 virtual std::string GetEmbedderOriginString() = 0;
203 // Returns whether the plugin container's frame exists.
204 virtual bool HasFrame() const = 0;
206 // Notifies the frame's client that the plugin started loading.
207 virtual void DidStartLoading() = 0;
209 // Notifies the frame's client that the plugin stopped loading.
210 virtual void DidStopLoading() = 0;
212 // Prints the plugin element.
213 virtual void Print() {}
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) {}
220 // Creates an implementation of `PdfAccessibilityDataHandler` catered to the
222 virtual std::unique_ptr<PdfAccessibilityDataHandler>
223 CreateAccessibilityDataHandler(
224 PdfAccessibilityActionHandler* action_handler,
225 PdfAccessibilityImageFetcher* image_fetcher);
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;
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,
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;
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,
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;
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,
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,
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;
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;
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;
368 // PostMessageReceiver::Client:
369 void OnMessage(const base::Value::Dict& message) override;
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;
381 // PdfAccessibilityActionHandler:
382 void EnableAccessibility() override;
383 void HandleAccessibilityAction(
384 const AccessibilityActionData& action_data) override;
385 void LoadOrReloadAccessibility() override;
387 // PdfAccessibilityImageFetcher:
388 SkBitmap GetImageForOcr(int32_t page_index,
389 int32_t page_object_index) override;
391 // PreviewModeClient::Client:
392 void PreviewDocumentLoadComplete() override;
393 void PreviewDocumentLoadFailed() override;
395 // Initializes the plugin for testing, bypassing certain consistency checks.
396 bool InitializeForTesting();
398 const gfx::Rect& GetPluginRectForTesting() const { return plugin_rect_; }
400 float GetDeviceScaleForTesting() const { return device_scale_; }
402 DocumentLoadState document_load_state_for_testing() const {
403 return document_load_state_;
406 int GetContentRestrictionsForTesting() const {
407 return GetContentRestrictions();
410 AccessibilityDocInfo GetAccessibilityDocInfoForTesting() const {
411 return GetAccessibilityDocInfo();
414 int32_t next_accessibility_page_index_for_testing() const {
415 return next_accessibility_page_index_;
418 void set_next_accessibility_page_index_for_testing(int32_t index) {
419 next_accessibility_page_index_ = index;
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,
429 enum class AccessibilityState {
431 kPending, // Enabled but waiting for doc to load.
432 kLoaded, // Fully loaded.
435 struct BackgroundPart {
440 // Metadata about an available preview page.
441 struct PreviewPageInfo {
445 // Page index in destination document.
446 int dest_page_index = -1;
449 // Call `Destroy()` instead.
450 ~PdfViewWebPlugin() override;
452 bool InitializeCommon();
454 // Sends whether to do smooth scrolling.
455 void SendSetSmoothScrolling();
457 // Handles `LoadUrl()` result for the main document.
458 void DidOpen(std::unique_ptr<UrlLoader> loader, int32_t result);
460 // Updates the scroll position, which is in CSS pixels relative to the
462 void UpdateScroll(const gfx::PointF& scroll_position);
464 // Loads `url`, invoking `callback` on receiving the initial response.
465 void LoadUrl(base::StringPiece url, LoadUrlCallback callback);
467 // Handles `Open()` result for `form_loader_`.
468 void DidFormOpen(int32_t result);
470 // Sends start/stop loading notifications to the plugin's render frame.
471 void DidStartLoading();
472 void DidStopLoading();
474 // Gets the content restrictions based on the permissions which `engine_` has.
475 int GetContentRestrictions() const;
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);
497 void SaveToBuffer(const std::string& token);
498 void SaveToFile(const std::string& token);
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
503 gfx::PointF GetScrollPositionFromOffset(
504 const gfx::Vector2dF& scroll_offset) const;
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);
512 // The preparation when painting on the image data buffer for the first
514 void PrepareForFirstPaint(std::vector<PaintReadyRect>& ready);
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);
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);
524 // Figures out the location of any background rectangles (i.e. those that
525 // aren't painted by the PDF engine).
526 void CalculateBackgroundParts();
528 // Computes document width/height in device pixels, based on current zoom and
530 int GetDocumentPixelWidth() const;
531 int GetDocumentPixelHeight() const;
533 // Schedules invalidation tasks after painting finishes.
534 void InvalidateAfterPaintDone();
536 // Callback to clear deferred invalidates after painting finishes.
537 void ClearDeferredInvalidates();
539 // Recalculates values that depend on scale factors.
540 void UpdateScaledValues();
542 void OnViewportChanged(const gfx::Rect& new_plugin_rect_in_css_pixel,
543 float new_device_scale);
545 // Text editing methods.
548 bool Paste(const blink::WebString& value);
552 bool HandleWebInputEvent(const blink::WebInputEvent& event);
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);
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();
565 void ResetRecentlySentFindUpdate();
567 // Records metrics about the document metadata.
568 void RecordDocumentMetrics();
570 // Sends the attachments data.
571 void SendAttachments();
573 // Sends the bookmarks data.
574 void SendBookmarks();
576 // Send document metadata data.
579 // Sends the loading progress, where `percentage` represents the progress, or
580 // -1 for loading error.
581 void SendLoadingProgress(double percentage);
583 // Handles message for resetting Print Preview.
584 void HandleResetPrintPreviewModeMessage(const base::Value::Dict& message);
586 // Handles message for loading a preview page.
587 void HandleLoadPreviewPageMessage(const base::Value::Dict& message);
589 // Starts loading the next available preview page into a blank page.
590 void LoadAvailablePreviewPage();
592 // Handles `LoadUrl()` result for a preview page.
593 void DidOpenPreview(std::unique_ptr<UrlLoader> loader, int32_t result);
595 // Continues loading the next preview page.
596 void LoadNextPreviewPage();
598 // Sends a notification that the print preview has loaded.
599 void SendPrintPreviewLoadedNotification();
601 // Sends the thumbnail image data.
602 void SendThumbnail(base::Value::Dict reply, Thumbnail thumbnail);
604 // Converts `frame_coordinates` to PDF coordinates.
605 gfx::Point FrameToPdfCoordinates(const gfx::PointF& frame_coordinates) const;
607 // Gets the accessibility doc info based on the information from `engine_`.
608 AccessibilityDocInfo GetAccessibilityDocInfo() const;
610 // Sets the accessibility information about the given `page_index` in the
612 void PrepareAndSetAccessibilityPageInfo(int32_t page_index);
614 // Prepares the accessibility information about the current viewport. This is
615 // done once when accessibility is first loaded and again when the geometry
617 void PrepareAndSetAccessibilityViewportInfo();
619 // Starts loading accessibility information.
620 void LoadAccessibility();
622 bool initialized_ = false;
624 blink::WebString selected_text_;
626 std::unique_ptr<Client> const client_;
628 // Used to access the services provided by the browser.
629 mojo::AssociatedRemote<pdf::mojom::PdfService> const pdf_service_;
631 mojo::Receiver<pdf::mojom::PdfListener> listener_receiver_{this};
633 std::unique_ptr<PDFiumEngine> engine_;
635 // The URL of the PDF document.
638 // The callback for receiving the password from the page.
639 base::OnceCallback<void(const std::string&)> password_callback_;
641 // The current cursor type.
642 ui::mojom::CursorType cursor_type_ = ui::mojom::CursorType::kPointer;
644 blink::WebTextInputType text_input_type_ =
645 blink::WebTextInputType::kWebTextInputTypeNone;
647 gfx::Rect caret_rect_;
649 blink::WebString composition_text_;
651 // Whether the plugin element currently has focus.
652 bool has_focus_ = false;
654 blink::WebPluginParams initial_params_;
656 v8::Persistent<v8::Object> scriptable_receiver_;
658 PaintManager paint_manager_{this};
660 // Image data buffer for painting.
661 SkBitmap image_data_;
663 // The current image snapshot.
664 cc::PaintImage snapshot_;
666 // Translate from snapshot to device pixels.
667 gfx::Vector2dF snapshot_translate_;
669 // Scale from snapshot to device pixels.
670 float snapshot_scale_ = 1.0f;
672 // The viewport coordinates to DIP (device-independent pixel) ratio.
673 float viewport_to_dip_scale_ = 1.0f;
675 // Combined translate from snapshot to device to CSS pixels.
676 gfx::Vector2dF total_translate_;
678 // The plugin rect in CSS pixels.
679 gfx::Rect css_plugin_rect_;
681 // True if the plugin occupies the entire frame (not embedded).
682 bool full_frame_ = false;
684 // The background color of the PDF viewer.
685 SkColor background_color_ = SK_ColorTRANSPARENT;
687 // Size, in DIPs, of plugin rectangle.
688 gfx::Size plugin_dip_size_;
690 // The plugin rectangle in device pixels.
691 gfx::Rect plugin_rect_;
693 // Remaining area, in pixels, to render the PDF in after accounting for
694 // horizontal centering.
695 gfx::Rect available_area_;
697 // Current zoom factor.
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;
705 // True if we haven't painted the plugin viewport yet.
706 bool first_paint_ = true;
708 // Whether OnPaint() is in progress or not.
709 bool in_paint_ = false;
711 // True if last bitmap was smaller than the screen.
712 bool last_bitmap_smaller_ = false;
714 // True if we request a new bitmap rendering.
715 bool needs_reraster_ = true;
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_;
721 std::vector<BackgroundPart> background_parts_;
723 // Deferred invalidates while `in_paint_` is true.
724 std::vector<gfx::Rect> deferred_invalidates_;
727 base::i18n::TextDirection ui_direction_ = base::i18n::UNKNOWN_DIRECTION;
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_;
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
737 bool stop_scrolling_ = false;
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;
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;
748 // The last document load progress value sent to the web page.
749 double last_progress_sent_ = 0.0;
751 // The current state of document load.
752 DocumentLoadState document_load_state_ = DocumentLoadState::kLoading;
754 // The current state of accessibility.
755 AccessibilityState accessibility_state_ = AccessibilityState::kOff;
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;
761 // Used for submitting forms.
762 std::unique_ptr<UrlLoader> form_loader_;
764 // Handler for accessibility data updates.
765 std::unique_ptr<PdfAccessibilityDataHandler> const
766 pdf_accessibility_data_handler_;
768 // The URL currently under the cursor.
769 std::string link_under_cursor_;
771 // The ID of the current find operation, or -1 if no current operation is
773 int find_identifier_ = -1;
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;
779 // Stores the tickmarks to be shown for the current find results.
780 std::vector<gfx::Rect> tickmarks_;
782 // Whether the document is in edit mode.
783 bool edit_mode_ = false;
785 // Only instantiated when not print previewing.
786 std::unique_ptr<MetricsHandler> metrics_handler_;
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_;
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;
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;
800 // The indices of pages to print.
801 std::vector<int> pages_to_print_;
803 // Assigned a value only between `PrintBegin()` and `PrintEnd()` calls.
804 absl::optional<blink::WebPrintParams> print_params_;
806 // For identifying actual print operations to avoid double logging of UMA.
807 bool print_pages_called_;
809 // Whether the plugin is loaded in Print Preview.
810 bool is_print_preview_ = false;
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;
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;
820 // The PreviewModeClient used for print preview. Will be passed to
821 // `preview_engine_`.
822 std::unique_ptr<PreviewModeClient> preview_client_;
824 // Engine used to render individual preview pages. This will use the
825 // `PreviewModeClient` interface.
826 std::unique_ptr<PDFiumEngine> preview_engine_;
828 // Document load state for the Print Preview engine.
829 DocumentLoadState preview_document_load_state_ = DocumentLoadState::kComplete;
831 // Queue of available preview pages to load next.
832 base::queue<PreviewPageInfo> preview_pages_info_;
834 base::WeakPtrFactory<PdfViewWebPlugin> weak_factory_{this};
837 } // namespace chrome_pdf
839 #endif // PDF_PDF_VIEW_WEB_PLUGIN_H_