use std::future::Future;
use std::pin::Pin;
use std::sync::OnceLock;
use std::thread::ThreadId;
use tokio::task::{JoinHandle, LocalSet};
use crate::Error;
#[derive(Debug)]
pub struct AppRuntime {
thread: ThreadId,
}
static APP: OnceLock<AppRuntime> = OnceLock::new();
thread_local! {
static TASKS: &'static LocalSet = start();
}
fn start() -> &'static LocalSet {
let tasks: &'static LocalSet = Box::leak(Box::new(LocalSet::new()));
let mut driving: Pin<Box<dyn Future<Output = ()>>> =
Box::pin(tasks.run_until(std::future::pending::<()>()));
wasm_bindgen_futures::spawn_local(std::future::poll_fn(move |cx| {
let _driving = crate::Driving::enter();
driving.as_mut().poll(cx)
}));
tasks
}
fn spawn_local<F>(future: F) -> JoinHandle<F::Output>
where
F: Future + 'static,
F::Output: 'static,
{
TASKS.with(|tasks| tasks.spawn_local(future))
}
#[cfg(target_family = "wasm")]
pub fn spawn_task(future: impl Future<Output = ()> + 'static) {
drop(spawn_local(future));
}
pub fn app() -> &'static AppRuntime {
APP.get_or_init(|| AppRuntime {
thread: std::thread::current().id(),
})
}
#[allow(
clippy::unnecessary_wraps,
reason = "the same signature as native builds, where starting the runtime thread can fail"
)]
pub fn try_app() -> Result<&'static AppRuntime, Error> {
Ok(app())
}
impl AppRuntime {
pub const fn thread_id(&self) -> ThreadId {
self.thread
}
pub fn is_runtime_thread(&self) -> bool {
crate::in_async_context()
}
pub fn spawn<F>(&self, future: F) -> JoinHandle<F::Output>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
spawn_local(future)
}
pub fn spawn_then<F, D>(&self, future: F, deliver: D) -> JoinHandle<()>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
D: FnOnce(F::Output) + Send + 'static,
{
spawn_local(async move { deliver(future.await) })
}
pub fn spawn_pinned<M, F>(&self, make: M) -> JoinHandle<F::Output>
where
M: FnOnce() -> F + Send + 'static,
F: Future + 'static,
F::Output: Send + 'static,
{
spawn_local(async move { make().await })
}
pub fn spawn_blocking<F, R>(&self, call: F) -> JoinHandle<R>
where
F: FnOnce() -> R + Send + 'static,
R: Send + 'static,
{
spawn_local(async move { call() })
}
pub fn block_on<F: Future>(&self, _future: F) -> Result<F::Output, Error> {
Err(Error::UiThread)
}
}
pub(crate) fn spawn_job(job: impl FnOnce() + Send + 'static) {
drop(spawn_local(async move { job() }));
}