cranpose_core/runtime/ui_task.rs
1use std::rc::Rc;
2
3use super::RuntimeHandle;
4
5// Work queued for the runtime thread: a closure that runs once, or a task
6// its owner keeps and queues again without allocating.
7pub(super) enum UiTask {
8 Once(Box<dyn FnOnce() + 'static>),
9 Shared(Rc<dyn Fn() + 'static>),
10}
11
12impl UiTask {
13 pub(super) fn run(self) {
14 match self {
15 Self::Once(task) => task(),
16 Self::Shared(task) => task(),
17 }
18 }
19}
20
21#[expect(
22 clippy::multiple_inherent_impl,
23 reason = "the runtime's task entry points live with the task they queue"
24)]
25impl RuntimeHandle {
26 /// Schedules work that must run on the runtime thread.
27 ///
28 /// The closure executes on the UI thread immediately when the runtime
29 /// drains its local queue, so it may capture `Rc`/`RefCell` values. Calling
30 /// this from any other thread is a logic error and will panic in debug
31 /// builds via the inner assertion.
32 pub fn enqueue_ui_task(&self, task: Box<dyn FnOnce() + 'static>) {
33 if let Some(inner) = self.inner.upgrade() {
34 inner.enqueue_ui_task(UiTask::Once(task));
35 } else {
36 task();
37 }
38 }
39
40 /// Schedules `task`, which its owner keeps and schedules again, to run on
41 /// the runtime thread, as [`RuntimeHandle::enqueue_ui_task`] runs a
42 /// closure once. Scheduling it clones the `Rc` and allocates nothing.
43 pub fn enqueue_shared_ui_task(&self, task: Rc<dyn Fn() + 'static>) {
44 match self.inner.upgrade() {
45 Some(inner) => inner.enqueue_ui_task(UiTask::Shared(task)),
46 None => task(),
47 }
48 }
49}