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/// Create an egui context, restoring it from storage if possible.
33pub fn create_egui_context(storage: Option<&dyn crate::Storage>) -> egui::Context {
34    profiling::function_scope!();
35
36    pub const IS_DESKTOP: bool = cfg!(any(
37        target_os = "freebsd",
38        target_os = "linux",
39        target_os = "macos",
40        target_os = "openbsd",
41        target_os = "windows",
42    ));
43
44    let egui_ctx = egui::Context::default();
45
46    egui_ctx.set_embed_viewports(!IS_DESKTOP);
47
48    egui_ctx.options_mut(|o| {
49        // eframe supports multi-pass (Context::request_discard).
50        #[expect(clippy::unwrap_used)]
51        {
52            o.max_passes = 2.try_into().unwrap();
53        }
54    });
55
56    let memory = crate::native::epi_integration::load_egui_memory(storage).unwrap_or_default();
57    egui_ctx.memory_mut(|mem| *mem = memory);
58
59    egui_ctx
60}
61
62/// The custom even `eframe` uses with the [`winit`] event loop.
63#[derive(Debug)]
64pub enum UserEvent {
65    /// A repaint is requested.
66    RequestRepaint {
67        /// What to repaint.
68        viewport_id: ViewportId,
69
70        /// When to repaint.
71        when: Instant,
72
73        /// What the cumulative pass number was when the repaint was _requested_.
74        cumulative_pass_nr: u64,
75    },
76
77    /// A request related to [`accesskit`](https://accesskit.dev/).
78    #[cfg(feature = "accesskit")]
79    AccessKitActionRequest(accesskit_winit::Event),
80}
81
82#[cfg(feature = "accesskit")]
83impl From<accesskit_winit::Event> for UserEvent {
84    fn from(inner: accesskit_winit::Event) -> Self {
85        Self::AccessKitActionRequest(inner)
86    }
87}
88
89pub trait WinitApp {
90    fn egui_ctx(&self) -> Option<&egui::Context>;
91
92    fn window(&self, window_id: WindowId) -> Option<Arc<Window>>;
93
94    fn window_id_from_viewport_id(&self, id: ViewportId) -> Option<WindowId>;
95
96    fn save(&mut self);
97
98    fn save_and_destroy(&mut self);
99
100    fn run_ui_and_paint(
101        &mut self,
102        event_loop: &ActiveEventLoop,
103        window_id: WindowId,
104    ) -> crate::Result<EventResult>;
105
106    fn suspended(&mut self, event_loop: &ActiveEventLoop) -> crate::Result<EventResult>;
107
108    fn resumed(&mut self, event_loop: &ActiveEventLoop) -> crate::Result<EventResult>;
109
110    fn device_event(
111        &mut self,
112        event_loop: &ActiveEventLoop,
113        device_id: winit::event::DeviceId,
114        event: winit::event::DeviceEvent,
115    ) -> crate::Result<EventResult>;
116
117    fn window_event(
118        &mut self,
119        event_loop: &ActiveEventLoop,
120        window_id: WindowId,
121        event: winit::event::WindowEvent,
122    ) -> crate::Result<EventResult>;
123
124    #[cfg(feature = "accesskit")]
125    fn on_accesskit_event(&mut self, event: accesskit_winit::Event) -> crate::Result<EventResult>;
126}
127
128#[derive(Clone, Copy, Debug, PartialEq, Eq)]
129pub enum EventResult {
130    Wait,
131
132    /// Causes a synchronous repaint inside the event handler. This should only
133    /// be used in special situations if the window must be repainted while
134    /// handling a specific event. This occurs on Windows when handling resizes.
135    ///
136    /// `RepaintNow` creates a new frame synchronously, and should therefore
137    /// only be used for extremely urgent repaints.
138    RepaintNow(WindowId),
139
140    /// Queues a repaint for once the event loop handles its next redraw. Exists
141    /// so that multiple input events can be handled in one frame. Does not
142    /// cause any delay like `RepaintNow`.
143    RepaintNext(WindowId),
144
145    RepaintAt(WindowId, Instant),
146
147    /// Causes a save of the client state when the persistence feature is enabled.
148    Save,
149
150    /// Starts the process of ending eframe execution whilst allowing for proper
151    /// clean up of resources.
152    ///
153    /// # Warning
154    /// This event **must** occur before [`Exit`] to correctly exit eframe code.
155    /// If in doubt, return this event.
156    ///
157    /// [`Exit`]: [EventResult::Exit]
158    CloseRequested,
159
160    /// The event loop will exit, now.
161    /// The correct circumstance to return this event is in response to a winit "Destroyed" event.
162    ///
163    /// # Warning
164    /// The [`CloseRequested`] **must** occur before this event to ensure that winit
165    /// is able to remove any open windows. Otherwise the window(s) will remain open
166    /// until the program terminates.
167    ///
168    /// [`CloseRequested`]: EventResult::CloseRequested
169    Exit,
170}
171
172#[cfg(feature = "accesskit")]
173pub(crate) fn on_accesskit_window_event(
174    egui_winit: &mut egui_winit::State,
175    window_id: WindowId,
176    event: &accesskit_winit::WindowEvent,
177) -> EventResult {
178    match event {
179        accesskit_winit::WindowEvent::InitialTreeRequested => {
180            egui_winit.egui_ctx().enable_accesskit();
181            // Because we can't provide the initial tree synchronously
182            // (because that would require the activation handler to access
183            // the same mutable state as the winit event handler), some
184            // AccessKit platform adapters will use a placeholder tree
185            // until we send the first tree update. To minimize the possible
186            // bad effects of that workaround, repaint and send the tree
187            // immediately.
188            EventResult::RepaintNow(window_id)
189        }
190        accesskit_winit::WindowEvent::ActionRequested(request) => {
191            egui_winit.on_accesskit_action_request(request.clone());
192            // As a form of user input, accessibility actions should cause
193            // a repaint, but not until the next regular frame.
194            EventResult::RepaintNext(window_id)
195        }
196        accesskit_winit::WindowEvent::AccessibilityDeactivated => {
197            egui_winit.egui_ctx().disable_accesskit();
198            // Disabling AccessKit support should have no visible effect,
199            // so there's no need to repaint.
200            EventResult::Wait
201        }
202    }
203}