Skip to main content

hypersig_desktop/
shortcut.rs

1//! Global shortcuts, which the application hears while another application
2//! has focus, as push-to-talk and a show-and-hide key need.
3
4use global_hotkey::hotkey::{Code, HotKey};
5use tokio::sync::broadcast;
6
7/// The modifier keys of a [`Shortcut`], joined with [`and`](Self::and).
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
9pub struct Modifiers {
10    bits: u8,
11}
12
13impl Modifiers {
14    /// No modifier, which only a function key may have.
15    pub const NONE: Self = Self { bits: 0 };
16    /// The Shift key.
17    pub const SHIFT: Self = Self { bits: 1 };
18    /// The Control key, on macOS as well.
19    pub const CONTROL: Self = Self { bits: 1 << 1 };
20    /// The Alt key, which macOS labels Option.
21    pub const ALT: Self = Self { bits: 1 << 2 };
22    /// The Command key on macOS and the Windows key elsewhere.
23    pub const SUPER: Self = Self { bits: 1 << 3 };
24    /// Command on macOS and Control elsewhere, the key of each system's own shortcuts.
25    #[cfg(target_os = "macos")]
26    pub const PRIMARY: Self = Self::SUPER;
27    /// Command on macOS and Control elsewhere, the key of each system's own shortcuts.
28    #[cfg(not(target_os = "macos"))]
29    pub const PRIMARY: Self = Self::CONTROL;
30
31    /// These modifiers and `other` together.
32    #[must_use]
33    pub const fn and(self, other: Self) -> Self {
34        Self {
35            bits: self.bits | other.bits,
36        }
37    }
38
39    const fn has(self, other: Self) -> bool {
40        self.bits & other.bits == other.bits
41    }
42
43    /// The same modifiers, as `global-hotkey` names them.
44    fn system(self) -> global_hotkey::hotkey::Modifiers {
45        use global_hotkey::hotkey::Modifiers as System;
46        [
47            (Self::SHIFT, System::SHIFT),
48            (Self::CONTROL, System::CONTROL),
49            (Self::ALT, System::ALT),
50            (Self::SUPER, System::META),
51        ]
52        .into_iter()
53        .filter(|&(ours, _)| self.has(ours))
54        .fold(System::empty(), |all, (_, system)| all | system)
55    }
56}
57
58/// The key of a [`Shortcut`], named by where it is on a US keyboard.
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
60#[non_exhaustive]
61#[expect(missing_docs, reason = "each variant is the key it names")]
62pub enum Key {
63    A,
64    B,
65    C,
66    D,
67    E,
68    F,
69    G,
70    H,
71    I,
72    J,
73    K,
74    L,
75    M,
76    N,
77    O,
78    P,
79    Q,
80    R,
81    S,
82    T,
83    U,
84    V,
85    W,
86    X,
87    Y,
88    Z,
89    Digit0,
90    Digit1,
91    Digit2,
92    Digit3,
93    Digit4,
94    Digit5,
95    Digit6,
96    Digit7,
97    Digit8,
98    Digit9,
99    F1,
100    F2,
101    F3,
102    F4,
103    F5,
104    F6,
105    F7,
106    F8,
107    F9,
108    F10,
109    F11,
110    F12,
111    Space,
112    Enter,
113    Escape,
114    Tab,
115    Backspace,
116    ArrowUp,
117    ArrowDown,
118    ArrowLeft,
119    ArrowRight,
120}
121
122impl Key {
123    const fn is_function(self) -> bool {
124        matches!(
125            self,
126            Self::F1
127                | Self::F2
128                | Self::F3
129                | Self::F4
130                | Self::F5
131                | Self::F6
132                | Self::F7
133                | Self::F8
134                | Self::F9
135                | Self::F10
136                | Self::F11
137                | Self::F12
138        )
139    }
140
141    /// The same key, as `global-hotkey` names it.
142    fn code(self) -> Code {
143        match self {
144            Self::A => Code::KeyA,
145            Self::B => Code::KeyB,
146            Self::C => Code::KeyC,
147            Self::D => Code::KeyD,
148            Self::E => Code::KeyE,
149            Self::F => Code::KeyF,
150            Self::G => Code::KeyG,
151            Self::H => Code::KeyH,
152            Self::I => Code::KeyI,
153            Self::J => Code::KeyJ,
154            Self::K => Code::KeyK,
155            Self::L => Code::KeyL,
156            Self::M => Code::KeyM,
157            Self::N => Code::KeyN,
158            Self::O => Code::KeyO,
159            Self::P => Code::KeyP,
160            Self::Q => Code::KeyQ,
161            Self::R => Code::KeyR,
162            Self::S => Code::KeyS,
163            Self::T => Code::KeyT,
164            Self::U => Code::KeyU,
165            Self::V => Code::KeyV,
166            Self::W => Code::KeyW,
167            Self::X => Code::KeyX,
168            Self::Y => Code::KeyY,
169            Self::Z => Code::KeyZ,
170            Self::Digit0 => Code::Digit0,
171            Self::Digit1 => Code::Digit1,
172            Self::Digit2 => Code::Digit2,
173            Self::Digit3 => Code::Digit3,
174            Self::Digit4 => Code::Digit4,
175            Self::Digit5 => Code::Digit5,
176            Self::Digit6 => Code::Digit6,
177            Self::Digit7 => Code::Digit7,
178            Self::Digit8 => Code::Digit8,
179            Self::Digit9 => Code::Digit9,
180            Self::F1 => Code::F1,
181            Self::F2 => Code::F2,
182            Self::F3 => Code::F3,
183            Self::F4 => Code::F4,
184            Self::F5 => Code::F5,
185            Self::F6 => Code::F6,
186            Self::F7 => Code::F7,
187            Self::F8 => Code::F8,
188            Self::F9 => Code::F9,
189            Self::F10 => Code::F10,
190            Self::F11 => Code::F11,
191            Self::F12 => Code::F12,
192            Self::Space => Code::Space,
193            Self::Enter => Code::Enter,
194            Self::Escape => Code::Escape,
195            Self::Tab => Code::Tab,
196            Self::Backspace => Code::Backspace,
197            Self::ArrowUp => Code::ArrowUp,
198            Self::ArrowDown => Code::ArrowDown,
199            Self::ArrowLeft => Code::ArrowLeft,
200            Self::ArrowRight => Code::ArrowRight,
201        }
202    }
203}
204
205/// A key and its modifiers, for [`Os::shortcut`](crate::Os::shortcut).
206#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
207pub struct Shortcut {
208    modifiers: Modifiers,
209    key: Key,
210}
211
212impl Shortcut {
213    /// The shortcut of `key` held with `modifiers`.
214    ///
215    /// # Panics
216    ///
217    /// Panics when `modifiers` is [`Modifiers::NONE`] and `key` is not a
218    /// function key, since the application would take that key from every
219    /// other application. In a `const`, that is a compile error.
220    ///
221    /// ```compile_fail,E0080
222    /// use hypersig_desktop::{Key, Modifiers, Shortcut};
223    ///
224    /// const TALK: Shortcut = Shortcut::new(Modifiers::NONE, Key::Space);
225    /// # let _ = TALK;
226    /// ```
227    #[must_use]
228    pub const fn new(modifiers: Modifiers, key: Key) -> Self {
229        assert!(
230            modifiers.bits != 0 || key.is_function(),
231            "a global shortcut holds a modifier, unless its key is a function key, since it takes the key from every other application"
232        );
233        Self { modifiers, key }
234    }
235
236    /// The same shortcut, as `global-hotkey` registers it.
237    pub(crate) fn hotkey(self) -> HotKey {
238        HotKey::new(Some(self.modifiers.system()), self.key.code())
239    }
240}
241
242/// Whether a [`Shortcut`] went down or came up.
243#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
244#[expect(
245    clippy::exhaustive_enums,
246    reason = "a key goes down or comes up, and there is no third state"
247)]
248pub enum Press {
249    /// The shortcut's keys went down.
250    Pressed,
251    /// The shortcut's key came up.
252    Released,
253}
254
255impl From<global_hotkey::HotKeyState> for Press {
256    fn from(state: global_hotkey::HotKeyState) -> Self {
257        match state {
258            global_hotkey::HotKeyState::Pressed => Self::Pressed,
259            global_hotkey::HotKeyState::Released => Self::Released,
260        }
261    }
262}
263
264/// The presses and releases of a [`Shortcut`], from [`Os::shortcut`](crate::Os::shortcut).
265#[derive(Debug)]
266pub struct Presses {
267    receiver: broadcast::Receiver<Press>,
268}
269
270impl Presses {
271    pub(crate) fn new(receiver: broadcast::Receiver<Press>) -> Self {
272        Self { receiver }
273    }
274
275    /// Waits for the next press or release, and returns `None` once the
276    /// application has stopped.
277    pub async fn next(&mut self) -> Option<Press> {
278        loop {
279            match self.receiver.recv().await {
280                Ok(press) => return Some(press),
281                Err(broadcast::error::RecvError::Lagged(_)) => {}
282                Err(broadcast::error::RecvError::Closed) => return None,
283            }
284        }
285    }
286}
287
288/// Where a shortcut's presses go, for every [`Presses`] that waits on them.
289pub(crate) fn channel() -> broadcast::Sender<Press> {
290    broadcast::channel(16).0
291}
292
293#[cfg(test)]
294mod tests {
295    use super::{Key, Modifiers, Shortcut};
296
297    #[test]
298    fn a_shortcut_registers_its_modifiers_and_key() {
299        let talk = Shortcut::new(Modifiers::CONTROL.and(Modifiers::SHIFT), Key::Space);
300        let hotkey = talk.hotkey();
301        assert_eq!(hotkey.key, global_hotkey::hotkey::Code::Space);
302        assert_eq!(
303            hotkey.mods,
304            global_hotkey::hotkey::Modifiers::CONTROL | global_hotkey::hotkey::Modifiers::SHIFT
305        );
306        assert_ne!(
307            talk.hotkey().id(),
308            Shortcut::new(Modifiers::ALT, Key::Space).hotkey().id()
309        );
310        let _ = Shortcut::new(Modifiers::NONE, Key::F9);
311    }
312}