win_hotkey/
global.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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
use rustc_hash::FxHashMap;

use crate::{HotkeyId, HotkeyManager, HotkeyManagerImpl, ModifiersKey, VirtualKey};
use core::fmt;
use std::sync::{
    atomic::{AtomicBool, Ordering},
    Arc, Mutex,
};

#[derive(Clone)]
pub struct GlobalHotkey<T> {
    key: VirtualKey,
    modifiers: Option<Vec<ModifiersKey>>,
    extras: Option<Vec<VirtualKey>>,
    action: Option<Arc<Mutex<dyn Fn() -> T + Send + 'static>>>, // Callback needs to be Send too
}

impl<T> fmt::Debug for GlobalHotkey<T>
where
    T: fmt::Debug, // Ensures that T can be printed if necessary
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("GlobalHotkey")
            .field("key", &self.key)
            .field("modifiers", &self.modifiers)
            .field("extras", &self.extras)
            .field(
                "action",
                &self.action.as_ref().map_or_else(
                    || "None".to_string(),
                    |_| "Some(Fn() -> T + Send)".to_string(),
                ),
            )
            .finish()
    }
}

#[derive(Clone, Debug)]
pub struct GlobalHotkeyManager<T: Send + 'static> {
    hotkeys: Arc<Mutex<FxHashMap<String, GlobalHotkey<T>>>>,
    manager: Arc<Mutex<HotkeyManager<T>>>,
    listening: Arc<AtomicBool>,
    key_ids: Arc<Mutex<Vec<HotkeyId>>>,
}

impl<T: Send + 'static> GlobalHotkey<T> {
    pub fn set_action(&mut self, action: impl Fn() -> T + Send + 'static) {
        self.action = Some(Arc::new(Mutex::new(action)));
    }
}

impl<T: Send + 'static> Default for GlobalHotkeyManager<T> {
    fn default() -> Self {
        let mut hkm = HotkeyManager::new();
        hkm.set_no_repeat(false);
        Self {
            manager: Arc::new(Mutex::new(hkm)),
            listening: Arc::new(AtomicBool::new(false)),
            hotkeys: Arc::new(Mutex::new(FxHashMap::default())),
            key_ids: Arc::new(Mutex::new(Vec::new())),
        }
    }
}

pub trait GlobalHotkeyManagerImpl<T> {
    fn new() -> Self;
    fn register_hotkey(
        &self,
        name: String,
        key: VirtualKey,
        modifiers: Option<Vec<ModifiersKey>>,
        extras: Option<Vec<VirtualKey>>,
        callback: Option<impl Fn() -> T + Send + 'static>,
    );
    fn add_hotkey(&self, name: String, hotkey: GlobalHotkey<T>);
    fn remove_hotkey(&self, name: String) -> Option<GlobalHotkey<T>>;
    fn start(&self);
    fn stop(&self) -> bool;
    fn update(&mut self);
}

impl<T: Send + 'static> GlobalHotkeyManagerImpl<T> for GlobalHotkeyManager<T> {
    fn new() -> Self {
        Self::default()
    }

    fn register_hotkey(
        &self,
        name: String,
        key: VirtualKey,
        modifiers: Option<Vec<ModifiersKey>>,
        extras: Option<Vec<VirtualKey>>,
        callback: Option<impl Fn() -> T + Send + 'static>,
    ) {
        let mut hotkeys = self.hotkeys.lock().unwrap();
        hotkeys.insert(
            name,
            GlobalHotkey {
                key,
                modifiers,
                extras,
                action: callback.map(|cb| {
                    Arc::new(Mutex::new(cb)) as Arc<Mutex<dyn Fn() -> T + Send + 'static>>
                }),
            },
        );
    }

    fn add_hotkey(&self, name: String, hotkey: GlobalHotkey<T>) {
        let mut hotkeys = self.hotkeys.lock().unwrap();
        hotkeys.insert(name, hotkey);
    }

    fn remove_hotkey(&self, key: String) -> Option<GlobalHotkey<T>> {
        let mut hotkeys = self.hotkeys.lock().unwrap();
        hotkeys.remove(&key)
    }

    fn update(&mut self) {
        let listening = self.listening.clone();
        let hotkey_manager = self.manager.clone();

        // Lock bindings to access keybindings
        let mut hotkey_manager_mut = hotkey_manager.lock().unwrap();
        let hotkeys = self.hotkeys.lock().unwrap();
        let mut key_ids = self.key_ids.lock().unwrap();

        if let Err(e) = hotkey_manager_mut.unregister_all() {
            eprintln!("failed to unregister all keybindings: {}", e);
        }

        let handle = hotkey_manager_mut.interrupt_handle();
        handle.interrupt();
        key_ids.clear();

        let mut new_hk = HotkeyManager::new();
        new_hk.set_no_repeat(false);
        let new_hkm = Arc::new(Mutex::new(new_hk));
        self.manager = new_hkm.clone();

        let hotkey_manager = self.manager.clone();
        let mut hotkey_manager_mut = hotkey_manager.lock().unwrap();

        // Collect hotkeys and their actions upfront
        for hotkey in hotkeys.values() {
            let action = hotkey.action.clone();
            let result = if let Some(action) = action {
                // Register with an action if present
                hotkey_manager_mut.register_extrakeys(
                    hotkey.key,
                    hotkey.modifiers.as_deref(),
                    hotkey.extras.as_deref(),
                    Some(move || {
                        let action = action.clone();
                        let action = action.lock().unwrap();
                        action()
                    }),
                )
            } else {
                // Register without an action if None
                hotkey_manager_mut.register_extrakeys(
                    hotkey.key,
                    hotkey.modifiers.as_deref(),
                    hotkey.extras.as_deref(),
                    None::<fn() -> T>,
                )
            };

            match result {
                Ok(hotkey_id) => key_ids.push(hotkey_id),
                Err(e) => {
                    eprintln!("failed to register keybinding {:?}: {}", hotkey.key, e);
                }
            }
        }

        let hkm = hotkey_manager.clone();

        std::thread::spawn(move || {
            // Lock the Mutex inside the thread, instead of moving the MutexGuard
            while listening.load(Ordering::SeqCst) {
                hkm.lock().unwrap().event_loop();
            }
        });
    }

    fn start(&self) {
        if self.listening.load(Ordering::SeqCst) {
            eprintln!("already listening for hotkeys.");
            return;
        }

        let hotkey_manager = self.manager.clone();
        let listening = self.listening.clone();

        listening.store(true, Ordering::SeqCst);

        // Lock bindings to access keybindings
        let mut hotkey_manager_mut = hotkey_manager.lock().unwrap();
        let hotkeys = self.hotkeys.lock().unwrap();
        let mut key_ids = self.key_ids.lock().unwrap();

        // Collect hotkeys and their actions upfront
        for hotkey in hotkeys.values() {
            let action = hotkey.action.clone();
            let result = if let Some(action) = action {
                // Register with an action if present
                hotkey_manager_mut.register_extrakeys(
                    hotkey.key,
                    hotkey.modifiers.as_deref(),
                    hotkey.extras.as_deref(),
                    Some(move || {
                        let action = action.clone();
                        let action = action.lock().unwrap();
                        action()
                    }),
                )
            } else {
                // Register without an action if None
                hotkey_manager_mut.register_extrakeys(
                    hotkey.key,
                    hotkey.modifiers.as_deref(),
                    hotkey.extras.as_deref(),
                    None::<fn() -> T>,
                )
            };

            match result {
                Ok(hotkey_id) => key_ids.push(hotkey_id),
                Err(e) => {
                    eprintln!("failed to register keybinding {:?}: {}", hotkey.key, e);
                }
            }
        }

        let hkm = hotkey_manager.clone();

        std::thread::spawn(move || {
            // Lock the Mutex inside the thread, instead of moving the MutexGuard
            while listening.load(Ordering::SeqCst) {
                hkm.lock().unwrap().event_loop();
            }
        });
    }

    fn stop(&self) -> bool {
        if !self.listening.load(Ordering::SeqCst) {
            return false;
        }

        self.listening.store(false, Ordering::SeqCst);

        true
    }
}

#[derive(Debug)]
pub enum HotKeyParseError {
    UnsupportedKey(String),
    EmptyToken(String),
    InvalidFormat(String),
}

impl std::fmt::Display for HotKeyParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match *self {
            HotKeyParseError::UnsupportedKey(ref key) => {
                write!(
                    f,
                    "Couldn't recognize \"{}\" as a valid key for hotkey",
                    key
                )
            }
            HotKeyParseError::EmptyToken(ref token) => {
                write!(f, "Found empty token while parsing hotkey: {}", token)
            }
            HotKeyParseError::InvalidFormat(ref format) => {
                write!(
                    f,
                    "Invalid hotkey format: \"{}\", a hotkey should have the modifiers first and only one main key, for example: \"Shift + Alt + K\"",
                    format
                )
            }
        }
    }
}

impl std::error::Error for HotKeyParseError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        // No underlying error, so we return None.
        None
    }
}

impl<T: Send + 'static> TryInto<GlobalHotkey<T>> for &str {
    type Error = HotKeyParseError;

    fn try_into(self) -> Result<GlobalHotkey<T>, Self::Error> {
        let tokens = self.split('+').collect::<Vec<&str>>();
        let mut modifiers: Vec<ModifiersKey> = Vec::new();
        let mut key = None;
        let mut extras: Vec<VirtualKey> = Vec::new();

        match tokens.len() {
            1 => {
                // Only a key, no modifiers or extras
                key = Some(
                    VirtualKey::try_from(tokens[0].trim())
                        .map_err(|e| HotKeyParseError::UnsupportedKey(e.to_string()))?,
                );
            }
            _ => {
                let mut found_key = false;

                for raw in tokens {
                    let token = raw.trim();

                    if token.is_empty() {
                        return Err(HotKeyParseError::EmptyToken(self.to_string()));
                    }

                    // If we have already found the key, treat the rest as extras
                    if found_key {
                        let extra_key = VirtualKey::try_from(token)
                            .map_err(|e| HotKeyParseError::UnsupportedKey(e.to_string()))?;
                        extras.push(extra_key);
                    } else {
                        if key.is_some() {
                            return Err(HotKeyParseError::InvalidFormat(self.to_string()));
                        }

                        let temp_key = VirtualKey::try_from(token)
                            .map_err(|e| HotKeyParseError::UnsupportedKey(e.to_string()))?;

                        // If the token is a valid modifier, add it to the modifiers
                        if let Ok(modifier) = temp_key.try_into() {
                            modifiers.push(modifier);
                        } else {
                            // Otherwise, treat it as the main key
                            key = Some(temp_key);
                            found_key = true; // Mark that the key has been found
                        }
                    }
                }
            }
        }

        // If no key was found, return an error
        let key = key.ok_or_else(|| HotKeyParseError::InvalidFormat(self.to_string()))?;

        Ok(GlobalHotkey {
            key,
            modifiers: if modifiers.is_empty() {
                None
            } else {
                Some(modifiers)
            },
            extras: if extras.is_empty() {
                None
            } else {
                Some(extras)
            },
            action: None, // action is still None
        })
    }
}