Skip to main content

mitsuami_core/
input.rs

1//! What a `GpuSurface` that takes input reports: keys by where they are on
2//! the keyboard, and the pointer over it, as the platform delivers them.
3
4use crate::geometry::Point;
5
6/// Input on a `GpuSurface` that takes it, reported as
7/// [`UiEvent::SurfaceInput`](crate::UiEvent::SurfaceInput).
8#[derive(Clone, Copy, Debug, PartialEq)]
9pub enum SurfaceInput {
10    /// A key went down, or up, while the surface had focus. `repeat`: the
11    /// platform's own repeat of a key held down.
12    Key {
13        code: KeyCode,
14        /// The platform's own code for the key: a macOS virtual key code,
15        /// a Linux evdev code, a Windows scan code (`0xE0` in the high
16        /// byte for extended keys).
17        native: u32,
18        pressed: bool,
19        repeat: bool,
20        modifiers: Modifiers,
21    },
22    /// The pointer moved over the surface (anywhere, while a button is
23    /// held), in points from its top left. Not reported while the pointer
24    /// is locked.
25    PointerMoved { position: Point, modifiers: Modifiers },
26    /// The pointer left the surface.
27    PointerLeft,
28    /// A button went down or up at `position`, in points from the
29    /// surface's top left.
30    Button { button: MouseButton, pressed: bool, position: Point, modifiers: Modifiers },
31    /// The wheel turned, or a trackpad scrolled. Positive: towards the end
32    /// (down, right), with the user's scrolling direction applied.
33    Scroll { delta: ScrollDelta, modifiers: Modifiers },
34    /// While the pointer is locked: how far it moved, in points,
35    /// accelerated as the cursor would be.
36    Motion { dx: f32, dy: f32 },
37    /// While the pointer is locked: how far the mouse moved, in the
38    /// device's own counts, before the host's acceleration. Reported with
39    /// `Motion`, for an app that applies its own (a virtual machine's
40    /// guest, a game's camera).
41    RawMotion { dx: f32, dy: f32 },
42}
43
44/// How far a scroll went.
45#[derive(Clone, Copy, Debug, PartialEq)]
46pub enum ScrollDelta {
47    /// A wheel's notches (fractions, for high-resolution wheels).
48    Lines { x: f32, y: f32 },
49    /// A trackpad's (or a precise wheel's) distance, in points.
50    Points { x: f32, y: f32 },
51}
52
53/// A pointer button, as the platform names it: the primary one is the
54/// left one for right-handed users.
55#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
56pub enum MouseButton {
57    Primary,
58    Secondary,
59    Middle,
60    Back,
61    Forward,
62    /// Another, by the platform's number for it.
63    Other(u16),
64}
65
66/// The modifier keys held with an event. `meta` is Command on macOS, the
67/// Super (Windows) key elsewhere.
68#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
69pub struct Modifiers {
70    pub shift: bool,
71    pub control: bool,
72    pub alt: bool,
73    pub meta: bool,
74}
75
76macro_rules! key_codes {
77    ($($name:ident),* $(,)?) => {
78        /// A key by where it is on the keyboard, whatever the layout says
79        /// it types: the W3C UI Events `code` names (`KeyA` is the key
80        /// right of Caps Lock, also on an AZERTY keyboard).
81        #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
82        pub enum KeyCode {
83            $($name,)*
84            /// A key without a name here: see the event's `native` code.
85            Unidentified,
86        }
87
88        impl KeyCode {
89            /// Its W3C `code` name.
90            pub fn name(self) -> &'static str {
91                match self {
92                    $(KeyCode::$name => stringify!($name),)*
93                    KeyCode::Unidentified => "Unidentified",
94                }
95            }
96        }
97    };
98}
99
100key_codes! {
101    KeyA, KeyB, KeyC, KeyD, KeyE, KeyF, KeyG, KeyH, KeyI, KeyJ, KeyK, KeyL, KeyM, KeyN, KeyO, KeyP, KeyQ, KeyR,
102    KeyS, KeyT, KeyU, KeyV, KeyW, KeyX, KeyY, KeyZ, Digit0, Digit1, Digit2, Digit3, Digit4, Digit5, Digit6, Digit7,
103    Digit8, Digit9, Backquote, Minus, Equal, BracketLeft, BracketRight, Backslash, Semicolon, Quote, Comma, Period,
104    Slash, IntlBackslash, IntlRo, IntlYen, Escape, Tab, CapsLock, Backspace, Enter, Space, ShiftLeft, ShiftRight,
105    ControlLeft, ControlRight, AltLeft, AltRight, MetaLeft, MetaRight, ContextMenu, Insert, Delete, Home, End,
106    PageUp, PageDown, ArrowUp, ArrowDown, ArrowLeft, ArrowRight, PrintScreen, ScrollLock, Pause, NumLock, Numpad0,
107    Numpad1, Numpad2, Numpad3, Numpad4, Numpad5, Numpad6, Numpad7, Numpad8, Numpad9, NumpadDivide, NumpadMultiply,
108    NumpadSubtract, NumpadAdd, NumpadEnter, NumpadDecimal, NumpadEqual, NumpadComma, KanaMode, Lang1, Lang2,
109    Convert, NonConvert, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, F16, F17, F18, F19, F20,
110    F21, F22, F23, F24,
111}
112
113use KeyCode::*;
114
115/// Linux evdev codes (`linux/input-event-codes.h`) from 1, in order;
116/// `Unidentified` for the ones without a name here.
117#[rustfmt::skip]
118const EVDEV: [KeyCode; 127] = [
119    Escape, Digit1, Digit2, Digit3, Digit4, Digit5, Digit6, Digit7, Digit8, Digit9, Digit0, Minus, Equal,
120    Backspace, Tab, KeyQ, KeyW, KeyE, KeyR, KeyT, KeyY, KeyU, KeyI, KeyO, KeyP, BracketLeft, BracketRight, Enter,
121    ControlLeft, KeyA, KeyS, KeyD, KeyF, KeyG, KeyH, KeyJ, KeyK, KeyL, Semicolon, Quote, Backquote, ShiftLeft,
122    Backslash, KeyZ, KeyX, KeyC, KeyV, KeyB, KeyN, KeyM, Comma, Period, Slash, ShiftRight, NumpadMultiply, AltLeft,
123    Space, CapsLock, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, NumLock, ScrollLock, Numpad7, Numpad8, Numpad9,
124    NumpadSubtract, Numpad4, Numpad5, Numpad6, NumpadAdd, Numpad1, Numpad2, Numpad3, Numpad0, NumpadDecimal,
125    // 84, 85 (zenkaku/hankaku), 86 (the ISO key), F11, F12, 89 (ro).
126    Unidentified, Unidentified, IntlBackslash, F11, F12, IntlRo,
127    // 90..=95: katakana, hiragana, henkan, katakana/hiragana, muhenkan,
128    // keypad JP comma.
129    Unidentified, Unidentified, Convert, KanaMode, NonConvert, NumpadComma, NumpadEnter, ControlRight,
130    NumpadDivide, PrintScreen, AltRight,
131    // 101: line feed.
132    Unidentified, Home, ArrowUp, PageUp, ArrowLeft, ArrowRight, End, ArrowDown, PageDown, Insert, Delete,
133    // 112..=116: macro, mute, volume down, volume up, power.
134    Unidentified, Unidentified, Unidentified, Unidentified, Unidentified, NumpadEqual,
135    // 118: keypad plus/minus.
136    Unidentified, Pause,
137    // 120: scale; 121: keypad comma.
138    Unidentified, NumpadComma, Lang1, Lang2, IntlYen, MetaLeft, MetaRight, ContextMenu,
139];
140
141/// macOS virtual key codes (`kVK_…`), from 0.
142#[rustfmt::skip]
143const MAC: [KeyCode; 127] = [
144    KeyA, KeyS, KeyD, KeyF, KeyH, KeyG, KeyZ, KeyX, KeyC, KeyV, IntlBackslash, KeyB, KeyQ, KeyW, KeyE, KeyR, KeyY,
145    KeyT, Digit1, Digit2, Digit3, Digit4, Digit6, Digit5, Equal, Digit9, Digit7, Minus, Digit8, Digit0,
146    BracketRight, KeyO, KeyU, BracketLeft, KeyI, KeyP, Enter, KeyL, KeyJ, Quote, KeyK, Semicolon, Backslash, Comma,
147    Slash, KeyN, KeyM, Period, Tab, Space, Backquote, Backspace,
148    // 0x34: unused.
149    Unidentified, Escape, MetaRight, MetaLeft, ShiftLeft, CapsLock, AltLeft, ControlLeft, ShiftRight, AltRight,
150    ControlRight,
151    // 0x3F: Fn.
152    Unidentified, F17, NumpadDecimal, Unidentified, NumpadMultiply, Unidentified, NumpadAdd, Unidentified,
153    // 0x47: Clear, where PC keyboards have Num Lock.
154    NumLock,
155    // 0x48..=0x4A: volume up, down, mute.
156    Unidentified, Unidentified, Unidentified, NumpadDivide, NumpadEnter, Unidentified, NumpadSubtract, F18, F19,
157    NumpadEqual, Numpad0, Numpad1, Numpad2, Numpad3, Numpad4, Numpad5, Numpad6, Numpad7, F20, Numpad8, Numpad9,
158    IntlYen, IntlRo, NumpadComma, F5, F6, F7, F3, F8, F9, Lang2, F11, Lang1, F13, F16, F14, Unidentified, F10,
159    ContextMenu, F12, Unidentified, F15,
160    // 0x72: Help, where PC keyboards have Insert.
161    Insert, Home, PageUp, Delete, F4, End, F2, PageDown, F1, ArrowLeft, ArrowRight, ArrowDown, ArrowUp,
162];
163
164impl KeyCode {
165    /// The key a Linux evdev code stands for (GTK's and Qt's hardware key
166    /// codes, on X11 and Wayland, are 8 more).
167    pub fn from_evdev(code: u32) -> KeyCode {
168        match code {
169            1..=127 => EVDEV[code as usize - 1],
170            183..=194 => [F13, F14, F15, F16, F17, F18, F19, F20, F21, F22, F23, F24][code as usize - 183],
171            _ => Unidentified,
172        }
173    }
174
175    /// The key an XKB keysym names, for the keys that type no character
176    /// (modifiers, Caps Lock, Escape, arrows, function keys); `None` for
177    /// the others. A keymap's options move these (`ctrl:swapcaps`,
178    /// `caps:escape`) above the evdev code, as macOS and Windows remap
179    /// below theirs, so they're read from the keysym the key types. Meta
180    /// is left out: it's Shift+Alt's keysym on most layouts.
181    pub fn from_keysym(keysym: u32) -> Option<KeyCode> {
182        Some(match keysym {
183            0xff1b => Escape,
184            0xff09 | 0xfe20 => Tab,
185            0xff0d => Enter,
186            0xff08 => Backspace,
187            0xffff => Delete,
188            0xff63 => Insert,
189            0xff50 => Home,
190            0xff57 => End,
191            0xff55 => PageUp,
192            0xff56 => PageDown,
193            0xff51 => ArrowLeft,
194            0xff52 => ArrowUp,
195            0xff53 => ArrowRight,
196            0xff54 => ArrowDown,
197            0xff61 => PrintScreen,
198            0xff67 => ContextMenu,
199            0xff13 => Pause,
200            0xff14 => ScrollLock,
201            0xff7f => NumLock,
202            0xffe5 => CapsLock,
203            0xffe1 => ShiftLeft,
204            0xffe2 => ShiftRight,
205            0xffe3 => ControlLeft,
206            0xffe4 => ControlRight,
207            0xffe9 => AltLeft,
208            // AltGr.
209            0xffea | 0xfe03 => AltRight,
210            0xffeb => MetaLeft,
211            0xffec => MetaRight,
212            0xffbe..=0xffd5 => [
213                F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, F16, F17, F18, F19, F20, F21, F22,
214                F23, F24,
215            ][keysym as usize - 0xffbe],
216            _ => return None,
217        })
218    }
219
220    /// The key a macOS virtual key code stands for.
221    pub fn from_mac(code: u16) -> KeyCode {
222        MAC.get(code as usize).copied().unwrap_or(Unidentified)
223    }
224
225    /// The key a Windows scan code stands for: set 1, `0xE0` in the high
226    /// byte for extended keys (as `WM_KEYDOWN` flags them).
227    pub fn from_windows_scancode(code: u32) -> KeyCode {
228        match code {
229            // Where set 1 and evdev agree.
230            0x01..=0x53 if code != 0x45 => EVDEV[code as usize - 1],
231            // Pause comes without the extended flag, Num Lock with it.
232            0x45 => Pause,
233            0x56 => IntlBackslash,
234            0x57 => F11,
235            0x58 => F12,
236            0x59 => NumpadEqual,
237            0x64..=0x6E => [F13, F14, F15, F16, F17, F18, F19, F20, F21, F22, F23][code as usize - 0x64],
238            0x70 => KanaMode,
239            0x73 => IntlRo,
240            0x76 => F24,
241            0x79 => Convert,
242            0x7B => NonConvert,
243            0x7D => IntlYen,
244            0x7E => NumpadComma,
245            0x54 => PrintScreen,
246            0xE01C => NumpadEnter,
247            0xE01D => ControlRight,
248            0xE035 => NumpadDivide,
249            0xE037 => PrintScreen,
250            0xE038 => AltRight,
251            0xE045 => NumLock,
252            0xE047 => Home,
253            0xE048 => ArrowUp,
254            0xE049 => PageUp,
255            0xE04B => ArrowLeft,
256            0xE04D => ArrowRight,
257            0xE04F => End,
258            0xE050 => ArrowDown,
259            0xE051 => PageDown,
260            0xE052 => Insert,
261            0xE053 => Delete,
262            0xE05B => MetaLeft,
263            0xE05C => MetaRight,
264            0xE05D => ContextMenu,
265            0x72 => Lang1,
266            0x71 => Lang2,
267            _ => Unidentified,
268        }
269    }
270
271    /// The key that types this character on a US keyboard, unshifted:
272    /// what tests type.
273    pub fn from_us_char(c: char) -> KeyCode {
274        const LETTERS: [KeyCode; 26] = [
275            KeyA, KeyB, KeyC, KeyD, KeyE, KeyF, KeyG, KeyH, KeyI, KeyJ, KeyK, KeyL, KeyM, KeyN, KeyO, KeyP, KeyQ, KeyR,
276            KeyS, KeyT, KeyU, KeyV, KeyW, KeyX, KeyY, KeyZ,
277        ];
278        const DIGITS: [KeyCode; 10] = [Digit0, Digit1, Digit2, Digit3, Digit4, Digit5, Digit6, Digit7, Digit8, Digit9];
279        match c.to_ascii_lowercase() {
280            c @ 'a'..='z' => LETTERS[c as usize - 'a' as usize],
281            c @ '0'..='9' => DIGITS[c as usize - '0' as usize],
282            ' ' => Space,
283            '`' => Backquote,
284            '-' => Minus,
285            '=' => Equal,
286            '[' => BracketLeft,
287            ']' => BracketRight,
288            '\\' => Backslash,
289            ';' => Semicolon,
290            '\'' => Quote,
291            ',' => Comma,
292            '.' => Period,
293            '/' => Slash,
294            _ => Unidentified,
295        }
296    }
297
298    /// The key that types or is `key` on a US keyboard: what tests press.
299    pub fn from_key(key: crate::backend::Key) -> KeyCode {
300        use crate::backend::Key;
301        const F: [KeyCode; 24] = [
302            F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, F16, F17, F18, F19, F20, F21, F22, F23,
303            F24,
304        ];
305        match key {
306            Key::Char(c) => KeyCode::from_us_char(c),
307            Key::Enter => Enter,
308            Key::Escape => Escape,
309            Key::Tab => Tab,
310            Key::Backspace => Backspace,
311            Key::Delete => Delete,
312            Key::Up => ArrowUp,
313            Key::Down => ArrowDown,
314            Key::Left => ArrowLeft,
315            Key::Right => ArrowRight,
316            Key::Home => Home,
317            Key::End => End,
318            Key::PageUp => PageUp,
319            Key::PageDown => PageDown,
320            Key::F(n) => F.get(usize::from(n).wrapping_sub(1)).copied().unwrap_or(Unidentified),
321        }
322    }
323}