Skip to main content

eframe/native/
winit_integration.rs

1use std::{sync::Arc, time::Instant};
2
3use winit::{
4    event_loop::ActiveEventLoop,
5    window::{Window, WindowId},
6};
7
8use egui::ViewportId;
9#[cfg(feature = "accesskit")]
10use egui_winit::accesskit_winit;
11
12/// Returns `true` if the window is invisible or minimized.
13///
14/// These windows don't receive `RedrawRequested` events on Windows,
15/// so they need special handling to keep processing viewport commands.
16pub fn is_invisible_or_minimized(window: &Window) -> bool {
17    window.is_visible() == Some(false) || window.is_minimized() == Some(true)
18}
19
20/// On Mac, a minimized window uses up all CPU:
21/// <https://github.com/emilk/egui/issues/325>
22///
23/// On Windows, an invisible window also uses up all CPU:
24/// <https://github.com/emilk/egui/issues/7776>
25pub fn sleep_if_invisible_or_minimized(window: Option<&Window>) {
26    if window.is_some_and(is_invisible_or_minimized) {
27        profiling::scope!("minimized_sleep");
28        std::thread::sleep(core::time::Duration::from_millis(10));
29    }
30}
31
32/// Is a window built from `builder` held hidden until its first frame is painted?
33///
34/// Not when the app asked for it hidden, and not when it asks for maximized, fullscreen or a
35/// monitor: X11 window managers ignore those for a hidden window, and macOS enters fullscreen
36/// through a path of its own, so such a window keeps being created as the app described it.
37pub fn is_held_until_painted(builder: &egui::ViewportBuilder) -> bool {
38    builder.visible != Some(false)
39        && builder.maximized != Some(true)
40        && builder.fullscreen != Some(true)
41        && builder.monitor.is_none()
42}
43
44/// What [`WinitApp::run_ui_and_paint`] runs.
45#[derive(Clone, Copy, Debug, PartialEq, Eq)]
46pub enum PassMode {
47    /// Run [`crate::App::logic`], plus the ui and painting if the viewport is visible.
48    Full,
49
50    /// Run only [`crate::App::logic`]: no egui pass and no painting.
51    ///
52    /// Used when the window was asked to redraw, but the windowing system hasn't let it
53    /// (e.g. a Wayland compositor withholding frame callbacks from a hidden window).
54    LogicOnly,
55}
56
57/// Create an egui context, restoring it from storage if possible.
58pub fn create_egui_context(storage: Option<&dyn crate::Storage>) -> egui::Context {
59    profiling::function_scope!();
60
61    pub const IS_DESKTOP: bool = cfg!(any(
62        target_os = "freebsd",
63        target_os = "linux",
64        target_os = "macos",
65        target_os = "openbsd",
66        target_os = "windows",
67    ));
68
69    let egui_ctx = egui::Context::default();
70
71    egui_ctx.set_embed_viewports(!IS_DESKTOP);
72
73    egui_ctx.options_mut(|o| {
74        // eframe supports multi-pass (Context::request_discard).
75        #[expect(clippy::unwrap_used)]
76        {
77            o.max_passes = 2.try_into().unwrap();
78        }
79    });
80
81    let memory = crate::native::epi_integration::load_egui_memory(storage).unwrap_or_default();
82    egui_ctx.memory_mut(|mem| *mem = memory);
83
84    egui_ctx
85}
86
87/// The custom even `eframe` uses with the [`winit`] event loop.
88#[derive(Debug)]
89pub enum UserEvent {
90    /// A repaint is requested.
91    RequestRepaint {
92        /// What to repaint.
93        viewport_id: ViewportId,
94
95        /// When to repaint.
96        when: Instant,
97
98        /// What the cumulative pass number was when the repaint was _requested_.
99        cumulative_pass_nr: u64,
100    },
101
102    /// A request related to [`accesskit`](https://accesskit.dev/).
103    #[cfg(feature = "accesskit")]
104    AccessKitActionRequest(accesskit_winit::Event),
105}
106
107#[cfg(feature = "accesskit")]
108impl From<accesskit_winit::Event> for UserEvent {
109    fn from(inner: accesskit_winit::Event) -> Self {
110        Self::AccessKitActionRequest(inner)
111    }
112}
113
114pub trait WinitApp {
115    fn egui_ctx(&self) -> Option<&egui::Context>;
116
117    fn window(&self, window_id: WindowId) -> Option<Arc<Window>>;
118
119    fn window_id_from_viewport_id(&self, id: ViewportId) -> Option<WindowId>;
120
121    fn save(&mut self);
122
123    fn save_and_destroy(&mut self);
124
125    fn run_ui_and_paint(
126        &mut self,
127        event_loop: &ActiveEventLoop,
128        window_id: WindowId,
129        mode: PassMode,
130    ) -> crate::Result<EventResult>;
131
132    fn suspended(&mut self, event_loop: &ActiveEventLoop) -> crate::Result<EventResult>;
133
134    fn resumed(&mut self, event_loop: &ActiveEventLoop) -> crate::Result<EventResult>;
135
136    fn device_event(
137        &mut self,
138        event_loop: &ActiveEventLoop,
139        device_id: winit::event::DeviceId,
140        event: winit::event::DeviceEvent,
141    ) -> crate::Result<EventResult>;
142
143    fn window_event(
144        &mut self,
145        event_loop: &ActiveEventLoop,
146        window_id: WindowId,
147        event: winit::event::WindowEvent,
148    ) -> crate::Result<EventResult>;
149
150    #[cfg(feature = "accesskit")]
151    fn on_accesskit_event(&mut self, event: accesskit_winit::Event) -> crate::Result<EventResult>;
152}
153
154#[derive(Clone, Copy, Debug, PartialEq, Eq)]
155pub enum EventResult {
156    Wait,
157
158    /// Causes a synchronous repaint inside the event handler. This should only
159    /// be used in special situations if the window must be repainted while
160    /// handling a specific event. This occurs on Windows when handling resizes.
161    ///
162    /// `RepaintNow` creates a new frame synchronously, and should therefore
163    /// only be used for extremely urgent repaints.
164    RepaintNow(WindowId),
165
166    /// Queues a repaint for once the event loop handles its next redraw. Exists
167    /// so that multiple input events can be handled in one frame. Does not
168    /// cause any delay like `RepaintNow`.
169    RepaintNext(WindowId),
170
171    RepaintAt(WindowId, Instant),
172
173    /// Causes a save of the client state when the persistence feature is enabled.
174    Save,
175
176    /// Starts the process of ending eframe execution whilst allowing for proper
177    /// clean up of resources.
178    ///
179    /// # Warning
180    /// This event **must** occur before [`Exit`] to correctly exit eframe code.
181    /// If in doubt, return this event.
182    ///
183    /// [`Exit`]: [EventResult::Exit]
184    CloseRequested,
185
186    /// The event loop will exit, now.
187    /// The correct circumstance to return this event is in response to a winit "Destroyed" event.
188    ///
189    /// # Warning
190    /// The [`CloseRequested`] **must** occur before this event to ensure that winit
191    /// is able to remove any open windows. Otherwise the window(s) will remain open
192    /// until the program terminates.
193    ///
194    /// [`CloseRequested`]: EventResult::CloseRequested
195    Exit,
196}
197
198#[cfg(feature = "accesskit")]
199pub(crate) fn on_accesskit_window_event(
200    egui_winit: &mut egui_winit::State,
201    window_id: WindowId,
202    event: &accesskit_winit::WindowEvent,
203) -> EventResult {
204    match event {
205        accesskit_winit::WindowEvent::InitialTreeRequested => {
206            egui_winit.egui_ctx().enable_accesskit();
207            // Because we can't provide the initial tree synchronously
208            // (because that would require the activation handler to access
209            // the same mutable state as the winit event handler), some
210            // AccessKit platform adapters will use a placeholder tree
211            // until we send the first tree update. To minimize the possible
212            // bad effects of that workaround, repaint and send the tree
213            // immediately.
214            EventResult::RepaintNow(window_id)
215        }
216        accesskit_winit::WindowEvent::ActionRequested(request) => {
217            egui_winit.on_accesskit_action_request(request.clone());
218            // As a form of user input, accessibility actions should cause
219            // a repaint, but not until the next regular frame.
220            EventResult::RepaintNext(window_id)
221        }
222        accesskit_winit::WindowEvent::AccessibilityDeactivated => {
223            egui_winit.egui_ctx().disable_accesskit();
224            // Disabling AccessKit support should have no visible effect,
225            // so there's no need to repaint.
226            EventResult::Wait
227        }
228    }
229}
230
231#[cfg(test)]
232mod tests {
233    use super::*;
234
235    #[test]
236    fn a_plain_window_is_held_until_painted() {
237        assert!(is_held_until_painted(&egui::ViewportBuilder::default()));
238        assert!(is_held_until_painted(
239            &egui::ViewportBuilder::default().with_visible(true)
240        ));
241    }
242
243    #[test]
244    fn a_window_the_app_hid_stays_hidden() {
245        assert!(!is_held_until_painted(
246            &egui::ViewportBuilder::default().with_visible(false)
247        ));
248    }
249
250    #[test]
251    fn windows_that_ask_for_a_state_the_os_ignores_when_hidden_are_not_held() {
252        let builder = egui::ViewportBuilder::default;
253        assert!(!is_held_until_painted(&builder().with_maximized(true)));
254        assert!(!is_held_until_painted(&builder().with_fullscreen(true)));
255        assert!(!is_held_until_painted(&builder().with_monitor(0)));
256        assert!(is_held_until_painted(&builder().with_maximized(false)));
257    }
258}