Skip to main content

strata_platform/
shortcuts.rs

1//! Universal cross-platform keyboard shortcut and keybinding manager.
2//!
3//! Provides declarative shortcut registration (e.g., "Ctrl+Shift+I", "F12", "Alt+Left"),
4//! modifier bitmask matching, and priority event dispatching across desktop platforms.
5
6use crate::events::{KeyCode, Modifiers, PlatformEvent};
7
8/// Normalized keyboard shortcut trigger combining a key code and required modifier states.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
10pub struct ShortcutTrigger {
11    pub key: KeyCode,
12    pub modifiers: Modifiers,
13}
14
15impl ShortcutTrigger {
16    /// Creates a new trigger with explicit key and modifier flags.
17    pub const fn new(key: KeyCode, modifiers: Modifiers) -> Self {
18        Self { key, modifiers }
19    }
20
21    /// Creates a trigger with no modifier keys active.
22    pub const fn plain(key: KeyCode) -> Self {
23        Self {
24            key,
25            modifiers: Modifiers {
26                shift: false,
27                ctrl: false,
28                alt: false,
29                meta: false,
30            },
31        }
32    }
33
34    /// Parses a human-readable shortcut string (e.g., "Ctrl+Shift+I", "F12", "Alt+Left").
35    pub fn parse(spec: &str) -> Option<Self> {
36        let mut ctrl = false;
37        let mut shift = false;
38        let mut alt = false;
39        let mut meta = false;
40        let mut target_key = None;
41
42        for part in spec.split('+') {
43            let trimmed = part.trim();
44            match trimmed.to_lowercase().as_str() {
45                "ctrl" | "control" => ctrl = true,
46                "shift" => shift = true,
47                "alt" | "opt" | "option" => alt = true,
48                "meta" | "cmd" | "command" | "super" | "win" => meta = true,
49                _ => {
50                    target_key = parse_key_code(trimmed);
51                }
52            }
53        }
54
55        target_key.map(|key| Self {
56            key,
57            modifiers: Modifiers {
58                shift,
59                ctrl,
60                alt,
61                meta,
62            },
63        })
64    }
65
66    /// Tests if this trigger matches a given platform key and modifier state.
67    pub fn matches(&self, key: KeyCode, modifiers: Modifiers) -> bool {
68        self.key == key
69            && self.modifiers.ctrl == modifiers.ctrl
70            && self.modifiers.shift == modifiers.shift
71            && self.modifiers.alt == modifiers.alt
72            && self.modifiers.meta == modifiers.meta
73    }
74}
75
76/// Parses a string representation of a key name into a `KeyCode`.
77fn parse_key_code(name: &str) -> Option<KeyCode> {
78    match name.to_uppercase().as_str() {
79        "A" => Some(KeyCode::KeyA),
80        "B" => Some(KeyCode::KeyB),
81        "C" => Some(KeyCode::KeyC),
82        "D" => Some(KeyCode::KeyD),
83        "E" => Some(KeyCode::KeyE),
84        "F" => Some(KeyCode::KeyF),
85        "G" => Some(KeyCode::KeyG),
86        "H" => Some(KeyCode::KeyH),
87        "I" => Some(KeyCode::KeyI),
88        "J" => Some(KeyCode::KeyJ),
89        "K" => Some(KeyCode::KeyK),
90        "L" => Some(KeyCode::KeyL),
91        "M" => Some(KeyCode::KeyM),
92        "N" => Some(KeyCode::KeyN),
93        "O" => Some(KeyCode::KeyO),
94        "P" => Some(KeyCode::KeyP),
95        "Q" => Some(KeyCode::KeyQ),
96        "R" => Some(KeyCode::KeyR),
97        "S" => Some(KeyCode::KeyS),
98        "T" => Some(KeyCode::KeyT),
99        "U" => Some(KeyCode::KeyU),
100        "V" => Some(KeyCode::KeyV),
101        "W" => Some(KeyCode::KeyW),
102        "X" => Some(KeyCode::KeyX),
103        "Y" => Some(KeyCode::KeyY),
104        "Z" => Some(KeyCode::KeyZ),
105        "0" => Some(KeyCode::Digit0),
106        "1" => Some(KeyCode::Digit1),
107        "2" => Some(KeyCode::Digit2),
108        "3" => Some(KeyCode::Digit3),
109        "4" => Some(KeyCode::Digit4),
110        "5" => Some(KeyCode::Digit5),
111        "6" => Some(KeyCode::Digit6),
112        "7" => Some(KeyCode::Digit7),
113        "8" => Some(KeyCode::Digit8),
114        "9" => Some(KeyCode::Digit9),
115        "F1" => Some(KeyCode::F1),
116        "F2" => Some(KeyCode::F2),
117        "F3" => Some(KeyCode::F3),
118        "F4" => Some(KeyCode::F4),
119        "F5" => Some(KeyCode::F5),
120        "F6" => Some(KeyCode::F6),
121        "F7" => Some(KeyCode::F7),
122        "F8" => Some(KeyCode::F8),
123        "F9" => Some(KeyCode::F9),
124        "F10" => Some(KeyCode::F10),
125        "F11" => Some(KeyCode::F11),
126        "F12" => Some(KeyCode::F12),
127        "ESC" | "ESCAPE" => Some(KeyCode::Escape),
128        "ENTER" | "RETURN" => Some(KeyCode::Enter),
129        "TAB" => Some(KeyCode::Tab),
130        "SPACE" => Some(KeyCode::Space),
131        "BACKSPACE" => Some(KeyCode::Backspace),
132        "DELETE" | "DEL" => Some(KeyCode::Delete),
133        "LEFT" | "ARROWLEFT" => Some(KeyCode::ArrowLeft),
134        "RIGHT" | "ARROWRIGHT" => Some(KeyCode::ArrowRight),
135        "UP" | "ARROWUP" => Some(KeyCode::ArrowUp),
136        "DOWN" | "ARROWDOWN" => Some(KeyCode::ArrowDown),
137        "HOME" => Some(KeyCode::Home),
138        "END" => Some(KeyCode::End),
139        "PAGEUP" | "PGUP" => Some(KeyCode::PageUp),
140        "PAGEDOWN" | "PGDN" => Some(KeyCode::PageDown),
141        "/" | "SLASH" => Some(KeyCode::Slash),
142        "," | "COMMA" => Some(KeyCode::Comma),
143        "." | "PERIOD" => Some(KeyCode::Period),
144        "-" | "MINUS" => Some(KeyCode::Minus),
145        "=" | "+" | "EQUALS" | "EQUAL" | "PLUS" => Some(KeyCode::Equals),
146        "[" | "BRACKETLEFT" => Some(KeyCode::BracketLeft),
147        "]" | "BRACKETRIGHT" => Some(KeyCode::BracketRight),
148        ";" | "SEMICOLON" => Some(KeyCode::Semicolon),
149        "'" | "\"" | "QUOTE" | "APOSTROPHE" => Some(KeyCode::Quote),
150        "\\" | "|" | "BACKSLASH" => Some(KeyCode::Backslash),
151        "`" | "BACKQUOTE" | "GRAVE" => Some(KeyCode::Backquote),
152        _ => None,
153    }
154}
155
156/// Action closure executed when a registered shortcut triggers.
157/// Returns `true` if the shortcut was consumed and requires a UI repaint.
158pub type ShortcutCallback = Box<dyn Fn() -> bool>;
159
160/// Registry managing active keyboard shortcuts and dispatching incoming key events.
161#[derive(Default)]
162pub struct ShortcutManager {
163    bindings: Vec<(ShortcutTrigger, ShortcutCallback)>,
164}
165
166impl ShortcutManager {
167    /// Creates an empty shortcut manager.
168    pub fn new() -> Self {
169        Self {
170            bindings: Vec::new(),
171        }
172    }
173
174    /// Registers a shortcut by spec string (e.g. "Ctrl+Shift+I", "F12").
175    /// Returns `true` if the shortcut string was parsed and successfully registered.
176    pub fn register(&mut self, spec: &str, action: impl Fn() -> bool + 'static) -> bool {
177        if let Some(trigger) = ShortcutTrigger::parse(spec) {
178            self.bindings.push((trigger, Box::new(action)));
179            true
180        } else {
181            false
182        }
183    }
184
185    /// Registers a shortcut with a pre-constructed `ShortcutTrigger`.
186    pub fn register_trigger(
187        &mut self,
188        trigger: ShortcutTrigger,
189        action: impl Fn() -> bool + 'static,
190    ) {
191        self.bindings.push((trigger, Box::new(action)));
192    }
193
194    /// Dispatches an incoming `PlatformEvent`. If it matches a registered shortcut,
195    /// invokes the associated action and returns its repaint status.
196    pub fn dispatch(&self, event: &PlatformEvent) -> bool {
197        if let PlatformEvent::KeyDown { key, modifiers } = event {
198            for (trigger, action) in &self.bindings {
199                if trigger.matches(*key, *modifiers) {
200                    return action();
201                }
202            }
203        }
204        false
205    }
206
207    /// Returns the number of registered shortcut bindings.
208    pub fn len(&self) -> usize {
209        self.bindings.len()
210    }
211
212    /// Checks if the manager contains any registered shortcuts.
213    pub fn is_empty(&self) -> bool {
214        self.bindings.is_empty()
215    }
216}