Skip to main content

anvil/
input.rs

1//! `anvil-overlay.input`: keys and mouse buttons for plugins, from the game
2//! window's procedure, held back while the player types in the game or uses
3//! Anvil's panel (`anvil_input.h`, anvil-overlay 1.18.0).
4//!
5//! Depend on the overlay in plugin.toml (`[[dependencies]] id =
6//! "anvil-overlay"`, `optional = true` for a plugin that also works without
7//! it) and look the service up with [`Input::get`]. A code is a [`Key`]: what
8//! a setting of type `key` holds, a mouse button's virtual key with the same
9//! modifiers, or `Key(0)` for none.
10//!
11//! The first binding of a code keeps it: a second one is
12//! [`ErrorCode::Conflict`] and stays inert until it gets a free code. The
13//! handler runs on the game's main thread after the next outer frame, so it
14//! may read [`World`](crate::world::World). Without anvil-game,
15//! [`Input::bind`] is [`ErrorCode::Unsupported`].
16//!
17//! [`ErrorCode::Conflict`]: crate::ErrorCode::Conflict
18//! [`ErrorCode::Unsupported`]: crate::ErrorCode::Unsupported
19
20use 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
37/// The service's name.
38pub const SERVICE: &std::ffi::CStr = c"anvil-overlay.input";
39/// The service's major version.
40pub const VERSION: u32 = ANVIL_INPUT_SERVICE_VERSION;
41
42/// What holds input back now (`ANVIL_INPUT_*` of `state()`).
43#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
44pub struct State(pub u32);
45
46impl State {
47    /// Anvil's panel is open.
48    pub const OVERLAY_PANEL: u32 = ANVIL_INPUT_OVERLAY_PANEL;
49    /// The overlay takes the keyboard.
50    pub const OVERLAY_KEYBOARD: u32 = ANVIL_INPUT_OVERLAY_KEYBOARD;
51    /// The mouse is over a window of the overlay.
52    pub const OVERLAY_MOUSE: u32 = ANVIL_INPUT_OVERLAY_MOUSE;
53    /// A text field of the game has focus.
54    pub const GAME_TEXT: u32 = ANVIL_INPUT_GAME_TEXT;
55    /// The game's shortcut editor waits for a key.
56    pub const GAME_SHORTCUT: u32 = ANVIL_INPUT_GAME_SHORTCUT;
57    /// anvil-game cannot say whether the two above hold.
58    pub const GAME_UNKNOWN: u32 = ANVIL_INPUT_GAME_UNKNOWN;
59
60    /// Whether keys are held back.
61    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    /// Whether mouse buttons are held back.
67    pub const fn holds_mouse(self) -> bool {
68        self.0 & Self::OVERLAY_MOUSE != 0
69    }
70}
71
72/// How a binding treats a press.
73#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
74pub struct BindFlags {
75    /// The game does not see the press (it sees the release).
76    pub consume: bool,
77    /// Also the auto-repeat of a held key.
78    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/// A press of a binding's code.
89#[derive(Clone, Copy, Debug, PartialEq, Eq)]
90pub struct Press {
91    /// The binding's code at the press.
92    pub code: Key,
93    /// An auto-repeat.
94    pub repeat: bool,
95    /// The cursor at the press, in the window's client pixels.
96    pub x: i32,
97    /// See `x`.
98    pub y: i32,
99    /// anvil-game's frame number at the press.
100    pub frame: u64,
101}
102
103/// The `anvil-overlay.input` service.
104#[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/// A binding. It is `Copy`: the overlay keeps it until the process ends.
118#[derive(Clone, Copy)]
119pub struct Binding {
120    table: Table<AnvilInputService>,
121    raw: NonNull<AnvilInputBinding>,
122}
123
124// SAFETY: every input call may come from any thread (anvil_input.h, "Threads").
125unsafe impl Send for Binding {}
126// SAFETY: as above.
127unsafe 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    // SAFETY: the adapter bind registered, never freed.
145    let adapter = unsafe { &*context.cast::<PressAdapter<F>>() };
146    // SAFETY: the overlay's event, valid for the call, starting with its size.
147    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    /// The service; `None` without the overlay or with one older than 1.18.
164    pub fn get(host: &Host) -> Option<Self> {
165        // SAFETY: the table type of anvil-overlay.input version 1.
166        let table = unsafe { host.service::<AnvilInputService>(SERVICE, VERSION) }?;
167        Some(Self { table })
168    }
169
170    /// The C table, for what this crate does not wrap.
171    pub fn c_api(&self) -> Table<AnvilInputService> {
172        self.table
173    }
174
175    /// What holds input back now; `None` when the service lacks the call.
176    pub fn state(&self) -> Option<State> {
177        // SAFETY: the service's function.
178        function!(self.table, AnvilInputService, state)
179            .ok()
180            .map(|f| State(unsafe { f() }))
181    }
182
183    /// Binds `code` (`Key(0)` for none yet). A code another binding holds is
184    /// [`ErrorCode::Conflict`], and the overlay's inert binding is dropped:
185    /// use [`Input::bind_or_inert`] to keep it and give it a free code later.
186    /// 256 bindings a process, a dropped one included.
187    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    /// Binds `code` as [`Input::bind`] does, but keeps the binding when
198    /// another one holds the code, as the C API does: it is inert (code 0)
199    /// until [`Binding::set_code`] gives it a free one, such as from the key
200    /// setting's callback once the player picks another key. The error is
201    /// `Some` with [`ErrorCode::Conflict`] for such a binding, `None` when the
202    /// binding holds `code`. Other errors make no binding.
203    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        // Never freed: a queued press may still run the handler after unbind.
214        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        // SAFETY: an adapter that lives for the process and never unwinds, and an out pointer.
220        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            // A conflict without the binding the header promises: nothing to keep.
236            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    /// Whether the code's key is down with at least its modifiers, and not
249    /// held back: for what is polled every frame.
250    pub fn held(&self, code: Key) -> bool {
251        // SAFETY: the service's function.
252        function!(self.table, AnvilInputService, held)
253            .ok()
254            .is_some_and(|f| unsafe { f(code.0) } != 0)
255    }
256}
257
258impl Binding {
259    /// The raw binding, for the C table.
260    pub fn as_raw(&self) -> *mut AnvilInputBinding {
261        self.raw.as_ptr()
262    }
263
264    /// Another code, such as after its setting changed; `Key(0)` suspends it.
265    pub fn set_code(&self, code: Key) -> Result<()> {
266        let f = function!(self.table, AnvilInputService, set_code)?;
267        // SAFETY: the service's function with its binding.
268        check(unsafe { f(self.raw.as_ptr(), code.0) }, || {
269            format!("input set_code {:#x}", code.0)
270        })
271    }
272
273    /// Ends the binding: its queued presses are not delivered.
274    pub fn unbind(&self) -> Result<()> {
275        let f = function!(self.table, AnvilInputService, unbind)?;
276        // SAFETY: the service's function with its binding.
277        check(unsafe { f(self.raw.as_ptr()) }, || "input unbind")
278    }
279}