Skip to main content

servoshell/
window.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::rc::Rc;
7#[cfg(target_os = "android")]
8use std::sync::atomic::AtomicU64;
9
10use euclid::Scale;
11use log::warn;
12use servo::{
13    AuthenticationRequest, BluetoothDeviceSelectionRequest, ConsoleLogLevel,
14    CreateNewWebViewRequest, Cursor, DeviceIndependentIntRect, DeviceIndependentPixel,
15    DeviceIntPoint, DeviceIntSize, DevicePixel, EmbedderControl, EmbedderControlId, InputEventId,
16    InputEventResult, PermissionRequest, RenderingContext, ScreenGeometry, WebView, WebViewBuilder,
17    WebViewId,
18};
19use url::Url;
20
21use crate::parser::location_bar_input_to_url;
22use crate::running_app_state::{RunningAppState, UserInterfaceCommand, WebViewCollection};
23
24// This should vary by zoom level and maybe actual text size (focused or under cursor)
25#[cfg_attr(any(target_os = "android", target_env = "ohos"), expect(dead_code))]
26pub(crate) const LINE_HEIGHT: f32 = 76.0;
27#[cfg_attr(any(target_os = "android", target_env = "ohos"), expect(dead_code))]
28pub(crate) const LINE_WIDTH: f32 = 76.0;
29
30/// <https://github.com/web-platform-tests/wpt/blob/9320b1f724632c52929a3fdb11bdaf65eafc7611/webdriver/tests/classic/set_window_rect/set.py#L287-L290>
31/// "A window size of 10x10px shouldn't be supported by any browser."
32#[cfg_attr(any(target_os = "android", target_env = "ohos"), expect(dead_code))]
33pub(crate) const MIN_WINDOW_INNER_SIZE: DeviceIntSize = DeviceIntSize::new(100, 100);
34
35#[cfg(target_os = "android")]
36static SERVOSHELL_WINDOW_ID: AtomicU64 = AtomicU64::new(0);
37
38#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
39pub(crate) struct ServoShellWindowId(u64);
40
41impl From<u64> for ServoShellWindowId {
42    fn from(value: u64) -> Self {
43        Self(value)
44    }
45}
46
47impl From<u32> for ServoShellWindowId {
48    fn from(value: u32) -> Self {
49        Self(u64::from(value))
50    }
51}
52
53impl ServoShellWindowId {
54    #[cfg(target_os = "android")]
55    pub(crate) fn next() -> ServoShellWindowId {
56        ServoShellWindowId(SERVOSHELL_WINDOW_ID.fetch_add(1, std::sync::atomic::Ordering::SeqCst))
57    }
58
59    /// Expose the inner ID
60    #[cfg_attr(not(target_env = "ohos"), expect(unused))]
61    pub(crate) fn raw(self) -> u64 {
62        self.0
63    }
64}
65
66pub(crate) struct ServoShellWindow {
67    /// The [`WebView`]s that have been added to this window.
68    webview_collection: RefCell<WebViewCollection>,
69    /// A handle to the [`PlatformWindow`] that servoshell is rendering in.
70    platform_window: Rc<dyn PlatformWindow>,
71    /// Whether or not this window should be closed at the end of the spin of the next event loop.
72    close_scheduled: Cell<bool>,
73    /// Whether or not the application interface needs to be updated.
74    needs_update: Cell<bool>,
75    /// Whether or not Servo needs to repaint its display. Currently this is global
76    /// because every `WebView` shares a `RenderingContext`.
77    needs_repaint: Cell<bool>,
78    /// List of webviews that have favicon textures which are not yet uploaded
79    /// to the GPU by egui.
80    pending_favicon_loads: RefCell<Vec<WebViewId>>,
81    /// Pending [`UserInterfaceCommand`] that have yet to be processed by the main loop.
82    pending_commands: RefCell<Vec<UserInterfaceCommand>>,
83}
84
85pub(crate) enum TopLevelWebViewCreationRequest {
86    WithUrl(Url),
87    WithCreateRequest(CreateNewWebViewRequest),
88}
89
90impl ServoShellWindow {
91    pub(crate) fn new(platform_window: Rc<dyn PlatformWindow>) -> Self {
92        Self {
93            webview_collection: Default::default(),
94            platform_window,
95            close_scheduled: Default::default(),
96            needs_update: Default::default(),
97            needs_repaint: Default::default(),
98            pending_favicon_loads: Default::default(),
99            pending_commands: Default::default(),
100        }
101    }
102
103    pub(crate) fn id(&self) -> ServoShellWindowId {
104        self.platform_window().id()
105    }
106
107    /// Must be called *after* `self` is in `state.windows`, otherwise it will panic.
108    pub(crate) fn create_and_activate_toplevel_webview(
109        self: &Rc<Self>,
110        state: Rc<RunningAppState>,
111        creation_type: TopLevelWebViewCreationRequest,
112    ) -> WebView {
113        let webview = self.create_toplevel_webview(state, creation_type);
114        self.activate_webview(webview.id());
115        webview
116    }
117
118    /// Must be called *after* `self` is in `state.windows`, otherwise it will panic.
119    #[servo::servo_tracing::instrument(skip(self, state, creation_type))]
120    pub(crate) fn create_toplevel_webview(
121        &self,
122        state: Rc<RunningAppState>,
123        creation_type: TopLevelWebViewCreationRequest,
124    ) -> WebView {
125        let mut webview_builder = match creation_type {
126            TopLevelWebViewCreationRequest::WithUrl(url) => {
127                WebViewBuilder::new(state.servo(), self.platform_window.rendering_context())
128                    .url(url)
129            },
130            TopLevelWebViewCreationRequest::WithCreateRequest(request) => {
131                request.builder(self.platform_window.rendering_context())
132            },
133        };
134        webview_builder = webview_builder
135            .hidpi_scale_factor(self.platform_window.hidpi_scale_factor())
136            .user_content_manager(state.user_content_manager.clone())
137            .delegate(state.clone());
138
139        #[cfg(all(
140            feature = "gamepad",
141            not(any(target_os = "android", target_env = "ohos"))
142        ))]
143        if let Some(gamepad_delegate) = state.gamepad_delegate() {
144            webview_builder = webview_builder.gamepad_delegate(gamepad_delegate);
145        }
146
147        let webview = webview_builder.build();
148        self.add_webview(webview.clone());
149
150        // If `self` is not in `state.windows`, our notify_accessibility_tree_update() will panic.
151        if state.accessibility_active() {
152            // Activate accessibility in the WebView.
153            // There are two sites like this; this is the WebView creation site.
154            webview.set_accessibility_active(true);
155        }
156        webview
157    }
158
159    /// Repaint the active [`WebView`].
160    pub(crate) fn repaint_webviews(&self) {
161        let Some(webview) = self.active_webview() else {
162            return;
163        };
164
165        self.platform_window()
166            .rendering_context()
167            .make_current()
168            .expect("Could not make PlatformWindow RenderingContext current");
169        webview.paint();
170        self.platform_window().rendering_context().present();
171    }
172
173    /// Whether or not this [`ServoShellWindow`] has any [`WebView`]s.
174    pub(crate) fn should_close(&self) -> bool {
175        self.webview_collection.borrow().is_empty() || self.close_scheduled.get()
176    }
177
178    pub(crate) fn webview_by_id(&self, id: WebViewId) -> Option<WebView> {
179        self.webview_collection.borrow().get(id).cloned()
180    }
181
182    pub(crate) fn set_needs_update(&self) {
183        self.needs_update.set(true);
184    }
185
186    pub(crate) fn set_needs_repaint(&self) {
187        self.needs_repaint.set(true)
188    }
189
190    #[cfg_attr(target_os = "android", expect(dead_code))]
191    pub(crate) fn schedule_close(&self) {
192        self.close_scheduled.set(true)
193    }
194
195    pub(crate) fn platform_window(&self) -> Rc<dyn PlatformWindow> {
196        self.platform_window.clone()
197    }
198
199    pub(crate) fn add_webview(&self, webview: WebView) {
200        webview.notify_theme_change(self.platform_window.theme());
201        self.webview_collection.borrow_mut().add(webview);
202        self.set_needs_update();
203        self.set_needs_repaint();
204    }
205
206    pub(crate) fn webview_ids(&self) -> Vec<WebViewId> {
207        self.webview_collection.borrow().creation_order.clone()
208    }
209
210    /// Returns all [`WebView`]s in creation order.
211    pub(crate) fn webviews(&self) -> Vec<(WebViewId, WebView)> {
212        self.webview_collection()
213            .all_in_creation_order()
214            .map(|(id, webview)| (id, webview.clone()))
215            .collect()
216    }
217
218    pub(crate) fn webview_collection(&self) -> Ref<'_, WebViewCollection> {
219        self.webview_collection.borrow()
220    }
221
222    pub(crate) fn webview_collection_mut(&self) -> RefMut<'_, WebViewCollection> {
223        self.webview_collection.borrow_mut()
224    }
225
226    pub(crate) fn activate_webview(&self, webview_id: WebViewId) {
227        self.webview_collection
228            .borrow_mut()
229            .activate_webview(webview_id);
230        self.set_needs_update();
231    }
232
233    #[cfg_attr(any(target_os = "android", target_env = "ohos"), expect(dead_code))]
234    pub(crate) fn activate_webview_by_index(&self, index_to_activate: usize) {
235        self.webview_collection
236            .borrow_mut()
237            .activate_webview_by_index(index_to_activate);
238        self.set_needs_update();
239    }
240
241    #[cfg_attr(any(target_os = "android", target_env = "ohos"), expect(dead_code))]
242    pub(crate) fn get_active_webview_index(&self) -> Option<usize> {
243        let active_id = self.webview_collection.borrow().active_id()?;
244        self.webviews()
245            .iter()
246            .position(|webview| webview.0 == active_id)
247    }
248
249    pub(crate) fn update_and_request_repaint_if_necessary(&self, state: &RunningAppState) {
250        let updated_user_interface = self.needs_update.take() &&
251            self.platform_window
252                .update_user_interface_state(state, self);
253
254        // Delegate handlers may have asked us to present or update painted WebView contents.
255        // Currently, egui-file-dialog dialogs need to be constantly redrawn or animations aren't fluid.
256        let needs_repaint = self.needs_repaint.take();
257        if updated_user_interface || needs_repaint {
258            self.platform_window.request_repaint(self);
259        }
260    }
261
262    /// Close the given [`WebView`] via its [`WebViewId`].
263    ///
264    /// Note: This can happen because we can trigger a close with a UI action and then get
265    /// the close notification via the [`WebViewDelegate`] later.
266    pub(crate) fn close_webview(&self, webview_id: WebViewId) {
267        let mut webview_collection = self.webview_collection.borrow_mut();
268        if webview_collection.remove(webview_id).is_none() {
269            return;
270        }
271        self.platform_window
272            .dismiss_embedder_controls_for_webview(webview_id);
273
274        self.set_needs_update();
275        self.set_needs_repaint();
276    }
277
278    pub(crate) fn notify_favicon_changed(&self, webview: WebView) {
279        self.pending_favicon_loads.borrow_mut().push(webview.id());
280        self.set_needs_repaint();
281    }
282
283    #[cfg_attr(any(target_os = "android", target_env = "ohos"), expect(dead_code))]
284    pub(crate) fn hidpi_scale_factor_changed(&self) {
285        let new_scale_factor = self.platform_window.hidpi_scale_factor();
286        for webview in self.webview_collection.borrow().values() {
287            webview.set_hidpi_scale_factor(new_scale_factor);
288        }
289    }
290
291    pub(crate) fn active_webview(&self) -> Option<WebView> {
292        self.webview_collection.borrow().active().cloned()
293    }
294
295    #[cfg_attr(
296        not(any(target_os = "android", target_env = "ohos")),
297        expect(dead_code)
298    )]
299    pub(crate) fn active_or_newest_webview(&self) -> Option<WebView> {
300        let webview_collection = self.webview_collection.borrow();
301        webview_collection
302            .active()
303            .or(webview_collection.newest())
304            .cloned()
305    }
306
307    /// Return a list of all webviews that have favicons that have not yet been loaded by egui.
308    #[cfg_attr(any(target_os = "android", target_env = "ohos"), expect(dead_code))]
309    pub(crate) fn take_pending_favicon_loads(&self) -> Vec<WebViewId> {
310        std::mem::take(&mut *self.pending_favicon_loads.borrow_mut())
311    }
312
313    pub(crate) fn show_embedder_control(
314        &self,
315        webview: WebView,
316        embedder_control: EmbedderControl,
317    ) {
318        self.platform_window
319            .show_embedder_control(webview.id(), embedder_control);
320        self.set_needs_update();
321        self.set_needs_repaint();
322    }
323
324    pub(crate) fn hide_embedder_control(
325        &self,
326        webview: WebView,
327        embedder_control: EmbedderControlId,
328    ) {
329        self.platform_window
330            .hide_embedder_control(webview.id(), embedder_control);
331        self.set_needs_update();
332        self.set_needs_repaint();
333    }
334
335    pub(crate) fn queue_user_interface_command(&self, command: UserInterfaceCommand) {
336        self.pending_commands.borrow_mut().push(command)
337    }
338
339    /// Takes any events generated during UI updates and performs their actions.
340    pub(crate) fn handle_interface_commands(
341        self: &Rc<Self>,
342        state: &Rc<RunningAppState>,
343        create_platform_window: Option<&dyn Fn(Url) -> Rc<dyn PlatformWindow>>,
344    ) {
345        let commands = std::mem::take(&mut *self.pending_commands.borrow_mut());
346        for event in commands {
347            match event {
348                UserInterfaceCommand::Go(location) => {
349                    self.set_needs_update();
350                    let Some(url) = location_bar_input_to_url(
351                        &location.clone(),
352                        &state.servoshell_preferences.searchpage,
353                    ) else {
354                        warn!("failed to parse location");
355                        break;
356                    };
357                    if let Some(active_webview) = self.active_webview() {
358                        active_webview.load(url.into_url());
359                    }
360                },
361                UserInterfaceCommand::Back => {
362                    if let Some(active_webview) = self.active_webview() {
363                        active_webview.go_back(1);
364                    }
365                },
366                UserInterfaceCommand::Forward => {
367                    if let Some(active_webview) = self.active_webview() {
368                        active_webview.go_forward(1);
369                    }
370                },
371                UserInterfaceCommand::Reload => {
372                    self.set_needs_update();
373                    if let Some(active_webview) = self.active_webview() {
374                        active_webview.reload();
375                    }
376                },
377                UserInterfaceCommand::ReloadAll => {
378                    for window in state.windows().iter() {
379                        window.set_needs_update();
380                        for (_, webview) in window.webviews() {
381                            webview.reload();
382                        }
383                    }
384                },
385                UserInterfaceCommand::NewWebView => {
386                    self.set_needs_update();
387                    let url = Url::parse("servo:newtab").expect("Should always be able to parse");
388                    self.create_and_activate_toplevel_webview(
389                        state.clone(),
390                        TopLevelWebViewCreationRequest::WithUrl(url),
391                    );
392                },
393                UserInterfaceCommand::CloseWebView(id) => {
394                    self.set_needs_update();
395                    self.close_webview(id);
396                },
397                UserInterfaceCommand::NewWindow(creation_request) => {
398                    let Some(create_platform_window) = create_platform_window else {
399                        continue;
400                    };
401                    let url = match &creation_request {
402                        TopLevelWebViewCreationRequest::WithUrl(url) => url.clone(),
403                        TopLevelWebViewCreationRequest::WithCreateRequest(..) => {
404                            Url::parse("servo:newtab").unwrap()
405                        },
406                    };
407                    let platform_window = create_platform_window(url);
408                    state.open_window(platform_window, creation_request);
409                },
410            }
411        }
412    }
413
414    #[cfg_attr(any(target_os = "android", target_env = "ohos"), expect(dead_code))]
415    pub(crate) fn set_accessibility_active(self: &Rc<Self>, active: bool) {
416        for (_, webview) in self.webviews() {
417            // Activate accessibility in the WebView.
418            // There are two sites like this; this is the a11y activation site.
419            webview.set_accessibility_active(active);
420        }
421    }
422}
423
424/// A `PlatformWindow` abstracts away the differents kinds of platform windows that might
425/// be used in a servoshell execution. This currently includes headed (winit) and headless
426/// windows.
427pub(crate) trait PlatformWindow {
428    /// Whether or not the platform manages focus. This is used to decide whether
429    /// servoshell should focus another window when one closes.
430    fn platform_manages_focus(&self) -> bool {
431        false
432    }
433
434    fn id(&self) -> ServoShellWindowId;
435    fn screen_geometry(&self) -> ScreenGeometry;
436    #[cfg_attr(any(target_os = "android", target_env = "ohos"), expect(dead_code))]
437    fn device_hidpi_scale_factor(&self) -> Scale<f32, DeviceIndependentPixel, DevicePixel>;
438    fn hidpi_scale_factor(&self) -> Scale<f32, DeviceIndependentPixel, DevicePixel>;
439    #[cfg_attr(any(target_os = "android", target_env = "ohos"), expect(dead_code))]
440    fn get_fullscreen(&self) -> bool;
441    /// Inform the `Window` that the state of a `WebView` has changed and that it should
442    /// do an incremental update of user interface state. Returns `true` if the user
443    /// interface actually changed and a rebuild  and repaint is needed, `false` otherwise.
444    fn update_user_interface_state(&self, _: &RunningAppState, _: &ServoShellWindow) -> bool {
445        false
446    }
447    /// Request that the window redraw itself. It is up to the window to do this
448    /// once the windowing system is ready. If this is a headless window, the redraw
449    /// will happen immediately.
450    fn request_repaint(&self, _: &ServoShellWindow);
451    /// Request a new outer size for the window, including external decorations.
452    /// This should be the same as `window.outerWidth` and `window.outerHeight``
453    fn request_resize(&self, webview: &WebView, outer_size: DeviceIntSize)
454    -> Option<DeviceIntSize>;
455    fn set_position(&self, _point: DeviceIntPoint) {}
456    fn set_fullscreen(&self, _state: bool) {}
457    fn set_cursor(&self, _cursor: Cursor) {}
458    #[cfg(all(
459        feature = "webxr",
460        not(any(target_os = "android", target_env = "ohos"))
461    ))]
462    fn new_glwindow(
463        &self,
464        event_loop: &winit::event_loop::ActiveEventLoop,
465    ) -> Rc<dyn servo::webxr::GlWindow>;
466    /// This returns [`RenderingContext`] matching the viewport.
467    fn rendering_context(&self) -> Rc<dyn RenderingContext>;
468    fn theme(&self) -> servo::Theme {
469        servo::Theme::Light
470    }
471    fn window_rect(&self) -> DeviceIndependentIntRect;
472    fn maximize(&self, _: &WebView) {}
473    fn has_platform_focus(&self) -> bool {
474        true
475    }
476
477    fn show_embedder_control(&self, _: WebViewId, _: EmbedderControl) {}
478    fn hide_embedder_control(&self, _: WebViewId, _: EmbedderControlId) {}
479    fn dismiss_embedder_controls_for_webview(&self, _: WebViewId) {}
480    fn show_bluetooth_device_dialog(
481        &self,
482        _: WebViewId,
483        _request: BluetoothDeviceSelectionRequest,
484    ) {
485    }
486    fn show_permission_dialog(&self, _: WebViewId, _: PermissionRequest) {}
487    fn show_http_authentication_dialog(&self, _: WebViewId, _: AuthenticationRequest) {}
488
489    fn notify_input_event_handled(
490        &self,
491        _webview: &WebView,
492        _id: InputEventId,
493        _result: InputEventResult,
494    ) {
495    }
496
497    fn notify_crashed(&self, _: WebView, _reason: String, _backtrace: Option<String>) {}
498    fn show_console_message(&self, _level: ConsoleLogLevel, _message: &str) {}
499
500    #[cfg(not(any(target_os = "android", target_env = "ohos")))]
501    /// If this window is a headed window, access the concrete type.
502    fn as_headed_window(&self) -> Option<&crate::desktop::headed_window::HeadedWindow> {
503        None
504    }
505
506    #[cfg(any(target_os = "android", target_env = "ohos"))]
507    /// If this window is a headed window, access the concrete type.
508    fn as_headed_window(&self) -> Option<&crate::egl::app::EmbeddedPlatformWindow> {
509        None
510    }
511
512    fn notify_accessibility_tree_update(&self, _: WebView, _: accesskit::TreeUpdate) {}
513}