Skip to main content

eframe/native/
run.rs

1use core::time::Duration;
2use std::time::Instant;
3
4use winit::{
5    application::ApplicationHandler,
6    event_loop::{ActiveEventLoop, ControlFlow, EventLoop},
7    window::WindowId,
8};
9
10use ahash::HashMap;
11
12use super::winit_integration::{UserEvent, WinitApp};
13use crate::{
14    Result, epi,
15    native::{
16        event_loop_context,
17        winit_integration::{EventResult, is_invisible_or_minimized},
18    },
19};
20
21/// Minimum interval between repaints for invisible windows.
22///
23/// On Windows, invisible windows don't receive `RedrawRequested` events,
24/// so we throttle their repaints to avoid busy-looping while still
25/// processing viewport commands like `Visible(true)`.
26/// See <https://github.com/emilk/egui/issues/7776>.
27const INVISIBLE_WINDOW_REPAINT_INTERVAL: Duration = Duration::from_millis(100);
28
29// ----------------------------------------------------------------------------
30fn create_event_loop(native_options: &mut epi::NativeOptions) -> Result<EventLoop<UserEvent>> {
31    #[cfg(target_os = "android")]
32    use winit::platform::android::EventLoopBuilderExtAndroid as _;
33
34    profiling::function_scope!();
35    let mut builder = winit::event_loop::EventLoop::with_user_event();
36
37    #[cfg(target_os = "android")]
38    let mut builder =
39        builder.with_android_app(native_options.android_app.take().ok_or_else(|| {
40            crate::Error::AppCreation(Box::from(
41                "`NativeOptions` is missing required `android_app`",
42            ))
43        })?);
44
45    if let Some(hook) = core::mem::take(&mut native_options.event_loop_builder) {
46        hook(&mut builder);
47    }
48
49    profiling::scope!("EventLoopBuilder::build");
50    Ok(builder.build()?)
51}
52
53/// Access a thread-local event loop.
54///
55/// We reuse the event-loop so we can support closing and opening an eframe window
56/// multiple times. This is just a limitation of winit.
57#[cfg(not(target_os = "ios"))]
58fn with_event_loop<R>(
59    mut native_options: epi::NativeOptions,
60    f: impl FnOnce(&mut EventLoop<UserEvent>, epi::NativeOptions) -> R,
61) -> Result<R> {
62    thread_local!(static EVENT_LOOP: core::cell::RefCell<Option<EventLoop<UserEvent>>> = const { core::cell::RefCell::new(None) });
63
64    EVENT_LOOP.with(|event_loop| {
65        // Since we want to reference NativeOptions when creating the EventLoop we can't
66        // do that as part of the lazy thread local storage initialization and so we instead
67        // create the event loop lazily here
68        let mut event_loop_lock = event_loop.borrow_mut();
69        let event_loop = if let Some(event_loop) = &mut *event_loop_lock {
70            event_loop
71        } else {
72            event_loop_lock.insert(create_event_loop(&mut native_options)?)
73        };
74        Ok(f(event_loop, native_options))
75    })
76}
77
78/// Wraps a [`WinitApp`] to implement [`ApplicationHandler`]. This handles redrawing, exit states, and
79/// some events, but otherwise forwards events to the [`WinitApp`].
80struct WinitAppWrapper<T: WinitApp> {
81    windows_next_repaint_times: HashMap<WindowId, Instant>,
82    winit_app: T,
83    return_result: Result<(), crate::Error>,
84    run_and_return: bool,
85}
86
87impl<T: WinitApp> WinitAppWrapper<T> {
88    fn new(winit_app: T, run_and_return: bool) -> Self {
89        Self {
90            windows_next_repaint_times: HashMap::default(),
91            winit_app,
92            return_result: Ok(()),
93            run_and_return,
94        }
95    }
96
97    fn handle_event_result(
98        &mut self,
99        event_loop: &ActiveEventLoop,
100        event_result: Result<EventResult>,
101    ) {
102        let mut exit = false;
103        let mut save = false;
104
105        log::trace!("event_result: {event_result:?}");
106
107        let mut event_result = event_result;
108
109        if cfg!(target_os = "windows")
110            && let Ok(EventResult::RepaintNow(window_id)) = event_result
111        {
112            log::trace!("RepaintNow of {window_id:?}");
113            self.windows_next_repaint_times
114                .insert(window_id, Instant::now());
115
116            // Fix flickering on Windows, see https://github.com/emilk/egui/pull/2280
117            event_result = self.winit_app.run_ui_and_paint(event_loop, window_id);
118        }
119
120        let combined_result = event_result.map(|event_result| match event_result {
121            EventResult::Wait => {
122                event_loop.set_control_flow(ControlFlow::Wait);
123                event_result
124            }
125            EventResult::RepaintNow(window_id) => {
126                log::trace!("RepaintNow of {window_id:?}");
127                self.windows_next_repaint_times
128                    .insert(window_id, Instant::now());
129                event_result
130            }
131            EventResult::RepaintNext(window_id) => {
132                log::trace!("RepaintNext of {window_id:?}");
133                self.windows_next_repaint_times
134                    .insert(window_id, Instant::now());
135                event_result
136            }
137            EventResult::RepaintAt(window_id, repaint_time) => {
138                self.windows_next_repaint_times.insert(
139                    window_id,
140                    self.windows_next_repaint_times
141                        .get(&window_id)
142                        .map_or(repaint_time, |last| (*last).min(repaint_time)),
143                );
144                event_result
145            }
146            EventResult::Save => {
147                save = true;
148                event_result
149            }
150            EventResult::Exit => {
151                exit = true;
152                event_result
153            }
154            EventResult::CloseRequested => {
155                // The windows need to be dropped whilst the event loop is running to allow for proper cleanup.
156                self.winit_app.save_and_destroy();
157                event_result
158            }
159        });
160
161        if let Err(err) = combined_result {
162            log::error!("Exiting because of error: {err}");
163            exit = true;
164            self.return_result = Err(err);
165        }
166
167        if save {
168            log::debug!("Received an EventResult::Save - saving app state");
169            self.winit_app.save();
170        }
171
172        if exit {
173            if self.run_and_return {
174                log::debug!("Asking to exit event loop…");
175                event_loop.exit();
176            } else {
177                log::debug!("Quitting - saving app state…");
178                self.winit_app.save_and_destroy();
179
180                log::debug!("Exiting with return code 0");
181
182                std::process::exit(0);
183            }
184        }
185
186        self.check_redraw_requests(event_loop);
187    }
188
189    fn check_redraw_requests(&mut self, event_loop: &ActiveEventLoop) {
190        let now = Instant::now();
191
192        let mut invisible_window_ids = Vec::new();
193
194        self.windows_next_repaint_times
195            .retain(|window_id, repaint_time| {
196                if now < *repaint_time {
197                    return true; // not yet ready
198                }
199
200                if let Some(window) = self.winit_app.window(*window_id) {
201                    // On Windows, invisible windows don't receive RedrawRequested
202                    // events, so pending viewport commands (e.g. Visible(true)) would
203                    // never be processed. We collect these windows to paint them
204                    // directly below.
205                    // See: https://github.com/emilk/egui/issues/5229
206                    if is_invisible_or_minimized(&window) {
207                        invisible_window_ids.push(*window_id);
208                    } else {
209                        log::trace!("request_redraw for {window_id:?}");
210                        // Don't switch to `ControlFlow::Poll` here. `request_redraw`
211                        // is enough to wake the event loop, and on Wayland the
212                        // `RedrawRequested` event is only delivered once the
213                        // compositor sends a frame callback. Polling in the meantime
214                        // busy-loops a whole CPU core.
215                        // See https://github.com/emilk/egui/issues/8326.
216                        window.request_redraw();
217                    }
218                } else {
219                    log::trace!("No window found for {window_id:?}");
220                }
221                false
222            });
223
224        // Paint invisible windows directly, since they won't receive
225        // RedrawRequested events on Windows. This ensures that viewport
226        // commands like Visible(true) are still processed.
227        for window_id in &invisible_window_ids {
228            let event_result = self.winit_app.run_ui_and_paint(event_loop, *window_id);
229            self.handle_event_result(event_loop, event_result);
230        }
231
232        // Throttle any already-scheduled repaints for invisible windows
233        // to avoid busy-looping. If no repaint was requested by the app,
234        // the window will simply sleep.
235        // See: https://github.com/emilk/egui/issues/7776
236        if !invisible_window_ids.is_empty() {
237            let next_paint = Instant::now() + INVISIBLE_WINDOW_REPAINT_INTERVAL;
238            for window_id in &invisible_window_ids {
239                self.windows_next_repaint_times
240                    .entry(*window_id)
241                    .and_modify(|t| *t = (*t).min(next_paint));
242            }
243        }
244
245        // Always set an explicit, sleeping control flow. Previously we only set
246        // `WaitUntil` when a repaint was already scheduled, which meant that a
247        // `ControlFlow::Poll` set earlier was never undone once the last timed
248        // repaint had been consumed, leaving the loop spinning.
249        // See https://github.com/emilk/egui/issues/8326.
250        let next_repaint_time = self.windows_next_repaint_times.values().min().copied();
251        event_loop.set_control_flow(match next_repaint_time {
252            Some(next_repaint_time) => ControlFlow::WaitUntil(next_repaint_time),
253            None => ControlFlow::Wait,
254        });
255    }
256}
257
258impl<T: WinitApp> ApplicationHandler<UserEvent> for WinitAppWrapper<T> {
259    fn suspended(&mut self, event_loop: &ActiveEventLoop) {
260        profiling::scope!("Event::Suspended");
261
262        event_loop_context::with_event_loop_context(event_loop, move || {
263            let event_result = self.winit_app.suspended(event_loop);
264            self.handle_event_result(event_loop, event_result);
265        });
266    }
267
268    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
269        profiling::scope!("Event::Resumed");
270
271        // Nb: Make sure this guard is dropped after this function returns.
272        event_loop_context::with_event_loop_context(event_loop, move || {
273            let event_result = self.winit_app.resumed(event_loop);
274            self.handle_event_result(event_loop, event_result);
275        });
276    }
277
278    fn exiting(&mut self, event_loop: &ActiveEventLoop) {
279        // On Mac, Cmd-Q we get here and then `run_app_on_demand` doesn't return (despite its name),
280        // so we need to save state now:
281        log::debug!("Received Event::LoopExiting - saving app state…");
282        event_loop_context::with_event_loop_context(event_loop, move || {
283            self.winit_app.save_and_destroy();
284        });
285    }
286
287    fn device_event(
288        &mut self,
289        event_loop: &ActiveEventLoop,
290        device_id: winit::event::DeviceId,
291        event: winit::event::DeviceEvent,
292    ) {
293        profiling::function_scope!(egui_winit::short_device_event_description(&event));
294
295        // Nb: Make sure this guard is dropped after this function returns.
296        event_loop_context::with_event_loop_context(event_loop, move || {
297            let event_result = self.winit_app.device_event(event_loop, device_id, event);
298            self.handle_event_result(event_loop, event_result);
299        });
300    }
301
302    fn user_event(&mut self, event_loop: &ActiveEventLoop, event: UserEvent) {
303        profiling::function_scope!(match &event {
304            UserEvent::RequestRepaint { .. } => "UserEvent::RequestRepaint",
305            #[cfg(feature = "accesskit")]
306            UserEvent::AccessKitActionRequest(_) => "UserEvent::AccessKitActionRequest",
307        });
308
309        event_loop_context::with_event_loop_context(event_loop, move || {
310            let event_result = match event {
311                UserEvent::RequestRepaint {
312                    when,
313                    cumulative_pass_nr,
314                    viewport_id,
315                } => {
316                    let current_pass_nr = self
317                        .winit_app
318                        .egui_ctx()
319                        .map_or(0, |ctx| ctx.cumulative_pass_nr_for(viewport_id));
320                    if current_pass_nr == cumulative_pass_nr
321                        || current_pass_nr == cumulative_pass_nr + 1
322                    {
323                        log::trace!("UserEvent::RequestRepaint scheduling repaint at {when:?}");
324                        if let Some(window_id) =
325                            self.winit_app.window_id_from_viewport_id(viewport_id)
326                        {
327                            // Throttle repaints for invisible windows to prevent
328                            // high CPU usage on Windows.
329                            // See: https://github.com/emilk/egui/issues/7776
330                            let when = if let Some(window) = self.winit_app.window(window_id)
331                                && is_invisible_or_minimized(&window)
332                            {
333                                when.max(Instant::now() + INVISIBLE_WINDOW_REPAINT_INTERVAL)
334                            } else {
335                                when
336                            };
337                            Ok(EventResult::RepaintAt(window_id, when))
338                        } else {
339                            Ok(EventResult::Wait)
340                        }
341                    } else {
342                        log::trace!("Got outdated UserEvent::RequestRepaint");
343                        Ok(EventResult::Wait) // old request - we've already repainted
344                    }
345                }
346                #[cfg(feature = "accesskit")]
347                UserEvent::AccessKitActionRequest(request) => {
348                    self.winit_app.on_accesskit_event(request)
349                }
350            };
351            self.handle_event_result(event_loop, event_result);
352        });
353    }
354
355    fn new_events(&mut self, event_loop: &ActiveEventLoop, cause: winit::event::StartCause) {
356        if let winit::event::StartCause::ResumeTimeReached { .. } = cause {
357            log::trace!("Woke up to check next_repaint_time");
358        }
359
360        self.check_redraw_requests(event_loop);
361    }
362
363    fn window_event(
364        &mut self,
365        event_loop: &ActiveEventLoop,
366        window_id: WindowId,
367        event: winit::event::WindowEvent,
368    ) {
369        profiling::function_scope!(egui_winit::short_window_event_description(&event));
370
371        // Nb: Make sure this guard is dropped after this function returns.
372        event_loop_context::with_event_loop_context(event_loop, move || {
373            let event_result = match event {
374                winit::event::WindowEvent::RedrawRequested => {
375                    self.winit_app.run_ui_and_paint(event_loop, window_id)
376                }
377                _ => self.winit_app.window_event(event_loop, window_id, event),
378            };
379
380            self.handle_event_result(event_loop, event_result);
381        });
382    }
383}
384
385#[cfg(not(target_os = "ios"))]
386fn run_and_return(event_loop: &mut EventLoop<UserEvent>, winit_app: impl WinitApp) -> Result {
387    use winit::platform::run_on_demand::EventLoopExtRunOnDemand as _;
388
389    log::trace!("Entering the winit event loop (run_app_on_demand)…");
390
391    let mut app = WinitAppWrapper::new(winit_app, true);
392    event_loop.run_app_on_demand(&mut app)?;
393    log::debug!("eframe window closed");
394    app.return_result
395}
396
397fn run_and_exit(event_loop: EventLoop<UserEvent>, winit_app: impl WinitApp) -> Result {
398    log::trace!("Entering the winit event loop (run_app)…");
399
400    // When to repaint what window
401    let mut app = WinitAppWrapper::new(winit_app, false);
402    event_loop.run_app(&mut app)?;
403
404    log::debug!("winit event loop unexpectedly returned");
405    Ok(())
406}
407
408// ----------------------------------------------------------------------------
409
410#[cfg(feature = "glow")]
411pub fn run_glow(
412    app_name: &str,
413    mut native_options: epi::NativeOptions,
414    egui_ctx: Option<egui::Context>,
415    app_creator: epi::AppCreator<'_>,
416) -> Result {
417    use super::glow_integration::GlowWinitApp;
418
419    #[cfg(not(target_os = "ios"))]
420    if native_options.run_and_return {
421        return with_event_loop(native_options, |event_loop, native_options| {
422            let glow_eframe =
423                GlowWinitApp::new(event_loop, app_name, native_options, egui_ctx, app_creator);
424            run_and_return(event_loop, glow_eframe)
425        })?;
426    }
427
428    let event_loop = create_event_loop(&mut native_options)?;
429    let glow_eframe =
430        GlowWinitApp::new(&event_loop, app_name, native_options, egui_ctx, app_creator);
431    run_and_exit(event_loop, glow_eframe)
432}
433
434#[cfg(feature = "glow")]
435pub fn create_glow<'a>(
436    app_name: &str,
437    native_options: epi::NativeOptions,
438    app_creator: epi::AppCreator<'a>,
439    event_loop: &EventLoop<UserEvent>,
440) -> impl ApplicationHandler<UserEvent> + 'a {
441    use super::glow_integration::GlowWinitApp;
442
443    let glow_eframe = GlowWinitApp::new(event_loop, app_name, native_options, None, app_creator);
444    WinitAppWrapper::new(glow_eframe, true)
445}
446
447// ----------------------------------------------------------------------------
448
449#[cfg(feature = "wgpu_no_default_features")]
450pub fn run_wgpu(
451    app_name: &str,
452    mut native_options: epi::NativeOptions,
453    egui_ctx: Option<egui::Context>,
454    app_creator: epi::AppCreator<'_>,
455) -> Result {
456    use super::wgpu_integration::WgpuWinitApp;
457
458    #[cfg(not(target_os = "ios"))]
459    if native_options.run_and_return {
460        return with_event_loop(native_options, |event_loop, native_options| {
461            let wgpu_eframe =
462                WgpuWinitApp::new(event_loop, app_name, native_options, egui_ctx, app_creator);
463            run_and_return(event_loop, wgpu_eframe)
464        })?;
465    }
466
467    let event_loop = create_event_loop(&mut native_options)?;
468    let wgpu_eframe =
469        WgpuWinitApp::new(&event_loop, app_name, native_options, egui_ctx, app_creator);
470    run_and_exit(event_loop, wgpu_eframe)
471}
472
473#[cfg(feature = "wgpu_no_default_features")]
474pub fn create_wgpu<'a>(
475    app_name: &str,
476    native_options: epi::NativeOptions,
477    app_creator: epi::AppCreator<'a>,
478    event_loop: &EventLoop<UserEvent>,
479) -> impl ApplicationHandler<UserEvent> + 'a {
480    use super::wgpu_integration::WgpuWinitApp;
481
482    let wgpu_eframe = WgpuWinitApp::new(event_loop, app_name, native_options, None, app_creator);
483    WinitAppWrapper::new(wgpu_eframe, true)
484}
485
486// ----------------------------------------------------------------------------
487
488/// A proxy to the eframe application that implements [`ApplicationHandler`].
489///
490/// This can be run directly on your own [`EventLoop`] by itself or with other
491/// windows you manage outside of eframe.
492pub struct EframeWinitApplication<'a> {
493    wrapper: Box<dyn ApplicationHandler<UserEvent> + 'a>,
494    control_flow: ControlFlow,
495}
496
497impl ApplicationHandler<UserEvent> for EframeWinitApplication<'_> {
498    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
499        self.wrapper.resumed(event_loop);
500    }
501
502    fn window_event(
503        &mut self,
504        event_loop: &ActiveEventLoop,
505        window_id: winit::window::WindowId,
506        event: winit::event::WindowEvent,
507    ) {
508        self.wrapper.window_event(event_loop, window_id, event);
509    }
510
511    fn new_events(&mut self, event_loop: &ActiveEventLoop, cause: winit::event::StartCause) {
512        self.wrapper.new_events(event_loop, cause);
513    }
514
515    fn user_event(&mut self, event_loop: &ActiveEventLoop, event: UserEvent) {
516        self.wrapper.user_event(event_loop, event);
517    }
518
519    fn device_event(
520        &mut self,
521        event_loop: &ActiveEventLoop,
522        device_id: winit::event::DeviceId,
523        event: winit::event::DeviceEvent,
524    ) {
525        self.wrapper.device_event(event_loop, device_id, event);
526    }
527
528    fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
529        self.wrapper.about_to_wait(event_loop);
530        self.control_flow = event_loop.control_flow();
531    }
532
533    fn suspended(&mut self, event_loop: &ActiveEventLoop) {
534        self.wrapper.suspended(event_loop);
535    }
536
537    fn exiting(&mut self, event_loop: &ActiveEventLoop) {
538        self.wrapper.exiting(event_loop);
539    }
540
541    fn memory_warning(&mut self, event_loop: &ActiveEventLoop) {
542        self.wrapper.memory_warning(event_loop);
543    }
544}
545
546impl<'a> EframeWinitApplication<'a> {
547    pub(crate) fn new<T: ApplicationHandler<UserEvent> + 'a>(app: T) -> Self {
548        Self {
549            wrapper: Box::new(app),
550            control_flow: ControlFlow::default(),
551        }
552    }
553
554    /// Pump the `EventLoop` to check for and dispatch pending events to this application.
555    ///
556    /// Returns either the exit code for the application or the final state of the [`ControlFlow`]
557    /// after all events have been dispatched in this iteration.
558    ///
559    /// This is useful when your [`EventLoop`] is not the main event loop for your application.
560    /// See the `external_eventloop_async` example.
561    #[cfg(not(target_os = "ios"))]
562    pub fn pump_eframe_app(
563        &mut self,
564        event_loop: &mut EventLoop<UserEvent>,
565        timeout: Option<core::time::Duration>,
566    ) -> EframePumpStatus {
567        use winit::platform::pump_events::{EventLoopExtPumpEvents as _, PumpStatus};
568
569        match event_loop.pump_app_events(timeout, self) {
570            PumpStatus::Continue => EframePumpStatus::Continue(self.control_flow),
571            PumpStatus::Exit(code) => EframePumpStatus::Exit(code),
572        }
573    }
574}
575
576/// Either an exit code or a [`ControlFlow`] from the [`ActiveEventLoop`].
577///
578/// The result of [`EframeWinitApplication::pump_eframe_app`].
579#[cfg(not(target_os = "ios"))]
580pub enum EframePumpStatus {
581    /// The final state of the [`ControlFlow`] after all events have been dispatched
582    ///
583    /// Callers should perform the action that is appropriate for the [`ControlFlow`] value.
584    Continue(ControlFlow),
585
586    /// The exit code for the application
587    Exit(i32),
588}