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#[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#[derive(Clone)]
150pub struct UiDispatcher {
151 inner: UiDispatcherRef,
152}
153
154impl UiDispatcher {
155 fn new(inner: UiDispatcherRef) -> Self {
156 Self { inner }
157 }
158
159 pub fn post(&self, task: impl FnOnce() + Send + 'static) {
162 self.inner.post(task);
163 }
164
165 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 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 spare_scopes: RefCell<Vec<RecomposeScope>>,
188 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 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 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 if scopes.len() > 1 {
324 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 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 #[inline(never)]
423 fn poll_async_tasks(&self) -> bool {
424 let mut order = std::mem::take(&mut *self.task_order.borrow_mut());
427 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 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 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 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 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 #[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 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#[derive(Clone)]
751pub struct Runtime {
752 inner: Rc<RuntimeInner>,
753}
754
755impl Runtime {
756 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 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 pub fn has_updates(&self) -> bool {
791 self.inner.has_updates()
792 }
793
794 pub fn needs_frame(&self) -> bool {
796 *self.inner.needs_frame.borrow() || self.inner.has_runnable_tasks()
797 }
798
799 pub fn set_needs_frame(&self, value: bool) {
801 *self.inner.needs_frame.borrow_mut() = value;
802 }
803
804 pub fn has_pending_ui(&self) -> bool {
807 self.inner.has_pending_ui()
808 }
809
810 pub fn has_invalid_scopes(&self) -> bool {
812 self.inner.has_invalid_scopes()
813 }
814
815 pub fn has_frame_callbacks(&self) -> bool {
817 self.inner.has_frame_callbacks()
818 }
819
820 pub fn has_transient_frame_callbacks(&self) -> bool {
823 self.inner.has_transient_frame_callbacks()
824 }
825
826 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 pub fn last_frame_time_nanos(&self) -> Option<u64> {
844 self.inner.last_frame_time_nanos.get()
845 }
846
847 #[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#[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#[derive(Clone)]
916pub struct RuntimeHandle {
917 inner: Weak<RuntimeInner>,
918 dispatcher: UiDispatcher,
919 id: RuntimeId,
920}
921
922pub 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 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 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 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 pub fn state_arena_stats(&self) -> (usize, usize) {
1046 self.try_with_state_arena(StateArena::stats)
1047 .unwrap_or_default()
1048 }
1049
1050 pub fn state_arena_debug_stats(&self) -> StateArenaDebugStats {
1052 self.try_with_state_arena(StateArena::debug_stats)
1053 .unwrap_or_default()
1054 }
1055
1056 pub fn debug_stats(&self) -> RuntimeDebugStats {
1058 self.inner
1059 .upgrade()
1060 .map(|inner| inner.debug_stats())
1061 .unwrap_or_default()
1062 }
1063
1064 pub fn live_ui_task_labels(&self) -> Vec<(u64, String)> {
1066 self.inner
1067 .upgrade()
1068 .map(|inner| {
1069 inner
1070 .tasks
1071 .borrow()
1072 .iter()
1073 .map(|(id, entry)| (id, entry.label.to_string()))
1074 .collect()
1075 })
1076 .unwrap_or_default()
1077 }
1078
1079 pub fn schedule(&self) {
1081 if let Some(inner) = self.inner.upgrade() {
1082 inner.schedule();
1083 }
1084 }
1085
1086 pub(crate) fn enqueue_node_update(&self, command: Command) {
1087 if let Some(inner) = self.inner.upgrade() {
1088 inner.enqueue_update(command);
1089 }
1090 }
1091
1092 pub fn spawn_ui<F>(&self, fut: F) -> Option<TaskHandle>
1095 where
1096 F: Future<Output = ()> + 'static,
1097 {
1098 self.spawn_labelled(Box::pin(fut), TaskLabel::Unnamed)
1099 }
1100
1101 pub(crate) fn spawn_labelled(
1102 &self,
1103 future: Pin<Box<dyn Future<Output = ()>>>,
1104 label: TaskLabel,
1105 ) -> Option<TaskHandle> {
1106 let inner = self.inner.upgrade()?;
1107 let id = inner.spawn_ui_task(future, label);
1108 Some(TaskHandle {
1109 id,
1110 runtime: self.clone(),
1111 })
1112 }
1113
1114 pub fn cancel_task(&self, id: u64) {
1116 if let Some(inner) = self.inner.upgrade() {
1117 inner.cancel_task(id);
1118 }
1119 }
1120
1121 pub fn has_task(&self, id: u64) -> bool {
1123 self.inner.upgrade().is_some_and(|inner| inner.has_task(id))
1124 }
1125
1126 pub fn post_ui(&self, task: impl FnOnce() + Send + 'static) {
1131 self.dispatcher.post(task);
1132 }
1133
1134 pub fn register_ui_cont<T: 'static>(&self, f: impl FnOnce(T) + 'static) -> Option<u64> {
1137 self.inner.upgrade().map(|inner| inner.register_ui_cont(f))
1138 }
1139
1140 pub fn cancel_ui_cont(&self, id: u64) {
1142 if let Some(inner) = self.inner.upgrade() {
1143 inner.cancel_ui_cont(id);
1144 }
1145 }
1146
1147 pub fn drain_ui(&self) {
1149 if let Some(inner) = self.inner.upgrade() {
1150 inner.drain_ui();
1151 }
1152 }
1153
1154 pub fn has_pending_ui(&self) -> bool {
1156 self.inner.upgrade().map_or_else(
1157 || self.dispatcher.has_pending(),
1158 |inner| inner.has_pending_ui(),
1159 )
1160 }
1161
1162 pub fn register_frame_callback(
1165 &self,
1166 callback: impl FnOnce(u64) + 'static,
1167 ) -> Option<FrameCallbackId> {
1168 self.inner.upgrade().map(|inner| {
1169 inner.register_frame_callback(
1170 FrameCallbackKind::Transient,
1171 FrameCallback::Run(Box::new(callback)),
1172 )
1173 })
1174 }
1175
1176 pub fn register_perpetual_frame_callback(
1179 &self,
1180 callback: impl FnOnce(u64) + 'static,
1181 ) -> Option<FrameCallbackId> {
1182 self.inner.upgrade().map(|inner| {
1183 inner.register_frame_callback(
1184 FrameCallbackKind::Perpetual,
1185 FrameCallback::Run(Box::new(callback)),
1186 )
1187 })
1188 }
1189
1190 #[cfg(any(feature = "internal", test))]
1193 pub(crate) fn register_frame_waker(
1194 &self,
1195 kind: FrameCallbackKind,
1196 waker: Waker,
1197 ) -> Option<FrameCallbackId> {
1198 self.inner
1199 .upgrade()
1200 .map(|inner| inner.register_frame_callback(kind, FrameCallback::Wake(waker)))
1201 }
1202
1203 #[cfg(any(feature = "internal", test))]
1206 pub(crate) fn frame_waker_time(&self, id: FrameCallbackId, waker: &Waker) -> Option<u64> {
1207 self.inner
1208 .upgrade()
1209 .and_then(|inner| inner.frame_waker_time(id, waker))
1210 }
1211
1212 pub fn cancel_frame_callback(&self, id: FrameCallbackId) {
1214 if let Some(inner) = self.inner.upgrade() {
1215 inner.cancel_frame_callback(id);
1216 }
1217 }
1218
1219 pub fn drain_frame_callbacks(&self, frame_time_nanos: u64) {
1223 if let Some(inner) = self.inner.upgrade() {
1224 inner.drain_frame_callbacks(frame_time_nanos);
1225 }
1226 }
1227
1228 pub fn last_frame_time_nanos(&self) -> Option<u64> {
1231 self.inner
1232 .upgrade()
1233 .and_then(|inner| inner.last_frame_time_nanos.get())
1234 }
1235
1236 #[cfg(any(feature = "internal", test))]
1238 pub fn frame_clock(&self) -> FrameClock {
1239 FrameClock::new(self.clone())
1240 }
1241
1242 pub fn set_needs_frame(&self, value: bool) {
1244 if let Some(inner) = self.inner.upgrade() {
1245 *inner.needs_frame.borrow_mut() = value;
1246 }
1247 }
1248
1249 pub(crate) fn take_updates(&self) -> Vec<Command> {
1250 self.inner
1251 .upgrade()
1252 .map(|inner| inner.take_updates())
1253 .unwrap_or_default()
1254 }
1255
1256 pub fn has_updates(&self) -> bool {
1258 self.inner
1259 .upgrade()
1260 .is_some_and(|inner| inner.has_updates())
1261 }
1262
1263 pub(crate) fn scope_runtime(&self) -> ScopeRuntime {
1265 ScopeRuntime(Weak::clone(&self.inner))
1266 }
1267
1268 pub(crate) fn requeue_invalid_scope(&self, scope: &RecomposeScope) {
1269 if let Some(inner) = self.inner.upgrade() {
1270 inner.requeue_invalid_scope(scope);
1271 }
1272 }
1273
1274 pub(crate) fn take_invalidated_scopes(&self) -> Option<Vec<RecomposeScope>> {
1275 self.inner
1276 .upgrade()
1277 .and_then(|inner| inner.take_invalidated_scopes())
1278 }
1279
1280 #[inline]
1282 pub(crate) fn recycle_scopes(&self, scopes: Vec<RecomposeScope>) {
1283 if let Some(inner) = self.inner.upgrade() {
1284 inner.recycle_scopes(scopes);
1285 }
1286 }
1287
1288 pub fn forget_movable(&self, id: Key) {
1292 if let Some(inner) = self.inner.upgrade() {
1293 inner.forgotten_movables.borrow_mut().push(id);
1294 inner.schedule();
1295 }
1296 }
1297
1298 pub(crate) fn next_movable_content_id(&self) -> Key {
1303 let Some(inner) = self.inner.upgrade() else {
1304 log::error!("movable content asked a runtime that is gone for an identity");
1305 return Key(0);
1306 };
1307 let id = inner.next_movable_content_id.get();
1308 inner.next_movable_content_id.set(id.wrapping_add(1).max(1));
1309 Key(id)
1310 }
1311
1312 pub fn has_invalid_scopes(&self) -> bool {
1314 self.inner
1315 .upgrade()
1316 .is_some_and(|inner| inner.has_invalid_scopes())
1317 }
1318
1319 fn live_recompose_scope_count(&self) -> usize {
1320 self.inner
1321 .upgrade()
1322 .map(|inner| inner.live_recompose_scope_count())
1323 .unwrap_or_default()
1324 }
1325
1326 #[doc(hidden)]
1327 pub fn debug_invalid_scope_ids(&self) -> Vec<usize> {
1328 self.inner
1329 .upgrade()
1330 .map(|inner| inner.queued_invalid_scope_ids())
1331 .unwrap_or_default()
1332 }
1333
1334 pub fn has_frame_callbacks(&self) -> bool {
1336 self.inner
1337 .upgrade()
1338 .is_some_and(|inner| inner.has_frame_callbacks())
1339 }
1340
1341 pub fn has_transient_frame_callbacks(&self) -> bool {
1344 self.inner
1345 .upgrade()
1346 .is_some_and(|inner| inner.has_transient_frame_callbacks())
1347 }
1348
1349 pub fn assert_ui_thread(&self) {
1351 debug_assert!(
1352 self.inner
1353 .upgrade()
1354 .is_none_or(|inner| inner.ui_thread_id == std::thread::current().id()),
1355 "state mutated off the runtime's UI thread"
1356 );
1357 }
1358
1359 pub fn dispatcher(&self) -> UiDispatcher {
1361 self.dispatcher.clone()
1362 }
1363
1364 #[doc(hidden)]
1365 pub fn with_deferred_state_releases<R>(&self, f: impl FnOnce() -> R) -> R {
1366 let _scope = enter_state_teardown_scope();
1367 f()
1368 }
1369}
1370
1371impl TaskHandle {
1372 pub fn cancel(&self) {
1374 self.runtime.cancel_task(self.id);
1375 }
1376
1377 pub fn is_finished(&self) -> bool {
1379 !self.runtime.has_task(self.id)
1380 }
1381}
1382
1383pub(crate) struct FrameCallbackEntry {
1384 id: FrameCallbackId,
1385 kind: FrameCallbackKind,
1386 callback: FrameCallback,
1387}
1388
1389enum FrameCallback {
1390 Run(Box<dyn FnOnce(u64) + 'static>),
1392 #[cfg(any(feature = "internal", test))]
1394 Wake(Waker),
1395}
1396
1397#[cfg(not(target_arch = "wasm32"))]
1398struct RuntimeTaskWaker {
1399 scheduler: SchedulerRef,
1400 runnable: Arc<AtomicBool>,
1401 woken: Arc<AtomicBool>,
1402}
1403
1404#[cfg(target_arch = "wasm32")]
1405struct RuntimeTaskWaker {
1406 runtime_id: RuntimeId,
1407 runnable: Arc<AtomicBool>,
1408 woken: Arc<AtomicBool>,
1409}
1410
1411impl RuntimeTaskWaker {
1412 #[cfg(not(target_arch = "wasm32"))]
1413 fn new(inner: &RuntimeInner, runnable: Arc<AtomicBool>) -> Self {
1414 let scheduler = Arc::clone(&inner.scheduler);
1415 Self {
1416 scheduler,
1417 runnable,
1418 woken: Arc::clone(&inner.task_woken),
1419 }
1420 }
1421
1422 #[cfg(target_arch = "wasm32")]
1423 fn new(inner: &RuntimeInner, runnable: Arc<AtomicBool>) -> Self {
1424 let runtime_id = inner.runtime_id;
1425 Self {
1426 runtime_id,
1427 runnable,
1428 woken: Arc::clone(&inner.task_woken),
1429 }
1430 }
1431
1432 fn into_waker(self) -> Waker {
1433 futures_task::waker(Arc::new(self))
1434 }
1435}
1436
1437impl futures_task::ArcWake for RuntimeTaskWaker {
1438 #[cfg(not(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 arc_self.scheduler.schedule_frame();
1443 }
1444
1445 #[cfg(target_arch = "wasm32")]
1446 fn wake_by_ref(arc_self: &Arc<Self>) {
1447 arc_self.runnable.store(true, Ordering::Release);
1448 arc_self.woken.store(true, Ordering::Release);
1449 if let Some(handle) = runtime_handle_by_id(arc_self.runtime_id) {
1450 handle.schedule();
1451 }
1452 }
1453}
1454
1455#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1458pub struct RuntimeThreadLocalDebugStats {
1459 pub active_runtimes_len: usize,
1461 pub active_runtimes_cap: usize,
1463 pub registered_runtimes_len: usize,
1465 pub registered_runtimes_cap: usize,
1467 pub deferred_state_releases_len: usize,
1469 pub deferred_state_releases_cap: usize,
1471}
1472
1473pub fn current_runtime_handle() -> Option<RuntimeHandle> {
1478 thread_state::try_runtimes(|state| {
1479 if let Some(handle) = state.active_runtimes.borrow().last() {
1480 return Some(handle.clone());
1481 }
1482 state.last_runtime.borrow().clone()
1483 })
1484 .flatten()
1485}
1486
1487#[cfg(target_os = "android")]
1488pub(crate) fn share_rescue<'a>(
1489 handles: impl Iterator<Item = &'a RuntimeHandle>,
1490) -> Option<Rc<thread_state::RescuedThreadState>> {
1491 let live: Vec<Rc<RuntimeInner>> = handles
1492 .filter_map(|handle| handle.inner.upgrade())
1493 .collect();
1494 let shared = live
1495 .iter()
1496 .find_map(|inner| inner.rescued.borrow().clone())
1497 .or_else(|| (!live.is_empty()).then(Rc::default))?;
1498 for inner in &live {
1499 *inner.rescued.borrow_mut() = Some(Rc::clone(&shared));
1500 }
1501 Some(shared)
1502}
1503
1504pub(crate) fn live_recompose_scope_count() -> usize {
1505 thread_state::runtimes(|state| {
1506 state
1507 .registered_runtimes
1508 .borrow()
1509 .values()
1510 .map(RuntimeHandle::live_recompose_scope_count)
1511 .sum()
1512 })
1513}
1514
1515pub fn debug_runtime_thread_local_stats() -> RuntimeThreadLocalDebugStats {
1517 thread_state::runtimes(|state| {
1518 let active = state.active_runtimes.borrow();
1519 let registered = state.registered_runtimes.borrow();
1520 let deferred = state.deferred_state_releases.borrow();
1521 RuntimeThreadLocalDebugStats {
1522 active_runtimes_len: active.len(),
1523 active_runtimes_cap: active.capacity(),
1524 registered_runtimes_len: registered.len(),
1525 registered_runtimes_cap: registered.capacity(),
1526 deferred_state_releases_len: deferred.len(),
1527 deferred_state_releases_cap: deferred.capacity(),
1528 }
1529 })
1530}
1531
1532fn defer_state_release(runtime: &RuntimeHandle, id: StateId) {
1533 let deferred = thread_state::try_runtimes(|state| {
1534 if state.state_teardown_depth.get() == 0 {
1535 return false;
1536 }
1537 state
1538 .deferred_state_releases
1539 .borrow_mut()
1540 .push(DeferredStateRelease {
1541 runtime: Weak::clone(&runtime.inner),
1542 id,
1543 });
1544 true
1545 });
1546 if deferred != Some(true) {
1547 release_state(&runtime.inner, id);
1548 }
1549}
1550
1551fn release_state(runtime: &Weak<RuntimeInner>, id: StateId) {
1552 if let Some(inner) = runtime.upgrade() {
1553 inner.state_arena.release(id);
1554 }
1555}
1556
1557pub(crate) struct StateTeardownScope;
1558
1559pub(crate) fn enter_state_teardown_scope() -> StateTeardownScope {
1560 thread_state::try_runtimes(|state| {
1561 let depth = &state.state_teardown_depth;
1562 depth.set(depth.get() + 1);
1563 });
1564 StateTeardownScope
1565}
1566
1567impl Drop for StateTeardownScope {
1568 fn drop(&mut self) {
1569 let finished = thread_state::try_runtimes(|state| {
1570 let depth = &state.state_teardown_depth;
1571 let next = depth.get().saturating_sub(1);
1572 depth.set(next);
1573 if next == 0 {
1574 let mut releases = state.deferred_state_releases.borrow_mut();
1575 while let Some(deferred) = releases.pop() {
1576 release_state(&deferred.runtime, deferred.id);
1577 }
1578 }
1579 next == 0
1580 });
1581 if finished == Some(true) {
1582 thread_state::release_when_idle();
1583 }
1584 }
1585}
1586
1587pub(crate) fn push_active_runtime(handle: &RuntimeHandle) {
1588 thread_state::runtimes(|state| {
1589 state
1591 .registered_runtimes
1592 .borrow_mut()
1593 .entry(handle.id())
1594 .or_insert_with(|| handle.clone());
1595 state.active_runtimes.borrow_mut().push(handle.clone());
1596 let mut last = state.last_runtime.borrow_mut();
1597 if last.as_ref().is_none_or(|last| last.id != handle.id) {
1598 *last = Some(handle.clone());
1599 }
1600 });
1601}
1602
1603pub(crate) fn pop_active_runtime() {
1604 thread_state::runtimes(|state| {
1605 state.active_runtimes.borrow_mut().pop();
1606 });
1607}
1608
1609pub fn schedule_frame() {
1611 if let Some(handle) = current_runtime_handle() {
1612 handle.schedule();
1613 return;
1614 }
1615 log::debug!(
1616 target: "cranpose::runtime",
1617 "ignoring frame request without an active runtime",
1618 );
1619}
1620
1621pub fn schedule_node_update(
1623 update: impl FnOnce(&mut dyn Applier) -> Result<(), NodeError> + 'static,
1624) {
1625 if let Some(handle) = current_runtime_handle() {
1626 handle.enqueue_node_update(Command::callback(update));
1627 } else {
1628 drop(update);
1629 log::debug!(
1630 target: "cranpose::runtime",
1631 "ignoring node update request without an active runtime",
1632 );
1633 }
1634}
1635
1636#[cfg(test)]
1637#[path = "tests/runtime_tests.rs"]
1638mod tests;