use std::ffi::c_void;
use std::fmt;
use std::ptr::{self, NonNull};
use std::sync::atomic::AtomicBool;
use crate::error::{check, Error, ErrorCode, Result};
use crate::event::read_sized;
use crate::host::{Host, Key};
use crate::panic::run_callback;
use crate::sys::{
AnvilInputBinding, AnvilInputEvent, AnvilInputService, ANVIL_INPUT_CONSUME,
ANVIL_INPUT_EVENT_REPEAT, ANVIL_INPUT_GAME_SHORTCUT, ANVIL_INPUT_GAME_TEXT,
ANVIL_INPUT_GAME_UNKNOWN, ANVIL_INPUT_OVERLAY_KEYBOARD, ANVIL_INPUT_OVERLAY_MOUSE,
ANVIL_INPUT_OVERLAY_PANEL, ANVIL_INPUT_REPEAT, ANVIL_INPUT_SERVICE_VERSION,
};
pub const SERVICE: &std::ffi::CStr = c"anvil-overlay.input";
pub const VERSION: u32 = ANVIL_INPUT_SERVICE_VERSION;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct State(pub u32);
impl State {
pub const OVERLAY_PANEL: u32 = ANVIL_INPUT_OVERLAY_PANEL;
pub const OVERLAY_KEYBOARD: u32 = ANVIL_INPUT_OVERLAY_KEYBOARD;
pub const OVERLAY_MOUSE: u32 = ANVIL_INPUT_OVERLAY_MOUSE;
pub const GAME_TEXT: u32 = ANVIL_INPUT_GAME_TEXT;
pub const GAME_SHORTCUT: u32 = ANVIL_INPUT_GAME_SHORTCUT;
pub const GAME_UNKNOWN: u32 = ANVIL_INPUT_GAME_UNKNOWN;
pub const fn holds_keys(self) -> bool {
self.0
& (Self::OVERLAY_PANEL | Self::OVERLAY_KEYBOARD | Self::GAME_TEXT | Self::GAME_SHORTCUT)
!= 0
}
pub const fn holds_mouse(self) -> bool {
self.0 & Self::OVERLAY_MOUSE != 0
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct BindFlags {
pub consume: bool,
pub repeat: bool,
}
impl BindFlags {
fn raw(self) -> u32 {
(if self.consume { ANVIL_INPUT_CONSUME } else { 0 })
| (if self.repeat { ANVIL_INPUT_REPEAT } else { 0 })
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Press {
pub code: Key,
pub repeat: bool,
pub x: i32,
pub y: i32,
pub frame: u64,
}
#[derive(Clone, Copy)]
pub struct Input {
table: &'static AnvilInputService,
}
impl fmt::Debug for Input {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Input")
.field("size", &self.table.size)
.finish()
}
}
#[derive(Clone, Copy)]
pub struct Binding {
table: &'static AnvilInputService,
raw: NonNull<AnvilInputBinding>,
}
unsafe impl Send for Binding {}
unsafe impl Sync for Binding {}
impl fmt::Debug for Binding {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("Binding").field(&self.raw).finish()
}
}
struct PressAdapter<F> {
handler: F,
panicked: AtomicBool,
}
unsafe extern "C" fn press_adapter<F: Fn(Press) + Send + Sync + 'static>(
context: *mut c_void,
event: *const AnvilInputEvent,
) {
let adapter = unsafe { &*context.cast::<PressAdapter<F>>() };
let Some(raw) = (unsafe { read_sized::<AnvilInputEvent>(event.cast()) }) else {
return;
};
let press = Press {
code: Key(raw.code),
repeat: raw.flags & ANVIL_INPUT_EVENT_REPEAT != 0,
x: raw.x,
y: raw.y,
frame: raw.frame,
};
run_callback("input handler", &adapter.panicked, (), || {
(adapter.handler)(press)
});
}
impl Input {
pub fn get(host: &Host) -> Option<Self> {
let table = unsafe { host.service::<AnvilInputService>(SERVICE, VERSION) }?;
Some(Self { table })
}
pub fn c_api(&self) -> &'static AnvilInputService {
self.table
}
pub fn state(&self) -> Option<State> {
function!(self.table, AnvilInputService, state)
.ok()
.map(|f| State(unsafe { f() }))
}
pub fn bind<F>(&self, code: Key, flags: BindFlags, handler: F) -> Result<Binding>
where
F: Fn(Press) + Send + Sync + 'static,
{
match self.bind_or_inert(code, flags, handler)? {
(binding, None) => Ok(binding),
(_, Some(conflict)) => Err(conflict),
}
}
pub fn bind_or_inert<F>(
&self,
code: Key,
flags: BindFlags,
handler: F,
) -> Result<(Binding, Option<Error>)>
where
F: Fn(Press) + Send + Sync + 'static,
{
let f = function!(self.table, AnvilInputService, bind)?;
let adapter: &'static PressAdapter<F> = Box::leak(Box::new(PressAdapter {
handler,
panicked: AtomicBool::new(false),
}));
let mut raw: *mut AnvilInputBinding = ptr::null_mut();
let result = unsafe {
f(
code.0,
flags.raw(),
Some(press_adapter::<F>),
ptr::from_ref(adapter).cast_mut().cast(),
&mut raw,
)
};
let conflict = match check(result, || format!("input bind {:#x}", code.0)) {
Ok(()) => None,
Err(error) if error.code() == ErrorCode::Conflict => Some(error),
Err(error) => return Err(error),
};
let Some(raw) = NonNull::new(raw) else {
return Err(conflict
.unwrap_or_else(|| Error::new(ErrorCode::Internal, "input bind: no binding")));
};
Ok((
Binding {
table: self.table,
raw,
},
conflict,
))
}
pub fn held(&self, code: Key) -> bool {
function!(self.table, AnvilInputService, held)
.ok()
.is_some_and(|f| unsafe { f(code.0) } != 0)
}
}
impl Binding {
pub fn as_raw(&self) -> *mut AnvilInputBinding {
self.raw.as_ptr()
}
pub fn set_code(&self, code: Key) -> Result<()> {
let f = function!(self.table, AnvilInputService, set_code)?;
check(unsafe { f(self.raw.as_ptr(), code.0) }, || {
format!("input set_code {:#x}", code.0)
})
}
pub fn unbind(&self) -> Result<()> {
let f = function!(self.table, AnvilInputService, unbind)?;
check(unsafe { f(self.raw.as_ptr()) }, || "input unbind")
}
}