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