Skip to main content

mitsuami_core/
task.rs

1//! Async on the UI thread: a small executor driven by [`Ui::tick`], timers
2//! on a swappable clock, and a bridge for work done on other threads.
3//!
4//! - [`spawn_local`] runs a future on the UI thread. It is owned by the
5//!   current reactive scope and cancelled when that scope is disposed.
6//!   Stores' actions use [`Store::spawn`](crate::Store::spawn), which runs
7//!   it in the store's scope.
8//! - [`spawn_blocking`] runs a closure on a background thread and resolves
9//!   (on the UI thread) with its result.
10//! - [`sleep`] waits on the `Ui`'s clock: real time in apps, a manual clock in
11//!   tests.
12//!
13//! [`Ui::tick`]: crate::Ui::tick
14
15use std::cell::{Cell, RefCell};
16use std::collections::{BTreeMap, HashSet, VecDeque};
17use std::future::Future;
18use std::pin::Pin;
19use std::rc::Rc;
20use std::sync::{Arc, Mutex};
21use std::task::{Context, Poll, Wake, Waker};
22use std::thread::ThreadId;
23use std::time::{Duration, Instant};
24
25use mitsuami_reactive::Owner;
26
27use crate::ui::Ui;
28
29type LocalFuture = Pin<Box<dyn Future<Output = ()>>>;
30
31/// A task and the reactive scope it runs in.
32struct Task {
33    future: LocalFuture,
34    owner: Option<Owner>,
35}
36
37thread_local! {
38    /// The Ui that is running code right now (polling tasks, dispatching
39    /// events), for code with no reactive scope to find it in.
40    static CURRENT: RefCell<Option<crate::ui::WeakUi>> = const { RefCell::new(None) };
41}
42
43/// Runs `f` with `ui` as the current Ui.
44pub(crate) fn with_current<R>(ui: &Ui, f: impl FnOnce() -> R) -> R {
45    /// Puts the previous Ui back even if `f` panics, so a caught panic in a
46    /// handler doesn't leave this one current.
47    struct Restore(Option<crate::ui::WeakUi>);
48    impl Drop for Restore {
49        fn drop(&mut self) {
50            let previous = self.0.take();
51            let _ = CURRENT.try_with(|c| *c.borrow_mut() = previous);
52        }
53    }
54    let _restore = Restore(CURRENT.with(|c| c.replace(Some(ui.downgrade()))));
55    f()
56}
57
58/// Time as the UI sees it. Apps use real time; tests use a manual clock.
59pub trait Clock {
60    /// Time elapsed since the clock started.
61    fn now(&self) -> Duration;
62}
63
64/// Real, monotonic time.
65pub struct SystemClock(Instant);
66
67impl Default for SystemClock {
68    fn default() -> SystemClock {
69        SystemClock(Instant::now())
70    }
71}
72
73impl Clock for SystemClock {
74    fn now(&self) -> Duration {
75        self.0.elapsed()
76    }
77}
78
79/// A clock that only moves when told to. Share it with [`Rc`] to advance it.
80#[derive(Default)]
81pub struct ManualClock(Cell<Duration>);
82
83impl ManualClock {
84    pub fn advance(&self, by: Duration) {
85        self.0.set(self.0.get() + by);
86    }
87}
88
89impl Clock for ManualClock {
90    fn now(&self) -> Duration {
91        self.0.get()
92    }
93}
94
95impl Clock for Rc<ManualClock> {
96    fn now(&self) -> Duration {
97        self.0.get()
98    }
99}
100
101/// Tasks to poll, in the order they were woken. A task woken again while
102/// it waits keeps its place: it's polled once.
103#[derive(Default)]
104struct Queue {
105    order: VecDeque<u64>,
106    queued: HashSet<u64>,
107}
108
109impl Queue {
110    fn push(&mut self, id: u64) {
111        if self.queued.insert(id) {
112            self.order.push_back(id);
113        }
114    }
115
116    fn pop(&mut self) -> Option<u64> {
117        let id = self.order.pop_front()?;
118        self.queued.remove(&id);
119        Some(id)
120    }
121}
122
123/// Where wakers put ready tasks. Shared with other threads.
124struct ReadyQueue {
125    /// Woken on the UI thread: by events, other tasks, timers, spawns.
126    ready: Mutex<Queue>,
127    /// Woken on another thread. A tick takes these in once, at its start,
128    /// so a task another thread wakes again while it runs (a frame
129    /// published during a draw that waits for vsync) waits for the run
130    /// loop's next turn, after the platform's input, instead of running
131    /// back to back and holding every event until it pauses.
132    remote: Mutex<Queue>,
133    ui_thread: ThreadId,
134    /// Asks the UI thread's run loop to turn (thread-safe).
135    wake_ui: Mutex<Option<Arc<dyn Fn() + Send + Sync>>>,
136}
137
138struct TaskWaker {
139    id: u64,
140    queue: Arc<ReadyQueue>,
141}
142
143impl Wake for TaskWaker {
144    fn wake(self: Arc<Self>) {
145        self.wake_by_ref();
146    }
147
148    fn wake_by_ref(self: &Arc<Self>) {
149        let queue =
150            if std::thread::current().id() == self.queue.ui_thread { &self.queue.ready } else { &self.queue.remote };
151        queue.lock().unwrap().push(self.id);
152        let wake_ui = self.queue.wake_ui.lock().unwrap().clone();
153        if let Some(wake_ui) = wake_ui {
154            wake_ui();
155        }
156    }
157}
158
159/// The executor owned by a [`Ui`].
160pub(crate) struct Executor {
161    tasks: RefCell<BTreeMap<u64, Task>>,
162    next_task: Cell<u64>,
163    queue: Arc<ReadyQueue>,
164    clock: RefCell<Rc<dyn Clock>>,
165    /// Deadline → wakers of the futures sleeping until then.
166    timers: RefCell<BTreeMap<(Duration, u64), Waker>>,
167    next_timer: Cell<u64>,
168}
169
170impl Default for Executor {
171    fn default() -> Executor {
172        Executor {
173            tasks: RefCell::default(),
174            next_task: Cell::new(0),
175            queue: Arc::new(ReadyQueue {
176                ready: Mutex::default(),
177                remote: Mutex::default(),
178                ui_thread: std::thread::current().id(),
179                wake_ui: Mutex::default(),
180            }),
181            clock: RefCell::new(Rc::new(SystemClock::default())),
182            timers: RefCell::default(),
183            next_timer: Cell::new(0),
184        }
185    }
186}
187
188impl Executor {
189    /// Every poll of the task runs inside `owner`, the scope it was spawned
190    /// from: `inject`, `sleep` and nested `spawn_local` work as in the
191    /// component, and what the task creates belongs to it.
192    pub(crate) fn spawn(&self, future: LocalFuture, owner: Option<Owner>) -> u64 {
193        let id = self.next_task.get();
194        self.next_task.set(id + 1);
195        self.tasks.borrow_mut().insert(id, Task { future, owner });
196        self.queue.ready.lock().unwrap().push(id);
197        id
198    }
199
200    pub(crate) fn cancel(&self, id: u64) {
201        // Dropped outside the borrow: a future's drop may touch the executor.
202        let task = self.tasks.borrow_mut().remove(&id);
203        drop(task);
204    }
205
206    pub(crate) fn set_clock(&self, clock: Rc<dyn Clock>) {
207        *self.clock.borrow_mut() = clock;
208    }
209
210    pub(crate) fn now(&self) -> Duration {
211        self.clock.borrow().now()
212    }
213
214    pub(crate) fn set_wake_ui(&self, wake: Arc<dyn Fn() + Send + Sync>) {
215        *self.queue.wake_ui.lock().unwrap() = Some(wake);
216    }
217
218    fn add_timer(&self, deadline: Duration, waker: Waker) -> u64 {
219        let id = self.next_timer.get();
220        self.next_timer.set(id + 1);
221        self.timers.borrow_mut().insert((deadline, id), waker);
222        id
223    }
224
225    fn remove_timer(&self, deadline: Duration, id: u64) {
226        self.timers.borrow_mut().remove(&(deadline, id));
227    }
228
229    /// When the earliest timer fires, if any.
230    pub(crate) fn next_deadline(&self) -> Option<Duration> {
231        self.timers.borrow().keys().next().map(|(deadline, _)| *deadline)
232    }
233
234    /// Fires due timers and polls the tasks ready then; with `remote`,
235    /// the tasks other threads woke first. Returns whether any task ran.
236    pub(crate) fn run_ready(&self, ui: &Ui, remote: bool) -> bool {
237        if remote {
238            let woken = std::mem::take(&mut *self.queue.remote.lock().unwrap());
239            let mut ready = self.queue.ready.lock().unwrap();
240            for id in woken.order {
241                ready.push(id);
242            }
243        }
244        with_current(ui, || self.poll_ready())
245    }
246
247    fn poll_ready(&self) -> bool {
248        let now = self.now();
249        let due: Vec<Waker> = {
250            let mut timers = self.timers.borrow_mut();
251            let later = timers.split_off(&(now, u64::MAX));
252            std::mem::replace(&mut *timers, later).into_values().collect()
253        };
254        for waker in due {
255            waker.wake();
256        }
257        let mut ran = false;
258        // Only the tasks ready now: one that wakes itself (a `yield_now`
259        // loop) runs again on the tick's next turn, not forever in this one.
260        let ready = self.queue.ready.lock().unwrap().order.len();
261        for _ in 0..ready {
262            let Some(id) = self.queue.ready.lock().unwrap().pop() else { break };
263            // Take the task out while polling: it may spawn or cancel tasks.
264            let Some(mut task) = self.tasks.borrow_mut().remove(&id) else { continue };
265            ran = true;
266            let waker = Waker::from(Arc::new(TaskWaker { id, queue: self.queue.clone() }));
267            let mut cx = Context::from_waker(&waker);
268            let pending = match task.owner {
269                Some(owner) if owner.is_alive() => owner.with(|| task.future.as_mut().poll(&mut cx)),
270                _ => task.future.as_mut().poll(&mut cx),
271            }
272            .is_pending();
273            if pending {
274                self.tasks.borrow_mut().insert(id, task);
275            }
276        }
277        ran
278    }
279
280    pub(crate) fn has_ready(&self) -> bool {
281        !self.queue.ready.lock().unwrap().order.is_empty()
282    }
283
284    pub(crate) fn task_count(&self) -> usize {
285        self.tasks.borrow().len()
286    }
287}
288
289/// Handle to a task started with [`spawn_local`].
290#[derive(Clone)]
291pub struct TaskHandle {
292    id: u64,
293    ui: crate::ui::WeakUi,
294}
295
296impl TaskHandle {
297    pub(crate) fn new(id: u64, ui: crate::ui::WeakUi) -> TaskHandle {
298        TaskHandle { id, ui }
299    }
300
301    /// Stops the task: its future is dropped and never polled again.
302    pub fn cancel(&self) {
303        if let Some(ui) = self.ui.upgrade() {
304            ui.executor().cancel(self.id);
305        }
306    }
307}
308
309pub(crate) fn current_ui() -> Ui {
310    CURRENT.with(|c| c.borrow().as_ref().and_then(|ui| ui.upgrade())).or_else(mitsuami_reactive::inject::<Ui>).expect(
311        "mitsuami: no Ui in scope. spawn_local/sleep must run inside a mounted view or a task \
312             (or use Ui::spawn_local / Ui::sleep directly)",
313    )
314}
315
316/// Runs `future` on the UI thread. It is cancelled when the current reactive
317/// scope (e.g. the component that started it) is disposed. A store's action
318/// is called in its caller's scope: it spawns with
319/// [`Store::spawn`](crate::Store::spawn) instead.
320///
321/// # Panics
322/// Outside a `Ui`: call it from a mounted view or a task, or use
323/// [`Ui::spawn_local`].
324pub fn spawn_local(future: impl Future<Output = ()> + 'static) -> TaskHandle {
325    let owner = Owner::current();
326    // The cancel waits in a scope of its own, let go of when the task ends:
327    // in the scope itself, a long-lived one (a store's) would keep one for
328    // every task it ever ran.
329    let guard = owner.map(|owner| owner.child());
330    let future = async move {
331        future.await;
332        if let Some(guard) = guard {
333            guard.dispose();
334        }
335    };
336    let handle = current_ui().spawn_in(future, owner);
337    if let Some(guard) = guard {
338        let cancel = handle.clone();
339        guard.with(|| mitsuami_reactive::on_cleanup(move || cancel.cancel()));
340    }
341    handle
342}
343
344/// Runs `work` on a background thread; the returned future resolves on the
345/// UI thread with its result.
346pub fn spawn_blocking<T: Send + 'static>(work: impl FnOnce() -> T + Send + 'static) -> impl Future<Output = T> {
347    struct Shared<T> {
348        result: Option<T>,
349        waker: Option<Waker>,
350    }
351    let shared = Arc::new(Mutex::new(Shared { result: None, waker: None }));
352    let worker = shared.clone();
353    std::thread::spawn(move || {
354        let result = work();
355        let waker = {
356            let mut shared = worker.lock().unwrap();
357            shared.result = Some(result);
358            shared.waker.take()
359        };
360        if let Some(waker) = waker {
361            waker.wake();
362        }
363    });
364    std::future::poll_fn(move |cx| {
365        let mut shared = shared.lock().unwrap();
366        match shared.result.take() {
367            Some(result) => Poll::Ready(result),
368            None => {
369                shared.waker = Some(cx.waker().clone());
370                Poll::Pending
371            }
372        }
373    })
374}
375
376/// Waits `duration` on the current `Ui`'s clock.
377///
378/// # Panics
379/// Outside a `Ui`: call it from a mounted view or a task, or use
380/// [`Ui::sleep`].
381pub fn sleep(duration: Duration) -> Sleep {
382    current_ui().sleep(duration)
383}
384
385/// Future returned by [`sleep`].
386pub struct Sleep {
387    ui: Ui,
388    deadline: Duration,
389    timer: Option<u64>,
390}
391
392impl Sleep {
393    pub(crate) fn new(ui: Ui, duration: Duration) -> Sleep {
394        // Saturating: `Duration::MAX`, sleeping for good, would overflow.
395        let deadline = ui.executor().now().saturating_add(duration);
396        Sleep { ui, deadline, timer: None }
397    }
398}
399
400impl Future for Sleep {
401    type Output = ();
402
403    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
404        let this = &mut *self;
405        let executor = this.ui.executor();
406        if let Some(id) = this.timer.take() {
407            executor.remove_timer(this.deadline, id);
408        }
409        if executor.now() >= this.deadline {
410            return Poll::Ready(());
411        }
412        this.timer = Some(executor.add_timer(this.deadline, cx.waker().clone()));
413        Poll::Pending
414    }
415}
416
417impl Drop for Sleep {
418    fn drop(&mut self) {
419        if let Some(id) = self.timer.take() {
420            self.ui.executor().remove_timer(self.deadline, id);
421        }
422    }
423}