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 thread_local,
16};
17
18#[cfg(any(feature = "internal", test))]
19use crate::frame_clock::FrameClock;
20use crate::{
21 Applier, Command, FrameCallbackId, Key, MutableStateInner, NodeError, RecomposeScopeInner,
22 ScopeId,
23 collections::map::{HashMap, HashSet},
24 platform::{RuntimeScheduler, SchedulerRef},
25 state::{MutationPolicy, NeverEqual},
26};
27
28#[derive(Clone, Copy, PartialEq, Eq)]
29pub(crate) enum FrameCallbackKind {
30 Transient,
31 Perpetual,
32}
33
34enum UiMessage {
35 Task(Box<dyn FnOnce() + Send + 'static>),
36 Invoke { id: u64, value: Box<dyn Any + Send> },
37}
38
39type UiContinuation = Box<dyn Fn(Box<dyn Any>) -> bool + 'static>;
40type UiContinuationMap = HashMap<u64, UiContinuation>;
41
42struct TypedStateCell<T: Clone + 'static> {
43 inner: MutableStateInner<T>,
44}
45
46trait ScopeWatchCell {
47 fn unregister_scope(&self, scope_id: ScopeId);
48}
49
50impl<T: Clone + 'static> ScopeWatchCell for TypedStateCell<T> {
51 fn unregister_scope(&self, scope_id: ScopeId) {
52 self.inner.unregister_scope(scope_id);
53 }
54}
55
56struct StateArenaSlot {
57 generation: u32,
58 cell: Option<Rc<dyn Any>>,
59 watcher_cell: Option<Rc<dyn ScopeWatchCell>>,
60 lease: Option<Weak<StateHandleLease>>,
61}
62
63#[derive(Default)]
64struct StateArenaInner {
65 cells: Vec<StateArenaSlot>,
66 free: Vec<u32>,
67}
68
69#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
70pub struct StateArenaDebugStats {
71 pub cells_len: usize,
72 pub cells_cap: usize,
73 pub free_len: usize,
74 pub free_cap: usize,
75}
76
77#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
78pub struct RuntimeDebugStats {
79 pub node_updates_len: usize,
80 pub node_updates_cap: usize,
81 pub invalid_scopes_len: usize,
82 pub invalid_scopes_cap: usize,
83 pub scope_queue_len: usize,
84 pub scope_queue_cap: usize,
85 pub frame_callbacks_len: usize,
86 pub frame_callbacks_cap: usize,
87 pub local_tasks_len: usize,
88 pub local_tasks_cap: usize,
89 pub ui_conts_len: usize,
90 pub ui_conts_cap: usize,
91 pub tasks_len: usize,
92 pub tasks_cap: usize,
93 pub external_state_owners_len: usize,
94 pub external_state_owners_cap: usize,
95 pub ui_dispatcher_pending: usize,
96}
97
98#[derive(Default)]
99pub(crate) struct StateArena {
100 inner: RefCell<StateArenaInner>,
101}
102
103impl StateArena {
104 pub(crate) fn alloc<T: Clone + 'static>(&self, value: T, runtime: RuntimeHandle) -> StateId {
105 self.alloc_with_policy(value, runtime, Arc::new(NeverEqual))
106 }
107
108 pub(crate) fn alloc_with_policy<T: Clone + 'static>(
109 &self,
110 value: T,
111 runtime: RuntimeHandle,
112 policy: Arc<dyn MutationPolicy<T>>,
113 ) -> StateId {
114 let (slot, generation) = {
115 let mut inner = self.inner.borrow_mut();
116 loop {
117 let Some(slot) = inner.free.pop() else {
118 let slot = inner.cells.len() as u32;
119 inner.cells.push(StateArenaSlot {
120 generation: 0,
121 cell: None,
122 watcher_cell: None,
123 lease: None,
124 });
125 break (slot, 0);
126 };
127
128 let Some(entry) = inner.cells.get_mut(slot as usize) else {
129 continue;
130 };
131 if entry.cell.is_some() {
132 continue;
133 }
134
135 entry.watcher_cell = None;
136 entry.lease = None;
137 entry.generation = entry.generation.wrapping_add(1);
138 break (slot, entry.generation);
139 }
140 };
141 let id = StateId::new(slot, generation);
142 let inner = MutableStateInner::new_with_policy(value, runtime.clone(), policy);
143 inner.install_snapshot_observer(id);
144 let typed_cell = Rc::new(TypedStateCell { inner });
145 let cell: Rc<dyn Any> = typed_cell.clone();
146 let watcher_cell: Rc<dyn ScopeWatchCell> = typed_cell;
147 let mut arena = self.inner.borrow_mut();
148 let slot_entry = &mut arena.cells[slot as usize];
149 slot_entry.cell = Some(cell);
150 slot_entry.watcher_cell = Some(watcher_cell);
151 id
152 }
153
154 fn get_cell_opt(&self, id: StateId) -> Option<Rc<dyn Any>> {
155 self.inner
156 .borrow()
157 .cells
158 .get(id.slot_index())
159 .filter(|cell| cell.generation == id.generation())
160 .and_then(|cell| cell.cell.as_ref())
161 .cloned()
162 }
163
164 fn get_typed<T: Clone + 'static>(&self, id: StateId) -> Rc<TypedStateCell<T>> {
165 match self.get_cell_opt(id) {
166 None => panic!(
167 "state cell missing: slot={}, gen={}, expected={}",
168 id.slot(),
169 id.generation(),
170 std::any::type_name::<T>(),
171 ),
172 Some(cell) => Rc::downcast::<TypedStateCell<T>>(cell).unwrap_or_else(|_| {
173 panic!(
174 "state cell type mismatch: slot={}, gen={}, expected={}",
175 id.slot(),
176 id.generation(),
177 std::any::type_name::<T>(),
178 )
179 }),
180 }
181 }
182
183 fn get_typed_opt<T: Clone + 'static>(&self, id: StateId) -> Option<Rc<TypedStateCell<T>>> {
184 Rc::downcast::<TypedStateCell<T>>(self.get_cell_opt(id)?).ok()
185 }
186
187 pub(crate) fn with_typed<T: Clone + 'static, R>(
188 &self,
189 id: StateId,
190 f: impl FnOnce(&MutableStateInner<T>) -> R,
191 ) -> R {
192 let cell = self.get_typed::<T>(id);
193 f(&cell.inner)
194 }
195
196 pub(crate) fn with_typed_opt<T: Clone + 'static, R>(
197 &self,
198 id: StateId,
199 f: impl FnOnce(&MutableStateInner<T>) -> R,
200 ) -> Option<R> {
201 let cell = self.get_typed_opt::<T>(id)?;
202 Some(f(&cell.inner))
203 }
204
205 pub(crate) fn release(&self, id: StateId) {
206 let cell = {
207 let mut inner = self.inner.borrow_mut();
208 let Some(slot) = inner.cells.get_mut(id.slot_index()) else {
209 return;
210 };
211 if slot.generation != id.generation() {
212 return;
213 }
214 slot.lease = None;
215 slot.watcher_cell = None;
216 let cell = slot.cell.take();
217 if cell.is_some() {
218 inner.free.push(id.slot());
219 }
220 cell
221 };
222 drop(cell);
223 }
224
225 pub(crate) fn stats(&self) -> (usize, usize) {
226 let inner = self.inner.borrow();
227 (inner.cells.len(), inner.free.len())
228 }
229
230 pub(crate) fn debug_stats(&self) -> StateArenaDebugStats {
231 let inner = self.inner.borrow();
232 StateArenaDebugStats {
233 cells_len: inner.cells.len(),
234 cells_cap: inner.cells.capacity(),
235 free_len: inner.free.len(),
236 free_cap: inner.free.capacity(),
237 }
238 }
239
240 pub(crate) fn unregister_scope(&self, id: StateId, scope_id: ScopeId) {
241 let watcher_cell = {
242 let inner = self.inner.borrow();
243 inner
244 .cells
245 .get(id.slot_index())
246 .filter(|slot| slot.generation == id.generation())
247 .and_then(|slot| slot.watcher_cell.as_ref())
248 .cloned()
249 };
250 if let Some(watcher_cell) = watcher_cell {
251 watcher_cell.unregister_scope(scope_id);
252 }
253 }
254
255 pub(crate) fn register_lease(&self, id: StateId, lease: &Rc<StateHandleLease>) {
256 let mut inner = self.inner.borrow_mut();
257 let Some(slot) = inner.cells.get_mut(id.slot_index()) else {
258 return;
259 };
260 if slot.generation != id.generation() {
261 return;
262 }
263 slot.lease = Some(Rc::downgrade(lease));
264 }
265
266 pub(crate) fn retain_lease(&self, id: StateId) -> Option<Rc<StateHandleLease>> {
267 let inner = self.inner.borrow();
268 let slot = inner.cells.get(id.slot_index())?;
269 if slot.generation != id.generation() {
270 return None;
271 }
272 slot.lease.as_ref()?.upgrade()
273 }
274}
275
276#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
277pub struct StateId {
278 slot: u32,
279 generation: u32,
280}
281
282impl StateId {
283 const fn new(slot: u32, generation: u32) -> Self {
284 Self { slot, generation }
285 }
286
287 pub(crate) const fn slot(self) -> u32 {
288 self.slot
289 }
290
291 pub(crate) const fn slot_index(self) -> usize {
292 self.slot as usize
293 }
294
295 pub(crate) const fn generation(self) -> u32 {
296 self.generation
297 }
298}
299
300#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
301pub struct RuntimeId(u32);
302
303impl RuntimeId {
304 fn next() -> Self {
305 NEXT_RUNTIME_ID.with(|next| {
306 let id = next.get();
307 next.set(id.wrapping_add(1));
308 Self(id)
309 })
310 }
311}
312
313struct UiDispatcherInner {
314 scheduler: SchedulerRef,
315 tx: mpsc::Sender<UiMessage>,
316 pending: AtomicUsize,
317}
318
319#[cfg(not(target_arch = "wasm32"))]
320type UiDispatcherRef = Arc<UiDispatcherInner>;
321
322#[cfg(target_arch = "wasm32")]
323type UiDispatcherRef = Rc<UiDispatcherInner>;
324
325impl UiDispatcherInner {
326 fn new(scheduler: SchedulerRef, tx: mpsc::Sender<UiMessage>) -> Self {
327 Self {
328 scheduler,
329 tx,
330 pending: AtomicUsize::new(0),
331 }
332 }
333
334 fn post(&self, task: impl FnOnce() + Send + 'static) {
335 self.pending.fetch_add(1, Ordering::SeqCst);
336 if self.tx.send(UiMessage::Task(Box::new(task))).is_ok() {
337 self.scheduler.schedule_frame();
338 } else {
339 self.pending.fetch_sub(1, Ordering::SeqCst);
340 }
341 }
342
343 fn post_invoke(&self, id: u64, value: Box<dyn Any + Send>) {
344 self.pending.fetch_add(1, Ordering::SeqCst);
345 if self.tx.send(UiMessage::Invoke { id, value }).is_ok() {
346 self.scheduler.schedule_frame();
347 } else {
348 self.pending.fetch_sub(1, Ordering::SeqCst);
349 }
350 }
351
352 fn has_pending(&self) -> bool {
353 self.pending.load(Ordering::SeqCst) > 0
354 }
355}
356
357struct PendingGuard<'a> {
358 counter: &'a AtomicUsize,
359}
360
361impl<'a> PendingGuard<'a> {
362 fn new(counter: &'a AtomicUsize) -> Self {
363 Self { counter }
364 }
365}
366
367impl<'a> Drop for PendingGuard<'a> {
368 fn drop(&mut self) {
369 let mut current = self.counter.load(Ordering::SeqCst);
370 loop {
371 if current == 0 {
372 return;
373 }
374 match self.counter.compare_exchange(
375 current,
376 current - 1,
377 Ordering::SeqCst,
378 Ordering::SeqCst,
379 ) {
380 Ok(_) => return,
381 Err(next) => current = next,
382 }
383 }
384 }
385}
386
387#[derive(Clone)]
388pub struct UiDispatcher {
389 inner: UiDispatcherRef,
390}
391
392impl UiDispatcher {
393 fn new(inner: UiDispatcherRef) -> Self {
394 Self { inner }
395 }
396
397 pub fn post(&self, task: impl FnOnce() + Send + 'static) {
398 self.inner.post(task);
399 }
400
401 pub fn post_invoke<T>(&self, id: u64, value: T)
402 where
403 T: Send + 'static,
404 {
405 self.inner.post_invoke(id, Box::new(value));
406 }
407
408 pub fn has_pending(&self) -> bool {
409 self.inner.has_pending()
410 }
411}
412
413struct RuntimeInner {
414 scheduler: SchedulerRef,
415 needs_frame: RefCell<bool>,
416 node_updates: RefCell<Vec<Command>>,
417 invalid_scopes: RefCell<HashSet<ScopeId>>,
418 scope_queue: RefCell<Vec<(ScopeId, Weak<RecomposeScopeInner>)>>,
419 frame_callbacks: RefCell<VecDeque<FrameCallbackEntry>>,
420 next_frame_callback_id: Cell<u64>,
421 last_frame_time_nanos: Cell<Option<u64>>,
422 ui_dispatcher: UiDispatcherRef,
423 ui_rx: RefCell<mpsc::Receiver<UiMessage>>,
424 local_tasks: RefCell<VecDeque<Box<dyn FnOnce() + 'static>>>,
425 ui_conts: RefCell<UiContinuationMap>,
426 next_cont_id: Cell<u64>,
427 ui_thread_id: ThreadId,
428 tasks: RefCell<Vec<TaskEntry>>,
429 next_task_id: Cell<u64>,
430 state_arena: StateArena,
431 external_state_owners: RefCell<HashMap<StateId, Rc<StateHandleLease>>>,
432 live_recompose_scope_count: Cell<usize>,
433 forgotten_movables: RefCell<Vec<Key>>,
434 next_movable_content_id: Cell<u64>,
435 runtime_id: RuntimeId,
436}
437
438struct TaskEntry {
439 id: u64,
440 label: String,
441 future: Pin<Box<dyn Future<Output = ()> + 'static>>,
442 runnable: Arc<AtomicBool>,
443 waker: Waker,
444}
445
446thread_local! {
447 static NEXT_TASK_LABEL: RefCell<Option<String>> = const { RefCell::new(None) };
448}
449
450pub fn label_next_ui_task(label: impl Into<String>) {
451 NEXT_TASK_LABEL.with(|held| *held.borrow_mut() = Some(label.into()));
452}
453
454impl RuntimeInner {
455 fn new(scheduler: SchedulerRef) -> Self {
456 let (tx, rx) = mpsc::channel();
457 let dispatcher = UiDispatcherRef::new(UiDispatcherInner::new(scheduler.clone(), tx));
458 Self {
459 scheduler,
460 needs_frame: RefCell::new(false),
461 node_updates: RefCell::new(Vec::new()),
462 invalid_scopes: RefCell::new(HashSet::default()),
463 scope_queue: RefCell::new(Vec::new()),
464 frame_callbacks: RefCell::new(VecDeque::new()),
465 next_frame_callback_id: Cell::new(1),
466 last_frame_time_nanos: Cell::new(None),
467 ui_dispatcher: dispatcher,
468 ui_rx: RefCell::new(rx),
469 local_tasks: RefCell::new(VecDeque::new()),
470 ui_conts: RefCell::new(UiContinuationMap::default()),
471 next_cont_id: Cell::new(1),
472 ui_thread_id: std::thread::current().id(),
473 tasks: RefCell::new(Vec::new()),
474 next_task_id: Cell::new(1),
475 state_arena: StateArena::default(),
476 external_state_owners: RefCell::new(HashMap::default()),
477 live_recompose_scope_count: Cell::new(0),
478 forgotten_movables: RefCell::new(Vec::new()),
479 next_movable_content_id: Cell::new(1),
480 runtime_id: RuntimeId::next(),
481 }
482 }
483
484 fn schedule(&self) {
485 *self.needs_frame.borrow_mut() = true;
486 self.scheduler.schedule_frame();
487 }
488
489 fn enqueue_update(&self, command: Command) {
490 self.node_updates.borrow_mut().push(command);
491 self.schedule();
492 }
493
494 fn take_updates(&self) -> Vec<Command> {
495 self.node_updates.borrow_mut().drain(..).collect::<Vec<_>>()
496 }
497
498 fn has_updates(&self) -> bool {
499 !self.node_updates.borrow().is_empty() || self.has_invalid_scopes()
500 }
501
502 fn register_invalid_scope(&self, id: ScopeId, scope: Weak<RecomposeScopeInner>) {
503 let mut invalid = self.invalid_scopes.borrow_mut();
504 if invalid.insert(id) {
505 self.scope_queue.borrow_mut().push((id, scope));
506 self.schedule();
507 }
508 }
509
510 fn requeue_invalid_scope(&self, id: ScopeId, scope: Weak<RecomposeScopeInner>) {
511 if self.invalid_scopes.borrow().contains(&id) {
512 self.scope_queue.borrow_mut().push((id, scope));
513 self.schedule();
514 }
515 }
516
517 fn mark_scope_recomposed(&self, id: ScopeId) {
518 self.invalid_scopes.borrow_mut().remove(&id);
519 }
520
521 fn take_invalidated_scopes(&self) -> Vec<(ScopeId, Weak<RecomposeScopeInner>)> {
522 let mut queue = self.scope_queue.borrow_mut();
523 if queue.is_empty() {
524 return Vec::new();
525 }
526 let pending: Vec<_> = queue.drain(..).collect();
527 drop(queue);
528 let invalid = self.invalid_scopes.borrow();
529 pending
530 .into_iter()
531 .filter(|(id, _)| invalid.contains(id))
532 .collect()
533 }
534
535 fn has_invalid_scopes(&self) -> bool {
536 !self.invalid_scopes.borrow().is_empty()
537 }
538
539 fn increment_live_recompose_scope_count(&self) {
540 self.live_recompose_scope_count
541 .set(self.live_recompose_scope_count.get().saturating_add(1));
542 }
543
544 fn decrement_live_recompose_scope_count(&self) {
545 self.live_recompose_scope_count
546 .set(self.live_recompose_scope_count.get().saturating_sub(1));
547 }
548
549 fn live_recompose_scope_count(&self) -> usize {
550 self.live_recompose_scope_count.get()
551 }
552
553 fn has_frame_callbacks(&self) -> bool {
554 !self.frame_callbacks.borrow().is_empty()
555 }
556
557 fn has_transient_frame_callbacks(&self) -> bool {
558 self.frame_callbacks
559 .borrow()
560 .iter()
561 .any(|entry| entry.kind == FrameCallbackKind::Transient)
562 }
563
564 fn enqueue_ui_task(&self, task: Box<dyn FnOnce() + 'static>) {
565 self.local_tasks.borrow_mut().push_back(task);
566 self.schedule();
567 }
568
569 fn spawn_ui_task(&self, future: Pin<Box<dyn Future<Output = ()> + 'static>>) -> u64 {
570 let id = self.next_task_id.get();
571 self.next_task_id.set(id + 1);
572 let label = NEXT_TASK_LABEL
573 .with(|held| held.borrow_mut().take())
574 .unwrap_or_else(|| "unnamed".to_string());
575 let runnable = Arc::new(AtomicBool::new(true));
576 let waker = RuntimeTaskWaker::new(self, Arc::clone(&runnable)).into_waker();
577 self.tasks.borrow_mut().push(TaskEntry {
578 id,
579 label,
580 future,
581 runnable,
582 waker,
583 });
584 self.schedule();
585 id
586 }
587
588 fn cancel_task(&self, id: u64) {
589 let mut tasks = self.tasks.borrow_mut();
590 if tasks.iter().any(|entry| entry.id == id) {
591 tasks.retain(|entry| entry.id != id);
592 }
593 }
594
595 fn has_task(&self, id: u64) -> bool {
596 self.tasks
597 .try_borrow()
598 .map(|tasks| tasks.iter().any(|entry| entry.id == id))
599 .unwrap_or(true)
600 }
601
602 fn poll_async_tasks(&self) -> bool {
603 let mut tasks_ref = self.tasks.borrow_mut();
604 let tasks = std::mem::take(&mut *tasks_ref);
605 drop(tasks_ref);
606 let mut pending = Vec::with_capacity(tasks.len());
607 let mut made_progress = false;
608 for mut entry in tasks.into_iter() {
609 if !entry.runnable.swap(false, Ordering::AcqRel) {
610 pending.push(entry);
611 continue;
612 }
613 let mut cx = Context::from_waker(&entry.waker);
614 match entry.future.as_mut().poll(&mut cx) {
615 Poll::Ready(()) => {
616 made_progress = true;
617 }
618 Poll::Pending => {
619 pending.push(entry);
620 }
621 }
622 }
623 if !pending.is_empty() {
624 self.tasks.borrow_mut().extend(pending);
625 }
626 made_progress
627 }
628
629 fn drain_ui(&self) {
630 loop {
631 let mut executed = false;
632
633 {
634 let rx = &mut *self.ui_rx.borrow_mut();
635 for message in rx.try_iter() {
636 executed = true;
637 let _guard = PendingGuard::new(&self.ui_dispatcher.pending);
638 match message {
639 UiMessage::Task(task) => {
640 task();
641 }
642 UiMessage::Invoke { id, value } => {
643 self.invoke_ui_cont(id, value);
644 }
645 }
646 }
647 }
648
649 loop {
650 let task = {
651 let mut local = self.local_tasks.borrow_mut();
652 local.pop_front()
653 };
654
655 match task {
656 Some(task) => {
657 executed = true;
658 task();
659 }
660 None => break,
661 }
662 }
663
664 if self.poll_async_tasks() {
665 executed = true;
666 }
667
668 if !executed {
669 break;
670 }
671 }
672
673 self.clear_needs_frame_if_idle();
674 }
675
676 fn has_pending_ui(&self) -> bool {
677 let local_pending = self
678 .local_tasks
679 .try_borrow()
680 .map(|tasks| !tasks.is_empty())
681 .unwrap_or(true);
682
683 local_pending || self.ui_dispatcher.has_pending() || self.has_runnable_tasks()
684 }
685
686 fn has_runnable_tasks(&self) -> bool {
687 self.tasks
688 .try_borrow()
689 .map(|tasks| {
690 tasks
691 .iter()
692 .any(|task| task.runnable.load(Ordering::Acquire))
693 })
694 .unwrap_or(true)
695 }
696
697 fn register_ui_cont<T: 'static>(&self, f: impl FnOnce(T) + 'static) -> u64 {
698 debug_assert_eq!(
699 std::thread::current().id(),
700 self.ui_thread_id,
701 "UI continuation registered off the runtime thread",
702 );
703 let id = self.next_cont_id.get();
704 self.next_cont_id.set(id + 1);
705 let callback = RefCell::new(Some(f));
706 self.ui_conts.borrow_mut().insert(
707 id,
708 Box::new(move |value: Box<dyn Any>| {
709 let Ok(value) = value.downcast::<T>() else {
710 return false;
711 };
712 let Some(slot) = callback.borrow_mut().take() else {
713 return true;
714 };
715 slot(*value);
716 true
717 }),
718 );
719 id
720 }
721
722 fn invoke_ui_cont(&self, id: u64, value: Box<dyn Any + Send>) {
723 debug_assert_eq!(
724 std::thread::current().id(),
725 self.ui_thread_id,
726 "UI continuation invoked off the runtime thread",
727 );
728 let callback = { self.ui_conts.borrow_mut().remove(&id) };
729 if let Some(callback) = callback {
730 let value: Box<dyn Any> = value;
731 if !callback(value) {
732 self.ui_conts.borrow_mut().insert(id, callback);
733 }
734 }
735 }
736
737 fn cancel_ui_cont(&self, id: u64) {
738 self.ui_conts.borrow_mut().remove(&id);
739 }
740
741 fn register_frame_callback(
742 &self,
743 kind: FrameCallbackKind,
744 callback: Box<dyn FnOnce(u64) + 'static>,
745 ) -> FrameCallbackId {
746 let id = self.next_frame_callback_id.get();
747 self.next_frame_callback_id.set(id + 1);
748 self.frame_callbacks
749 .borrow_mut()
750 .push_back(FrameCallbackEntry {
751 id,
752 kind,
753 callback: Some(callback),
754 });
755 self.schedule();
756 id
757 }
758
759 fn cancel_frame_callback(&self, id: FrameCallbackId) {
760 let mut callbacks = self.frame_callbacks.borrow_mut();
761 if let Some(index) = callbacks.iter().position(|entry| entry.id == id) {
762 callbacks.remove(index);
763 }
764 drop(callbacks);
765 self.clear_needs_frame_if_idle();
766 }
767
768 fn clear_needs_frame_if_idle(&self) {
769 if !self.has_invalid_scopes()
770 && !self.has_updates()
771 && !self.has_frame_callbacks()
772 && !self.has_pending_ui()
773 {
774 *self.needs_frame.borrow_mut() = false;
775 }
776 }
777
778 fn drain_frame_callbacks(&self, frame_time_nanos: u64) {
779 self.last_frame_time_nanos.set(Some(frame_time_nanos));
780 let mut callbacks = self.frame_callbacks.borrow_mut();
781 let mut pending: Vec<Box<dyn FnOnce(u64) + 'static>> = Vec::with_capacity(callbacks.len());
782 while let Some(mut entry) = callbacks.pop_front() {
783 if let Some(callback) = entry.callback.take() {
784 pending.push(callback);
785 }
786 }
787 drop(callbacks);
788
789 if !pending.is_empty() {
790 let _ = crate::run_in_mutable_snapshot(|| {
791 for callback in pending {
792 callback(frame_time_nanos);
793 }
794 });
795 }
796
797 self.clear_needs_frame_if_idle();
798 }
799
800 fn debug_stats(&self) -> RuntimeDebugStats {
801 let node_updates = self.node_updates.borrow();
802 let invalid_scopes = self.invalid_scopes.borrow();
803 let scope_queue = self.scope_queue.borrow();
804 let frame_callbacks = self.frame_callbacks.borrow();
805 let local_tasks = self.local_tasks.borrow();
806 let ui_conts = self.ui_conts.borrow();
807 let tasks = self.tasks.borrow();
808 let external_state_owners = self.external_state_owners.borrow();
809
810 RuntimeDebugStats {
811 node_updates_len: node_updates.len(),
812 node_updates_cap: node_updates.capacity(),
813 invalid_scopes_len: invalid_scopes.len(),
814 invalid_scopes_cap: invalid_scopes.capacity(),
815 scope_queue_len: scope_queue.len(),
816 scope_queue_cap: scope_queue.capacity(),
817 frame_callbacks_len: frame_callbacks.len(),
818 frame_callbacks_cap: frame_callbacks.capacity(),
819 local_tasks_len: local_tasks.len(),
820 local_tasks_cap: local_tasks.capacity(),
821 ui_conts_len: ui_conts.len(),
822 ui_conts_cap: ui_conts.capacity(),
823 tasks_len: tasks.len(),
824 tasks_cap: tasks.capacity(),
825 external_state_owners_len: external_state_owners.len(),
826 external_state_owners_cap: external_state_owners.capacity(),
827 ui_dispatcher_pending: self.ui_dispatcher.pending.load(Ordering::SeqCst),
828 }
829 }
830}
831
832#[derive(Clone)]
833pub struct Runtime {
834 inner: Rc<RuntimeInner>,
835}
836
837impl Runtime {
838 pub fn new(scheduler: SchedulerRef) -> Self {
839 let inner = Rc::new(RuntimeInner::new(scheduler));
840 let runtime = Self { inner };
841 let handle = runtime.handle();
842 register_runtime_handle(&handle);
843 LAST_RUNTIME.with(|slot| *slot.borrow_mut() = Some(handle));
844 runtime
845 }
846
847 pub fn handle(&self) -> RuntimeHandle {
848 RuntimeHandle {
849 inner: Rc::downgrade(&self.inner),
850 dispatcher: UiDispatcher::new(self.inner.ui_dispatcher.clone()),
851 ui_thread_id: self.inner.ui_thread_id,
852 id: self.inner.runtime_id,
853 }
854 }
855
856 pub fn has_updates(&self) -> bool {
857 self.inner.has_updates()
858 }
859
860 pub fn needs_frame(&self) -> bool {
861 *self.inner.needs_frame.borrow() || self.inner.has_runnable_tasks()
862 }
863
864 pub fn set_needs_frame(&self, value: bool) {
865 *self.inner.needs_frame.borrow_mut() = value;
866 }
867
868 pub fn last_frame_time_nanos(&self) -> Option<u64> {
873 self.inner.last_frame_time_nanos.get()
874 }
875
876 #[cfg(any(feature = "internal", test))]
877 pub fn frame_clock(&self) -> FrameClock {
878 FrameClock::new(self.handle())
879 }
880}
881
882impl Drop for Runtime {
883 fn drop(&mut self) {
884 if Rc::strong_count(&self.inner) != 1 {
885 return;
886 }
887 unregister_runtime_handle(self.inner.runtime_id);
888 LAST_RUNTIME.with(|slot| {
889 let should_clear = slot
890 .borrow()
891 .as_ref()
892 .is_some_and(|handle| handle.id() == self.inner.runtime_id);
893 if should_clear {
894 *slot.borrow_mut() = None;
895 }
896 });
897 }
898}
899
900#[derive(Default)]
901pub struct DefaultScheduler;
902
903impl RuntimeScheduler for DefaultScheduler {
904 fn schedule_frame(&self) {}
905}
906
907#[cfg(test)]
908#[derive(Default)]
909pub struct TestScheduler;
910
911#[cfg(test)]
912impl RuntimeScheduler for TestScheduler {
913 fn schedule_frame(&self) {}
914}
915
916#[cfg(test)]
917pub struct TestRuntime {
918 runtime: Runtime,
919}
920
921#[cfg(test)]
922impl Default for TestRuntime {
923 fn default() -> Self {
924 Self::new()
925 }
926}
927
928#[cfg(test)]
929impl TestRuntime {
930 pub fn new() -> Self {
931 Self {
932 runtime: Runtime::new(Arc::new(TestScheduler)),
933 }
934 }
935
936 pub fn handle(&self) -> RuntimeHandle {
937 self.runtime.handle()
938 }
939}
940
941#[derive(Clone)]
942pub struct RuntimeHandle {
943 inner: Weak<RuntimeInner>,
944 dispatcher: UiDispatcher,
945 ui_thread_id: ThreadId,
946 id: RuntimeId,
947}
948
949pub struct TaskHandle {
950 id: u64,
951 runtime: RuntimeHandle,
952}
953
954struct DeferredStateRelease {
955 runtime: RuntimeHandle,
956 id: StateId,
957}
958
959pub(crate) struct StateHandleLease {
960 id: StateId,
961 runtime: RuntimeHandle,
962}
963
964impl StateHandleLease {
965 pub(crate) fn id(&self) -> StateId {
966 self.id
967 }
968
969 pub(crate) fn runtime(&self) -> RuntimeHandle {
970 self.runtime.clone()
971 }
972}
973
974impl Drop for StateHandleLease {
975 fn drop(&mut self) {
976 defer_state_release(self.runtime.clone(), self.id);
977 }
978}
979
980thread_local! {
981 static STATE_OWNERS: RefCell<Vec<Vec<Rc<StateHandleLease>>>> =
982 const { RefCell::new(Vec::new()) };
983}
984
985struct StateOwnerFrame;
986
987impl Drop for StateOwnerFrame {
988 fn drop(&mut self) {
989 STATE_OWNERS.with(|owners| owners.borrow_mut().pop());
990 }
991}
992
993pub(crate) fn collecting_states<T>(build: impl FnOnce() -> T) -> (T, Vec<Rc<StateHandleLease>>) {
1011 STATE_OWNERS.with(|owners| owners.borrow_mut().push(Vec::new()));
1012 let frame = StateOwnerFrame;
1013 let value = build();
1014 let states = STATE_OWNERS.with(|owners| {
1015 owners
1016 .borrow_mut()
1017 .last_mut()
1018 .map(std::mem::take)
1019 .unwrap_or_default()
1020 });
1021 drop(frame);
1022 (value, states)
1023}
1024
1025fn hand_to_current_owner(lease: &Rc<StateHandleLease>) -> bool {
1026 STATE_OWNERS.with(|owners| match owners.borrow_mut().last_mut() {
1027 Some(owner) => {
1028 owner.push(Rc::clone(lease));
1029 true
1030 }
1031 None => false,
1032 })
1033}
1034
1035impl RuntimeHandle {
1036 pub fn id(&self) -> RuntimeId {
1037 self.id
1038 }
1039
1040 pub(crate) fn alloc_state<T: Clone + 'static>(&self, value: T) -> Rc<StateHandleLease> {
1041 let id = self.with_state_arena(|arena| arena.alloc(value, self.clone()));
1042 let lease = Rc::new(StateHandleLease {
1043 id,
1044 runtime: self.clone(),
1045 });
1046 self.with_state_arena(|arena| arena.register_lease(id, &lease));
1047 lease
1048 }
1049
1050 pub(crate) fn alloc_state_with_policy<T: Clone + 'static>(
1051 &self,
1052 value: T,
1053 policy: Arc<dyn MutationPolicy<T>>,
1054 ) -> Rc<StateHandleLease> {
1055 let id =
1056 self.with_state_arena(|arena| arena.alloc_with_policy(value, self.clone(), policy));
1057 let lease = Rc::new(StateHandleLease {
1058 id,
1059 runtime: self.clone(),
1060 });
1061 self.with_state_arena(|arena| arena.register_lease(id, &lease));
1062 lease
1063 }
1064
1065 pub(crate) fn alloc_persistent_state<T: Clone + 'static>(
1066 &self,
1067 value: T,
1068 ) -> crate::MutableState<T> {
1069 self.hand_out(self.alloc_state(value))
1070 }
1071
1072 pub(crate) fn alloc_persistent_state_with_policy<T: Clone + 'static>(
1073 &self,
1074 value: T,
1075 policy: Arc<dyn MutationPolicy<T>>,
1076 ) -> crate::MutableState<T> {
1077 self.hand_out(self.alloc_state_with_policy(value, policy))
1078 }
1079
1080 fn hand_out<T: Clone + 'static>(&self, lease: Rc<StateHandleLease>) -> crate::MutableState<T> {
1081 if !hand_to_current_owner(&lease)
1082 && let Some(inner) = self.inner.upgrade()
1083 {
1084 inner
1085 .external_state_owners
1086 .borrow_mut()
1087 .insert(lease.id(), Rc::clone(&lease));
1088 }
1089 crate::MutableState::from_lease(&lease)
1090 }
1091
1092 pub(crate) fn retain_state_lease(&self, id: StateId) -> Option<Rc<StateHandleLease>> {
1093 self.with_state_arena(|arena| arena.retain_lease(id))
1094 }
1095
1096 pub(crate) fn with_state_arena<R>(&self, f: impl FnOnce(&StateArena) -> R) -> R {
1097 self.try_with_state_arena(f)
1098 .unwrap_or_else(|| panic!("runtime dropped"))
1099 }
1100
1101 pub(crate) fn try_with_state_arena<R>(&self, f: impl FnOnce(&StateArena) -> R) -> Option<R> {
1102 self.inner.upgrade().map(|inner| f(&inner.state_arena))
1103 }
1104
1105 fn release_state_immediate(&self, id: StateId) {
1106 if let Some(inner) = self.inner.upgrade() {
1107 inner.state_arena.release(id);
1108 }
1109 }
1110
1111 pub fn state_arena_stats(&self) -> (usize, usize) {
1112 self.try_with_state_arena(StateArena::stats)
1113 .unwrap_or_default()
1114 }
1115
1116 pub fn state_arena_debug_stats(&self) -> StateArenaDebugStats {
1117 self.try_with_state_arena(StateArena::debug_stats)
1118 .unwrap_or_default()
1119 }
1120
1121 pub fn debug_stats(&self) -> RuntimeDebugStats {
1122 self.inner
1123 .upgrade()
1124 .map(|inner| inner.debug_stats())
1125 .unwrap_or_default()
1126 }
1127
1128 pub fn live_ui_task_labels(&self) -> Vec<(u64, String)> {
1129 self.inner
1130 .upgrade()
1131 .map(|inner| {
1132 inner
1133 .tasks
1134 .borrow()
1135 .iter()
1136 .map(|entry| (entry.id, entry.label.clone()))
1137 .collect()
1138 })
1139 .unwrap_or_default()
1140 }
1141
1142 pub(crate) fn unregister_state_scope(&self, id: StateId, scope_id: ScopeId) {
1143 if let Some(inner) = self.inner.upgrade() {
1144 inner.state_arena.unregister_scope(id, scope_id);
1145 }
1146 }
1147
1148 pub fn schedule(&self) {
1149 if let Some(inner) = self.inner.upgrade() {
1150 inner.schedule();
1151 }
1152 }
1153
1154 pub(crate) fn enqueue_node_update(&self, command: Command) {
1155 if let Some(inner) = self.inner.upgrade() {
1156 inner.enqueue_update(command);
1157 }
1158 }
1159
1160 pub fn enqueue_ui_task(&self, task: Box<dyn FnOnce() + 'static>) {
1167 if let Some(inner) = self.inner.upgrade() {
1168 inner.enqueue_ui_task(task);
1169 } else {
1170 task();
1171 }
1172 }
1173
1174 pub fn spawn_ui<F>(&self, fut: F) -> Option<TaskHandle>
1175 where
1176 F: Future<Output = ()> + 'static,
1177 {
1178 self.inner.upgrade().map(|inner| {
1179 let id = inner.spawn_ui_task(Box::pin(fut));
1180 TaskHandle {
1181 id,
1182 runtime: self.clone(),
1183 }
1184 })
1185 }
1186
1187 pub fn cancel_task(&self, id: u64) {
1188 if let Some(inner) = self.inner.upgrade() {
1189 inner.cancel_task(id);
1190 }
1191 }
1192
1193 pub fn has_task(&self, id: u64) -> bool {
1195 self.inner
1196 .upgrade()
1197 .map(|inner| inner.has_task(id))
1198 .unwrap_or(false)
1199 }
1200
1201 pub fn post_ui(&self, task: impl FnOnce() + Send + 'static) {
1206 self.dispatcher.post(task);
1207 }
1208
1209 pub fn register_ui_cont<T: 'static>(&self, f: impl FnOnce(T) + 'static) -> Option<u64> {
1210 self.inner.upgrade().map(|inner| inner.register_ui_cont(f))
1211 }
1212
1213 pub fn cancel_ui_cont(&self, id: u64) {
1214 if let Some(inner) = self.inner.upgrade() {
1215 inner.cancel_ui_cont(id);
1216 }
1217 }
1218
1219 pub fn drain_ui(&self) {
1220 if let Some(inner) = self.inner.upgrade() {
1221 inner.drain_ui();
1222 }
1223 }
1224
1225 pub fn has_pending_ui(&self) -> bool {
1226 self.inner
1227 .upgrade()
1228 .map(|inner| inner.has_pending_ui())
1229 .unwrap_or_else(|| self.dispatcher.has_pending())
1230 }
1231
1232 pub fn register_frame_callback(
1233 &self,
1234 callback: impl FnOnce(u64) + 'static,
1235 ) -> Option<FrameCallbackId> {
1236 self.inner.upgrade().map(|inner| {
1237 inner.register_frame_callback(FrameCallbackKind::Transient, Box::new(callback))
1238 })
1239 }
1240
1241 pub fn register_perpetual_frame_callback(
1242 &self,
1243 callback: impl FnOnce(u64) + 'static,
1244 ) -> Option<FrameCallbackId> {
1245 self.inner.upgrade().map(|inner| {
1246 inner.register_frame_callback(FrameCallbackKind::Perpetual, Box::new(callback))
1247 })
1248 }
1249
1250 pub fn cancel_frame_callback(&self, id: FrameCallbackId) {
1251 if let Some(inner) = self.inner.upgrade() {
1252 inner.cancel_frame_callback(id);
1253 }
1254 }
1255
1256 pub fn drain_frame_callbacks(&self, frame_time_nanos: u64) {
1257 if let Some(inner) = self.inner.upgrade() {
1258 inner.drain_frame_callbacks(frame_time_nanos);
1259 }
1260 }
1261
1262 pub fn last_frame_time_nanos(&self) -> Option<u64> {
1265 self.inner
1266 .upgrade()
1267 .and_then(|inner| inner.last_frame_time_nanos.get())
1268 }
1269
1270 #[cfg(any(feature = "internal", test))]
1271 pub fn frame_clock(&self) -> FrameClock {
1272 FrameClock::new(self.clone())
1273 }
1274
1275 pub fn set_needs_frame(&self, value: bool) {
1276 if let Some(inner) = self.inner.upgrade() {
1277 *inner.needs_frame.borrow_mut() = value;
1278 }
1279 }
1280
1281 pub(crate) fn take_updates(&self) -> Vec<Command> {
1282 self.inner
1283 .upgrade()
1284 .map(|inner| inner.take_updates())
1285 .unwrap_or_default()
1286 }
1287
1288 pub fn has_updates(&self) -> bool {
1289 self.inner
1290 .upgrade()
1291 .map(|inner| inner.has_updates())
1292 .unwrap_or(false)
1293 }
1294
1295 pub(crate) fn mark_scope_recomposed(&self, id: ScopeId) {
1296 if let Some(inner) = self.inner.upgrade() {
1297 inner.mark_scope_recomposed(id);
1298 }
1299 }
1300
1301 pub(crate) fn register_invalid_scope(&self, id: ScopeId, scope: Weak<RecomposeScopeInner>) {
1302 if let Some(inner) = self.inner.upgrade() {
1303 inner.register_invalid_scope(id, scope);
1304 }
1305 }
1306
1307 pub(crate) fn requeue_invalid_scope(&self, id: ScopeId, scope: Weak<RecomposeScopeInner>) {
1308 if let Some(inner) = self.inner.upgrade() {
1309 inner.requeue_invalid_scope(id, scope);
1310 }
1311 }
1312
1313 pub(crate) fn take_invalidated_scopes(&self) -> Vec<(ScopeId, Weak<RecomposeScopeInner>)> {
1314 self.inner
1315 .upgrade()
1316 .map(|inner| inner.take_invalidated_scopes())
1317 .unwrap_or_default()
1318 }
1319
1320 pub fn forget_movable(&self, id: Key) {
1324 if let Some(inner) = self.inner.upgrade() {
1325 inner.forgotten_movables.borrow_mut().push(id);
1326 inner.schedule();
1327 }
1328 }
1329
1330 pub(crate) fn take_forgotten_movables(&self) -> Vec<Key> {
1331 self.inner
1332 .upgrade()
1333 .map(|inner| std::mem::take(&mut *inner.forgotten_movables.borrow_mut()))
1334 .unwrap_or_default()
1335 }
1336
1337 pub(crate) fn next_movable_content_id(&self) -> Key {
1342 let Some(inner) = self.inner.upgrade() else {
1343 log::error!("movable content asked a runtime that is gone for an identity");
1344 return 0;
1345 };
1346 let id = inner.next_movable_content_id.get();
1347 inner.next_movable_content_id.set(id.wrapping_add(1).max(1));
1348 id
1349 }
1350
1351 pub fn has_invalid_scopes(&self) -> bool {
1352 self.inner
1353 .upgrade()
1354 .map(|inner| inner.has_invalid_scopes())
1355 .unwrap_or(false)
1356 }
1357
1358 pub(crate) fn increment_live_recompose_scope_count(&self) {
1359 if let Some(inner) = self.inner.upgrade() {
1360 inner.increment_live_recompose_scope_count();
1361 }
1362 }
1363
1364 pub(crate) fn decrement_live_recompose_scope_count(&self) {
1365 if let Some(inner) = self.inner.upgrade() {
1366 inner.decrement_live_recompose_scope_count();
1367 }
1368 }
1369
1370 fn live_recompose_scope_count(&self) -> usize {
1371 self.inner
1372 .upgrade()
1373 .map(|inner| inner.live_recompose_scope_count())
1374 .unwrap_or_default()
1375 }
1376
1377 #[doc(hidden)]
1378 pub fn debug_invalid_scope_ids(&self) -> Vec<usize> {
1379 self.inner
1380 .upgrade()
1381 .map(|inner| inner.invalid_scopes.borrow().iter().copied().collect())
1382 .unwrap_or_default()
1383 }
1384
1385 pub fn has_frame_callbacks(&self) -> bool {
1386 self.inner
1387 .upgrade()
1388 .map(|inner| inner.has_frame_callbacks())
1389 .unwrap_or(false)
1390 }
1391
1392 pub fn has_transient_frame_callbacks(&self) -> bool {
1393 self.inner
1394 .upgrade()
1395 .map(|inner| inner.has_transient_frame_callbacks())
1396 .unwrap_or(false)
1397 }
1398
1399 pub fn assert_ui_thread(&self) {
1400 debug_assert_eq!(
1401 std::thread::current().id(),
1402 self.ui_thread_id,
1403 "state mutated off the runtime's UI thread"
1404 );
1405 }
1406
1407 pub fn dispatcher(&self) -> UiDispatcher {
1408 self.dispatcher.clone()
1409 }
1410
1411 #[doc(hidden)]
1412 pub fn with_deferred_state_releases<R>(&self, f: impl FnOnce() -> R) -> R {
1413 let _scope = enter_state_teardown_scope();
1414 f()
1415 }
1416}
1417
1418impl TaskHandle {
1419 pub fn cancel(&self) {
1420 self.runtime.cancel_task(self.id);
1421 }
1422
1423 pub fn is_finished(&self) -> bool {
1425 !self.runtime.has_task(self.id)
1426 }
1427}
1428
1429pub(crate) struct FrameCallbackEntry {
1430 id: FrameCallbackId,
1431 kind: FrameCallbackKind,
1432 callback: Option<Box<dyn FnOnce(u64) + 'static>>,
1433}
1434
1435#[cfg(not(target_arch = "wasm32"))]
1436struct RuntimeTaskWaker {
1437 scheduler: SchedulerRef,
1438 runnable: Arc<AtomicBool>,
1439}
1440
1441#[cfg(target_arch = "wasm32")]
1442struct RuntimeTaskWaker {
1443 runtime_id: RuntimeId,
1444 runnable: Arc<AtomicBool>,
1445}
1446
1447impl RuntimeTaskWaker {
1448 #[cfg(not(target_arch = "wasm32"))]
1449 fn new(inner: &RuntimeInner, runnable: Arc<AtomicBool>) -> Self {
1450 let scheduler = inner.scheduler.clone();
1451 Self {
1452 scheduler,
1453 runnable,
1454 }
1455 }
1456
1457 #[cfg(target_arch = "wasm32")]
1458 fn new(inner: &RuntimeInner, runnable: Arc<AtomicBool>) -> Self {
1459 let runtime_id = inner.runtime_id;
1460 Self {
1461 runtime_id,
1462 runnable,
1463 }
1464 }
1465
1466 fn into_waker(self) -> Waker {
1467 futures_task::waker(Arc::new(self))
1468 }
1469}
1470
1471impl futures_task::ArcWake for RuntimeTaskWaker {
1472 #[cfg(not(target_arch = "wasm32"))]
1473 fn wake_by_ref(arc_self: &Arc<Self>) {
1474 arc_self.runnable.store(true, Ordering::Release);
1475 arc_self.scheduler.schedule_frame();
1476 }
1477
1478 #[cfg(target_arch = "wasm32")]
1479 fn wake_by_ref(arc_self: &Arc<Self>) {
1480 arc_self.runnable.store(true, Ordering::Release);
1481 REGISTERED_RUNTIMES.with(|registry| {
1482 if let Some(handle) = registry.borrow().get(&arc_self.runtime_id).cloned() {
1483 handle.schedule();
1484 }
1485 });
1486 }
1487}
1488
1489thread_local! {
1490 static NEXT_RUNTIME_ID: Cell<u32> = const { Cell::new(1) };
1491 static ACTIVE_RUNTIMES: RefCell<Vec<RuntimeHandle>> = const { RefCell::new(Vec::new()) };
1492 static LAST_RUNTIME: RefCell<Option<RuntimeHandle>> = const { RefCell::new(None) };
1493 static REGISTERED_RUNTIMES: RefCell<HashMap<RuntimeId, RuntimeHandle>> = RefCell::new(HashMap::default());
1494 static STATE_TEARDOWN_DEPTH: Cell<usize> = const { Cell::new(0) };
1495 static DEFERRED_STATE_RELEASES: RefCell<Vec<DeferredStateRelease>> = const { RefCell::new(Vec::new()) };
1496}
1497
1498#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1499pub struct RuntimeThreadLocalDebugStats {
1500 pub active_runtimes_len: usize,
1501 pub active_runtimes_cap: usize,
1502 pub registered_runtimes_len: usize,
1503 pub registered_runtimes_cap: usize,
1504 pub deferred_state_releases_len: usize,
1505 pub deferred_state_releases_cap: usize,
1506}
1507
1508pub fn current_runtime_handle() -> Option<RuntimeHandle> {
1513 if let Some(handle) = ACTIVE_RUNTIMES.with(|stack| stack.borrow().last().cloned()) {
1514 return Some(handle);
1515 }
1516 LAST_RUNTIME.with(|slot| slot.borrow().clone())
1517}
1518
1519pub(crate) fn runtime_handle_by_id(id: RuntimeId) -> Option<RuntimeHandle> {
1520 REGISTERED_RUNTIMES.with(|registry| registry.borrow().get(&id).cloned())
1521}
1522
1523pub(crate) fn live_recompose_scope_count() -> usize {
1524 REGISTERED_RUNTIMES.with(|registry| {
1525 registry
1526 .borrow()
1527 .values()
1528 .map(RuntimeHandle::live_recompose_scope_count)
1529 .sum()
1530 })
1531}
1532
1533pub fn debug_runtime_thread_local_stats() -> RuntimeThreadLocalDebugStats {
1534 let (active_runtimes_len, active_runtimes_cap) = ACTIVE_RUNTIMES.with(|stack| {
1535 let stack = stack.borrow();
1536 (stack.len(), stack.capacity())
1537 });
1538 let (registered_runtimes_len, registered_runtimes_cap) = REGISTERED_RUNTIMES.with(|registry| {
1539 let registry = registry.borrow();
1540 (registry.len(), registry.capacity())
1541 });
1542 let (deferred_state_releases_len, deferred_state_releases_cap) =
1543 DEFERRED_STATE_RELEASES.with(|releases| {
1544 let releases = releases.borrow();
1545 (releases.len(), releases.capacity())
1546 });
1547
1548 RuntimeThreadLocalDebugStats {
1549 active_runtimes_len,
1550 active_runtimes_cap,
1551 registered_runtimes_len,
1552 registered_runtimes_cap,
1553 deferred_state_releases_len,
1554 deferred_state_releases_cap,
1555 }
1556}
1557
1558fn register_runtime_handle(handle: &RuntimeHandle) {
1559 REGISTERED_RUNTIMES.with(|registry| {
1560 registry.borrow_mut().insert(handle.id(), handle.clone());
1561 });
1562}
1563
1564fn unregister_runtime_handle(id: RuntimeId) {
1565 REGISTERED_RUNTIMES.with(|registry| {
1566 registry.borrow_mut().remove(&id);
1567 });
1568}
1569
1570fn defer_state_release(runtime: RuntimeHandle, id: StateId) {
1571 let teardown_active = STATE_TEARDOWN_DEPTH.with(|depth| depth.get() > 0);
1572 if teardown_active {
1573 DEFERRED_STATE_RELEASES.with(|releases| {
1574 releases
1575 .borrow_mut()
1576 .push(DeferredStateRelease { runtime, id });
1577 });
1578 } else {
1579 runtime.release_state_immediate(id);
1580 }
1581}
1582
1583fn flush_deferred_state_releases() {
1584 DEFERRED_STATE_RELEASES.with(|releases| {
1585 let mut releases = releases.borrow_mut();
1586 while let Some(deferred) = releases.pop() {
1587 deferred.runtime.release_state_immediate(deferred.id);
1588 }
1589 });
1590}
1591
1592pub(crate) struct StateTeardownScope;
1593
1594pub(crate) fn enter_state_teardown_scope() -> StateTeardownScope {
1595 STATE_TEARDOWN_DEPTH.with(|depth| depth.set(depth.get() + 1));
1596 StateTeardownScope
1597}
1598
1599impl Drop for StateTeardownScope {
1600 fn drop(&mut self) {
1601 STATE_TEARDOWN_DEPTH.with(|depth| {
1602 let next = depth.get().saturating_sub(1);
1603 depth.set(next);
1604 if next == 0 {
1605 flush_deferred_state_releases();
1606 }
1607 });
1608 }
1609}
1610
1611pub(crate) fn push_active_runtime(handle: &RuntimeHandle) {
1612 register_runtime_handle(handle);
1613 ACTIVE_RUNTIMES.with(|stack| stack.borrow_mut().push(handle.clone()));
1614 LAST_RUNTIME.with(|slot| *slot.borrow_mut() = Some(handle.clone()));
1615}
1616
1617pub(crate) fn pop_active_runtime() {
1618 ACTIVE_RUNTIMES.with(|stack| {
1619 stack.borrow_mut().pop();
1620 });
1621}
1622
1623pub fn schedule_frame() {
1625 if let Some(handle) = current_runtime_handle() {
1626 handle.schedule();
1627 return;
1628 }
1629 log::debug!(
1630 target: "cranpose::runtime",
1631 "ignoring frame request without an active runtime",
1632 );
1633}
1634
1635pub fn schedule_node_update(
1637 update: impl FnOnce(&mut dyn Applier) -> Result<(), NodeError> + 'static,
1638) {
1639 if let Some(handle) = current_runtime_handle() {
1640 handle.enqueue_node_update(Command::callback(update));
1641 } else {
1642 drop(update);
1643 log::debug!(
1644 target: "cranpose::runtime",
1645 "ignoring node update request without an active runtime",
1646 );
1647 }
1648}
1649
1650#[cfg(test)]
1651#[path = "tests/runtime_tests.rs"]
1652mod tests;