ailloli_ui_winit/
event_loop.rs

1//! winit event loop construction and `ApplicationHandler` execution.
2
3use winit::application::ApplicationHandler;
4use winit::error::EventLoopError;
5use winit::event_loop::{ControlFlow, EventLoop};
6
7#[cfg(target_os = "linux")]
8/// Process-global Ctrl+C state used to wake and stop the active Linux event loop.
9pub(crate) mod shutdown_signal {
10    use std::sync::atomic::{AtomicBool, Ordering};
11    use std::sync::{Mutex, Once};
12
13    use winit::event_loop::EventLoopProxy;
14
15    /// Ensures the OS signal handler is registered at most once per process.
16    static INSTALL: Once = Once::new();
17    /// Latched request bit consumed by [`take_requested`].
18    static SHUTDOWN_REQUESTED: AtomicBool = AtomicBool::new(false);
19    /// Most recently installed event-loop proxy, replaced on each application run.
20    static PROXY: Mutex<Option<EventLoopProxy<()>>> = Mutex::new(None);
21
22    /// Registers `proxy` for wake-ups and lazily installs the process handler.
23    ///
24    /// Signal-handler installation failure is intentionally ignored: the event
25    /// loop can still exit through its normal window lifecycle. A poisoned proxy
26    /// mutex likewise suppresses wake-up rather than panicking.
27    ///
28    /// # Examples
29    ///
30    /// ```no_run
31    /// // `run_app_on_event_loop` installs the shutdown bridge automatically.
32    /// let loop_: winit::event_loop::EventLoop<()> =
33    ///     ailloli_ui_winit::new_event_loop().unwrap();
34    /// let _proxy = loop_.create_proxy();
35    /// ```
36    pub fn install(proxy: EventLoopProxy<()>) {
37        if let Ok(mut current) = PROXY.lock() {
38            *current = Some(proxy);
39        }
40
41        INSTALL.call_once(|| {
42            let _ = ctrlc::set_handler(|| {
43                SHUTDOWN_REQUESTED.store(true, Ordering::SeqCst);
44                if let Ok(current) = PROXY.lock() {
45                    if let Some(proxy) = current.as_ref() {
46                        let _ = proxy.send_event(());
47                    }
48                }
49            });
50        });
51    }
52
53    /// Atomically consumes the pending shutdown request.
54    ///
55    /// The first call after Ctrl+C returns `true`; subsequent calls return
56    /// `false` until another signal arrives. Sequential consistency is used so
57    /// the signal handler and event-loop thread agree on ordering.
58    ///
59    /// # Examples
60    ///
61    /// ```
62    /// // Public applications observe this through the runner's shutdown path.
63    /// let pending_before_a_signal = false;
64    /// assert!(!pending_before_a_signal);
65    /// ```
66    pub fn take_requested() -> bool {
67        SHUTDOWN_REQUESTED.swap(false, Ordering::SeqCst)
68    }
69}
70
71#[cfg(not(target_os = "linux"))]
72/// No-op shutdown bridge for platforms where winit owns signal handling.
73pub(crate) mod shutdown_signal {
74    use winit::event_loop::EventLoopProxy;
75
76    /// Accepts and drops the proxy; no process signal hook is installed.
77    ///
78    /// # Examples
79    ///
80    /// ```no_run
81    /// let loop_ = ailloli_ui_winit::new_event_loop().unwrap();
82    /// let _proxy: winit::event_loop::EventLoopProxy<()> = loop_.create_proxy();
83    /// ```
84    pub fn install(_proxy: EventLoopProxy<()>) {}
85
86    /// Always reports no framework-owned shutdown request.
87    ///
88    /// # Examples
89    ///
90    /// ```
91    /// let requested = false;
92    /// assert!(!requested);
93    /// ```
94    pub fn take_requested() -> bool {
95        false
96    }
97}
98
99/// Constructs the framework's unit-user-event loop on the calling thread.
100///
101/// Platform main-thread requirements are preserved; use
102/// [`new_event_loop_allow_any_thread`] for worker-thread Linux tests.
103///
104/// # Errors
105///
106/// Returns winit's construction error, including attempts to create more than
107/// one event loop where the platform forbids it.
108///
109/// # Examples
110///
111/// ```no_run
112/// let loop_: winit::event_loop::EventLoop<()> =
113///     ailloli_ui_winit::new_event_loop().unwrap();
114/// ```
115pub fn new_event_loop() -> Result<EventLoop<()>, EventLoopError> {
116    EventLoop::new()
117}
118
119/// Event loop usable from a non-main thread (worker-thread tests, Linux Wayland/X11).
120///
121/// On Linux this opts both Wayland and X11 builders into any-thread operation.
122/// Other platforms receive the ordinary builder and retain its platform rules.
123///
124/// # Errors
125///
126/// Propagates winit event-loop construction failures.
127///
128/// # Examples
129///
130/// ```no_run
131/// let loop_: winit::event_loop::EventLoop<()> =
132///     ailloli_ui_winit::new_event_loop_allow_any_thread().unwrap();
133/// ```
134pub fn new_event_loop_allow_any_thread() -> Result<EventLoop<()>, EventLoopError> {
135    #[cfg(target_os = "linux")]
136    {
137        use winit::platform::wayland::EventLoopBuilderExtWayland;
138        use winit::platform::x11::EventLoopBuilderExtX11;
139
140        let mut b = EventLoop::builder();
141        EventLoopBuilderExtWayland::with_any_thread(&mut b, true);
142        EventLoopBuilderExtX11::with_any_thread(&mut b, true);
143        b.build()
144    }
145    #[cfg(not(target_os = "linux"))]
146    {
147        EventLoop::builder().build()
148    }
149}
150
151/// Sets [`ControlFlow`] and runs the handler on an existing event loop.
152///
153/// The call blocks until winit exits. On Linux it installs the Ctrl+C wake-up
154/// bridge and treats `ExitFailure(1)` as a normal platform teardown; every other
155/// event-loop result is preserved.
156///
157/// # Errors
158///
159/// Returns any non-normalized winit event-loop failure.
160///
161/// # Examples
162///
163/// ```no_run
164/// use winit::{application::ApplicationHandler, event_loop::{ControlFlow, EventLoop}};
165/// fn run<A: ApplicationHandler + 'static>(loop_: EventLoop<()>, app: &mut A) {
166///     ailloli_ui_winit::run_app_on_event_loop(loop_, app, ControlFlow::Wait).unwrap();
167/// }
168/// ```
169pub fn run_app_on_event_loop<A: ApplicationHandler + 'static>(
170    event_loop: EventLoop<()>,
171    app: &mut A,
172    control_flow: ControlFlow,
173) -> Result<(), EventLoopError> {
174    shutdown_signal::install(event_loop.create_proxy());
175    event_loop.set_control_flow(control_flow);
176    match event_loop.run_app(app) {
177        #[cfg(target_os = "linux")]
178        Err(EventLoopError::ExitFailure(1)) => {
179            if crate::winit_trace_enabled() {
180                eprintln!("ailloli_ui_winit: event loop returned ExitFailure(1)");
181            }
182            // Wayland can report status 1 when the display connection is torn down
183            // during process interruption or window teardown. Ailloli UI does not use
184            // non-zero application exit codes yet, so treat this platform shutdown
185            // quirk as a clean loop stop while preserving explicit UiApp errors.
186            Ok(())
187        }
188        result => result,
189    }
190}