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
16use std::sync::{Mutex, OnceLock};
17
18use hao_il2cpp_runtime::{Error, Result};
19
20type Job = Box<dyn FnOnce() + Send>;
21type Waker = Box<dyn Fn() + Send + Sync>;
22
23static QUEUE: Mutex<Vec<Job>> = Mutex::new(Vec::new());
24static PUMP_ERR: OnceLock<Option<String>> = OnceLock::new();
25static WAKER: Mutex<Option<Waker>> = Mutex::new(None);
26
27fn ensure_pump() -> Result<()> {
28    let err = PUMP_ERR.get_or_init(|| {
29        match super::lifecycle::on_update(drain) {
30            Ok(()) => None,
31            Err(e) => Some(e.to_string()),
32        }
33    });
34    match err {
35        None => Ok(()),
36        Some(msg) => Err(Error::Exception(msg.clone())),
37    }
38}
39
40fn drain() {
41    let jobs: Vec<Job> =
42        std::mem::take(&mut *QUEUE.lock().unwrap_or_else(|e| e.into_inner()));
43    for job in jobs {
44        job();
45    }
46}
47
48fn wake() {
49    if let Some(w) = &*WAKER.lock().unwrap_or_else(|e| e.into_inner()) {
50        w();
51    }
52}
53
54/// Installs a waker that is called (from the queuing thread) every time a
55/// new job is pushed. Use this to wake a condvar or similar so the main
56/// thread can call [`drain_pending`] promptly instead of polling.
57pub fn set_waker(f: impl Fn() + Send + Sync + 'static) {
58    *WAKER.lock().unwrap_or_else(|e| e.into_inner()) = Some(Box::new(f));
59}
60
61/// Runs all pending jobs on the current thread, then returns. Safe to call
62/// from any thread, but only useful on the main thread — the jobs expect
63/// to run there.
64pub fn drain_pending() {
65    drain();
66}
67
68/// Queues `f` to run on Unity's main thread on the next frame. Returns
69/// immediately without waiting for `f` to execute.
70pub fn queue(f: impl FnOnce() + Send + 'static) -> Result<()> {
71    ensure_pump()?;
72    QUEUE
73        .lock()
74        .unwrap_or_else(|e| e.into_inner())
75        .push(Box::new(f));
76    wake();
77    Ok(())
78}
79
80/// Runs `f` on Unity's main thread and blocks the caller until the result
81/// is ready.
82pub fn call<R: Send + 'static>(
83    f: impl FnOnce() -> R + Send + 'static,
84) -> Result<R> {
85    ensure_pump()?;
86    let (tx, rx) = std::sync::mpsc::sync_channel(1);
87    tracing::debug!("dispatch::call: queuing job");
88    QUEUE
89        .lock()
90        .unwrap_or_else(|e| e.into_inner())
91        .push(Box::new(move || {
92            tracing::debug!("dispatch: running job on main thread");
93            let _ = tx.send(f());
94        }));
95    wake();
96    let result = rx.recv()
97        .map_err(|_| Error::Exception("main-thread dispatch: channel closed".into()));
98    tracing::debug!("dispatch::call: job completed");
99    result
100}