Skip to main content

egui_kit/remote/
runtime.rs

1//! Where queries and commands run: a Tokio runtime natively, the browser's event loop on the web.
2
3use core::future::Future;
4use core::pin::Pin;
5
6#[cfg(not(target_arch = "wasm32"))]
7pub use native::*;
8#[cfg(target_arch = "wasm32")]
9pub use web::*;
10
11#[cfg(not(target_arch = "wasm32"))]
12mod native {
13    use core::future::Future;
14    use std::sync::OnceLock;
15
16    use tokio::runtime::{EnterGuard, Handle, Runtime};
17
18    /// `Send` natively, where futures run on the threads of a Tokio runtime, and nothing on the
19    /// web, where they run on the browser's event loop.
20    pub trait MaybeSend: Send {}
21
22    impl<T: Send + ?Sized> MaybeSend for T {}
23
24    /// The runtime used when the app didn't enter one.
25    fn runtime() -> &'static Runtime {
26        static RUNTIME: OnceLock<Runtime> = OnceLock::new();
27        RUNTIME.get_or_init(|| {
28            tokio::runtime::Builder::new_multi_thread()
29                .enable_all()
30                .thread_name("egui-kit")
31                .build()
32                .expect("egui-kit: failed to start the Tokio runtime")
33        })
34    }
35
36    fn handle() -> Handle {
37        Handle::try_current().unwrap_or_else(|_| runtime().handle().clone())
38    }
39
40    /// Enters egui-kit's runtime, unless the app entered one of its own.
41    pub(crate) fn enter() -> Option<EnterGuard<'static>> {
42        Handle::try_current().is_err().then(|| runtime().enter())
43    }
44
45    /// Aborts its task when dropped.
46    pub(crate) struct Abort(tokio::task::AbortHandle);
47
48    impl Drop for Abort {
49        fn drop(&mut self) {
50            self.0.abort();
51        }
52    }
53
54    pub(crate) fn spawn(future: impl Future<Output = ()> + Send + 'static) -> Abort {
55        Abort(handle().spawn(future).abort_handle())
56    }
57
58    pub(crate) fn spawn_detached(future: impl Future<Output = ()> + Send + 'static) {
59        drop(handle().spawn(future));
60    }
61}
62
63#[cfg(target_arch = "wasm32")]
64mod web {
65    use core::cell::{Cell, RefCell};
66    use core::future::{Future, poll_fn};
67    use core::task::{Poll, Waker};
68    use std::rc::Rc;
69
70    /// `Send` natively, where futures run on the threads of a Tokio runtime, and nothing on the
71    /// web, where they run on the browser's event loop.
72    pub trait MaybeSend {}
73
74    impl<T: ?Sized> MaybeSend for T {}
75
76    /// The browser needs no runtime.
77    pub(crate) fn enter() -> Option<()> {
78        None
79    }
80
81    #[derive(Default)]
82    struct AbortState {
83        aborted: Cell<bool>,
84        waker: RefCell<Option<Waker>>,
85    }
86
87    /// Aborts its task when dropped.
88    pub(crate) struct Abort(Rc<AbortState>);
89
90    impl Drop for Abort {
91        fn drop(&mut self) {
92            self.0.aborted.set(true);
93            if let Some(waker) = self.0.waker.take() {
94                waker.wake();
95            }
96        }
97    }
98
99    pub(crate) fn spawn(future: impl Future<Output = ()> + 'static) -> Abort {
100        let state = Rc::new(AbortState::default());
101        let task = Rc::clone(&state);
102        wasm_bindgen_futures::spawn_local(async move {
103            let mut future = core::pin::pin!(future);
104            poll_fn(|cx| {
105                if task.aborted.get() {
106                    return Poll::Ready(());
107                }
108                let poll = future.as_mut().poll(cx);
109                if poll.is_pending() {
110                    task.waker.replace(Some(cx.waker().clone()));
111                }
112                poll
113            })
114            .await;
115        });
116        Abort(state)
117    }
118
119    pub(crate) fn spawn_detached(future: impl Future<Output = ()> + 'static) {
120        wasm_bindgen_futures::spawn_local(future);
121    }
122}
123
124/// A boxed future that can be spawned.
125#[cfg(not(target_arch = "wasm32"))]
126pub(crate) type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
127#[cfg(target_arch = "wasm32")]
128pub(crate) type BoxFuture<T> = Pin<Box<dyn Future<Output = T>>>;