crcbl_core/input.rs
1//! Input vocabulary: the names every layer of the engine uses for keys,
2//! buttons, axes and the devices they came from.
3//!
4//! # Why this is in `crcbl-core` and not in `crcbl-shell`
5//!
6//! The shell-boundary rule in `docs/notes/backends.md` puts "input event
7//! normalisation into engine types" in `crcbl-core::input`, and the input
8//! design (`docs/notes/simulation.md`, _What the deleted 19-input plan left
9//! behind_) explains why: the action layer (`crcbl-input`, P2), the profile
10//! store (topic 14, where user rebinds are serialized), the UI (glyph hints),
11//! and the editor all have to *name* a key. If [`KeyCode`] lived in the
12//! windowing crate, the save-game crate would depend on a windowing library to
13//! spell `Space`, and a headless `crcbl sim` replay would link a shell it never
14//! opens.
15//!
16//! The split is therefore:
17//!
18//! ```text
19//! crcbl-core::input vocabulary — KeyCode, Keysym, PointerButton, Modifiers,
20//! ButtonState, ScrollDelta, DeviceId,
21//! ContactId, TouchPhase, CursorIcon
22//! crcbl-shell events — ShellEvent, which names windows and is only
23//! ever produced by a shell backend
24//! ```
25//!
26//! Nothing here knows what a window is, and nothing here allocates.
27//!
28//! # Physical versus logical: three coordinates for one keystroke
29//!
30//! A key press carries three independent facts, and conflating any two of them
31//! is the classic input bug:
32//!
33//! | Fact | Type | Depends on layout? | Used for |
34//! | --- | --- | --- | --- |
35//! | Which key was pressed | [`KeyCode`] | no | gameplay bindings ("W moves forward" stays under the W key on AZERTY) |
36//! | What the OS calls that key | [`Scancode`] | no | round-tripping keys we have no name for |
37//! | What symbol it produces | [`Keysym`] | **yes** | rebind menus, shortcut display, layout-sensitive shortcuts |
38//!
39//! The symbol comes twice on a shell's key event: as the key produces it, and
40//! as it would with Caps Lock off (`ShellEvent::Key`'s `shortcut_keysym`). A
41//! shortcut matches the second, so `Ctrl+R` with Caps Lock on is still
42//! `Ctrl+r`; text and labels read the first. The difference is the layout's,
43//! not a case swap: AZERTY's `caps:digits_row` makes Caps Lock move the digit
44//! row as well. A Shift Lock (`caps:shiftlock`) is a locked Shift, not Caps
45//! Lock, so it stays applied to both symbols and in [`Modifiers`].
46//!
47//! And a fourth, which is not a keystroke at all: **text**. Composed text
48//! arrives as a separate commit string (`ShellEvent::TextCommit`) because IME
49//! input has no one-to-one relationship with key presses — one keystroke can
50//! commit five characters, five keystrokes can commit one, and a dead key
51//! commits nothing.
52//!
53//! # `Keysym` is the X11/XKB namespace
54//!
55//! [`Keysym`] holds an X11 keysym value, which is what `xkbcommon` produces.
56//! This is a decision, not an accident: two of the five planned shell backends
57//! (Wayland and X11 — the only two that exist at P0) produce these natively,
58//! and the other three need a translation table whatever namespace we pick.
59//! Inventing an engine-specific symbol enum would mean *three* tables instead of
60//! two plus a well-documented, stable, externally-specified numbering that
61//! already covers every keyboard symbol anyone has ever shipped.
62
63use core::fmt;
64
65bitflags::bitflags! {
66 /// Modifier keys held when an input event was produced.
67 ///
68 /// Latched state (Caps Lock, Num Lock) is included alongside held state
69 /// because a rebind UI and a shortcut matcher both need it, and asking the
70 /// shell for it later — after the event has been queued — would race with
71 /// the user letting go.
72 ///
73 /// Left and right modifiers are *not* distinguished here. The distinction
74 /// survives in [`KeyCode`] ([`ShiftLeft`](KeyCode::ShiftLeft) versus
75 /// [`ShiftRight`](KeyCode::ShiftRight)), which is where a game that wants to
76 /// bind them separately should look; a shortcut matcher never wants it, and
77 /// duplicating the axis here would mean every `contains(SHIFT)` check had to
78 /// remember to test two bits.
79 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
80 pub struct Modifiers: u32 {
81 /// Either Shift key is held.
82 const SHIFT = 1 << 0;
83 /// Either Control key is held.
84 const CTRL = 1 << 1;
85 /// Either Alt key is held (Option on macOS).
86 const ALT = 1 << 2;
87 /// Either Super key is held — Windows key, Command on macOS, Meta on
88 /// X11.
89 const SUPER = 1 << 3;
90 /// Caps Lock is latched on.
91 const CAPS_LOCK = 1 << 4;
92 /// Num Lock is latched on.
93 const NUM_LOCK = 1 << 5;
94 /// AltGr / ISO Level-3 Shift is held.
95 ///
96 /// Separate from [`ALT`](Self::ALT) because on many European layouts
97 /// AltGr produces characters, and a shortcut bound to `Alt+E` must not
98 /// fire when the user types `€`.
99 const ALT_GR = 1 << 6;
100 }
101}
102
103impl Modifiers {
104 /// The modifiers a shortcut matcher cares about: Shift, Ctrl, Alt, Super.
105 ///
106 /// Masks off latched state, which is never part of a chord.
107 pub const CHORD: Self = Self::SHIFT
108 .union(Self::CTRL)
109 .union(Self::ALT)
110 .union(Self::SUPER);
111
112 /// Just the chord bits of `self`.
113 #[inline]
114 #[must_use]
115 pub const fn chord(self) -> Self {
116 self.intersection(Self::CHORD)
117 }
118}
119
120/// Which physical device an event came from.
121///
122/// The input design requires a per-device id on raw events from day one,
123/// because local-multiplayer device-to-player assignment is post-MVP but is
124/// impossible to retrofit into an event stream that never said which keyboard
125/// pressed the key. Ids are unique for the lifetime of the process and are not
126/// reused when a device is unplugged.
127#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
128pub struct DeviceId(pub u32);
129
130impl DeviceId {
131 /// The device that events with no attributable source carry.
132 ///
133 /// Backends that cannot tell two keyboards apart (X11 core protocol without
134 /// XInput2, and the browser) use this for everything, and so do synthesized
135 /// events from a replay or a test script.
136 pub const UNKNOWN: Self = Self(0);
137}
138
139impl fmt::Display for DeviceId {
140 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141 if *self == Self::UNKNOWN {
142 f.write_str("device ?")
143 } else {
144 write!(f, "device {}", self.0)
145 }
146 }
147}
148
149/// Whether a two-state input element went down or came up.
150///
151/// One type for keyboard keys, pointer buttons and gamepad buttons: they are
152/// the same fact, and a separate `KeyState`/`MouseState` pair only creates
153/// conversion noise at the action layer, which treats all three identically.
154#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
155pub enum ButtonState {
156 /// The element went down.
157 Pressed,
158 /// The element came up.
159 Released,
160}
161
162impl ButtonState {
163 /// Whether this is [`ButtonState::Pressed`].
164 #[inline]
165 #[must_use]
166 pub const fn is_pressed(self) -> bool {
167 matches!(self, Self::Pressed)
168 }
169
170 /// [`Pressed`](Self::Pressed) for `true`, [`Released`](Self::Released) for
171 /// `false`.
172 #[inline]
173 #[must_use]
174 pub const fn from_pressed(pressed: bool) -> Self {
175 if pressed {
176 Self::Pressed
177 } else {
178 Self::Released
179 }
180 }
181}
182
183/// The raw, platform-assigned code for a physical key.
184///
185/// Opaque on purpose: its numbering is whatever the window system uses (Linux
186/// evdev codes offset by 8 on both Wayland and X11, `MapVirtualKey` scan codes
187/// on Win32, `kVK_*` on macOS). It exists so a key the engine has no
188/// [`KeyCode`] name for can still be bound, logged and round-tripped through a
189/// profile rather than being silently dropped.
190///
191/// Never compare a `Scancode` against a literal in engine code — that is
192/// platform sniffing with extra steps. Compare [`KeyCode`].
193#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
194pub struct Scancode(pub u32);
195
196impl fmt::Display for Scancode {
197 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
198 write!(f, "scancode {}", self.0)
199 }
200}
201
202/// A layout-mapped key symbol, in the X11/XKB keysym numbering.
203///
204/// See the [module docs](self) for why that numbering. The values a game
205/// actually wants are usually reachable through [`Keysym::to_char`]; the raw
206/// number matters only for named function keys, which live above
207/// `0xFF00`.
208#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
209pub struct Keysym(pub u32);
210
211impl Keysym {
212 /// No symbol — a key that produces nothing in the current layout, or a
213 /// backend that could not map one. `XKB_KEY_NoSymbol`.
214 pub const NONE: Self = Self(0);
215
216 // The keys whose symbol no layout moves, by their X11 names (`XK_` dropped,
217 // in `SCREAMING_CASE`), from `X11/keysymdef.h`. Compare
218 // `ShellEvent::Key`'s `keysym` against these, not its `key_code`, to act on
219 // the key the layout produced: `key_code` is the physical key, which an xkb
220 // remap (`caps:escape`) or a virtual keyboard's own keymap does not change.
221 /// `XK_BackSpace`.
222 pub const BACKSPACE: Self = Self(0xFF08);
223 /// `XK_Tab`.
224 pub const TAB: Self = Self(0xFF09);
225 /// `XK_Return`.
226 pub const RETURN: Self = Self(0xFF0D);
227 /// `XK_Pause`.
228 pub const PAUSE: Self = Self(0xFF13);
229 /// `XK_Scroll_Lock`.
230 pub const SCROLL_LOCK: Self = Self(0xFF14);
231 /// `XK_Escape`.
232 pub const ESCAPE: Self = Self(0xFF1B);
233 /// `XK_Home`.
234 pub const HOME: Self = Self(0xFF50);
235 /// `XK_Left`.
236 pub const LEFT: Self = Self(0xFF51);
237 /// `XK_Up`.
238 pub const UP: Self = Self(0xFF52);
239 /// `XK_Right`.
240 pub const RIGHT: Self = Self(0xFF53);
241 /// `XK_Down`.
242 pub const DOWN: Self = Self(0xFF54);
243 /// `XK_Prior`.
244 pub const PAGE_UP: Self = Self(0xFF55);
245 /// `XK_Next`.
246 pub const PAGE_DOWN: Self = Self(0xFF56);
247 /// `XK_End`.
248 pub const END: Self = Self(0xFF57);
249 /// `XK_Print`.
250 pub const PRINT: Self = Self(0xFF61);
251 /// `XK_Insert`.
252 pub const INSERT: Self = Self(0xFF63);
253 /// `XK_Menu`.
254 pub const MENU: Self = Self(0xFF67);
255 /// `XK_Num_Lock`.
256 pub const NUM_LOCK: Self = Self(0xFF7F);
257 /// `XK_KP_Enter`.
258 pub const KP_ENTER: Self = Self(0xFF8D);
259 /// `XK_KP_Multiply`.
260 pub const KP_MULTIPLY: Self = Self(0xFFAA);
261 /// `XK_KP_Add`.
262 pub const KP_ADD: Self = Self(0xFFAB);
263 /// `XK_KP_Subtract`.
264 pub const KP_SUBTRACT: Self = Self(0xFFAD);
265 /// `XK_KP_Decimal`.
266 pub const KP_DECIMAL: Self = Self(0xFFAE);
267 /// `XK_KP_Divide`.
268 pub const KP_DIVIDE: Self = Self(0xFFAF);
269 /// `XK_KP_0`.
270 pub const KP_0: Self = Self(0xFFB0);
271 /// `XK_KP_1`.
272 pub const KP_1: Self = Self(0xFFB1);
273 /// `XK_KP_2`.
274 pub const KP_2: Self = Self(0xFFB2);
275 /// `XK_KP_3`.
276 pub const KP_3: Self = Self(0xFFB3);
277 /// `XK_KP_4`.
278 pub const KP_4: Self = Self(0xFFB4);
279 /// `XK_KP_5`.
280 pub const KP_5: Self = Self(0xFFB5);
281 /// `XK_KP_6`.
282 pub const KP_6: Self = Self(0xFFB6);
283 /// `XK_KP_7`.
284 pub const KP_7: Self = Self(0xFFB7);
285 /// `XK_KP_8`.
286 pub const KP_8: Self = Self(0xFFB8);
287 /// `XK_KP_9`.
288 pub const KP_9: Self = Self(0xFFB9);
289 /// `XK_F1`.
290 pub const F1: Self = Self(0xFFBE);
291 /// `XK_F2`.
292 pub const F2: Self = Self(0xFFBF);
293 /// `XK_F3`.
294 pub const F3: Self = Self(0xFFC0);
295 /// `XK_F4`.
296 pub const F4: Self = Self(0xFFC1);
297 /// `XK_F5`.
298 pub const F5: Self = Self(0xFFC2);
299 /// `XK_F6`.
300 pub const F6: Self = Self(0xFFC3);
301 /// `XK_F7`.
302 pub const F7: Self = Self(0xFFC4);
303 /// `XK_F8`.
304 pub const F8: Self = Self(0xFFC5);
305 /// `XK_F9`.
306 pub const F9: Self = Self(0xFFC6);
307 /// `XK_F10`.
308 pub const F10: Self = Self(0xFFC7);
309 /// `XK_F11`.
310 pub const F11: Self = Self(0xFFC8);
311 /// `XK_F12`.
312 pub const F12: Self = Self(0xFFC9);
313 /// `XK_Shift_L`.
314 pub const SHIFT_L: Self = Self(0xFFE1);
315 /// `XK_Shift_R`.
316 pub const SHIFT_R: Self = Self(0xFFE2);
317 /// `XK_Control_L`.
318 pub const CONTROL_L: Self = Self(0xFFE3);
319 /// `XK_Control_R`.
320 pub const CONTROL_R: Self = Self(0xFFE4);
321 /// `XK_Caps_Lock`.
322 pub const CAPS_LOCK: Self = Self(0xFFE5);
323 /// `XK_Alt_L`.
324 pub const ALT_L: Self = Self(0xFFE9);
325 /// `XK_Alt_R`.
326 pub const ALT_R: Self = Self(0xFFEA);
327 /// `XK_Super_L`.
328 pub const SUPER_L: Self = Self(0xFFEB);
329 /// `XK_Super_R`.
330 pub const SUPER_R: Self = Self(0xFFEC);
331 /// `XK_Delete`.
332 pub const DELETE: Self = Self(0xFFFF);
333
334 /// Start of the "Unicode keysym" block: `0x0100_0000 | codepoint`.
335 const UNICODE_BASE: u32 = 0x0100_0000;
336
337 /// The character this symbol produces, if it produces one.
338 ///
339 /// Implements the two rules XKB uses: keysyms `0x20..=0x7E` and
340 /// `0xA0..=0xFF` are Latin-1 directly, and everything else that maps to a
341 /// character is `0x0100_0000 | codepoint`. Function keys, modifiers and
342 /// dead keys return `None`.
343 ///
344 /// This deliberately does **not** cover the several hundred legacy
345 /// non-Latin-1 keysyms that predate the Unicode block (Greek, Cyrillic and
346 /// friends in `0x05xx`–`0x07xx`). Text input is delivered as committed
347 /// strings, not reconstructed from keysyms, so the table would exist only
348 /// to be wrong in a way nobody notices; a shortcut label falls back to the
349 /// [`KeyCode`] name.
350 #[must_use]
351 pub const fn to_char(self) -> Option<char> {
352 let codepoint = match self.0 {
353 0x20..=0x7E | 0xA0..=0xFF => self.0,
354 value if value >= Self::UNICODE_BASE => value - Self::UNICODE_BASE,
355 _ => return None,
356 };
357 char::from_u32(codepoint)
358 }
359
360 /// The keysym for a character, in the canonical form XKB produces.
361 #[must_use]
362 pub const fn from_char(character: char) -> Self {
363 let codepoint = character as u32;
364 match codepoint {
365 0x20..=0x7E | 0xA0..=0xFF => Self(codepoint),
366 _ => Self(Self::UNICODE_BASE | codepoint),
367 }
368 }
369
370 /// Whether this is [`Keysym::NONE`].
371 #[inline]
372 #[must_use]
373 pub const fn is_none(self) -> bool {
374 self.0 == Self::NONE.0
375 }
376}
377
378impl fmt::Display for Keysym {
379 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
380 match self.to_char() {
381 Some(character) if !character.is_control() => write!(f, "'{character}'"),
382 _ => write!(f, "keysym {:#06x}", self.0),
383 }
384 }
385}
386
387/// A button on a pointing device.
388///
389/// Named by role, not by physical position: `Left` is the primary button even
390/// on a left-handed mouse, because that is the swap the OS already applied and
391/// the game must not apply again.
392#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
393pub enum PointerButton {
394 /// Primary button.
395 Left,
396 /// Secondary (context-menu) button.
397 Right,
398 /// Wheel click.
399 Middle,
400 /// Thumb button that means "back" — `BTN_SIDE`, `XBUTTON1`.
401 Back,
402 /// Thumb button that means "forward" — `BTN_EXTRA`, `XBUTTON2`.
403 Forward,
404 /// Anything else, by platform-assigned index.
405 ///
406 /// Bindable and loggable, never interpreted by the engine.
407 Other(u16),
408}
409
410/// One finger on a touchscreen, for as long as it stays down.
411///
412/// **Unique among the contacts that are down at the same moment, stable from the
413/// [`TouchPhase::Began`] that starts a gesture to the
414/// [`Ended`](TouchPhase::Ended) or [`Cancelled`](TouchPhase::Cancelled) that
415/// finishes it, and free to be reused after that.** Those three sentences are
416/// the whole contract, and the third is the one that bites: a consumer keying
417/// per-gesture state off this — which finger is holding the movement stick —
418/// must drop that state when the contact ends, or the next finger to land
419/// inherits it.
420///
421/// A contact is not a device. Two fingers on one screen are one [`DeviceId`] and
422/// two `ContactId`s, which is exactly why the id could not be folded into the
423/// device: a per-device registry cannot represent a second finger.
424///
425/// The numbering is the platform's (a browser `pointerId`, a `wl_touch` id, a
426/// Win32 pointer id) and is meaningless to compare against a literal or across
427/// windows — like [`Scancode`], it exists to be matched against *other* ids from
428/// the same stream.
429#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
430pub struct ContactId(pub u32);
431
432impl fmt::Display for ContactId {
433 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
434 write!(f, "contact {}", self.0)
435 }
436}
437
438/// Where a [`ContactId`] is in its gesture.
439///
440/// A touchscreen has no "hover": a contact exists from the moment it lands until
441/// the moment it goes away, so this is the lifecycle rather than a button state
442/// — which is why touch does not reuse [`ButtonState`].
443#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
444pub enum TouchPhase {
445 /// The finger landed. The first event any [`ContactId`] gets.
446 Began,
447 /// It moved while down.
448 Moved,
449 /// The user lifted it. **The gesture completed**, and a consumer commits
450 /// whatever it meant — a tap fires, a stick centres, a drag lands where it
451 /// was let go.
452 Ended,
453 /// The system took the gesture away: the OS claimed it for an edge swipe,
454 /// palm rejection changed its mind, the window lost focus, the browser
455 /// decided the page was scrolling after all.
456 ///
457 /// **Not an [`Ended`](Self::Ended), and a consumer that treats it as one
458 /// fires actions the user did not ask for.** The position it carries is the
459 /// last one the platform knew, not a place anyone chose, so the answer is to
460 /// undo the interaction rather than complete it — the drag goes back, the
461 /// tap does not fire, the stick centres without the character having lunged.
462 /// What both share is that the contact is over: the id is gone either way,
463 /// and a consumer that ignores this one is left holding a finger that will
464 /// never move again.
465 Cancelled,
466}
467
468impl TouchPhase {
469 /// Whether this phase ends the contact — [`Ended`](Self::Ended) or
470 /// [`Cancelled`](Self::Cancelled).
471 ///
472 /// The test anything tracking live contacts writes; it is the *reason* they
473 /// differ that the two variants exist for, not the fact that they both stop.
474 #[inline]
475 #[must_use]
476 pub const fn ends_contact(self) -> bool {
477 matches!(self, Self::Ended | Self::Cancelled)
478 }
479
480 /// A short, stable name for logs and test assertions.
481 #[must_use]
482 pub const fn as_str(self) -> &'static str {
483 match self {
484 Self::Began => "Began",
485 Self::Moved => "Moved",
486 Self::Ended => "Ended",
487 Self::Cancelled => "Cancelled",
488 }
489 }
490}
491
492impl fmt::Display for TouchPhase {
493 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
494 f.write_str(self.as_str())
495 }
496}
497
498/// How far a scroll event moved, in the units the device reported.
499///
500/// The two variants are not interchangeable and must not be collapsed by the
501/// shell: a notched wheel genuinely reports discrete clicks, a touchpad
502/// genuinely reports pixels, and the conversion factor between them is a
503/// *policy* decision (how many pixels is one line?) that belongs to the action
504/// layer and the UI, where it can be configured, not to a backend.
505#[derive(Clone, Copy, Debug, PartialEq)]
506pub enum ScrollDelta {
507 /// Discrete detents — `y` positive scrolls the content up (away from the
508 /// user), matching every platform's convention for a wheel.
509 Lines {
510 /// Horizontal detents.
511 x: f32,
512 /// Vertical detents.
513 y: f32,
514 },
515 /// Continuous motion in physical pixels, from a touchpad or high-resolution
516 /// wheel. Same sign convention as [`ScrollDelta::Lines`].
517 Pixels {
518 /// Horizontal pixels.
519 x: f64,
520 /// Vertical pixels.
521 y: f64,
522 },
523}
524
525impl ScrollDelta {
526 /// Whether this delta is exactly zero in both axes.
527 ///
528 /// Wayland's `wl_pointer.axis_stop` and X11's button-4/5 emulation both
529 /// produce zero-length scrolls; consumers usually want to drop them.
530 #[must_use]
531 pub fn is_zero(self) -> bool {
532 match self {
533 Self::Lines { x, y } => x == 0.0 && y == 0.0,
534 Self::Pixels { x, y } => x == 0.0 && y == 0.0,
535 }
536 }
537}
538
539/// Generates [`KeyCode`] plus its name table from one list.
540///
541/// Two derived tables (`as_str`, `from_name`) and a hundred-odd variants are
542/// exactly the kind of thing that rots when maintained by hand — one added key
543/// with a forgotten name arm is a binding that serializes and never loads back.
544macro_rules! key_codes {
545 ($($variant:ident => $name:literal),+ $(,)?) => {
546 /// A key identified by physical position, independent of keyboard
547 /// layout.
548 ///
549 /// Variant names follow the W3C UI Events `code` values, which name
550 /// positions after the US-QWERTY legends: [`KeyCode::KeyW`] is the key
551 /// *where W is on a US keyboard*, which on AZERTY is the key labelled
552 /// Z. That is precisely the property gameplay bindings want — WASD
553 /// stays a square under the left hand everywhere — and precisely the
554 /// property a rebind menu must *not* display, which is what
555 /// [`Keysym`](crate::input::Keysym) is for.
556 ///
557 /// # Non-exhaustive on purpose
558 ///
559 /// Unlike [`SurfaceTarget`](crate::SurfaceTarget), which is exhaustive
560 /// so that a new platform breaks every backend loudly, this enum is
561 /// `#[non_exhaustive]`: consumers match a handful of keys and fall
562 /// through on the rest, so adding a key must not be a breaking change.
563 /// A key nobody named is a key nobody bound, which degrades to "the
564 /// binding does not fire" — not to a wrong action.
565 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
566 #[non_exhaustive]
567 pub enum KeyCode {
568 $(
569 #[doc = concat!("The `", $name, "` key.")]
570 $variant,
571 )+
572 }
573
574 impl KeyCode {
575 /// Every key this engine has a name for, in declaration order.
576 ///
577 /// Used by the rebind UI to enumerate choices and by tests to prove
578 /// the name table round-trips.
579 pub const ALL: &'static [Self] = &[$(Self::$variant),+];
580
581 /// The stable name of this key, as written in binding assets and
582 /// profiles.
583 ///
584 /// Stable across releases: it is a serialization format, not a
585 /// display string. A rebind menu shows the *keysym*, not this.
586 #[must_use]
587 pub const fn as_str(self) -> &'static str {
588 match self {
589 $(Self::$variant => $name,)+
590 }
591 }
592
593 /// Parses a name produced by [`KeyCode::as_str`].
594 ///
595 /// Not a [`FromStr`](core::str::FromStr) impl: the only possible
596 /// failure is "no such key", and an error type carrying that one
597 /// fact would be ceremony. Bindings for unknown names are kept as
598 /// [`Scancode`](crate::input::Scancode) by the profile loader
599 /// rather than dropped.
600 #[must_use]
601 pub fn from_name(name: &str) -> Option<Self> {
602 match name {
603 $($name => Some(Self::$variant),)+
604 _ => None,
605 }
606 }
607 }
608 };
609}
610
611key_codes! {
612 // Alphanumeric block.
613 KeyA => "KeyA", KeyB => "KeyB", KeyC => "KeyC", KeyD => "KeyD", KeyE => "KeyE",
614 KeyF => "KeyF", KeyG => "KeyG", KeyH => "KeyH", KeyI => "KeyI", KeyJ => "KeyJ",
615 KeyK => "KeyK", KeyL => "KeyL", KeyM => "KeyM", KeyN => "KeyN", KeyO => "KeyO",
616 KeyP => "KeyP", KeyQ => "KeyQ", KeyR => "KeyR", KeyS => "KeyS", KeyT => "KeyT",
617 KeyU => "KeyU", KeyV => "KeyV", KeyW => "KeyW", KeyX => "KeyX", KeyY => "KeyY",
618 KeyZ => "KeyZ",
619 Digit0 => "Digit0", Digit1 => "Digit1", Digit2 => "Digit2", Digit3 => "Digit3",
620 Digit4 => "Digit4", Digit5 => "Digit5", Digit6 => "Digit6", Digit7 => "Digit7",
621 Digit8 => "Digit8", Digit9 => "Digit9",
622
623 // Punctuation, in US-QWERTY positions.
624 Backquote => "Backquote", Minus => "Minus", Equal => "Equal",
625 BracketLeft => "BracketLeft", BracketRight => "BracketRight", Backslash => "Backslash",
626 Semicolon => "Semicolon", Quote => "Quote", Comma => "Comma", Period => "Period",
627 Slash => "Slash",
628
629 // Keys that only exist on some physical layouts. Present because a binding
630 // made on an ISO or JIS keyboard has to survive a round trip through a
631 // profile written on an ANSI one.
632 IntlBackslash => "IntlBackslash", IntlRo => "IntlRo", IntlYen => "IntlYen",
633
634 // Editing and whitespace.
635 Escape => "Escape", Tab => "Tab", CapsLock => "CapsLock", Space => "Space",
636 Backspace => "Backspace", Enter => "Enter", Delete => "Delete", Insert => "Insert",
637
638 // Modifiers, left and right distinguished.
639 ShiftLeft => "ShiftLeft", ShiftRight => "ShiftRight",
640 ControlLeft => "ControlLeft", ControlRight => "ControlRight",
641 AltLeft => "AltLeft", AltRight => "AltRight",
642 SuperLeft => "SuperLeft", SuperRight => "SuperRight",
643 ContextMenu => "ContextMenu",
644
645 // Navigation.
646 Home => "Home", End => "End", PageUp => "PageUp", PageDown => "PageDown",
647 ArrowUp => "ArrowUp", ArrowDown => "ArrowDown",
648 ArrowLeft => "ArrowLeft", ArrowRight => "ArrowRight",
649
650 // Function row.
651 F1 => "F1", F2 => "F2", F3 => "F3", F4 => "F4", F5 => "F5", F6 => "F6",
652 F7 => "F7", F8 => "F8", F9 => "F9", F10 => "F10", F11 => "F11", F12 => "F12",
653
654 // System keys.
655 PrintScreen => "PrintScreen", ScrollLock => "ScrollLock", Pause => "Pause",
656
657 // Numpad.
658 NumLock => "NumLock",
659 Numpad0 => "Numpad0", Numpad1 => "Numpad1", Numpad2 => "Numpad2",
660 Numpad3 => "Numpad3", Numpad4 => "Numpad4", Numpad5 => "Numpad5",
661 Numpad6 => "Numpad6", Numpad7 => "Numpad7", Numpad8 => "Numpad8",
662 Numpad9 => "Numpad9",
663 NumpadDivide => "NumpadDivide", NumpadMultiply => "NumpadMultiply",
664 NumpadSubtract => "NumpadSubtract", NumpadAdd => "NumpadAdd",
665 NumpadEnter => "NumpadEnter", NumpadDecimal => "NumpadDecimal",
666}
667
668impl fmt::Display for KeyCode {
669 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
670 f.write_str(self.as_str())
671 }
672}
673
674/// Generates [`CursorIcon`], [`CursorIcon::ALL`] and both directions of its
675/// keyword table from one list, so a shape cannot be added without its CSS
676/// keyword or left out of the list a parser searches.
677macro_rules! cursor_icons {
678 ($($(#[$meta:meta])* $variant:ident => $name:literal),+ $(,)?) => {
679 /// A standard cursor shape.
680 ///
681 /// Names rather than pixels, because every platform already has themed,
682 /// correctly scaled, user-configured cursors; `crcbl_shell::cursor`
683 /// explains the rest.
684 ///
685 /// **Exhaustive on purpose.** Every shell backend maps each shape to its
686 /// own stock cursor, and a shape added later must fail to compile in
687 /// each of them rather than fall to an arrow through a wildcard arm.
688 /// That makes adding a shape a breaking change, which is the price.
689 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
690 pub enum CursorIcon {
691 $($(#[$meta])* $variant,)+
692 }
693
694 impl CursorIcon {
695 /// Every shape, in declaration order.
696 pub const ALL: &'static [Self] = &[$(Self::$variant),+];
697
698 /// The CSS/`cursor-shape-v1` keyword for this shape.
699 ///
700 /// Backends map from this rather than from the variant name, because
701 /// the keyword is the string X11 cursor themes and the browser both
702 /// index by.
703 #[must_use]
704 pub const fn as_css_name(self) -> &'static str {
705 match self {
706 $(Self::$variant => $name,)+
707 }
708 }
709
710 /// The shape a CSS `cursor` keyword names, matched as CSS matches
711 /// keywords: ignoring ASCII case. `None` for a keyword with no shape
712 /// here, `auto` and `none` among them, which are not shapes.
713 #[must_use]
714 pub fn from_css_name(name: &str) -> Option<Self> {
715 Self::ALL
716 .iter()
717 .copied()
718 .find(|shape| shape.as_css_name().eq_ignore_ascii_case(name))
719 }
720 }
721 };
722}
723
724cursor_icons! {
725 /// The platform's normal arrow.
726 #[default]
727 Default => "default",
728 /// The "this is clickable" hand.
729 Pointer => "pointer",
730 /// I-beam, for text.
731 Text => "text",
732 /// Crosshair, for precise placement.
733 Crosshair => "crosshair",
734 /// Something is happening and input is blocked.
735 Wait => "wait",
736 /// Something is happening but input still works.
737 Progress => "progress",
738 /// This action is not allowed here.
739 NotAllowed => "not-allowed",
740 /// The thing under the pointer can be picked up.
741 Grab => "grab",
742 /// The thing under the pointer is being dragged.
743 Grabbing => "grabbing",
744 /// Move in any direction.
745 Move => "move",
746 /// Resize vertically.
747 ResizeNorthSouth => "ns-resize",
748 /// Resize horizontally.
749 ResizeEastWest => "ew-resize",
750 /// Resize along the ↗↙ diagonal.
751 ResizeNorthEastSouthWest => "nesw-resize",
752 /// Resize along the ↖↘ diagonal.
753 ResizeNorthWestSouthEast => "nwse-resize",
754 /// Split pane, vertical divider.
755 ResizeColumn => "col-resize",
756 /// Split pane, horizontal divider.
757 ResizeRow => "row-resize",
758}
759
760/// What a text field taking typing is for, as an input method needs to know
761/// it.
762///
763/// Here rather than in `crcbl-shell` for the reason [`CursorIcon`] is: a UI
764/// names it for its field, and a UI crate depends on this one, not on the
765/// shell.
766///
767/// **Exhaustive on purpose**, as [`CursorIcon`] is: a purpose added later
768/// must fail to compile in every backend's mapping rather than fall to
769/// [`Normal`](Self::Normal) through a wildcard arm, because a password read
770/// as ordinary text is one an input method may learn and suggest back.
771#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
772pub enum TextPurpose {
773 /// Ordinary text: the input method may complete, correct and remember.
774 #[default]
775 Normal,
776 /// A password: hidden as typed, and nothing typed may be stored, learned
777 /// or offered back as a suggestion.
778 Password,
779 /// A PIN: digits, hidden, and not stored, as a password.
780 Pin,
781}
782
783impl TextPurpose {
784 /// Whether what is typed must not be stored, learned or suggested.
785 #[must_use]
786 pub const fn is_sensitive(self) -> bool {
787 match self {
788 Self::Normal => false,
789 Self::Password | Self::Pin => true,
790 }
791 }
792}
793
794#[cfg(test)]
795mod tests {
796 use super::*;
797
798 #[test]
799 fn cursor_keywords_are_unique_css_shaped_and_parse_back() {
800 let shapes = CursorIcon::ALL;
801 let mut names: Vec<&str> = shapes.iter().map(|shape| shape.as_css_name()).collect();
802 let count = names.len();
803 names.sort_unstable();
804 names.dedup();
805 assert_eq!(names.len(), count, "cursor keywords must be unique");
806 assert!(
807 names
808 .iter()
809 .all(|name| name.chars().all(|c| c.is_ascii_lowercase() || c == '-')),
810 "keywords are CSS identifiers"
811 );
812 assert_eq!(CursorIcon::default().as_css_name(), "default");
813 for &shape in shapes {
814 assert_eq!(CursorIcon::from_css_name(shape.as_css_name()), Some(shape));
815 }
816 assert_eq!(
817 CursorIcon::from_css_name("Not-Allowed"),
818 Some(CursorIcon::NotAllowed),
819 "keywords ignore ASCII case"
820 );
821 for not_a_shape in ["auto", "none", "", "pointer ", "hand"] {
822 assert_eq!(
823 CursorIcon::from_css_name(not_a_shape),
824 None,
825 "{not_a_shape:?}"
826 );
827 }
828 }
829
830 #[test]
831 fn key_names_round_trip_and_are_unique() {
832 let mut names: Vec<&'static str> = KeyCode::ALL.iter().map(|key| key.as_str()).collect();
833 let count = names.len();
834 assert!(count > 100, "the table covers a full keyboard, got {count}");
835 names.sort_unstable();
836 names.dedup();
837 assert_eq!(names.len(), count, "key names must be unique");
838
839 for key in KeyCode::ALL {
840 assert_eq!(KeyCode::from_name(key.as_str()), Some(*key));
841 assert_eq!(key.to_string(), key.as_str());
842 }
843 assert_eq!(KeyCode::from_name("KeyÆ"), None);
844 }
845
846 #[test]
847 fn wasd_is_a_physical_square_not_a_layout_one() {
848 // The whole point of the type: these are positions, so a binding stored
849 // as a name resolves to the same position on any layout.
850 for name in ["KeyW", "KeyA", "KeyS", "KeyD"] {
851 assert!(KeyCode::from_name(name).is_some(), "{name}");
852 }
853 }
854
855 #[test]
856 fn keysyms_map_both_ways_over_the_xkb_rules() {
857 // Latin-1 range: the keysym *is* the codepoint.
858 assert_eq!(Keysym::from_char('a'), Keysym(0x61));
859 assert_eq!(Keysym(0x61).to_char(), Some('a'));
860 assert_eq!(Keysym::from_char('ä'), Keysym(0xE4));
861 assert_eq!(Keysym(0xE4).to_char(), Some('ä'));
862
863 // Everything else lives in the Unicode block.
864 let euro = Keysym::from_char('€');
865 assert_eq!(euro, Keysym(0x0100_20AC));
866 assert_eq!(euro.to_char(), Some('€'));
867
868 // Function keys and modifiers are not characters.
869 const XKB_KEY_F1: Keysym = Keysym(0xFFBE);
870 assert_eq!(XKB_KEY_F1.to_char(), None);
871 assert!(Keysym::NONE.is_none());
872 assert_eq!(Keysym::NONE.to_char(), None);
873
874 assert_eq!(Keysym::from_char('q').to_string(), "'q'");
875 assert_eq!(XKB_KEY_F1.to_string(), "keysym 0xffbe");
876 }
877
878 #[test]
879 fn every_printable_ascii_round_trips_through_a_keysym() {
880 for codepoint in 0x20u32..=0x7E {
881 let character = char::from_u32(codepoint).expect("ascii");
882 assert_eq!(Keysym::from_char(character).to_char(), Some(character));
883 }
884 }
885
886 #[test]
887 fn chord_modifiers_exclude_latched_state() {
888 let held = Modifiers::CTRL | Modifiers::SHIFT | Modifiers::CAPS_LOCK | Modifiers::NUM_LOCK;
889 assert_eq!(held.chord(), Modifiers::CTRL | Modifiers::SHIFT);
890 assert!(!Modifiers::CHORD.contains(Modifiers::ALT_GR));
891 assert_eq!(Modifiers::default(), Modifiers::empty());
892 }
893
894 #[test]
895 fn button_state_is_one_type_for_every_kind_of_button() {
896 assert!(ButtonState::from_pressed(true).is_pressed());
897 assert_eq!(ButtonState::from_pressed(false), ButtonState::Released);
898 }
899
900 #[test]
901 fn scroll_units_stay_distinct() {
902 let lines = ScrollDelta::Lines { x: 0.0, y: -1.0 };
903 let pixels = ScrollDelta::Pixels { x: 0.0, y: -13.0 };
904 assert_ne!(
905 format!("{lines:?}"),
906 format!("{pixels:?}"),
907 "a wheel detent and 13 px must not be the same value"
908 );
909 assert!(ScrollDelta::Lines { x: 0.0, y: 0.0 }.is_zero());
910 assert!(ScrollDelta::Pixels { x: 0.0, y: 0.0 }.is_zero());
911 assert!(!lines.is_zero());
912 assert!(!pixels.is_zero());
913 }
914
915 #[test]
916 fn device_ids_are_displayable_and_default_to_unknown() {
917 assert_eq!(DeviceId::default(), DeviceId::UNKNOWN);
918 assert_eq!(DeviceId::UNKNOWN.to_string(), "device ?");
919 assert_eq!(DeviceId(4).to_string(), "device 4");
920 assert_eq!(Scancode(30).to_string(), "scancode 30");
921 }
922}