cushy/widgets/
shortcuts.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
//! A keyboard shortcut handling widget.

use ahash::AHashMap;
use kludgine::app::winit::keyboard::{
    Key, KeyCode, ModifiersState, NamedKey, NativeKey, NativeKeyCode, PhysicalKey, SmolStr,
};

use crate::widget::{
    EventHandling, MakeWidget, SharedCallback, WidgetRef, WrapperWidget, HANDLED, IGNORED,
};
use crate::window::KeyEvent;
use crate::{ModifiersExt, ModifiersStateExt};

/// A collection of keyboard shortcut handlers.
#[derive(Default, Debug, Clone)]
pub struct ShortcutMap(AHashMap<Shortcut, ShortcutConfig>);

impl ShortcutMap {
    /// Inserts a handler that invokes `callback` once when `key` is pressed
    /// with `modifiers`.
    #[must_use]
    pub fn with_shortcut<F>(
        mut self,
        key: impl Into<ShortcutKey>,
        modifiers: ModifiersState,
        callback: F,
    ) -> Self
    where
        F: FnMut(KeyEvent) -> EventHandling + Send + 'static,
    {
        self.insert(key.into(), modifiers, callback);
        self
    }

    /// Inserts a handler that invokes `callback` once when `key` is pressed
    /// with `modifiers`.
    pub fn insert<F>(&mut self, key: impl Into<ShortcutKey>, modifiers: ModifiersState, callback: F)
    where
        F: FnMut(KeyEvent) -> EventHandling + Send + 'static,
    {
        self.insert_shortcut_inner(key.into(), modifiers, false, SharedCallback::new(callback));
    }

    /// Inserts a handler that invokes `callback` when `key` is pressed with
    /// `modifiers`. This callback will be invoked for repeated key events.
    #[must_use]
    pub fn with_repeating_shortcut<F>(
        mut self,
        key: impl Into<ShortcutKey>,
        modifiers: ModifiersState,
        callback: F,
    ) -> Self
    where
        F: FnMut(KeyEvent) -> EventHandling + Send + 'static,
    {
        self.insert_repeating(key.into(), modifiers, callback);
        self
    }

    /// Inserts a handler that invokes `callback` when `key` is pressed with
    /// `modifiers`. This callback will be invoked for repeated key events.
    pub fn insert_repeating<F>(
        &mut self,
        key: impl Into<ShortcutKey>,
        modifiers: ModifiersState,
        callback: F,
    ) where
        F: FnMut(KeyEvent) -> EventHandling + Send + 'static,
    {
        self.insert_shortcut_inner(key.into(), modifiers, true, SharedCallback::new(callback));
    }

    fn insert_shortcut_inner(
        &mut self,
        key: ShortcutKey,
        modifiers: ModifiersState,
        repeat: bool,
        callback: SharedCallback<KeyEvent, EventHandling>,
    ) {
        let (first, second) = Shortcut { key, modifiers }.into_variations();
        let config = ShortcutConfig { repeat, callback };

        if let Some(second) = second {
            self.0.insert(second, config.clone());
        }

        self.0.insert(first, config);
    }

    /// Invokes any associated handlers for `input`.
    ///
    /// Returns whether the event has been handled or not.
    #[must_use]
    pub fn input(&self, input: KeyEvent) -> EventHandling {
        for modifiers in FuzzyModifiers(input.modifiers.state()) {
            let physical_match = self.0.get(&Shortcut {
                key: ShortcutKey::Physical(input.physical_key),
                modifiers,
            });
            let logical_match = self.0.get(&Shortcut {
                key: ShortcutKey::Logical(input.logical_key.clone()),
                modifiers,
            });
            match (physical_match, logical_match) {
                (Some(physical), Some(logical)) if physical.callback != logical.callback => {
                    // Prefer an exact physical key match.
                    if input.state.is_pressed()
                        && (!input.repeat || physical.repeat)
                        && physical.callback.invoke(input.clone()).is_break()
                    {
                        return HANDLED;
                    }

                    return if input.state.is_pressed() && (!input.repeat || logical.repeat) {
                        logical.callback.invoke(input)
                    } else {
                        IGNORED
                    };
                }
                (Some(callback), _) | (_, Some(callback)) => {
                    return if input.state.is_pressed() && (!input.repeat || callback.repeat) {
                        callback.callback.invoke(input)
                    } else {
                        IGNORED
                    };
                }
                _ => {}
            }
        }

        IGNORED
    }
}

/// An iterator that attempts one fallback towards a common shortcut modifier.
///
/// The precedence for the fallback is: Primary, Control, Super.
struct FuzzyModifiers(ModifiersState);

impl Iterator for FuzzyModifiers {
    type Item = ModifiersState;

    fn next(&mut self) -> Option<Self::Item> {
        let modifiers = self.0;
        if modifiers.is_empty() {
            return None;
        } else if modifiers.primary() && !modifiers.only_primary() {
            self.0 = ModifiersState::PRIMARY;
        } else if modifiers.control_key() && !modifiers.only_control() {
            self.0 = ModifiersState::CONTROL;
        } else if modifiers.super_key() && !modifiers.only_super() {
            self.0 = ModifiersState::SUPER;
        } else {
            self.0 = ModifiersState::empty();
        }
        Some(modifiers)
    }
}

/// A widget that handles keyboard shortcuts.
#[derive(Debug)]
pub struct Shortcuts {
    shortcuts: ShortcutMap,
    child: WidgetRef,
}

impl Shortcuts {
    /// Wraps `child` with keyboard shortcut handling.
    #[must_use]
    pub fn new(child: impl MakeWidget) -> Self {
        Self {
            shortcuts: ShortcutMap::default(),
            child: WidgetRef::new(child),
        }
    }

    /// Invokes `callback` when `key` is pressed while `modifiers` are pressed.
    ///
    /// This shortcut will only be invoked if focus is within a child of this
    /// widget, or if this widget becomes the root widget of a window.
    #[must_use]
    pub fn with_shortcut<F>(
        mut self,
        key: impl Into<ShortcutKey>,
        modifiers: ModifiersState,
        callback: F,
    ) -> Self
    where
        F: FnMut(KeyEvent) -> EventHandling + Send + 'static,
    {
        self.shortcuts.insert(key, modifiers, callback);
        self
    }

    /// Invokes `callback` when `key` is pressed while `modifiers` are pressed.
    /// If the shortcut is held, the callback will be invoked on repeat events.
    ///
    /// This shortcut will only be invoked if focus is within a child of this
    /// widget, or if this widget becomes the root widget of a window.
    #[must_use]
    pub fn with_repeating_shortcut<F>(
        mut self,
        key: impl Into<ShortcutKey>,
        modifiers: ModifiersState,
        callback: F,
    ) -> Self
    where
        F: FnMut(KeyEvent) -> EventHandling + Send + 'static,
    {
        self.shortcuts.insert_repeating(key, modifiers, callback);
        self
    }
}

#[derive(Debug, Clone, Eq, PartialEq, Hash)]
struct Shortcut {
    pub key: ShortcutKey,
    pub modifiers: ModifiersState,
}

impl Shortcut {
    fn into_variations(self) -> (Shortcut, Option<Shortcut>) {
        let modifiers = self.modifiers;
        let extra = match &self.key {
            ShortcutKey::Logical(Key::Character(c)) => {
                let lowercase = SmolStr::new(c.to_lowercase());
                let uppercase = SmolStr::new(c.to_uppercase());
                if c == &lowercase {
                    Some(Shortcut {
                        key: uppercase.into(),
                        modifiers,
                    })
                } else {
                    Some(Shortcut {
                        key: lowercase.into(),
                        modifiers,
                    })
                }
            }
            _ => None,
        };
        (self, extra)
    }
}

impl From<PhysicalKey> for ShortcutKey {
    fn from(key: PhysicalKey) -> Self {
        ShortcutKey::Physical(key)
    }
}

impl From<Key> for ShortcutKey {
    fn from(key: Key) -> Self {
        ShortcutKey::Logical(key)
    }
}

impl From<NamedKey> for ShortcutKey {
    fn from(key: NamedKey) -> Self {
        Self::from(Key::from(key))
    }
}

impl From<NativeKey> for ShortcutKey {
    fn from(key: NativeKey) -> Self {
        Self::from(Key::from(key))
    }
}

impl From<SmolStr> for ShortcutKey {
    fn from(key: SmolStr) -> Self {
        Self::from(Key::Character(key))
    }
}

impl From<&'_ str> for ShortcutKey {
    fn from(key: &'_ str) -> Self {
        Self::from(SmolStr::new(key))
    }
}

impl From<KeyCode> for ShortcutKey {
    fn from(key: KeyCode) -> Self {
        Self::from(PhysicalKey::from(key))
    }
}

impl From<NativeKeyCode> for ShortcutKey {
    fn from(key: NativeKeyCode) -> Self {
        Self::from(PhysicalKey::from(key))
    }
}

#[derive(Debug, Clone)]
struct ShortcutConfig {
    repeat: bool,
    callback: SharedCallback<KeyEvent, EventHandling>,
}

/// A key used in a [`Shortcuts`] widget.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub enum ShortcutKey {
    /// A logical key.
    ///
    /// Logical keys are mapped using the operating system configuration.
    Logical(Key),

    /// A physical key.
    ///
    /// Physical keys represent a physical keyboard location and may be
    /// different logical keys depending on operating system configurations.
    Physical(PhysicalKey),
}

impl WrapperWidget for Shortcuts {
    fn child_mut(&mut self) -> &mut crate::widget::WidgetRef {
        &mut self.child
    }

    fn keyboard_input(
        &mut self,
        _device_id: crate::window::DeviceId,
        input: KeyEvent,
        _is_synthetic: bool,
        _context: &mut crate::context::EventContext<'_>,
    ) -> EventHandling {
        self.shortcuts.input(input)
    }
}