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