Skip to main content

egui_pop_core/
latest.rs

1//! A slow load that follows a selection: the latest asked wins.
2//!
3//! <div class="warning">Experimental: may change in any release
4//! (docs/stability.md).</div>
5//!
6//! A panel previewing what is selected elsewhere asks for the current key
7//! each time it draws ([`Latest::want`]). A key that changed starts a load
8//! on a worker thread and the panel goes on drawing; a load asked before
9//! it and not started yet is dropped, one running is told through its
10//! [`Cancel`] and its result is dropped. One load runs at a time, so going
11//! down a list with an arrow key does not start one thread per row.
12//!
13//! Nothing runs behind a hidden panel: only `want` starts a load, and a
14//! hidden panel's `ui()` does not run. A panel shown again asks for what
15//! is selected then, and only that. A load already running when the panel
16//! is closed goes on to its end; the panel keeps its result if the key is
17//! still the one selected when it comes back.
18//!
19//! ```
20//! use egui_pop_core::latest::{Latest, Loaded};
21//!
22//! fn preview(ui: &mut egui::Ui, latest: &mut Latest<String, String>, selected: Option<&String>) {
23//!     let shown = latest.want(ui.ctx(), selected, |key, cancel| {
24//!         // On a worker thread; a long load looks at `cancel` now and then.
25//!         if cancel.cancelled() {
26//!             return String::new();
27//!         }
28//!         format!("the preview of {key}")
29//!     });
30//!     match shown {
31//!         Loaded::Nothing => ui.weak("Nothing selected."),
32//!         Loaded::Loading { .. } => ui.weak("Loading…"),
33//!         Loaded::Ready(text) => ui.label(text.as_str()),
34//!         Loaded::Failed(reason) => ui.label(reason),
35//!     };
36//! }
37//! ```
38//!
39//! On the web there are no threads: the load runs in the frame that asks
40//! for it. The file picker's previews have a worker of their own, tied to
41//! files (`egui-pop-api`'s `files::preview`); this one knows nothing of
42//! what it loads. See `docs/linked-panels.md`.
43
44use std::fmt;
45use std::panic::{AssertUnwindSafe, catch_unwind};
46use std::sync::atomic::{AtomicU64, Ordering};
47use std::sync::{Arc, Mutex};
48
49use egui::ViewportId;
50
51use crate::lock;
52
53/// Whether a load is still wanted: a long one looks now and then, and may
54/// stop. What it returns then is dropped.
55#[derive(Clone, Debug)]
56pub struct Cancel {
57    wanted: Arc<AtomicU64>,
58    mine: u64,
59}
60
61impl Cancel {
62    /// Another key was asked for since this load was.
63    pub fn cancelled(&self) -> bool {
64        self.wanted.load(Ordering::Relaxed) != self.mine
65    }
66}
67
68/// What [`Latest::want`] has to show.
69#[derive(Debug)]
70pub enum Loaded<'a, V> {
71    /// No key is asked for.
72    Nothing,
73    /// The key's load is not done; `previous` is the last value received,
74    /// to show dimmed instead of a blank.
75    Loading { previous: Option<&'a V> },
76    /// The key's value.
77    Ready(&'a V),
78    /// The key's load panicked: the panic's message.
79    Failed(&'a str),
80}
81
82type Job<V> = Box<dyn FnOnce(&Cancel) -> V + Send>;
83
84/// What the frame and the worker share.
85struct Slot<V> {
86    /// The load to run next, with its generation.
87    next: Option<(u64, Job<V>)>,
88    /// A worker is at work.
89    working: bool,
90    /// The newest result, with its generation.
91    done: Option<(u64, Result<V, String>)>,
92    /// The window to wake with a result (a detached panel has its own).
93    viewport: ViewportId,
94}
95
96struct Shared<V> {
97    /// The generation asked for last.
98    wanted: Arc<AtomicU64>,
99    slot: Mutex<Slot<V>>,
100}
101
102/// One slow value following a key; see the [module](self).
103pub struct Latest<K, V> {
104    /// The key asked for last.
105    key: Option<K>,
106    generation: u64,
107    /// The last value received: of `key` when `ready`, else of an earlier
108    /// one.
109    value: Option<V>,
110    ready: bool,
111    failed: Option<String>,
112    shared: Arc<Shared<V>>,
113}
114
115impl<K, V> Default for Latest<K, V> {
116    fn default() -> Self {
117        Self {
118            key: None,
119            generation: 0,
120            value: None,
121            ready: false,
122            failed: None,
123            shared: Arc::new(Shared {
124                wanted: Arc::new(AtomicU64::new(0)),
125                slot: Mutex::new(Slot {
126                    next: None,
127                    working: false,
128                    done: None,
129                    viewport: ViewportId::ROOT,
130                }),
131            }),
132        }
133    }
134}
135
136impl<K: fmt::Debug, V> fmt::Debug for Latest<K, V> {
137    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138        f.debug_struct("Latest")
139            .field("key", &self.key)
140            .field("ready", &self.ready)
141            .field("failed", &self.failed)
142            .finish_non_exhaustive()
143    }
144}
145
146impl<K, V> Drop for Latest<K, V> {
147    /// A load running is told, one waiting never starts.
148    fn drop(&mut self) {
149        self.shared.wanted.fetch_add(1, Ordering::Relaxed);
150        lock(&self.shared.slot).next = None;
151    }
152}
153
154impl<K, V> Latest<K, V>
155where
156    K: Clone + PartialEq + Send + 'static,
157    V: Send + 'static,
158{
159    pub fn new() -> Self {
160        Self::default()
161    }
162
163    /// What to show for `key` (`None`: nothing is selected). Call it each
164    /// time the panel draws: `load` runs only when `key` changed, on the
165    /// worker, and the window is woken when its result is in.
166    pub fn want(
167        &mut self,
168        ctx: &egui::Context,
169        key: Option<&K>,
170        load: impl FnOnce(&K, &Cancel) -> V + Send + 'static,
171    ) -> Loaded<'_, V> {
172        // Before a load can start: its result wakes the window drawing it.
173        let done = {
174            let mut slot = lock(&self.shared.slot);
175            slot.viewport = ctx.viewport_id();
176            slot.done.take()
177        };
178        if let Some((generation, result)) = done
179            && generation == self.generation
180        {
181            match result {
182                Ok(value) => {
183                    self.value = Some(value);
184                    self.ready = true;
185                }
186                Err(reason) => {
187                    self.value = None;
188                    self.failed = Some(reason);
189                }
190            }
191        }
192        if self.key.as_ref() != key {
193            self.ask(ctx, key, load);
194        }
195        if self.key.is_none() {
196            return Loaded::Nothing;
197        }
198        if let Some(reason) = &self.failed {
199            return Loaded::Failed(reason);
200        }
201        match &self.value {
202            Some(value) if self.ready => Loaded::Ready(value),
203            previous => Loaded::Loading {
204                previous: previous.as_ref(),
205            },
206        }
207    }
208
209    /// The key changed: what was asked before is not wanted any more.
210    fn ask(
211        &mut self,
212        ctx: &egui::Context,
213        key: Option<&K>,
214        load: impl FnOnce(&K, &Cancel) -> V + Send + 'static,
215    ) {
216        self.key = key.cloned();
217        self.generation += 1;
218        self.shared.wanted.store(self.generation, Ordering::Relaxed);
219        self.ready = false;
220        self.failed = None;
221        let Some(key) = key.cloned() else {
222            lock(&self.shared.slot).next = None;
223            self.value = None;
224            return;
225        };
226        let job: Job<V> = Box::new(move |cancel: &Cancel| load(&key, cancel));
227        let start = {
228            let mut slot = lock(&self.shared.slot);
229            slot.next = Some((self.generation, job));
230            !std::mem::replace(&mut slot.working, true)
231        };
232        if start {
233            self.start(ctx);
234        }
235    }
236
237    /// Starts the worker: in this frame on the web, or without a thread.
238    fn start(&self, ctx: &egui::Context) {
239        if cfg!(target_arch = "wasm32") {
240            work(&self.shared, ctx);
241            return;
242        }
243        let shared = self.shared.clone();
244        let wake = ctx.clone();
245        let spawned = std::thread::Builder::new()
246            .name("egui-pop-latest".into())
247            .spawn(move || work(&shared, &wake));
248        if let Err(e) = spawned {
249            log::warn!(target: "egui_pop", "latest: no thread for a load: {e}");
250            work(&self.shared, ctx);
251        }
252    }
253}
254
255/// Runs the load waiting, then the one asked meanwhile, until none waits.
256fn work<V>(shared: &Shared<V>, ctx: &egui::Context) {
257    loop {
258        let job = {
259            let mut slot = lock(&shared.slot);
260            let job = slot.next.take();
261            slot.working = job.is_some();
262            job
263        };
264        let Some((generation, load)) = job else {
265            return;
266        };
267        let cancel = Cancel {
268            wanted: shared.wanted.clone(),
269            mine: generation,
270        };
271        if cancel.cancelled() {
272            continue;
273        }
274        let result = catch_unwind(AssertUnwindSafe(|| load(&cancel)))
275            .map_err(|payload| crate::fault::message(&*payload));
276        if cancel.cancelled() {
277            continue;
278        }
279        let viewport = {
280            let mut slot = lock(&shared.slot);
281            slot.done = Some((generation, result));
282            slot.viewport
283        };
284        ctx.request_repaint_of(viewport);
285    }
286}
287
288#[cfg(test)]
289mod tests {
290    use super::*;
291    use std::sync::atomic::AtomicUsize;
292    use std::sync::mpsc;
293    use std::time::{Duration, Instant};
294
295    /// Longer than any load here takes: a test that hangs fails instead.
296    const DEADLINE: Duration = Duration::from_secs(30);
297
298    fn never(_: &u32, _: &Cancel) -> u32 {
299        panic!("this key was asked for already");
300    }
301
302    /// Asks for `key` until its value is in.
303    fn value_of(latest: &mut Latest<u32, u32>, ctx: &egui::Context, key: u32) -> u32 {
304        let start = Instant::now();
305        loop {
306            if let Loaded::Ready(v) = latest.want(ctx, Some(&key), never) {
307                return *v;
308            }
309            assert!(start.elapsed() < DEADLINE, "the load of {key} never came");
310            std::thread::sleep(Duration::from_millis(1));
311        }
312    }
313
314    #[test]
315    fn the_latest_wins_and_what_was_asked_between_never_runs() {
316        let ctx = egui::Context::default();
317        let mut latest = Latest::<u32, u32>::new();
318        let ran = Arc::new(Mutex::new(Vec::new()));
319        let (started, has_started) = mpsc::channel::<()>();
320        let (release, released) = mpsc::channel::<()>();
321        let r = ran.clone();
322        let shown = latest.want(&ctx, Some(&1), move |k, _| {
323            r.lock().unwrap().push(*k);
324            started.send(()).unwrap();
325            released.recv_timeout(DEADLINE).unwrap();
326            *k
327        });
328        assert!(matches!(shown, Loaded::Loading { previous: None }));
329        has_started.recv_timeout(DEADLINE).unwrap();
330        // 1 is running: 2 waits behind it, then 3 takes its place.
331        let r = ran.clone();
332        let _ = latest.want(&ctx, Some(&2), move |k, _| {
333            r.lock().unwrap().push(*k);
334            *k
335        });
336        let r = ran.clone();
337        let _ = latest.want(&ctx, Some(&3), move |k, _| {
338            r.lock().unwrap().push(*k);
339            *k
340        });
341        release.send(()).unwrap();
342        assert_eq!(value_of(&mut latest, &ctx, 3), 3);
343        assert_eq!(*ran.lock().unwrap(), vec![1, 3]);
344    }
345
346    #[test]
347    fn a_running_load_is_told_it_is_not_wanted() {
348        let ctx = egui::Context::default();
349        let mut latest = Latest::<u32, u32>::new();
350        let (started, has_started) = mpsc::channel::<()>();
351        let (told, was_told) = mpsc::channel::<()>();
352        let _ = latest.want(&ctx, Some(&1), move |_, cancel| {
353            started.send(()).unwrap();
354            let start = Instant::now();
355            while !cancel.cancelled() && start.elapsed() < DEADLINE {
356                std::thread::sleep(Duration::from_millis(1));
357            }
358            told.send(()).unwrap();
359            1
360        });
361        has_started.recv_timeout(DEADLINE).unwrap();
362        let _ = latest.want(&ctx, Some(&2), |k, _| *k);
363        was_told.recv_timeout(DEADLINE).unwrap();
364        assert_eq!(value_of(&mut latest, &ctx, 2), 2);
365    }
366
367    #[test]
368    fn a_key_loads_once_and_the_last_value_shows_while_the_next_loads() {
369        let ctx = egui::Context::default();
370        let mut latest = Latest::<u32, u32>::new();
371        let runs = Arc::new(AtomicUsize::new(0));
372        let n = runs.clone();
373        let _ = latest.want(&ctx, Some(&1), move |k, _| {
374            n.fetch_add(1, Ordering::Relaxed);
375            *k * 10
376        });
377        assert_eq!(value_of(&mut latest, &ctx, 1), 10);
378        assert_eq!(runs.load(Ordering::Relaxed), 1);
379        let (release, released) = mpsc::channel::<()>();
380        let shown = latest.want(&ctx, Some(&2), move |k, _| {
381            released.recv_timeout(DEADLINE).unwrap();
382            *k * 10
383        });
384        assert!(matches!(
385            shown,
386            Loaded::Loading {
387                previous: Some(&10)
388            }
389        ));
390        release.send(()).unwrap();
391        assert_eq!(value_of(&mut latest, &ctx, 2), 20);
392    }
393
394    #[test]
395    fn no_key_shows_nothing_and_the_same_key_afterwards_loads_again() {
396        let ctx = egui::Context::default();
397        let mut latest = Latest::<u32, u32>::new();
398        assert!(matches!(latest.want(&ctx, None, never), Loaded::Nothing));
399        let _ = latest.want(&ctx, Some(&1), |k, _| *k);
400        assert_eq!(value_of(&mut latest, &ctx, 1), 1);
401        assert!(matches!(latest.want(&ctx, None, never), Loaded::Nothing));
402        let shown = latest.want(&ctx, Some(&1), |k, _| *k + 1);
403        assert!(matches!(shown, Loaded::Loading { previous: None }));
404        assert_eq!(value_of(&mut latest, &ctx, 1), 2);
405    }
406
407    #[test]
408    fn a_load_that_panics_says_so_and_the_next_key_still_loads() {
409        let ctx = egui::Context::default();
410        let mut latest = Latest::<u32, u32>::new();
411        let _ = latest.want(&ctx, Some(&1), |_, _| panic!("no such photo"));
412        let start = Instant::now();
413        loop {
414            if let Loaded::Failed(reason) = latest.want(&ctx, Some(&1), never) {
415                assert_eq!(reason, "no such photo");
416                break;
417            }
418            assert!(start.elapsed() < DEADLINE, "the panic was never said");
419            std::thread::sleep(Duration::from_millis(1));
420        }
421        let _ = latest.want(&ctx, Some(&2), |k, _| *k);
422        assert_eq!(value_of(&mut latest, &ctx, 2), 2);
423    }
424}