Skip to content

A tiny friend in your Mac's notch and on your iPhone that keeps an eye on your AI coding agents: Claude Code, Codex, Cursor, Gemini CLI, Antigravity and more. Approve from the notch or your Lock Screen.

Windows/Linux: register global shortcuts from Rust

Claudedeab632cbd56
diff --git a/windows/Cargo.lock b/windows/Cargo.lock
index 6278c752..b6a09d34 100644
--- a/windows/Cargo.lock
+++ b/windows/Cargo.lock
@@ -621,6 +621,7 @@ dependencies = [
"tauri",
"tauri-build",
"tauri-plugin-autostart",
+ "tauri-plugin-global-shortcut",
"tauri-plugin-single-instance",
"tokio",
"windows 0.61.3",
@@ -1366,6 +1367,16 @@ dependencies = [
"version_check",
]
+[[package]]
+name = "gethostname"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8"
+dependencies = [
+ "rustix",
+ "windows-link 0.2.1",
+]
+
[[package]]
name = "getrandom"
version = "0.2.17"
@@ -1490,6 +1501,24 @@ version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"
+[[package]]
+name = "global-hotkey"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8c386b0a4a70cb2d39fffd74480f985b6f0bfbcb934b6a6b6b7e630e448f242e"
+dependencies = [
+ "crossbeam-channel",
+ "keyboard-types 0.7.0",
+ "objc2",
+ "objc2-app-kit",
+ "once_cell",
+ "serde",
+ "thiserror 2.0.21",
+ "windows-sys 0.59.0",
+ "x11rb",
+ "xkeysym",
+]
+
[[package]]
name = "gobject-sys"
version = "0.18.0"
@@ -2068,6 +2097,17 @@ dependencies = [
"serde_json",
]
+[[package]]
+name = "keyboard-types"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b750dcadc39a09dbadd74e118f6dd6598df77fa01df0cfcdc52c28dece74528a"
+dependencies = [
+ "bitflags 2.13.2",
+ "serde",
+ "unicode-segmentation",
+]
+
[[package]]
name = "keyboard-types"
version = "0.8.3"
@@ -2255,7 +2295,7 @@ dependencies = [
"crossbeam-channel",
"dpi",
"gtk",
- "keyboard-types",
+ "keyboard-types 0.8.3",
"objc2",
"objc2-app-kit",
"objc2-core-foundation",
@@ -4048,6 +4088,21 @@ dependencies = [
"thiserror 2.0.21",
]
+[[package]]
+name = "tauri-plugin-global-shortcut"
+version = "2.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0bd2e1f725891a1613af8f25bf918ba3357654b0fd3f2d794c0ce76cbdd92ed2"
+dependencies = [
+ "global-hotkey",
+ "log",
+ "serde",
+ "serde_json",
+ "tauri",
+ "tauri-plugin",
+ "thiserror 2.0.21",
+]
+
[[package]]
name = "tauri-plugin-single-instance"
version = "2.5.0"
@@ -5447,6 +5502,23 @@ dependencies = [
"pkg-config",
]
+[[package]]
+name = "x11rb"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414"
+dependencies = [
+ "gethostname",
+ "rustix",
+ "x11rb-protocol",
+]
+
+[[package]]
+name = "x11rb-protocol"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd"
+
[[package]]
name = "xdg-home"
version = "1.3.0"
@@ -5457,6 +5529,12 @@ dependencies = [
"windows-sys 0.59.0",
]
+[[package]]
+name = "xkeysym"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56"
+
[[package]]
name = "yoke"
version = "0.8.3"
diff --git a/windows/src-tauri/Cargo.toml b/windows/src-tauri/Cargo.toml
index f581867d..901b5665 100644
--- a/windows/src-tauri/Cargo.toml
+++ b/windows/src-tauri/Cargo.toml
@@ -17,6 +17,7 @@ tauri-build = { version = "2", features = [] }
tauri = { version = "2", features = ["tray-icon"] }
tauri-plugin-single-instance = "2"
tauri-plugin-autostart = "2"
+tauri-plugin-global-shortcut = "2"
serde = { version = "1", features = ["derive"] }
serde_json = { version = "1", features = ["preserve_order"] }
tokio = { version = "1", features = ["net", "io-util", "sync", "time", "rt"] }
diff --git a/windows/src-tauri/src/lib.rs b/windows/src-tauri/src/lib.rs
index d9ec3353..5f06cca6 100644
--- a/windows/src-tauri/src/lib.rs
+++ b/windows/src-tauri/src/lib.rs
@@ -10,6 +10,7 @@ mod pipe;
mod platform;
mod secrets;
mod settings;
+mod shortcuts;
mod tray;
use std::process::Command;
@@ -61,12 +62,13 @@ fn boot(app: AppHandle, shared: State<Shared>) -> BootInfo {
#[tauri::command]
fn save_settings(app: AppHandle, shared: State<Shared>, settings: Settings) {
- let (screen_changed, autostart_changed) = {
+ let (screen_changed, autostart_changed, shortcuts_changed) = {
let mut current = shared.settings.lock().unwrap();
let screen_changed = current.screen != settings.screen;
let autostart_changed = current.autostart != settings.autostart;
+ let shortcuts_changed = current.shortcuts != settings.shortcuts;
*current = settings.clone();
- (screen_changed, autostart_changed)
+ (screen_changed, autostart_changed, shortcuts_changed)
};
if let Err(err) = settings::save(&settings) {
log::line(format!("could not save settings: {err}"));
@@ -82,6 +84,9 @@ fn save_settings(app: AppHandle, shared: State<Shared>, settings: Settings) {
let collapsed = shared.gate.collapsed.load(Ordering::Relaxed);
island::apply_geometry(&app, &settings.screen, collapsed);
}
+ if shortcuts_changed {
+ shortcuts::apply(&app, &settings.shortcuts);
+ }
// Keep the other window in step (island ⇄ settings window).
let _ = app.emit("settings-changed", settings);
}
@@ -294,6 +299,26 @@ fn log_line(message: String) {
log::line(format!("ui {message}"));
}
+// ── Global shortcuts ──────────────────────────────────────────────────────────
+
+/// How each global shortcut went: registered, taken by another app, and so on.
+#[tauri::command]
+fn shortcuts_status(app: AppHandle) -> shortcuts::Report {
+ shortcuts::status(&app)
+}
+
+/// Settings is recording a new combination: let go of ours meanwhile, so the
+/// keys reach the recorder instead of running an action. `false` takes them back.
+#[tauri::command]
+fn shortcuts_suspend(app: AppHandle, shared: State<Shared>, suspended: bool) {
+ if suspended {
+ shortcuts::suspend(&app);
+ } else {
+ let stored = shared.settings.lock().unwrap().shortcuts.clone();
+ shortcuts::apply(&app, &stored);
+ }
+}
+
// ── Settings window ───────────────────────────────────────────────────────────
/// WebView2 allows exactly one browser environment per app, and its options are
@@ -365,17 +390,31 @@ pub fn run() {
let loaded = settings::load();
let gate = Arc::new(PollGate::new());
- tauri::Builder::default()
- .plugin(tauri_plugin_single_instance::init(|app, _argv, _cwd| {
- let _ = app.emit_to(island::WINDOW_LABEL, "tray", "open".to_string());
+ let mut builder = tauri::Builder::default()
+ .plugin(tauri_plugin_single_instance::init(|app, argv, _cwd| {
+ // `coucou --shortcut <action>`: what a desktop's own keyboard
+ // settings run where we can't listen for keys ourselves (Wayland).
+ match shortcuts::from_args(&argv) {
+ Some(action) => shortcuts::dispatch(app, action),
+ None => {
+ let _ = app.emit_to(island::WINDOW_LABEL, "tray", "open".to_string());
+ }
+ }
}))
- .plugin(tauri_plugin_autostart::init(MacosLauncher::LaunchAgent, None))
+ .plugin(tauri_plugin_autostart::init(MacosLauncher::LaunchAgent, None));
+ // Where no global shortcut can work, the plugin isn't even started.
+ if platform::global_shortcuts_blocked().is_none() {
+ builder = builder.plugin(shortcuts::plugin());
+ }
+
+ builder
.manage(Shared {
settings: Mutex::new(loaded.clone()),
gate: gate.clone(),
})
.manage(Pending::default())
.manage(Chat::default())
+ .manage(shortcuts::Registry::default())
.invoke_handler(tauri::generate_handler![
boot,
save_settings,
@@ -403,6 +442,8 @@ pub fn run() {
open_n8n,
open_settings_window,
set_paused,
+ shortcuts_status,
+ shortcuts_suspend,
])
.setup(move |app| {
let handle = app.handle().clone();
@@ -428,6 +469,7 @@ pub fn run() {
hooks::ensure_hook_exe(&handle);
pipe::start(handle.clone());
integrations::start(handle.clone());
+ shortcuts::apply(&handle, &loaded.shortcuts);
Ok(())
})
.run(tauri::generate_context!())
diff --git a/windows/src-tauri/src/platform/linux.rs b/windows/src-tauri/src/platform/linux.rs
index e748a336..26203313 100644
--- a/windows/src-tauri/src/platform/linux.rs
+++ b/windows/src-tauri/src/platform/linux.rs
@@ -300,6 +300,33 @@ fn apply_input_region(gw: &impl IsA<gtk::Widget>, rect: Region) {
}
}
+// ── Global shortcuts ──────────────────────────────────────────────────────────
+
+/// Global shortcuts are X11 key grabs. A Wayland session has no such thing: a
+/// grab made through XWayland only sees keys typed into other X11 windows, so
+/// it would look registered and never fire. The XDG GlobalShortcuts portal is
+/// the Wayland way and isn't wired up yet, so on Wayland nothing is registered
+/// and Settings explains how to bind `coucou --shortcut <id>` in the desktop's
+/// own keyboard settings instead.
+pub fn global_shortcuts_blocked() -> Option<&'static str> {
+ let set = |var: &str| std::env::var_os(var).is_some_and(|v| !v.is_empty());
+ let wayland = set("WAYLAND_DISPLAY")
+ || std::env::var("XDG_SESSION_TYPE").is_ok_and(|v| v.eq_ignore_ascii_case("wayland"));
+ if wayland {
+ Some("wayland")
+ } else if !set("DISPLAY") {
+ Some("no-display")
+ } else {
+ None
+ }
+}
+
+/// On X11, AltGr is a modifier of its own (ISO_Level3_Shift): Ctrl+Alt+key
+/// never stands for it, so no combination takes a character away.
+pub fn ctrl_alt_types(_vk: u16, _shift: bool) -> Option<String> {
+ None
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/windows/src-tauri/src/platform/windows.rs b/windows/src-tauri/src/platform/windows.rs
index 6e1200a8..6707a2d6 100644
--- a/windows/src-tauri/src/platform/windows.rs
+++ b/windows/src-tauri/src/platform/windows.rs
@@ -13,7 +13,10 @@ use ::windows::Win32::Security::{GetTokenInformation, TokenUser, TOKEN_QUERY, TO
use ::windows::Win32::System::Ole::RevokeDragDrop;
use ::windows::Win32::System::SystemInformation::GetLocalTime;
use ::windows::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
-use ::windows::Win32::UI::Input::KeyboardAndMouse::{GetAsyncKeyState, VK_LBUTTON};
+use ::windows::Win32::UI::Input::KeyboardAndMouse::{
+ GetAsyncKeyState, GetKeyboardLayoutList, MapVirtualKeyExW, ToUnicodeEx, HKL, MAPVK_VK_TO_VSC,
+ VK_CONTROL, VK_LBUTTON, VK_MENU, VK_SHIFT,
+};
use ::windows::Win32::UI::WindowsAndMessaging::{
EnumChildWindows, GetClassNameW, GetCursorPos, GetWindowLongPtrW, SetWindowLongPtrW,
GWL_EXSTYLE, WS_EX_NOACTIVATE, WS_EX_TOOLWINDOW,
@@ -233,3 +236,44 @@ pub fn set_activating(win: &WebviewWindow, activating: bool) {
/// Click-through here is the poll's WS_EX_TRANSPARENT toggle, not a region.
pub fn set_input_region(_win: &WebviewWindow, _rect: Option<(f64, f64, f64, f64)>) {}
+
+// ── Global shortcuts ──────────────────────────────────────────────────────────
+
+/// RegisterHotKey works in every Windows session.
+pub fn global_shortcuts_blocked() -> Option<&'static str> {
+ None
+}
+
+/// The character Ctrl+Alt(+Shift)+`vk` types on one of the installed keyboard
+/// layouts, if any. Windows reads Ctrl+Alt as AltGr, so registering such a
+/// combination as a global shortcut would stop the user typing that character
+/// (AltGr+E is € on most European layouts, AltGr+A is ą in Polish).
+pub fn ctrl_alt_types(vk: u16, shift: bool) -> Option<String> {
+ let mut layouts = [HKL::default(); 32];
+ let count = unsafe { GetKeyboardLayoutList(Some(&mut layouts[..])) };
+ let count = usize::try_from(count).unwrap_or(0).min(layouts.len());
+
+ let mut state = [0u8; 256];
+ state[VK_CONTROL.0 as usize] = 0x80;
+ state[VK_MENU.0 as usize] = 0x80;
+ if shift {
+ state[VK_SHIFT.0 as usize] = 0x80;
+ }
+ for &layout in &layouts[..count] {
+ let scan = unsafe { MapVirtualKeyExW(u32::from(vk), MAPVK_VK_TO_VSC, Some(layout)) };
+ let mut buf = [0u16; 8];
+ // Flag 0x4: leave the keyboard state alone, so a dead key met here
+ // doesn't change what the user types next (Windows 10 1607 and later).
+ let n = unsafe { ToUnicodeEx(u32::from(vk), scan, &state, &mut buf, 0x4, Some(layout)) };
+ let typed = match n {
+ // A dead key (´ ^ ¨…) is still something the user types with it.
+ n if n < 0 => String::from_utf16_lossy(&buf[..1]),
+ 0 => continue,
+ n => String::from_utf16_lossy(&buf[..(n as usize).min(buf.len())]),
+ };
+ if typed.chars().any(|c| !c.is_control()) {
+ return Some(typed);
+ }
+ }
+ None
+}
diff --git a/windows/src-tauri/src/settings.rs b/windows/src-tauri/src/settings.rs
index 17f63e1c..003b4c28 100644
--- a/windows/src-tauri/src/settings.rs
+++ b/windows/src-tauri/src/settings.rs
@@ -23,6 +23,9 @@ pub struct Settings {
pub hooks_installed: bool,
/// Claude model used by the chat. Changeable in the settings window.
pub model: String,
+ /// Global shortcuts the user changed, by action id; the others keep their
+ /// default (see shortcuts.rs).
+ pub shortcuts: crate::shortcuts::Bindings,
}
fn default_model() -> String {
@@ -46,6 +49,7 @@ impl Default for Settings {
autostart: false,
hooks_installed: false,
model: default_model(),
+ shortcuts: Default::default(),
}
}
}
@@ -306,7 +310,8 @@ mod tests {
"screen": "cursor",
"autostart": true,
"hooksInstalled": true,
- "model": "some-model"
+ "model": "some-model",
+ "shortcuts": { "openChat": { "keys": "Ctrl+Shift+K", "enabled": false } }
}"#;
fn custom() -> Value {
@@ -414,6 +419,7 @@ mod tests {
("soundEnabled", json!(1)),
("activeIntegrations", json!("integration_n8n")),
("screen", Value::Null),
+ ("shortcuts", json!("Ctrl+Alt+A")),
] {
let loaded = parse(&custom_with(key, Some(wrong)))
.unwrap_or_else(|| panic!("a file with a bad {key} was thrown away"));
@@ -632,6 +638,7 @@ mod tests {
"autostart",
"hooksInstalled",
"model",
+ "shortcuts",
]
);
let _ = std::fs::remove_dir_all(&dir);
diff --git a/windows/src-tauri/src/shortcuts.rs b/windows/src-tauri/src/shortcuts.rs
new file mode 100644
index 00000000..a47c7c4e
--- /dev/null
+++ b/windows/src-tauri/src/shortcuts.rs
@@ -0,0 +1,551 @@
+// Global keyboard shortcuts — port of HotKeyCenter.swift + ShortcutLogic.swift.
+//
+// The shortcuts are registered from Rust through tauri-plugin-global-shortcut
+// (RegisterHotKey on Windows, XGrabKey on X11). A press is handed to the island
+// as a `shortcut` event carrying the action id; the island does the rest, the
+// same way it handles the tray menu. The wardrobe is the exception: it goes out
+// as its own `open-wardrobe` event, which the wardrobe view listens to.
+//
+// Default keys. The Mac uses ⌃⌥ + a letter. On Windows Ctrl+Alt *is* AltGr on
+// most European layouts, so a global Ctrl+Alt+E would swallow every € typed on
+// a French or German keyboard. The defaults below were checked against the
+// AltGr layer of the French (AZERTY), German (QWERTZ), Spanish, Italian,
+// Portuguese and Brazilian (ABNT2) layouts, which between them put a character
+// on E, Q, M, W, C and on every digit and most punctuation keys:
+//
+// Ctrl+Alt+Space open the chat Ctrl+Alt+→ / ← next / previous pill
+// Ctrl+Alt+A waiting permission Ctrl+Alt+S mute Mochi
+// Ctrl+Alt+T open the terminal Ctrl+Alt+G wardrobe
+// Ctrl+Alt+N open / close the island (off by default, as on the Mac)
+//
+// ⌃⌥[ and ⌃⌥] became the arrows (brackets are AltGr characters almost
+// everywhere) and ⌃⌥M became S (AltGr+M is µ in German). Layouts outside that
+// list can still clash — Polish puts ą on AltGr+A and ś on AltGr+S — so on
+// Windows every Ctrl+Alt combination is also checked against the keyboard
+// layouts actually installed (platform::ctrl_alt_types) and left unregistered,
+// flagged in Settings, when it types a character. The same table lives in
+// src/core/shortcuts.ts; tests/shortcuts.test.mjs keeps the two in step.
+
+use std::collections::{BTreeMap, HashMap, HashSet};
+use std::str::FromStr;
+use std::sync::Mutex;
+
+use serde::{Deserialize, Serialize};
+use tauri::{AppHandle, Emitter, Manager, Runtime};
+use tauri_plugin_global_shortcut::{Code, GlobalShortcut, Modifiers, Shortcut, ShortcutState};
+
+use crate::island::WINDOW_LABEL;
+
+/// One global action, as on the Mac (`ShortcutAction`). The ids are the Mac's
+/// raw values and are stored in settings.json: never rename one.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct ActionDef {
+ pub id: &'static str,
+ pub default_keys: &'static str,
+ pub enabled_by_default: bool,
+ /// False for the Mac actions this version cannot do yet. Their ids and
+ /// defaults stay reserved so a later port lands on the same keys.
+ pub ported: bool,
+}
+
+const fn action(id: &'static str, keys: &'static str, on: bool, ported: bool) -> ActionDef {
+ ActionDef { id, default_keys: keys, enabled_by_default: on, ported }
+}
+
+/// Same order as `ShortcutAction.allCases`.
+pub const ACTIONS: &[ActionDef] = &[
+ action("toggleIsland", "Ctrl+Alt+N", false, true),
+ action("openChat", "Ctrl+Alt+Space", true, true),
+ action("goToAlert", "Ctrl+Alt+A", true, true),
+ action("jumpToTerminal", "Ctrl+Alt+T", true, true),
+ // Dragging Mochi onto a window is not in this version.
+ action("attachFrontWindow", "Ctrl+Alt+F", true, false),
+ action("nextPill", "Ctrl+Alt+Right", true, true),
+ action("prevPill", "Ctrl+Alt+Left", true, true),
+ action("muteToggle", "Ctrl+Alt+S", true, true),
+ // Mochi on the desktop is not in this version.
+ action("desktopToggle", "Ctrl+Alt+D", true, false),
+ action("wardrobeToggle", "Ctrl+Alt+G", true, true),
+];
+
+pub fn find(id: &str) -> Option<&'static ActionDef> {
+ ACTIONS.iter().find(|a| a.id == id)
+}
+
+/// What the user chose for one action. An action missing from settings.json
+/// uses its default; `keys` empty means no key at all.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct Binding {
+ pub keys: String,
+ pub enabled: bool,
+}
+
+impl Default for Binding {
+ fn default() -> Self {
+ Self { keys: String::new(), enabled: true }
+ }
+}
+
+/// `settings.shortcuts`: only the actions the user changed.
+pub type Bindings = BTreeMap<String, Binding>;
+
+/// The binding in force for `def`: the stored one, or the default.
+pub fn effective(def: &ActionDef, stored: &Bindings) -> Binding {
+ stored.get(def.id).cloned().unwrap_or_else(|| Binding {
+ keys: def.default_keys.to_string(),
+ enabled: def.enabled_by_default,
+ })
+}
+
+// ── Status shown in Settings ──────────────────────────────────────────────────
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub enum Status {
+ /// Registered and listening.
+ Active,
+ /// Turned off, or no key.
+ Off,
+ /// Another app already holds this combination.
+ InUse,
+ /// Another Coucou shortcut has the same combination.
+ Duplicate,
+ /// Not a combination the OS can register.
+ Invalid,
+ /// Ctrl+Alt+key types a character on one of the keyboard layouts.
+ TypesCharacter,
+ /// Global shortcuts can't be registered in this session (Wayland).
+ Unsupported,
+ /// The action itself isn't in this version.
+ NotPorted,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ActionStatus {
+ pub id: &'static str,
+ pub status: Status,
+ /// The character a `TypesCharacter` combination types.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub typed: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Report {
+ pub actions: Vec<ActionStatus>,
+ /// Why nothing could be registered at all, when that is the case.
+ pub blocked: Option<String>,
+ /// The command a desktop's own shortcut settings can run instead:
+ /// `<this executable> --shortcut <action id>`.
+ pub command: String,
+}
+
+/// What is registered right now: hot-key id → action id, plus the last report.
+#[derive(Default)]
+pub struct Registry {
+ by_id: Mutex<HashMap<u32, &'static str>>,
+ report: Mutex<Vec<ActionStatus>>,
+}
+
+// ── Pure helpers ──────────────────────────────────────────────────────────────
+
+/// Parses an accelerator the way the plugin will. `None` for an empty or
+/// unknown one, and for a bare or Shift-only key: a global shortcut needs
+/// Ctrl, Alt or the Windows key, or it would take that key away from every
+/// other app (same rule as parseKeys in src/core/shortcuts.ts).
+pub fn parse(keys: &str) -> Option<Shortcut> {
+ if keys.trim().is_empty() {
+ return None;
+ }
+ let shortcut = Shortcut::from_str(keys).ok()?;
+ let has_modifier = shortcut
+ .mods
+ .intersects(Modifiers::CONTROL | Modifiers::ALT | Modifiers::SUPER | Modifiers::META);
+ (has_modifier && shortcut.key != Code::Escape).then_some(shortcut)
+}
+
+/// True when Windows reads the combination as AltGr: Ctrl and Alt held, no
+/// Windows key.
+pub fn is_altgr_like(shortcut: &Shortcut) -> bool {
+ shortcut.mods.contains(Modifiers::CONTROL | Modifiers::ALT)
+ && !shortcut.mods.intersects(Modifiers::SUPER | Modifiers::META)
+}
+
+/// The Windows virtual-key code global-hotkey registers for `code`, for the
+/// keys that can type a character. Others (arrows, F-keys…) never do: `None`.
+pub fn character_vk(code: Code) -> Option<u16> {
+ use Code::*;
+ let letters = [
+ KeyA, KeyB, KeyC, KeyD, KeyE, KeyF, KeyG, KeyH, KeyI, KeyJ, KeyK, KeyL, KeyM, KeyN,
+ KeyO, KeyP, KeyQ, KeyR, KeyS, KeyT, KeyU, KeyV, KeyW, KeyX, KeyY, KeyZ,
+ ];
+ if let Some(i) = letters.iter().position(|c| *c == code) {
+ return Some(0x41 + i as u16);
+ }
+ let digits = [Digit0, Digit1, Digit2, Digit3, Digit4, Digit5, Digit6, Digit7, Digit8, Digit9];
+ if let Some(i) = digits.iter().position(|c| *c == code) {
+ return Some(0x30 + i as u16);
+ }
+ Some(match code {
+ Space => 0x20,
+ Semicolon => 0xBA,
+ Equal => 0xBB,
+ Comma => 0xBC,
+ Minus => 0xBD,
+ Period => 0xBE,
+ Slash => 0xBF,
+ Backquote => 0xC0,
+ BracketLeft => 0xDB,
+ Backslash => 0xDC,
+ BracketRight => 0xDD,
+ Quote => 0xDE,
+ IntlBackslash => 0xE2,
+ _ => return None,
+ })
+}
+
+/// What each action should do, before the OS is asked anything: the shortcut
+/// to register, or the reason it won't be. `types` answers whether a Ctrl+Alt
+/// combination types a character (see platform::ctrl_alt_types).
+pub fn plan(
+ stored: &Bindings,
+ types: impl Fn(&Shortcut) -> Option<String>,
+) -> Vec<(&'static ActionDef, Result<Shortcut, ActionStatus>)> {
+ let mut seen = HashSet::new();
+ ACTIONS
+ .iter()
+ .map(|def| {
+ let refuse = |status, typed| Err(ActionStatus { id: def.id, status, typed });
+ let binding = effective(def, stored);
+ let outcome = if !def.ported {
+ refuse(Status::NotPorted, None)
+ } else if !binding.enabled || binding.keys.trim().is_empty() {
+ refuse(Status::Off, None)
+ } else {
+ match parse(&binding.keys) {
+ None => refuse(Status::Invalid, None),
+ Some(shortcut) => {
+ if let Some(typed) = types(&shortcut) {
+ refuse(Status::TypesCharacter, Some(typed))
+ } else if !seen.insert(shortcut.id()) {
+ refuse(Status::Duplicate, None)
+ } else {
+ Ok(shortcut)
+ }
+ }
+ }
+ };
+ (def, outcome)
+ })
+ .collect()
+}
+
+/// `coucou --shortcut <id>` → the action id, when it names a ported one.
+pub fn from_args(args: &[String]) -> Option<&'static str> {
+ let at = args.iter().position(|a| a == "--shortcut")?;
+ let def = find(args.get(at + 1)?)?;
+ def.ported.then_some(def.id)
+}
+
+// ── Registration ──────────────────────────────────────────────────────────────
+
+/// The plugin, with every press routed through `dispatch`.
+pub fn plugin<R: Runtime>() -> tauri::plugin::TauriPlugin<R> {
+ tauri_plugin_global_shortcut::Builder::new()
+ .with_handler(|app, shortcut, event| {
+ if event.state != ShortcutState::Pressed {
+ return;
+ }
+ let Some(registry) = app.try_state::<Registry>() else { return };
+ let action = registry.by_id.lock().unwrap().get(&shortcut.id()).copied();
+ if let Some(action) = action {
+ dispatch(app, action);
+ }
+ })
+ .build()
+}
+
+/// Hands an action to the island.
+pub fn dispatch<R: Runtime>(app: &AppHandle<R>, action: &str) {
+ crate::log::line(format!("shortcut {action}"));
+ if action == "wardrobeToggle" {
+ let _ = app.emit_to(WINDOW_LABEL, "open-wardrobe", ());
+ } else {
+ let _ = app.emit_to(WINDOW_LABEL, "shortcut", action.to_string());
+ }
+}
+
+/// Unregisters everything Coucou holds.
+fn release<R: Runtime>(app: &AppHandle<R>) {
+ if let Some(gs) = app.try_state::<GlobalShortcut<R>>() {
+ if let Err(err) = gs.unregister_all() {
+ crate::log::line(format!("shortcuts: unregister failed: {err}"));
+ }
+ }
+ if let Some(registry) = app.try_state::<Registry>() {
+ registry.by_id.lock().unwrap().clear();
+ }
+}
+
+/// Registers the shortcuts in `stored` in place of the current ones, and
+/// tells the settings window how each one went. Never fails: a shortcut that
+/// can't be had is reported, not fatal.
+pub fn apply<R: Runtime>(app: &AppHandle<R>, stored: &Bindings) {
+ release(app);
+ let blocked = crate::platform::global_shortcuts_blocked();
+ let gs = app.try_state::<GlobalShortcut<R>>();
+
+ let mut by_id = HashMap::new();
+ let mut report = Vec::new();
+ for (def, outcome) in plan(stored, typed_character) {
+ let status = match outcome {
+ Err(status) => status,
+ Ok(_) if blocked.is_some() || gs.is_none() => {
+ ActionStatus { id: def.id, status: Status::Unsupported, typed: None }
+ }
+ Ok(shortcut) => {
+ // No lock of ours is held here: the plugin calls our handler
+ // with its own lock taken, on the thread that registers.
+ let result = gs.as_ref().map(|gs| gs.register(shortcut));
+ let status = match result {
+ Some(Ok(())) => {
+ by_id.insert(shortcut.id(), def.id);
+ Status::Active
+ }
+ Some(Err(err)) => {
+ crate::log::line(format!("shortcuts: {} not registered: {err}", def.id));
+ Status::InUse
+ }
+ None => Status::Unsupported,
+ };
+ ActionStatus { id: def.id, status, typed: None }
+ }
+ };
+ report.push(status);
+ }
+
+ if let Some(registry) = app.try_state::<Registry>() {
+ *registry.by_id.lock().unwrap() = by_id;
+ *registry.report.lock().unwrap() = report;
+ }
+ let _ = app.emit("shortcuts-status", status(app));
+}
+
+/// Lets go of every shortcut while a new one is being recorded in Settings,
+/// so pressing a combination Coucou already holds records it instead of
+/// running it.
+pub fn suspend<R: Runtime>(app: &AppHandle<R>) {
+ release(app);
+}
+
+pub fn status<R: Runtime>(app: &AppHandle<R>) -> Report {
+ let actions = app
+ .try_state::<Registry>()
+ .map(|r| r.report.lock().unwrap().clone())
+ .unwrap_or_default();
+ Report {
+ actions,
+ blocked: crate::platform::global_shortcuts_blocked().map(str::to_string),
+ command: format!("{} --shortcut", launch_command()),
+ }
+}
+
+/// How a desktop shortcut should start us: the AppImage when we run from one
+/// (the mounted executable moves on every launch), this executable otherwise.
+fn launch_command() -> String {
+ let exe = std::env::var_os("APPIMAGE")
+ .map(std::path::PathBuf::from)
+ .or_else(|| std::env::current_exe().ok())
+ .map(|p| p.to_string_lossy().to_string())
+ .unwrap_or_else(|| "coucou".to_string());
+ if exe.contains(' ') {
+ format!("\"{exe}\"")
+ } else {
+ exe
+ }
+}
+
+fn typed_character(shortcut: &Shortcut) -> Option<String> {
+ if !is_altgr_like(shortcut) {
+ return None;
+ }
+ let vk = character_vk(shortcut.key)?;
+ crate::platform::ctrl_alt_types(vk, shortcut.mods.contains(Modifiers::SHIFT))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const MAC_IDS: [&str; 10] = [
+ "toggleIsland", "openChat", "goToAlert", "jumpToTerminal", "attachFrontWindow",
+ "nextPill", "prevPill", "muteToggle", "desktopToggle", "wardrobeToggle",
+ ];
+
+ fn never(_: &Shortcut) -> Option<String> {
+ None
+ }
+
+ // testDefaultsExhaustive
+ #[test]
+ fn every_mac_action_has_a_default_and_keeps_its_id() {
+ let ids: Vec<_> = ACTIONS.iter().map(|a| a.id).collect();
+ assert_eq!(ids, MAC_IDS);
+ }
+
+ // testAllDefaultsHaveModifier
+ #[test]
+ fn every_default_parses_and_has_a_modifier() {
+ for def in ACTIONS {
+ let shortcut = parse(def.default_keys)
+ .unwrap_or_else(|| panic!("{} default does not parse", def.id));
+ assert!(is_altgr_like(&shortcut), "{} default is not Ctrl+Alt", def.id);
+ }
+ }
+
+ // testNoDefaultDuplicates
+ #[test]
+ fn no_two_defaults_share_a_combination() {
+ let mut seen = HashSet::new();
+ for def in ACTIONS {
+ assert!(seen.insert(parse(def.default_keys).unwrap().id()), "{} duplicates", def.id);
+ }
+ }
+
+ // testEnabledByDefault
+ #[test]
+ fn only_the_island_toggle_is_off_by_default() {
+ for def in ACTIONS {
+ assert_eq!(def.enabled_by_default, def.id != "toggleIsland", "{}", def.id);
+ }
+ }
+
+ #[test]
+ fn the_actions_not_ported_yet_are_reserved_not_registered() {
+ let plan = plan(&Bindings::new(), never);
+ for (def, outcome) in plan {
+ let reserved = matches!(def.id, "attachFrontWindow" | "desktopToggle");
+ assert_eq!(def.ported, !reserved);
+ match outcome {
+ Ok(_) => assert!(def.ported && def.enabled_by_default, "{}", def.id),
+ Err(s) if reserved => assert_eq!(s.status, Status::NotPorted),
+ Err(s) => assert_eq!((def.id, s.status), ("toggleIsland", Status::Off)),
+ }
+ }
+ }
+
+ #[test]
+ fn parsing_needs_a_modifier_and_a_known_key() {
+ assert!(parse("").is_none());
+ assert!(parse("A").is_none(), "a bare key would take A from every app");
+ assert!(parse("Shift+A").is_none(), "so would Shift+A");
+ assert!(parse("Ctrl+Escape").is_none());
+ assert!(parse("Ctrl+Alt+Nope").is_none());
+ assert!(parse("Ctrl+Alt").is_none());
+ let s = parse("Ctrl+Alt+Space").unwrap();
+ assert_eq!(s.key, Code::Space);
+ assert!(s.mods.contains(Modifiers::CONTROL | Modifiers::ALT));
+ assert!(!s.mods.contains(Modifiers::SHIFT));
+ let all = parse("Ctrl+Alt+Shift+Super+K").unwrap();
+ assert!(all.mods.contains(Modifiers::CONTROL | Modifiers::ALT | Modifiers::SHIFT | Modifiers::SUPER));
+ // Case and spelling don't change the combination.
+ assert_eq!(parse("ctrl+alt+right").unwrap().id(), parse("Control+Alt+ArrowRight").unwrap().id());
+ }
+
+ #[test]
+ fn only_ctrl_alt_without_the_windows_key_reads_as_altgr() {
+ assert!(is_altgr_like(&parse("Ctrl+Alt+E").unwrap()));
+ assert!(is_altgr_like(&parse("Ctrl+Alt+Shift+E").unwrap()));
+ assert!(!is_altgr_like(&parse("Ctrl+Shift+E").unwrap()));
+ assert!(!is_altgr_like(&parse("Ctrl+Alt+Super+E").unwrap()));
+ }
+
+ #[test]
+ fn virtual_keys_match_the_ones_registered() {
+ assert_eq!(character_vk(Code::KeyA), Some(0x41));
+ assert_eq!(character_vk(Code::KeyZ), Some(0x5A));
+ assert_eq!(character_vk(Code::Digit0), Some(0x30));
+ assert_eq!(character_vk(Code::Digit9), Some(0x39));
+ assert_eq!(character_vk(Code::BracketRight), Some(0xDD));
+ assert_eq!(character_vk(Code::Space), Some(0x20));
+ assert_eq!(character_vk(Code::ArrowLeft), None);
+ assert_eq!(character_vk(Code::F5), None);
+ }
+
+ // testDuplicateDetection
+ #[test]
+ fn a_combination_used_twice_is_registered_once() {
+ let mut stored = Bindings::new();
+ let same = Binding { keys: "Ctrl+Alt+A".into(), enabled: true };
+ stored.insert("jumpToTerminal".into(), same.clone());
+ let plan = plan(&stored, never);
+ let alert = plan.iter().find(|(d, _)| d.id == "goToAlert").unwrap();
+ let term = plan.iter().find(|(d, _)| d.id == "jumpToTerminal").unwrap();
+ assert!(alert.1.is_ok());
+ assert_eq!(term.1.as_ref().unwrap_err().status, Status::Duplicate);
+
+ // Same key, other modifiers: not a duplicate.
+ stored.insert("jumpToTerminal".into(), Binding { keys: "Ctrl+Shift+A".into(), enabled: true });
+ let plan = super::plan(&stored, never);
+ assert!(plan.iter().all(|(d, o)| o.is_ok() || !d.ported || d.id == "toggleIsland"));
+
+ // A disabled action doesn't hold its keys.
+ stored.insert("goToAlert".into(), Binding { keys: "Ctrl+Alt+A".into(), enabled: false });
+ stored.insert("jumpToTerminal".into(), same);
+ let plan = super::plan(&stored, never);
+ let term = plan.iter().find(|(d, _)| d.id == "jumpToTerminal").unwrap();
+ assert!(term.1.is_ok());
+ }
+
+ #[test]
+ fn a_combination_that_types_a_character_is_not_registered() {
+ let euro = |s: &Shortcut| (s.key == Code::KeyA).then(|| "ą".to_string());
+ let plan = plan(&Bindings::new(), euro);
+ let alert = plan.iter().find(|(d, _)| d.id == "goToAlert").unwrap();
+ let refused = alert.1.as_ref().unwrap_err();
+ assert_eq!(refused.status, Status::TypesCharacter);
+ assert_eq!(refused.typed.as_deref(), Some("ą"));
+ }
+
+ #[test]
+ fn stored_bindings_override_the_defaults_and_the_rest_fall_back() {
+ let mut stored = Bindings::new();
+ stored.insert("openChat".into(), Binding { keys: "Ctrl+Shift+K".into(), enabled: true });
+ stored.insert("muteToggle".into(), Binding { keys: String::new(), enabled: true });
+ let chat = effective(find("openChat").unwrap(), &stored);
+ assert_eq!(chat.keys, "Ctrl+Shift+K");
+ let alert = effective(find("goToAlert").unwrap(), &stored);
+ assert_eq!(alert, Binding { keys: "Ctrl+Alt+A".into(), enabled: true });
+ let toggle = effective(find("toggleIsland").unwrap(), &stored);
+ assert!(!toggle.enabled);
+ let plan = plan(&stored, never);
+ let mute = plan.iter().find(|(d, _)| d.id == "muteToggle").unwrap();
+ assert_eq!(mute.1.as_ref().unwrap_err().status, Status::Off);
+ }
+
+ // testLoadSaveRoundTrip
+ #[test]
+ fn bindings_round_trip_through_json() {
+ let mut stored = Bindings::new();
+ stored.insert("openChat".into(), Binding { keys: "Ctrl+Alt+K".into(), enabled: false });
+ let json = serde_json::to_string(&stored).unwrap();
+ assert_eq!(json, r#"{"openChat":{"keys":"Ctrl+Alt+K","enabled":false}}"#);
+ assert_eq!(serde_json::from_str::<Bindings>(&json).unwrap(), stored);
+ // A hand-edited entry without `enabled` stays on.
+ let partial: Bindings = serde_json::from_str(r#"{"openChat":{"keys":"Ctrl+Alt+K"}}"#).unwrap();
+ assert!(partial["openChat"].enabled);
+ }
+
+ #[test]
+ fn the_command_line_names_an_action() {
+ let args = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
+ assert_eq!(from_args(&args(&["coucou", "--shortcut", "openChat"])), Some("openChat"));
+ assert_eq!(from_args(&args(&["coucou", "--shortcut", "wardrobeToggle"])), Some("wardrobeToggle"));
+ assert_eq!(from_args(&args(&["coucou", "--shortcut"])), None);
+ assert_eq!(from_args(&args(&["coucou", "--shortcut", "rm -rf"])), None);
+ assert_eq!(from_args(&args(&["coucou", "--shortcut", "desktopToggle"])), None);
+ assert_eq!(from_args(&args(&["coucou"])), None);
+ }
+}