mitsuami-core 2.0.0

Node tree, layout, styles, units, a11y model and backend contract for mitsuami
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
//! Async on the UI thread: a small executor driven by [`Ui::tick`], timers
//! on a swappable clock, and a bridge for work done on other threads.
//!
//! - [`spawn_local`] runs a future on the UI thread. It is owned by the
//!   current reactive scope and cancelled when that scope is disposed.
//!   Stores' actions use [`Store::spawn`](crate::Store::spawn), which runs
//!   it in the store's scope.
//! - [`spawn_blocking`] runs a closure on a background thread and resolves
//!   (on the UI thread) with its result.
//! - [`sleep`] waits on the `Ui`'s clock: real time in apps, a manual clock in
//!   tests.
//!
//! [`Ui::tick`]: crate::Ui::tick

use std::cell::{Cell, RefCell};
use std::collections::{BTreeMap, HashSet, VecDeque};
use std::future::Future;
use std::pin::Pin;
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll, Wake, Waker};
use std::thread::ThreadId;
use std::time::{Duration, Instant};

use mitsuami_reactive::Owner;

use crate::ui::Ui;

type LocalFuture = Pin<Box<dyn Future<Output = ()>>>;

/// A task and the reactive scope it runs in.
struct Task {
    future: LocalFuture,
    owner: Option<Owner>,
}

thread_local! {
    /// The Ui that is running code right now (polling tasks, dispatching
    /// events), for code with no reactive scope to find it in.
    static CURRENT: RefCell<Option<crate::ui::WeakUi>> = const { RefCell::new(None) };
}

/// Runs `f` with `ui` as the current Ui.
pub(crate) fn with_current<R>(ui: &Ui, f: impl FnOnce() -> R) -> R {
    /// Puts the previous Ui back even if `f` panics, so a caught panic in a
    /// handler doesn't leave this one current.
    struct Restore(Option<crate::ui::WeakUi>);
    impl Drop for Restore {
        fn drop(&mut self) {
            let previous = self.0.take();
            let _ = CURRENT.try_with(|c| *c.borrow_mut() = previous);
        }
    }
    let _restore = Restore(CURRENT.with(|c| c.replace(Some(ui.downgrade()))));
    f()
}

/// Time as the UI sees it. Apps use real time; tests use a manual clock.
pub trait Clock {
    /// Time elapsed since the clock started.
    fn now(&self) -> Duration;
}

/// Real, monotonic time.
pub struct SystemClock(Instant);

impl Default for SystemClock {
    fn default() -> SystemClock {
        SystemClock(Instant::now())
    }
}

impl Clock for SystemClock {
    fn now(&self) -> Duration {
        self.0.elapsed()
    }
}

/// A clock that only moves when told to. Share it with [`Rc`] to advance it.
#[derive(Default)]
pub struct ManualClock(Cell<Duration>);

impl ManualClock {
    pub fn advance(&self, by: Duration) {
        self.0.set(self.0.get() + by);
    }
}

impl Clock for ManualClock {
    fn now(&self) -> Duration {
        self.0.get()
    }
}

impl Clock for Rc<ManualClock> {
    fn now(&self) -> Duration {
        self.0.get()
    }
}

/// Tasks to poll, in the order they were woken. A task woken again while
/// it waits keeps its place: it's polled once.
#[derive(Default)]
struct Queue {
    order: VecDeque<u64>,
    queued: HashSet<u64>,
}

impl Queue {
    fn push(&mut self, id: u64) {
        if self.queued.insert(id) {
            self.order.push_back(id);
        }
    }

    fn pop(&mut self) -> Option<u64> {
        let id = self.order.pop_front()?;
        self.queued.remove(&id);
        Some(id)
    }
}

/// Where wakers put ready tasks. Shared with other threads.
struct ReadyQueue {
    /// Woken on the UI thread: by events, other tasks, timers, spawns.
    ready: Mutex<Queue>,
    /// Woken on another thread. A tick takes these in once, at its start,
    /// so a task another thread wakes again while it runs (a frame
    /// published during a draw that waits for vsync) waits for the run
    /// loop's next turn, after the platform's input, instead of running
    /// back to back and holding every event until it pauses.
    remote: Mutex<Queue>,
    ui_thread: ThreadId,
    /// Asks the UI thread's run loop to turn (thread-safe).
    wake_ui: Mutex<Option<Arc<dyn Fn() + Send + Sync>>>,
}

struct TaskWaker {
    id: u64,
    queue: Arc<ReadyQueue>,
}

impl Wake for TaskWaker {
    fn wake(self: Arc<Self>) {
        self.wake_by_ref();
    }

    fn wake_by_ref(self: &Arc<Self>) {
        let queue =
            if std::thread::current().id() == self.queue.ui_thread { &self.queue.ready } else { &self.queue.remote };
        queue.lock().unwrap().push(self.id);
        let wake_ui = self.queue.wake_ui.lock().unwrap().clone();
        if let Some(wake_ui) = wake_ui {
            wake_ui();
        }
    }
}

/// The executor owned by a [`Ui`].
pub(crate) struct Executor {
    tasks: RefCell<BTreeMap<u64, Task>>,
    next_task: Cell<u64>,
    queue: Arc<ReadyQueue>,
    clock: RefCell<Rc<dyn Clock>>,
    /// Deadline → wakers of the futures sleeping until then.
    timers: RefCell<BTreeMap<(Duration, u64), Waker>>,
    next_timer: Cell<u64>,
}

impl Default for Executor {
    fn default() -> Executor {
        Executor {
            tasks: RefCell::default(),
            next_task: Cell::new(0),
            queue: Arc::new(ReadyQueue {
                ready: Mutex::default(),
                remote: Mutex::default(),
                ui_thread: std::thread::current().id(),
                wake_ui: Mutex::default(),
            }),
            clock: RefCell::new(Rc::new(SystemClock::default())),
            timers: RefCell::default(),
            next_timer: Cell::new(0),
        }
    }
}

impl Executor {
    /// Every poll of the task runs inside `owner`, the scope it was spawned
    /// from: `inject`, `sleep` and nested `spawn_local` work as in the
    /// component, and what the task creates belongs to it.
    pub(crate) fn spawn(&self, future: LocalFuture, owner: Option<Owner>) -> u64 {
        let id = self.next_task.get();
        self.next_task.set(id + 1);
        self.tasks.borrow_mut().insert(id, Task { future, owner });
        self.queue.ready.lock().unwrap().push(id);
        id
    }

    pub(crate) fn cancel(&self, id: u64) {
        // Dropped outside the borrow: a future's drop may touch the executor.
        let task = self.tasks.borrow_mut().remove(&id);
        drop(task);
    }

    pub(crate) fn set_clock(&self, clock: Rc<dyn Clock>) {
        *self.clock.borrow_mut() = clock;
    }

    pub(crate) fn now(&self) -> Duration {
        self.clock.borrow().now()
    }

    pub(crate) fn set_wake_ui(&self, wake: Arc<dyn Fn() + Send + Sync>) {
        *self.queue.wake_ui.lock().unwrap() = Some(wake);
    }

    fn add_timer(&self, deadline: Duration, waker: Waker) -> u64 {
        let id = self.next_timer.get();
        self.next_timer.set(id + 1);
        self.timers.borrow_mut().insert((deadline, id), waker);
        id
    }

    fn remove_timer(&self, deadline: Duration, id: u64) {
        self.timers.borrow_mut().remove(&(deadline, id));
    }

    /// When the earliest timer fires, if any.
    pub(crate) fn next_deadline(&self) -> Option<Duration> {
        self.timers.borrow().keys().next().map(|(deadline, _)| *deadline)
    }

    /// Fires due timers and polls the tasks ready then; with `remote`,
    /// the tasks other threads woke first. Returns whether any task ran.
    pub(crate) fn run_ready(&self, ui: &Ui, remote: bool) -> bool {
        if remote {
            let woken = std::mem::take(&mut *self.queue.remote.lock().unwrap());
            let mut ready = self.queue.ready.lock().unwrap();
            for id in woken.order {
                ready.push(id);
            }
        }
        with_current(ui, || self.poll_ready())
    }

    fn poll_ready(&self) -> bool {
        let now = self.now();
        let due: Vec<Waker> = {
            let mut timers = self.timers.borrow_mut();
            let later = timers.split_off(&(now, u64::MAX));
            std::mem::replace(&mut *timers, later).into_values().collect()
        };
        for waker in due {
            waker.wake();
        }
        let mut ran = false;
        // Only the tasks ready now: one that wakes itself (a `yield_now`
        // loop) runs again on the tick's next turn, not forever in this one.
        let ready = self.queue.ready.lock().unwrap().order.len();
        for _ in 0..ready {
            let Some(id) = self.queue.ready.lock().unwrap().pop() else { break };
            // Take the task out while polling: it may spawn or cancel tasks.
            let Some(mut task) = self.tasks.borrow_mut().remove(&id) else { continue };
            ran = true;
            let waker = Waker::from(Arc::new(TaskWaker { id, queue: self.queue.clone() }));
            let mut cx = Context::from_waker(&waker);
            let pending = match task.owner {
                Some(owner) if owner.is_alive() => owner.with(|| task.future.as_mut().poll(&mut cx)),
                _ => task.future.as_mut().poll(&mut cx),
            }
            .is_pending();
            if pending {
                self.tasks.borrow_mut().insert(id, task);
            }
        }
        ran
    }

    pub(crate) fn has_ready(&self) -> bool {
        !self.queue.ready.lock().unwrap().order.is_empty()
    }

    pub(crate) fn task_count(&self) -> usize {
        self.tasks.borrow().len()
    }
}

/// Handle to a task started with [`spawn_local`].
#[derive(Clone)]
pub struct TaskHandle {
    id: u64,
    ui: crate::ui::WeakUi,
}

impl TaskHandle {
    pub(crate) fn new(id: u64, ui: crate::ui::WeakUi) -> TaskHandle {
        TaskHandle { id, ui }
    }

    /// Stops the task: its future is dropped and never polled again.
    pub fn cancel(&self) {
        if let Some(ui) = self.ui.upgrade() {
            ui.executor().cancel(self.id);
        }
    }
}

pub(crate) fn current_ui() -> Ui {
    CURRENT.with(|c| c.borrow().as_ref().and_then(|ui| ui.upgrade())).or_else(mitsuami_reactive::inject::<Ui>).expect(
        "mitsuami: no Ui in scope. spawn_local/sleep must run inside a mounted view or a task \
             (or use Ui::spawn_local / Ui::sleep directly)",
    )
}

/// Runs `future` on the UI thread. It is cancelled when the current reactive
/// scope (e.g. the component that started it) is disposed. A store's action
/// is called in its caller's scope: it spawns with
/// [`Store::spawn`](crate::Store::spawn) instead.
///
/// # Panics
/// Outside a `Ui`: call it from a mounted view or a task, or use
/// [`Ui::spawn_local`].
pub fn spawn_local(future: impl Future<Output = ()> + 'static) -> TaskHandle {
    let owner = Owner::current();
    // The cancel waits in a scope of its own, let go of when the task ends:
    // in the scope itself, a long-lived one (a store's) would keep one for
    // every task it ever ran.
    let guard = owner.map(|owner| owner.child());
    let future = async move {
        future.await;
        if let Some(guard) = guard {
            guard.dispose();
        }
    };
    let handle = current_ui().spawn_in(future, owner);
    if let Some(guard) = guard {
        let cancel = handle.clone();
        guard.with(|| mitsuami_reactive::on_cleanup(move || cancel.cancel()));
    }
    handle
}

/// Runs `work` on a background thread; the returned future resolves on the
/// UI thread with its result.
pub fn spawn_blocking<T: Send + 'static>(work: impl FnOnce() -> T + Send + 'static) -> impl Future<Output = T> {
    struct Shared<T> {
        result: Option<T>,
        waker: Option<Waker>,
    }
    let shared = Arc::new(Mutex::new(Shared { result: None, waker: None }));
    let worker = shared.clone();
    std::thread::spawn(move || {
        let result = work();
        let waker = {
            let mut shared = worker.lock().unwrap();
            shared.result = Some(result);
            shared.waker.take()
        };
        if let Some(waker) = waker {
            waker.wake();
        }
    });
    std::future::poll_fn(move |cx| {
        let mut shared = shared.lock().unwrap();
        match shared.result.take() {
            Some(result) => Poll::Ready(result),
            None => {
                shared.waker = Some(cx.waker().clone());
                Poll::Pending
            }
        }
    })
}

/// Waits `duration` on the current `Ui`'s clock.
///
/// # Panics
/// Outside a `Ui`: call it from a mounted view or a task, or use
/// [`Ui::sleep`].
pub fn sleep(duration: Duration) -> Sleep {
    current_ui().sleep(duration)
}

/// Future returned by [`sleep`].
pub struct Sleep {
    ui: Ui,
    deadline: Duration,
    timer: Option<u64>,
}

impl Sleep {
    pub(crate) fn new(ui: Ui, duration: Duration) -> Sleep {
        // Saturating: `Duration::MAX`, sleeping for good, would overflow.
        let deadline = ui.executor().now().saturating_add(duration);
        Sleep { ui, deadline, timer: None }
    }
}

impl Future for Sleep {
    type Output = ();

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
        let this = &mut *self;
        let executor = this.ui.executor();
        if let Some(id) = this.timer.take() {
            executor.remove_timer(this.deadline, id);
        }
        if executor.now() >= this.deadline {
            return Poll::Ready(());
        }
        this.timer = Some(executor.add_timer(this.deadline, cx.waker().clone()));
        Poll::Pending
    }
}

impl Drop for Sleep {
    fn drop(&mut self) {
        if let Some(id) = self.timer.take() {
            self.ui.executor().remove_timer(self.deadline, id);
        }
    }
}