1use std::ffi::c_void;
21use std::fmt;
22use std::ptr::{self, NonNull};
23use std::sync::atomic::AtomicBool;
24
25use crate::error::{check, Error, ErrorCode, Result};
26use crate::event::read_sized;
27use crate::host::{Host, Key};
28use crate::panic::run_callback;
29use crate::sys::{
30 AnvilInputBinding, AnvilInputEvent, AnvilInputService, ANVIL_INPUT_CONSUME,
31 ANVIL_INPUT_EVENT_REPEAT, ANVIL_INPUT_GAME_SHORTCUT, ANVIL_INPUT_GAME_TEXT,
32 ANVIL_INPUT_GAME_UNKNOWN, ANVIL_INPUT_OVERLAY_KEYBOARD, ANVIL_INPUT_OVERLAY_MOUSE,
33 ANVIL_INPUT_OVERLAY_PANEL, ANVIL_INPUT_REPEAT, ANVIL_INPUT_SERVICE_VERSION,
34};
35use crate::table::Table;
36
37pub const SERVICE: &std::ffi::CStr = c"anvil-overlay.input";
39pub const VERSION: u32 = ANVIL_INPUT_SERVICE_VERSION;
41
42#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
44pub struct State(pub u32);
45
46impl State {
47 pub const OVERLAY_PANEL: u32 = ANVIL_INPUT_OVERLAY_PANEL;
49 pub const OVERLAY_KEYBOARD: u32 = ANVIL_INPUT_OVERLAY_KEYBOARD;
51 pub const OVERLAY_MOUSE: u32 = ANVIL_INPUT_OVERLAY_MOUSE;
53 pub const GAME_TEXT: u32 = ANVIL_INPUT_GAME_TEXT;
55 pub const GAME_SHORTCUT: u32 = ANVIL_INPUT_GAME_SHORTCUT;
57 pub const GAME_UNKNOWN: u32 = ANVIL_INPUT_GAME_UNKNOWN;
59
60 pub const fn holds_keys(self) -> bool {
62 self.0
63 & (Self::OVERLAY_PANEL | Self::OVERLAY_KEYBOARD | Self::GAME_TEXT | Self::GAME_SHORTCUT)
64 != 0
65 }
66 pub const fn holds_mouse(self) -> bool {
68 self.0 & Self::OVERLAY_MOUSE != 0
69 }
70}
71
72#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
74pub struct BindFlags {
75 pub consume: bool,
77 pub repeat: bool,
79}
80
81impl BindFlags {
82 fn raw(self) -> u32 {
83 (if self.consume { ANVIL_INPUT_CONSUME } else { 0 })
84 | (if self.repeat { ANVIL_INPUT_REPEAT } else { 0 })
85 }
86}
87
88#[derive(Clone, Copy, Debug, PartialEq, Eq)]
90pub struct Press {
91 pub code: Key,
93 pub repeat: bool,
95 pub x: i32,
97 pub y: i32,
99 pub frame: u64,
101}
102
103#[derive(Clone, Copy)]
105pub struct Input {
106 table: Table<AnvilInputService>,
107}
108
109impl fmt::Debug for Input {
110 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
111 f.debug_struct("Input")
112 .field("size", &self.table.size())
113 .finish()
114 }
115}
116
117#[derive(Clone, Copy)]
119pub struct Binding {
120 table: Table<AnvilInputService>,
121 raw: NonNull<AnvilInputBinding>,
122}
123
124unsafe impl Send for Binding {}
126unsafe impl Sync for Binding {}
128
129impl fmt::Debug for Binding {
130 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131 f.debug_tuple("Binding").field(&self.raw).finish()
132 }
133}
134
135struct PressAdapter<F> {
136 handler: F,
137 panicked: AtomicBool,
138}
139
140unsafe extern "C" fn press_adapter<F: Fn(Press) + Send + Sync + 'static>(
141 context: *mut c_void,
142 event: *const AnvilInputEvent,
143) {
144 let adapter = unsafe { &*context.cast::<PressAdapter<F>>() };
146 let Some(raw) = (unsafe { read_sized::<AnvilInputEvent>(event.cast()) }) else {
148 return;
149 };
150 let press = Press {
151 code: Key(raw.code),
152 repeat: raw.flags & ANVIL_INPUT_EVENT_REPEAT != 0,
153 x: raw.x,
154 y: raw.y,
155 frame: raw.frame,
156 };
157 run_callback("input handler", &adapter.panicked, (), || {
158 (adapter.handler)(press)
159 });
160}
161
162impl Input {
163 pub fn get(host: &Host) -> Option<Self> {
165 let table = unsafe { host.service::<AnvilInputService>(SERVICE, VERSION) }?;
167 Some(Self { table })
168 }
169
170 pub fn c_api(&self) -> Table<AnvilInputService> {
172 self.table
173 }
174
175 pub fn state(&self) -> Option<State> {
177 function!(self.table, AnvilInputService, state)
179 .ok()
180 .map(|f| State(unsafe { f() }))
181 }
182
183 pub fn bind<F>(&self, code: Key, flags: BindFlags, handler: F) -> Result<Binding>
188 where
189 F: Fn(Press) + Send + Sync + 'static,
190 {
191 match self.bind_or_inert(code, flags, handler)? {
192 (binding, None) => Ok(binding),
193 (_, Some(conflict)) => Err(conflict),
194 }
195 }
196
197 pub fn bind_or_inert<F>(
204 &self,
205 code: Key,
206 flags: BindFlags,
207 handler: F,
208 ) -> Result<(Binding, Option<Error>)>
209 where
210 F: Fn(Press) + Send + Sync + 'static,
211 {
212 let f = function!(self.table, AnvilInputService, bind)?;
213 let adapter: &'static PressAdapter<F> = Box::leak(Box::new(PressAdapter {
215 handler,
216 panicked: AtomicBool::new(false),
217 }));
218 let mut raw: *mut AnvilInputBinding = ptr::null_mut();
219 let result = unsafe {
221 f(
222 code.0,
223 flags.raw(),
224 Some(press_adapter::<F>),
225 ptr::from_ref(adapter).cast_mut().cast(),
226 &mut raw,
227 )
228 };
229 let conflict = match check(result, || format!("input bind {:#x}", code.0)) {
230 Ok(()) => None,
231 Err(error) if error.code() == ErrorCode::Conflict => Some(error),
232 Err(error) => return Err(error),
233 };
234 let Some(raw) = NonNull::new(raw) else {
235 return Err(conflict
237 .unwrap_or_else(|| Error::new(ErrorCode::Internal, "input bind: no binding")));
238 };
239 Ok((
240 Binding {
241 table: self.table,
242 raw,
243 },
244 conflict,
245 ))
246 }
247
248 pub fn held(&self, code: Key) -> bool {
251 function!(self.table, AnvilInputService, held)
253 .ok()
254 .is_some_and(|f| unsafe { f(code.0) } != 0)
255 }
256}
257
258impl Binding {
259 pub fn as_raw(&self) -> *mut AnvilInputBinding {
261 self.raw.as_ptr()
262 }
263
264 pub fn set_code(&self, code: Key) -> Result<()> {
266 let f = function!(self.table, AnvilInputService, set_code)?;
267 check(unsafe { f(self.raw.as_ptr(), code.0) }, || {
269 format!("input set_code {:#x}", code.0)
270 })
271 }
272
273 pub fn unbind(&self) -> Result<()> {
275 let f = function!(self.table, AnvilInputService, unbind)?;
276 check(unsafe { f(self.raw.as_ptr()) }, || "input unbind")
278 }
279}