use std::sync::{Mutex, OnceLock};
use hao_il2cpp_runtime::{Error, Result};
type Job = Box<dyn FnOnce() + Send>;
type Waker = Box<dyn Fn() + Send + Sync>;
static QUEUE: Mutex<Vec<Job>> = Mutex::new(Vec::new());
static PUMP_ERR: OnceLock<Option<String>> = OnceLock::new();
static WAKER: Mutex<Option<Waker>> = Mutex::new(None);
fn ensure_pump() -> Result<()> {
let err = PUMP_ERR.get_or_init(|| {
match super::lifecycle::on_update(drain) {
Ok(()) => None,
Err(e) => Some(e.to_string()),
}
});
match err {
None => Ok(()),
Some(msg) => Err(Error::Exception(msg.clone())),
}
}
fn drain() {
let jobs: Vec<Job> =
std::mem::take(&mut *QUEUE.lock().unwrap_or_else(|e| e.into_inner()));
for job in jobs {
job();
}
}
fn wake() {
if let Some(w) = &*WAKER.lock().unwrap_or_else(|e| e.into_inner()) {
w();
}
}
pub fn set_waker(f: impl Fn() + Send + Sync + 'static) {
*WAKER.lock().unwrap_or_else(|e| e.into_inner()) = Some(Box::new(f));
}
pub fn drain_pending() {
drain();
}
pub fn queue(f: impl FnOnce() + Send + 'static) -> Result<()> {
ensure_pump()?;
QUEUE
.lock()
.unwrap_or_else(|e| e.into_inner())
.push(Box::new(f));
wake();
Ok(())
}
pub fn call<R: Send + 'static>(
f: impl FnOnce() -> R + Send + 'static,
) -> Result<R> {
ensure_pump()?;
let (tx, rx) = std::sync::mpsc::sync_channel(1);
tracing::debug!("dispatch::call: queuing job");
QUEUE
.lock()
.unwrap_or_else(|e| e.into_inner())
.push(Box::new(move || {
tracing::debug!("dispatch: running job on main thread");
let _ = tx.send(f());
}));
wake();
let result = rx.recv()
.map_err(|_| Error::Exception("main-thread dispatch: channel closed".into()));
tracing::debug!("dispatch::call: job completed");
result
}