use alloc::boxed::Box;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use std::cell::{Cell, RefCell};
use std::sync::Mutex;
use crate::runtime::{Runtime, Value};
const THE_SLOTS: usize = 64;
struct Entry {
name: String,
params: usize,
func: Option<Value>,
event_info: Option<i64>,
}
static REGISTRY: Mutex<Vec<Option<Entry>>> = Mutex::new(Vec::new());
thread_local! {
static DEPTH: Cell<u32> = const { Cell::new(0) };
static SLOTS: RefCell<Vec<*mut TheSlot>> = const { RefCell::new(Vec::new()) };
}
struct TheSlot {
the_runtime: Cell<Option<&'static mut Runtime<'static>>>,
}
pub fn set_current(rt: &mut Runtime<'_>) -> usize {
let rt: &'static mut Runtime<'static> = unsafe {
std::mem::transmute::<&mut Runtime<'_>, &'static mut Runtime<'static>>(rt)
};
let slot = Box::into_raw(Box::new(TheSlot {
the_runtime: Cell::new(Some(rt)),
}));
SLOTS.with(|slots| {
let mut slots = slots.borrow_mut();
let depth = slots.len();
slots.push(slot);
depth
})
}
#[cfg(feature = "std")]
fn the_thread_of_the_script() -> std::thread::ThreadId {
std::thread::current().id()
}
pub fn clear_current(previous: usize) {
SLOTS.with(|slots| {
let mut slots = slots.borrow_mut();
if slots.len() <= previous {
#[cfg(feature = "std")]
if std::env::var_os("AHK_DEBUG_CALLBACK").is_some() {
eprintln!(
"the stack of the loans of the machine is at {} and the call expects {}",
slots.len(),
previous
);
}
return;
}
let raw = slots.pop().expect("the slot of the call is there");
unsafe { drop(Box::from_raw(raw)) };
});
}
fn the_slot() -> Option<*mut TheSlot> {
SLOTS.with(|slots| slots.borrow().last().copied())
}
fn with_the_runtime<T>(answer: impl FnOnce(&mut Runtime<'_>) -> T) -> Option<T> {
let slot = the_slot()?;
let runtime = unsafe { (*slot).the_runtime.take() }?;
let answer = answer(&mut *runtime);
unsafe { (*slot).the_runtime.set(Some(runtime)) };
Some(answer)
}
pub fn the_message_runs(msg: i64, wparam: i64, lparam: i64, hwnd: i64) -> Option<i64> {
with_the_runtime(|rt| rt.the_message_runs(msg, wparam, lparam, hwnd)).flatten()
}
pub fn register(name: &str, params: usize) -> usize {
register_with_event_info(name, params, None)
}
pub fn register_with_event_info(name: &str, params: usize, event_info: Option<i64>) -> usize {
let mut registry = match REGISTRY.lock() {
Ok(registry) => registry,
Err(_) => return 0,
};
let slot = match registry.iter().position(|entry| entry.is_none()) {
Some(slot) => slot,
None => {
if registry.len() >= THE_SLOTS {
return 0;
}
registry.push(None);
registry.len() - 1
}
};
let address = THE_TRAMPOLINES[slot] as usize;
registry[slot] = Some(Entry {
name: name.to_string(),
params,
func: None,
event_info: Some(event_info.unwrap_or(address as i64)),
});
address
}
pub fn the_trampoline_of(
address: usize,
) -> Option<extern "C" fn(usize, usize, usize, usize) -> usize> {
THE_TRAMPOLINES
.iter()
.position(|trampoline| *trampoline as usize == address)
.map(|slot| THE_TRAMPOLINES[slot])
}
pub fn register_value(func: Value, params: usize) -> usize { let mut registry = match REGISTRY.lock() {
Ok(registry) => registry,
Err(_) => return 0,
};
let slot = match registry.iter().position(|entry| entry.is_none()) {
Some(slot) => slot,
None => {
if registry.len() >= THE_SLOTS {
return 0;
}
registry.push(None);
registry.len() - 1
}
};
registry[slot] = Some(Entry {
name: String::new(),
params,
func: Some(func),
event_info: None,
});
THE_TRAMPOLINES[slot] as usize
}
pub fn free(address: usize) {
release_if_callback(address);
}
pub fn release_if_callback(address: usize) -> bool {
let Some(slot) = THE_TRAMPOLINES.iter().position(|&t| t as usize == address) else {
return false;
};
if let Ok(mut registry) = REGISTRY.lock() {
if let Some(entry) = registry.get_mut(slot) {
*entry = None;
}
}
true
}
fn invoke(slot: usize, args: [usize; 4]) -> usize {
let entry = {
let registry = match REGISTRY.lock() {
Ok(registry) => registry,
Err(_) => return 0,
};
match registry.get(slot).and_then(|entry| entry.as_ref()) {
Some(entry) => Entry {
name: entry.name.clone(),
params: entry.params,
func: entry.func.clone(),
event_info: entry.event_info,
},
None => return 0,
}
};
let values: Vec<Value> = args
.iter()
.take(entry.params)
.map(|&arg| Value::Int(arg as i64))
.collect();
DEPTH.with(|d| d.set(d.get() + 1));
#[cfg(feature = "std")]
if std::env::var_os("AHK_DEBUG_CALLBACK").is_some() {
eprintln!(
"the callback {} runs at the depth {} on the thread {:?} with args [0x{:X}, 0x{:X}, 0x{:X}, 0x{:X}]",
entry.name,
DEPTH.with(|d| d.get()),
the_thread_of_the_script(),
args[0],
args[1],
args[2],
args[3],
);
}
let answer = with_the_runtime(|rt| {
let prev_event_info = if let Some(info) = entry.event_info {
let prev = rt.lookup("A_EventInfo");
rt.set_global("A_EventInfo", Value::Int(info));
Some(prev)
} else {
None
};
let result = if let Some(func) = &entry.func {
rt.the_callback_runs(func, &values)
} else {
rt.the_callback_of_a_name_runs(&entry.name, &values)
};
if let Some(Some(val)) = prev_event_info {
rt.set_global("A_EventInfo", val);
}
result
});
DEPTH.with(|d| d.set(d.get() - 1));
match answer {
Some(Ok(value)) => value.to_number().unwrap_or(0.0) as usize,
Some(Err(failure)) => {
#[cfg(feature = "std")]
if std::env::var_os("AHK_DEBUG_CALLBACK").is_some() {
eprintln!("the callback {} failed: {}", entry.name, failure.message);
}
0
}
None => 0,
}
}
extern "C" fn trampoline<const SLOT: usize>(
a0: usize,
a1: usize,
a2: usize,
a3: usize,
) -> usize {
invoke(SLOT, [a0, a1, a2, a3])
}
macro_rules! trampoline_array {
($($index:literal),* $(,)?) => {
static THE_TRAMPOLINES: [extern "C" fn(usize, usize, usize, usize) -> usize; THE_SLOTS] = [
$(trampoline::<$index>,)*
];
};
}
trampoline_array!(
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
);