Skip to main content

servoshell/desktop/
event_loop.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//! An event loop implementation that works in headless mode.
6
7use std::sync::{Arc, Condvar, Mutex};
8use std::task::Wake;
9use std::time;
10
11use gilrs::Event;
12use log::warn;
13use servo::EventLoopWaker;
14#[cfg(feature = "gamepad")]
15use servo::GamepadIndex;
16use winit::event_loop::{EventLoop, EventLoop as WinitEventLoop, EventLoopProxy};
17
18use super::app::App;
19use crate::window::ServoShellWindowId;
20
21#[derive(Debug)]
22pub enum AppEvent {
23    /// Another process or thread has kicked the OS event loop with EventLoopWaker.
24    Waker,
25    Accessibility(egui_winit::accesskit_winit::Event),
26    RequestRepaint(ServoShellWindowId),
27    #[cfg(feature = "gamepad")]
28    Gamepad(Event, String, GamepadIndex),
29}
30
31impl From<egui_winit::accesskit_winit::Event> for AppEvent {
32    fn from(event: egui_winit::accesskit_winit::Event) -> AppEvent {
33        AppEvent::Accessibility(event)
34    }
35}
36
37/// A headed or headless event loop. Headless event loops are necessary for environments without a
38/// display server. Ideally, we could use the headed winit event loop in both modes, but on Linux,
39/// the event loop requires a display server, which prevents running servoshell in a console.
40#[allow(clippy::large_enum_variant)]
41pub(crate) enum ServoShellEventLoop {
42    /// A real Winit windowing event loop.
43    Winit(EventLoop<AppEvent>),
44    /// A fake event loop which contains a signalling flag used to ensure
45    /// that pending events get processed in a timely fashion, and a condition
46    /// variable to allow waiting on that flag changing state.
47    Headless(Arc<HeadlessEventLoop>),
48}
49
50impl ServoShellEventLoop {
51    pub(crate) fn headless() -> ServoShellEventLoop {
52        ServoShellEventLoop::Headless(Default::default())
53    }
54
55    pub(crate) fn headed() -> ServoShellEventLoop {
56        ServoShellEventLoop::Winit(
57            WinitEventLoop::with_user_event()
58                .build()
59                .expect("Could not start winit event loop"),
60        )
61    }
62}
63
64impl ServoShellEventLoop {
65    pub(crate) fn event_loop_proxy(&self) -> Option<EventLoopProxy<AppEvent>> {
66        match self {
67            ServoShellEventLoop::Winit(event_loop) => Some(event_loop.create_proxy()),
68            ServoShellEventLoop::Headless(..) => None,
69        }
70    }
71
72    pub fn create_event_loop_waker(&self) -> Box<dyn EventLoopWaker> {
73        match self {
74            ServoShellEventLoop::Winit(event_loop) => {
75                Box::new(HeadedEventLoopWaker::new(event_loop))
76            },
77            ServoShellEventLoop::Headless(data) => Box::new(HeadlessEventLoopWaker(data.clone())),
78        }
79    }
80
81    pub fn run_app(self, app: &mut App) {
82        match self {
83            ServoShellEventLoop::Winit(event_loop) => {
84                event_loop
85                    .run_app(app)
86                    .expect("Failed while running events loop");
87            },
88            ServoShellEventLoop::Headless(event_loop) => event_loop.run_app(app),
89        }
90    }
91}
92
93#[derive(Clone)]
94struct HeadedEventLoopWaker {
95    proxy: Arc<Mutex<EventLoopProxy<AppEvent>>>,
96}
97
98impl HeadedEventLoopWaker {
99    fn new(event_loop: &EventLoop<AppEvent>) -> HeadedEventLoopWaker {
100        let proxy = Arc::new(Mutex::new(event_loop.create_proxy()));
101        HeadedEventLoopWaker { proxy }
102    }
103}
104
105impl EventLoopWaker for HeadedEventLoopWaker {
106    fn wake(&self) {
107        // Kick the OS event loop awake.
108        if let Err(err) = self.proxy.lock().unwrap().send_event(AppEvent::Waker) {
109            warn!("Failed to wake up event loop ({}).", err);
110        }
111    }
112
113    fn clone_box(&self) -> Box<dyn EventLoopWaker> {
114        Box::new(self.clone())
115    }
116}
117
118/// The [`HeadlessEventLoop`] is used when running in headless mode. The event
119/// loop just loops over a condvar to simulate a real windowing system event loop.
120#[derive(Default)]
121pub(crate) struct HeadlessEventLoop {
122    guard: Arc<Mutex<bool>>,
123    condvar: Condvar,
124}
125
126impl HeadlessEventLoop {
127    fn run_app(&self, app: &mut App) {
128        app.init(None);
129
130        loop {
131            self.sleep();
132            if !app.pump_servo_event_loop(None) {
133                break;
134            }
135            *self.guard.lock().unwrap() = false;
136        }
137    }
138
139    fn sleep(&self) {
140        // To avoid sleeping when we should be processing events, do two things:
141        // * before sleeping, check whether our signalling flag has been set
142        // * wait on a condition variable with a maximum timeout, to allow
143        //   being woken up by any signals that occur while sleeping.
144        let guard = self.guard.lock().unwrap();
145        if *guard {
146            return;
147        }
148        let _ = self
149            .condvar
150            .wait_timeout(guard, time::Duration::from_millis(5))
151            .unwrap();
152    }
153}
154
155#[derive(Clone)]
156struct HeadlessEventLoopWaker(Arc<HeadlessEventLoop>);
157
158impl EventLoopWaker for HeadlessEventLoopWaker {
159    fn wake(&self) {
160        // Set the signalling flag and notify the condition variable.
161        // This ensures that any sleep operation is interrupted,
162        // and any non-sleeping operation will have a change to check
163        // the flag before going to sleep.
164        let mut flag = self.0.guard.lock().unwrap();
165        *flag = true;
166        self.0.condvar.notify_all();
167    }
168
169    fn clone_box(&self) -> Box<dyn EventLoopWaker> {
170        Box::new(self.clone())
171    }
172}
173
174pub(crate) struct RepaintEventLoopWaker {
175    proxy: EventLoopProxy<AppEvent>,
176    window_id: ServoShellWindowId,
177}
178
179impl RepaintEventLoopWaker {
180    pub(crate) fn new(proxy: EventLoopProxy<AppEvent>, window_id: ServoShellWindowId) -> Self {
181        Self { proxy, window_id }
182    }
183}
184
185impl Wake for RepaintEventLoopWaker {
186    fn wake(self: Arc<Self>) {
187        let _ = self
188            .proxy
189            .send_event(AppEvent::RequestRepaint(self.window_id));
190    }
191}