diff --git a/Cargo.lock b/Cargo.lock index 038e1a2..78ba7c5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -156,6 +156,20 @@ dependencies = [ "libloading", ] +[[package]] +name = "ashpd" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ba377f1fb1e3972907220f1f8e7c0a45164580905c981d872c1fb90d921cbcc" +dependencies = [ + "bitflags 2.13.2", + "futures-util", + "getrandom 0.4.3", + "serde", + "tokio", + "zbus 6.2.1", +] + [[package]] name = "async-broadcast" version = "0.7.2" @@ -818,6 +832,15 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "crossbeam-channel" +version = "0.5.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "crossbeam-utils" version = "0.8.23" @@ -1543,6 +1566,23 @@ version = "0.25.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "151665d9be52f9bb40fc7966565d39666f2d1e69233571b71b87791c7e0528b3" +[[package]] +name = "global-hotkey" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adda8c76a5139df3bae0eb0413c2cd746f66594e0bb66231a4daa0be3172da70" +dependencies = [ + "crossbeam-channel", + "keyboard-types", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "once_cell", + "thiserror 2.0.21", + "windows-sys 0.59.0", + "x11rb", + "xkeysym", +] + [[package]] name = "gloo-timers" version = "0.4.0" @@ -2127,6 +2167,16 @@ dependencies = [ "rand_core", ] +[[package]] +name = "keyboard-types" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fbe853b403ae61a04233030ae8a79d94975281ed9770a1f9e246732b534b28d" +dependencies = [ + "bitflags 2.13.2", + "serde", +] + [[package]] name = "khronos-egl" version = "6.0.0" @@ -2399,6 +2449,8 @@ dependencies = [ name = "moorly" version = "0.1.0" dependencies = [ + "ashpd", + "global-hotkey", "iced", "iced_aw", "nix", @@ -2435,7 +2487,7 @@ dependencies = [ "wasm-bindgen-futures", "web-sys", "windows 0.62.2", - "zbus", + "zbus 5.19.0", ] [[package]] @@ -5420,11 +5472,39 @@ dependencies = [ "uuid", "windows-sys 0.61.2", "winnow 1.0.4", - "zbus_macros", + "zbus_macros 5.19.0", "zbus_names", "zvariant", ] +[[package]] +name = "zbus" +version = "6.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ddb2961d9587ef9f24ad14cde1c3bc4c5edc9f1525932a8cffdd5bd98886eb9" +dependencies = [ + "async-trait", + "bitflags 2.13.2", + "endi", + "futures-core", + "hex", + "libc", + "ordered-stream", + "rustix 1.1.6", + "serde", + "serde_repr", + "socket2", + "tokio", + "uds_windows", + "uuid", + "windows-sys 0.61.2", + "winnow 1.0.4", + "zbus_macros 6.2.1", + "zbus_utils", + "zcheapstr", + "zruntime", +] + [[package]] name = "zbus_macros" version = "5.19.0" @@ -5440,6 +5520,18 @@ dependencies = [ "zvariant_utils", ] +[[package]] +name = "zbus_macros" +version = "6.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "083b38add47c340fc12ec560124fb1d9c23acb584f7021099f85ec6587a03c54" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "zbus_utils", +] + [[package]] name = "zbus_names" version = "4.3.5" @@ -5451,6 +5543,19 @@ dependencies = [ "zvariant", ] +[[package]] +name = "zbus_utils" +version = "6.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af55e52da295311b368c45bcae221f020e28e97a2420360170ce389218e76ec7" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "syn 3.0.9", + "winnow 1.0.4", +] + [[package]] name = "zcheapstr" version = "1.1.0" @@ -5498,6 +5603,16 @@ version = "0.6.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" +[[package]] +name = "zruntime" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23ef5ed7d628cdf0af82f93dfe03330a8e37383bf7422a1d3d6eb72326680be5" +dependencies = [ + "futures-core", + "futures-io", +] + [[package]] name = "zvariant" version = "5.15.1" diff --git a/Cargo.toml b/Cargo.toml index 4151098..a4af3ff 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,6 +18,12 @@ vt100 = "0.18.1" [target.'cfg(unix)'.dependencies] nix = { version = "0.31.3", features = ["term", "process", "signal", "fs"] } +[target.'cfg(any(target_os = "linux", target_os = "windows"))'.dependencies] +global-hotkey = "0.9.0" + +[target.'cfg(target_os = "linux")'.dependencies] +ashpd = { version = "0.14.0", features = ["global_shortcuts"] } + [target.'cfg(windows)'.dependencies] windows-sys = { version = "0.61.2", features = [ "Win32_Foundation", diff --git a/assets/dev.moorly.Moorly.desktop b/assets/dev.moorly.Moorly.desktop new file mode 100644 index 0000000..84ec2f6 --- /dev/null +++ b/assets/dev.moorly.Moorly.desktop @@ -0,0 +1,10 @@ +[Desktop Entry] +Type=Application +Name=Moorly +Comment=SSH and terminal client +Exec=moorly +Icon=utilities-terminal +Terminal=false +Categories=Network;Utility;TerminalEmulator; +StartupNotify=true +StartupWMClass=Moorly diff --git a/src/hotkeys.rs b/src/hotkeys.rs new file mode 100644 index 0000000..aa31848 --- /dev/null +++ b/src/hotkeys.rs @@ -0,0 +1,889 @@ +//! System-wide keyboard shortcuts. +//! +//! `global-hotkey` covers Windows and Linux X11. Linux Wayland uses the +//! XDG GlobalShortcuts portal through `ashpd`; it never grabs input directly. + +use std::collections::HashMap; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, OnceLock, RwLock}; + +use iced::Subscription; +use iced::futures::StreamExt; +use iced::futures::stream::{self, BoxStream}; +use tokio::sync::broadcast; + +#[cfg(any(target_os = "linux", target_os = "windows"))] +use global_hotkey::hotkey::HotKey; +#[cfg(any(target_os = "linux", target_os = "windows"))] +use global_hotkey::{GlobalHotKeyEvent, GlobalHotKeyManager, HotKeyState}; + +/// Stable desktop identity used when registering with the portal. +#[cfg(target_os = "linux")] +pub const APP_ID: &str = "dev.moorly.Moorly"; + +/// Actions exposed as global shortcuts. The IDs are persisted by desktop +/// environments, so they must not change. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Action { + ToggleWindowVisibility, + OpenCommandPalette, +} + +impl Action { + pub const ALL: [Self; 2] = [Self::ToggleWindowVisibility, Self::OpenCommandPalette]; + + pub fn id(self) -> &'static str { + match self { + Self::ToggleWindowVisibility => "toggle_window_visibility", + Self::OpenCommandPalette => "open_command_palette", + } + } + + pub fn description(self) -> &'static str { + match self { + Self::ToggleWindowVisibility => "Show or hide Moorly", + Self::OpenCommandPalette => "Open the Moorly command palette", + } + } + + #[cfg(target_os = "linux")] + pub fn default_trigger(self) -> &'static str { + match self { + Self::ToggleWindowVisibility => "Ctrl+Space", + Self::OpenCommandPalette => "Ctrl+Shift+Space", + } + } + + #[cfg(target_os = "linux")] + pub fn from_id(id: &str) -> Option { + Self::ALL.into_iter().find(|action| action.id() == id) + } +} + +/// The backend selected for the current session. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Backend { + /// Native implementation from `global-hotkey` (Windows / X11). + Native, + /// XDG GlobalShortcuts portal (Wayland). + Portal, + /// No safe implementation is available in this session. + Unsupported, +} + +/// Result of trying to register one action. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Status { + Registered, + Disabled, + Unavailable(String), +} + +/// Events delivered to the Iced application loop. +#[derive(Debug, Clone)] +pub enum Event { + Activated(Action), + Status { + action: Action, + status: Status, + }, + /// The portal reports a new trigger description after the user changed a + /// shortcut in the desktop environment. + #[allow(dead_code)] // Only constructed by the Linux portal backend. + ShortcutChanged { + action: Action, + trigger: Option, + }, + /// The selected backend could not be used at all. + BackendUnavailable(String), +} + +/// One action and the preferred trigger configured by Moorly. +#[derive(Debug, Clone)] +pub struct Binding { + pub action: Action, + pub trigger: Option, +} + +#[derive(Clone)] +struct Shared { + events: broadcast::Sender, + statuses: Arc>>, + revision: Arc, +} + +impl Shared { + fn send(&self, event: Event) { + let _ = self.events.send(event); + } + + fn set_status(&self, action: Action, status: Status) { + let changed = { + let mut statuses = self.statuses.lock().unwrap(); + + if statuses.get(&action) == Some(&status) { + false + } else { + statuses.insert(action, status.clone()); + true + } + }; + + if changed { + self.revision.fetch_add(1, Ordering::SeqCst); + self.send(Event::Status { action, status }); + } + } + + fn backend_unavailable(&self, reason: String) { + { + let mut statuses = self.statuses.lock().unwrap(); + + for action in Action::ALL { + statuses.insert(action, Status::Unavailable(reason.clone())); + } + } + + self.revision.fetch_add(1, Ordering::SeqCst); + self.send(Event::BackendUnavailable(reason)); + } + + fn status_events(&self) -> Vec { + let statuses = self.statuses.lock().unwrap(); + + Action::ALL + .into_iter() + .filter_map(|action| { + statuses.get(&action).map(|status| Event::Status { + action, + status: status.clone(), + }) + }) + .collect() + } +} + +struct Service { + backend: Backend, + shared: Shared, + #[cfg(any(target_os = "linux", target_os = "windows"))] + native: Option>, + #[cfg(target_os = "linux")] + portal: Option, +} + +static SERVICE: OnceLock = OnceLock::new(); + +/// Starts the service once. Later calls only return the selected backend. +pub fn start(bindings: Vec) -> Backend { + if let Some(service) = SERVICE.get() { + return service.backend; + } + + let (events, _) = broadcast::channel(64); + let shared = Shared { + events, + statuses: Arc::new(Mutex::new(HashMap::new())), + revision: Arc::new(AtomicU64::new(0)), + }; + + let mut backend = detect_backend(); + + #[cfg(any(target_os = "linux", target_os = "windows"))] + let mut native = None; + #[cfg(target_os = "linux")] + let mut portal = None; + + match backend { + Backend::Native => { + #[cfg(any(target_os = "linux", target_os = "windows"))] + match Native::new(shared.clone()) { + Ok(mut manager) => { + manager.apply(&shared, &bindings); + native = Some(Mutex::new(manager)); + } + Err(reason) => { + shared.backend_unavailable(reason); + backend = Backend::Unsupported; + } + } + + #[cfg(not(any(target_os = "linux", target_os = "windows")))] + { + shared.backend_unavailable( + "Native global shortcuts are not available on this platform.".to_owned(), + ); + backend = Backend::Unsupported; + } + } + Backend::Portal => { + #[cfg(target_os = "linux")] + { + // Preferred triggers are only suggestions to the portal; the + // desktop environment owns the persisted binding. Use the + // documented defaults instead of Moorly's local settings so + // restarting never rewrites a user's portal configuration. + let bindings = bindings + .into_iter() + .map(|binding| Binding { + action: binding.action, + trigger: binding + .trigger + .map(|_| binding.action.default_trigger().to_owned()), + }) + .collect(); + + match start_portal(shared.clone(), bindings) { + Some(handle) => portal = Some(handle), + None => { + shared.backend_unavailable( + "Could not start the XDG GlobalShortcuts portal worker.".to_owned(), + ); + backend = Backend::Unsupported; + } + } + } + + #[cfg(not(target_os = "linux"))] + { + shared.backend_unavailable( + "The XDG GlobalShortcuts portal is only available on Linux.".to_owned(), + ); + backend = Backend::Unsupported; + } + } + Backend::Unsupported => { + shared.backend_unavailable(unsupported_reason()); + } + } + + let service = Service { + backend, + shared, + #[cfg(any(target_os = "linux", target_os = "windows"))] + native, + #[cfg(target_os = "linux")] + portal, + }; + + let _ = SERVICE.set(service); + backend +} + +pub fn backend() -> Backend { + SERVICE + .get() + .map(|service| service.backend) + .unwrap_or(Backend::Unsupported) +} + +/// Changes whenever a registration status changes. Used as subscription data +/// so Iced re-evaluates dependent subscriptions. +pub fn revision() -> u64 { + SERVICE + .get() + .map(|service| service.shared.revision.load(Ordering::SeqCst)) + .unwrap_or(0) +} + +pub fn is_registered(action: Action) -> bool { + SERVICE + .get() + .and_then(|service| service.shared.statuses.lock().ok()?.get(&action).cloned()) + .is_some_and(|status| status == Status::Registered) +} + +/// Applies new triggers to a Moorly-managed backend. Portal shortcuts are +/// managed by the desktop environment and are intentionally left untouched. +pub fn set_bindings(bindings: Vec) { + let Some(service) = SERVICE.get() else { + return; + }; + + #[cfg(any(target_os = "linux", target_os = "windows"))] + if let Some(native) = &service.native + && let Ok(mut manager) = native.lock() + { + manager.apply(&service.shared, &bindings); + } + + #[cfg(target_os = "linux")] + let _ = (&service.portal, bindings); + #[cfg(not(target_os = "linux"))] + let _ = (service, bindings); +} + +/// Releases registrations before the process exits. +pub fn shutdown() { + let Some(service) = SERVICE.get() else { + return; + }; + + #[cfg(any(target_os = "linux", target_os = "windows"))] + if let Some(native) = &service.native + && let Ok(mut manager) = native.lock() + { + manager.shutdown(); + } + + #[cfg(target_os = "linux")] + if let Some(portal) = &service.portal { + portal.shutdown(); + } +} + +pub fn subscription() -> Subscription { + Subscription::run(event_stream) +} + +fn event_stream() -> BoxStream<'static, Event> { + let Some(service) = SERVICE.get() else { + return stream::pending().boxed(); + }; + + // Subscribe before taking the snapshot so no status can fall between the + // two. Duplicates are harmless and the app deduplicates notifications. + let receiver = service.shared.events.subscribe(); + let snapshot = service.shared.status_events(); + + stream::iter(snapshot) + .chain(stream::unfold(receiver, |mut receiver| async move { + loop { + match receiver.recv().await { + Ok(event) => return Some((event, receiver)), + Err(broadcast::error::RecvError::Lagged(_)) => continue, + Err(broadcast::error::RecvError::Closed) => return None, + } + } + })) + .boxed() +} + +fn detect_backend() -> Backend { + #[cfg(target_os = "windows")] + { + Backend::Native + } + + #[cfg(target_os = "linux")] + { + if is_wayland_session() { + Backend::Portal + } else if std::env::var_os("DISPLAY").is_some() { + Backend::Native + } else { + Backend::Unsupported + } + } + + #[cfg(not(any(target_os = "linux", target_os = "windows")))] + { + Backend::Unsupported + } +} + +#[cfg(target_os = "linux")] +fn is_wayland_session() -> bool { + std::env::var_os("WAYLAND_DISPLAY").is_some() + || std::env::var("XDG_SESSION_TYPE") + .is_ok_and(|session| session.eq_ignore_ascii_case("wayland")) +} + +fn unsupported_reason() -> String { + #[cfg(target_os = "linux")] + { + "No display server was detected. Global shortcuts are unavailable.".to_owned() + } + + #[cfg(not(target_os = "linux"))] + { + "Global shortcuts are not supported on this platform.".to_owned() + } +} + +/// Makes the application discoverable by the portal on systems where Moorly +/// was not installed through a package manager. Existing entries are never +/// overwritten. +#[cfg(target_os = "linux")] +fn ensure_desktop_entry() { + let Some(data_dir) = std::env::var_os("XDG_DATA_HOME") + .map(std::path::PathBuf::from) + .or_else(|| { + std::env::var_os("HOME").map(|home| std::path::PathBuf::from(home).join(".local/share")) + }) + else { + return; + }; + + let applications = data_dir.join("applications"); + let path = applications.join(format!("{APP_ID}.desktop")); + + if let Ok(existing) = std::fs::read_to_string(&path) + && !existing.contains("X-Moorly-Generated=true") + { + // A packaged entry (or the user's own entry) is authoritative. + return; + } + + let Ok(executable) = std::env::current_exe() else { + return; + }; + let executable = executable.display().to_string(); + let executable = executable.replace('\\', "\\\\").replace('"', "\\\""); + let entry = format!( + "[Desktop Entry]\n\ + Type=Application\n\ + Name=Moorly\n\ + Comment=SSH and terminal client\n\ + Exec=\"{executable}\"\n\ + Icon=utilities-terminal\n\ + Terminal=false\n\ + Categories=Network;Utility;TerminalEmulator;\n\ + StartupNotify=true\n\ + StartupWMClass=Moorly\n\ + X-Moorly-Generated=true\n" + ); + + if std::fs::create_dir_all(&applications).is_ok() { + let _ = std::fs::write(path, entry); + } +} + +/// XKB keysym name used by the XDG shortcuts specification. +#[cfg(target_os = "linux")] +fn portal_trigger(trigger: &str) -> Option { + let mut parts = trigger + .split('+') + .map(str::trim) + .filter(|part| !part.is_empty()) + .collect::>(); + let key = parts.pop()?; + + let key = match key.to_ascii_lowercase().as_str() { + "space" => "space".to_owned(), + "enter" | "return" => "Return".to_owned(), + "escape" | "esc" => "Escape".to_owned(), + "tab" => "Tab".to_owned(), + "," => "comma".to_owned(), + "." => "period".to_owned(), + ";" => "semicolon".to_owned(), + "'" => "apostrophe".to_owned(), + "/" => "slash".to_owned(), + "\\" => "backslash".to_owned(), + "[" => "bracketleft".to_owned(), + "]" => "bracketright".to_owned(), + "-" => "minus".to_owned(), + "=" => "equal".to_owned(), + "`" => "grave".to_owned(), + key if key.chars().count() == 1 && key.chars().all(|c| c.is_ascii_alphanumeric()) => { + key.to_ascii_lowercase() + } + _ => return None, + }; + + let mut output = Vec::new(); + for modifier in parts { + output.push(match modifier.to_ascii_lowercase().as_str() { + "ctrl" | "control" => "CTRL".to_owned(), + "shift" => "SHIFT".to_owned(), + "alt" => "ALT".to_owned(), + "super" | "meta" | "win" => "LOGO".to_owned(), + _ => return None, + }); + } + output.push(key); + Some(output.join("+")) +} + +#[cfg(any(target_os = "linux", target_os = "windows"))] +struct Native { + manager: GlobalHotKeyManager, + registered: HashMap, + ids: Arc>>, + stop: Arc, + thread: Option>, +} + +// The manager is only accessed through the Mutex above. Windows requires the +// manager to be created on the same thread as the Win32 event loop (Iced's +// main thread), but registration is safe to call through its window handle. +#[cfg(any(target_os = "linux", target_os = "windows"))] +unsafe impl Send for Native {} +#[cfg(any(target_os = "linux", target_os = "windows"))] +unsafe impl Sync for Native {} + +#[cfg(any(target_os = "linux", target_os = "windows"))] +impl Native { + fn new(shared: Shared) -> Result { + let manager = GlobalHotKeyManager::new() + .map_err(|error| format!("Could not start global hotkeys: {error}"))?; + let ids = Arc::new(RwLock::new(HashMap::new())); + let stop = Arc::new(AtomicBool::new(false)); + let receiver = GlobalHotKeyEvent::receiver().clone(); + let event_ids = ids.clone(); + let events = shared.events.clone(); + let thread_stop = stop.clone(); + + let thread = std::thread::Builder::new() + .name("moorly-global-hotkeys".to_owned()) + .spawn(move || { + while !thread_stop.load(Ordering::Relaxed) { + let Ok(event) = receiver.recv_timeout(std::time::Duration::from_millis(250)) + else { + continue; + }; + + if event.state != HotKeyState::Pressed { + continue; + } + + let action = event_ids + .read() + .ok() + .and_then(|ids| ids.get(&event.id).copied()); + + if let Some(action) = action { + let _ = events.send(Event::Activated(action)); + } + } + }) + .map_err(|error| format!("Could not start the global hotkey listener: {error}"))?; + + Ok(Self { + manager, + registered: HashMap::new(), + ids, + stop, + thread: Some(thread), + }) + } + + fn apply(&mut self, shared: &Shared, bindings: &[Binding]) { + for (_, hotkey) in self.registered.drain() { + let _ = self.manager.unregister(hotkey); + } + + if let Ok(mut ids) = self.ids.write() { + ids.clear(); + } + + for binding in bindings { + let Some(trigger) = binding + .trigger + .as_deref() + .filter(|trigger| !trigger.is_empty()) + else { + shared.set_status(binding.action, Status::Disabled); + continue; + }; + + let hotkey = match trigger.parse::() { + Ok(hotkey) => hotkey, + Err(error) => { + shared.set_status( + binding.action, + Status::Unavailable(format!("\"{trigger}\" is not supported: {error}")), + ); + continue; + } + }; + + match self.manager.register(hotkey) { + Ok(()) => { + if let Ok(mut ids) = self.ids.write() { + ids.insert(hotkey.id(), binding.action); + } + self.registered.insert(binding.action, hotkey); + shared.set_status(binding.action, Status::Registered); + } + Err(error) => { + shared.set_status( + binding.action, + Status::Unavailable(format!( + "\"{trigger}\" could not be registered: {error}" + )), + ); + } + } + } + } + + fn shutdown(&mut self) { + self.stop.store(true, Ordering::Relaxed); + + for (_, hotkey) in self.registered.drain() { + let _ = self.manager.unregister(hotkey); + } + + if let Ok(mut ids) = self.ids.write() { + ids.clear(); + } + + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + } +} + +#[cfg(target_os = "linux")] +enum PortalCommand { + Shutdown, +} + +#[cfg(target_os = "linux")] +struct PortalHandle { + commands: tokio::sync::mpsc::UnboundedSender, + done: Mutex>, +} + +#[cfg(target_os = "linux")] +impl PortalHandle { + fn shutdown(&self) { + // Wait briefly for the session to close. Never block the GUI for long: + // the worker may be waiting on a portal confirmation dialog. + let _ = self.commands.send(PortalCommand::Shutdown); + + if let Ok(done) = self.done.lock() { + let _ = done.recv_timeout(std::time::Duration::from_millis(500)); + } + } +} + +#[cfg(target_os = "linux")] +fn start_portal(shared: Shared, bindings: Vec) -> Option { + let (commands, receiver) = tokio::sync::mpsc::unbounded_channel(); + let (done, done_receiver) = std::sync::mpsc::channel(); + std::thread::Builder::new() + .name("moorly-portal-shortcuts".to_owned()) + .spawn(move || { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build(); + + match runtime { + Ok(runtime) => { + runtime.block_on(portal_main(shared, bindings, receiver)); + } + Err(error) => { + shared.backend_unavailable(format!( + "Could not start the portal shortcut worker: {error}" + )); + } + } + + let _ = done.send(()); + }) + .ok()?; + + Some(PortalHandle { + commands, + done: Mutex::new(done_receiver), + }) +} + +#[cfg(target_os = "linux")] +async fn portal_main( + shared: Shared, + bindings: Vec, + mut commands: tokio::sync::mpsc::UnboundedReceiver, +) { + if let Err(reason) = run_portal(&shared, &bindings, &mut commands).await { + shared.backend_unavailable(reason); + } +} + +#[cfg(target_os = "linux")] +async fn run_portal( + shared: &Shared, + bindings: &[Binding], + commands: &mut tokio::sync::mpsc::UnboundedReceiver, +) -> Result<(), String> { + use ashpd::desktop::Session; + use ashpd::desktop::global_shortcuts::{GlobalShortcuts, NewShortcut}; + + let connection = ashpd::zbus::Connection::session() + .await + .map_err(|error| format!("Could not connect to the session bus: {error}"))?; + + if let Ok(app_id) = ashpd::AppID::try_from(APP_ID) { + // Host (non-Flatpak) applications need this so the portal can attach + // permissions to a stable application ID. It must use the same + // connection as the portal calls, because the registry maps the + // caller's bus connection to the app ID. + if !ashpd::is_sandboxed() { + ensure_desktop_entry(); + } + // Older portal versions may not implement the registry. The portal's + // fallback identity still works, but cannot be pinned to our app ID. + let _ = ashpd::register_host_app_with_connection(connection.clone(), app_id).await; + } + + let proxy = GlobalShortcuts::with_connection(connection) + .await + .map_err(|error| format!("XDG GlobalShortcuts portal is unavailable: {error}"))?; + let session: Session = proxy + .create_session(Default::default()) + .await + .map_err(|error| format!("Could not create a global shortcuts session: {error}"))?; + + let mut activated = Box::pin( + proxy + .receive_activated() + .await + .map_err(|error| format!("Could not listen for shortcut activations: {error}"))?, + ); + let mut changed = Box::pin( + proxy + .receive_shortcuts_changed() + .await + .map_err(|error| format!("Could not listen for desktop shortcut changes: {error}"))?, + ); + + let requested = bindings + .iter() + .filter_map(|binding| { + let trigger = binding.trigger.as_deref()?; + let trigger = portal_trigger(trigger)?; + + Some( + NewShortcut::new(binding.action.id(), binding.action.description()) + .preferred_trigger(Some(trigger.as_str())), + ) + }) + .collect::>(); + + if requested.is_empty() { + for binding in bindings { + shared.set_status(binding.action, Status::Disabled); + } + } else { + let request = proxy + .bind_shortcuts(&session, &requested, None, Default::default()) + .await + .map_err(|error| { + format!("The desktop environment rejected global shortcuts: {error}") + })?; + let response = request.response().map_err(|error| { + format!("The desktop environment rejected global shortcuts: {error}") + })?; + let granted = response + .shortcuts() + .iter() + .map(|shortcut| (shortcut.id(), shortcut)) + .collect::>(); + + for binding in bindings { + if binding.trigger.is_none() { + shared.set_status(binding.action, Status::Disabled); + continue; + } + + match granted.get(binding.action.id()) { + Some(shortcut) => { + shared.set_status(binding.action, Status::Registered); + shared.send(Event::ShortcutChanged { + action: binding.action, + trigger: Some(shortcut.trigger_description().to_owned()), + }); + } + None => shared.set_status( + binding.action, + Status::Unavailable( + "The desktop environment did not grant this shortcut.".to_owned(), + ), + ), + } + } + } + + loop { + tokio::select! { + Some(event) = activated.next() => { + if let Some(action) = Action::from_id(event.shortcut_id()) { + shared.send(Event::Activated(action)); + } + } + Some(event) = changed.next() => { + apply_portal_changes(shared, bindings, event.shortcuts()); + } + Some(command) = commands.recv() => { + if matches!(command, PortalCommand::Shutdown) { + let _ = session.close().await; + return Ok(()); + } + } + else => return Ok(()), + } + } +} + +#[cfg(target_os = "linux")] +fn apply_portal_changes( + shared: &Shared, + bindings: &[Binding], + shortcuts: &[ashpd::desktop::global_shortcuts::Shortcut], +) { + let changed = shortcuts + .iter() + .map(|shortcut| (shortcut.id(), shortcut)) + .collect::>(); + + for binding in bindings { + if binding.trigger.is_none() { + shared.set_status(binding.action, Status::Disabled); + continue; + } + + match changed.get(binding.action.id()) { + Some(shortcut) => { + shared.set_status(binding.action, Status::Registered); + shared.send(Event::ShortcutChanged { + action: binding.action, + trigger: Some(shortcut.trigger_description().to_owned()), + }); + } + None => shared.set_status( + binding.action, + Status::Unavailable("The shortcut was removed in the desktop settings.".to_owned()), + ), + } + } +} + +#[cfg(test)] +mod tests { + use super::{Action, portal_trigger}; + + #[test] + fn action_ids_and_defaults_are_stable() { + assert_eq!( + Action::ToggleWindowVisibility.id(), + "toggle_window_visibility" + ); + assert_eq!(Action::OpenCommandPalette.id(), "open_command_palette"); + assert_eq!( + Action::ToggleWindowVisibility.default_trigger(), + "Ctrl+Space" + ); + assert_eq!( + Action::OpenCommandPalette.default_trigger(), + "Ctrl+Shift+Space" + ); + assert_eq!( + Action::from_id("open_command_palette"), + Some(Action::OpenCommandPalette) + ); + assert_eq!(Action::from_id("unknown"), None); + } + + #[test] + fn portal_triggers_use_xkb_names() { + assert_eq!(portal_trigger("Ctrl+Space").as_deref(), Some("CTRL+space")); + assert_eq!( + portal_trigger("Ctrl+Shift+Space").as_deref(), + Some("CTRL+SHIFT+space") + ); + assert_eq!(portal_trigger("Alt+,").as_deref(), Some("ALT+comma")); + assert_eq!(portal_trigger("Ctrl+NotAKey"), None); + } +} diff --git a/src/main.rs b/src/main.rs index c0a6bbf..52f3d08 100644 --- a/src/main.rs +++ b/src/main.rs @@ -17,6 +17,8 @@ use iced::{ Size, Subscription, Task, Vector, font, keyboard, mouse, window, }; +#[cfg_attr(test, allow(dead_code))] +mod hotkeys; mod notifications; #[allow(dead_code)] mod terminal; @@ -118,6 +120,9 @@ fn boot() -> (Moorly, Task) { .map(|_| Message::Ignore), ]); + #[cfg(not(test))] + hotkeys::start(global_hotkey_bindings(&state)); + (state, Task::batch([task.map(|_| Message::Ignore), fonts])) } @@ -317,11 +322,13 @@ fn subscription(state: &Moorly) -> Subscription { state.saved_shortcuts.command_palette.clone(), state.shortcut_capture.is_some(), state.command_palette_enabled, + hotkeys::revision(), )) .filter_map( - |((shortcut, capturing, enabled), (key, modifiers, window))| { + |((shortcut, capturing, enabled, _), (key, modifiers, window))| { (enabled && !capturing + && !hotkeys::is_registered(hotkeys::Action::OpenCommandPalette) && shortcut .as_ref() .is_some_and(|shortcut| shortcut.matches(&key, modifiers))) @@ -360,6 +367,7 @@ fn subscription(state: &Moorly) -> Subscription { palette_shortcut, terminal_keys, terminal_text, + hotkeys::subscription().map(Message::Hotkey), iced::time::every(Duration::from_secs(1)).map(|_| Message::ReloadThemes), window::events().map(|(window, event)| Message::WindowEvent(window, event)), iced::event::listen_with(pointer_event), @@ -515,6 +523,7 @@ impl std::fmt::Display for Shortcut { enum ShortcutAction { Settings, Quit, + ToggleWindow, CommandPalette, QuickTerminal, QuickSsh, @@ -525,6 +534,7 @@ impl ShortcutAction { match self { Self::Settings => "Settings", Self::Quit => "Quit", + Self::ToggleWindow => "Show/hide window", Self::CommandPalette => "Command palette", Self::QuickTerminal => "Quick terminal", Self::QuickSsh => "Quick SSH", @@ -536,6 +546,7 @@ impl ShortcutAction { struct Shortcuts { settings: Option, quit: Option, + toggle_window: Option, command_palette: Option, quick_terminal: Option, quick_ssh: Option, @@ -546,6 +557,7 @@ impl Default for Shortcuts { Self { settings: Shortcut::parse("Ctrl+,"), quit: Shortcut::parse("Ctrl+Shift+Q"), + toggle_window: Shortcut::parse("Ctrl+Space"), command_palette: Shortcut::parse("Ctrl+Shift+Space"), quick_terminal: Shortcut::parse("Ctrl+Shift+T"), quick_ssh: Shortcut::parse("Ctrl+Shift+S"), @@ -558,6 +570,7 @@ impl Shortcuts { match action { ShortcutAction::Settings => self.settings.as_ref(), ShortcutAction::Quit => self.quit.as_ref(), + ShortcutAction::ToggleWindow => self.toggle_window.as_ref(), ShortcutAction::CommandPalette => self.command_palette.as_ref(), ShortcutAction::QuickTerminal => self.quick_terminal.as_ref(), ShortcutAction::QuickSsh => self.quick_ssh.as_ref(), @@ -568,6 +581,7 @@ impl Shortcuts { match action { ShortcutAction::Settings => self.settings = shortcut, ShortcutAction::Quit => self.quit = shortcut, + ShortcutAction::ToggleWindow => self.toggle_window = shortcut, ShortcutAction::CommandPalette => self.command_palette = shortcut, ShortcutAction::QuickTerminal => self.quick_terminal = shortcut, ShortcutAction::QuickSsh => self.quick_ssh = shortcut, @@ -580,6 +594,7 @@ impl Shortcuts { let configurable = [ (ShortcutAction::Settings, &self.settings), (ShortcutAction::Quit, &self.quit), + (ShortcutAction::ToggleWindow, &self.toggle_window), (ShortcutAction::CommandPalette, &self.command_palette), (ShortcutAction::QuickTerminal, &self.quick_terminal), (ShortcutAction::QuickSsh, &self.quick_ssh), @@ -608,6 +623,36 @@ struct ShortcutCapture { error: Option, } +/// Global actions and their configured triggers. Disabled actions are still +/// passed so an already registered shortcut is removed. +fn global_hotkey_bindings(state: &Moorly) -> Vec { + let trigger = + |action: ShortcutAction| state.saved_shortcuts.get(action).map(ToString::to_string); + + vec![ + hotkeys::Binding { + action: hotkeys::Action::ToggleWindowVisibility, + trigger: trigger(ShortcutAction::ToggleWindow), + }, + hotkeys::Binding { + action: hotkeys::Action::OpenCommandPalette, + trigger: state + .command_palette_enabled + .then(|| trigger(ShortcutAction::CommandPalette)) + .flatten(), + }, + ] +} + +/// Re-applies the saved bindings after settings are committed. The portal +/// owns its shortcuts, so the service ignores updates on Wayland. +fn sync_global_hotkeys(state: &Moorly) { + #[cfg(not(test))] + hotkeys::set_bindings(global_hotkey_bindings(state)); + #[cfg(test)] + let _ = state; +} + #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] enum ProfileKind { @@ -1630,6 +1675,7 @@ struct Moorly { window_order: Vec, main_window: Option, focused_window: Option, + main_window_hidden: bool, drag: Option, theme: theme::Preference, saved_theme: theme::Preference, @@ -1696,6 +1742,8 @@ struct Moorly { terminal_sessions: HashMap, next_terminal_tab: u32, notifications: notifications::NotificationManager, + hotkey_notified: HashSet, + hotkey_triggers: HashMap, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] @@ -2630,6 +2678,8 @@ struct ShortcutConfig { settings: String, #[serde(default = "default_quit_shortcut")] quit: String, + #[serde(default = "default_toggle_window_shortcut")] + toggle_window: String, #[serde(default = "default_command_palette_shortcut")] command_palette: String, #[serde(default = "default_quick_terminal_shortcut")] @@ -2643,6 +2693,7 @@ impl Default for ShortcutConfig { Self { settings: default_settings_shortcut(), quit: default_quit_shortcut(), + toggle_window: default_toggle_window_shortcut(), command_palette: default_command_palette_shortcut(), quick_terminal: default_quick_terminal_shortcut(), quick_ssh: default_quick_ssh_shortcut(), @@ -2691,6 +2742,13 @@ fn default_command_palette_shortcut() -> String { .unwrap_or_default() } +fn default_toggle_window_shortcut() -> String { + Shortcuts::default() + .toggle_window + .map(|shortcut| shortcut.to_string()) + .unwrap_or_default() +} + fn default_quick_terminal_shortcut() -> String { Shortcuts::default() .quick_terminal @@ -4508,6 +4566,12 @@ fn config_file(state: &Moorly) -> ConfigFile { .as_ref() .map(ToString::to_string) .unwrap_or_default(), + toggle_window: state + .saved_shortcuts + .toggle_window + .as_ref() + .map(ToString::to_string) + .unwrap_or_default(), command_palette: state .saved_shortcuts .command_palette @@ -4551,6 +4615,7 @@ impl Default for Moorly { let shortcuts = Shortcuts { settings: Shortcut::parse(&config.shortcuts.settings), quit: Shortcut::parse(&config.shortcuts.quit), + toggle_window: Shortcut::parse(&config.shortcuts.toggle_window), command_palette: Shortcut::parse(&config.shortcuts.command_palette), quick_terminal: Shortcut::parse(&config.shortcuts.quick_terminal), quick_ssh: Shortcut::parse(&config.shortcuts.quick_ssh), @@ -4568,6 +4633,7 @@ impl Default for Moorly { window_order: Vec::new(), main_window: None, focused_window: None, + main_window_hidden: false, drag: None, theme, saved_theme: theme, @@ -4634,6 +4700,8 @@ impl Default for Moorly { terminal_sessions: HashMap::new(), next_terminal_tab: 1, notifications, + hotkey_notified: HashSet::new(), + hotkey_triggers: HashMap::new(), } } } @@ -4831,6 +4899,8 @@ enum Message { TabsScrolled(window::Id, scrollable::Viewport), ScrollTabs(window::Id, mouse::ScrollDelta), ScrollTabsBy(window::Id, f32), + Hotkey(hotkeys::Event), + FinishToggleWindowVisibility(Option), Quit, } @@ -5520,6 +5590,7 @@ fn update(state: &mut Moorly, message: Message) -> Task { Message::SaveSettings => { apply_settings(state); save_config(state); + sync_global_hotkeys(state); } Message::UndoChanges => undo_settings(state), Message::Notification(action) => match action { @@ -6141,7 +6212,12 @@ fn update(state: &mut Moorly, message: Message) -> Task { Message::ScrollTabsBy(window, amount) => { return scroll_tabs_by(state, window, amount); } + Message::Hotkey(event) => return handle_hotkey_event(state, event), + Message::FinishToggleWindowVisibility(minimized) => { + return finish_toggle_window_visibility(state, minimized); + } Message::Quit => { + hotkeys::shutdown(); // Drop PTY sessions explicitly so their child processes are // terminated before process::exit bypasses the state destructor. state.terminal_sessions.clear(); @@ -6160,6 +6236,125 @@ fn close_command_palette(state: &mut Moorly, window: window::Id) { } } +/// Main window to restore for a global action. +fn main_window_id(state: &Moorly) -> Option { + state + .main_window + .or(state.focused_window) + .or_else(|| state.window_order.first().copied()) +} + +fn show_main_window(state: &mut Moorly) -> Task { + let Some(window) = main_window_id(state) else { + return Task::none(); + }; + + state.main_window_hidden = false; + state.focused_window = Some(window); + + Task::batch([ + window::set_mode(window, window::Mode::Windowed), + window::minimize(window, false), + window::gain_focus(window), + ]) +} + +fn toggle_main_window(state: &mut Moorly) -> Task { + let Some(window) = main_window_id(state) else { + return Task::none(); + }; + + if state.main_window_hidden { + return show_main_window(state); + } + + // A minimized window is still visible as far as `Mode` is concerned, so + // ask the platform before deciding to hide it. + window::is_minimized(window).map(Message::FinishToggleWindowVisibility) +} + +fn finish_toggle_window_visibility(state: &mut Moorly, minimized: Option) -> Task { + let Some(window) = main_window_id(state) else { + return Task::none(); + }; + + if minimized == Some(true) { + return show_main_window(state); + } + + state.main_window_hidden = true; + window::set_mode(window, window::Mode::Hidden) +} + +fn open_palette_from_hotkey(state: &mut Moorly) -> Task { + let Some(window) = main_window_id(state) else { + return Task::none(); + }; + + let show = show_main_window(state); + let palette = update(state, Message::ToggleCommandPalette(window)); + + Task::batch([show, palette]) +} + +fn handle_hotkey_event(state: &mut Moorly, event: hotkeys::Event) -> Task { + use notifications::{Notification, NotificationKind}; + + match event { + hotkeys::Event::Activated(action) => match action { + hotkeys::Action::ToggleWindowVisibility => return toggle_main_window(state), + hotkeys::Action::OpenCommandPalette => return open_palette_from_hotkey(state), + }, + hotkeys::Event::Status { action, status } => { + let hotkeys::Status::Unavailable(reason) = status else { + return Task::none(); + }; + + let key = format!("status:{}:{reason}", action.id()); + + if state.hotkey_notified.insert(key) { + state.notifications.add( + Notification::new( + NotificationKind::Warning, + format!("{}: {reason}", action.description()), + ) + .title("Global shortcut unavailable") + .persistent(), + ); + } + } + hotkeys::Event::ShortcutChanged { action, trigger } => { + let Some(trigger) = trigger else { + return Task::none(); + }; + let previous = state.hotkey_triggers.insert(action, trigger.clone()); + + if previous.is_some_and(|previous| previous != trigger) { + state.notifications.add( + Notification::new( + NotificationKind::Info, + format!("{} is now {trigger}.", action.description()), + ) + .title("Shortcut updated"), + ); + } + } + hotkeys::Event::BackendUnavailable(reason) => { + let key = format!("backend:{reason}"); + + if state.hotkey_notified.insert(key) { + state.notifications.add( + Notification::new(NotificationKind::Warning, reason) + .title("Global shortcuts unavailable") + .persistent(), + ); + } + } + } + + Task::none() +} + /// Commits the captured shortcut if it is valid and unused. fn apply_shortcut(state: &mut Moorly) { let Some(capture) = state.shortcut_capture.as_ref() else { @@ -6210,6 +6405,7 @@ fn window_event(state: &mut Moorly, window: window::Id, event: window::Event) -> remove_window(state, window); if state.windows.is_empty() { + hotkeys::shutdown(); return iced::exit(); } @@ -6219,6 +6415,7 @@ fn window_event(state: &mut Moorly, window: window::Id, event: window::Event) -> remove_window(state, window); if state.windows.is_empty() { + hotkeys::shutdown(); return iced::exit(); } } @@ -7725,23 +7922,39 @@ fn shortcuts_panel(state: &Moorly) -> Element<'_, Message> { ShortcutAction::Quit, state.shortcuts.get(ShortcutAction::Quit) ), - shortcut_row( + ] + .spacing(8); + + if hotkeys::backend() == hotkeys::Backend::Native { + panel = panel.push(shortcut_row( + &state.typography.h3, + ShortcutAction::ToggleWindow, + state.shortcuts.get(ShortcutAction::ToggleWindow), + )); + } + + panel = panel + .push(shortcut_row( &state.typography.h3, ShortcutAction::CommandPalette, state.shortcuts.get(ShortcutAction::CommandPalette), - ), - shortcut_row( + )) + .push(shortcut_row( &state.typography.h3, ShortcutAction::QuickTerminal, state.shortcuts.get(ShortcutAction::QuickTerminal), - ), - shortcut_row( + )) + .push(shortcut_row( &state.typography.h3, ShortcutAction::QuickSsh, state.shortcuts.get(ShortcutAction::QuickSsh), - ), - ] - .spacing(8); + )); + + if hotkeys::backend() == hotkeys::Backend::Portal { + panel = panel.push( + text("Global shortcuts are managed by your desktop environment on Wayland.").size(12), + ); + } match &state.shortcut_capture { Some(capture) => panel = panel.push(shortcut_capture_panel(capture)), @@ -10884,6 +11097,7 @@ mod tests { window_order: vec![window], main_window: Some(window), focused_window: Some(window), + main_window_hidden: false, drag: None, theme: theme::Preference::default(), saved_theme: theme::Preference::default(), @@ -10950,6 +11164,8 @@ mod tests { terminal_sessions: Default::default(), next_terminal_tab: 1, notifications: super::notifications::NotificationManager::default(), + hotkey_notified: Default::default(), + hotkey_triggers: Default::default(), } } @@ -12252,6 +12468,33 @@ mod tests { ); } + #[test] + fn toggle_window_has_a_default_global_shortcut() { + let state = state(); + + assert_eq!( + state + .shortcuts + .toggle_window + .as_ref() + .map(ToString::to_string), + Some("Ctrl+Space".to_owned()) + ); + + let bindings = super::global_hotkey_bindings(&state); + assert_eq!(bindings.len(), 2); + assert_eq!( + bindings[0].action, + super::hotkeys::Action::ToggleWindowVisibility + ); + assert_eq!(bindings[0].trigger.as_deref(), Some("Ctrl+Space")); + assert_eq!( + bindings[1].action, + super::hotkeys::Action::OpenCommandPalette + ); + assert_eq!(bindings[1].trigger.as_deref(), Some("Ctrl+Shift+Space")); + } + #[test] fn quick_actions_have_default_shortcuts() { let state = state();