Skip to main content

pushrod/
input.rs

1// Input
2// Pushrod
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! # Input
17//!
18//! Pushrod's own input vocabulary: [`Key`], [`Modifiers`], [`MouseButton`], and the
19//! [`InputEvent`]s a [`Backend`](crate::backend::Backend) delivers to the engine.  No windowing
20//! library type appears here, so a widget library never compiles against one.
21
22use crate::event::EventMask;
23use crate::geometry::{Point, Size};
24use bitflags::bitflags;
25
26/// A keyboard key, by what it means rather than where it sits.
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
28pub enum Key {
29    /// A printable key, as its lowercase character: `Char('a')`, `Char('.')`, `Char(' ')`.
30    Char(char),
31    /// The Tab key.
32    Tab,
33    /// The Return (Enter) key.
34    Return,
35    /// The Enter key on the numeric keypad.
36    KpEnter,
37    /// The Escape key.
38    Escape,
39    /// The Backspace key.
40    Backspace,
41    /// The Delete key.
42    Delete,
43    /// The Home key.
44    Home,
45    /// The End key.
46    End,
47    /// The Page Up key.
48    PageUp,
49    /// The Page Down key.
50    PageDown,
51    /// The Up arrow.
52    Up,
53    /// The Down arrow.
54    Down,
55    /// The Left arrow.
56    Left,
57    /// The Right arrow.
58    Right,
59    /// A function key, `F(1)` through `F(12)`.
60    F(u8),
61    /// A key the backend could not name; the number is the backend's own code.
62    Other(u32),
63}
64
65bitflags! {
66    /// The modifier keys held during a key event.  Left and right keys are not distinguished.
67    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
68    pub struct Modifiers: u8 {
69        /// A Shift key.
70        const SHIFT = 1;
71        /// A Control key.
72        const CTRL = 1 << 1;
73        /// An Alt (Option) key.
74        const ALT = 1 << 2;
75        /// A GUI key (Command on macOS, Windows key elsewhere).
76        const GUI = 1 << 3;
77    }
78}
79
80/// A mouse button.
81#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
82pub enum MouseButton {
83    /// The left (primary) button.
84    Left,
85    /// The middle button.
86    Middle,
87    /// The right (secondary) button.
88    Right,
89    /// An extra button; the number is the backend's own code.
90    Other(u8),
91}
92
93/// A window-system event a backend delivers to the engine, in window coordinates.
94#[derive(Debug, Clone, PartialEq)]
95pub enum InputEvent {
96    /// The user asked to close the window.
97    Quit,
98    /// The window needs repainting.
99    Exposed,
100    /// The window changed size.
101    Resized(Size),
102    /// The window gained or lost keyboard focus.
103    FocusChanged(bool),
104    /// A mouse button went down.
105    MouseDown {
106        /// The pointer position.
107        position: Point,
108        /// The button.
109        button: MouseButton,
110        /// The click count (1 single, 2 double).
111        clicks: u8,
112    },
113    /// A mouse button went up.
114    MouseUp {
115        /// The pointer position.
116        position: Point,
117        /// The button.
118        button: MouseButton,
119        /// The click count (1 single, 2 double).
120        clicks: u8,
121    },
122    /// The pointer moved.
123    MouseMove {
124        /// The pointer position.
125        position: Point,
126    },
127    /// The wheel or trackpad scrolled.
128    Wheel {
129        /// How far it scrolled, horizontally (`x`) and vertically (`y`).
130        delta: Point,
131    },
132    /// A key went down (or repeated).
133    KeyDown {
134        /// The key.
135        key: Key,
136        /// The modifier keys held.
137        modifiers: Modifiers,
138        /// `true` if this is an auto-repeat.
139        repeat: bool,
140    },
141    /// A key went up.
142    KeyUp {
143        /// The key.
144        key: Key,
145        /// The modifier keys held.
146        modifiers: Modifiers,
147    },
148    /// Text was typed.
149    Text(String),
150    /// Another thread asked the loop to wake; see [`Backend::waker`](crate::backend::Backend::waker).
151    Wake,
152}
153
154impl InputEvent {
155    /// The [`EventMask`] class this event belongs to.
156    ///
157    /// # Returns
158    ///
159    /// The class, or `None` for events that are never filtered: close requests, exposure and
160    /// resizing keep the window alive and up to date.
161    pub fn class(&self) -> Option<EventMask> {
162        match self {
163            InputEvent::Quit | InputEvent::Exposed | InputEvent::Resized(_) => None,
164            InputEvent::MouseDown { .. } | InputEvent::MouseUp { .. } => {
165                Some(EventMask::POINTER_BUTTONS)
166            }
167            InputEvent::MouseMove { .. } => Some(EventMask::POINTER_MOTION | EventMask::HOVER),
168            InputEvent::Wheel { .. } => Some(EventMask::SCROLL),
169            InputEvent::KeyDown { .. } | InputEvent::KeyUp { .. } => Some(EventMask::KEYBOARD),
170            InputEvent::Text(_) => Some(EventMask::TEXT),
171            InputEvent::FocusChanged(_) => Some(EventMask::WINDOW),
172            InputEvent::Wake => Some(EventMask::CUSTOM),
173        }
174    }
175}
176
177#[cfg(test)]
178mod tests {
179    use super::*;
180
181    #[test]
182    fn close_and_repaint_events_are_never_filtered() {
183        assert!(InputEvent::Quit.class().is_none());
184        assert!(InputEvent::Exposed.class().is_none());
185        assert!(InputEvent::Resized(Size { w: 1, h: 1 }).class().is_none());
186    }
187
188    #[test]
189    fn input_events_map_to_their_mask_classes() {
190        let down = InputEvent::KeyDown {
191            key: Key::Tab,
192            modifiers: Modifiers::empty(),
193            repeat: false,
194        };
195
196        assert_eq!(down.class(), Some(EventMask::KEYBOARD));
197        assert_eq!(InputEvent::Text("a".into()).class(), Some(EventMask::TEXT));
198        assert_eq!(InputEvent::Wake.class(), Some(EventMask::CUSTOM));
199        assert_eq!(
200            InputEvent::FocusChanged(true).class(),
201            Some(EventMask::WINDOW)
202        );
203    }
204
205    #[test]
206    fn modifiers_combine() {
207        let m = Modifiers::SHIFT | Modifiers::GUI;
208
209        assert!(m.contains(Modifiers::SHIFT));
210        assert!(!m.intersects(Modifiers::CTRL | Modifiers::ALT));
211    }
212}