Skip to main content

tilo_presentation/
keys.rs

1//! The key an X11 or Wayland keysym names.
2//!
3//! A host that reads the keyboard itself (X11, Wayland, a KMS session through
4//! libinput and xkbcommon) delivers a press as a keysym; the vocabulary is
5//! winit's own, and a build that runs no such host has no keysyms.
6
7use winit::keyboard::{Key, KeyLocation};
8
9/// The modifier keys held with a press, as an engine and the toolkit both read them.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
11#[allow(
12    clippy::struct_excessive_bools,
13    reason = "one flag per physical modifier key, mirroring winit's own \
14              modifiers state; a browser app constructs this by field name \
15              across the crate boundary, so reshaping it into flags is out \
16              of scope for a lint fix"
17)]
18pub struct KeyModifiers {
19    pub ctrl: bool,
20    pub shift: bool,
21    pub alt: bool,
22    pub meta: bool,
23}
24
25/// The key `keysym` names and where on the keyboard it sits; `None` where
26/// this build has no X11 or Wayland host, so no keysym names anything here.
27///
28/// A keysym naming no key winit knows is [`Key::Unidentified`]: the caller
29/// takes the key's text instead.
30#[cfg(target_os = "linux")]
31#[must_use]
32pub fn keysym_key(keysym: u32) -> Option<(Key, KeyLocation)> {
33    Some(winit::platform::scancode::keysym_to_key(keysym))
34}
35
36#[cfg(not(target_os = "linux"))]
37#[must_use]
38pub const fn keysym_key(_keysym: u32) -> Option<(Key, KeyLocation)> {
39    None
40}
41
42#[cfg(all(test, target_os = "linux"))]
43mod tests {
44    use super::*;
45    use winit::keyboard::NamedKey;
46
47    #[test]
48    fn a_named_keysym_names_the_key_winit_names() {
49        let (key, _) = keysym_key(0xff0d).expect("no host lacks keysyms here");
50        assert_eq!(key, Key::Named(NamedKey::Enter));
51    }
52
53    #[test]
54    fn a_typed_character_is_no_named_key() {
55        let (key, _) = keysym_key(u32::from('с')).expect("no host lacks keysyms here");
56        assert!(matches!(key, Key::Unidentified(_)), "{key:?}");
57    }
58}