Skip to main content

alpha2_extensions/
progress.rs

1//! Per-frame progress from long provider calls, so a host watchdog can tell slow from stuck.
2//!
3//! The watch is thread-local, so a provider needs no handle to report it.
4
5use std::cell::RefCell;
6
7thread_local! {
8    static WATCH: RefCell<Option<Box<dyn Fn()>>> = const { RefCell::new(None) };
9}
10
11/// Calls `progressed` each time a provider call on this thread gets further, until the watch drops.
12pub fn watch_progress(progressed: impl Fn() + 'static) -> ProgressWatch {
13    let previous = WATCH.with(|watch| watch.replace(Some(Box::new(progressed))));
14    ProgressWatch {
15        previous,
16        thread: std::marker::PhantomData,
17    }
18}
19
20/// Ends a [`watch_progress`] watch, restoring the one before it.
21pub struct ProgressWatch {
22    previous: Option<Box<dyn Fn()>>,
23    /// Makes the watch `!Send`, as it must drop on the thread that set it.
24    thread: std::marker::PhantomData<*const ()>,
25}
26
27impl Drop for ProgressWatch {
28    fn drop(&mut self) {
29        let previous = self.previous.take();
30        WATCH.with(|watch| {
31            watch.replace(previous);
32        });
33    }
34}
35
36#[cfg(feature = "animated-image")]
37pub(crate) fn progressed() {
38    WATCH.with(|watch| {
39        if let Some(progressed) = watch.borrow().as_ref() {
40            progressed();
41        }
42    });
43}