Files
Moorly/src/hotkeys.rs
T
Squid abbca0e411
Moorly CI / windows-build (push) Successful in 3m54s
Moorly CI / linux-build (push) Successful in 4m12s
Added tray function for windows and linux(kde/gnome). Global shortcut to show/hide program windows
2026-11-08 20:37:19 +01:00

890 lines
28 KiB
Rust

//! 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> {
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<String>,
},
/// 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<String>,
}
#[derive(Clone)]
struct Shared {
events: broadcast::Sender<Event>,
statuses: Arc<Mutex<HashMap<Action, Status>>>,
revision: Arc<AtomicU64>,
}
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<Event> {
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<Mutex<Native>>,
#[cfg(target_os = "linux")]
portal: Option<PortalHandle>,
}
static SERVICE: OnceLock<Service> = OnceLock::new();
/// Starts the service once. Later calls only return the selected backend.
pub fn start(bindings: Vec<Binding>) -> 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<Binding>) {
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<Event> {
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")]
pub(crate) 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<String> {
let mut parts = trigger
.split('+')
.map(str::trim)
.filter(|part| !part.is_empty())
.collect::<Vec<_>>();
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<Action, HotKey>,
ids: Arc<RwLock<HashMap<u32, Action>>>,
stop: Arc<AtomicBool>,
thread: Option<std::thread::JoinHandle<()>>,
}
// 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<Self, String> {
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::<HotKey>() {
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<PortalCommand>,
done: Mutex<std::sync::mpsc::Receiver<()>>,
}
#[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<Binding>) -> Option<PortalHandle> {
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<Binding>,
mut commands: tokio::sync::mpsc::UnboundedReceiver<PortalCommand>,
) {
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<PortalCommand>,
) -> 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<GlobalShortcuts> = 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::<Vec<_>>();
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::<HashMap<_, _>>();
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::<HashMap<_, _>>();
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);
}
}