Skip to main content

egui_pop_api/
main_wake.rs

1//! The main window's frames owed, for whoever runs the event loop.
2//!
3//! <div class="warning">Experimental: may change in any release
4//! (docs/stability.md).</div>
5//!
6//! egui paints a window in its `RedrawRequested`, and on Wayland that
7//! event comes only with the compositor's frame callback, which a
8//! compositor withholds from a window it does not show: GNOME's, for a
9//! main window covered by the application's other windows. eframe then
10//! runs the application's logic only (`App::logic`), no pass of the main
11//! window, until the system shows it again.
12//!
13//! The main window's pass is not only its own picture: it lets go of a
14//! closed window (the backend drops the system windows its last pass no
15//! longer declares) and it draws the detached panels' windows (egui's
16//! immediate viewports, painted inside it). With the main window covered,
17//! a closed Settings window stayed on screen frozen, and a detached
18//! panel froze while it was the one shown, until a click or Alt+Tab
19//! brought the main window forward.
20//!
21//! [`MainWake`] keeps what is owed: a repaint asked of the main window
22//! (egui's repaint request, for it), or a redraw of a window that ran no
23//! pass of its own (an immediate viewport: its pass is the main
24//! window's); a pass of the main window pays it. Owed longer than
25//! [`GRACE`], the loop paints the main window itself ([`MainWake::due`]),
26//! as a `RedrawRequested` the system did not send. Safe where the present
27//! does not wait for the compositor (egui-pop's present mode on Wayland,
28//! `windows::present_mode`); a FIFO present to a hidden Wayland surface
29//! can block, so a loop presenting that way does not paint
30//! ([`MainWake::set_enabled`]).
31//!
32//! The window key `W` is the loop's window id (winit's `WindowId`); the
33//! crate's native runner and a host running its own loop use it alike,
34//! and the test kit runs it with viewport ids.
35
36use std::time::Duration;
37
38use web_time::Instant;
39
40/// How long a frame of the main window may be owed before the loop paints
41/// it: well over a frame at 30 Hz, so a window the system shows always
42/// gets its own redraw first; short enough that a closed window goes
43/// without a wait anyone notices.
44pub const GRACE: Duration = Duration::from_millis(100);
45
46/// The main window's frame owed, and since when.
47#[derive(Debug)]
48pub struct MainWake<W> {
49    main: Option<W>,
50    enabled: bool,
51    /// When the frame owed came due, and the main window's passes then.
52    owed: Option<(Instant, u64)>,
53    /// The main window's passes counted so far.
54    passes: u64,
55    /// The context's passes, counted by its begin-pass hook.
56    counter: Option<PassCounter>,
57}
58
59impl<W> Default for MainWake<W> {
60    fn default() -> Self {
61        Self {
62            main: None,
63            enabled: true,
64            owed: None,
65            passes: 0,
66            counter: None,
67        }
68    }
69}
70
71impl<W: Copy + PartialEq> MainWake<W> {
72    pub fn new() -> Self {
73        Self::default()
74    }
75
76    /// The main window's id, once the loop knows it.
77    pub fn set_main(&mut self, main: W) {
78        self.main = Some(main);
79    }
80
81    pub fn main(&self) -> Option<W> {
82        self.main
83    }
84
85    /// Counts the passes of the application's context
86    /// ([`PassCounter::install`]): the main window's pay what is owed,
87    /// and a redraw that began none drew an immediate viewport
88    /// ([`MainWake::redraw`]).
89    pub fn set_counter(&mut self, counter: PassCounter) {
90        self.counter = Some(counter);
91    }
92
93    /// The main window's passes begun, from the counter.
94    fn sync(&mut self) {
95        if let Some(n) = self.counter.as_ref().map(PassCounter::main) {
96            self.main_passes(n);
97        }
98    }
99
100    /// Runs the system's (or the loop's) redraw of `window` (`run`:
101    /// handing `RedrawRequested` to eframe); with a counter, a redraw of
102    /// a window other than the main one that began no pass owes the main
103    /// window a frame.
104    pub fn redraw<R>(&mut self, window: W, run: impl FnOnce() -> R) -> R {
105        self.sync();
106        let before = self.counter.as_ref().map(PassCounter::all);
107        let out = run();
108        if let (Some(c), Some(before)) = (&self.counter, before) {
109            let own_pass = c.all() > before;
110            self.redrawn(window, own_pass, Instant::now());
111        }
112        self.sync();
113        out
114    }
115
116    /// Whether the loop paints the main window when its frame is owed
117    /// too long (off where a present to a hidden window can block).
118    pub fn set_enabled(&mut self, enabled: bool) {
119        self.enabled = enabled;
120    }
121
122    /// A repaint is asked of the main window, due at `at`: owed from
123    /// then, unless a frame is owed already.
124    pub fn asked(&mut self, at: Instant) {
125        self.sync();
126        let passes = self.passes;
127        match &mut self.owed {
128            Some((since, _)) if *since <= at => {}
129            owed => *owed = Some((at, passes)),
130        }
131    }
132
133    /// A window's redraw ran: `window`, with `passes` main-window passes
134    /// begun during it. A redraw of another window that began no pass of
135    /// its own (`own_pass` false: an immediate viewport, drawn by the
136    /// main window's pass) owes the main window a frame.
137    pub fn redrawn(&mut self, window: W, own_pass: bool, now: Instant) {
138        if Some(window) != self.main && !own_pass {
139            self.asked(now);
140        }
141    }
142
143    /// A pass of the main window began: what was owed before it is paid.
144    pub fn main_pass(&mut self) {
145        self.main_passes(self.passes + 1);
146    }
147
148    /// The main window's passes begun so far ([`PassCounter::main`]):
149    /// what was owed before the last of them is paid.
150    pub fn main_passes(&mut self, passes: u64) {
151        self.passes = self.passes.max(passes);
152        if self.owed.is_some_and(|(_, at)| self.passes > at) {
153            self.owed = None;
154        }
155    }
156
157    /// The main window's passes counted so far.
158    pub fn passes(&self) -> u64 {
159        self.passes
160    }
161
162    /// Whether a frame of the main window is owed.
163    pub fn owed(&self) -> bool {
164        self.owed.is_some()
165    }
166
167    /// When the loop should look again ([`MainWake::due`]): the owed
168    /// frame's time plus [`GRACE`].
169    pub fn next(&self) -> Option<Instant> {
170        if !self.enabled || self.main.is_none() {
171            return None;
172        }
173        self.owed.map(|(since, _)| since + GRACE)
174    }
175
176    /// The main window to paint now, its frame owed longer than
177    /// [`GRACE`] (the system sent no redraw for it). The loop paints it
178    /// at once (a `RedrawRequested` of its own making); the pass that
179    /// begins pays it.
180    pub fn due(&mut self, now: Instant) -> Option<W> {
181        self.sync();
182        let at = self.next()?;
183        if now < at {
184            return None;
185        }
186        // Painted now: owed again only by what is asked from here on.
187        self.owed = None;
188        self.main
189    }
190}
191
192/// The passes begun in a context, counted by a begin-pass hook: the main
193/// window's, and every window's (a redraw that began none drew an
194/// immediate viewport, whose pass is the main window's).
195#[derive(Clone, Debug, Default)]
196pub struct PassCounter {
197    main: std::sync::Arc<std::sync::atomic::AtomicU64>,
198    all: std::sync::Arc<std::sync::atomic::AtomicU64>,
199}
200
201impl PassCounter {
202    /// Counts `ctx`'s passes from now on.
203    pub fn install(ctx: &egui::Context) -> Self {
204        let counter = Self::default();
205        let c = counter.clone();
206        ctx.on_begin_pass(
207            "egui_pop::main_wake",
208            std::sync::Arc::new(move |ui: &mut egui::Ui| {
209                use std::sync::atomic::Ordering;
210                c.all.fetch_add(1, Ordering::Relaxed);
211                if ui.ctx().viewport_id() == egui::ViewportId::ROOT {
212                    c.main.fetch_add(1, Ordering::Relaxed);
213                }
214            }),
215        );
216        counter
217    }
218
219    /// The main window's passes begun.
220    pub fn main(&self) -> u64 {
221        self.main.load(std::sync::atomic::Ordering::Relaxed)
222    }
223
224    /// Every window's passes begun.
225    pub fn all(&self) -> u64 {
226        self.all.load(std::sync::atomic::Ordering::Relaxed)
227    }
228}
229
230/// eframe's side: its repaint request for the main window (the event
231/// egui's repaint callback sends to the loop) as eframe takes it, a
232/// request outdated by a pass since being dropped.
233#[cfg(all(feature = "eframe", not(target_arch = "wasm32")))]
234impl<W: Copy + PartialEq> MainWake<W> {
235    /// Notes eframe's `UserEvent::RequestRepaint` for the main window
236    /// (`ctx`: the application's context). Call it before handing the
237    /// event to eframe.
238    pub fn user_event(&mut self, ctx: &egui::Context, event: &eframe::UserEvent) {
239        #[allow(
240            irrefutable_let_patterns,
241            reason = "eframe's UserEvent has a single variant in some builds; the match stays right when it gains more"
242        )]
243        if let eframe::UserEvent::RequestRepaint {
244            viewport_id,
245            when,
246            cumulative_pass_nr,
247        } = event
248            && *viewport_id == egui::ViewportId::ROOT
249        {
250            let now = ctx.cumulative_pass_nr_for(egui::ViewportId::ROOT);
251            if now == *cumulative_pass_nr || now == cumulative_pass_nr + 1 {
252                self.asked(*when);
253            }
254        }
255    }
256}
257
258/// Whether the loop may paint a window the system does not show with
259/// this present mode: not with a FIFO present (eframe's default), which on
260/// Wayland waits for the compositor's frame callback that a hidden window
261/// does not get; with one that does not wait (egui-pop's choice on
262/// Wayland, `windows::present_mode`), or off Wayland, where nothing
263/// withholds a window's redraw.
264#[cfg(all(feature = "eframe", not(target_arch = "wasm32")))]
265pub fn paint_safe(mode: eframe::wgpu::PresentMode) -> bool {
266    use eframe::wgpu::PresentMode;
267    let wayland = std::env::var_os("WAYLAND_DISPLAY").is_some_and(|v| !v.is_empty());
268    !wayland
269        || !matches!(
270            mode,
271            PresentMode::AutoVsync | PresentMode::Fifo | PresentMode::FifoRelaxed
272        )
273}
274
275#[cfg(test)]
276mod tests {
277    use super::*;
278
279    const MAIN: u8 = 0;
280    const PANEL: u8 = 1;
281
282    fn wake() -> (MainWake<u8>, Instant) {
283        let mut w = MainWake::new();
284        w.set_main(MAIN);
285        (w, Instant::now())
286    }
287
288    #[test]
289    fn nothing_owed_nothing_painted() {
290        let (mut w, t) = wake();
291        assert_eq!(w.next(), None);
292        assert_eq!(w.due(t + GRACE * 10), None);
293    }
294
295    #[test]
296    fn a_repaint_the_system_answers_is_not_painted_again() {
297        let (mut w, t) = wake();
298        w.asked(t);
299        // The system's redraw came: a pass of the main window.
300        w.main_pass();
301        assert!(!w.owed());
302        assert_eq!(w.due(t + GRACE * 2), None);
303    }
304
305    #[test]
306    fn a_repaint_the_system_withholds_is_painted_after_the_grace() {
307        let (mut w, t) = wake();
308        w.asked(t);
309        assert_eq!(w.due(t + GRACE / 2), None, "not before the grace");
310        assert_eq!(w.next(), Some(t + GRACE));
311        assert_eq!(w.due(t + GRACE), Some(MAIN));
312        // Painted: nothing owed until asked again.
313        assert_eq!(w.due(t + GRACE * 3), None);
314    }
315
316    #[test]
317    fn a_pass_begun_before_the_request_does_not_pay_it() {
318        let (mut w, t) = wake();
319        w.main_pass();
320        w.asked(t);
321        assert!(w.owed());
322        w.main_pass();
323        assert!(!w.owed());
324    }
325
326    #[test]
327    fn a_detached_panels_redraw_owes_the_main_window_a_frame() {
328        let (mut w, t) = wake();
329        // A deferred window painting itself owes nothing.
330        w.redrawn(PANEL, true, t);
331        assert!(!w.owed());
332        // An immediate one is drawn by the main window's pass.
333        w.redrawn(PANEL, false, t);
334        assert_eq!(w.due(t + GRACE), Some(MAIN));
335        // The main window's own redraw owes nothing more.
336        w.redrawn(MAIN, false, t);
337        assert!(!w.owed());
338    }
339
340    #[test]
341    fn a_later_request_keeps_the_first_time_owed() {
342        let (mut w, t) = wake();
343        w.asked(t);
344        w.asked(t + GRACE / 2);
345        assert_eq!(w.next(), Some(t + GRACE));
346        // A request for later moves nothing earlier.
347        let (mut w, t) = wake();
348        w.asked(t + GRACE);
349        w.asked(t);
350        assert_eq!(w.next(), Some(t + GRACE));
351    }
352
353    #[test]
354    fn disabled_or_without_a_main_window_it_never_paints() {
355        let (mut w, t) = wake();
356        w.set_enabled(false);
357        w.asked(t);
358        assert_eq!(w.due(t + GRACE * 2), None);
359        let mut w: MainWake<u8> = MainWake::new();
360        w.asked(t);
361        assert_eq!(w.due(t + GRACE * 2), None);
362    }
363}