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//! - [`spawn_blocking`] runs a closure on a background thread and resolves
7//!   (on the UI thread) with its result.
8//! - [`sleep`] waits on the `Ui`'s clock: real time in apps, a manual clock in
9//!   tests.
10//!
11//! [`Ui::tick`]: crate::Ui::tick
12
13use std::cell::{Cell, RefCell};
14use std::collections::{BTreeMap, VecDeque};
15use std::future::Future;
16use std::pin::Pin;
17use std::rc::Rc;
18use std::sync::{Arc, Mutex};
19use std::task::{Context, Poll, Wake, Waker};
20use std::time::{Duration, Instant};
21
22use mitsuami_reactive::Owner;
23
24use crate::ui::Ui;
25
26type LocalFuture = Pin<Box<dyn Future<Output = ()>>>;
27
28/// A task and the reactive scope it runs in.
29struct Task {
30    future: LocalFuture,
31    owner: Option<Owner>,
32}
33
34thread_local! {
35    /// The Ui that is running code right now (polling tasks, dispatching
36    /// events), for code with no reactive scope to find it in.
37    static CURRENT: RefCell<Option<crate::ui::WeakUi>> = const { RefCell::new(None) };
38}
39
40/// Runs `f` with `ui` as the current Ui.
41pub(crate) fn with_current<R>(ui: &Ui, f: impl FnOnce() -> R) -> R {
42    let previous = CURRENT.with(|c| c.replace(Some(ui.downgrade())));
43    let result = f();
44    CURRENT.with(|c| *c.borrow_mut() = previous);
45    result
46}
47
48/// Wraps `f` to run inside the reactive scope that is current now, so code
49/// a component triggers later (event handlers, tasks) sees the same context.
50pub(crate) fn in_current_scope<A>(f: impl Fn(A) + 'static) -> impl Fn(A) + 'static {
51    let owner = Owner::current();
52    move |arg| match owner {
53        Some(owner) if owner.is_alive() => owner.with(|| f(arg)),
54        _ => f(arg),
55    }
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/// Where wakers put ready tasks. Shared with other threads.
102#[derive(Default)]
103struct ReadyQueue {
104    ready: Mutex<VecDeque<u64>>,
105    /// Asks the UI thread's run loop to turn (thread-safe).
106    wake_ui: Mutex<Option<Arc<dyn Fn() + Send + Sync>>>,
107}
108
109struct TaskWaker {
110    id: u64,
111    queue: Arc<ReadyQueue>,
112}
113
114impl Wake for TaskWaker {
115    fn wake(self: Arc<Self>) {
116        self.wake_by_ref();
117    }
118
119    fn wake_by_ref(self: &Arc<Self>) {
120        self.queue.ready.lock().unwrap().push_back(self.id);
121        let wake_ui = self.queue.wake_ui.lock().unwrap().clone();
122        if let Some(wake_ui) = wake_ui {
123            wake_ui();
124        }
125    }
126}
127
128/// The executor owned by a [`Ui`].
129pub(crate) struct Executor {
130    tasks: RefCell<BTreeMap<u64, Task>>,
131    next_task: Cell<u64>,
132    queue: Arc<ReadyQueue>,
133    clock: RefCell<Rc<dyn Clock>>,
134    /// Deadline → wakers of the futures sleeping until then.
135    timers: RefCell<BTreeMap<(Duration, u64), Waker>>,
136    next_timer: Cell<u64>,
137}
138
139impl Default for Executor {
140    fn default() -> Executor {
141        Executor {
142            tasks: RefCell::default(),
143            next_task: Cell::new(0),
144            queue: Arc::default(),
145            clock: RefCell::new(Rc::new(SystemClock::default())),
146            timers: RefCell::default(),
147            next_timer: Cell::new(0),
148        }
149    }
150}
151
152impl Executor {
153    /// Every poll of the task runs inside `owner`, the scope it was spawned
154    /// from: `inject`, `sleep` and nested `spawn_local` work as in the
155    /// component, and what the task creates belongs to it.
156    pub(crate) fn spawn(&self, future: LocalFuture, owner: Option<Owner>) -> u64 {
157        let id = self.next_task.get();
158        self.next_task.set(id + 1);
159        self.tasks.borrow_mut().insert(id, Task { future, owner });
160        self.queue.ready.lock().unwrap().push_back(id);
161        id
162    }
163
164    pub(crate) fn cancel(&self, id: u64) {
165        // Dropped outside the borrow: a future's drop may touch the executor.
166        let task = self.tasks.borrow_mut().remove(&id);
167        drop(task);
168    }
169
170    pub(crate) fn set_clock(&self, clock: Rc<dyn Clock>) {
171        *self.clock.borrow_mut() = clock;
172    }
173
174    pub(crate) fn now(&self) -> Duration {
175        self.clock.borrow().now()
176    }
177
178    pub(crate) fn set_wake_ui(&self, wake: Arc<dyn Fn() + Send + Sync>) {
179        *self.queue.wake_ui.lock().unwrap() = Some(wake);
180    }
181
182    fn add_timer(&self, deadline: Duration, waker: Waker) -> u64 {
183        let id = self.next_timer.get();
184        self.next_timer.set(id + 1);
185        self.timers.borrow_mut().insert((deadline, id), waker);
186        id
187    }
188
189    fn remove_timer(&self, deadline: Duration, id: u64) {
190        self.timers.borrow_mut().remove(&(deadline, id));
191    }
192
193    /// When the earliest timer fires, if any.
194    pub(crate) fn next_deadline(&self) -> Option<Duration> {
195        self.timers.borrow().keys().next().map(|(deadline, _)| *deadline)
196    }
197
198    /// Fires due timers and polls ready tasks until nothing is ready.
199    /// Returns whether any task ran.
200    pub(crate) fn run_ready(&self, ui: &Ui) -> bool {
201        with_current(ui, || self.poll_ready())
202    }
203
204    fn poll_ready(&self) -> bool {
205        let now = self.now();
206        let due: Vec<Waker> = {
207            let mut timers = self.timers.borrow_mut();
208            let later = timers.split_off(&(now, u64::MAX));
209            std::mem::replace(&mut *timers, later).into_values().collect()
210        };
211        for waker in due {
212            waker.wake();
213        }
214        let mut ran = false;
215        loop {
216            let Some(id) = self.queue.ready.lock().unwrap().pop_front() else { break };
217            // Take the task out while polling: it may spawn or cancel tasks.
218            let Some(mut task) = self.tasks.borrow_mut().remove(&id) else { continue };
219            ran = true;
220            let waker = Waker::from(Arc::new(TaskWaker { id, queue: self.queue.clone() }));
221            let mut cx = Context::from_waker(&waker);
222            let pending = match task.owner {
223                Some(owner) if owner.is_alive() => owner.with(|| task.future.as_mut().poll(&mut cx)),
224                _ => task.future.as_mut().poll(&mut cx),
225            }
226            .is_pending();
227            if pending {
228                self.tasks.borrow_mut().insert(id, task);
229            }
230        }
231        ran
232    }
233
234    pub(crate) fn has_ready(&self) -> bool {
235        !self.queue.ready.lock().unwrap().is_empty()
236    }
237
238    pub(crate) fn task_count(&self) -> usize {
239        self.tasks.borrow().len()
240    }
241}
242
243/// Handle to a task started with [`spawn_local`].
244#[derive(Clone)]
245pub struct TaskHandle {
246    id: u64,
247    ui: crate::ui::WeakUi,
248}
249
250impl TaskHandle {
251    pub(crate) fn new(id: u64, ui: crate::ui::WeakUi) -> TaskHandle {
252        TaskHandle { id, ui }
253    }
254
255    /// Stops the task: its future is dropped and never polled again.
256    pub fn cancel(&self) {
257        if let Some(ui) = self.ui.upgrade() {
258            ui.executor().cancel(self.id);
259        }
260    }
261}
262
263pub(crate) fn current_ui() -> Ui {
264    CURRENT.with(|c| c.borrow().as_ref().and_then(|ui| ui.upgrade())).or_else(mitsuami_reactive::inject::<Ui>).expect(
265        "mitsuami: no Ui in scope. spawn_local/sleep must run inside a mounted view or a task \
266             (or use Ui::spawn_local / Ui::sleep directly)",
267    )
268}
269
270/// Runs `future` on the UI thread. It is cancelled when the current reactive
271/// scope (e.g. the component that started it) is disposed.
272pub fn spawn_local(future: impl Future<Output = ()> + 'static) -> TaskHandle {
273    let handle = current_ui().spawn_in(future, Owner::current());
274    let cancel = handle.clone();
275    mitsuami_reactive::on_cleanup(move || cancel.cancel());
276    handle
277}
278
279/// Runs `work` on a background thread; the returned future resolves on the
280/// UI thread with its result.
281pub fn spawn_blocking<T: Send + 'static>(work: impl FnOnce() -> T + Send + 'static) -> impl Future<Output = T> {
282    struct Shared<T> {
283        result: Option<T>,
284        waker: Option<Waker>,
285    }
286    let shared = Arc::new(Mutex::new(Shared { result: None, waker: None }));
287    let worker = shared.clone();
288    std::thread::spawn(move || {
289        let result = work();
290        let waker = {
291            let mut shared = worker.lock().unwrap();
292            shared.result = Some(result);
293            shared.waker.take()
294        };
295        if let Some(waker) = waker {
296            waker.wake();
297        }
298    });
299    std::future::poll_fn(move |cx| {
300        let mut shared = shared.lock().unwrap();
301        match shared.result.take() {
302            Some(result) => Poll::Ready(result),
303            None => {
304                shared.waker = Some(cx.waker().clone());
305                Poll::Pending
306            }
307        }
308    })
309}
310
311/// Waits `duration` on the current `Ui`'s clock.
312pub fn sleep(duration: Duration) -> Sleep {
313    current_ui().sleep(duration)
314}
315
316/// Future returned by [`sleep`].
317pub struct Sleep {
318    ui: Ui,
319    deadline: Duration,
320    timer: Option<u64>,
321}
322
323impl Sleep {
324    pub(crate) fn new(ui: Ui, duration: Duration) -> Sleep {
325        let deadline = ui.executor().now() + duration;
326        Sleep { ui, deadline, timer: None }
327    }
328}
329
330impl Future for Sleep {
331    type Output = ();
332
333    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
334        let this = &mut *self;
335        let executor = this.ui.executor();
336        if let Some(id) = this.timer.take() {
337            executor.remove_timer(this.deadline, id);
338        }
339        if executor.now() >= this.deadline {
340            return Poll::Ready(());
341        }
342        this.timer = Some(executor.add_timer(this.deadline, cx.waker().clone()));
343        Poll::Pending
344    }
345}
346
347impl Drop for Sleep {
348    fn drop(&mut self) {
349        if let Some(id) = self.timer.take() {
350            self.ui.executor().remove_timer(self.deadline, id);
351        }
352    }
353}