Skip to main content

wgame_input/
lib.rs

1//! Input for a drawing area, independent of a windowing or UI backend.
2//!
3//! Positions and scrolling use local logical pixels, X right and Y down.
4//! Adapters produce one [`CanvasInput`] per application frame. Events retain the
5//! order supplied by that adapter, not necessarily the original OS event history.
6//! A canvas has one primary pointer (mouse or primary touch), five buttons, and
7//! logical keys. Text editing, IME, individual touch IDs and raw device motion
8//! belong to the host's platform/UI API.
9//!
10//! Capture belongs to the canvas where a press started. Movement and release may
11//! occur outside its bounds. [`Event::Cancelled`] ends all held interactions on
12//! focus loss, geometry changes, or removal; it must not activate a click action.
13
14#![forbid(unsafe_code)]
15
16use glam::Vec2;
17use std::collections::BTreeSet;
18
19#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20pub enum Button {
21    Primary,
22    Secondary,
23    Middle,
24    Back,
25    Forward,
26}
27impl Button {
28    pub const ALL: [Self; 5] = [
29        Self::Primary,
30        Self::Secondary,
31        Self::Middle,
32        Self::Back,
33        Self::Forward,
34    ];
35}
36
37/// Logical key; letters are lowercase, independent of Shift. Use platform events
38/// for physical key locations. Text entry should be handled by the UI host.
39#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
40pub enum Key {
41    Character(char),
42    Escape,
43    Space,
44    Enter,
45    Tab,
46    Backspace,
47    Delete,
48    Home,
49    End,
50    PageUp,
51    PageDown,
52    ArrowLeft,
53    ArrowRight,
54    ArrowUp,
55    ArrowDown,
56    Plus,
57    Minus,
58}
59
60#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
61pub struct Modifiers {
62    pub shift: bool,
63    pub control: bool,
64    pub alt: bool,
65    pub command: bool,
66}
67
68#[derive(Clone, Copy, Debug, PartialEq)]
69pub enum Event {
70    Moved(Vec2),
71    Button {
72        button: Button,
73        pressed: bool,
74        position: Vec2,
75    },
76    /// Logical pixels. Positive Y follows the host's scroll direction.
77    Scroll(Vec2),
78    Key {
79        key: Key,
80        pressed: bool,
81        repeat: bool,
82    },
83    /// OS window focus; distinct from this canvas's keyboard focus.
84    Focused(bool),
85    Cancelled,
86}
87
88/// Immutable input paired with one content frame.
89#[derive(Clone, Debug, Default)]
90pub struct CanvasInput {
91    /// Summed relative mouse motion in platform-defined device units. Unaffected
92    /// by display scaling. Hosts provide it only while this canvas is focused;
93    /// cancellation clears it. Do not also use pointer deltas for the same motion.
94    pub relative_motion: Vec2,
95    pub events: Vec<Event>,
96    pub pointer: Option<Vec2>,
97    pub hovered: bool,
98    pub focused: bool,
99    pub window_focused: bool,
100    pub modifiers: Modifiers,
101    buttons: [bool; 5],
102    keys: BTreeSet<Key>,
103}
104impl CanvasInput {
105    pub fn button_down(&self, button: Button) -> bool {
106        self.buttons[button as usize]
107    }
108    pub fn key_down(&self, key: Key) -> bool {
109        self.keys.contains(&key)
110    }
111}
112
113/// Adapter-side accumulator. Clearing a frame keeps held state; cancellation
114/// clears held state and emits an explicit cancellation instead of fake releases.
115#[derive(Default)]
116pub struct InputState {
117    input: CanvasInput,
118}
119impl InputState {
120    pub fn input(&self) -> &CanvasInput {
121        &self.input
122    }
123    pub fn push(&mut self, event: Event) {
124        match event {
125            Event::Moved(pos) => self.input.pointer = Some(pos),
126            Event::Button {
127                button,
128                pressed,
129                position,
130            } => {
131                self.input.pointer = Some(position);
132                self.input.buttons[button as usize] = pressed;
133            }
134            Event::Key { key, pressed, .. } => {
135                if pressed {
136                    self.input.keys.insert(key);
137                } else {
138                    self.input.keys.remove(&key);
139                }
140            }
141            Event::Focused(value) => {
142                self.input.window_focused = value;
143                if !value {
144                    self.push(Event::Cancelled);
145                }
146            }
147            Event::Cancelled => {
148                self.input.buttons.fill(false);
149                self.input.keys.clear();
150                self.input.pointer = None;
151                self.input.relative_motion = Vec2::ZERO;
152            }
153            Event::Scroll(_) => {}
154        }
155        self.input.events.push(event);
156    }
157    pub fn finish(&mut self, hovered: bool, focused: bool, modifiers: Modifiers) -> CanvasInput {
158        self.input.hovered = hovered;
159        self.input.focused = focused;
160        self.input.modifiers = modifiers;
161        let result = self.input.clone();
162        self.input.events.clear();
163        result
164    }
165}
166
167#[cfg(test)]
168mod tests {
169    use super::*;
170    #[test]
171    fn held_state_survives_frames_but_cancellation_never_activates_release() {
172        let mut state = InputState::default();
173        state.push(Event::Button {
174            button: Button::Primary,
175            pressed: true,
176            position: Vec2::ONE,
177        });
178        state.push(Event::Key {
179            key: Key::Space,
180            pressed: true,
181            repeat: false,
182        });
183        assert_eq!(
184            state.finish(true, true, Modifiers::default()).events.len(),
185            2
186        );
187        let frame = state.finish(false, true, Modifiers::default());
188        assert!(frame.button_down(Button::Primary) && frame.key_down(Key::Space));
189        assert!(frame.events.is_empty());
190        state.push(Event::Focused(false));
191        let frame = state.finish(false, false, Modifiers::default());
192        assert!(!frame.button_down(Button::Primary) && !frame.key_down(Key::Space));
193        assert_eq!(frame.events, [Event::Cancelled, Event::Focused(false)]);
194    }
195    #[test]
196    fn press_and_release_within_one_frame_are_both_retained() {
197        let mut state = InputState::default();
198        for pressed in [true, false] {
199            state.push(Event::Button {
200                button: Button::Primary,
201                pressed,
202                position: Vec2::ZERO,
203            });
204        }
205        let frame = state.finish(true, true, Modifiers::default());
206        assert_eq!(frame.events.len(), 2);
207        assert!(!frame.button_down(Button::Primary));
208    }
209}