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