Skip to main content

hyprforge_ui/
keys.rs

1//! From an iced key event to a [`hyprforge_keys::KeyPress`].
2//!
3//! The one adapter between the toolkit and the suite's keyboard grammar,
4//! and the reason `hyprforge-keys` itself can stay free of iced: a crate
5//! that only describes what a binding *is* should not need a GUI toolkit
6//! to compile, and its tests should not need a window.
7//!
8//! It lives here rather than behind an optional feature on that crate
9//! because a feature would not stay optional. Cargo unifies features
10//! across the workspace, so any build containing one app would switch
11//! iced on for every other consumer — the trap the root `Cargo.toml`
12//! documents twice already. This crate *is* the iced layer, so nothing
13//! is smuggled in by putting the adapter in it.
14//!
15//! Entirely action-agnostic: it knows which keys exist, not what any of
16//! them do. That is why the file manager and the image viewer can share
17//! it despite binding completely different things.
18
19use hyprforge_keys::{Key, KeyPress, Modifiers};
20use iced::keyboard::{self, key};
21
22/// One iced key press, as the keymap reads it — or `None` for a key no
23/// binding can name.
24///
25/// Two fields, deliberately from two places — the CLAUDE.md rule on the
26/// three things iced reports for a key press:
27///
28/// - `key` comes from iced's *unmodified* `key`, which is what a binding
29///   is matched against. Ctrl+Shift+N arrives as `n` with Ctrl and Shift
30///   held, which is exactly how the binding is written.
31/// - `text` comes from iced's `text`, what the press actually typed, and
32///   is only ever used for typing into a field. Reading `key` for that
33///   would turn `Shift+/` into `/` — and, in the case this rule was
34///   written for, cost a password every capital it had.
35pub fn key_press(event: &keyboard::Event) -> Option<KeyPress> {
36    let keyboard::Event::KeyPressed { key: pressed, modifiers, text, .. } = event else {
37        return None;
38    };
39    let mods = Modifiers {
40        ctrl: modifiers.control(),
41        alt: modifiers.alt(),
42        shift: modifiers.shift(),
43        logo: modifiers.logo(),
44    };
45    let key = match pressed.as_ref() {
46        keyboard::Key::Named(named) => match named {
47            key::Named::Enter => Key::Enter,
48            key::Named::Backspace => Key::Backspace,
49            key::Named::Escape => Key::Escape,
50            key::Named::Delete => Key::Delete,
51            key::Named::Tab => Key::Tab,
52            key::Named::Space => Key::Space,
53            key::Named::ArrowUp => Key::Up,
54            key::Named::ArrowDown => Key::Down,
55            key::Named::ArrowLeft => Key::Left,
56            key::Named::ArrowRight => Key::Right,
57            key::Named::Home => Key::Home,
58            key::Named::End => Key::End,
59            key::Named::PageUp => Key::PageUp,
60            key::Named::PageDown => Key::PageDown,
61            key::Named::Insert => Key::Insert,
62            key::Named::ContextMenu => Key::Menu,
63            other => Key::F(function_key_number(other)?),
64        },
65        keyboard::Key::Character(c) => {
66            let mut chars = c.chars();
67            match (chars.next(), chars.next()) {
68                (Some(ch), None) => Key::Char(ch.to_lowercase().next().unwrap_or(ch)),
69                _ => return None,
70            }
71        }
72        _ => return None,
73    };
74    let text = text.as_ref().and_then(|t| {
75        let mut chars = t.chars();
76        match (chars.next(), chars.next()) {
77            (Some(ch), None) => Some(ch),
78            _ => None,
79        }
80    });
81    Some(KeyPress { key, mods, text })
82}
83
84fn function_key_number(named: key::Named) -> Option<u8> {
85    use key::Named as N;
86    let n = match named {
87        N::F1 => 1,
88        N::F2 => 2,
89        N::F3 => 3,
90        N::F4 => 4,
91        N::F5 => 5,
92        N::F6 => 6,
93        N::F7 => 7,
94        N::F8 => 8,
95        N::F9 => 9,
96        N::F10 => 10,
97        N::F11 => 11,
98        N::F12 => 12,
99        N::F13 => 13,
100        N::F14 => 14,
101        N::F15 => 15,
102        N::F16 => 16,
103        N::F17 => 17,
104        N::F18 => 18,
105        N::F19 => 19,
106        N::F20 => 20,
107        N::F21 => 21,
108        N::F22 => 22,
109        N::F23 => 23,
110        N::F24 => 24,
111        _ => return None,
112    };
113    Some(n)
114}
115
116#[cfg(test)]
117mod tests {
118    use super::*;
119    use iced::keyboard::Modifiers as IcedModifiers;
120
121    fn pressed(key: keyboard::Key, mods: IcedModifiers, text: Option<&str>) -> keyboard::Event {
122        keyboard::Event::KeyPressed {
123            key: key.clone(),
124            modified_key: key.clone(),
125            physical_key: keyboard::key::Physical::Unidentified(
126                keyboard::key::NativeCode::Unidentified,
127            ),
128            location: keyboard::Location::Standard,
129            modifiers: mods,
130            text: text.map(Into::into),
131            repeat: false,
132        }
133    }
134
135    fn character(c: &str) -> keyboard::Key {
136        keyboard::Key::Character(c.into())
137    }
138
139    /// The whole reason both fields are read: the binding matches on the
140    /// unmodified key, and what gets typed is what the press produced.
141    #[test]
142    fn a_shifted_letter_keeps_its_lowercase_key_and_its_typed_capital() {
143        let event = pressed(character("N"), IcedModifiers::SHIFT, Some("N"));
144        let press = key_press(&event).unwrap();
145        assert_eq!(press.key, Key::Char('n'));
146        assert!(press.mods.shift);
147        assert_eq!(press.text, Some('N'));
148    }
149
150    #[test]
151    fn a_named_key_becomes_the_key_a_binding_can_name() {
152        let event = pressed(keyboard::Key::Named(key::Named::ArrowLeft), IcedModifiers::ALT, None);
153        let press = key_press(&event).unwrap();
154        assert_eq!(press.key, Key::Left);
155        assert!(press.mods.alt);
156    }
157
158    #[test]
159    fn function_keys_arrive_by_number() {
160        let event = pressed(keyboard::Key::Named(key::Named::F2), IcedModifiers::empty(), None);
161        assert_eq!(key_press(&event).unwrap().key, Key::F(2));
162    }
163
164    /// A key with no name in this grammar is `None` rather than a guess —
165    /// a binding that cannot be written cannot be matched.
166    #[test]
167    fn a_key_no_binding_can_name_is_not_invented() {
168        let event =
169            pressed(keyboard::Key::Named(key::Named::MediaPlay), IcedModifiers::empty(), None);
170        assert_eq!(key_press(&event), None);
171    }
172
173    #[test]
174    fn a_release_is_not_a_press() {
175        let event = keyboard::Event::KeyReleased {
176            key: character("n"),
177            modified_key: character("n"),
178            physical_key: keyboard::key::Physical::Unidentified(
179                keyboard::key::NativeCode::Unidentified,
180            ),
181            location: keyboard::Location::Standard,
182            modifiers: IcedModifiers::empty(),
183        };
184        assert_eq!(key_press(&event), None);
185    }
186}