Skip to main content

cranpose_core/
runtime.rs

1use std::{
2    any::Any,
3    cell::{Cell, RefCell},
4    collections::VecDeque,
5    future::Future,
6    pin::Pin,
7    rc::{Rc, Weak},
8    sync::{
9        Arc,
10        atomic::{AtomicBool, AtomicUsize, Ordering},
11        mpsc,
12    },
13    task::{Context, Poll, Waker},
14    thread::ThreadId,
15};
16
17#[cfg(any(feature = "internal", test))]
18use crate::frame_clock::FrameClock;
19use crate::{
20    Applier, Command, FrameCallbackId, Key, NodeError, RecomposeScope, RecomposeScopeInner,
21    ScopeId,
22    collections::map::HashMap,
23    platform::{RuntimeScheduler, SchedulerRef},
24    scope_order::ScopeOrder,
25    state::MutationPolicy,
26    task_site::TaskLabel,
27    thread_state,
28};
29
30mod debug_stats;
31mod registered_runtime;
32mod scope_runtime;
33mod state_arena;
34mod state_owners;
35mod task_slots;
36mod ui_task;
37
38pub use debug_stats::RuntimeDebugStats;
39pub(crate) use registered_runtime::{runtime_handle_by_id, with_state_arena_by_id};
40pub(crate) use scope_runtime::ScopeRuntime;
41pub(crate) use state_arena::{DerivedRefresh, StateArena};
42pub use state_arena::{StateArenaDebugStats, StateId};
43pub(crate) use state_owners::collecting_states;
44use state_owners::hand_to_current_owner;
45use ui_task::UiTask;
46
47#[derive(Clone, Copy, PartialEq, Eq)]
48pub(crate) enum FrameCallbackKind {
49    Transient,
50    Perpetual,
51}
52
53enum UiMessage {
54    Task(Box<dyn FnOnce() + Send + 'static>),
55    Invoke { id: u64, value: Box<dyn Any + Send> },
56}
57
58type UiContinuation = Box<dyn Fn(Box<dyn Any>) -> bool + 'static>;
59type UiContinuationMap = HashMap<u64, UiContinuation>;
60
61/// Identifies a runtime within its thread.
62#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
63pub struct RuntimeId(u32);
64
65impl RuntimeId {
66    fn next() -> Self {
67        thread_state::runtimes(|state| {
68            let id = state.next_runtime_id.get();
69            state.next_runtime_id.set(id.wrapping_add(1));
70            Self(id)
71        })
72    }
73}
74
75struct UiDispatcherInner {
76    scheduler: SchedulerRef,
77    tx: mpsc::Sender<UiMessage>,
78    pending: AtomicUsize,
79}
80
81#[cfg(not(target_arch = "wasm32"))]
82type UiDispatcherRef = Arc<UiDispatcherInner>;
83
84#[cfg(target_arch = "wasm32")]
85type UiDispatcherRef = Rc<UiDispatcherInner>;
86
87impl UiDispatcherInner {
88    fn new(scheduler: SchedulerRef, tx: mpsc::Sender<UiMessage>) -> Self {
89        Self {
90            scheduler,
91            tx,
92            pending: AtomicUsize::new(0),
93        }
94    }
95
96    fn post(&self, task: impl FnOnce() + Send + 'static) {
97        self.pending.fetch_add(1, Ordering::SeqCst);
98        if self.tx.send(UiMessage::Task(Box::new(task))).is_ok() {
99            self.scheduler.schedule_frame();
100        } else {
101            self.pending.fetch_sub(1, Ordering::SeqCst);
102        }
103    }
104
105    fn post_invoke(&self, id: u64, value: Box<dyn Any + Send>) {
106        self.pending.fetch_add(1, Ordering::SeqCst);
107        if self.tx.send(UiMessage::Invoke { id, value }).is_ok() {
108            self.scheduler.schedule_frame();
109        } else {
110            self.pending.fetch_sub(1, Ordering::SeqCst);
111        }
112    }
113
114    fn has_pending(&self) -> bool {
115        self.pending.load(Ordering::SeqCst) > 0
116    }
117}
118
119struct PendingGuard<'a> {
120    counter: &'a AtomicUsize,
121}
122
123impl<'a> PendingGuard<'a> {
124    fn new(counter: &'a AtomicUsize) -> Self {
125        Self { counter }
126    }
127}
128
129impl Drop for PendingGuard<'_> {
130    fn drop(&mut self) {
131        let mut current = self.counter.load(Ordering::SeqCst);
132        loop {
133            if current == 0 {
134                return;
135            }
136            match self.counter.compare_exchange(
137                current,
138                current - 1,
139                Ordering::SeqCst,
140                Ordering::SeqCst,
141            ) {
142                Ok(_) => return,
143                Err(next) => current = next,
144            }
145        }
146    }
147}
148
149/// Posts work from any thread to the UI thread of a runtime.
150#[derive(Clone)]
151pub struct UiDispatcher {
152    inner: UiDispatcherRef,
153}
154
155impl UiDispatcher {
156    fn new(inner: UiDispatcherRef) -> Self {
157        Self { inner }
158    }
159
160    /// Queues `task` to run on the UI thread the next time the runtime drains UI work. May be
161    /// called from any thread.
162    pub fn post(&self, task: impl FnOnce() + Send + 'static) {
163        self.inner.post(task);
164    }
165
166    /// Queues a call of the continuation registered under `id` with `value`, to run on the UI
167    /// thread. May be called from any thread.
168    pub fn post_invoke<T>(&self, id: u64, value: T)
169    where
170        T: Send + 'static,
171    {
172        self.inner.post_invoke(id, Box::new(value));
173    }
174
175    /// Returns `true` if a posted message has not run yet.
176    pub fn has_pending(&self) -> bool {
177        self.inner.has_pending()
178    }
179}
180
181struct RuntimeInner {
182    scheduler: SchedulerRef,
183    needs_frame: RefCell<bool>,
184    node_updates: RefCell<Vec<Command>>,
185    invalid_scope_count: Cell<usize>,
186    scope_queue: RefCell<Vec<Weak<RecomposeScopeInner>>>,
187    /// The storage of the last pass's scope list, for the next pass.
188    spare_scopes: RefCell<Vec<RecomposeScope>>,
189    // Places a pass's scopes in depth order.
190    scope_order: RefCell<ScopeOrder>,
191    frame_callbacks: RefCell<VecDeque<FrameCallbackEntry>>,
192    next_frame_callback_id: Cell<u64>,
193    last_frame_time_nanos: Cell<Option<u64>>,
194    ui_dispatcher: UiDispatcherRef,
195    ui_rx: RefCell<mpsc::Receiver<UiMessage>>,
196    local_tasks: RefCell<VecDeque<UiTask>>,
197    ui_conts: RefCell<UiContinuationMap>,
198    next_cont_id: Cell<u64>,
199    ui_thread_id: ThreadId,
200    tasks: RefCell<task_slots::Slots<TaskEntry>>,
201    task_order: RefCell<Vec<u64>>,
202    /// Set by every task wake after the task's own flag, and cleared by the
203    /// poll that then looks at the tasks: a poll after no wake skips them.
204    task_woken: Arc<AtomicBool>,
205    state_arena: StateArena,
206    external_state_owners: RefCell<HashMap<StateId, Rc<StateHandleLease>>>,
207    live_recompose_scope_count: Cell<usize>,
208    forgotten_movables: RefCell<Vec<Key>>,
209    next_movable_content_id: Cell<u64>,
210    runtime_id: RuntimeId,
211    #[cfg(target_os = "android")]
212    rescued: RefCell<Option<Rc<thread_state::RescuedThreadState>>>,
213}
214
215struct TaskEntry {
216    label: TaskLabel,
217    future: Option<Pin<Box<dyn Future<Output = ()> + 'static>>>,
218    runnable: Arc<AtomicBool>,
219    waker: Waker,
220}
221
222impl RuntimeInner {
223    fn new(scheduler: SchedulerRef) -> Self {
224        let (tx, rx) = mpsc::channel();
225        let dispatcher =
226            UiDispatcherRef::new(UiDispatcherInner::new(SchedulerRef::clone(&scheduler), tx));
227        Self {
228            scheduler,
229            needs_frame: RefCell::new(false),
230            node_updates: RefCell::new(Vec::new()),
231            invalid_scope_count: Cell::new(0),
232            scope_queue: RefCell::new(Vec::new()),
233            spare_scopes: RefCell::new(Vec::new()),
234            scope_order: RefCell::default(),
235            frame_callbacks: RefCell::new(VecDeque::new()),
236            next_frame_callback_id: Cell::new(1),
237            last_frame_time_nanos: Cell::new(None),
238            ui_dispatcher: dispatcher,
239            ui_rx: RefCell::new(rx),
240            local_tasks: RefCell::new(VecDeque::new()),
241            ui_conts: RefCell::new(UiContinuationMap::default()),
242            next_cont_id: Cell::new(1),
243            ui_thread_id: std::thread::current().id(),
244            tasks: RefCell::new(task_slots::Slots::new()),
245            task_order: RefCell::new(Vec::new()),
246            task_woken: Arc::new(AtomicBool::new(false)),
247            state_arena: StateArena::default(),
248            external_state_owners: RefCell::new(HashMap::default()),
249            live_recompose_scope_count: Cell::new(0),
250            forgotten_movables: RefCell::new(Vec::new()),
251            next_movable_content_id: Cell::new(1),
252            runtime_id: RuntimeId::next(),
253            #[cfg(target_os = "android")]
254            rescued: RefCell::new(None),
255        }
256    }
257
258    fn schedule(&self) {
259        *self.needs_frame.borrow_mut() = true;
260        self.scheduler.schedule_frame();
261    }
262
263    fn enqueue_update(&self, command: Command) {
264        self.node_updates.borrow_mut().push(command);
265        self.schedule();
266    }
267
268    fn take_updates(&self) -> Vec<Command> {
269        self.node_updates.borrow_mut().drain(..).collect::<Vec<_>>()
270    }
271
272    fn has_updates(&self) -> bool {
273        !self.node_updates.borrow().is_empty() || self.has_invalid_scopes()
274    }
275
276    fn register_invalid_scope(&self, scope: Weak<RecomposeScopeInner>) {
277        self.invalid_scope_count
278            .set(self.invalid_scope_count.get() + 1);
279        self.scope_queue.borrow_mut().push(scope);
280        self.schedule();
281    }
282
283    fn requeue_invalid_scope(&self, scope: &RecomposeScope) {
284        if scope.is_enqueued() {
285            self.scope_queue.borrow_mut().push(scope.downgrade());
286            self.schedule();
287        }
288    }
289
290    fn mark_scope_recomposed(&self) {
291        self.invalid_scope_count
292            .set(self.invalid_scope_count.get().saturating_sub(1));
293    }
294
295    fn take_invalidated_scopes(&self) -> Option<Vec<RecomposeScope>> {
296        // An empty queue keeps its storage for the next invalidation.
297        let mut pending = {
298            let mut queue = self.scope_queue.borrow_mut();
299            if queue.is_empty() {
300                return None;
301            }
302            std::mem::take(&mut *queue)
303        };
304        let mut scopes = std::mem::take(&mut *self.spare_scopes.borrow_mut());
305        scopes.extend(
306            pending
307                .iter()
308                .filter_map(RecomposeScope::upgrade)
309                .filter(RecomposeScope::is_enqueued),
310        );
311        pending.clear();
312        let mut queue = self.scope_queue.borrow_mut();
313        if queue.is_empty() {
314            std::mem::swap(&mut *queue, &mut pending);
315        }
316        drop(queue);
317        if scopes.is_empty() {
318            self.recycle_scopes(scopes);
319            return None;
320        }
321        // Ancestors first, as Compose recomposes in composition order: a
322        // scope that a recomposing parent removes or composes again does not
323        // run first with the arguments it had.
324        // Scopes of one depth keep their queue order.
325        if !scopes.is_sorted_by_key(RecomposeScope::depth) {
326            let mut order = self.scope_order.borrow_mut();
327            order.order_by(&mut scopes, RecomposeScope::depth);
328        }
329        Some(scopes)
330    }
331
332    fn recycle_scopes(&self, mut scopes: Vec<RecomposeScope>) {
333        // Cleared before the borrow: dropping a scope may run any code.
334        scopes.clear();
335        let mut spare = self.spare_scopes.borrow_mut();
336        if spare.capacity() < scopes.capacity() {
337            *spare = scopes;
338        }
339    }
340
341    fn has_invalid_scopes(&self) -> bool {
342        self.invalid_scope_count.get() != 0
343    }
344
345    fn queued_invalid_scope_ids(&self) -> Vec<ScopeId> {
346        let mut ids: Vec<ScopeId> = self
347            .scope_queue
348            .borrow()
349            .iter()
350            .filter_map(RecomposeScope::upgrade)
351            .filter(RecomposeScope::is_enqueued)
352            .map(|scope| scope.id())
353            .collect();
354        ids.sort_unstable();
355        ids.dedup();
356        ids
357    }
358
359    fn increment_live_recompose_scope_count(&self) {
360        self.live_recompose_scope_count
361            .set(self.live_recompose_scope_count.get().saturating_add(1));
362    }
363
364    fn decrement_live_recompose_scope_count(&self) {
365        self.live_recompose_scope_count
366            .set(self.live_recompose_scope_count.get().saturating_sub(1));
367    }
368
369    fn live_recompose_scope_count(&self) -> usize {
370        self.live_recompose_scope_count.get()
371    }
372
373    fn has_frame_callbacks(&self) -> bool {
374        !self.frame_callbacks.borrow().is_empty()
375    }
376
377    fn has_transient_frame_callbacks(&self) -> bool {
378        self.frame_callbacks
379            .borrow()
380            .iter()
381            .any(|entry| entry.kind == FrameCallbackKind::Transient)
382    }
383
384    fn enqueue_ui_task(&self, task: UiTask) {
385        self.local_tasks.borrow_mut().push_back(task);
386        self.schedule();
387    }
388
389    fn spawn_ui_task(&self, future: Pin<Box<dyn Future<Output = ()>>>, label: TaskLabel) -> u64 {
390        let runnable = Arc::new(AtomicBool::new(true));
391        self.task_woken.store(true, Ordering::Release);
392        let waker = RuntimeTaskWaker::new(self, Arc::clone(&runnable)).into_waker();
393        let id = self.tasks.borrow_mut().insert(TaskEntry {
394            label,
395            future: Some(future),
396            runnable,
397            waker,
398        });
399        self.task_order.borrow_mut().push(id);
400        self.schedule();
401        id
402    }
403
404    fn cancel_task(&self, id: u64) {
405        let task = self.tasks.borrow_mut().remove(id);
406        self.task_order.borrow_mut().retain(|queued| *queued != id);
407        drop(task);
408    }
409
410    fn has_task(&self, id: u64) -> bool {
411        self.tasks
412            .try_borrow()
413            .map_or(true, |tasks| tasks.contains(id))
414    }
415
416    // Polls the woken tasks; the drain calls it once a wake is set. Without
417    // a wake no task can make progress, and the order stays. Out of line:
418    // the poll is large and most drains find no wake.
419    #[inline(never)]
420    fn poll_async_tasks(&self) -> bool {
421        // The tasks still pending move to the front of `order`, which goes
422        // back as the task order, after any task spawned while polling.
423        let mut order = std::mem::take(&mut *self.task_order.borrow_mut());
424        // An empty order is a poll nested in another, which holds the order:
425        // the wake flag stays for the polls after it.
426        if order.is_empty() || !self.task_woken.swap(false, Ordering::AcqRel) {
427            let mut task_order = self.task_order.borrow_mut();
428            if task_order.is_empty() {
429                *task_order = order;
430            } else {
431                task_order.extend(order);
432            }
433            return false;
434        }
435        let mut pending = 0;
436        let mut made_progress = false;
437        for index in 0..order.len() {
438            let id = order[index];
439            let task = {
440                let mut tasks = self.tasks.borrow_mut();
441                let Some(entry) = tasks.get_mut(id) else {
442                    continue;
443                };
444                if entry.runnable.swap(false, Ordering::AcqRel) {
445                    entry
446                        .future
447                        .take()
448                        .map(|future| (future, entry.waker.clone()))
449                } else {
450                    None
451                }
452            };
453            let Some((mut future, waker)) = task else {
454                order[pending] = id;
455                pending += 1;
456                continue;
457            };
458            let mut cx = Context::from_waker(&waker);
459            match future.as_mut().poll(&mut cx) {
460                Poll::Ready(()) => {
461                    self.cancel_task(id);
462                    made_progress = true;
463                }
464                Poll::Pending => {
465                    let mut tasks = self.tasks.borrow_mut();
466                    if let Some(entry) = tasks.get_mut(id) {
467                        entry.future = Some(future);
468                        order[pending] = id;
469                        pending += 1;
470                    } else {
471                        drop(tasks);
472                        drop(future);
473                    }
474                }
475            }
476        }
477        order.truncate(pending);
478        order.retain(|id| self.has_task(*id));
479        let mut task_order = self.task_order.borrow_mut();
480        if task_order.is_empty() {
481            *task_order = order;
482        } else {
483            task_order.extend(order);
484        }
485        made_progress
486    }
487
488    fn drain_ui(&self) {
489        #[cfg(any(target_os = "emscripten", target_os = "espidf"))]
490        crate::concurrency::fire_due_alarms();
491        loop {
492            let mut executed = false;
493            // A message counts as pending from before it is sent until it
494            // ran, so none waits while none is pending.
495            if self.ui_dispatcher.has_pending() {
496                let rx = &mut *self.ui_rx.borrow_mut();
497                for message in rx.try_iter() {
498                    executed = true;
499                    let _guard = PendingGuard::new(&self.ui_dispatcher.pending);
500                    match message {
501                        UiMessage::Task(task) => {
502                            task();
503                        }
504                        UiMessage::Invoke { id, value } => {
505                            self.invoke_ui_cont(id, value);
506                        }
507                    }
508                }
509            }
510
511            // Most drains find nothing: each queue is tested here before its call.
512            if !self.local_tasks.borrow().is_empty() {
513                executed |= self.run_local_tasks();
514            }
515            if self.task_woken.load(Ordering::Acquire) {
516                executed |= self.poll_async_tasks();
517                // The tasks just polled may have queued work of their own,
518                // such as a state observer's change notice for a state they
519                // wrote. It belongs to this drain, or a frame that resumed an
520                // animation would draw the value it wrote only on the next
521                // frame. It does not count as progress: a task writing state
522                // on every poll must not keep the drain polling it.
523                self.run_local_tasks();
524            }
525            if !executed {
526                break;
527            }
528        }
529
530        self.clear_needs_frame_if_idle();
531    }
532
533    fn run_local_tasks(&self) -> bool {
534        let mut ran = false;
535        loop {
536            let task = self.local_tasks.borrow_mut().pop_front();
537            let Some(task) = task else {
538                return ran;
539            };
540            ran = true;
541            task.run();
542        }
543    }
544
545    fn has_pending_ui(&self) -> bool {
546        let local_pending = self
547            .local_tasks
548            .try_borrow()
549            .map_or(true, |tasks| !tasks.is_empty());
550
551        let pending =
552            local_pending || self.ui_dispatcher.has_pending() || self.has_runnable_tasks();
553        #[cfg(any(target_os = "emscripten", target_os = "espidf"))]
554        let pending = pending || crate::concurrency::has_due_alarm();
555        pending
556    }
557
558    /// A finished task's waker may still wake after the task is gone; with
559    /// no task left that wake is stale.
560    fn has_runnable_tasks(&self) -> bool {
561        self.task_woken.load(Ordering::Acquire)
562            && self
563                .tasks
564                .try_borrow()
565                .map_or(true, |tasks| !tasks.is_empty())
566    }
567
568    fn register_ui_cont<T: 'static>(&self, f: impl FnOnce(T) + 'static) -> u64 {
569        debug_assert_eq!(
570            std::thread::current().id(),
571            self.ui_thread_id,
572            "UI continuation registered off the runtime thread",
573        );
574        let id = self.next_cont_id.get();
575        self.next_cont_id.set(id + 1);
576        let callback = RefCell::new(Some(f));
577        self.ui_conts.borrow_mut().insert(
578            id,
579            Box::new(move |value: Box<dyn Any>| {
580                let Ok(value) = value.downcast::<T>() else {
581                    return false;
582                };
583                let Some(slot) = callback.borrow_mut().take() else {
584                    return true;
585                };
586                slot(*value);
587                true
588            }),
589        );
590        id
591    }
592
593    fn invoke_ui_cont(&self, id: u64, value: Box<dyn Any + Send>) {
594        debug_assert_eq!(
595            std::thread::current().id(),
596            self.ui_thread_id,
597            "UI continuation invoked off the runtime thread",
598        );
599        let callback = { self.ui_conts.borrow_mut().remove(&id) };
600        if let Some(callback) = callback {
601            let value: Box<dyn Any> = value;
602            if !callback(value) {
603                self.ui_conts.borrow_mut().insert(id, callback);
604            }
605        }
606    }
607
608    fn cancel_ui_cont(&self, id: u64) {
609        let continuation = self.ui_conts.borrow_mut().remove(&id);
610        drop(continuation);
611    }
612
613    fn register_frame_callback(
614        &self,
615        kind: FrameCallbackKind,
616        callback: FrameCallback,
617    ) -> FrameCallbackId {
618        let id = self.next_frame_callback_id.get();
619        self.next_frame_callback_id.set(id + 1);
620        self.frame_callbacks
621            .borrow_mut()
622            .push_back(FrameCallbackEntry { id, kind, callback });
623        self.schedule();
624        id
625    }
626
627    /// The frame time once the frame callback `id` has run. A waiting
628    /// task's entry takes `waker` when the one it holds would wake another
629    /// task.
630    #[cfg(any(feature = "internal", test))]
631    fn frame_waker_time(&self, id: FrameCallbackId, waker: &Waker) -> Option<u64> {
632        let mut callbacks = self.frame_callbacks.borrow_mut();
633        let Some(entry) = callbacks.iter_mut().find(|entry| entry.id == id) else {
634            return self.last_frame_time_nanos.get();
635        };
636        if let FrameCallback::Wake(held) = &mut entry.callback
637            && !held.will_wake(waker)
638        {
639            held.clone_from(waker);
640        }
641        None
642    }
643
644    fn cancel_frame_callback(&self, id: FrameCallbackId) {
645        let removed = {
646            let mut callbacks = self.frame_callbacks.borrow_mut();
647            callbacks
648                .iter()
649                .position(|entry| entry.id == id)
650                .and_then(|index| callbacks.remove(index))
651        };
652        drop(removed);
653        self.clear_needs_frame_if_idle();
654    }
655
656    fn clear_needs_frame_if_idle(&self) {
657        if !self.has_invalid_scopes()
658            && !self.has_updates()
659            && !self.has_frame_callbacks()
660            && !self.has_pending_ui()
661        {
662            *self.needs_frame.borrow_mut() = false;
663        }
664    }
665
666    fn drain_frame_callbacks(&self, frame_time_nanos: u64) {
667        if self
668            .last_frame_time_nanos
669            .get()
670            .is_some_and(|previous| frame_time_nanos <= previous)
671        {
672            return;
673        }
674        self.last_frame_time_nanos.set(Some(frame_time_nanos));
675        let next_frame_id = self.next_frame_callback_id.get();
676        let drain = || {
677            loop {
678                let entry = {
679                    let mut callbacks = self.frame_callbacks.borrow_mut();
680                    if callbacks
681                        .front()
682                        .is_some_and(|entry| entry.id < next_frame_id)
683                    {
684                        callbacks.pop_front()
685                    } else {
686                        None
687                    }
688                };
689                let Some(entry) = entry else {
690                    break;
691                };
692                match entry.callback {
693                    FrameCallback::Run(callback) => callback(frame_time_nanos),
694                    #[cfg(any(feature = "internal", test))]
695                    FrameCallback::Wake(waker) => waker.wake(),
696                }
697            }
698        };
699        // Callbacks write state in one snapshot. Waking a task writes none:
700        // a frame of only waiting tasks opens no snapshot.
701        let runs_callbacks = self
702            .frame_callbacks
703            .borrow()
704            .iter()
705            .any(|entry| matches!(entry.callback, FrameCallback::Run(_)));
706        if runs_callbacks {
707            let _ = crate::run_in_mutable_snapshot(drain);
708        } else {
709            drain();
710        }
711
712        self.clear_needs_frame_if_idle();
713    }
714
715    fn debug_stats(&self) -> RuntimeDebugStats {
716        let node_updates = self.node_updates.borrow();
717        let scope_queue = self.scope_queue.borrow();
718        let frame_callbacks = self.frame_callbacks.borrow();
719        let local_tasks = self.local_tasks.borrow();
720        let ui_conts = self.ui_conts.borrow();
721        let tasks = self.tasks.borrow();
722        let external_state_owners = self.external_state_owners.borrow();
723
724        RuntimeDebugStats {
725            node_updates_len: node_updates.len(),
726            node_updates_cap: node_updates.capacity(),
727            invalid_scopes_len: self.invalid_scope_count.get(),
728            scope_queue_len: scope_queue.len(),
729            scope_queue_cap: scope_queue.capacity(),
730            frame_callbacks_len: frame_callbacks.len(),
731            frame_callbacks_cap: frame_callbacks.capacity(),
732            local_tasks_len: local_tasks.len(),
733            local_tasks_cap: local_tasks.capacity(),
734            ui_conts_len: ui_conts.len(),
735            ui_conts_cap: ui_conts.capacity(),
736            tasks_len: tasks.len(),
737            tasks_cap: tasks.capacity(),
738            external_state_owners_len: external_state_owners.len(),
739            external_state_owners_cap: external_state_owners.capacity(),
740            ui_dispatcher_pending: self.ui_dispatcher.pending.load(Ordering::SeqCst),
741        }
742    }
743}
744
745/// Owns the state cells, UI tasks, frame callbacks and invalidated scopes of one composition.
746/// Clones share the same runtime.
747#[derive(Clone)]
748pub struct Runtime {
749    inner: Rc<RuntimeInner>,
750}
751
752impl Runtime {
753    /// Creates a runtime whose UI thread is the current thread. `scheduler` is asked for a frame
754    /// whenever the runtime has work.
755    pub fn new(scheduler: SchedulerRef) -> Self {
756        thread_state::watch_thread_exit();
757        let inner = Rc::new(RuntimeInner::new(scheduler));
758        let runtime = Self { inner };
759        let handle = runtime.handle();
760        thread_state::runtimes(|state| {
761            state
762                .registered_runtimes
763                .borrow_mut()
764                .insert(handle.id(), handle.clone());
765            *state.last_runtime.borrow_mut() = Some(handle);
766        });
767        runtime
768    }
769
770    #[cfg(target_os = "android")]
771    pub(crate) fn restore_thread_state(&self) {
772        if let Some(rescued) = self.inner.rescued.take() {
773            thread_state::restore(&rescued);
774        }
775    }
776
777    /// Returns a handle that reaches this runtime without keeping it alive.
778    pub fn handle(&self) -> RuntimeHandle {
779        RuntimeHandle {
780            inner: Rc::downgrade(&self.inner),
781            dispatcher: UiDispatcher::new(UiDispatcherRef::clone(&self.inner.ui_dispatcher)),
782            id: self.inner.runtime_id,
783        }
784    }
785
786    /// Returns `true` if node updates are queued or any recompose scope is invalid.
787    pub fn has_updates(&self) -> bool {
788        self.inner.has_updates()
789    }
790
791    /// Returns `true` if the runtime has asked for a frame or has a task ready to run.
792    pub fn needs_frame(&self) -> bool {
793        *self.inner.needs_frame.borrow() || self.inner.has_runnable_tasks()
794    }
795
796    /// Sets or clears the request for a frame.
797    pub fn set_needs_frame(&self, value: bool) {
798        *self.inner.needs_frame.borrow_mut() = value;
799    }
800
801    /// Returns `true` if posted UI work has not run yet. The owner of a
802    /// runtime asks it here; a [`RuntimeHandle`] costs a clone of its parts.
803    pub fn has_pending_ui(&self) -> bool {
804        self.inner.has_pending_ui()
805    }
806
807    /// Returns `true` if any recompose scope is invalid.
808    pub fn has_invalid_scopes(&self) -> bool {
809        self.inner.has_invalid_scopes()
810    }
811
812    /// Returns `true` if any frame callback is registered.
813    pub fn has_frame_callbacks(&self) -> bool {
814        self.inner.has_frame_callbacks()
815    }
816
817    /// Returns `true` while a one-shot frame callback waits for the next
818    /// frame. Perpetual frame callbacks do not count.
819    pub fn has_transient_frame_callbacks(&self) -> bool {
820        self.inner.has_transient_frame_callbacks()
821    }
822
823    /// Runs the frame callbacks due at `frame_time_nanos`.
824    pub fn drain_frame_callbacks(&self, frame_time_nanos: u64) {
825        self.inner.drain_frame_callbacks(frame_time_nanos);
826    }
827
828    pub(crate) fn take_forgotten_movables(&self) -> Vec<Key> {
829        std::mem::take(&mut *self.inner.forgotten_movables.borrow_mut())
830    }
831
832    pub(crate) fn take_updates(&self) -> Vec<Command> {
833        self.inner.take_updates()
834    }
835
836    /// Animation-clock time of the most recent frame-callback drain. This is
837    /// the same clock `Animatable`s advance on (virtual under robot exact
838    /// captures), so per-frame integrators derive dt from it instead of wall
839    /// time.
840    pub fn last_frame_time_nanos(&self) -> Option<u64> {
841        self.inner.last_frame_time_nanos.get()
842    }
843
844    /// Returns a clock for the frames of this runtime.
845    #[cfg(any(feature = "internal", test))]
846    pub fn frame_clock(&self) -> FrameClock {
847        FrameClock::new(self.handle())
848    }
849}
850
851impl Drop for Runtime {
852    fn drop(&mut self) {
853        if Rc::strong_count(&self.inner) != 1 {
854            return;
855        }
856        let id = self.inner.runtime_id;
857        thread_state::try_runtimes(|state| {
858            state.registered_runtimes.borrow_mut().remove(&id);
859            let mut last = state.last_runtime.borrow_mut();
860            if last.as_ref().is_some_and(|handle| handle.id() == id) {
861                *last = None;
862            }
863        });
864        thread_state::release_when_idle();
865    }
866}
867
868/// A scheduler that ignores frame requests, for compositions that the caller drives itself.
869#[derive(Default)]
870pub struct DefaultScheduler;
871
872impl RuntimeScheduler for DefaultScheduler {
873    fn schedule_frame(&self) {}
874}
875
876#[cfg(test)]
877#[derive(Default)]
878pub(crate) struct TestScheduler;
879
880#[cfg(test)]
881impl RuntimeScheduler for TestScheduler {
882    fn schedule_frame(&self) {}
883}
884
885#[cfg(test)]
886pub(crate) struct TestRuntime {
887    runtime: Runtime,
888}
889
890#[cfg(test)]
891impl Default for TestRuntime {
892    fn default() -> Self {
893        Self::new()
894    }
895}
896
897#[cfg(test)]
898impl TestRuntime {
899    pub(crate) fn new() -> Self {
900        Self {
901            runtime: Runtime::new(Arc::new(TestScheduler)),
902        }
903    }
904
905    pub(crate) fn handle(&self) -> RuntimeHandle {
906        self.runtime.handle()
907    }
908}
909
910/// A cheap handle to a [`Runtime`]. It does not keep the runtime alive, and its calls do nothing
911/// once the runtime is dropped.
912#[derive(Clone)]
913pub struct RuntimeHandle {
914    inner: Weak<RuntimeInner>,
915    dispatcher: UiDispatcher,
916    id: RuntimeId,
917}
918
919/// Controls a future spawned with `RuntimeHandle::spawn_ui`.
920pub struct TaskHandle {
921    id: u64,
922    runtime: RuntimeHandle,
923}
924
925pub(crate) struct DeferredStateRelease {
926    runtime: Weak<RuntimeInner>,
927    id: StateId,
928}
929
930pub(crate) struct StateHandleLease {
931    id: StateId,
932    runtime: RuntimeHandle,
933}
934
935impl StateHandleLease {
936    pub(crate) fn id(&self) -> StateId {
937        self.id
938    }
939
940    pub(crate) fn runtime_id(&self) -> RuntimeId {
941        self.runtime.id()
942    }
943}
944
945impl Drop for StateHandleLease {
946    fn drop(&mut self) {
947        defer_state_release(&self.runtime, self.id);
948    }
949}
950
951impl RuntimeHandle {
952    /// Returns the id of the runtime.
953    pub fn id(&self) -> RuntimeId {
954        self.id
955    }
956
957    pub(crate) fn alloc_state<T: Clone + 'static>(&self, value: T) -> Rc<StateHandleLease> {
958        let id = self.with_state_arena(|arena| arena.alloc(value, self.clone()));
959        let lease = Rc::new(StateHandleLease {
960            id,
961            runtime: self.clone(),
962        });
963        self.with_state_arena(|arena| arena.register_lease(id, &lease));
964        lease
965    }
966
967    pub(crate) fn alloc_state_with_policy<T: Clone + 'static>(
968        &self,
969        value: T,
970        policy: Rc<dyn MutationPolicy<T>>,
971    ) -> Rc<StateHandleLease> {
972        let id =
973            self.with_state_arena(|arena| arena.alloc_with_policy(value, self.clone(), policy));
974        let lease = Rc::new(StateHandleLease {
975            id,
976            runtime: self.clone(),
977        });
978        self.with_state_arena(|arena| arena.register_lease(id, &lease));
979        lease
980    }
981
982    /// Stores `value` in a new plain cell, whose lease goes to the value
983    /// being remembered, or else to the runtime; returns the cell's id.
984    pub(crate) fn alloc_owned_plain<T: 'static>(&self, value: T) -> StateId {
985        let id = self.with_state_arena(|arena| arena.alloc_plain(value));
986        let lease = Rc::new(StateHandleLease {
987            id,
988            runtime: self.clone(),
989        });
990        self.with_state_arena(|arena| arena.register_lease(id, &lease));
991        self.hand_to_owner(&lease);
992        id
993    }
994
995    pub(crate) fn alloc_persistent_state<T: Clone + 'static>(
996        &self,
997        value: T,
998    ) -> crate::MutableState<T> {
999        self.hand_out(self.alloc_state(value))
1000    }
1001
1002    pub(crate) fn alloc_persistent_state_with_policy<T: Clone + 'static>(
1003        &self,
1004        value: T,
1005        policy: Rc<dyn MutationPolicy<T>>,
1006    ) -> crate::MutableState<T> {
1007        self.hand_out(self.alloc_state_with_policy(value, policy))
1008    }
1009
1010    fn hand_out<T: Clone + 'static>(&self, lease: Rc<StateHandleLease>) -> crate::MutableState<T> {
1011        self.hand_to_owner(&lease);
1012        crate::MutableState::from_lease(&lease)
1013    }
1014
1015    /// Hands `lease` to the value being remembered, or else to the runtime,
1016    /// which keeps it as long as it lives.
1017    fn hand_to_owner(&self, lease: &Rc<StateHandleLease>) {
1018        if !hand_to_current_owner(lease)
1019            && let Some(inner) = self.inner.upgrade()
1020        {
1021            inner
1022                .external_state_owners
1023                .borrow_mut()
1024                .insert(lease.id(), Rc::clone(lease));
1025        }
1026    }
1027
1028    pub(crate) fn retain_state_lease(&self, id: StateId) -> Option<Rc<StateHandleLease>> {
1029        self.with_state_arena(|arena| arena.retain_lease(id))
1030    }
1031
1032    pub(crate) fn with_state_arena<R>(&self, f: impl FnOnce(&StateArena) -> R) -> R {
1033        self.try_with_state_arena(f)
1034            .unwrap_or_else(|| panic!("runtime dropped"))
1035    }
1036
1037    pub(crate) fn try_with_state_arena<R>(&self, f: impl FnOnce(&StateArena) -> R) -> Option<R> {
1038        self.inner.upgrade().map(|inner| f(&inner.state_arena))
1039    }
1040
1041    /// Returns the number of state cells and, of those, the number free for reuse.
1042    pub fn state_arena_stats(&self) -> (usize, usize) {
1043        self.try_with_state_arena(StateArena::stats)
1044            .unwrap_or_default()
1045    }
1046
1047    /// Returns the sizes of the runtime's state arena, for leak and memory checks.
1048    pub fn state_arena_debug_stats(&self) -> StateArenaDebugStats {
1049        self.try_with_state_arena(StateArena::debug_stats)
1050            .unwrap_or_default()
1051    }
1052
1053    /// Returns the sizes of the runtime's queues and tables, for leak and memory checks.
1054    pub fn debug_stats(&self) -> RuntimeDebugStats {
1055        self.inner
1056            .upgrade()
1057            .map_or_default(|inner| inner.debug_stats())
1058    }
1059
1060    /// Returns the id and label of every spawned UI task that has not finished.
1061    pub fn live_ui_task_labels(&self) -> Vec<(u64, String)> {
1062        self.inner.upgrade().map_or_default(|inner| {
1063            inner
1064                .tasks
1065                .borrow()
1066                .iter()
1067                .map(|(id, entry)| (id, entry.label.to_string()))
1068                .collect()
1069        })
1070    }
1071
1072    /// Marks the runtime as needing a frame and asks its scheduler for one.
1073    pub fn schedule(&self) {
1074        if let Some(inner) = self.inner.upgrade() {
1075            inner.schedule();
1076        }
1077    }
1078
1079    pub(crate) fn enqueue_node_update(&self, command: Command) {
1080        if let Some(inner) = self.inner.upgrade() {
1081            inner.enqueue_update(command);
1082        }
1083    }
1084
1085    /// Spawns `fut` on the UI thread, where `drain_ui` polls it whenever it is woken. Returns
1086    /// `None` if the runtime is gone.
1087    pub fn spawn_ui<F>(&self, fut: F) -> Option<TaskHandle>
1088    where
1089        F: Future<Output = ()> + 'static,
1090    {
1091        self.spawn_labelled(Box::pin(fut), TaskLabel::Unnamed)
1092    }
1093
1094    pub(crate) fn spawn_labelled(
1095        &self,
1096        future: Pin<Box<dyn Future<Output = ()>>>,
1097        label: TaskLabel,
1098    ) -> Option<TaskHandle> {
1099        let inner = self.inner.upgrade()?;
1100        let id = inner.spawn_ui_task(future, label);
1101        Some(TaskHandle {
1102            id,
1103            runtime: self.clone(),
1104        })
1105    }
1106
1107    /// Cancels the spawned UI task `id` and drops its future.
1108    pub fn cancel_task(&self, id: u64) {
1109        if let Some(inner) = self.inner.upgrade() {
1110            inner.cancel_task(id);
1111        }
1112    }
1113
1114    /// Whether the runtime still holds the spawned task `id`.
1115    pub fn has_task(&self, id: u64) -> bool {
1116        self.inner.upgrade().is_some_and(|inner| inner.has_task(id))
1117    }
1118
1119    /// Enqueues work from any thread to run on the UI thread.
1120    ///
1121    /// The closure must be `Send` because it may cross threads before executing
1122    /// on the runtime thread. Use this when posting from background work.
1123    pub fn post_ui(&self, task: impl FnOnce() + Send + 'static) {
1124        self.dispatcher.post(task);
1125    }
1126
1127    /// Registers `f` to run once on the UI thread when `UiDispatcher::post_invoke` sends a `T` for
1128    /// the returned id. Returns `None` if the runtime is gone.
1129    pub fn register_ui_cont<T: 'static>(&self, f: impl FnOnce(T) + 'static) -> Option<u64> {
1130        self.inner.upgrade().map(|inner| inner.register_ui_cont(f))
1131    }
1132
1133    /// Removes the continuation `id` without running it.
1134    pub fn cancel_ui_cont(&self, id: u64) {
1135        if let Some(inner) = self.inner.upgrade() {
1136            inner.cancel_ui_cont(id);
1137        }
1138    }
1139
1140    /// Runs the work posted to the UI thread, including woken tasks, until none is left.
1141    pub fn drain_ui(&self) {
1142        if let Some(inner) = self.inner.upgrade() {
1143            inner.drain_ui();
1144        }
1145    }
1146
1147    /// Returns `true` if posted UI work has not run yet.
1148    pub fn has_pending_ui(&self) -> bool {
1149        self.inner.upgrade().map_or_else(
1150            || self.dispatcher.has_pending(),
1151            |inner| inner.has_pending_ui(),
1152        )
1153    }
1154
1155    /// Registers `callback` to run once on the next frame with the frame time in nanoseconds.
1156    /// Returns `None` if the runtime is gone.
1157    pub fn register_frame_callback(
1158        &self,
1159        callback: impl FnOnce(u64) + 'static,
1160    ) -> Option<FrameCallbackId> {
1161        self.inner.upgrade().map(|inner| {
1162            inner.register_frame_callback(
1163                FrameCallbackKind::Transient,
1164                FrameCallback::Run(Box::new(callback)),
1165            )
1166        })
1167    }
1168
1169    /// Registers `callback` to run once on the next frame, for a long-lived loop that registers
1170    /// again after every frame. It does not count in `has_transient_frame_callbacks`.
1171    pub fn register_perpetual_frame_callback(
1172        &self,
1173        callback: impl FnOnce(u64) + 'static,
1174    ) -> Option<FrameCallbackId> {
1175        self.inner.upgrade().map(|inner| {
1176            inner.register_frame_callback(
1177                FrameCallbackKind::Perpetual,
1178                FrameCallback::Run(Box::new(callback)),
1179            )
1180        })
1181    }
1182
1183    /// Wakes the task of `waker` at the next frame, whose time it then reads
1184    /// with [`Self::frame_waker_time`].
1185    #[cfg(any(feature = "internal", test))]
1186    pub(crate) fn register_frame_waker(
1187        &self,
1188        kind: FrameCallbackKind,
1189        waker: Waker,
1190    ) -> Option<FrameCallbackId> {
1191        self.inner
1192            .upgrade()
1193            .map(|inner| inner.register_frame_callback(kind, FrameCallback::Wake(waker)))
1194    }
1195
1196    /// The frame time once the frame waker `id` has run; until then its
1197    /// entry wakes `waker`.
1198    #[cfg(any(feature = "internal", test))]
1199    pub(crate) fn frame_waker_time(&self, id: FrameCallbackId, waker: &Waker) -> Option<u64> {
1200        self.inner
1201            .upgrade()
1202            .and_then(|inner| inner.frame_waker_time(id, waker))
1203    }
1204
1205    /// Cancels the frame callback `id` if it has not run.
1206    pub fn cancel_frame_callback(&self, id: FrameCallbackId) {
1207        if let Some(inner) = self.inner.upgrade() {
1208            inner.cancel_frame_callback(id);
1209        }
1210    }
1211
1212    /// Delivers callbacks registered before this display frame. Timestamps use
1213    /// one monotonic nanosecond epoch; duplicate or older timestamps are ignored.
1214    /// A callback registered during delivery waits for a newer frame timestamp.
1215    pub fn drain_frame_callbacks(&self, frame_time_nanos: u64) {
1216        if let Some(inner) = self.inner.upgrade() {
1217            inner.drain_frame_callbacks(frame_time_nanos);
1218        }
1219    }
1220
1221    /// Animation-clock time of the most recent frame-callback drain (see
1222    /// [`Runtime::last_frame_time_nanos`]).
1223    pub fn last_frame_time_nanos(&self) -> Option<u64> {
1224        self.inner
1225            .upgrade()
1226            .and_then(|inner| inner.last_frame_time_nanos.get())
1227    }
1228
1229    /// Returns a clock for the frames of this runtime.
1230    #[cfg(any(feature = "internal", test))]
1231    pub fn frame_clock(&self) -> FrameClock {
1232        FrameClock::new(self.clone())
1233    }
1234
1235    /// Sets or clears the request for a frame.
1236    pub fn set_needs_frame(&self, value: bool) {
1237        if let Some(inner) = self.inner.upgrade() {
1238            *inner.needs_frame.borrow_mut() = value;
1239        }
1240    }
1241
1242    pub(crate) fn take_updates(&self) -> Vec<Command> {
1243        self.inner
1244            .upgrade()
1245            .map_or_default(|inner| inner.take_updates())
1246    }
1247
1248    /// Returns `true` if node updates are queued or any recompose scope is invalid.
1249    pub fn has_updates(&self) -> bool {
1250        self.inner
1251            .upgrade()
1252            .is_some_and(|inner| inner.has_updates())
1253    }
1254
1255    /// The link a recompose scope keeps to this runtime.
1256    pub(crate) fn scope_runtime(&self) -> ScopeRuntime {
1257        ScopeRuntime(Weak::clone(&self.inner))
1258    }
1259
1260    pub(crate) fn requeue_invalid_scope(&self, scope: &RecomposeScope) {
1261        if let Some(inner) = self.inner.upgrade() {
1262            inner.requeue_invalid_scope(scope);
1263        }
1264    }
1265
1266    pub(crate) fn take_invalidated_scopes(&self) -> Option<Vec<RecomposeScope>> {
1267        self.inner
1268            .upgrade()
1269            .and_then(|inner| inner.take_invalidated_scopes())
1270    }
1271
1272    /// Gives back a scope list from [`Self::take_invalidated_scopes`] for reuse.
1273    #[inline]
1274    pub(crate) fn recycle_scopes(&self, scopes: Vec<RecomposeScope>) {
1275        if let Some(inner) = self.inner.upgrade() {
1276            inner.recycle_scopes(scopes);
1277        }
1278    }
1279
1280    /// Releases the retained state of the movable content with identity
1281    /// `id` at the composition's next opportunity. See
1282    /// [`crate::forget_movable`].
1283    pub fn forget_movable(&self, id: Key) {
1284        if let Some(inner) = self.inner.upgrade() {
1285            inner.forgotten_movables.borrow_mut().push(id);
1286            inner.schedule();
1287        }
1288    }
1289
1290    /// An identity for a piece of movable content, unique within this
1291    /// runtime. Owned by the runtime instance rather than a process-wide
1292    /// counter, so two compositions in one process cannot collide and a
1293    /// test cannot be made to pass by the order it happens to run in.
1294    pub(crate) fn next_movable_content_id(&self) -> Key {
1295        let Some(inner) = self.inner.upgrade() else {
1296            log::error!("movable content asked a runtime that is gone for an identity");
1297            return Key(0);
1298        };
1299        let id = inner.next_movable_content_id.get();
1300        inner.next_movable_content_id.set(id.wrapping_add(1).max(1));
1301        Key(id)
1302    }
1303
1304    /// Returns `true` if a recompose scope has been invalidated and not yet recomposed.
1305    pub fn has_invalid_scopes(&self) -> bool {
1306        self.inner
1307            .upgrade()
1308            .is_some_and(|inner| inner.has_invalid_scopes())
1309    }
1310
1311    fn live_recompose_scope_count(&self) -> usize {
1312        self.inner
1313            .upgrade()
1314            .map_or_default(|inner| inner.live_recompose_scope_count())
1315    }
1316
1317    #[doc(hidden)]
1318    pub fn debug_invalid_scope_ids(&self) -> Vec<usize> {
1319        self.inner
1320            .upgrade()
1321            .map_or_default(|inner| inner.queued_invalid_scope_ids())
1322    }
1323
1324    /// Returns `true` if any frame callback, transient or perpetual, is waiting.
1325    pub fn has_frame_callbacks(&self) -> bool {
1326        self.inner
1327            .upgrade()
1328            .is_some_and(|inner| inner.has_frame_callbacks())
1329    }
1330
1331    /// Returns `true` if a callback from `register_frame_callback` is waiting. Perpetual callbacks
1332    /// do not count.
1333    pub fn has_transient_frame_callbacks(&self) -> bool {
1334        self.inner
1335            .upgrade()
1336            .is_some_and(|inner| inner.has_transient_frame_callbacks())
1337    }
1338
1339    /// Panics in debug builds when called off the runtime's UI thread.
1340    pub fn assert_ui_thread(&self) {
1341        debug_assert!(
1342            self.inner
1343                .upgrade()
1344                .is_none_or(|inner| inner.ui_thread_id == std::thread::current().id()),
1345            "state mutated off the runtime's UI thread"
1346        );
1347    }
1348
1349    /// Returns a dispatcher that posts work to the UI thread from any thread.
1350    pub fn dispatcher(&self) -> UiDispatcher {
1351        self.dispatcher.clone()
1352    }
1353
1354    #[doc(hidden)]
1355    pub fn with_deferred_state_releases<R>(&self, f: impl FnOnce() -> R) -> R {
1356        let _scope = enter_state_teardown_scope();
1357        f()
1358    }
1359}
1360
1361impl TaskHandle {
1362    /// Cancels the task if it has not finished.
1363    pub fn cancel(&self) {
1364        self.runtime.cancel_task(self.id);
1365    }
1366
1367    /// Whether the spawned future has finished or been cancelled.
1368    pub fn is_finished(&self) -> bool {
1369        !self.runtime.has_task(self.id)
1370    }
1371}
1372
1373pub(crate) struct FrameCallbackEntry {
1374    id: FrameCallbackId,
1375    kind: FrameCallbackKind,
1376    callback: FrameCallback,
1377}
1378
1379enum FrameCallback {
1380    /// Runs with the frame time.
1381    Run(Box<dyn FnOnce(u64) + 'static>),
1382    /// Wakes a task awaiting the frame.
1383    #[cfg(any(feature = "internal", test))]
1384    Wake(Waker),
1385}
1386
1387#[cfg(not(target_arch = "wasm32"))]
1388struct RuntimeTaskWaker {
1389    scheduler: SchedulerRef,
1390    runnable: Arc<AtomicBool>,
1391    woken: Arc<AtomicBool>,
1392}
1393
1394#[cfg(target_arch = "wasm32")]
1395struct RuntimeTaskWaker {
1396    runtime_id: RuntimeId,
1397    runnable: Arc<AtomicBool>,
1398    woken: Arc<AtomicBool>,
1399}
1400
1401impl RuntimeTaskWaker {
1402    #[cfg(not(target_arch = "wasm32"))]
1403    fn new(inner: &RuntimeInner, runnable: Arc<AtomicBool>) -> Self {
1404        let scheduler = Arc::clone(&inner.scheduler);
1405        Self {
1406            scheduler,
1407            runnable,
1408            woken: Arc::clone(&inner.task_woken),
1409        }
1410    }
1411
1412    #[cfg(target_arch = "wasm32")]
1413    fn new(inner: &RuntimeInner, runnable: Arc<AtomicBool>) -> Self {
1414        let runtime_id = inner.runtime_id;
1415        Self {
1416            runtime_id,
1417            runnable,
1418            woken: Arc::clone(&inner.task_woken),
1419        }
1420    }
1421
1422    fn into_waker(self) -> Waker {
1423        futures_task::waker(Arc::new(self))
1424    }
1425}
1426
1427impl futures_task::ArcWake for RuntimeTaskWaker {
1428    #[cfg(not(target_arch = "wasm32"))]
1429    fn wake_by_ref(arc_self: &Arc<Self>) {
1430        arc_self.runnable.store(true, Ordering::Release);
1431        arc_self.woken.store(true, Ordering::Release);
1432        arc_self.scheduler.schedule_frame();
1433    }
1434
1435    #[cfg(target_arch = "wasm32")]
1436    fn wake_by_ref(arc_self: &Arc<Self>) {
1437        arc_self.runnable.store(true, Ordering::Release);
1438        arc_self.woken.store(true, Ordering::Release);
1439        if let Some(handle) = runtime_handle_by_id(arc_self.runtime_id) {
1440            handle.schedule();
1441        }
1442    }
1443}
1444
1445/// Sizes of the runtime registries of one thread, for leak and memory checks. A `_len` field counts
1446/// entries and a `_cap` field the capacity reserved.
1447#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1448pub struct RuntimeThreadLocalDebugStats {
1449    /// Runtimes currently installed as active on this thread.
1450    pub active_runtimes_len: usize,
1451    /// Capacity reserved for the active runtimes.
1452    pub active_runtimes_cap: usize,
1453    /// Runtimes registered on this thread.
1454    pub registered_runtimes_len: usize,
1455    /// Capacity reserved for the registered runtimes.
1456    pub registered_runtimes_cap: usize,
1457    /// State releases waiting for the end of a teardown scope.
1458    pub deferred_state_releases_len: usize,
1459    /// Capacity reserved for the deferred state releases.
1460    pub deferred_state_releases_cap: usize,
1461}
1462
1463/// Gets the current runtime handle from thread-local storage.
1464///
1465/// Returns the most recently pushed active runtime, or the last known runtime.
1466/// Used by fling animation and other components that need access to the runtime.
1467pub fn current_runtime_handle() -> Option<RuntimeHandle> {
1468    thread_state::try_runtimes(|state| {
1469        if let Some(handle) = state.active_runtimes.borrow().last() {
1470            return Some(handle.clone());
1471        }
1472        state.last_runtime.borrow().clone()
1473    })
1474    .flatten()
1475}
1476
1477#[cfg(target_os = "android")]
1478pub(crate) fn share_rescue<'a>(
1479    handles: impl Iterator<Item = &'a RuntimeHandle>,
1480) -> Option<Rc<thread_state::RescuedThreadState>> {
1481    let live: Vec<Rc<RuntimeInner>> = handles
1482        .filter_map(|handle| handle.inner.upgrade())
1483        .collect();
1484    let shared = live
1485        .iter()
1486        .find_map(|inner| inner.rescued.borrow().clone())
1487        .or_else(|| (!live.is_empty()).then(Rc::default))?;
1488    for inner in &live {
1489        *inner.rescued.borrow_mut() = Some(Rc::clone(&shared));
1490    }
1491    Some(shared)
1492}
1493
1494pub(crate) fn live_recompose_scope_count() -> usize {
1495    thread_state::runtimes(|state| {
1496        state
1497            .registered_runtimes
1498            .borrow()
1499            .values()
1500            .map(RuntimeHandle::live_recompose_scope_count)
1501            .sum()
1502    })
1503}
1504
1505/// Returns the sizes of the runtime registries of the current thread, for leak and memory checks.
1506pub fn debug_runtime_thread_local_stats() -> RuntimeThreadLocalDebugStats {
1507    thread_state::runtimes(|state| {
1508        let active = state.active_runtimes.borrow();
1509        let registered = state.registered_runtimes.borrow();
1510        let deferred = state.deferred_state_releases.borrow();
1511        RuntimeThreadLocalDebugStats {
1512            active_runtimes_len: active.len(),
1513            active_runtimes_cap: active.capacity(),
1514            registered_runtimes_len: registered.len(),
1515            registered_runtimes_cap: registered.capacity(),
1516            deferred_state_releases_len: deferred.len(),
1517            deferred_state_releases_cap: deferred.capacity(),
1518        }
1519    })
1520}
1521
1522fn defer_state_release(runtime: &RuntimeHandle, id: StateId) {
1523    let deferred = thread_state::try_runtimes(|state| {
1524        if state.state_teardown_depth.get() == 0 {
1525            return false;
1526        }
1527        state
1528            .deferred_state_releases
1529            .borrow_mut()
1530            .push(DeferredStateRelease {
1531                runtime: Weak::clone(&runtime.inner),
1532                id,
1533            });
1534        true
1535    });
1536    if deferred != Some(true) {
1537        release_state(&runtime.inner, id);
1538    }
1539}
1540
1541fn release_state(runtime: &Weak<RuntimeInner>, id: StateId) {
1542    if let Some(inner) = runtime.upgrade() {
1543        inner.state_arena.release(id);
1544    }
1545}
1546
1547pub(crate) struct StateTeardownScope;
1548
1549pub(crate) fn enter_state_teardown_scope() -> StateTeardownScope {
1550    thread_state::try_runtimes(|state| {
1551        let depth = &state.state_teardown_depth;
1552        depth.set(depth.get() + 1);
1553    });
1554    StateTeardownScope
1555}
1556
1557impl Drop for StateTeardownScope {
1558    fn drop(&mut self) {
1559        let finished = thread_state::try_runtimes(|state| {
1560            let depth = &state.state_teardown_depth;
1561            let next = depth.get().saturating_sub(1);
1562            depth.set(next);
1563            if next == 0 {
1564                let mut releases = state.deferred_state_releases.borrow_mut();
1565                while let Some(deferred) = releases.pop() {
1566                    release_state(&deferred.runtime, deferred.id);
1567                }
1568            }
1569            next == 0
1570        });
1571        if finished == Some(true) {
1572            thread_state::release_when_idle();
1573        }
1574    }
1575}
1576
1577pub(crate) fn push_active_runtime(handle: &RuntimeHandle) {
1578    thread_state::runtimes(|state| {
1579        // A runtime's handles are alike: the ones the thread holds stay.
1580        state
1581            .registered_runtimes
1582            .borrow_mut()
1583            .entry(handle.id())
1584            .or_insert_with(|| handle.clone());
1585        state.active_runtimes.borrow_mut().push(handle.clone());
1586        let mut last = state.last_runtime.borrow_mut();
1587        if last.as_ref().is_none_or(|last| last.id != handle.id) {
1588            *last = Some(handle.clone());
1589        }
1590    });
1591}
1592
1593pub(crate) fn pop_active_runtime() {
1594    thread_state::runtimes(|state| {
1595        state.active_runtimes.borrow_mut().pop();
1596    });
1597}
1598
1599/// Schedule a new frame render using the most recently active runtime handle.
1600pub fn schedule_frame() {
1601    if let Some(handle) = current_runtime_handle() {
1602        handle.schedule();
1603        return;
1604    }
1605    log::debug!(
1606        target: "cranpose::runtime",
1607        "ignoring frame request without an active runtime",
1608    );
1609}
1610
1611/// Schedule an in-place node update using the most recently active runtime.
1612pub fn schedule_node_update(
1613    update: impl FnOnce(&mut dyn Applier) -> Result<(), NodeError> + 'static,
1614) {
1615    if let Some(handle) = current_runtime_handle() {
1616        handle.enqueue_node_update(Command::callback(update));
1617    } else {
1618        drop(update);
1619        log::debug!(
1620            target: "cranpose::runtime",
1621            "ignoring node update request without an active runtime",
1622        );
1623    }
1624}
1625
1626#[cfg(test)]
1627#[path = "tests/runtime_tests.rs"]
1628mod tests;