Skip to main content

hao_il2cpp_unity/
dispatch.rs

1//! Main-thread dispatch queue.
2//!
3//! Unity's API may only be called from its main thread. Code that runs on
4//! another thread (an egui overlay, a background task) can use [`queue`] to
5//! fire-and-forget a closure, or [`call`] to run a closure and block until
6//! the result is ready.
7//!
8//! The queue is drained once per frame via [`super::on_update`], and can
9//! also be drained explicitly with [`drain_pending`] from any code that
10//! holds the main thread (e.g. the egui bridge's wait loop).
11//!
12//! A waker ([`set_waker`]) lets the dispatch module notify sleeping main-
13//! thread code (like a condvar wait) that work has been queued, so it can
14//! wake up and call [`drain_pending`] without polling.
15//!
16//! ```no_run
17//! use hao_il2cpp_unity::{dispatch, screen};
18//!
19//! std::thread::spawn(|| {
20//!     // Runs on Unity's main thread on the next frame; this thread waits.
21//!     // (The runtime's `Error` isn't `Send`, so convert it inside the closure.)
22//!     if let Ok(size) = dispatch::call(|| screen::size().ok()) {
23//!         println!("screen is {size:?}");
24//!     }
25//!     // Fire and forget.
26//!     let _ = dispatch::queue(|| {
27//!         let _ = hao_il2cpp_unity::log("hello from a background thread");
28//!     });
29//! });
30//! ```
31
32use std::sync::{Mutex, OnceLock};
33
34use hao_il2cpp_runtime::{Error, Result};
35
36type Job = Box<dyn FnOnce() + Send>;
37type Waker = Box<dyn Fn() + Send + Sync>;
38
39static QUEUE: Mutex<Vec<Job>> = Mutex::new(Vec::new());
40static PUMP_ERR: OnceLock<Option<String>> = OnceLock::new();
41static WAKER: Mutex<Option<Waker>> = Mutex::new(None);
42
43fn ensure_pump() -> Result<()> {
44    let err = PUMP_ERR.get_or_init(|| match super::lifecycle::on_update(drain) {
45        Ok(()) => None,
46        Err(e) => Some(e.to_string()),
47    });
48    match err {
49        None => Ok(()),
50        Some(msg) => Err(Error::Exception(msg.clone())),
51    }
52}
53
54fn drain() {
55    let jobs: Vec<Job> = std::mem::take(&mut *QUEUE.lock().unwrap_or_else(|e| e.into_inner()));
56    for job in jobs {
57        job();
58    }
59}
60
61fn wake() {
62    if let Some(w) = &*WAKER.lock().unwrap_or_else(|e| e.into_inner()) {
63        w();
64    }
65}
66
67/// Installs a waker that is called (from the queuing thread) every time a
68/// new job is pushed. Use this to wake a condvar or similar so the main
69/// thread can call [`drain_pending`] promptly instead of polling.
70pub fn set_waker(f: impl Fn() + Send + Sync + 'static) {
71    *WAKER.lock().unwrap_or_else(|e| e.into_inner()) = Some(Box::new(f));
72}
73
74/// Runs all pending jobs on the current thread, then returns. Safe to call
75/// from any thread, but only useful on the main thread — the jobs expect
76/// to run there.
77pub fn drain_pending() {
78    drain();
79}
80
81/// Queues `f` to run on Unity's main thread on the next frame. Returns
82/// immediately without waiting for `f` to execute.
83pub fn queue(f: impl FnOnce() + Send + 'static) -> Result<()> {
84    ensure_pump()?;
85    QUEUE
86        .lock()
87        .unwrap_or_else(|e| e.into_inner())
88        .push(Box::new(f));
89    wake();
90    Ok(())
91}
92
93/// Runs `f` on Unity's main thread and blocks the caller until the result
94/// is ready.
95pub fn call<R: Send + 'static>(f: impl FnOnce() -> R + Send + 'static) -> Result<R> {
96    ensure_pump()?;
97    let (tx, rx) = std::sync::mpsc::sync_channel(1);
98    tracing::debug!("dispatch::call: queuing job");
99    QUEUE
100        .lock()
101        .unwrap_or_else(|e| e.into_inner())
102        .push(Box::new(move || {
103            tracing::debug!("dispatch: running job on main thread");
104            let _ = tx.send(f());
105        }));
106    wake();
107    let result = rx
108        .recv()
109        .map_err(|_| Error::Exception("main-thread dispatch: channel closed".into()));
110    tracing::debug!("dispatch::call: job completed");
111    result
112}