Skip to main content

servoshell/desktop/
headed_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
5//! A winit window implementation.
6
7#![deny(clippy::panic)]
8#![deny(clippy::unwrap_used)]
9
10use std::cell::{Cell, RefCell};
11use std::collections::HashMap;
12use std::rc::Rc;
13use std::thread::{self, JoinHandle};
14use std::time::{Duration, Instant};
15
16use crossbeam_channel::{RecvTimeoutError, Sender};
17use euclid::{Angle, Length, Point2D, Rect, Rotation3D, Scale, Size2D, UnknownUnit, Vector3D};
18use keyboard_types::ShortcutMatcher;
19use log::{debug, info};
20use raw_window_handle::{HasDisplayHandle, HasWindowHandle, RawWindowHandle};
21use servo::{
22    AuthenticationRequest, BluetoothDeviceSelectionRequest, Cursor, DeviceIndependentIntRect,
23    DeviceIndependentPixel, DeviceIntPoint, DeviceIntRect, DeviceIntSize, DevicePixel, DevicePoint,
24    EmbedderControl, EmbedderControlId, ImeEvent, InputEvent, InputEventId, InputEventResult,
25    InputMethodControl, Key, KeyState, KeyboardEvent, Modifiers, MouseButton as ServoMouseButton,
26    MouseButtonAction, MouseButtonEvent, MouseLeftViewportEvent, MouseMoveEvent, NamedKey,
27    OffscreenRenderingContext, PermissionRequest, RenderingContext, ScreenGeometry, Theme,
28    TouchEvent, TouchEventType, TouchId, TouchPointerType, WebRenderDebugOption, WebView,
29    WebViewId, WheelDelta, WheelEvent, WheelMode, WindowRenderingContext,
30    convert_rect_to_css_pixel,
31};
32use url::Url;
33use winit::dpi::{LogicalSize, PhysicalPosition, PhysicalSize};
34use winit::event::{
35    ElementState, Ime, KeyEvent, MouseButton, MouseScrollDelta, TouchPhase, WindowEvent,
36};
37use winit::event_loop::{ActiveEventLoop, EventLoopProxy};
38use winit::keyboard::{Key as LogicalKey, ModifiersState, NamedKey as WinitNamedKey};
39#[cfg(target_os = "linux")]
40use winit::platform::wayland::WindowAttributesExtWayland;
41#[cfg(any(target_os = "linux", target_os = "windows"))]
42use winit::window::Icon;
43#[cfg(target_os = "macos")]
44use {
45    objc2_app_kit::{NSColorSpace, NSView},
46    objc2_foundation::MainThreadMarker,
47};
48
49use super::geometry::{winit_position_to_euclid_point, winit_size_to_euclid_size};
50use super::keyutils::{CMD_OR_ALT, keyboard_event_from_winit};
51use crate::desktop::accelerated_gl_media::setup_gl_accelerated_media;
52use crate::desktop::dialog::Dialog;
53use crate::desktop::event_loop::{AppEvent, RepaintEventLoopWaker};
54use crate::desktop::gui::Gui;
55use crate::desktop::keyutils::{CMD_OR_CONTROL, keyboard_modifiers_from_winit_modifiers};
56use crate::prefs::ServoShellPreferences;
57use crate::running_app_state::{RunningAppState, UserInterfaceCommand};
58use crate::window::{
59    LINE_HEIGHT, LINE_WIDTH, MIN_WINDOW_INNER_SIZE, PlatformWindow, ServoShellWindow,
60    ServoShellWindowId, TopLevelWebViewCreationRequest,
61};
62
63pub(crate) const INITIAL_WINDOW_TITLE: &str = "Servo";
64
65pub(crate) const TOOLTIP_DELAY: Duration = Duration::from_millis(500);
66
67pub(crate) struct TooltipTimer {
68    sender: Option<Sender<Option<Instant>>>,
69    join_handle: Option<JoinHandle<()>>,
70}
71
72impl TooltipTimer {
73    fn new(proxy: EventLoopProxy<AppEvent>, window_id: ServoShellWindowId) -> Self {
74        let (sender, receiver) = crossbeam_channel::unbounded::<Option<Instant>>();
75        let join_handle = thread::Builder::new()
76            .name(String::from("TooltipTimerThread"))
77            .spawn(move || {
78                let mut deadline: Option<Instant> = None;
79                loop {
80                    let msg = match deadline {
81                        Some(at) => receiver.recv_deadline(at),
82                        None => receiver.recv().map_err(|_| RecvTimeoutError::Disconnected),
83                    };
84
85                    match msg {
86                        Ok(new_deadline) => deadline = new_deadline,
87                        Err(RecvTimeoutError::Timeout) => {
88                            deadline = None;
89                            let _ = proxy.send_event(AppEvent::RequestRepaint(window_id));
90                        },
91                        Err(RecvTimeoutError::Disconnected) => return,
92                    }
93                }
94            })
95            .expect("Could not create tooltip timer");
96
97        Self {
98            sender: Some(sender),
99            join_handle: Some(join_handle),
100        }
101    }
102
103    fn schedule(&self, delay: Duration) {
104        let Some(ref sender) = self.sender else {
105            return;
106        };
107        let _ = sender.send(Some(Instant::now() + delay));
108    }
109
110    fn cancel(&self) {
111        let Some(ref sender) = self.sender else {
112            return;
113        };
114        let _ = sender.send(None);
115    }
116}
117
118impl Drop for TooltipTimer {
119    fn drop(&mut self) {
120        let _ = self.sender.take();
121        if let Some(join_handle) = self.join_handle.take() {
122            let _ = join_handle.join();
123        }
124    }
125}
126
127pub struct HeadedWindow {
128    /// The [`EventLoopProxy`] for this [`HeadedWindow`].
129    event_loop_proxy: EventLoopProxy<AppEvent>,
130    /// The egui interface that is responsible for showing the user interface elements of
131    /// this headed `Window`.
132    gui: RefCell<Gui>,
133    screen_size: Size2D<u32, DeviceIndependentPixel>,
134    webview_relative_mouse_point: Cell<Point2D<f32, DevicePixel>>,
135    /// The inner size of the window in physical pixels which excludes OS decorations.
136    /// It equals viewport size + (0, toolbar height).
137    inner_size: Cell<PhysicalSize<u32>>,
138    fullscreen: Cell<bool>,
139    fullscreen_from_document: Cell<bool>,
140    device_pixel_ratio_override: Option<f32>,
141    xr_window_poses: RefCell<Vec<Rc<XRWindowPose>>>,
142    modifiers_state: Cell<ModifiersState>,
143    /// The `RenderingContext` of Servo itself. This is used to render Servo results
144    /// temporarily until they can be blitted into the egui scene.
145    rendering_context: Rc<OffscreenRenderingContext>,
146    /// The RenderingContext that renders directly onto the Window. This is used as
147    /// the target of egui rendering and also where Servo rendering results are finally
148    /// blitted.
149    window_rendering_context: Rc<WindowRenderingContext>,
150    /// A helper that simulates touch events when the `--simulate-touch-events` flag
151    /// is enabled.
152    touch_event_simulator: Option<TouchEventSimulator>,
153    /// Keyboard events that have been sent to Servo that have still not been handled yet.
154    /// When these are handled, they will optionally be used to trigger keybindings that
155    /// are overridable by web content.
156    pending_keyboard_events: RefCell<HashMap<InputEventId, KeyboardEvent>>,
157    // Keep this as the last field of the struct to ensure that the rendering context is
158    // dropped first.
159    // (https://github.com/servo/servo/issues/36711)
160    winit_window: winit::window::Window,
161    /// The last title set on this window. We need to store this value here, as `winit::Window::title`
162    /// is not supported very many platforms.
163    last_title: RefCell<String>,
164    /// The current set of open dialogs.
165    dialogs: RefCell<HashMap<WebViewId, Vec<Dialog>>>,
166    /// The [`EmbedderControlId`] of the currently showing [`InputMethod`] interfaces,
167    /// if one is showing.
168    visible_input_method: Cell<Option<EmbedderControlId>>,
169    /// The position of the mouse cursor after the most recent `MouseMove` event.
170    last_mouse_position: Cell<Option<Point2D<f32, DeviceIndependentPixel>>>,
171
172    tooltip_timer: TooltipTimer,
173}
174
175impl HeadedWindow {
176    #[servo::servo_tracing::instrument(level = "debug", name = "HeadedWindow::new", skip_all)]
177    pub(crate) fn new(
178        servoshell_preferences: &ServoShellPreferences,
179        event_loop: &ActiveEventLoop,
180        event_loop_proxy: EventLoopProxy<AppEvent>,
181        initial_url: Url,
182    ) -> Rc<Self> {
183        let no_native_titlebar = servoshell_preferences.no_native_titlebar;
184        let inner_size = servoshell_preferences.initial_window_size;
185        let window_attr = winit::window::Window::default_attributes()
186            .with_title(INITIAL_WINDOW_TITLE.to_string())
187            .with_decorations(!no_native_titlebar)
188            .with_transparent(no_native_titlebar)
189            .with_inner_size(LogicalSize::new(inner_size.width, inner_size.height))
190            .with_min_inner_size(LogicalSize::new(
191                MIN_WINDOW_INNER_SIZE.width,
192                MIN_WINDOW_INNER_SIZE.height,
193            ))
194            // Must be invisible at startup; accesskit_winit setup needs to
195            // happen before the window is shown for the first time.
196            .with_visible(false);
197
198        // Set a name so it can be pinned to taskbars in Linux.
199        #[cfg(target_os = "linux")]
200        let window_attr = window_attr.with_name("org.servo.Servo", "Servo");
201
202        #[allow(deprecated)]
203        let winit_window = event_loop
204            .create_window(window_attr)
205            .expect("Failed to create window.");
206
207        #[cfg(any(target_os = "linux", target_os = "windows"))]
208        {
209            let icon_bytes = include_bytes!("../../../resources/servo_64.png");
210            winit_window.set_window_icon(Some(load_icon(icon_bytes)));
211        }
212
213        let window_handle = winit_window
214            .window_handle()
215            .expect("winit window did not have a window handle");
216        HeadedWindow::force_srgb_color_space(window_handle.as_raw());
217
218        let monitor = winit_window
219            .current_monitor()
220            .or_else(|| winit_window.available_monitors().nth(0))
221            .expect("No monitor detected");
222
223        let (screen_size, screen_scale) = servoshell_preferences.screen_size_override.map_or_else(
224            || (monitor.size(), winit_window.scale_factor()),
225            |size| (PhysicalSize::new(size.width, size.height), 1.0),
226        );
227        let screen_scale: Scale<f64, DeviceIndependentPixel, DevicePixel> =
228            Scale::new(screen_scale);
229        let screen_size = (winit_size_to_euclid_size(screen_size).to_f64() / screen_scale).to_u32();
230        let inner_size = winit_window.inner_size();
231
232        let display_handle = event_loop
233            .display_handle()
234            .expect("could not get display handle from window");
235        let window_handle = winit_window
236            .window_handle()
237            .expect("could not get window handle from window");
238        let window_rendering_context = Rc::new(
239            WindowRenderingContext::new(display_handle, window_handle, inner_size)
240                .expect("Could not create RenderingContext for Window"),
241        );
242
243        // Setup for GL accelerated media handling. This is only active on certain Linux platforms
244        // and Windows.
245        {
246            let details = window_rendering_context.surfman_details();
247            setup_gl_accelerated_media(details.0, details.1);
248        }
249
250        // Make sure the gl context is made current.
251        window_rendering_context
252            .make_current()
253            .expect("Could not make window RenderingContext current");
254
255        let rendering_context = Rc::new(window_rendering_context.offscreen_context(inner_size));
256        let gui = RefCell::new(Gui::new(
257            &winit_window,
258            event_loop,
259            event_loop_proxy.clone(),
260            rendering_context.clone(),
261            initial_url,
262            servoshell_preferences.device_pixel_ratio_override,
263        ));
264
265        let tooltip_timer = TooltipTimer::new(
266            event_loop_proxy.clone(),
267            ServoShellWindowId::from(u64::from(winit_window.id())),
268        );
269
270        debug!("Created window {:?}", winit_window.id());
271        Rc::new(HeadedWindow {
272            event_loop_proxy,
273            gui,
274            winit_window,
275            webview_relative_mouse_point: Cell::new(Point2D::zero()),
276            fullscreen: Cell::new(false),
277            fullscreen_from_document: Cell::new(false),
278            inner_size: Cell::new(inner_size),
279            screen_size,
280            device_pixel_ratio_override: servoshell_preferences.device_pixel_ratio_override,
281            xr_window_poses: RefCell::new(vec![]),
282            modifiers_state: Cell::new(ModifiersState::empty()),
283            window_rendering_context,
284            touch_event_simulator: servoshell_preferences
285                .simulate_touch_events
286                .then(Default::default),
287            pending_keyboard_events: Default::default(),
288            rendering_context,
289            last_title: RefCell::new(String::from(INITIAL_WINDOW_TITLE)),
290            dialogs: Default::default(),
291            visible_input_method: Default::default(),
292            last_mouse_position: Default::default(),
293            tooltip_timer,
294        })
295    }
296
297    pub(crate) fn winit_window(&self) -> &winit::window::Window {
298        &self.winit_window
299    }
300
301    fn handle_keyboard_input(
302        &self,
303        state: Rc<RunningAppState>,
304        window: &Rc<ServoShellWindow>,
305        winit_event: KeyEvent,
306    ) {
307        // First, handle servoshell key bindings that are not overridable by, or visible to, the page.
308        let keyboard_event = keyboard_event_from_winit(&winit_event, self.modifiers_state.get());
309        if self.handle_intercepted_key_bindings(state, window, &keyboard_event) {
310            return;
311        }
312
313        // Then we deliver character and keyboard events to the page in the active webview.
314        let Some(webview) = window.active_webview() else {
315            return;
316        };
317
318        for xr_window_pose in self.xr_window_poses.borrow().iter() {
319            xr_window_pose.handle_xr_rotation(&winit_event, self.modifiers_state.get());
320            xr_window_pose.handle_xr_translation(&keyboard_event);
321        }
322
323        let id = webview.notify_input_event(InputEvent::Keyboard(keyboard_event.clone()));
324        self.pending_keyboard_events
325            .borrow_mut()
326            .insert(id, keyboard_event);
327    }
328
329    /// Helper function to handle a click
330    fn handle_mouse_button_event(
331        &self,
332        webview: &WebView,
333        button: MouseButton,
334        action: ElementState,
335    ) {
336        // `point` can be outside viewport, such as at toolbar with negative y-coordinate.
337        let point = self.webview_relative_mouse_point.get();
338        let webview_rect: Rect<_, _> = webview.size().into();
339        if !webview_rect.contains(point) {
340            return;
341        }
342
343        // A primary or secondary mouse button event moves keyboard focus to the webview.
344        if button == MouseButton::Left || button == MouseButton::Right {
345            self.gui.borrow_mut().set_webview_widget_focused(true);
346        }
347
348        if self
349            .touch_event_simulator
350            .as_ref()
351            .is_some_and(|touch_event_simulator| {
352                touch_event_simulator
353                    .maybe_consume_move_button_event(webview, button, action, point)
354            })
355        {
356            return;
357        }
358
359        let mouse_button = match &button {
360            MouseButton::Left => ServoMouseButton::Primary,
361            MouseButton::Right => ServoMouseButton::Secondary,
362            MouseButton::Middle => ServoMouseButton::Auxiliary,
363            MouseButton::Back => ServoMouseButton::Back,
364            MouseButton::Forward => ServoMouseButton::Forward,
365            MouseButton::Other(value) => ServoMouseButton::Other(*value),
366        };
367
368        let action = match action {
369            ElementState::Pressed => MouseButtonAction::Down,
370            ElementState::Released => MouseButtonAction::Up,
371        };
372
373        webview.notify_input_event(InputEvent::MouseButton(MouseButtonEvent::new(
374            action,
375            mouse_button,
376            point.into(),
377        )));
378    }
379
380    /// Helper function to handle mouse move events.
381    fn handle_mouse_move_event(&self, webview: &WebView, position: PhysicalPosition<f64>) {
382        let mut point = winit_position_to_euclid_point(position).to_f32();
383        point.y -= (self.toolbar_height() * self.hidpi_scale_factor()).0;
384
385        let previous_point = self.webview_relative_mouse_point.get();
386        self.webview_relative_mouse_point.set(point);
387
388        let webview_rect: Rect<_, _> = webview.size().into();
389        if !webview_rect.contains(point) {
390            if webview_rect.contains(previous_point) {
391                webview.notify_input_event(InputEvent::MouseLeftViewport(
392                    MouseLeftViewportEvent::default(),
393                ));
394            }
395            return;
396        }
397
398        if self
399            .touch_event_simulator
400            .as_ref()
401            .is_some_and(|touch_event_simulator| {
402                touch_event_simulator.maybe_consume_mouse_move_event(webview, point)
403            })
404        {
405            return;
406        }
407
408        webview.notify_input_event(InputEvent::MouseMove(MouseMoveEvent::new(point.into())));
409    }
410
411    /// Handle key events before sending them to Servo.
412    fn handle_intercepted_key_bindings(
413        &self,
414        state: Rc<RunningAppState>,
415        window: &Rc<ServoShellWindow>,
416        key_event: &KeyboardEvent,
417    ) -> bool {
418        let Some(active_webview) = window.active_webview() else {
419            return false;
420        };
421
422        let mut handled = true;
423        ShortcutMatcher::from_event(key_event.event.clone())
424            .shortcut(CMD_OR_CONTROL, 'W', || {
425                window.close_webview(active_webview.id());
426            })
427            .shortcut(Modifiers::CONTROL, Key::Named(NamedKey::F9), || {
428                active_webview.capture_webrender();
429            })
430            .shortcut(Modifiers::CONTROL, Key::Named(NamedKey::F10), || {
431                active_webview.toggle_webrender_debugging(WebRenderDebugOption::RenderTargetDebug);
432            })
433            .shortcut(Modifiers::CONTROL, Key::Named(NamedKey::F11), || {
434                active_webview.toggle_webrender_debugging(WebRenderDebugOption::TextureCacheDebug);
435            })
436            .shortcut(Modifiers::CONTROL, Key::Named(NamedKey::F12), || {
437                active_webview.toggle_webrender_debugging(WebRenderDebugOption::Profiler);
438            })
439            .shortcut(CMD_OR_ALT, Key::Named(NamedKey::ArrowRight), || {
440                active_webview.go_forward(1);
441            })
442            .optional_shortcut(
443                cfg!(not(target_os = "windows")),
444                CMD_OR_CONTROL,
445                ']',
446                || {
447                    active_webview.go_forward(1);
448                },
449            )
450            .shortcut(CMD_OR_ALT, Key::Named(NamedKey::ArrowLeft), || {
451                active_webview.go_back(1);
452            })
453            .optional_shortcut(
454                cfg!(not(target_os = "windows")),
455                CMD_OR_CONTROL,
456                '[',
457                || {
458                    active_webview.go_back(1);
459                },
460            )
461            .optional_shortcut(
462                self.get_fullscreen(),
463                Modifiers::empty(),
464                Key::Named(NamedKey::Escape),
465                || active_webview.exit_fullscreen(),
466            )
467            // Select the first 8 tabs via shortcuts
468            .shortcut(CMD_OR_CONTROL, '1', || window.activate_webview_by_index(0))
469            .shortcut(CMD_OR_CONTROL, '2', || window.activate_webview_by_index(1))
470            .shortcut(CMD_OR_CONTROL, '3', || window.activate_webview_by_index(2))
471            .shortcut(CMD_OR_CONTROL, '4', || window.activate_webview_by_index(3))
472            .shortcut(CMD_OR_CONTROL, '5', || window.activate_webview_by_index(4))
473            .shortcut(CMD_OR_CONTROL, '6', || window.activate_webview_by_index(5))
474            .shortcut(CMD_OR_CONTROL, '7', || window.activate_webview_by_index(6))
475            .shortcut(CMD_OR_CONTROL, '8', || window.activate_webview_by_index(7))
476            // Cmd/Ctrl 9 is a bit different in that it focuses the last tab instead of the 9th
477            .shortcut(CMD_OR_CONTROL, '9', || {
478                let len = window.webviews().len();
479                if len > 0 {
480                    window.activate_webview_by_index(len - 1)
481                }
482            })
483            .shortcut(Modifiers::CONTROL, Key::Named(NamedKey::PageDown), || {
484                if let Some(index) = window.get_active_webview_index() {
485                    window.activate_webview_by_index((index + 1) % window.webviews().len())
486                }
487            })
488            .shortcut(Modifiers::CONTROL, Key::Named(NamedKey::PageUp), || {
489                if let Some(index) = window.get_active_webview_index() {
490                    let len = window.webviews().len();
491                    window.activate_webview_by_index((index + len - 1) % len);
492                }
493            })
494            .shortcut(CMD_OR_CONTROL, 'T', || {
495                let url = Url::parse("servo:newtab")
496                    .expect("Should be able to unconditionally parse 'servo:newtab' as URL");
497                window.create_and_activate_toplevel_webview(
498                    state.clone(),
499                    TopLevelWebViewCreationRequest::WithUrl(url),
500                );
501            })
502            .shortcut(CMD_OR_CONTROL, 'Q', || state.schedule_exit())
503            .otherwise(|| handled = false);
504        handled
505    }
506
507    #[cfg_attr(not(target_os = "macos"), expect(unused_variables))]
508    fn force_srgb_color_space(window_handle: RawWindowHandle) {
509        #[cfg(target_os = "macos")]
510        {
511            if let RawWindowHandle::AppKit(handle) = window_handle {
512                assert!(MainThreadMarker::new().is_some());
513                unsafe {
514                    let view = handle.ns_view.cast::<NSView>().as_ref();
515                    view.window()
516                        .expect("Should have a window")
517                        .setColorSpace(Some(&NSColorSpace::sRGBColorSpace()));
518                }
519            }
520        }
521    }
522
523    fn show_ime(&self, control_id: EmbedderControlId, input_method: InputMethodControl) {
524        self.visible_input_method.set(Some(control_id));
525
526        let position = input_method.position().to_f32();
527        let toolbar_height = (self.toolbar_height() * self.hidpi_scale_factor()).0;
528        self.winit_window.set_ime_allowed(true);
529        self.winit_window.set_ime_cursor_area(
530            PhysicalPosition::new(position.min.x, position.min.y + toolbar_height),
531            PhysicalSize::new(position.width(), position.height()),
532        );
533    }
534
535    pub(crate) fn for_each_active_dialog(
536        &self,
537        window: &ServoShellWindow,
538        callback: impl Fn(&mut Dialog) -> bool,
539    ) {
540        let Some(active_webview) = window.active_webview() else {
541            return;
542        };
543        let mut dialogs = self.dialogs.borrow_mut();
544        let Some(dialogs) = dialogs.get_mut(&active_webview.id()) else {
545            return;
546        };
547        if dialogs.is_empty() {
548            return;
549        }
550
551        // If a dialog is open, clear any Servo cursor. TODO: This should restore the
552        // cursor too, when all dialogs close. In general, we need a better cursor
553        // management strategy.
554        self.set_cursor(Cursor::Default);
555        dialogs.retain_mut(callback);
556    }
557
558    fn add_dialog(&self, webview_id: WebViewId, dialog: Dialog) {
559        self.dialogs
560            .borrow_mut()
561            .entry(webview_id)
562            .or_default()
563            .push(dialog)
564    }
565
566    fn remove_dialog(&self, webview_id: WebViewId, embedder_control_id: EmbedderControlId) {
567        let mut dialogs = self.dialogs.borrow_mut();
568        if let Some(dialogs) = dialogs.get_mut(&webview_id) {
569            dialogs.retain(|dialog| dialog.embedder_control_id() != Some(embedder_control_id));
570        }
571        dialogs.retain(|_, dialogs| !dialogs.is_empty());
572    }
573
574    fn has_active_dialog_for_webview(&self, webview_id: WebViewId) -> bool {
575        // First lazily clean up any empty dialog vectors.
576        let mut dialogs = self.dialogs.borrow_mut();
577        dialogs.retain(|_, dialogs| !dialogs.is_empty());
578        dialogs.contains_key(&webview_id)
579    }
580
581    fn toolbar_height(&self) -> Length<f32, DeviceIndependentPixel> {
582        self.gui.borrow().toolbar_height()
583    }
584
585    pub(crate) fn handle_winit_window_event(
586        &self,
587        state: Rc<RunningAppState>,
588        window: Rc<ServoShellWindow>,
589        event: WindowEvent,
590    ) {
591        // Handle resize events first, so that any subsequent redrawing draws onto a buffer of the
592        // correct size.
593        let mut resized = false;
594        if let WindowEvent::Resized(new_inner_size) = event &&
595            self.inner_size.get() != new_inner_size
596        {
597            self.inner_size.set(new_inner_size);
598            self.window_rendering_context.resize(new_inner_size);
599            resized = true;
600        }
601
602        // If requested to redraw or resized, repaint as soon as possible, so that new buffer
603        // contents are available to the window manager.
604        if event == WindowEvent::RedrawRequested || resized {
605            let mut gui = self.gui.borrow_mut();
606            gui.update(&state, &window, self);
607            gui.paint(&self.winit_window);
608        }
609
610        if let WindowEvent::CursorMoved { position, .. } = event {
611            self.last_mouse_position.set(Some(
612                winit_position_to_euclid_point(position).to_f32() / self.hidpi_scale_factor(),
613            ));
614        }
615        let should_forward_mouse_event_to_egui = || {
616            // If a dialog is showing, it always captures all mouse events.
617            if window
618                .active_webview()
619                .is_some_and(|webview| self.has_active_dialog_for_webview(webview.id()))
620            {
621                return true;
622            }
623            // Otherwise, if the cursor is over the egui interface, forward the event.
624            self.last_mouse_position
625                .get()
626                .is_none_or(|point| self.gui.borrow().is_in_egui_toolbar_rect(point))
627        };
628
629        // Handle the event
630        let mut consumed = false;
631        match event {
632            WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
633                // Intercept any ScaleFactorChanged events away from EguiGlow::on_window_event, so
634                // we can use our own logic for calculating the scale factor and set egui’s
635                // scale factor to that value manually.
636                let desired_scale_factor = self.hidpi_scale_factor().get();
637                let effective_egui_zoom_factor = desired_scale_factor / scale_factor as f32;
638
639                info!(
640                    "window scale factor changed to {}, setting egui zoom factor to {}",
641                    scale_factor, effective_egui_zoom_factor
642                );
643
644                self.gui
645                    .borrow()
646                    .set_zoom_factor(effective_egui_zoom_factor);
647
648                window.hidpi_scale_factor_changed();
649
650                // Request a winit redraw event, so we can recomposite, update and paint
651                // the GUI, and present the new frame.
652                self.winit_window.request_redraw();
653            },
654            WindowEvent::MouseInput {
655                state: ElementState::Pressed,
656                button: MouseButton::Forward,
657                ..
658            } => {
659                window.queue_user_interface_command(UserInterfaceCommand::Forward);
660                consumed = true;
661            },
662            WindowEvent::MouseInput {
663                state: ElementState::Pressed,
664                button: MouseButton::Back,
665                ..
666            } => {
667                window.queue_user_interface_command(UserInterfaceCommand::Back);
668                consumed = true;
669            },
670            WindowEvent::KeyboardInput { .. } if self.gui.borrow().webview_widget_focused() => {
671                // Keyboard events should go to the WebView unless some other GUI
672                // component has keyboard focus.
673                //
674                // TODO: Release focus from the webview if keyboard focus moves past the beginning
675                // or end of the web contents.
676            },
677            ref event => {
678                if let WindowEvent::Focused(focused) = event {
679                    state.set_window_has_focus(window.clone(), *focused);
680
681                    if !focused {
682                        // If the window lost focus, update the gui so that if focus is in web
683                        // contents the webview widget can surrender focus to avoid a crash in
684                        // accesskit when on_window_event() is called below.
685                        //
686                        // If the window gained focus, we still need to wait a tick before
687                        // requesting focus on the webview widget, so skip it here.
688                        self.gui.borrow_mut().update(&state, &window, self);
689                    }
690                }
691
692                let response = self
693                    .gui
694                    .borrow_mut()
695                    .on_window_event(&self.winit_window, event);
696
697                if response.repaint && *event != WindowEvent::RedrawRequested {
698                    self.winit_window.request_redraw();
699                }
700
701                // All CursorMoved events, even when forwarded to the WebView, are also
702                // forwarded to Gui (above). This is because egui needs to know when
703                // the mouse is moving in other parts of the view in order to properly
704                // hide tooltips.
705                if let WindowEvent::CursorMoved { .. } = event &&
706                    !should_forward_mouse_event_to_egui()
707                {
708                    consumed = false;
709                } else {
710                    consumed = response.consumed;
711                }
712            },
713        }
714
715        if !consumed && let Some(webview) = window.active_webview() {
716            match event {
717                WindowEvent::KeyboardInput { event, .. } => {
718                    self.handle_keyboard_input(state, &window, event)
719                },
720                WindowEvent::ModifiersChanged(modifiers) => {
721                    self.modifiers_state.set(modifiers.state())
722                },
723                WindowEvent::MouseInput { state, button, .. } => {
724                    self.handle_mouse_button_event(&webview, button, state);
725                },
726                WindowEvent::CursorMoved { position, .. } => {
727                    self.handle_mouse_move_event(&webview, position);
728                    if self.gui.borrow_mut().restart_pending_tooltip_delay() {
729                        self.tooltip_timer.schedule(TOOLTIP_DELAY);
730                    }
731                },
732                WindowEvent::CursorLeft { .. } => {
733                    let webview_rect: Rect<_, _> = webview.size().into();
734                    if webview_rect.contains(self.webview_relative_mouse_point.get()) {
735                        webview.notify_input_event(InputEvent::MouseLeftViewport(
736                            MouseLeftViewportEvent::default(),
737                        ));
738                    }
739                },
740                WindowEvent::MouseWheel { delta, .. } => {
741                    let (delta_x, delta_y, mode) = match delta {
742                        MouseScrollDelta::LineDelta(delta_x, delta_y) => (
743                            (delta_x * LINE_WIDTH) as f64,
744                            (delta_y * LINE_HEIGHT) as f64,
745                            WheelMode::DeltaPixel,
746                        ),
747                        MouseScrollDelta::PixelDelta(delta) => {
748                            (delta.x, delta.y, WheelMode::DeltaPixel)
749                        },
750                    };
751
752                    // Create wheel event before snapping to the major axis of movement
753                    let delta = WheelDelta {
754                        x: delta_x,
755                        y: delta_y,
756                        z: 0.0,
757                        mode,
758                    };
759                    let point = self.webview_relative_mouse_point.get();
760                    webview.notify_input_event(InputEvent::Wheel(WheelEvent::new(
761                        delta,
762                        point.into(),
763                        keyboard_modifiers_from_winit_modifiers(self.modifiers_state.get()),
764                    )));
765                },
766                WindowEvent::Touch(touch) => {
767                    webview.notify_input_event(InputEvent::Touch(TouchEvent::new(
768                        winit_phase_to_touch_event_type(touch.phase),
769                        TouchId(touch.id as i32),
770                        DevicePoint::new(touch.location.x as f32, touch.location.y as f32).into(),
771                        TouchPointerType::Touch,
772                    )));
773                },
774                WindowEvent::PinchGesture { delta, .. } => {
775                    webview.adjust_pinch_zoom(
776                        delta as f32 + 1.0,
777                        self.webview_relative_mouse_point.get(),
778                    );
779                },
780                WindowEvent::CloseRequested => {
781                    window.schedule_close();
782                },
783                WindowEvent::ThemeChanged(theme) => {
784                    webview.notify_theme_change(match theme {
785                        winit::window::Theme::Light => Theme::Light,
786                        winit::window::Theme::Dark => Theme::Dark,
787                    });
788                },
789                WindowEvent::Ime(ime) => match ime {
790                    Ime::Enabled => {
791                        webview.notify_input_event(InputEvent::Ime(ImeEvent::Composition(
792                            servo::CompositionEvent {
793                                state: servo::CompositionState::Start,
794                                data: String::new(),
795                            },
796                        )));
797                    },
798                    Ime::Preedit(text, _) => {
799                        webview.notify_input_event(InputEvent::Ime(ImeEvent::Composition(
800                            servo::CompositionEvent {
801                                state: servo::CompositionState::Update,
802                                data: text,
803                            },
804                        )));
805                    },
806                    Ime::Commit(text) => {
807                        webview.notify_input_event(InputEvent::Ime(ImeEvent::Composition(
808                            servo::CompositionEvent {
809                                state: servo::CompositionState::Update,
810                                data: text.clone(),
811                            },
812                        )));
813                        webview.notify_input_event(InputEvent::Ime(ImeEvent::Composition(
814                            servo::CompositionEvent {
815                                state: servo::CompositionState::End,
816                                data: text,
817                            },
818                        )));
819                    },
820                    Ime::Disabled => {
821                        // There are two reasons we receive this message from winit:
822                        //
823                        // 1. The user dismissed the IME. In that case we want to inform Servo
824                        //    so it can unfocus the current editable element.
825                        // 2. Servo changed focus and requested that we dismiss the IME, which
826                        //    in turn triggers this message. We know this is the case when we don't
827                        //    expect any IME to be open and shouldn't send any more messages to
828                        //    Servo as it might cause unexpected blurring of the newly focused
829                        //    element.
830                        if self.visible_input_method.take().is_some() {
831                            webview.notify_input_event(InputEvent::Ime(ImeEvent::Dismissed));
832                        }
833                    },
834                },
835                WindowEvent::DroppedFile(dropped_file) => {
836                    if let Ok(url) = Url::from_file_path(&dropped_file) {
837                        webview.load(url);
838                    } else {
839                        log::error!(
840                            "Failed to create URL for dropped file ({})",
841                            dropped_file.display()
842                        );
843                    }
844                },
845                _ => {},
846            }
847        }
848    }
849
850    pub(crate) fn handle_winit_app_event(&self, state: Rc<RunningAppState>, app_event: AppEvent) {
851        if let AppEvent::Accessibility(ref event) = app_event {
852            match &event.window_event {
853                egui_winit::accesskit_winit::WindowEvent::InitialTreeRequested => {
854                    state.set_accessibility_active(true);
855                },
856                egui_winit::accesskit_winit::WindowEvent::ActionRequested(req) => {
857                    if req.target_tree != accesskit::TreeId::ROOT {
858                        state.servo.forward_accessibility_action(req.clone());
859                    }
860                },
861                egui_winit::accesskit_winit::WindowEvent::AccessibilityDeactivated => {
862                    state.set_accessibility_active(false);
863                },
864            }
865
866            if self
867                .gui
868                .borrow_mut()
869                .handle_accesskit_event(&event.window_event)
870            {
871                self.winit_window.request_redraw();
872            }
873        }
874    }
875
876    pub(crate) fn is_fullscreen_from_document(&self) -> bool {
877        self.fullscreen_from_document.get()
878    }
879}
880
881impl PlatformWindow for HeadedWindow {
882    fn platform_manages_focus(&self) -> bool {
883        true
884    }
885
886    fn as_headed_window(&self) -> Option<&Self> {
887        Some(self)
888    }
889
890    fn screen_geometry(&self) -> ScreenGeometry {
891        let hidpi_factor = self.hidpi_scale_factor();
892        let toolbar_size = Size2D::new(0.0, (self.toolbar_height() * self.hidpi_scale_factor()).0);
893        let screen_size = self.screen_size.to_f32() * hidpi_factor;
894
895        // FIXME: In reality, this should subtract screen space used by the system interface
896        // elements, but it is difficult to get this value with `winit` currently. See:
897        // See https://github.com/rust-windowing/winit/issues/2494
898        let available_screen_size = screen_size - toolbar_size;
899
900        let window_rect = DeviceIntRect::from_origin_and_size(
901            winit_position_to_euclid_point(self.winit_window.outer_position().unwrap_or_default()),
902            winit_size_to_euclid_size(self.winit_window.outer_size()).to_i32(),
903        );
904
905        ScreenGeometry {
906            size: screen_size.to_i32(),
907            available_size: available_screen_size.to_i32(),
908            window_rect,
909        }
910    }
911
912    fn device_hidpi_scale_factor(&self) -> Scale<f32, DeviceIndependentPixel, DevicePixel> {
913        Scale::new(self.winit_window.scale_factor() as f32)
914    }
915
916    fn hidpi_scale_factor(&self) -> Scale<f32, DeviceIndependentPixel, DevicePixel> {
917        self.device_pixel_ratio_override
918            .map(Scale::new)
919            .unwrap_or_else(|| self.device_hidpi_scale_factor())
920    }
921
922    fn update_user_interface_state(&self, _: &RunningAppState, window: &ServoShellWindow) -> bool {
923        let title = window
924            .active_webview()
925            .and_then(|webview| {
926                webview
927                    .page_title()
928                    .filter(|title| !title.is_empty())
929                    .or_else(|| webview.url().map(|url| url.to_string()))
930            })
931            .unwrap_or_else(|| INITIAL_WINDOW_TITLE.to_string());
932        if title != *self.last_title.borrow() {
933            self.winit_window.set_title(&title);
934            *self.last_title.borrow_mut() = title;
935        }
936
937        self.gui.borrow_mut().update_webview_data(window)
938    }
939
940    fn request_repaint(&self, _: &ServoShellWindow) {
941        self.winit_window.request_redraw();
942    }
943
944    fn request_resize(&self, _: &WebView, new_outer_size: DeviceIntSize) -> Option<DeviceIntSize> {
945        // Allocate space for the window deocrations, but do not let the inner size get
946        // smaller than `MIN_WINDOW_INNER_SIZE` or larger than twice the screen size.
947        let inner_size = self.winit_window.inner_size();
948        let outer_size = self.winit_window.outer_size();
949        let decoration_size: DeviceIntSize = Size2D::new(
950            outer_size.width - inner_size.width,
951            outer_size.height - inner_size.height,
952        )
953        .cast();
954
955        let screen_size = (self.screen_size.to_f32() * self.hidpi_scale_factor()).to_i32();
956        let new_outer_size =
957            new_outer_size.clamp(MIN_WINDOW_INNER_SIZE + decoration_size, screen_size * 2);
958
959        if outer_size.width == new_outer_size.width as u32 &&
960            outer_size.height == new_outer_size.height as u32
961        {
962            return Some(new_outer_size);
963        }
964
965        let new_inner_size = new_outer_size - decoration_size;
966        self.winit_window
967            .request_inner_size(PhysicalSize::new(
968                new_inner_size.width,
969                new_inner_size.height,
970            ))
971            .map(|resulting_size| {
972                // `Some` means that winit applied the resize synchronously, in which case it may
973                // not emit a subsequent `WindowEvent::Resized`.
974                if self.inner_size.get() != resulting_size {
975                    self.inner_size.set(resulting_size);
976                    self.window_rendering_context.resize(resulting_size);
977                }
978
979                DeviceIntSize::new(
980                    resulting_size.width as i32 + decoration_size.width,
981                    resulting_size.height as i32 + decoration_size.height,
982                )
983            })
984    }
985
986    fn window_rect(&self) -> DeviceIndependentIntRect {
987        let outer_size = self.winit_window.outer_size();
988        let scale = self.hidpi_scale_factor();
989
990        let outer_size = winit_size_to_euclid_size(outer_size).to_i32();
991
992        let origin = self
993            .winit_window
994            .outer_position()
995            .map(winit_position_to_euclid_point)
996            .unwrap_or_default();
997        convert_rect_to_css_pixel(
998            DeviceIntRect::from_origin_and_size(origin, outer_size),
999            scale,
1000        )
1001    }
1002
1003    fn set_position(&self, point: DeviceIntPoint) {
1004        self.winit_window
1005            .set_outer_position::<PhysicalPosition<i32>>(PhysicalPosition::new(point.x, point.y))
1006    }
1007
1008    fn set_fullscreen(&self, state: bool) {
1009        let monitor = self
1010            .winit_window()
1011            .current_monitor()
1012            .or_else(|| self.winit_window.available_monitors().nth(0))
1013            .expect("No monitor detected");
1014        if self.fullscreen.get() != state {
1015            self.winit_window.set_fullscreen(if state {
1016                Some(winit::window::Fullscreen::Borderless(Some(monitor)))
1017            } else {
1018                None
1019            });
1020        }
1021        self.fullscreen.set(state);
1022        self.fullscreen_from_document.set(state);
1023    }
1024
1025    fn get_fullscreen(&self) -> bool {
1026        self.fullscreen.get()
1027    }
1028
1029    fn set_cursor(&self, cursor: Cursor) {
1030        use winit::window::CursorIcon;
1031
1032        let winit_cursor = match cursor {
1033            Cursor::Default => CursorIcon::Default,
1034            Cursor::Pointer => CursorIcon::Pointer,
1035            Cursor::ContextMenu => CursorIcon::ContextMenu,
1036            Cursor::Help => CursorIcon::Help,
1037            Cursor::Progress => CursorIcon::Progress,
1038            Cursor::Wait => CursorIcon::Wait,
1039            Cursor::Cell => CursorIcon::Cell,
1040            Cursor::Crosshair => CursorIcon::Crosshair,
1041            Cursor::Text => CursorIcon::Text,
1042            Cursor::VerticalText => CursorIcon::VerticalText,
1043            Cursor::Alias => CursorIcon::Alias,
1044            Cursor::Copy => CursorIcon::Copy,
1045            Cursor::Move => CursorIcon::Move,
1046            Cursor::NoDrop => CursorIcon::NoDrop,
1047            Cursor::NotAllowed => CursorIcon::NotAllowed,
1048            Cursor::Grab => CursorIcon::Grab,
1049            Cursor::Grabbing => CursorIcon::Grabbing,
1050            Cursor::EResize => CursorIcon::EResize,
1051            Cursor::NResize => CursorIcon::NResize,
1052            Cursor::NeResize => CursorIcon::NeResize,
1053            Cursor::NwResize => CursorIcon::NwResize,
1054            Cursor::SResize => CursorIcon::SResize,
1055            Cursor::SeResize => CursorIcon::SeResize,
1056            Cursor::SwResize => CursorIcon::SwResize,
1057            Cursor::WResize => CursorIcon::WResize,
1058            Cursor::EwResize => CursorIcon::EwResize,
1059            Cursor::NsResize => CursorIcon::NsResize,
1060            Cursor::NeswResize => CursorIcon::NeswResize,
1061            Cursor::NwseResize => CursorIcon::NwseResize,
1062            Cursor::ColResize => CursorIcon::ColResize,
1063            Cursor::RowResize => CursorIcon::RowResize,
1064            Cursor::AllScroll => CursorIcon::AllScroll,
1065            Cursor::ZoomIn => CursorIcon::ZoomIn,
1066            Cursor::ZoomOut => CursorIcon::ZoomOut,
1067            Cursor::None => {
1068                self.winit_window.set_cursor_visible(false);
1069                return;
1070            },
1071        };
1072        self.winit_window.set_cursor(winit_cursor);
1073        self.winit_window.set_cursor_visible(true);
1074    }
1075
1076    fn id(&self) -> ServoShellWindowId {
1077        let id: u64 = self.winit_window.id().into();
1078        id.into()
1079    }
1080
1081    #[cfg(feature = "webxr")]
1082    fn new_glwindow(&self, event_loop: &ActiveEventLoop) -> Rc<dyn servo::webxr::GlWindow> {
1083        let size = self.winit_window.outer_size();
1084
1085        let window_attr = winit::window::Window::default_attributes()
1086            .with_title("Servo XR".to_string())
1087            .with_inner_size(size)
1088            .with_visible(false);
1089
1090        let winit_window = event_loop
1091            .create_window(window_attr)
1092            .expect("Failed to create window.");
1093
1094        let pose = Rc::new(XRWindowPose {
1095            xr_rotation: Cell::new(Rotation3D::identity()),
1096            xr_translation: Cell::new(Vector3D::zero()),
1097        });
1098        self.xr_window_poses.borrow_mut().push(pose.clone());
1099        Rc::new(XRWindow { winit_window, pose })
1100    }
1101
1102    fn rendering_context(&self) -> Rc<dyn RenderingContext> {
1103        self.rendering_context.clone()
1104    }
1105
1106    fn theme(&self) -> servo::Theme {
1107        match self.winit_window.theme() {
1108            Some(winit::window::Theme::Dark) => servo::Theme::Dark,
1109            Some(winit::window::Theme::Light) | None => servo::Theme::Light,
1110        }
1111    }
1112
1113    fn maximize(&self, _webview: &WebView) {
1114        self.winit_window.set_maximized(true);
1115    }
1116
1117    /// Handle servoshell key bindings that may have been prevented by the page in the active webview.
1118    fn notify_input_event_handled(
1119        &self,
1120        webview: &WebView,
1121        id: InputEventId,
1122        result: InputEventResult,
1123    ) {
1124        let Some(keyboard_event) = self.pending_keyboard_events.borrow_mut().remove(&id) else {
1125            return;
1126        };
1127        if result.intersects(InputEventResult::DefaultPrevented | InputEventResult::Consumed) {
1128            return;
1129        }
1130
1131        ShortcutMatcher::from_event(keyboard_event.event)
1132            .shortcut(CMD_OR_CONTROL, '=', || {
1133                webview.set_page_zoom(webview.page_zoom() + 0.1);
1134            })
1135            .shortcut(CMD_OR_CONTROL, '+', || {
1136                webview.set_page_zoom(webview.page_zoom() + 0.1);
1137            })
1138            .shortcut(CMD_OR_CONTROL, '-', || {
1139                webview.set_page_zoom(webview.page_zoom() - 0.1);
1140            })
1141            .shortcut(CMD_OR_CONTROL, '0', || {
1142                webview.set_page_zoom(1.0);
1143            })
1144            .shortcut(CMD_OR_CONTROL, 'R', || webview.reload())
1145            .shortcut(Modifiers::empty(), Key::Named(NamedKey::F5), || {
1146                webview.reload()
1147            });
1148    }
1149
1150    fn has_platform_focus(&self) -> bool {
1151        self.winit_window.has_focus()
1152    }
1153
1154    fn show_embedder_control(&self, webview_id: WebViewId, embedder_control: EmbedderControl) {
1155        let control_id = embedder_control.id();
1156        match embedder_control {
1157            EmbedderControl::SelectElement(prompt) => {
1158                self.add_dialog(webview_id, Dialog::new_select_element_dialog(prompt));
1159            },
1160            EmbedderControl::ColorPicker(color_picker) => {
1161                self.add_dialog(webview_id, Dialog::new_color_picker_dialog(color_picker));
1162            },
1163            EmbedderControl::InputMethod(input_method_control) => {
1164                self.show_ime(control_id, input_method_control);
1165            },
1166            EmbedderControl::FilePicker(file_picker) => {
1167                let waker = RepaintEventLoopWaker::new(self.event_loop_proxy.clone(), self.id());
1168                self.add_dialog(
1169                    webview_id,
1170                    Dialog::new_file_dialog(file_picker, &self.winit_window, waker),
1171                );
1172            },
1173            EmbedderControl::SimpleDialog(simple_dialog) => {
1174                self.add_dialog(webview_id, Dialog::new_simple_dialog(simple_dialog));
1175            },
1176            EmbedderControl::ContextMenu(prompt) => {
1177                self.add_dialog(webview_id, Dialog::new_context_menu(prompt));
1178            },
1179            EmbedderControl::Tooltip(tooltip_control) => {
1180                self.gui
1181                    .borrow_mut()
1182                    .show_tooltip(webview_id, &tooltip_control);
1183                self.tooltip_timer.schedule(TOOLTIP_DELAY);
1184            },
1185        }
1186    }
1187
1188    fn hide_embedder_control(&self, webview_id: WebViewId, embedder_control_id: EmbedderControlId) {
1189        if self.gui.borrow_mut().hide_tooltip(embedder_control_id) {
1190            self.tooltip_timer.cancel();
1191        }
1192        if self.visible_input_method.get() == Some(embedder_control_id) {
1193            self.visible_input_method.set(None);
1194            self.winit_window.set_ime_allowed(false);
1195            return;
1196        }
1197        self.remove_dialog(webview_id, embedder_control_id);
1198    }
1199
1200    fn show_bluetooth_device_dialog(
1201        &self,
1202        webview_id: WebViewId,
1203        request: BluetoothDeviceSelectionRequest,
1204    ) {
1205        self.add_dialog(webview_id, Dialog::new_device_selection_dialog(request));
1206    }
1207
1208    fn show_permission_dialog(&self, webview_id: WebViewId, permission_request: PermissionRequest) {
1209        self.add_dialog(
1210            webview_id,
1211            Dialog::new_permission_request_dialog(permission_request),
1212        );
1213    }
1214
1215    fn show_http_authentication_dialog(
1216        &self,
1217        webview_id: WebViewId,
1218        authentication_request: AuthenticationRequest,
1219    ) {
1220        self.add_dialog(
1221            webview_id,
1222            Dialog::new_authentication_dialog(authentication_request),
1223        );
1224    }
1225
1226    fn dismiss_embedder_controls_for_webview(&self, webview_id: WebViewId) {
1227        self.dialogs.borrow_mut().remove(&webview_id);
1228        if self
1229            .gui
1230            .borrow_mut()
1231            .dismiss_tooltips_for_webview(webview_id)
1232        {
1233            self.tooltip_timer.cancel();
1234        }
1235    }
1236
1237    fn show_console_message(&self, level: servo::ConsoleLogLevel, message: &str) {
1238        println!("{message}");
1239        log::log!(level.into(), "{message}");
1240    }
1241
1242    fn notify_accessibility_tree_update(
1243        &self,
1244        _webview: WebView,
1245        tree_update: accesskit::TreeUpdate,
1246    ) {
1247        self.gui
1248            .borrow_mut()
1249            .notify_accessibility_tree_update(tree_update);
1250    }
1251}
1252
1253fn winit_phase_to_touch_event_type(phase: TouchPhase) -> TouchEventType {
1254    match phase {
1255        TouchPhase::Started => TouchEventType::Down,
1256        TouchPhase::Moved => TouchEventType::Move,
1257        TouchPhase::Ended => TouchEventType::Up,
1258        TouchPhase::Cancelled => TouchEventType::Cancel,
1259    }
1260}
1261
1262#[cfg(any(target_os = "linux", target_os = "windows"))]
1263fn load_icon(icon_bytes: &[u8]) -> Icon {
1264    let (icon_rgba, icon_width, icon_height) = {
1265        use image::{GenericImageView, Pixel};
1266        let image = image::load_from_memory(icon_bytes).expect("Failed to load icon");
1267        let (width, height) = image.dimensions();
1268        let mut rgba = Vec::with_capacity((width * height) as usize * 4);
1269        for (_, _, pixel) in image.pixels() {
1270            rgba.extend_from_slice(&pixel.to_rgba().0);
1271        }
1272        (rgba, width, height)
1273    };
1274    Icon::from_rgba(icon_rgba, icon_width, icon_height).expect("Failed to load icon")
1275}
1276
1277#[cfg(feature = "webxr")]
1278struct XRWindow {
1279    winit_window: winit::window::Window,
1280    pose: Rc<XRWindowPose>,
1281}
1282
1283struct XRWindowPose {
1284    xr_rotation: Cell<Rotation3D<f32, UnknownUnit, UnknownUnit>>,
1285    xr_translation: Cell<Vector3D<f32, UnknownUnit>>,
1286}
1287
1288#[cfg(feature = "webxr")]
1289impl servo::webxr::GlWindow for XRWindow {
1290    fn get_render_target(
1291        &self,
1292        device: &mut surfman::Device,
1293        _context: &mut surfman::Context,
1294    ) -> servo::webxr::GlWindowRenderTarget {
1295        self.winit_window.set_visible(true);
1296        let window_handle = self
1297            .winit_window
1298            .window_handle()
1299            .expect("could not get window handle from window");
1300        let size = self.winit_window.inner_size();
1301        let size = Size2D::new(size.width as i32, size.height as i32);
1302        let native_widget = device
1303            .connection()
1304            .create_native_widget_from_window_handle(window_handle, size)
1305            .expect("Failed to create native widget");
1306        servo::webxr::GlWindowRenderTarget::NativeWidget(native_widget)
1307    }
1308
1309    fn get_rotation(&self) -> Rotation3D<f32, UnknownUnit, UnknownUnit> {
1310        self.pose.xr_rotation.get()
1311    }
1312
1313    fn get_translation(&self) -> Vector3D<f32, UnknownUnit> {
1314        self.pose.xr_translation.get()
1315    }
1316
1317    fn get_mode(&self) -> servo::webxr::GlWindowMode {
1318        use servo::pref;
1319        if pref!(dom_webxr_glwindow_red_cyan) {
1320            servo::webxr::GlWindowMode::StereoRedCyan
1321        } else if pref!(dom_webxr_glwindow_left_right) {
1322            servo::webxr::GlWindowMode::StereoLeftRight
1323        } else if pref!(dom_webxr_glwindow_spherical) {
1324            servo::webxr::GlWindowMode::Spherical
1325        } else if pref!(dom_webxr_glwindow_cubemap) {
1326            servo::webxr::GlWindowMode::Cubemap
1327        } else {
1328            servo::webxr::GlWindowMode::Blit
1329        }
1330    }
1331
1332    fn display_handle(&self) -> raw_window_handle::DisplayHandle<'_> {
1333        self.winit_window
1334            .display_handle()
1335            .expect("Every window should have a display handle")
1336    }
1337}
1338
1339impl XRWindowPose {
1340    fn handle_xr_translation(&self, input: &KeyboardEvent) {
1341        if input.event.state != KeyState::Down {
1342            return;
1343        }
1344        const NORMAL_TRANSLATE: f32 = 0.1;
1345        const QUICK_TRANSLATE: f32 = 1.0;
1346        let mut x = 0.0;
1347        let mut z = 0.0;
1348        match input.event.key {
1349            Key::Character(ref k) => match &**k {
1350                "w" => z = -NORMAL_TRANSLATE,
1351                "W" => z = -QUICK_TRANSLATE,
1352                "s" => z = NORMAL_TRANSLATE,
1353                "S" => z = QUICK_TRANSLATE,
1354                "a" => x = -NORMAL_TRANSLATE,
1355                "A" => x = -QUICK_TRANSLATE,
1356                "d" => x = NORMAL_TRANSLATE,
1357                "D" => x = QUICK_TRANSLATE,
1358                _ => return,
1359            },
1360            _ => return,
1361        };
1362        let (old_x, old_y, old_z) = self.xr_translation.get().to_tuple();
1363        let vec = Vector3D::new(x + old_x, old_y, z + old_z);
1364        self.xr_translation.set(vec);
1365    }
1366
1367    fn handle_xr_rotation(&self, input: &KeyEvent, modifiers: ModifiersState) {
1368        if input.state != ElementState::Pressed {
1369            return;
1370        }
1371        let mut x = 0.0;
1372        let mut y = 0.0;
1373        match input.logical_key {
1374            LogicalKey::Named(WinitNamedKey::ArrowUp) => x = 1.0,
1375            LogicalKey::Named(WinitNamedKey::ArrowDown) => x = -1.0,
1376            LogicalKey::Named(WinitNamedKey::ArrowLeft) => y = 1.0,
1377            LogicalKey::Named(WinitNamedKey::ArrowRight) => y = -1.0,
1378            _ => return,
1379        };
1380        if modifiers.shift_key() {
1381            x *= 10.0;
1382            y *= 10.0;
1383        }
1384        let x: Rotation3D<_, UnknownUnit, UnknownUnit> = Rotation3D::around_x(Angle::degrees(x));
1385        let y: Rotation3D<_, UnknownUnit, UnknownUnit> = Rotation3D::around_y(Angle::degrees(y));
1386        let rotation = self.xr_rotation.get().then(&x).then(&y);
1387        self.xr_rotation.set(rotation);
1388    }
1389}
1390
1391#[derive(Default)]
1392pub struct TouchEventSimulator {
1393    pub left_mouse_button_down: Cell<bool>,
1394}
1395
1396impl TouchEventSimulator {
1397    fn maybe_consume_move_button_event(
1398        &self,
1399        webview: &WebView,
1400        button: MouseButton,
1401        action: ElementState,
1402        point: DevicePoint,
1403    ) -> bool {
1404        if button != MouseButton::Left {
1405            return false;
1406        }
1407
1408        if action == ElementState::Pressed && !self.left_mouse_button_down.get() {
1409            webview.notify_input_event(InputEvent::Touch(TouchEvent::new(
1410                TouchEventType::Down,
1411                TouchId(0),
1412                point.into(),
1413                TouchPointerType::Touch,
1414            )));
1415            self.left_mouse_button_down.set(true);
1416        } else if action == ElementState::Released {
1417            webview.notify_input_event(InputEvent::Touch(TouchEvent::new(
1418                TouchEventType::Up,
1419                TouchId(0),
1420                point.into(),
1421                TouchPointerType::Touch,
1422            )));
1423            self.left_mouse_button_down.set(false);
1424        }
1425
1426        true
1427    }
1428
1429    fn maybe_consume_mouse_move_event(
1430        &self,
1431        webview: &WebView,
1432        point: Point2D<f32, DevicePixel>,
1433    ) -> bool {
1434        if !self.left_mouse_button_down.get() {
1435            return false;
1436        }
1437
1438        webview.notify_input_event(InputEvent::Touch(TouchEvent::new(
1439            TouchEventType::Move,
1440            TouchId(0),
1441            point.into(),
1442            TouchPointerType::Touch,
1443        )));
1444        true
1445    }
1446}