use std::sync::atomic::{AtomicUsize, Ordering}; use crate::handles::{Scope, Scoped, insert_scoped}; use crate::status::{EGUICL_ERR_NO_TRAMPOLINE, Error, Result, guard}; /// Calls the Lisp closure registered under `closure_id` with one scoped handle /// (or 0). Returns 0 on success, nonzero when Lisp caught and reported an error. /// Lisp must never unwind out of this call. pub type EguiclTrampoline = extern "C" fn(closure_id: u64, handle: u64) -> i32; static TRAMPOLINE: AtomicUsize = AtomicUsize::new(0); #[unsafe(no_mangle)] pub extern "C" fn eguicl_set_trampoline(trampoline: EguiclTrampoline) -> i32 { guard(|| { TRAMPOLINE.store(trampoline as usize, Ordering::SeqCst); Ok(()) }) } pub fn trampoline() -> Result { match TRAMPOLINE.load(Ordering::SeqCst) { 0 => Err(Error::new( EGUICL_ERR_NO_TRAMPOLINE, "no trampoline is installed", )), // SAFETY: the only nonzero values stored are `EguiclTrampoline` pointers. address => Ok(unsafe { std::mem::transmute::(address) }), } } /// Invokes a Lisp closure inside a new scope, giving it a handle to `object`. /// Handles created during the call are invalidated when it returns. pub fn invoke_with(closure_id: u64, object: Option) -> Result { let trampoline = trampoline()?; let _scope = Scope::enter(); let handle = match object { Some(object) => insert_scoped(object)?, None => 0, }; Ok(trampoline(closure_id, handle)) } pub fn invoke_ui(closure_id: u64, ui: &mut egui::Ui) -> Result { invoke_with(closure_id, Some(Scoped::Ui(ui as *mut egui::Ui))) }