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