hao_il2cpp_unity/
dispatch.rs1use 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
54pub 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
61pub fn drain_pending() {
65 drain();
66}
67
68pub 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
80pub 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}