Skip to main content

servo/
webview.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::cell::{Cell, Ref, RefCell, RefMut};
6use std::hash::Hash;
7use std::rc::{Rc, Weak};
8
9use accesskit::{
10    Affine as AccesskitAffine, Node as AccesskitNode, NodeId, Rect as AccesskitRect, Role, TreeId,
11    TreeInfo, TreeUpdate, Uuid as AccesskitUuid,
12};
13use dpi::PhysicalSize;
14use embedder_traits::{
15    ContextMenuAction, ContextMenuItem, Cursor, EmbedderControlId, EmbedderControlRequest, Image,
16    InputEvent, InputEventAndId, InputEventId, JSValue, JavaScriptEvaluationError, LoadStatus,
17    MediaSessionActionType, NewWebViewDetails, ScreenGeometry, ScreenshotCaptureError, Scroll,
18    Theme, TraversalId, UrlRequest, ViewportDetails, WebViewPoint, WebViewRect,
19};
20use euclid::{Scale, Size2D};
21use image::RgbaImage;
22use log::debug;
23use paint_api::WebViewTrait;
24use paint_api::rendering_context::RenderingContext;
25use servo_base::Epoch;
26use servo_base::generic_channel::GenericSender;
27use servo_base::id::WebViewId;
28use servo_config::pref;
29use servo_constellation_traits::{
30    EmbedderToConstellationMessage, HistoryTraversalSource, SessionHistoryTraversalRequest,
31    TraversalDirection,
32};
33use servo_geometry::DeviceIndependentPixel;
34use servo_url::ServoUrl;
35use style_traits::CSSPixel;
36use url::Url;
37use webrender_api::units::{DeviceIntRect, DevicePixel, DevicePoint, DeviceSize};
38
39use crate::clipboard_delegate::{ClipboardDelegate, DefaultClipboardDelegate};
40#[cfg(feature = "gamepad")]
41use crate::gamepad_delegate::{DefaultGamepadDelegate, GamepadDelegate};
42use crate::geolocation_delegate::{DefaultGeolocationDelegate, GeolocationDelegate};
43use crate::responders::AutomaticResponder;
44use crate::servo::PendingHandledInputEvent;
45use crate::webview_delegate::{
46    CreateNewWebViewRequest, DefaultWebViewDelegate, TooltipControl, WebViewDelegate,
47};
48use crate::{
49    ColorPicker, ContextMenu, EmbedderControl, InputMethodControl, SelectElement, Servo,
50    UserContentManager, WebRenderDebugOption,
51};
52
53pub(crate) const MINIMUM_WEBVIEW_SIZE: Size2D<i32, DevicePixel> = Size2D::new(1, 1);
54
55/// A handle to a Servo webview. If you clone this handle, it does not create a new webview,
56/// but instead creates a new handle to the webview. Once the last handle is dropped, Servo
57/// considers that the webview has closed and will clean up all associated resources related
58/// to this webview.
59///
60/// ## Creating a WebView
61///
62/// To create a [`WebView`], use [`WebViewBuilder`].
63///
64/// ## Rendering Model
65///
66/// Every [`WebView`] has a [`RenderingContext`]. The embedder manages when
67/// the contents of the [`WebView`] paint to the [`RenderingContext`]. When
68/// a [`WebView`] needs to be painted, for instance, because its contents have changed, Servo will
69/// call [`WebViewDelegate::notify_new_frame_ready`] in order to signal that it is time to repaint
70/// the [`WebView`] using [`WebView::paint`].
71///
72/// An example of how this flow might work is:
73///
74/// 1. [`WebViewDelegate::notify_new_frame_ready`] is called. The applications triggers a request
75///    to repaint the window that contains this [`WebView`].
76/// 2. During window repainting, the application calls [`WebView::paint`] and the contents of the
77///    [`RenderingContext`] are updated.
78/// 3. If the [`RenderingContext`] is double-buffered, the
79///    application then calls [`crate::RenderingContext::present()`] in order to swap the back buffer
80///    to the front, finally displaying the updated [`WebView`] contents.
81///
82/// In cases where the [`WebView`] contents have not been updated, but a repaint is necessary, for
83/// instance when repainting a window due to damage, an application may simply perform the final two
84/// steps and Servo will repaint even without first calling the
85/// [`WebViewDelegate::notify_new_frame_ready`] method.
86#[derive(Clone)]
87pub struct WebView(Rc<RefCell<WebViewInner>>);
88
89impl PartialEq for WebView {
90    fn eq(&self, other: &Self) -> bool {
91        self.inner().id == other.inner().id
92    }
93}
94
95impl Hash for WebView {
96    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
97        self.inner().id.hash(state);
98    }
99}
100
101pub(crate) struct WebViewInner {
102    pub(crate) id: WebViewId,
103    pub(crate) servo: Servo,
104    pub(crate) delegate: Rc<dyn WebViewDelegate>,
105    pub(crate) clipboard_delegate: Rc<dyn ClipboardDelegate>,
106    #[cfg(feature = "gamepad")]
107    pub(crate) gamepad_delegate: Rc<dyn GamepadDelegate>,
108    pub(crate) geolocation_delegate: Rc<dyn GeolocationDelegate>,
109
110    /// AccessKit subtree id for this [`WebView`], if accessibility is active.
111    ///
112    /// Set by [`WebView::set_accessibility_active()`], and forwarded to the constellation via
113    /// [`EmbedderToConstellationMessage::SetAccessibilityActive`].
114    pub(crate) accesskit_tree_id: Option<TreeId>,
115    /// [`TreeId`] of the web contents of this [`WebView`]’s active top-level pipeline,
116    /// which is grafted into the tree for this [`WebView`].
117    pub(crate) grafted_accesskit_tree_id: Option<TreeId>,
118    /// A counter for changes to the grafted accesskit tree for this webview.
119    /// See [`Self::grafted_accesskit_tree_id`].
120    grafted_accesskit_tree_epoch: Option<Epoch>,
121    /// Set when the paint layer applies a change to this [`WebView`]'s accessibility viewport
122    /// geometry — its size, page or pinch zoom, or HiDPI scale — via
123    /// [`WebViewTrait::notify_viewport_updated()`]. The root accessibility node is re-sent from
124    /// [`Servo`]'s event loop rather than from there, so that nothing calls into the
125    /// [`WebViewDelegate`] while the paint `RefCell` (or an embedder-facing method) is on the stack,
126    /// which could cause re-entrant `RefCell` borrows. See
127    /// [`WebView::note_accessibility_viewport_changed()`].
128    accessibility_viewport_changed: Cell<bool>,
129
130    rendering_context: Rc<dyn RenderingContext>,
131    user_content_manager: Option<Rc<UserContentManager>>,
132    hidpi_scale_factor: Scale<f32, DeviceIndependentPixel, DevicePixel>,
133    load_status: LoadStatus,
134    status_text: Option<String>,
135    page_title: Option<String>,
136    favicon: Option<Image>,
137    focused: bool,
138    animating: bool,
139    cursor: Cursor,
140
141    /// The back / forward list of this WebView.
142    back_forward_list: Vec<Url>,
143
144    /// The current index in the back / forward list.
145    back_forward_list_index: usize,
146
147    /// The current opened context menu.
148    open_context_menu: Cell<Option<EmbedderControlId>>,
149}
150
151impl Drop for WebViewInner {
152    fn drop(&mut self) {
153        self.servo
154            .constellation_proxy()
155            .send(EmbedderToConstellationMessage::CloseWebView(self.id));
156        self.servo.paint_mut().remove_webview(self.id);
157    }
158}
159
160impl WebView {
161    pub(crate) fn new(mut builder: WebViewBuilder) -> Self {
162        let servo = builder.servo;
163        let painter_id = servo
164            .paint_mut()
165            .register_rendering_context(builder.rendering_context.clone());
166
167        let id = WebViewId::new(painter_id);
168        let webview = Self(Rc::new(RefCell::new(WebViewInner {
169            id,
170            servo: servo.clone(),
171            rendering_context: builder.rendering_context,
172            delegate: builder.delegate,
173            clipboard_delegate: builder
174                .clipboard_delegate
175                .unwrap_or_else(|| Rc::new(DefaultClipboardDelegate)),
176            #[cfg(feature = "gamepad")]
177            gamepad_delegate: builder
178                .gamepad_delegate
179                .unwrap_or_else(|| Rc::new(DefaultGamepadDelegate)),
180            geolocation_delegate: builder
181                .geolocation_delegate
182                .unwrap_or_else(|| Rc::new(DefaultGeolocationDelegate::default())),
183            accesskit_tree_id: None,
184            grafted_accesskit_tree_id: None,
185            grafted_accesskit_tree_epoch: None,
186            accessibility_viewport_changed: Cell::new(false),
187            hidpi_scale_factor: builder.hidpi_scale_factor,
188            load_status: LoadStatus::Started,
189            status_text: None,
190            page_title: None,
191            favicon: None,
192            focused: true,
193            animating: false,
194            cursor: Cursor::Pointer,
195            back_forward_list: Default::default(),
196            back_forward_list_index: 0,
197            user_content_manager: builder.user_content_manager.clone(),
198            open_context_menu: Default::default(),
199        })));
200
201        let viewport_details = webview.viewport_details();
202        servo.paint().add_webview(
203            Box::new(ServoRendererWebView {
204                weak_handle: webview.weak_handle(),
205                id,
206            }),
207            viewport_details,
208        );
209
210        servo
211            .webviews_mut()
212            .insert(webview.id(), webview.weak_handle());
213
214        let user_content_manager_id = builder
215            .user_content_manager
216            .as_ref()
217            .map(|user_content_manager| user_content_manager.id());
218
219        let new_webview_details = NewWebViewDetails {
220            webview_id: webview.id(),
221            viewport_details,
222            user_content_manager_id,
223        };
224
225        // There are two possibilities here. Either the WebView is a new toplevel
226        // WebView in which case `Self::create_new_webview_responder` is `None` or this
227        // is the response to a `WebViewDelegate::request_create_new` method in which
228        // case script expects that we just return the information directly back to
229        // the `ScriptThread`.
230        match builder.create_new_webview_responder.as_mut() {
231            Some(responder) => {
232                let _ = responder.send(Some(new_webview_details));
233            },
234            None => {
235                let url = builder.url.unwrap_or(
236                    Url::parse("about:blank")
237                        .expect("Should always be able to parse 'about:blank'."),
238                );
239
240                servo
241                    .constellation_proxy()
242                    .send(EmbedderToConstellationMessage::NewWebView(
243                        url.into(),
244                        new_webview_details,
245                    ));
246            },
247        }
248
249        webview
250    }
251
252    fn inner(&self) -> Ref<'_, WebViewInner> {
253        self.0.borrow()
254    }
255
256    fn inner_mut(&self) -> RefMut<'_, WebViewInner> {
257        self.0.borrow_mut()
258    }
259
260    fn servo(&self) -> Servo {
261        self.0.borrow().servo.clone()
262    }
263
264    pub(crate) fn request_create_new(
265        &self,
266        response_sender: GenericSender<Option<NewWebViewDetails>>,
267    ) {
268        let request = CreateNewWebViewRequest {
269            servo: self.servo(),
270            responder: AutomaticResponder::new(response_sender, None),
271        };
272        self.delegate().request_create_new(self.clone(), request);
273    }
274
275    pub(crate) fn viewport_details(&self) -> ViewportDetails {
276        // The division by 1 represents the page's default zoom of 100%,
277        // and gives us the appropriate CSSPixel type for the viewport.
278        let inner = self.inner();
279        let viewport_size = inner.rendering_context.size2d().to_f32();
280        let scaled_viewport_size = viewport_size / inner.hidpi_scale_factor;
281        let device_size = self
282            .delegate()
283            .screen_geometry(self.clone())
284            .map(|geometry| geometry.size.to_f32())
285            .unwrap_or_else(|| viewport_size);
286        ViewportDetails {
287            size: scaled_viewport_size / Scale::new(1.0),
288            hidpi_scale_factor: Scale::new(inner.hidpi_scale_factor.0),
289            device_size,
290        }
291    }
292
293    pub(crate) fn from_weak_handle(inner: &Weak<RefCell<WebViewInner>>) -> Option<Self> {
294        inner.upgrade().map(WebView)
295    }
296
297    pub(crate) fn weak_handle(&self) -> Weak<RefCell<WebViewInner>> {
298        Rc::downgrade(&self.0)
299    }
300
301    /// Get the [`WebViewDelegate`] associated with this [`WebView`].
302    pub fn delegate(&self) -> Rc<dyn WebViewDelegate> {
303        self.inner().delegate.clone()
304    }
305
306    /// Get the [`ClipboardDelegate`] associated with this [`WebView`].
307    pub fn clipboard_delegate(&self) -> Rc<dyn ClipboardDelegate> {
308        self.inner().clipboard_delegate.clone()
309    }
310
311    /// Get the [`GamepadDelegate`] associated with this [`WebView`].
312    #[cfg(feature = "gamepad")]
313    pub fn gamepad_delegate(&self) -> Rc<dyn GamepadDelegate> {
314        self.inner().gamepad_delegate.clone()
315    }
316
317    /// Get the [`GeolocationDelegate`] associated with this [`WebView`].
318    pub fn geolocation_delegate(&self) -> Rc<dyn GeolocationDelegate> {
319        self.inner().geolocation_delegate.clone()
320    }
321
322    /// Get the unique identifier for this [`WebView`].
323    pub fn id(&self) -> WebViewId {
324        self.inner().id
325    }
326
327    /// Get the [`RenderingContext`] associated with this [`WebView`].
328    pub fn rendering_context(&self) -> Rc<dyn RenderingContext> {
329        self.inner().rendering_context.clone()
330    }
331
332    /// Get the load status for the page that is currently loading or loaded in this [`WebView`].
333    ///
334    /// The embedder can use [`WebViewDelegate::notify_load_status_changed`] to subscribe
335    /// to changes in the load status.
336    pub fn load_status(&self) -> LoadStatus {
337        self.inner().load_status
338    }
339
340    pub(crate) fn set_load_status(self, new_value: LoadStatus) {
341        if self.inner().load_status == new_value {
342            return;
343        }
344        self.inner_mut().load_status = new_value;
345        self.delegate().notify_load_status_changed(self, new_value);
346    }
347
348    /// Get the URL of the currently active page in this [`WebView`]'s navigation history.
349    /// Returns `None` if no page is currently loaded.
350    pub fn url(&self) -> Option<Url> {
351        let inner = self.inner();
352        inner
353            .back_forward_list
354            .get(inner.back_forward_list_index)
355            .cloned()
356    }
357
358    /// Get the current status text for this [`WebView`]. Returns `None` if there is no status text.
359    ///
360    /// The status text changes as the user interacts with the page, for example, by hovering over
361    /// a link. The embedder can use [`WebViewDelegate::notify_status_text_changed`] to subscribe
362    /// to changes in the status text.
363    pub fn status_text(&self) -> Option<String> {
364        self.inner().status_text.clone()
365    }
366
367    pub(crate) fn set_status_text(self, new_value: Option<String>) {
368        if self.inner().status_text == new_value {
369            return;
370        }
371        self.inner_mut().status_text = new_value.clone();
372        self.delegate().notify_status_text_changed(self, new_value);
373    }
374
375    /// Get the title of the currently active page in this [`WebView`]. Returns `None` if the
376    /// page has no title.
377    ///
378    /// The embedder can use [`WebViewDelegate::notify_page_title_changed`] to subscribe
379    /// to changes in the [`WebView`]'s page title.
380    pub fn page_title(&self) -> Option<String> {
381        self.inner().page_title.clone()
382    }
383
384    pub(crate) fn set_page_title(self, new_value: Option<String>) {
385        if self.inner().page_title == new_value {
386            return;
387        }
388        self.inner_mut().page_title = new_value.clone();
389        self.delegate().notify_page_title_changed(self, new_value);
390    }
391
392    /// Get a read-only reference to the image data for the favicon of the currently
393    /// active page in this [`WebView`]. Returns `None` if no favicon is available
394    /// for the currently active page.
395    ///
396    /// The embedder can use [`WebViewDelegate::notify_favicon_changed`] to subscribe
397    /// to changes in the [`WebView`]'s favicon.
398    pub fn favicon(&self) -> Option<Ref<'_, Image>> {
399        Ref::filter_map(self.inner(), |inner| inner.favicon.as_ref()).ok()
400    }
401
402    pub(crate) fn set_favicon(self, new_value: Option<Image>) {
403        if new_value.is_none() && self.inner().favicon.is_none() {
404            return;
405        }
406        self.inner_mut().favicon = new_value;
407        self.delegate().notify_favicon_changed(self);
408    }
409
410    /// Whether or not this [`WebView`] currently has system focus.
411    pub fn focused(&self) -> bool {
412        self.inner().focused
413    }
414
415    /// Get the current [`Cursor`] for this [`WebView`].
416    ///
417    /// The cursor can change as the user interacts with page content. The embedder
418    /// can use [`WebViewDelegate::notify_cursor_changed`] to subscribe to changes in
419    /// the  [`WebView`]'s cursor.
420    pub fn cursor(&self) -> Cursor {
421        self.inner().cursor
422    }
423
424    pub(crate) fn set_cursor(self, new_value: Cursor) {
425        if self.inner().cursor == new_value {
426            return;
427        }
428        self.inner_mut().cursor = new_value;
429        self.delegate().notify_cursor_changed(self, new_value);
430    }
431
432    /// Notify Servo that this [`WebView`] has gained or lost system focus.
433    ///
434    /// All [`WebView`]s start with system focus activated, so embedders are
435    /// expected to explicitly set this to false when the containing view loses
436    /// focus.
437    pub fn set_focused(&self, focused: bool) {
438        let old_focused = std::mem::replace(&mut self.inner_mut().focused, focused);
439        if old_focused != focused {
440            self.servo().constellation_proxy().send(
441                EmbedderToConstellationMessage::SetWebViewHasSystemFocus(self.id(), focused),
442            );
443        }
444    }
445
446    /// Whether or not this [`WebView`] has animating content, such as a CSS animation or
447    /// transition or is running `requestAnimationFrame` callbacks. This indicates that the
448    /// embedding application should be spinning the Servo event loop on regular intervals
449    /// in order to trigger animation updates.
450    pub fn animating(&self) -> bool {
451        self.inner().animating
452    }
453
454    pub(crate) fn set_animating(self, new_value: bool) {
455        if self.inner().animating == new_value {
456            return;
457        }
458        self.inner_mut().animating = new_value;
459        self.delegate().notify_animating_changed(self, new_value);
460    }
461
462    /// The size of this [`WebView`]'s [`RenderingContext`].
463    pub fn size(&self) -> DeviceSize {
464        self.inner().rendering_context.size2d().to_f32()
465    }
466
467    /// Request that the given [`WebView`]'s [`RenderingContext`] be resized. Note that the
468    /// minimum size for a WebView is 1 pixel by 1 pixel so any requested size will be
469    /// clamped by that value.
470    ///
471    /// This will also resize any other [`WebView`] using the same [`RenderingContext`]. A
472    /// [`WebView`] is always as big as its [`RenderingContext`].
473    pub fn resize(&self, new_size: PhysicalSize<u32>) {
474        let new_size = PhysicalSize {
475            width: new_size.width.max(MINIMUM_WEBVIEW_SIZE.width as u32),
476            height: new_size.height.max(MINIMUM_WEBVIEW_SIZE.height as u32),
477        };
478
479        self.servo()
480            .paint()
481            .resize_rendering_context(self.id(), new_size);
482    }
483
484    /// Get the HiDPI scale factor for this [`WebView`].
485    pub fn hidpi_scale_factor(&self) -> Scale<f32, DeviceIndependentPixel, DevicePixel> {
486        self.inner().hidpi_scale_factor
487    }
488
489    /// Set the HiDPI scale factor for this [`WebView`].
490    ///
491    /// This scale factor determines how device-independent pixels map to physical device pixels
492    /// and therefore depends on which device this [`WebView`] is being displayed.
493    pub fn set_hidpi_scale_factor(
494        &self,
495        new_scale_factor: Scale<f32, DeviceIndependentPixel, DevicePixel>,
496    ) {
497        if self.inner().hidpi_scale_factor == new_scale_factor {
498            return;
499        }
500
501        self.inner_mut().hidpi_scale_factor = new_scale_factor;
502        self.servo()
503            .paint()
504            .set_hidpi_scale_factor(self.id(), new_scale_factor);
505    }
506
507    /// Make this [`WebView`] visible within its [`RenderingContext`].
508    pub fn show(&self) {
509        self.servo()
510            .paint()
511            .show_webview(self.id())
512            .expect("BUG: invalid WebView instance");
513    }
514
515    /// Hide this [`WebView`] within its [`RenderingContext`].
516    pub fn hide(&self) {
517        self.servo()
518            .paint()
519            .hide_webview(self.id())
520            .expect("BUG: invalid WebView instance");
521    }
522
523    /// Notify this [`WebView`] of a change to the system theme (e.g. light or dark mode).
524    pub fn notify_theme_change(&self, theme: Theme) {
525        self.servo()
526            .constellation_proxy()
527            .send(EmbedderToConstellationMessage::ThemeChange(
528                self.id(),
529                theme,
530            ))
531    }
532
533    /// Load the given URL into this [`WebView`] using the default request headers.
534    ///
535    /// This pushes a new entry onto the navigation history, so the user can navigate
536    /// back to the previous page.
537    pub fn load(&self, url: Url) {
538        self.servo()
539            .constellation_proxy()
540            .send(EmbedderToConstellationMessage::LoadUrl(
541                self.id(),
542                UrlRequest::new(url),
543            ))
544    }
545
546    /// Load a [`UrlRequest`] with custom headers into this [`WebView`].
547    ///
548    /// This pushes a new entry onto the navigation history, so the user can navigate
549    /// back to the previous page.
550    pub fn load_request(&self, url_request: UrlRequest) {
551        self.servo()
552            .constellation_proxy()
553            .send(EmbedderToConstellationMessage::LoadUrl(
554                self.id(),
555                url_request,
556            ))
557    }
558
559    /// Reload the currently loaded page in this [`WebView`].
560    pub fn reload(&self) {
561        self.inner_mut().load_status = LoadStatus::Started;
562        self.servo()
563            .constellation_proxy()
564            .send(EmbedderToConstellationMessage::Reload(self.id()))
565    }
566
567    /// Whether or not this [`WebView`] can go backward in its navigation history.
568    ///
569    /// This is `false` if the currently active page is the oldest entry in the
570    /// [`WebView`]'s navigation history.
571    pub fn can_go_back(&self) -> bool {
572        self.inner().back_forward_list_index != 0
573    }
574
575    /// Go backward in this [`WebView`]'s navigation history by the given number of steps.
576    ///
577    /// Returns a [`TraversalId`] that can be used with the
578    /// [`WebViewDelegate::notify_traversal_complete`] callback to determine when the
579    /// traversal is complete.
580    pub fn go_back(&self, amount: usize) -> TraversalId {
581        let request = SessionHistoryTraversalRequest::new(
582            self.id(),
583            TraversalDirection::Back(amount),
584            HistoryTraversalSource::Embedder,
585        );
586        let traversal_id = request.id.clone();
587        self.servo()
588            .constellation_proxy()
589            .send(EmbedderToConstellationMessage::TraverseHistory(request));
590        traversal_id
591    }
592
593    /// Whether or not this [`WebView`] can go forward in its navigation history.
594    ///
595    /// This is `false` if the currently active page is the most recent entry in
596    /// the [`WebView`]'s navigation history.
597    pub fn can_go_forward(&self) -> bool {
598        let inner = self.inner();
599        inner.back_forward_list.len() > inner.back_forward_list_index + 1
600    }
601
602    /// Go forward in this [`WebView`]'s navigation history by the given number of steps.
603    ///
604    /// Returns a [`TraversalId`] that can be used with the
605    /// [`WebViewDelegate::notify_traversal_complete`] callback to determine when the
606    /// traversal is complete.
607    pub fn go_forward(&self, amount: usize) -> TraversalId {
608        let request = SessionHistoryTraversalRequest::new(
609            self.id(),
610            TraversalDirection::Forward(amount),
611            HistoryTraversalSource::Embedder,
612        );
613        let traversal_id = request.id.clone();
614        self.servo()
615            .constellation_proxy()
616            .send(EmbedderToConstellationMessage::TraverseHistory(request));
617        traversal_id
618    }
619
620    /// Ask the [`WebView`] to scroll the scrollable area under `point` to the
621    /// given `scroll` destination.
622    pub fn notify_scroll_event(&self, scroll: Scroll, point: WebViewPoint) {
623        self.servo()
624            .paint()
625            .notify_scroll_event(self.id(), scroll, point);
626    }
627
628    /// Notify this [`WebView`] about an [`InputEvent`] such as a mouse click, touch
629    /// event, or key press.
630    ///
631    /// Returns an [`InputEventId`] that can be used with the
632    /// [`WebViewDelegate::notify_input_event_handled`] callback to determine the result of
633    /// processing of the event by the page content.
634    pub fn notify_input_event(&self, event: InputEvent) -> InputEventId {
635        let event: InputEventAndId = event.into();
636        let event_id = event.id;
637        let webview_id = self.id();
638        let servo = &self.inner().servo;
639
640        // Events with a `point` first go to `Paint` for hit testing.
641        if event.event.point().is_some() {
642            if !servo.paint().notify_input_event(self.id(), event) {
643                servo.add_pending_handled_input_event(PendingHandledInputEvent {
644                    event_id,
645                    webview_id,
646                });
647                servo.event_loop_waker().wake();
648            }
649        } else {
650            servo
651                .constellation_proxy()
652                .send(EmbedderToConstellationMessage::ForwardInputEvent(
653                    webview_id, event, None, /* hit_test */
654                ));
655        }
656
657        event_id
658    }
659
660    /// Notify this [`WebView`] about a media session event (e.g. play, pause, next track).
661    pub fn notify_media_session_action_event(&self, event: MediaSessionActionType) {
662        self.servo()
663            .constellation_proxy()
664            .send(EmbedderToConstellationMessage::MediaSessionAction(event));
665    }
666
667    /// Set the page zoom of the [`WebView`]. This sets the final page zoom value of the
668    /// [`WebView`]. Unlike [`WebView::pinch_zoom`] *it is not* multiplied by the current
669    /// page zoom value, but overrides it.
670    ///
671    /// [`WebView`]s have two types of zoom, pinch zoom and page zoom. This adjusts page
672    /// zoom, which will adjust the `devicePixelRatio` of the page and cause it to modify
673    /// its layout.
674    ///
675    /// These values will be clamped internally to the inclusive range [0.1, 10.0]).
676    pub fn set_page_zoom(&self, new_zoom: f32) {
677        self.servo().paint().set_page_zoom(self.id(), new_zoom);
678    }
679
680    /// Get the page zoom of the [`WebView`].
681    pub fn page_zoom(&self) -> f32 {
682        self.servo().paint().page_zoom(self.id())
683    }
684
685    /// Adjust the pinch zoom on this [`WebView`] multiplying the current pinch zoom
686    /// level with the provided `pinch_zoom_delta`.
687    ///
688    /// [`WebView`]s have two types of zoom, pinch zoom and page zoom. This adjusts pinch
689    /// zoom, which is a type of zoom which does not modify layout, and instead simply
690    /// magnifies the view in the viewport.
691    ///
692    /// The final pinch zoom values will be clamped to defaults (the inclusive range [1.0, 10.0]).
693    /// The values used for clamping can be adjusted by page content when `<meta viewport>`
694    /// parsing is enabled via `Prefs::viewport_meta_enabled`, exclusively on mobile devices.
695    pub fn adjust_pinch_zoom(&self, pinch_zoom_delta: f32, center: DevicePoint) {
696        self.servo()
697            .paint()
698            .adjust_pinch_zoom(self.id(), pinch_zoom_delta, center);
699    }
700
701    /// Get the pinch zoom of the [`WebView`].
702    pub fn pinch_zoom(&self) -> f32 {
703        self.servo().paint().pinch_zoom(self.id())
704    }
705
706    /// Get the ratio of physical device pixels to CSS pixels for this [`WebView`].
707    ///
708    /// The returned scale factor takes into account page zoom, pinch zoom and the
709    /// HiDPI scaling factor.
710    pub fn device_pixels_per_css_pixel(&self) -> Scale<f32, CSSPixel, DevicePixel> {
711        self.servo().paint().device_pixels_per_page_pixel(self.id())
712    }
713
714    /// Tell the currently active page in this [`WebView`] to exit fullscreen mode.
715    pub fn exit_fullscreen(&self) {
716        self.servo()
717            .constellation_proxy()
718            .send(EmbedderToConstellationMessage::ExitFullScreen(self.id()));
719    }
720
721    /// Toggle the given [`WebRenderDebugOption`] from its current state.
722    ///
723    /// Note that this method toggles the debugging options globally i.e., it affects
724    /// all [`WebView`]s managed by Servo and not just the [`WebView`] on which
725    /// this method is invoked.
726    pub fn toggle_webrender_debugging(&self, debugging: WebRenderDebugOption) {
727        self.servo().paint().toggle_webrender_debug(debugging);
728    }
729
730    /// Capture the current WebRender state for this [`WebView`] for debugging.
731    ///
732    /// Note that the captured state includes information about all [`WebView`]s
733    /// that share this [`WebView`]'s [`RenderingContext`].
734    pub fn capture_webrender(&self) {
735        self.servo().paint().capture_webrender(self.id());
736    }
737
738    /// Paint the contents of this [`WebView`] into its [`RenderingContext`].
739    pub fn paint(&self) {
740        self.servo().paint().render(self.id());
741    }
742
743    /// Get the [`UserContentManager`] associated with this [`WebView`].
744    pub fn user_content_manager(&self) -> Option<Rc<UserContentManager>> {
745        self.inner().user_content_manager.clone()
746    }
747
748    /// Evaluate the specified string of JavaScript code. Once execution is complete or an error
749    /// occurs, Servo will call `callback`.
750    pub fn evaluate_javascript<T: ToString>(
751        &self,
752        script: T,
753        callback: impl FnOnce(Result<JSValue, JavaScriptEvaluationError>) + 'static,
754    ) {
755        self.servo().javascript_evaluator_mut().evaluate(
756            self.id(),
757            script.to_string(),
758            Box::new(callback),
759        );
760    }
761
762    /// Asynchronously take a screenshot of the [`WebView`] contents, given a `rect` or the whole
763    /// viewport, if no `rect` is given.
764    ///
765    /// This method will wait until the [`WebView`] is ready before the screenshot is taken.
766    /// This includes waiting for:
767    ///
768    ///  - all frames to fire their `load` event.
769    ///  - all render blocking elements, such as stylesheets included via the `<link>`
770    ///    element, to stop blocking the rendering.
771    ///  - all images to be loaded and displayed.
772    ///  - all web fonts are loaded.
773    ///  - the `reftest-wait` and `test-wait` classes have been removed from the root element.
774    ///  - the rendering is up-to-date
775    ///
776    /// Once all these conditions are met and the rendering does not have any pending frames
777    /// to render, the provided `callback` will be called with the results of the screenshot
778    /// operation.
779    pub fn take_screenshot(
780        &self,
781        rect: Option<WebViewRect>,
782        callback: impl FnOnce(Result<RgbaImage, ScreenshotCaptureError>) + 'static,
783    ) {
784        self.servo()
785            .paint()
786            .request_screenshot(self.id(), rect, Box::new(callback));
787    }
788
789    pub(crate) fn set_history(self, new_back_forward_list: Vec<ServoUrl>, new_index: usize) {
790        {
791            let mut inner_mut = self.inner_mut();
792            inner_mut.back_forward_list_index = new_index;
793            inner_mut.back_forward_list = new_back_forward_list
794                .into_iter()
795                .map(ServoUrl::into_url)
796                .collect();
797        }
798
799        let back_forward_list = self.inner().back_forward_list.clone();
800        let back_forward_list_index = self.inner().back_forward_list_index;
801        self.delegate().notify_url_changed(
802            self.clone(),
803            back_forward_list[back_forward_list_index].clone(),
804        );
805        self.delegate().notify_history_changed(
806            self.clone(),
807            back_forward_list,
808            back_forward_list_index,
809        );
810    }
811
812    pub(crate) fn show_embedder_control(
813        self,
814        control_id: EmbedderControlId,
815        position: DeviceIntRect,
816        embedder_control_request: EmbedderControlRequest,
817    ) {
818        let constellation_proxy = self.servo().constellation_proxy().clone();
819        let embedder_control = match embedder_control_request {
820            EmbedderControlRequest::SelectElement(request) => {
821                EmbedderControl::SelectElement(SelectElement {
822                    id: control_id,
823                    select_element_request: request,
824                    position,
825                    constellation_proxy,
826                    response_sent: false,
827                })
828            },
829            EmbedderControlRequest::ColorPicker(current_color) => {
830                EmbedderControl::ColorPicker(ColorPicker {
831                    id: control_id,
832                    current_color: Some(current_color),
833                    position,
834                    constellation_proxy,
835                    response_sent: false,
836                })
837            },
838            EmbedderControlRequest::InputMethod(input_method_request) => {
839                EmbedderControl::InputMethod(InputMethodControl {
840                    id: control_id,
841                    input_method_type: input_method_request.input_method_type,
842                    text: input_method_request.text,
843                    insertion_point: input_method_request.insertion_point,
844                    position,
845                    multiline: input_method_request.multiline,
846                    allow_virtual_keyboard: input_method_request.allow_virtual_keyboard,
847                })
848            },
849            EmbedderControlRequest::ContextMenu(mut context_menu_request) => {
850                // Close the old open context menu before opening another one anywhere.
851                if let Some(old_id) = self.inner().open_context_menu.replace(Some(control_id)) &&
852                    old_id.pipeline_id != control_id.pipeline_id
853                {
854                    self.delegate().hide_embedder_control(self.clone(), old_id);
855                }
856
857                for item in context_menu_request.items.iter_mut() {
858                    match item {
859                        ContextMenuItem::Item {
860                            action: ContextMenuAction::GoBack,
861                            enabled,
862                            ..
863                        } => *enabled = self.can_go_back(),
864                        ContextMenuItem::Item {
865                            action: ContextMenuAction::GoForward,
866                            enabled,
867                            ..
868                        } => *enabled = self.can_go_forward(),
869                        _ => {},
870                    }
871                }
872                EmbedderControl::ContextMenu(ContextMenu {
873                    id: control_id,
874                    position,
875                    items: context_menu_request.items,
876                    element_info: context_menu_request.element_info,
877                    constellation_proxy,
878                    response_sent: false,
879                })
880            },
881            EmbedderControlRequest::FilePicker { .. } => {
882                unreachable!("This message should be routed through the FileManagerThread")
883            },
884            EmbedderControlRequest::Tooltip(tooltip_request) => {
885                EmbedderControl::Tooltip(TooltipControl {
886                    id: control_id,
887                    text: tooltip_request.text,
888                })
889            },
890        };
891
892        self.delegate()
893            .show_embedder_control(self.clone(), embedder_control);
894    }
895
896    /// AccessKit subtree id for this [`WebView`], if accessibility is active.
897    pub fn accesskit_tree_id(&self) -> Option<TreeId> {
898        self.inner().accesskit_tree_id
899    }
900
901    /// Activate or deactivate accessibility features for this [`WebView`], returning the
902    /// AccessKit subtree id if accessibility is now active.
903    ///
904    /// After accessibility is activated, you must [graft] (with [`set_tree_id()`]) the returned
905    /// [`TreeId`] into your application’s main AccessKit tree as soon as possible, *before*
906    /// sending any tree updates from the webview to your AccessKit adapter. Otherwise you may
907    /// violate AccessKit’s subtree invariants and **panic**.
908    ///
909    /// If your impl for [`WebViewDelegate::notify_accessibility_tree_update()`] can’t create the
910    /// graft node (and send *that* update to AccessKit) before sending any updates from this
911    /// webview to AccessKit, then it must queue those updates until it can guarantee that.
912    ///
913    /// [graft]: https://docs.rs/accesskit/0.24.0/accesskit/struct.Node.html#method.tree_id
914    /// [`set_tree_id()`]: https://docs.rs/accesskit/0.24.0/accesskit/struct.Node.html#method.set_tree_id
915    pub fn set_accessibility_active(&self, active: bool) -> Option<TreeId> {
916        if !pref!(accessibility_enabled) {
917            return None;
918        }
919
920        if active == self.inner().accesskit_tree_id.is_some() {
921            return self.accesskit_tree_id();
922        }
923
924        if active {
925            let accesskit_tree_id = TreeId(AccesskitUuid::new_v4());
926            self.inner_mut().accesskit_tree_id = Some(accesskit_tree_id);
927        } else {
928            self.inner_mut().accesskit_tree_id = None;
929            self.inner_mut().grafted_accesskit_tree_id = None;
930            self.inner_mut().grafted_accesskit_tree_epoch = None;
931        }
932
933        self.send_accessibility_root_node();
934
935        self.servo().constellation_proxy().send(
936            EmbedderToConstellationMessage::SetAccessibilityActive(self.id(), active),
937        );
938
939        self.accesskit_tree_id()
940    }
941
942    pub(crate) fn notify_document_accessibility_tree_id(&self, grafted_tree_id: TreeId) {
943        let old_grafted_tree_id = self
944            .inner_mut()
945            .grafted_accesskit_tree_id
946            .replace(grafted_tree_id);
947        // TODO(#4344): try to avoid duplicate notifications in the first place?
948        // (see ConstellationWebView::new for more details)
949        if old_grafted_tree_id == Some(grafted_tree_id) {
950            return;
951        }
952        self.send_accessibility_root_node();
953    }
954
955    /// Record that this [`WebView`]'s accessibility viewport geometry changed (its size, page or
956    /// pinch zoom, or HiDPI scale). The root accessibility node covers the viewport and carries the
957    /// scale the grafted document nodes are resolved against, so it must be re-sent whenever that
958    /// geometry changes. This is called from the paint layer via
959    /// [`WebViewTrait::notify_viewport_updated()`]; the re-send itself is deferred to [`Servo`]'s
960    /// event loop (see `Servo::resend_accessibility_root_nodes_for_viewport_changes()`) so that it
961    /// never calls into the [`WebViewDelegate`] while the paint `RefCell` (or the embedder-facing
962    /// method that triggered the change) is on the stack.
963    pub(crate) fn note_accessibility_viewport_changed(&self) {
964        self.inner().accessibility_viewport_changed.set(true);
965    }
966
967    /// Take (and reset) the flag set by [`Self::note_accessibility_viewport_changed()`].
968    pub(crate) fn take_accessibility_viewport_changed(&self) -> bool {
969        self.inner().accessibility_viewport_changed.take()
970    }
971
972    /// Send the `WebView`-level accessibility root node, which grafts in the current document's
973    /// tree and carries the viewport bounds and scale that the document's own node bounds are
974    /// resolved against.
975    ///
976    /// This must be re-sent whenever that geometry changes, not only when the grafted document
977    /// changes, because the document nodes underneath are expressed relative to it.
978    pub(crate) fn send_accessibility_root_node(&self) {
979        let Some(webview_accesskit_tree_id) = self.inner().accesskit_tree_id else {
980            return;
981        };
982        let Some(grafted_tree_id) = self.inner().grafted_accesskit_tree_id else {
983            return;
984        };
985        let root_node_id = NodeId(0);
986        let mut root_node = AccesskitNode::new(Role::ScrollView);
987        // The root node covers the whole viewport, in the same coordinate space as the bounds of
988        // the document nodes grafted underneath it: CSS pixels relative to the viewport origin.
989        //
990        // Its transform converts those CSS pixels into device pixels. That scale is everything
991        // which maps a CSS pixel to a device pixel — page zoom, pinch zoom and HiDPI scale factor.
992        //
993        // See `update_bounds_from_dom_node()` in
994        // `components/layout/accessibility_tree.rs` for how bounds are computed for web contents.
995
996        // Compute the ratio from the WebView's current settings. `device_pixels_per_css_pixel()`
997        // reports the ratio the latest rendered display list was produced with, which lags behind
998        // the zoom/HiDPI change that triggered this call, since reflow is asynchronous.
999        let device_pixels_per_css_pixel =
1000            self.page_zoom() * self.hidpi_scale_factor().get() * self.pinch_zoom();
1001        let size =
1002            self.size() / Scale::<f32, CSSPixel, DevicePixel>::new(device_pixels_per_css_pixel);
1003        root_node.set_bounds(AccesskitRect::new(
1004            0.0,
1005            0.0,
1006            size.width as f64,
1007            size.height as f64,
1008        ));
1009        // AccessKit asks that a node with an identity transform leave it unset.
1010        if device_pixels_per_css_pixel != 1.0 {
1011            root_node.set_transform(AccesskitAffine::scale(device_pixels_per_css_pixel as f64));
1012        }
1013        let graft_node_id = NodeId(1);
1014        let mut graft_node = AccesskitNode::new(Role::GenericContainer);
1015        graft_node.set_tree_id(grafted_tree_id);
1016        root_node.set_children(vec![graft_node_id]);
1017        self.delegate().notify_accessibility_tree_update(
1018            self.clone(),
1019            TreeUpdate {
1020                nodes: vec![(root_node_id, root_node), (graft_node_id, graft_node)],
1021                tree: Some(TreeInfo {
1022                    root: root_node_id,
1023                    toolkit_name: None,
1024                    toolkit_version: None,
1025                }),
1026                tree_id: webview_accesskit_tree_id,
1027                focus: root_node_id,
1028            },
1029        );
1030    }
1031
1032    /// After a new tree has been grafted, move focus to the graft node so that the grafted tree's
1033    /// focused node becomes the focused node for the webview.
1034    fn move_accessibility_focus_to_graft_node(&self) {
1035        let Some(webview_accesskit_tree_id) = self.inner().accesskit_tree_id else {
1036            return;
1037        };
1038        let root_node_id = NodeId(0);
1039        let graft_node_id = NodeId(1);
1040
1041        self.delegate().notify_accessibility_tree_update(
1042            self.clone(),
1043            TreeUpdate {
1044                nodes: vec![],
1045                tree: Some(TreeInfo {
1046                    root: root_node_id,
1047                    toolkit_name: None,
1048                    toolkit_version: None,
1049                }),
1050                tree_id: webview_accesskit_tree_id,
1051                focus: graft_node_id,
1052            },
1053        );
1054    }
1055
1056    pub(crate) fn process_accessibility_tree_update(&self, tree_update: TreeUpdate, epoch: Epoch) {
1057        if self
1058            .inner()
1059            .grafted_accesskit_tree_epoch
1060            .is_some_and(|current| epoch < current)
1061        {
1062            // We expect this to happen occasionally when the constellation navigates, because
1063            // deactivating accessibility happens asynchronously, so the script thread of the
1064            // previously active document may continue sending updates for a short period of time.
1065            debug!("Ignoring stale tree update for {:?}", tree_update.tree_id);
1066            return;
1067        }
1068        if self
1069            .inner()
1070            .grafted_accesskit_tree_epoch
1071            .is_none_or(|current| epoch > current)
1072        {
1073            // This three-step process is necessary because we need the graft node to be the focused
1074            // node in the WebView's accessibility tree, but we can't make it the focused node until
1075            // the graft is completed by sending the initial tree update for the new tree.
1076            self.notify_document_accessibility_tree_id(tree_update.tree_id);
1077            self.inner_mut().grafted_accesskit_tree_epoch = Some(epoch);
1078
1079            self.delegate()
1080                .notify_accessibility_tree_update(self.clone(), tree_update);
1081
1082            self.move_accessibility_focus_to_graft_node();
1083            return;
1084        }
1085
1086        self.delegate()
1087            .notify_accessibility_tree_update(self.clone(), tree_update);
1088    }
1089
1090    /// Clear the session history of this [`WebView`]. The session history is also known
1091    /// as the back-forward cache. Once cleared, [`WebViewDelegate::notify_history`]
1092    /// will be called asynchronously and the resulting session history will contain only
1093    /// a single item with the current URL.
1094    pub fn clear_session_history(&self) {
1095        self.servo().constellation_proxy().send(
1096            EmbedderToConstellationMessage::ClearSessionHistory(self.id()),
1097        );
1098    }
1099}
1100
1101/// A structure used to expose a view of the [`WebView`] to the Servo
1102/// renderer, without having the Servo renderer depend on the embedding layer.
1103struct ServoRendererWebView {
1104    id: WebViewId,
1105    weak_handle: Weak<RefCell<WebViewInner>>,
1106}
1107
1108impl WebViewTrait for ServoRendererWebView {
1109    fn id(&self) -> WebViewId {
1110        self.id
1111    }
1112
1113    fn screen_geometry(&self) -> Option<ScreenGeometry> {
1114        let webview = WebView::from_weak_handle(&self.weak_handle)?;
1115        webview.delegate().screen_geometry(webview)
1116    }
1117
1118    fn set_animating(&self, new_value: bool) {
1119        if let Some(webview) = WebView::from_weak_handle(&self.weak_handle) {
1120            webview.set_animating(new_value);
1121        }
1122    }
1123
1124    fn notify_viewport_updated(&self) {
1125        if let Some(webview) = WebView::from_weak_handle(&self.weak_handle) {
1126            webview.note_accessibility_viewport_changed();
1127        }
1128    }
1129}
1130
1131/// Builder for creating a [`WebView`].
1132pub struct WebViewBuilder {
1133    servo: Servo,
1134    rendering_context: Rc<dyn RenderingContext>,
1135    delegate: Rc<dyn WebViewDelegate>,
1136    url: Option<Url>,
1137    hidpi_scale_factor: Scale<f32, DeviceIndependentPixel, DevicePixel>,
1138    create_new_webview_responder: Option<AutomaticResponder<Option<NewWebViewDetails>>>,
1139    user_content_manager: Option<Rc<UserContentManager>>,
1140    clipboard_delegate: Option<Rc<dyn ClipboardDelegate>>,
1141    #[cfg(feature = "gamepad")]
1142    gamepad_delegate: Option<Rc<dyn GamepadDelegate>>,
1143    geolocation_delegate: Option<Rc<dyn GeolocationDelegate>>,
1144}
1145
1146impl WebViewBuilder {
1147    /// Create a [`WebViewBuilder`] that can be used to configure and create a [`WebView`].
1148    ///
1149    /// The new [`WebView`] will be managed by the given `servo` instance and will
1150    /// use `rendering_context` to paint its contents.
1151    pub fn new(servo: &Servo, rendering_context: Rc<dyn RenderingContext>) -> Self {
1152        Self {
1153            servo: servo.clone(),
1154            rendering_context,
1155            url: None,
1156            hidpi_scale_factor: Scale::new(1.0),
1157            delegate: Rc::new(DefaultWebViewDelegate),
1158            create_new_webview_responder: None,
1159            user_content_manager: None,
1160            clipboard_delegate: None,
1161            #[cfg(feature = "gamepad")]
1162            gamepad_delegate: None,
1163            geolocation_delegate: None,
1164        }
1165    }
1166
1167    pub(crate) fn new_for_create_request(
1168        servo: &Servo,
1169        rendering_context: Rc<dyn RenderingContext>,
1170        responder: AutomaticResponder<Option<NewWebViewDetails>>,
1171    ) -> Self {
1172        let mut builder = Self::new(servo, rendering_context);
1173        builder.create_new_webview_responder = Some(responder);
1174        builder
1175    }
1176
1177    /// Set the [`WebViewDelegate`] that will receive notifications about the events
1178    /// in the [`WebView`] being created.
1179    pub fn delegate(mut self, delegate: Rc<dyn WebViewDelegate>) -> Self {
1180        self.delegate = delegate;
1181        self
1182    }
1183
1184    /// Set the initial URL to load in the [`WebView`] being created.
1185    pub fn url(mut self, url: Url) -> Self {
1186        self.url = Some(url);
1187        self
1188    }
1189
1190    /// Set the initial HiDPI scale factor for the [`WebView`] being created.
1191    pub fn hidpi_scale_factor(
1192        mut self,
1193        hidpi_scale_factor: Scale<f32, DeviceIndependentPixel, DevicePixel>,
1194    ) -> Self {
1195        self.hidpi_scale_factor = hidpi_scale_factor;
1196        self
1197    }
1198
1199    /// Set the [`UserContentManager`] for the `WebView` being created. The same
1200    /// `UserContentManager` can be shared among multiple `WebView`s. Any updates
1201    /// to the `UserContentManager` will take effect only after the document is reloaded.
1202    pub fn user_content_manager(mut self, user_content_manager: Rc<UserContentManager>) -> Self {
1203        self.user_content_manager = Some(user_content_manager);
1204        self
1205    }
1206
1207    /// Set the [`ClipboardDelegate`] for the `WebView` being created. The same
1208    /// [`ClipboardDelegate`] can be shared among multiple `WebView`s.
1209    pub fn clipboard_delegate(mut self, clipboard_delegate: Rc<dyn ClipboardDelegate>) -> Self {
1210        self.clipboard_delegate = Some(clipboard_delegate);
1211        self
1212    }
1213
1214    /// Set the [`GamepadDelegate`] for the `WebView` being created. The same
1215    /// [`GamepadDelegate`] can be shared among multiple `WebView`s.
1216    #[cfg(feature = "gamepad")]
1217    pub fn gamepad_delegate(mut self, gamepad_delegate: Rc<dyn GamepadDelegate>) -> Self {
1218        self.gamepad_delegate = Some(gamepad_delegate);
1219        self
1220    }
1221
1222    /// Set the [`GeolocationDelegate`] for the `WebView` being created. The same
1223    /// [`GeolocationDelegate`] can be shared among multiple `WebView`s.
1224    pub fn geolocation_delegate(
1225        mut self,
1226        geolocation_delegate: Rc<dyn GeolocationDelegate>,
1227    ) -> Self {
1228        self.geolocation_delegate = Some(geolocation_delegate);
1229        self
1230    }
1231
1232    /// Create the [`WebView`] using the configuration specified in this [`WebViewBuilder`].
1233    pub fn build(self) -> WebView {
1234        WebView::new(self)
1235    }
1236}