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.
Swift ai-agentsanthropicantigravityclaudeclaude-codecodexcursordynamic-islandgemini-cliiosiphonlinuxmacosmacos-appmenubar-appnotchopen-sourceswiftswiftuiwindows
Linux: global shortcuts on Wayland through the XDG GlobalShortcuts portal
Claude97f9d66ff7fc
diff --git a/windows/Cargo.lock b/windows/Cargo.lockindex 777a49ea..8a6e1813 100644--- a/windows/Cargo.lock+++ b/windows/Cargo.lock@@ -612,6 +612,7 @@ dependencies = [name = "coucou"version = "0.2.0"dependencies = [+ "dbus","gtk","keyring","libc",diff --git a/windows/README.md b/windows/README.mdindex cf48b882..5b21f05f 100644--- a/windows/README.md+++ b/windows/README.md@@ -398,8 +398,11 @@ own window.console window (`cmd.exe` or PowerShell without Windows Terminal) has no suchancestor — conhost owns that window — so its folder opens in VS Code instead,as it does when `code` is on your `PATH` and nothing was found.-- No global keyboard shortcuts yet: a waiting card is folded with its **⌃** or- `Esc` in the island, and reopened by clicking the island or Open in the tray.+- Global keyboard shortcuts are hot keys on Windows, key grabs on Linux under+ X11, and go through the desktop's GlobalShortcuts portal under Wayland (see+ [Linux](#linux)). A waiting card is also folded with its **⌃** or `Esc` in+ the island, and reopened by clicking the island, Open in the tray or **Go to+ alert**.- Apple Music, the one pill from the Mac catalog with nothing behind it here,is left out.- Not in this version: sending a dropped file by email and dragging Mochi onto@@ -521,13 +524,27 @@ What changes on Linux:for `sh`, and its config under `~` (see Supported agents). A config that is asymlink (dotfiles) is written through to its target, with its permissionskept.-- **Global shortcuts** are X11 key grabs, so they work in an X11 session.+- **Global shortcuts** are X11 key grabs in an X11 session.On X11, AltGr is a modifier of its own and never clashes with `Ctrl+Alt`;combinations the desktop already uses (GNOME's `Ctrl+Alt+T` terminal and- `Ctrl+Alt+←`/`→` workspace switching) show up as *In use*. Wayland has no- key grabs — the GlobalShortcuts portal isn't supported yet — so nothing is- registered there, and **Settings → Shortcuts** lists commands to bind in your- desktop's own keyboard settings instead:+ `Ctrl+Alt+←`/`→` workspace switching) show up as *In use*.+ Wayland has no key grabs, so there Coucou hands its shortcuts to the desktop+ through the XDG **GlobalShortcuts portal** (`xdg-desktop-portal`, with a+ backend that has it: KDE Plasma 6, GNOME 48+, Hyprland, COSMIC…). Each+ shortcut goes with its description and your keys as the preferred trigger;+ the desktop may show its own window to confirm them or to pick other keys,+ and it has the last word: a shortcut it already knows keeps the keys it was+ given there, and you change them in the desktop's own shortcut settings.+ **Settings → Shortcuts** says the shortcuts are registered with the desktop,+ shows next to each one the keys the desktop reports (*Desktop: …*), and flags+ one it left out. Changing or turning off a shortcut in Coucou binds the new+ set in a new portal session. Coucou names itself `fr.louisraille.coucou` to+ the portal where the portal allows it (`xdg-desktop-portal` 1.19+); a+ desktop that wants an app name may otherwise refuse.+ Where there is no such portal, or the desktop refuses, nothing is registered+ and **Settings → Shortcuts** lists commands to bind in your+ desktop's own keyboard settings instead (they are shown with the portal too,+ for any shortcut that doesn't work):`coucou --shortcut openChat` (or the AppImage's path) runs the action in theCoucou that is already open. The ids are `toggleIsland`, `openChat`,`goToAlert`, `jumpToTerminal`, `nextPill`, `prevPill`, `muteToggle` anddiff --git a/windows/src-tauri/Cargo.toml b/windows/src-tauri/Cargo.tomlindex 741b0081..b7dee25a 100644--- a/windows/src-tauri/Cargo.toml+++ b/windows/src-tauri/Cargo.toml@@ -50,3 +50,6 @@ libc = "0.2"# The GTK that Tauri already runs on, to reach its window for layer-shell and# the input region. libgtk-layer-shell itself is called directly (platform/linux.rs).gtk = "0.18"+# Global shortcuts on Wayland through the XDG GlobalShortcuts portal+# (portal.rs). The libdbus binding keyring's Secret Service already links.+dbus = "0.9"diff --git a/windows/src-tauri/src/lib.rs b/windows/src-tauri/src/lib.rsindex 3667b5e8..e854834c 100644--- a/windows/src-tauri/src/lib.rs+++ b/windows/src-tauri/src/lib.rs@@ -20,6 +20,8 @@ mod net;mod openai_compat;mod pipe;mod platform;+#[cfg(target_os = "linux")]+mod portal;mod recap;mod secrets;mod session_window;diff --git a/windows/src-tauri/src/platform/linux.rs b/windows/src-tauri/src/platform/linux.rsindex 38dff741..6f13adf9 100644--- a/windows/src-tauri/src/platform/linux.rs+++ b/windows/src-tauri/src/platform/linux.rs@@ -588,10 +588,10 @@ fn apply_input_region(gw: &impl IsA<gtk::Widget>, rect: Region) {/// 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.+/// it would look registered and never fire. On Wayland the shortcuts go to the+/// desktop through the XDG GlobalShortcuts portal instead (portal.rs), and+/// where there is none Settings explains how to bind `coucou --shortcut <id>`+/// in the desktop's own keyboard settings.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")diff --git a/windows/src-tauri/src/portal.rs b/windows/src-tauri/src/portal.rsnew file mode 100644index 00000000..cc8aa9e5--- /dev/null+++ b/windows/src-tauri/src/portal.rs@@ -0,0 +1,908 @@+// Global shortcuts on Wayland, through the XDG desktop portal+// (org.freedesktop.portal.GlobalShortcuts): KDE Plasma 6, GNOME 48+,+// Hyprland's portal, COSMIC…+//+// Wayland lets no app grab keys, so the desktop holds the shortcuts and tells+// us when one is pressed. The exchange, all on the session bus:+//+// CreateSession({handle_token, session_handle_token}) → Request → Response+// BindShortcuts(session, [(id, {description, preferred_trigger})], "", {handle_token})+// → Request → Response+// … then Activated(session, id, timestamp, options) on every press, and+// ShortcutsChanged(session, shortcuts) when the user picks other keys.+//+// The desktop may show its own dialog to confirm the shortcuts or change their+// keys, so a Response can take as long as the user does: nothing here waits+// for one. Everything runs on one thread that owns the D-Bus connection and+// sleeps in poll() on the bus and a wake-up socket — no timeout, so it costs+// nothing while no key is pressed. Shortcuts.rs talks to it through a Handle+// and hears back through the callback given to `start`; this file knows+// nothing of Tauri.+//+// The D-Bus client is the `dbus` crate (libdbus), which keyring's Secret+// Service support already links.++use std::io::{ErrorKind, Read, Write};+use std::os::fd::AsRawFd;+use std::os::unix::net::UnixStream;+use std::sync::mpsc::{self, TryRecvError};+use std::time::Duration;++use dbus::arg::{ArgType, PropMap, RefArg, Variant};+use dbus::channel::{BusType, Channel};+use dbus::message::MessageType;+use dbus::strings::Path;+use dbus::Message;+use tauri_plugin_global_shortcut::{Code, Modifiers, Shortcut};++const DEST: &str = "org.freedesktop.portal.Desktop";+const OBJECT: &str = "/org/freedesktop/portal/desktop";+const IFACE: &str = "org.freedesktop.portal.GlobalShortcuts";+const REQUEST: &str = "org.freedesktop.portal.Request";+const SESSION: &str = "org.freedesktop.portal.Session";+/// Tauri's identifier. Told to the portal so the desktop files the shortcuts+/// under Coucou rather than under an unnamed app.+const APP_ID: &str = "fr.louisraille.coucou";+/// For the calls themselves, which answer at once: the user's answer comes+/// later, in a Response signal.+const CALL_TIMEOUT: Duration = Duration::from_secs(10);++// ── Pure helpers ──────────────────────────────────────────────────────────────++/// Coucou's accelerator ("Ctrl+Alt+Space") → the XDG shortcuts spec's trigger+/// ("CTRL+ALT+space"): modifiers CTRL, ALT, SHIFT, LOGO, then an xkb keysym+/// name. `None` for a binding that isn't a shortcut, or whose key has no+/// keysym here; the desktop then picks the key, or lets the user pick one.+pub fn xdg_trigger(keys: &str) -> Option<String> {+ trigger_of(&crate::shortcuts::parse(keys)?)+}++fn trigger_of(shortcut: &Shortcut) -> Option<String> {+ let mut parts = Vec::new();+ if shortcut.mods.contains(Modifiers::CONTROL) {+ parts.push("CTRL".to_string());+ }+ if shortcut.mods.contains(Modifiers::ALT) {+ parts.push("ALT".to_string());+ }+ if shortcut.mods.contains(Modifiers::SHIFT) {+ parts.push("SHIFT".to_string());+ }+ if shortcut.mods.intersects(Modifiers::SUPER | Modifiers::META) {+ parts.push("LOGO".to_string());+ }+ parts.push(keysym(shortcut.key)?);+ Some(parts.join("+"))+}++/// The xkb keysym name of the keys an accelerator may name (KEY_NAMES in+/// src/core/shortcuts.ts).+fn keysym(code: Code) -> Option<String> {+ use Code::*;+ let fixed = match code {+ Space => "space",+ Enter => "Return",+ Tab => "Tab",+ Backspace => "BackSpace",+ Delete => "Delete",+ Insert => "Insert",+ Home => "Home",+ End => "End",+ PageUp => "Page_Up",+ PageDown => "Page_Down",+ ArrowUp => "Up",+ ArrowDown => "Down",+ ArrowLeft => "Left",+ ArrowRight => "Right",+ Comma => "comma",+ Period => "period",+ Slash => "slash",+ Semicolon => "semicolon",+ Quote => "apostrophe",+ Backquote => "grave",+ BracketLeft => "bracketleft",+ BracketRight => "bracketright",+ Backslash => "backslash",+ Minus => "minus",+ Equal => "equal",+ _ => "",+ };+ if !fixed.is_empty() {+ return Some(fixed.to_string());+ }+ // KeyA → a, Digit1 → 1, F5 → F5.+ let name = code.to_string();+ if let Some(letter) = name.strip_prefix("Key").filter(|l| l.len() == 1) {+ return Some(letter.to_ascii_lowercase());+ }+ if let Some(digit) = name.strip_prefix("Digit").filter(|d| d.len() == 1) {+ return Some(digit.to_string());+ }+ let function = name+ .strip_prefix('F')+ .and_then(|n| n.parse::<u8>().ok())+ .is_some_and(|n| (1..=24).contains(&n));+ function.then_some(name)+}++/// Where the portal puts the Request object for `token`: the caller's unique+/// name without its colon, dots made underscores.+pub fn request_path(sender: &str, token: &str) -> String {+ format!("{OBJECT}/request/{}/{token}", escape_sender(sender))+}++/// Same rule for the Session object.+pub fn session_path(sender: &str, token: &str) -> String {+ format!("{OBJECT}/session/{}/{token}", escape_sender(sender))+}++fn escape_sender(sender: &str) -> String {+ sender.trim_start_matches(':').replace('.', "_")+}++/// One shortcut handed to the desktop.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Wanted {+ pub id: String,+ pub description: String,+ /// XDG trigger; `None` leaves the key to the desktop.+ pub trigger: Option<String>,+}++/// One shortcut the desktop holds, and the keys it says run it.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Bound {+ pub id: String,+ /// `trigger_description`, as the desktop writes it; `None` when it gave+ /// none or an empty one.+ pub trigger: Option<String>,+}++/// The value inside a variant, however deep.+fn unwrap_variant(arg: &dyn RefArg) -> &dyn RefArg {+ let mut arg = arg;+ while arg.arg_type() == ArgType::Variant {+ match arg.as_iter().and_then(|mut inner| inner.next()) {+ Some(inner) => arg = inner,+ None => break,+ }+ }+ arg+}++/// `key` in an `a{sv}` read off the bus.+fn dict_get<'a>(dict: &'a dyn RefArg, key: &str) -> Option<&'a dyn RefArg> {+ let mut items = unwrap_variant(dict).as_iter()?;+ while let (Some(k), Some(v)) = (items.next(), items.next()) {+ if k.as_str() == Some(key) {+ return Some(unwrap_variant(v));+ }+ }+ None+}++/// The `a(sa{sv})` list of BindShortcuts' Response and of ShortcutsChanged.+/// `None` when it isn't one.+pub fn parse_shortcuts(arg: &dyn RefArg) -> Option<Vec<Bound>> {+ let list = unwrap_variant(arg);+ if list.arg_type() != ArgType::Array {+ return None;+ }+ let mut out = Vec::new();+ for item in list.as_iter()? {+ let mut fields = item.as_iter()?;+ let id = fields.next()?.as_str()?.to_string();+ let trigger = fields+ .next()+ .and_then(|props| dict_get(props, "trigger_description"))+ .and_then(|t| t.as_str())+ .map(str::trim)+ .filter(|t| !t.is_empty())+ .map(str::to_string);+ out.push(Bound { id, trigger });+ }+ Some(out)+}++/// A Request's Response: `Ok(results)` when the user went ahead (0), `Err`+/// with the code otherwise (1 cancelled, 2 anything else).+pub fn parse_response(msg: &Message) -> Result<PropMap, u32> {+ match msg.read2::<u32, PropMap>() {+ Ok((0, results)) => Ok(results),+ Ok((code, _)) => Err(code),+ Err(_) => Err(2),+ }+}++/// The session CreateSession made: `session_handle` from its results (a+/// string or an object path, depending on the portal's age).+pub fn session_from_results(results: &PropMap) -> Option<String> {+ let handle = results.get("session_handle")?.0.as_str()?;+ (!handle.is_empty()).then(|| handle.to_string())+}++// ── The portal thread ─────────────────────────────────────────────────────────++/// What the thread tells shortcuts.rs. `gen` is the `bind` call it answers.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum Event {+ /// The desktop holds the shortcuts. `None` when it didn't say which.+ Bound { gen: u64, shortcuts: Option<Vec<Bound>> },+ /// The user gave some shortcuts other keys.+ Changed { gen: u64, shortcuts: Vec<Bound> },+ /// Refused, failed, or the desktop closed the session.+ Failed { gen: u64, reason: String },+ /// No GlobalShortcuts portal (or no session bus). The thread has stopped.+ Unavailable(String),+ /// A shortcut was pressed.+ Activated(String),+}++enum Command {+ Bind { gen: u64, shortcuts: Vec<Wanted> },+ Release,+}++/// The way to the portal thread. Sending never blocks.+pub struct Handle {+ tx: mpsc::Sender<Command>,+ wake: UnixStream,+}++impl Handle {+ /// Asks the desktop for `shortcuts` in place of the current ones. False+ /// when the thread is gone (no portal).+ pub fn bind(&self, gen: u64, shortcuts: Vec<Wanted>) -> bool {+ self.send(Command::Bind { gen, shortcuts })+ }++ /// Gives every shortcut back (Settings is recording a new one).+ pub fn release(&self) -> bool {+ self.send(Command::Release)+ }++ fn send(&self, command: Command) -> bool {+ if self.tx.send(command).is_err() {+ return false;+ }+ // A full socket means a wake-up is already pending.+ let _ = (&self.wake).write(&[1]);+ true+ }+}++/// Starts the portal thread. It first checks there is a portal to talk to,+/// and says `Unavailable` (then stops) when there isn't.+pub fn start(on_event: impl Fn(Event) + Send + 'static) -> Option<Handle> {+ let (tx, rx) = mpsc::channel();+ let (wake_rx, wake_tx) = UnixStream::pair().ok()?;+ wake_rx.set_nonblocking(true).ok()?;+ wake_tx.set_nonblocking(true).ok()?;+ std::thread::Builder::new()+ .name("shortcuts-portal".into())+ .spawn(move || run(rx, wake_rx, on_event))+ .ok()?;+ Some(Handle { tx, wake: wake_tx })+}++fn run(rx: mpsc::Receiver<Command>, wake: UnixStream, on_event: impl Fn(Event)) {+ let mut portal = match Portal::connect() {+ Ok(portal) => portal,+ Err(why) => return on_event(Event::Unavailable(why)),+ };+ loop {+ loop {+ match rx.try_recv() {+ Ok(command) => portal.command(command, &on_event),+ Err(TryRecvError::Empty) => break,+ Err(TryRecvError::Disconnected) => return portal.abandon(),+ }+ }+ while let Some(msg) = portal.channel.pop_message() {+ portal.message(&msg, &on_event);+ }+ if !portal.channel.is_connected() {+ return on_event(Event::Unavailable("the session bus went away".into()));+ }+ if let Err(why) = wait(&portal.channel, &wake) {+ portal.abandon();+ return on_event(Event::Unavailable(why));+ }+ // Drain the wake-ups; the commands themselves are in `rx`.+ let mut buf = [0u8; 64];+ while matches!((&wake).read(&mut buf), Ok(n) if n > 0) {}+ if portal.channel.read_write(Some(Duration::ZERO)).is_err() {+ return on_event(Event::Unavailable("the session bus went away".into()));+ }+ }+}++/// Sleeps until the bus or a command has something. No timeout.+fn wait(channel: &Channel, wake: &UnixStream) -> Result<(), String> {+ let watch = channel.watch();+ let mut events = libc::POLLIN;+ if channel.has_messages_to_send() {+ events |= libc::POLLOUT;+ }+ let mut fds = [+ libc::pollfd { fd: watch.fd, events, revents: 0 },+ libc::pollfd { fd: wake.as_raw_fd(), events: libc::POLLIN, revents: 0 },+ ];+ loop {+ let n = unsafe { libc::poll(fds.as_mut_ptr(), fds.len() as libc::nfds_t, -1) };+ if n >= 0 {+ return Ok(());+ }+ let err = std::io::Error::last_os_error();+ if err.kind() != ErrorKind::Interrupted {+ return Err(format!("poll: {err}"));+ }+ }+}++/// Where the exchange with the desktop stands.+enum Phase {+ Idle,+ /// CreateSession sent, its Response awaited.+ Creating { gen: u64, request: String, session: String, want: Vec<Wanted> },+ /// BindShortcuts sent; the desktop may be showing its dialog.+ Binding { gen: u64, request: String, session: String, want: Vec<Wanted> },+ Bound { gen: u64, session: String, want: Vec<Wanted>, shortcuts: Option<Vec<Bound>> },+}++struct Portal {+ channel: Channel,+ sender: String,+ tokens: u64,+ phase: Phase,+}++impl Portal {+ fn connect() -> Result<Portal, String> {+ let mut channel = Channel::get_private(BusType::Session).map_err(|e| format!("session bus: {e}"))?;+ channel.set_watch_enabled(true);+ let sender = channel.unique_name().ok_or("no unique name on the session bus")?.to_string();+ let portal = Portal { channel, sender, tokens: 0, phase: Phase::Idle };++ // Names the app to the portal (xdg-desktop-portal 1.19+, apps outside+ // a sandbox). It has to come before any other portal call; an older+ // portal doesn't know it, and then the desktop names us itself.+ if let Err(err) = portal.call(+ method(OBJECT, "org.freedesktop.host.portal.Registry", "Register")?+ .append2(APP_ID, PropMap::new()),+ ) {+ crate::log::line(format!("shortcuts portal: no app registry ({err})"));+ }++ let version = portal+ .call(+ method(OBJECT, "org.freedesktop.DBus.Properties", "Get")?.append2(IFACE, "version"),+ )+ .and_then(|reply| {+ reply.read1::<Variant<u32>>().map(|v| v.0).map_err(|e| e.to_string())+ })+ .map_err(|e| format!("no GlobalShortcuts portal: {e}"))?;+ crate::log::line(format!("shortcuts portal: GlobalShortcuts version {version}"));++ for rule in [+ format!("type='signal',sender='{DEST}',interface='{IFACE}'"),+ format!("type='signal',sender='{DEST}',interface='{REQUEST}',member='Response'"),+ format!("type='signal',sender='{DEST}',interface='{SESSION}',member='Closed'"),+ ] {+ let add = Message::new_method_call(+ "org.freedesktop.DBus",+ "/org/freedesktop/DBus",+ "org.freedesktop.DBus",+ "AddMatch",+ )?+ .append1(rule);+ portal.call(add).map_err(|e| format!("AddMatch: {e}"))?;+ }+ Ok(portal)+ }++ fn call(&self, msg: Message) -> Result<Message, String> {+ self.channel.send_with_reply_and_block(msg, CALL_TIMEOUT).map_err(|e| {+ format!("{}: {}", e.name().unwrap_or("error"), e.message().unwrap_or(""))+ })+ }++ /// A method call we don't wait on (closing a request or a session).+ fn close(&self, path: &str, iface: &str) {+ if let Ok(msg) = Message::new_method_call(DEST, path, iface, "Close") {+ let _ = self.channel.send(msg);+ self.channel.flush();+ }+ }++ fn token(&mut self) -> String {+ self.tokens += 1;+ format!("coucou{}_{}", std::process::id(), self.tokens)+ }++ fn gen(&self) -> Option<u64> {+ match &self.phase {+ Phase::Idle => None,+ Phase::Creating { gen, .. } | Phase::Binding { gen, .. } | Phase::Bound { gen, .. } => Some(*gen),+ }+ }++ /// Drops whatever is in flight or bound. The portal may need a new session+ /// to bind other shortcuts, so a change always starts over.+ fn abandon(&mut self) {+ match std::mem::replace(&mut self.phase, Phase::Idle) {+ Phase::Idle => {}+ Phase::Creating { request, session, .. } | Phase::Binding { request, session, .. } => {+ self.close(&request, REQUEST);+ self.close(&session, SESSION);+ }+ Phase::Bound { session, .. } => self.close(&session, SESSION),+ }+ }++ fn command(&mut self, command: Command, on_event: &impl Fn(Event)) {+ match command {+ Command::Release => self.abandon(),+ Command::Bind { gen, shortcuts } => {+ // The same shortcuts as now: nothing to ask the desktop.+ if let Phase::Bound { gen: current, want, shortcuts: bound, .. } = &mut self.phase {+ if *want == shortcuts {+ *current = gen;+ return on_event(Event::Bound { gen, shortcuts: bound.clone() });+ }+ }+ self.abandon();+ if shortcuts.is_empty() {+ return on_event(Event::Bound { gen, shortcuts: Some(Vec::new()) });+ }+ if let Err(reason) = self.create_session(gen, shortcuts) {+ on_event(Event::Failed { gen, reason });+ }+ }+ }+ }++ fn create_session(&mut self, gen: u64, want: Vec<Wanted>) -> Result<(), String> {+ let handle_token = self.token();+ let session_token = self.token();+ let mut options = PropMap::new();+ options.insert("handle_token".into(), Variant(Box::new(handle_token.clone())));+ options.insert("session_handle_token".into(), Variant(Box::new(session_token.clone())));+ let reply = self.call(method(OBJECT, IFACE, "CreateSession")?.append1(options))?;+ // An old portal may not follow the token; its answer is the truth.+ let request = reply+ .read1::<Path>()+ .map(|p| p.to_string())+ .unwrap_or_else(|_| request_path(&self.sender, &handle_token));+ let session = session_path(&self.sender, &session_token);+ self.phase = Phase::Creating { gen, request, session, want };+ Ok(())+ }++ fn bind_shortcuts(&mut self, gen: u64, session: String, want: Vec<Wanted>) -> Result<(), String> {+ let list: Vec<(String, PropMap)> = want+ .iter()+ .map(|w| {+ let mut props = PropMap::new();+ props.insert("description".into(), Variant(Box::new(w.description.clone())));+ if let Some(trigger) = &w.trigger {+ props.insert("preferred_trigger".into(), Variant(Box::new(trigger.clone())));+ }+ (w.id.clone(), props)+ })+ .collect();+ let handle_token = self.token();+ let mut options = PropMap::new();+ options.insert("handle_token".into(), Variant(Box::new(handle_token.clone())));+ let session_obj = Path::new(session.clone())?;+ let msg = method(OBJECT, IFACE, "BindShortcuts")?.append3(session_obj, list, "").append1(options);+ // Bound to the session even if the call fails, so abandon() closes it.+ self.phase = Phase::Binding {+ gen,+ request: request_path(&self.sender, &handle_token),+ session: session.clone(),+ want: want.clone(),+ };+ let reply = self.call(msg)?;+ if let Ok(path) = reply.read1::<Path>() {+ self.phase = Phase::Binding { gen, request: path.to_string(), session, want };+ }+ Ok(())+ }++ fn message(&mut self, msg: &Message, on_event: &impl Fn(Event)) {+ if msg.msg_type() != MessageType::Signal {+ return;+ }+ let (Some(path), Some(iface), Some(member)) = (msg.path(), msg.interface(), msg.member()) else {+ return;+ };+ match (&*iface, &*member) {+ (REQUEST, "Response") => self.response(&path, msg, on_event),+ (IFACE, "Activated") => {+ let Phase::Bound { session, .. } = &self.phase else { return };+ if let Ok((from, id)) = msg.read2::<Path, String>() {+ if &*from == session.as_str() {+ on_event(Event::Activated(id));+ }+ }+ }+ (IFACE, "ShortcutsChanged") => {+ let Phase::Bound { gen, session, shortcuts, .. } = &mut self.phase else { return };+ let mut args = msg.iter_init();+ let from: Option<Path> = args.read().ok();+ if from.as_deref() != Some(session.as_str()) {+ return;+ }+ if let Some(changed) = args.get_refarg().and_then(|a| parse_shortcuts(&*a)) {+ *shortcuts = Some(changed.clone());+ on_event(Event::Changed { gen: *gen, shortcuts: changed });+ }+ }+ (SESSION, "Closed") => {+ let ours = match &self.phase {+ Phase::Binding { session, .. } | Phase::Bound { session, .. } => &*path == session.as_str(),+ _ => false,+ };+ if ours {+ let gen = self.gen().unwrap_or_default();+ self.phase = Phase::Idle;+ on_event(Event::Failed { gen, reason: "the desktop closed the session".into() });+ }+ }+ _ => {}+ }+ }++ fn response(&mut self, path: &str, msg: &Message, on_event: &impl Fn(Event)) {+ let awaited = match &self.phase {+ Phase::Creating { request, .. } | Phase::Binding { request, .. } => request == path,+ _ => false,+ };+ if !awaited {+ return;+ }+ let answer = parse_response(msg);+ match std::mem::replace(&mut self.phase, Phase::Idle) {+ Phase::Creating { gen, session, want, .. } => {+ let results = match answer {+ Ok(results) => results,+ Err(code) => {+ self.close(&session, SESSION);+ let reason = format!("CreateSession answered {code}");+ return on_event(Event::Failed { gen, reason });+ }+ };+ let session = session_from_results(&results).unwrap_or(session);+ if let Err(reason) = self.bind_shortcuts(gen, session, want) {+ self.abandon();+ on_event(Event::Failed { gen, reason: format!("BindShortcuts: {reason}") });+ }+ }+ Phase::Binding { gen, session, want, .. } => match answer {+ Ok(results) => {+ let shortcuts = results.get("shortcuts").and_then(|v| parse_shortcuts(&*v.0));+ self.phase = Phase::Bound { gen, session, want, shortcuts: shortcuts.clone() };+ on_event(Event::Bound { gen, shortcuts });+ }+ Err(code) => {+ self.close(&session, SESSION);+ let reason = if code == 1 { "the user declined".to_string() } else { format!("BindShortcuts answered {code}") };+ on_event(Event::Failed { gen, reason });+ }+ },+ other => self.phase = other,+ }+ }+}++fn method(path: &str, iface: &str, member: &str) -> Result<Message, String> {+ Message::new_method_call(DEST, path, iface, member)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn coucou_bindings_become_xdg_triggers() {+ assert_eq!(xdg_trigger("Ctrl+Alt+Space").as_deref(), Some("CTRL+ALT+space"));+ assert_eq!(xdg_trigger("Ctrl+Alt+A").as_deref(), Some("CTRL+ALT+a"));+ assert_eq!(xdg_trigger("Ctrl+Alt+Right").as_deref(), Some("CTRL+ALT+Right"));+ assert_eq!(xdg_trigger("Ctrl+Alt+Left").as_deref(), Some("CTRL+ALT+Left"));+ assert_eq!(xdg_trigger("Super+A").as_deref(), Some("LOGO+a"));+ assert_eq!(xdg_trigger("Ctrl+Alt+Shift+Super+K").as_deref(), Some("CTRL+ALT+SHIFT+LOGO+k"));+ assert_eq!(xdg_trigger("Ctrl+Shift+7").as_deref(), Some("CTRL+SHIFT+7"));+ assert_eq!(xdg_trigger("Alt+F5").as_deref(), Some("ALT+F5"));+ assert_eq!(xdg_trigger("Ctrl+F24").as_deref(), Some("CTRL+F24"));+ assert_eq!(xdg_trigger("Ctrl+Alt+Enter").as_deref(), Some("CTRL+ALT+Return"));+ assert_eq!(xdg_trigger("Ctrl+Alt+Backspace").as_deref(), Some("CTRL+ALT+BackSpace"));+ assert_eq!(xdg_trigger("Ctrl+Alt+PageDown").as_deref(), Some("CTRL+ALT+Page_Down"));+ assert_eq!(xdg_trigger("Ctrl+Alt+BracketLeft").as_deref(), Some("CTRL+ALT+bracketleft"));+ assert_eq!(xdg_trigger("Ctrl+Alt+Quote").as_deref(), Some("CTRL+ALT+apostrophe"));+ assert_eq!(xdg_trigger("Ctrl+Alt+Backquote").as_deref(), Some("CTRL+ALT+grave"));+ assert_eq!(xdg_trigger("Ctrl+Alt+Equal").as_deref(), Some("CTRL+ALT+equal"));+ // Any spelling parse() takes gives the same trigger.+ assert_eq!(xdg_trigger("control+option+arrowright"), xdg_trigger("Ctrl+Alt+Right"));+ assert_eq!(xdg_trigger("Ctrl+Alt+Super+T").as_deref(), Some("CTRL+ALT+LOGO+t"));+ }++ #[test]+ fn what_is_not_a_shortcut_has_no_trigger() {+ assert_eq!(xdg_trigger(""), None);+ assert_eq!(xdg_trigger("A"), None);+ assert_eq!(xdg_trigger("Shift+A"), None);+ assert_eq!(xdg_trigger("Ctrl+Alt+Nope"), None);+ // A real key with no keysym in the table: the desktop picks.+ assert_eq!(xdg_trigger("Ctrl+Alt+Numpad5"), None);+ }++ #[test]+ fn every_default_and_every_key_coucou_records_has_a_trigger() {+ for def in crate::shortcuts::ACTIONS {+ assert!(xdg_trigger(def.default_keys).is_some(), "{}", def.id);+ }+ // KEY_NAMES in src/core/shortcuts.ts.+ let mut keys: Vec<String> = ('A'..='Z').chain('0'..='9').map(String::from).collect();+ keys.extend((1..=24).map(|n| format!("F{n}")));+ for k in [+ "Space", "Enter", "Tab", "Backspace", "Delete", "Insert", "Home", "End", "PageUp",+ "PageDown", "Up", "Down", "Left", "Right", "Comma", "Period", "Slash", "Semicolon",+ "Quote", "Backquote", "BracketLeft", "BracketRight", "Backslash", "Minus", "Equal",+ ] {+ keys.push(k.to_string());+ }+ for key in keys {+ let trigger = xdg_trigger(&format!("Ctrl+Alt+{key}"));+ assert!(trigger.as_deref().is_some_and(|t| t.starts_with("CTRL+ALT+")), "{key}: {trigger:?}");+ }+ }++ #[test]+ fn request_and_session_paths_follow_the_portal_rule() {+ assert_eq!(+ request_path(":1.42", "coucou7_1"),+ "/org/freedesktop/portal/desktop/request/1_42/coucou7_1"+ );+ assert_eq!(+ session_path(":1.42", "coucou7_2"),+ "/org/freedesktop/portal/desktop/session/1_42/coucou7_2"+ );+ }++ /// The Response signal as it comes off the bus.+ fn response(code: u32, results: PropMap) -> Message {+ let msg = Message::new_signal("/org/freedesktop/portal/desktop/request/1_42/t", REQUEST, "Response")+ .unwrap()+ .append2(code, results);+ wire(msg)+ }++ /// Through the wire format and back, so the reader sees what libdbus+ /// hands over for a message from the bus.+ fn wire(mut msg: Message) -> Message {+ msg.set_serial(1);+ let mut bytes = Vec::new();+ msg.marshal(|b| -> Result<(), ()> {+ bytes.extend_from_slice(b);+ Ok(())+ })+ .unwrap();+ Message::demarshal(&bytes).unwrap()+ }++ fn shortcut(id: &str, trigger: Option<&str>) -> (String, PropMap) {+ let mut props = PropMap::new();+ props.insert("description".into(), Variant(Box::new(format!("{id} description"))));+ if let Some(t) = trigger {+ props.insert("trigger_description".into(), Variant(Box::new(t.to_string())));+ }+ (id.to_string(), props)+ }++ #[test]+ fn a_bind_response_lists_the_shortcuts_and_their_keys() {+ let list = vec![+ shortcut("openChat", Some("Ctrl+Alt+Space")),+ shortcut("goToAlert", Some(" ")),+ shortcut("muteToggle", None),+ ];+ let mut results = PropMap::new();+ results.insert("shortcuts".into(), Variant(Box::new(list)));+ let msg = response(0, results);+ let results = parse_response(&msg).expect("a success");+ let parsed = parse_shortcuts(&*results["shortcuts"].0).expect("a list");+ assert_eq!(+ parsed,+ vec![+ Bound { id: "openChat".into(), trigger: Some("Ctrl+Alt+Space".into()) },+ Bound { id: "goToAlert".into(), trigger: None },+ Bound { id: "muteToggle".into(), trigger: None },+ ]+ );+ }++ #[test]+ fn a_refused_or_failed_response_carries_its_code() {+ assert_eq!(parse_response(&response(1, PropMap::new())).unwrap_err(), 1);+ assert_eq!(parse_response(&response(2, PropMap::new())).unwrap_err(), 2);+ // Not a Response at all.+ let other = Message::new_signal("/x", REQUEST, "Response").unwrap().append1("nope");+ assert_eq!(parse_response(&other).unwrap_err(), 2);+ }++ #[test]+ fn the_session_handle_is_read_as_a_string_or_an_object_path() {+ let path = "/org/freedesktop/portal/desktop/session/1_42/s";+ let mut as_string = PropMap::new();+ as_string.insert("session_handle".into(), Variant(Box::new(path.to_string())));+ let mut as_path = PropMap::new();+ as_path.insert("session_handle".into(), Variant(Box::new(Path::new(path).unwrap())));+ for results in [as_string, as_path] {+ let msg = response(0, results);+ let results = parse_response(&msg).unwrap();+ assert_eq!(session_from_results(&results).as_deref(), Some(path));+ }+ assert_eq!(session_from_results(&PropMap::new()), None);+ }++ #[test]+ fn shortcuts_changed_reads_the_same_list() {+ let list = vec![shortcut("nextPill", Some("Meta+N"))];+ let msg = Message::new_signal(OBJECT, IFACE, "ShortcutsChanged")+ .unwrap()+ .append2(Path::new("/s").unwrap(), list);+ let msg = wire(msg);+ let mut args = msg.iter_init();+ let _: Path = args.read().unwrap();+ let parsed = parse_shortcuts(&*args.get_refarg().unwrap()).unwrap();+ assert_eq!(parsed, vec![Bound { id: "nextPill".into(), trigger: Some("Meta+N".into()) }]);+ // Not a list: nothing.+ assert_eq!(parse_shortcuts(&"text".to_string()), None);+ }++ // ── The whole exchange, against a stand-in portal ─────────────────────────+ //+ // Needs a session bus of its own, so it doesn't run by default:+ // dbus-run-session -- cargo test -p coucou --lib portal -- --ignored++ /// Plays org.freedesktop.portal.Desktop: answers every request at once,+ /// reports each shortcut's keys as "Fake <preferred trigger>", presses+ /// the first one, and refuses a list holding "refuseMe".+ /// Stops (and gives the name back) once `stop` is set.+ fn fake_portal(ready: mpsc::Sender<()>, stop: std::sync::Arc<std::sync::atomic::AtomicBool>) {+ let ch = Channel::get_private(BusType::Session).unwrap();+ let name = Message::new_method_call("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "RequestName")+ .unwrap()+ .append2(DEST, 4u32);+ let owner: u32 = ch.send_with_reply_and_block(name, CALL_TIMEOUT).unwrap().read1().unwrap();+ assert_eq!(owner, 1, "the stand-in must own {DEST} on this bus");+ ready.send(()).unwrap();+ let respond = |to: &str, request: &str, code: u32, results: PropMap| {+ let mut signal = Message::new_signal(request, REQUEST, "Response").unwrap().append2(code, results);+ signal.set_destination(Some(to.into()));+ ch.send(signal).unwrap();+ };+ while !stop.load(std::sync::atomic::Ordering::Relaxed) {+ let Ok(Some(msg)) = ch.blocking_pop_message(Duration::from_millis(50)) else { continue };+ if msg.msg_type() != MessageType::MethodCall {+ continue;+ }+ let sender = msg.sender().unwrap().to_string();+ let iface = msg.interface().map(|i| i.to_string()).unwrap_or_default();+ match (iface.as_str(), &*msg.member().unwrap()) {+ ("org.freedesktop.DBus.Properties", "Get") => {+ ch.send(msg.method_return().append1(Variant(1u32))).unwrap();+ }+ (IFACE, "CreateSession") => {+ let options: PropMap = msg.read1().unwrap();+ let request = request_path(&sender, options["handle_token"].0.as_str().unwrap());+ let session = session_path(&sender, options["session_handle_token"].0.as_str().unwrap());+ ch.send(msg.method_return().append1(Path::new(request.clone()).unwrap())).unwrap();+ let mut results = PropMap::new();+ results.insert("session_handle".into(), Variant(Box::new(session)));+ respond(&sender, &request, 0, results);+ }+ (IFACE, "BindShortcuts") => {+ let mut args = msg.iter_init();+ let session: Path = args.read().unwrap();+ let list: Vec<(String, PropMap)> = args.read().unwrap();+ let _parent: String = args.read().unwrap();+ let options: PropMap = args.read().unwrap();+ let request = request_path(&sender, options["handle_token"].0.as_str().unwrap());+ ch.send(msg.method_return().append1(Path::new(request.clone()).unwrap())).unwrap();+ if list.iter().any(|(id, _)| id == "refuseMe") {+ respond(&sender, &request, 1, PropMap::new());+ continue;+ }+ let bound: Vec<(String, PropMap)> = list+ .iter()+ .map(|(id, props)| {+ let wanted = props.get("preferred_trigger").and_then(|t| t.0.as_str()).unwrap_or("?");+ let mut out = PropMap::new();+ out.insert("description".into(), Variant(Box::new(props["description"].0.as_str().unwrap().to_string())));+ out.insert("trigger_description".into(), Variant(Box::new(format!("Fake {wanted}"))));+ (id.clone(), out)+ })+ .collect();+ let mut results = PropMap::new();+ results.insert("shortcuts".into(), Variant(Box::new(bound)));+ respond(&sender, &request, 0, results);+ // A press, broadcast as the portal does.+ let press = Message::new_signal(OBJECT, IFACE, "Activated")+ .unwrap()+ .append3(session.into_static(), list[0].0.clone(), 0u64)+ .append1(PropMap::new());+ ch.send(press).unwrap();+ }+ _ => {+ ch.send(msg.method_return()).unwrap();+ }+ }+ }+ }++ #[test]+ #[ignore = "needs its own session bus: dbus-run-session -- cargo test -p coucou --lib portal -- --ignored"]+ fn the_whole_exchange_with_a_stand_in_portal() {+ let recv = |rx: &mpsc::Receiver<Event>| rx.recv_timeout(Duration::from_secs(15)).expect("an event");++ let (ready_tx, ready_rx) = mpsc::channel();+ let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));+ let fake = {+ let stop = stop.clone();+ std::thread::spawn(move || fake_portal(ready_tx, stop))+ };+ ready_rx.recv_timeout(Duration::from_secs(15)).unwrap();++ let (tx, rx) = mpsc::channel();+ let handle = start(move |e| drop(tx.send(e))).unwrap();+ let want = |ids: &[(&str, &str)]| -> Vec<Wanted> {+ ids.iter()+ .map(|(id, keys)| Wanted { id: id.to_string(), description: format!("{id}!"), trigger: xdg_trigger(keys) })+ .collect()+ };+ let bound = |ids: &[(&str, &str)]| -> Option<Vec<Bound>> {+ Some(ids.iter().map(|(id, t)| Bound { id: id.to_string(), trigger: Some(t.to_string()) }).collect())+ };++ let first = want(&[("openChat", "Ctrl+Alt+Space"), ("goToAlert", "Ctrl+Alt+A")]);+ assert!(handle.bind(1, first.clone()));+ let answer = bound(&[("openChat", "Fake CTRL+ALT+space"), ("goToAlert", "Fake CTRL+ALT+a")]);+ assert_eq!(recv(&rx), Event::Bound { gen: 1, shortcuts: answer.clone() });+ assert_eq!(recv(&rx), Event::Activated("openChat".into()));++ // The same shortcuts again: answered at once, the desktop isn't asked.+ assert!(handle.bind(2, first));+ assert_eq!(recv(&rx), Event::Bound { gen: 2, shortcuts: answer });++ // Other shortcuts: a new session.+ assert!(handle.bind(3, want(&[("muteToggle", "Super+M")])));+ assert_eq!(recv(&rx), Event::Bound { gen: 3, shortcuts: bound(&[("muteToggle", "Fake LOGO+m")]) });+ assert_eq!(recv(&rx), Event::Activated("muteToggle".into()));++ // Refused in the desktop's dialog.+ assert!(handle.bind(4, want(&[("refuseMe", "Ctrl+Alt+R")])));+ assert!(matches!(recv(&rx), Event::Failed { gen: 4, .. }));++ // Released, then bound again from nothing.+ assert!(handle.release());+ assert!(handle.bind(5, want(&[("nextPill", "Ctrl+Alt+Right")])));+ assert_eq!(recv(&rx), Event::Bound { gen: 5, shortcuts: bound(&[("nextPill", "Fake CTRL+ALT+Right")]) });+ assert_eq!(recv(&rx), Event::Activated("nextPill".into()));+ assert!(rx.recv_timeout(Duration::from_millis(200)).is_err(), "nothing more");++ // No GlobalShortcuts portal on the bus (none at all, or one without+ // that interface): Unavailable, and the thread is gone.+ stop.store(true, std::sync::atomic::Ordering::Relaxed);+ fake.join().unwrap();+ let (tx, rx) = mpsc::channel();+ let handle = start(move |e| drop(tx.send(e))).unwrap();+ assert!(matches!(recv(&rx), Event::Unavailable(_)));+ let gone = (0..100).any(|_| {+ std::thread::sleep(Duration::from_millis(10));+ !handle.release()+ });+ assert!(gone, "the thread should stop when there is no portal");+ }+}diff --git a/windows/src-tauri/src/shortcuts.rs b/windows/src-tauri/src/shortcuts.rsindex a47c7c4e..a8b0998f 100644--- a/windows/src-tauri/src/shortcuts.rs+++ b/windows/src-tauri/src/shortcuts.rs@@ -1,7 +1,10 @@// 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+// (RegisterHotKey on Windows, XGrabKey on X11). Wayland has no key grabs: there+// they go to the desktop through the XDG GlobalShortcuts portal (portal.rs), and+// where there is no such portal Settings lists `coucou --shortcut <id>` commands+// to bind by hand. 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.@@ -72,6 +75,27 @@ pub fn find(id: &str) -> Option<&'static ActionDef> {ACTIONS.iter().find(|a| a.id == id)}+/// What an action does, in English: the key of its label in Settings+/// (SHORTCUT_TEXT in src/core/shortcuts.ts; tests/shortcuts.test.mjs keeps+/// the two in step). The portal shows it in the desktop's own settings.+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]+pub fn description(id: &str) -> &'static str {+ use crate::i18n::n_;+ match id {+ "toggleIsland" => n_("Open or close the island"),+ "openChat" => n_("Open the chat"),+ "goToAlert" => n_("Go to the waiting permission or question"),+ "jumpToTerminal" => n_("Open the terminal"),+ "attachFrontWindow" => n_("Attach the front window to the chat"),+ "nextPill" => n_("Next pill"),+ "prevPill" => n_("Previous pill"),+ "muteToggle" => n_("Mute or unmute Mochi"),+ "desktopToggle" => n_("Send Mochi to the desktop"),+ "wardrobeToggle" => n_("Open the wardrobe"),+ _ => "Coucou",+ }+}+/// 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)]@@ -119,6 +143,25 @@ pub enum Status {Unsupported,/// The action itself isn't in this version.NotPorted,+ /// Wayland: handed to the desktop, which hasn't answered yet (it may be+ /// showing its own dialog).+ #[cfg_attr(not(target_os = "linux"), allow(dead_code))]+ Pending,+ /// Wayland: the desktop took the others but left this one out.+ #[cfg_attr(not(target_os = "linux"), allow(dead_code))]+ Refused,+}++/// Wayland: where the GlobalShortcuts portal stands. Absent from the report+/// wherever it isn't used (X11, Windows, or no portal).+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase")]+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]+pub enum PortalState {+ /// Asked; the desktop may be showing its own dialog.+ Pending,+ /// The desktop holds the shortcuts and says when one is pressed.+ Active,}#[derive(Debug, Clone, Serialize)]@@ -129,6 +172,10 @@ pub struct ActionStatus {/// The character a `TypesCharacter` combination types.#[serde(skip_serializing_if = "Option::is_none")]pub typed: Option<String>,+ /// Wayland: the keys the desktop says run it, in its own words. It may+ /// let the user pick other keys than the ones Coucou asked for.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub trigger: Option<String>,}#[derive(Debug, Clone, Serialize)]@@ -140,6 +187,8 @@ pub struct Report {/// The command a desktop's own shortcut settings can run instead:/// `<this executable> --shortcut <action id>`.pub command: String,+ /// Wayland: the shortcuts went to the desktop through its portal.+ pub portal: Option<PortalState>,}/// What is registered right now: hot-key id → action id, plus the last report.@@ -147,6 +196,9 @@ pub struct Report {pub struct Registry {by_id: Mutex<HashMap<u32, &'static str>>,report: Mutex<Vec<ActionStatus>>,+ portal: Mutex<Option<PortalState>>,+ #[cfg(target_os = "linux")]+ wayland: Mutex<wayland::Link>,}// ── Pure helpers ──────────────────────────────────────────────────────────────@@ -217,7 +269,7 @@ pub fn plan(ACTIONS.iter().map(|def| {- let refuse = |status, typed| Err(ActionStatus { id: def.id, status, typed });+ let refuse = |status, typed| Err(ActionStatus { id: def.id, status, typed, trigger: None });let binding = effective(def, stored);let outcome = if !def.ported {refuse(Status::NotPorted, None)@@ -295,15 +347,23 @@ fn release<R: Runtime>(app: &AppHandle<R>) {pub fn apply<R: Runtime>(app: &AppHandle<R>, stored: &Bindings) {release(app);let blocked = crate::platform::global_shortcuts_blocked();+ let plan = plan(stored, typed_character);+ // Wayland: to the desktop's portal when there is one. Without one, as+ // below: every shortcut unsupported, and Settings shows the commands to+ // bind by hand.+ #[cfg(target_os = "linux")]+ if blocked == Some("wayland") && wayland::bind(app, stored, &plan) {+ return;+ }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) {+ for (def, outcome) in plan {let status = match outcome {Err(status) => status,Ok(_) if blocked.is_some() || gs.is_none() => {- ActionStatus { id: def.id, status: Status::Unsupported, typed: None }+ ActionStatus { id: def.id, status: Status::Unsupported, typed: None, trigger: None }}Ok(shortcut) => {// No lock of ours is held here: the plugin calls our handler@@ -320,7 +380,7 @@ pub fn apply<R: Runtime>(app: &AppHandle<R>, stored: &Bindings) {}None => Status::Unsupported,};- ActionStatus { id: def.id, status, typed: None }+ ActionStatus { id: def.id, status, typed: None, trigger: None }}};report.push(status);@@ -329,6 +389,7 @@ pub fn apply<R: Runtime>(app: &AppHandle<R>, stored: &Bindings) {if let Some(registry) = app.try_state::<Registry>() {*registry.by_id.lock().unwrap() = by_id;*registry.report.lock().unwrap() = report;+ *registry.portal.lock().unwrap() = None;}let _ = app.emit("shortcuts-status", status(app));}@@ -338,17 +399,19 @@ pub fn apply<R: Runtime>(app: &AppHandle<R>, stored: &Bindings) {/// running it.pub fn suspend<R: Runtime>(app: &AppHandle<R>) {release(app);+ #[cfg(target_os = "linux")]+ wayland::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();+ let registry = app.try_state::<Registry>();+ let actions = registry.as_ref().map(|r| r.report.lock().unwrap().clone()).unwrap_or_default();+ let portal = registry.as_ref().and_then(|r| *r.portal.lock().unwrap());Report {actions,blocked: crate::platform::global_shortcuts_blocked().map(str::to_string),command: format!("{} --shortcut", launch_command()),+ portal,}}@@ -375,6 +438,251 @@ fn typed_character(shortcut: &Shortcut) -> Option<String> {crate::platform::ctrl_alt_types(vk, shortcut.mods.contains(Modifiers::SHIFT))}+// ── Wayland: the GlobalShortcuts portal ───────────────────────────────────────++/// Glue between `apply` and the portal thread (portal.rs). Each `bind` gets a+/// new generation; an answer to an older one is dropped, so a slow desktop+/// dialog can't overwrite what the latest settings asked for.+#[cfg(target_os = "linux")]+mod wayland {+ use super::*;+ use crate::portal::{self, Bound, Event, Wanted};++ /// The portal thread, once started.+ #[derive(Default)]+ pub enum Link {+ #[default]+ NotStarted,+ Running { handle: portal::Handle, gen: u64 },+ /// No portal (or no session bus): today's commands instead, for the+ /// rest of the run.+ Gone,+ }++ /// Hands the planned shortcuts to the desktop. False when there is no+ /// portal to hand them to; `apply` then carries on as before.+ pub fn bind<R: Runtime>(+ app: &AppHandle<R>,+ stored: &Bindings,+ plan: &[(&'static ActionDef, Result<Shortcut, ActionStatus>)],+ ) -> bool {+ let Some(registry) = app.try_state::<Registry>() else { return false };+ // Held until the request is sent, so the thread's answer (on_event+ // takes this lock too) always lands after the Pending report below.+ let mut link = registry.wayland.lock().unwrap();+ if matches!(*link, Link::Gone) {+ return false;+ }+ let wanted: Vec<Wanted> = plan+ .iter()+ .filter(|(_, outcome)| outcome.is_ok())+ .map(|(def, _)| Wanted {+ id: def.id.to_string(),+ description: crate::i18n::t(description(def.id)),+ trigger: portal::xdg_trigger(&effective(def, stored).keys),+ })+ .collect();+ *registry.report.lock().unwrap() = plan+ .iter()+ .map(|(def, outcome)| match outcome {+ Err(status) => status.clone(),+ Ok(_) => ActionStatus { id: def.id, status: Status::Pending, typed: None, trigger: None },+ })+ .collect();+ *registry.portal.lock().unwrap() = Some(PortalState::Pending);++ if matches!(*link, Link::NotStarted) {+ let events = app.clone();+ *link = match portal::start(move |event| on_event(&events, event)) {+ Some(handle) => Link::Running { handle, gen: 0 },+ None => Link::Gone,+ };+ }+ let Link::Running { handle, gen } = &mut *link else { return false };+ *gen += 1;+ if !handle.bind(*gen, wanted) {+ *link = Link::Gone;+ return false;+ }+ drop(link);+ let _ = app.emit("shortcuts-status", status(app));+ true+ }++ /// Gives the shortcuts back to the desktop while Settings records a new+ /// one; the next `apply` binds them again.+ pub fn release<R: Runtime>(app: &AppHandle<R>) {+ let Some(registry) = app.try_state::<Registry>() else { return };+ let mut link = registry.wayland.lock().unwrap();+ if let Link::Running { handle, gen } = &mut *link {+ *gen += 1;+ handle.release();+ }+ }++ /// What the portal thread says. Runs on that thread.+ fn on_event<R: Runtime>(app: &AppHandle<R>, event: Event) {+ let Some(registry) = app.try_state::<Registry>() else { return };+ if let Event::Activated(id) = &event {+ if let Some(def) = find(id).filter(|d| d.ported) {+ dispatch(app, def.id);+ }+ return;+ }+ let mut link = registry.wayland.lock().unwrap();+ let current = match &*link {+ Link::Running { gen, .. } => *gen,+ _ => 0,+ };+ {+ let mut report = registry.report.lock().unwrap();+ let mut portal = registry.portal.lock().unwrap();+ match event {+ Event::Bound { gen, shortcuts } if gen == current => {+ crate::log::line("shortcuts: registered with the desktop portal");+ mark_bound(&mut report, shortcuts.as_deref());+ *portal = Some(PortalState::Active);+ }+ Event::Changed { gen, shortcuts } if gen == current => mark_changed(&mut report, &shortcuts),+ Event::Failed { gen, reason } if gen == current => {+ crate::log::line(format!("shortcuts: the desktop portal didn't take them: {reason}"));+ mark_failed(&mut report);+ *portal = None;+ }+ Event::Unavailable(reason) => {+ crate::log::line(format!("shortcuts: no portal, commands instead ({reason})"));+ *link = Link::Gone;+ mark_failed(&mut report);+ *portal = None;+ }+ _ => return,+ }+ }+ drop(link);+ let _ = app.emit("shortcuts-status", status(app));+ }++ fn handed_over(status: Status) -> bool {+ matches!(status, Status::Pending | Status::Active | Status::Refused)+ }++ /// The desktop answered: each shortcut it lists is active, with its keys;+ /// one it left out is refused. `None`: it didn't list them, so all are.+ pub fn mark_bound(report: &mut [ActionStatus], shortcuts: Option<&[Bound]>) {+ for st in report.iter_mut().filter(|st| handed_over(st.status)) {+ let bound = match shortcuts {+ None => Some(None),+ Some(list) => list.iter().find(|b| b.id == st.id).map(|b| b.trigger.clone()),+ };+ match bound {+ Some(trigger) => {+ st.status = Status::Active;+ st.trigger = trigger;+ }+ None => {+ st.status = Status::Refused;+ st.trigger = None;+ }+ }+ }+ }++ /// The user gave some shortcuts other keys in the desktop's settings.+ pub fn mark_changed(report: &mut [ActionStatus], shortcuts: &[Bound]) {+ for st in report.iter_mut().filter(|st| handed_over(st.status)) {+ if let Some(b) = shortcuts.iter().find(|b| b.id == st.id) {+ st.status = Status::Active;+ st.trigger = b.trigger.clone();+ }+ }+ }++ /// No portal after all: what a Wayland session showed before it.+ pub fn mark_failed(report: &mut [ActionStatus]) {+ for st in report.iter_mut().filter(|st| handed_over(st.status)) {+ st.status = Status::Unsupported;+ st.trigger = None;+ }+ }++ #[cfg(test)]+ mod tests {+ use super::*;++ fn report() -> Vec<ActionStatus> {+ plan(&Bindings::new(), |_| None)+ .into_iter()+ .map(|(def, outcome)| match outcome {+ Err(status) => status,+ Ok(_) => ActionStatus { id: def.id, status: Status::Pending, typed: None, trigger: None },+ })+ .collect()+ }++ fn of<'a>(report: &'a [ActionStatus], id: &str) -> &'a ActionStatus {+ report.iter().find(|s| s.id == id).unwrap()+ }++ fn bound(id: &str, trigger: Option<&str>) -> Bound {+ Bound { id: id.into(), trigger: trigger.map(str::to_string) }+ }++ #[test]+ fn the_desktop_answer_marks_each_shortcut() {+ let mut r = report();+ let answer = [bound("openChat", Some("Ctrl+Alt+Space")), bound("goToAlert", None)];+ mark_bound(&mut r, Some(&answer));+ assert_eq!(of(&r, "openChat").status, Status::Active);+ assert_eq!(of(&r, "openChat").trigger.as_deref(), Some("Ctrl+Alt+Space"));+ assert_eq!(of(&r, "goToAlert").status, Status::Active);+ assert_eq!(of(&r, "goToAlert").trigger, None);+ // Left out of the answer.+ assert_eq!(of(&r, "muteToggle").status, Status::Refused);+ // Never handed over: untouched.+ assert_eq!(of(&r, "toggleIsland").status, Status::Off);+ assert_eq!(of(&r, "desktopToggle").status, Status::NotPorted);+ }++ #[test]+ fn an_answer_without_a_list_takes_them_all() {+ let mut r = report();+ mark_bound(&mut r, None);+ assert!(r.iter().all(|s| matches!(s.status, Status::Active | Status::Off | Status::NotPorted)));+ assert_eq!(of(&r, "nextPill").status, Status::Active);+ }++ #[test]+ fn new_keys_from_the_desktop_replace_the_old_ones() {+ let mut r = report();+ mark_bound(&mut r, Some(&[bound("openChat", Some("Ctrl+Alt+Space"))]));+ mark_changed(&mut r, &[bound("openChat", Some("Meta+C")), bound("muteToggle", Some("Meta+M"))]);+ assert_eq!(of(&r, "openChat").trigger.as_deref(), Some("Meta+C"));+ assert_eq!(of(&r, "muteToggle").status, Status::Active);+ assert_eq!(of(&r, "muteToggle").trigger.as_deref(), Some("Meta+M"));+ assert_eq!(of(&r, "toggleIsland").status, Status::Off);+ }++ #[test]+ fn a_failure_goes_back_to_unsupported() {+ let mut r = report();+ mark_bound(&mut r, Some(&[bound("openChat", Some("Ctrl+Alt+Space"))]));+ mark_failed(&mut r);+ for s in &r {+ assert!(matches!(s.status, Status::Unsupported | Status::Off | Status::NotPorted), "{}", s.id);+ assert_eq!(s.trigger, None);+ }+ assert_eq!(of(&r, "openChat").status, Status::Unsupported);+ }++ #[test]+ fn every_action_has_a_description() {+ for def in ACTIONS {+ assert_ne!(description(def.id), "Coucou", "{}", def.id);+ }+ }+ }+}+#[cfg(test)]mod tests {use super::*;diff --git a/windows/src/core/bridge.ts b/windows/src/core/bridge.tsindex 1bbf25fc..3dc5d145 100644--- a/windows/src/core/bridge.ts+++ b/windows/src/core/bridge.ts@@ -204,14 +204,19 @@ export const Bridge = {export type ShortcutStatus =| "active" | "off" | "inUse" | "duplicate" | "invalid"- | "typesCharacter" | "unsupported" | "notPorted";+ | "typesCharacter" | "unsupported" | "notPorted"+ /** Wayland: handed to the desktop's portal, no answer yet / left out by it. */+ | "pending" | "refused";export interface ShortcutsReport {- actions: { id: string; status: ShortcutStatus; typed?: string }[];- /** "wayland" or "no-display" when no global shortcut can be registered. */+ /** `trigger`: on Wayland, the keys the desktop says run it, in its words. */+ actions: { id: string; status: ShortcutStatus; typed?: string; trigger?: string }[];+ /** "wayland" or "no-display" when no key grab can be made. */blocked: string | null;/** `<executable> --shortcut`: append an action id for a desktop shortcut. */command: string;+ /** Wayland: the shortcuts went to the desktop's GlobalShortcuts portal. */+ portal?: "pending" | "active" | null;}/** How the desktop Mochi's window works here (platform::DesktopMode). */diff --git a/windows/src/i18n/extra.json b/windows/src/i18n/extra.jsonindex 29080991..7de4fe35 100644--- a/windows/src/i18n/extra.json+++ b/windows/src/i18n/extra.json@@ -2707,6 +2707,61 @@"ru": "Ваш рабочий стол Wayland не позволяет приложениям слушать клавиши вне своих окон. Добавьте сочетания в настройках клавиатуры системы с такими командами:","id": "Desktop Wayland Anda tidak mengizinkan aplikasi mendengarkan tombol di luar jendelanya sendiri. Tambahkan pintasan di pengaturan keyboard sistem Anda, dengan perintah berikut:"},+ "Desktop: {keys}": {+ "zh-Hans": "桌面:{keys}",+ "hi": "डेस्कटॉप: {keys}",+ "es": "Escritorio: {keys}",+ "ar": "سطح المكتب: {keys}",+ "fr": "Bureau : {keys}",+ "bn": "ডেস্কটপ: {keys}",+ "pt-BR": "Desktop: {keys}",+ "ru": "Рабочий стол: {keys}",+ "id": "Desktop: {keys}"+ },+ "Not set by your desktop": {+ "zh-Hans": "桌面未设置",+ "hi": "आपके डेस्कटॉप ने सेट नहीं किया",+ "es": "Tu escritorio no lo activó",+ "ar": "لم يضبطه سطح المكتب",+ "fr": "Non activé par ton bureau",+ "bn": "আপনার ডেস্কটপ সেট করেনি",+ "pt-BR": "Não ativado pelo seu desktop",+ "ru": "Не назначено рабочим столом",+ "id": "Tidak diatur oleh desktop Anda"+ },+ "These shortcuts are registered with your desktop. It may ask you to confirm them or to pick other keys; when it says which keys it uses, they show next to each shortcut.": {+ "zh-Hans": "这些快捷键已在你的桌面注册。桌面可能会请你确认,或选择其他按键;如果它告知所用的按键,会显示在每个快捷键旁边。",+ "hi": "ये शॉर्टकट आपके डेस्कटॉप के साथ पंजीकृत हैं। वह आपसे इनकी पुष्टि करने या दूसरी कुंजियाँ चुनने को कह सकता है; जब वह बताता है कि कौन-सी कुंजियाँ इस्तेमाल होती हैं, तो वे हर शॉर्टकट के आगे दिखती हैं।",+ "es": "Estos atajos están registrados en tu escritorio. Puede pedirte que los confirmes o que elijas otras teclas; cuando indica qué teclas usa, aparecen junto a cada atajo.",+ "ar": "هذه الاختصارات مسجّلة لدى سطح المكتب. قد يطلب منك تأكيدها أو اختيار مفاتيح أخرى؛ وعندما يذكر المفاتيح التي يستخدمها، تظهر بجانب كل اختصار.",+ "fr": "Ces raccourcis sont enregistrés auprès de ton bureau. Il peut te demander de les confirmer ou de choisir d'autres touches ; quand il indique les touches qu'il utilise, elles s'affichent à côté de chaque raccourci.",+ "bn": "এই শর্টকাটগুলো আপনার ডেস্কটপে নিবন্ধিত। এটি আপনাকে সেগুলো নিশ্চিত করতে বা অন্য কী বেছে নিতে বলতে পারে; কোন কী ব্যবহার করছে তা জানালে সেগুলো প্রতিটি শর্টকাটের পাশে দেখা যায়।",+ "pt-BR": "Estes atalhos estão registrados no seu desktop. Ele pode pedir que você os confirme ou escolha outras teclas; quando informa quais teclas usa, elas aparecem ao lado de cada atalho.",+ "ru": "Эти сочетания зарегистрированы в вашем рабочем столе. Он может попросить подтвердить их или выбрать другие клавиши; если он сообщает, какие клавиши использует, они показаны рядом с каждым сочетанием.",+ "id": "Pintasan ini terdaftar di desktop Anda. Desktop mungkin meminta Anda mengonfirmasinya atau memilih tombol lain; jika desktop menyebutkan tombol yang dipakainya, tombol itu tampil di samping setiap pintasan."+ },+ "Asking your desktop to register the shortcuts. It may show its own window to confirm them.": {+ "zh-Hans": "正在请求桌面注册这些快捷键。桌面可能会显示自己的窗口让你确认。",+ "hi": "आपके डेस्कटॉप से शॉर्टकट पंजीकृत करने को कहा जा रहा है। पुष्टि के लिए वह अपनी विंडो दिखा सकता है।",+ "es": "Pidiendo a tu escritorio que registre los atajos. Puede mostrar su propia ventana para confirmarlos.",+ "ar": "جارٍ طلب تسجيل الاختصارات من سطح المكتب. قد يعرض نافذته الخاصة لتأكيدها.",+ "fr": "Demande en cours à ton bureau pour enregistrer les raccourcis. Il peut afficher sa propre fenêtre pour les confirmer.",+ "bn": "আপনার ডেস্কটপকে শর্টকাটগুলো নিবন্ধন করতে বলা হচ্ছে। নিশ্চিত করার জন্য এটি নিজের উইন্ডো দেখাতে পারে।",+ "pt-BR": "Pedindo ao seu desktop para registrar os atalhos. Ele pode mostrar a própria janela para confirmá-los.",+ "ru": "Запрашиваем регистрацию сочетаний у рабочего стола. Он может показать своё окно для подтверждения.",+ "id": "Meminta desktop Anda mendaftarkan pintasan. Desktop mungkin menampilkan jendelanya sendiri untuk konfirmasi."+ },+ "If one doesn't work, you can also add it in your system's keyboard settings with these commands:": {+ "zh-Hans": "如果某个快捷键不起作用,也可以使用以下命令在系统的键盘设置中添加:",+ "hi": "अगर कोई काम न करे, तो आप इन कमांड के साथ उसे अपने सिस्टम की कीबोर्ड सेटिंग्स में भी जोड़ सकते हैं:",+ "es": "Si alguno no funciona, también puedes añadirlo en la configuración de teclado del sistema con estos comandos:",+ "ar": "إذا لم يعمل أحدها، يمكنك أيضًا إضافته من إعدادات لوحة المفاتيح في نظامك بهذه الأوامر:",+ "fr": "Si l'un d'eux ne marche pas, tu peux aussi l'ajouter dans les réglages clavier de ton système, avec ces commandes :",+ "bn": "কোনোটি কাজ না করলে, এই কমান্ডগুলো দিয়ে সিস্টেমের কিবোর্ড সেটিংসেও সেটি যোগ করতে পারেন:",+ "pt-BR": "Se algum não funcionar, você também pode adicioná-lo nas configurações de teclado do sistema, com estes comandos:",+ "ru": "Если какое-то не работает, его можно добавить и в настройках клавиатуры системы с такими командами:",+ "id": "Jika salah satunya tidak berfungsi, Anda juga bisa menambahkannya di pengaturan keyboard sistem dengan perintah berikut:"+ },"all green": {"zh-Hans": "全部通过","hi": "सब हरा",diff --git a/windows/src/settings/main.ts b/windows/src/settings/main.tsindex 8571126a..871355b7 100644--- a/windows/src/settings/main.ts+++ b/windows/src/settings/main.ts@@ -975,6 +975,17 @@ const SHORTCUTS_UI = {return t("Your Wayland desktop doesn't let apps listen for keys outside their own windows. Add the shortcuts in your system's keyboard settings instead, with these commands:");},get noDisplay() { return t("No display server was found, so global shortcuts are off."); },+ get portalPending() {+ return t("Asking your desktop to register the shortcuts. It may show its own window to confirm them.");+ },+ get portalActive() {+ return t("These shortcuts are registered with your desktop. It may ask you to confirm them or to pick other keys; when it says which keys it uses, they show next to each shortcut.");+ },+ get portalFallback() {+ return t("If one doesn't work, you can also add it in your system's keyboard settings with these commands:");+ },+ desktopKeys: (keys: string) => t("Desktop: {keys}", { keys }),+ get refused() { return t("Not set by your desktop"); },};function shortcutsSection(initial: ShortcutsReport | null): HTMLElement {@@ -999,6 +1010,9 @@ function shortcutsSection(initial: ShortcutsReport | null): HTMLElement {case "invalid": return h("span", { class: "tag err", text: SHORTCUTS_UI.invalid });case "typesCharacter": return h("span", { class: "tag warn", text: SHORTCUTS_UI.types(st.typed ?? "?") });case "unsupported": return h("span", { class: "tag", text: SHORTCUTS_UI.unavailable });+ case "refused": return h("span", { class: "tag warn", text: SHORTCUTS_UI.refused });+ // Wayland: the desktop may run it on other keys than the ones asked for.+ case "active": return st.trigger ? h("span", { class: "tag", text: SHORTCUTS_UI.desktopKeys(st.trigger) }) : null;default: return null;}}@@ -1081,12 +1095,27 @@ function shortcutsSection(initial: ShortcutsReport | null): HTMLElement {}clear(blockedNote);- if (report?.blocked === "wayland") {- const commands = h("div", { class: "diff" });+ const commands = (command: string) => {+ const list = h("div", { class: "diff" });for (const d of SHORTCUTS) {- if (d.ported) commands.append(h("div", { class: "ctx", text: `${report.command} ${d.id}` }));+ if (d.ported) list.append(h("div", { class: "ctx", text: `${command} ${d.id}` }));}- blockedNote.append(h("div", { class: "notice warn", text: SHORTCUTS_UI.wayland }), commands);+ return list;+ };+ if (report?.portal) {+ // Wayland, through the desktop's GlobalShortcuts portal; the commands+ // stay as a way around a shortcut the desktop didn't take.+ const active = report.portal === "active";+ blockedNote.append(+ h("div", {+ class: active ? "notice ok" : "notice",+ text: active ? SHORTCUTS_UI.portalActive : SHORTCUTS_UI.portalPending,+ }),+ h("div", { class: "hint", text: SHORTCUTS_UI.portalFallback }),+ commands(report.command),+ );+ } else if (report?.blocked === "wayland") {+ blockedNote.append(h("div", { class: "notice warn", text: SHORTCUTS_UI.wayland }), commands(report.command));} else if (report?.blocked) {blockedNote.append(h("div", { class: "notice warn", text: SHORTCUTS_UI.noDisplay }));}diff --git a/windows/tests/shortcuts.test.mjs b/windows/tests/shortcuts.test.mjsindex e76e5348..bae882f3 100644--- a/windows/tests/shortcuts.test.mjs+++ b/windows/tests/shortcuts.test.mjs@@ -64,6 +64,14 @@ test("the defaults are the same on both sides of the bridge", () => {);});+test("the descriptions the Wayland portal shows are the labels Settings shows", () => {+ const rust = readFileSync(new URL("../src-tauri/src/shortcuts.rs", import.meta.url), "utf8");+ const rows = Object.fromEntries(+ [...rust.matchAll(/^\s*"(\w+)" => n_\("([^"]+)"\),/gm)].map(([, id, text]) => [id, text]),+ );+ assert.deepEqual(rows, Object.fromEntries(SHORTCUTS.map((d) => [d.id, SHORTCUT_TEXT[d.id]])));+});+// testEnabledByDefaulttest("only the island toggle is off by default; the two not ported yet are reserved", () => {for (const d of SHORTCUTS) {