Skip to main content

oa/
input.rs

1//! `oa::input` — platform-neutral input layer.
2//!
3//! Donor: `oa/ui/platformInput.h` and `oa/ui/platformInput.cpp` (SDL3 backend),
4//! `oa/ui/input.h` and `oa/ui/input.cpp` (action registry).
5//!
6//! The module owns everything between the platform and consumers:
7//!
8//! - [`sdl_events`]: SDL3 event translation (pixel scale, wheel-direction
9//!   normalization, pinch-gesture bridging) into [`InputEvent`].
10//! - Per-frame snapshots: [`process_event`], [`update`], [`down`], [`press`],
11//!   [`release`], [`keyboard`], [`mouse`], [`pointer_position`].
12//! - [`InputSystem`]: named key-action registry with context dispatch.
13//!
14//! Per-frame usage:
15//!
16//! ```ignore
17//! oa::input::initialize();
18//! // each frame, before clearing deltas:
19//! for event in sdl_events { oa::input::process_event(&event); }
20//! oa::input::update();
21//! let mouse = oa::input::mouse();
22//! oa::input::clear_for_next_frame();
23//! ```
24//!
25//! State is thread-local, matching the donor's effectively main-thread SDL
26//! event pump: each thread that pumps events owns its own snapshot.
27
28use std::cell::{Cell, RefCell};
29
30use sdl3::event::Event as SdlEvent;
31
32mod actions;
33pub mod navigation;
34pub mod sdl_events;
35#[path = "input/type.gen.rs"]
36mod type_gen;
37#[path = "input/type.rs"]
38pub mod types;
39
40pub use actions::{InputContext, InputSystem, KeyAction, KeyBinding};
41pub use navigation::{Navigation, NavigationConfig};
42pub use types::{
43	GAMEPAD_AXIS_LEFT_TRIGGER, GAMEPAD_AXIS_LEFT_X, GAMEPAD_AXIS_LEFT_Y, GAMEPAD_AXIS_RIGHT_TRIGGER,
44	GAMEPAD_AXIS_RIGHT_X, GAMEPAD_AXIS_RIGHT_Y, GAMEPAD_BUTTON_BACK, GAMEPAD_BUTTON_DPAD_DOWN,
45	GAMEPAD_BUTTON_DPAD_LEFT, GAMEPAD_BUTTON_DPAD_RIGHT, GAMEPAD_BUTTON_DPAD_UP, GAMEPAD_BUTTON_EAST,
46	GAMEPAD_BUTTON_GUIDE, GAMEPAD_BUTTON_LEFT_SHOULDER, GAMEPAD_BUTTON_LEFT_STICK,
47	GAMEPAD_BUTTON_NORTH, GAMEPAD_BUTTON_RIGHT_SHOULDER, GAMEPAD_BUTTON_RIGHT_STICK,
48	GAMEPAD_BUTTON_SOUTH, GAMEPAD_BUTTON_START, GAMEPAD_BUTTON_WEST, INPUT_MOD_ALT, INPUT_MOD_CTRL,
49	INPUT_MOD_NONE, INPUT_MOD_SHIFT, INPUT_MOD_SUPER, InputEvent, InputEventKind, InputModifiers,
50	InputState, Key, MotionSpeed, PinchPhase, ScrollGesture,
51};
52
53/// Stable input-button identity for held/rising/falling queries.
54///
55/// Donor: `oa::input::Button`.
56#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
57pub enum Button {
58	#[default]
59	None,
60	MouseLeft,
61	MouseMiddle,
62	MouseRight,
63	KeyUp,
64	KeyDown,
65	KeyLeft,
66	KeyRight,
67	KeySpace,
68	KeyEscape,
69	KeyEnter,
70}
71
72/// Per-frame keyboard held-state snapshot, indexed by SDL scancode.
73///
74/// Donor: `oa::input::KeyboardState`.
75#[derive(Clone, Debug)]
76pub struct KeyboardState {
77	pub keys: [bool; 256],
78}
79
80impl Default for KeyboardState {
81	fn default() -> Self {
82		Self { keys: [false; 256] }
83	}
84}
85
86impl KeyboardState {
87	/// Return whether `key` is currently held.
88	#[must_use]
89	pub fn down(&self, key: Key) -> bool {
90		self.keys.get(key as usize).copied().unwrap_or(false)
91	}
92}
93
94/// Per-frame pointer-state snapshot.
95///
96/// Donor: `oa::input::MouseState`.
97#[derive(Clone, Debug, Default)]
98pub struct MouseState {
99	pub x: f32,
100	pub y: f32,
101	pub dx: f32,
102	pub dy: f32,
103	pub scroll_x: f32,
104	pub scroll_y: f32,
105	pub pressure: f32,
106	pub left: bool,
107	pub middle: bool,
108	pub right: bool,
109}
110
111struct FrameState {
112	keyboard: KeyboardState,
113	mouse: MouseState,
114	prev_keys: [bool; 256],
115	press_keys: [bool; 256],
116	release_keys: [bool; 256],
117	prev_left: bool,
118	prev_middle: bool,
119	prev_right: bool,
120	press_left: bool,
121	press_middle: bool,
122	press_right: bool,
123	release_left: bool,
124	release_middle: bool,
125	release_right: bool,
126	pointer_x: f32,
127	pointer_y: f32,
128}
129
130impl Default for FrameState {
131	fn default() -> Self {
132		Self {
133			keyboard: KeyboardState::default(),
134			mouse: MouseState::default(),
135			prev_keys: [false; 256],
136			press_keys: [false; 256],
137			release_keys: [false; 256],
138			prev_left: false,
139			prev_middle: false,
140			prev_right: false,
141			press_left: false,
142			press_middle: false,
143			press_right: false,
144			release_left: false,
145			release_middle: false,
146			release_right: false,
147			pointer_x: 0.0,
148			pointer_y: 0.0,
149		}
150	}
151}
152
153impl FrameState {
154	fn update_pointer(&mut self, x: f32, y: f32) {
155		self.pointer_x = x;
156		self.pointer_y = y;
157		self.mouse.x = x;
158		self.mouse.y = y;
159	}
160}
161
162thread_local! {
163	static FRAME_STATE: RefCell<FrameState> = RefCell::new(FrameState::default());
164	static INITIALIZED: Cell<bool> = const { Cell::new(false) };
165}
166
167/// Initialize the input backend. Idempotent.
168///
169/// Prefers native pinch gestures and precise wheel deltas on Wayland; the
170/// touchpad stays pointer/wheel input rather than raw touch.
171pub fn initialize() {
172	INITIALIZED.with(|flag| {
173		if flag.get() {
174			return;
175		}
176		// SAFETY: constant name/value pointers outlive the call.
177		unsafe {
178			sdl3::sys::hints::SDL_SetHint(
179				sdl3::sys::hints::SDL_HINT_TRACKPAD_IS_TOUCH_ONLY,
180				c"0".as_ptr(),
181			)
182		};
183		flag.set(true);
184	});
185}
186
187/// Reset all input snapshots.
188pub fn shutdown() {
189	FRAME_STATE.with(|state| *state.borrow_mut() = FrameState::default());
190	INITIALIZED.with(|flag| flag.set(false));
191}
192
193/// Feed one raw platform event into the per-frame snapshot.
194///
195/// Mouse motion/buttons/wheel fold into the pointer state; key down/up sets
196/// the scancode-indexed held bits. Press/release edges are derived by
197/// [`update`].
198///
199/// Donor: `oa::input::processEvent`.
200pub fn process_event(event: &SdlEvent) {
201	FRAME_STATE.with(|state| {
202		let state = &mut *state.borrow_mut();
203		match event {
204			SdlEvent::MouseMotion {
205				x, y, xrel, yrel, ..
206			} => {
207				state.mouse.dx += xrel;
208				state.mouse.dy += yrel;
209				state.update_pointer(*x, *y);
210			}
211			SdlEvent::MouseButtonDown {
212				x, y, mouse_btn, ..
213			} => {
214				state.update_pointer(*x, *y);
215				match mouse_button_index(*mouse_btn) {
216					1 => state.mouse.left = true,
217					2 => state.mouse.middle = true,
218					3 => state.mouse.right = true,
219					_ => {}
220				}
221			}
222			SdlEvent::MouseButtonUp {
223				x, y, mouse_btn, ..
224			} => {
225				state.update_pointer(*x, *y);
226				match mouse_button_index(*mouse_btn) {
227					1 => state.mouse.left = false,
228					2 => state.mouse.middle = false,
229					3 => state.mouse.right = false,
230					_ => {}
231				}
232			}
233			SdlEvent::MouseWheel {
234				x,
235				y,
236				mouse_x,
237				mouse_y,
238				..
239			} => {
240				state.mouse.scroll_x += x;
241				state.mouse.scroll_y += y;
242				state.update_pointer(*mouse_x, *mouse_y);
243			}
244			SdlEvent::KeyDown { scancode, .. } => {
245				if let Some(index) = scancode_index(*scancode) {
246					state.keyboard.keys[index] = true;
247				}
248			}
249			SdlEvent::KeyUp { scancode, .. } => {
250				if let Some(index) = scancode_index(*scancode) {
251					state.keyboard.keys[index] = false;
252				}
253			}
254			_ => {}
255		}
256	});
257}
258
259fn mouse_button_index(button: sdl3::mouse::MouseButton) -> i32 {
260	match button {
261		sdl3::mouse::MouseButton::Left => 1,
262		sdl3::mouse::MouseButton::Middle => 2,
263		sdl3::mouse::MouseButton::Right => 3,
264		sdl3::mouse::MouseButton::X1 => 4,
265		sdl3::mouse::MouseButton::X2 => 5,
266		sdl3::mouse::MouseButton::Unknown => 0,
267	}
268}
269
270fn scancode_index(scancode: Option<sdl3::keyboard::Scancode>) -> Option<usize> {
271	let index = scancode? as i32;
272	(0..256).contains(&index).then_some(index as usize)
273}
274
275/// Fold queued events into held/rising/falling edges.
276///
277/// Call once per frame after all [`process_event`] calls and before reading
278/// [`press`]/[`release`].
279pub fn update() {
280	FRAME_STATE.with(|state| {
281		let state = &mut *state.borrow_mut();
282		for index in 0..256 {
283			state.press_keys[index] = state.keyboard.keys[index] && !state.prev_keys[index];
284			state.release_keys[index] = !state.keyboard.keys[index] && state.prev_keys[index];
285			state.prev_keys[index] = state.keyboard.keys[index];
286		}
287		state.press_left = state.mouse.left && !state.prev_left;
288		state.press_middle = state.mouse.middle && !state.prev_middle;
289		state.press_right = state.mouse.right && !state.prev_right;
290		state.release_left = !state.mouse.left && state.prev_left;
291		state.release_middle = !state.mouse.middle && state.prev_middle;
292		state.release_right = !state.mouse.right && state.prev_right;
293		state.prev_left = state.mouse.left;
294		state.prev_middle = state.mouse.middle;
295		state.prev_right = state.mouse.right;
296	});
297}
298
299/// Clear per-frame deltas (scroll, motion delta, press/release edges).
300pub fn clear_for_next_frame() {
301	FRAME_STATE.with(|state| {
302		let state = &mut *state.borrow_mut();
303		state.mouse.dx = 0.0;
304		state.mouse.dy = 0.0;
305		state.mouse.scroll_x = 0.0;
306		state.mouse.scroll_y = 0.0;
307		state.press_left = false;
308		state.press_middle = false;
309		state.press_right = false;
310		state.release_left = false;
311		state.release_middle = false;
312		state.release_right = false;
313		state.press_keys.fill(false);
314		state.release_keys.fill(false);
315	});
316}
317
318/// Access the current keyboard held-state snapshot.
319pub fn keyboard<R>(read: impl FnOnce(&KeyboardState) -> R) -> R {
320	FRAME_STATE.with(|state| read(&state.borrow().keyboard))
321}
322
323/// Access the current pointer-state snapshot.
324pub fn mouse<R>(read: impl FnOnce(&MouseState) -> R) -> R {
325	FRAME_STATE.with(|state| read(&state.borrow().mouse))
326}
327
328/// Last known pointer position, updated on motion, buttons, and wheel.
329#[must_use]
330pub fn pointer_position() -> (f32, f32) {
331	FRAME_STATE.with(|state| {
332		let state = state.borrow();
333		(state.pointer_x, state.pointer_y)
334	})
335}
336
337fn button_scancode(button: Button) -> Option<usize> {
338	let key = match button {
339		Button::KeyUp => Key::Up,
340		Button::KeyDown => Key::Down,
341		Button::KeyLeft => Key::Left,
342		Button::KeyRight => Key::Right,
343		Button::KeySpace => Key::Space,
344		Button::KeyEscape => Key::Escape,
345		Button::KeyEnter => Key::Return,
346		_ => return None,
347	};
348	Some(key as usize)
349}
350
351enum ButtonEdge {
352	Mouse(usize),
353	Key(usize),
354}
355
356fn button_edge(button: Button) -> Option<ButtonEdge> {
357	match button {
358		Button::MouseLeft => Some(ButtonEdge::Mouse(0)),
359		Button::MouseMiddle => Some(ButtonEdge::Mouse(1)),
360		Button::MouseRight => Some(ButtonEdge::Mouse(2)),
361		_ => button_scancode(button).map(ButtonEdge::Key),
362	}
363}
364
365/// Return whether `button` is currently held.
366#[must_use]
367pub fn down(button: Button) -> bool {
368	FRAME_STATE.with(|state| {
369		let state = state.borrow();
370		match button {
371			Button::MouseLeft => state.mouse.left,
372			Button::MouseMiddle => state.mouse.middle,
373			Button::MouseRight => state.mouse.right,
374			_ => button_scancode(button).is_some_and(|index| state.keyboard.keys[index]),
375		}
376	})
377}
378
379/// Return whether `button` went down since the last [`update`].
380///
381/// Remains valid until [`clear_for_next_frame`].
382#[must_use]
383pub fn press(button: Button) -> bool {
384	FRAME_STATE.with(|state| {
385		let state = state.borrow();
386		match button_edge(button) {
387			Some(ButtonEdge::Mouse(0)) => state.press_left,
388			Some(ButtonEdge::Mouse(1)) => state.press_middle,
389			Some(ButtonEdge::Mouse(2)) => state.press_right,
390			Some(ButtonEdge::Key(index)) => state.press_keys[index],
391			_ => false,
392		}
393	})
394}
395
396/// Return whether `button` went up since the last [`update`].
397///
398/// Remains valid until [`clear_for_next_frame`].
399#[must_use]
400pub fn release(button: Button) -> bool {
401	FRAME_STATE.with(|state| {
402		let state = state.borrow();
403		match button_edge(button) {
404			Some(ButtonEdge::Mouse(0)) => state.release_left,
405			Some(ButtonEdge::Mouse(1)) => state.release_middle,
406			Some(ButtonEdge::Mouse(2)) => state.release_right,
407			Some(ButtonEdge::Key(index)) => state.release_keys[index],
408			_ => false,
409		}
410	})
411}