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