//! Hex's own GNOME custom keyboard shortcuts, for GNOME without a //! GlobalShortcuts portal (GNOME 46 and older, #781): entries in GNOME //! Settings › Keyboard › Custom Shortcuts that run `hex` commands. Hex owns //! only the entries under its own paths (`…/custom-keybindings/hex-*/`) and //! leaves every other custom shortcut alone. GNOME runs a custom shortcut on //! the key press only, so dictation toggles there. use color_eyre::eyre::Result; use crate::app_settings::{AppSettings, HotkeyBinding}; use crate::desktop::host::DesktopShortcuts; use crate::linux::gsettings::{gsettings, string_list, string_list_text, string_text}; const LIST_SCHEMA: &str = "org.gnome.settings-daemon.plugins.media-keys"; const ENTRY_SCHEMA: &str = "org.gnome.settings-daemon.plugins.media-keys.custom-keybinding"; const BASE: &str = "/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/"; /// Every entry Hex may write, by path name. const ENTRIES: [&str; 4] = [ "hex-dictation", "hex-paste-last", "hex-typed-text", "hex-annotate", ]; /// One custom shortcut: its path name, its name in GNOME Settings, the `hex` /// arguments it runs, and its GTK accelerator. #[derive(Debug, PartialEq)] struct Entry { id: &'static str, name: &'static str, arguments: &'static str, accelerator: String, } /// Whether Hex's entries should exist, or `None` while a starting listener /// hasn't said how it gets its shortcuts. They stand in for a missing /// shortcuts portal only: once the portal (or X11) binds the shortcuts, an /// entry on the same key would also run `hex dictation toggle` on every press /// and repeat, stopping the hold the portal just started (#931). pub(crate) fn wanted(requested: bool, shortcuts: Option) -> Option { match shortcuts { _ if !requested => Some(false), Some(DesktopShortcuts::Commands) => Some(true), Some(DesktopShortcuts::Portal(_) | DesktopShortcuts::Registered) => Some(false), Some(DesktopShortcuts::Unregistered) | None => None, } } /// Writes Hex's entries for `settings`' shortcuts, starting `hex`, and /// removes Hex's entries it no longer has a shortcut for. An entry already /// listed keeps its key, which the person may have changed in GNOME Settings. pub(crate) fn install(settings: &AppSettings, hex: &std::path::Path) -> Result<()> { let entries = entries(settings); let listed = string_list(&gsettings(&["get", LIST_SCHEMA, "custom-keybindings"])?); let command_path = hex.to_string_lossy(); for entry in &entries { let path = format!("{ENTRY_SCHEMA}:{BASE}{}/", entry.id); let command = format!("{} {}", shell_word(&command_path), entry.arguments); gsettings(&["set", &path, "name", &string_text(entry.name)])?; gsettings(&["set", &path, "command", &string_text(&command)])?; if !listed.contains(&format!("{BASE}{}/", entry.id)) { gsettings(&["set", &path, "binding", &string_text(&entry.accelerator)])?; } } let kept = entries.iter().map(|entry| entry.id).collect::>(); write_list(&kept) } /// Removes every entry Hex wrote. pub(crate) fn remove() -> Result<()> { write_list(&[]) } /// Lists Hex's entries `kept` (and every entry that isn't Hex's) in GNOME's /// custom shortcuts, and resets Hex's others. fn write_list(kept: &[&str]) -> Result<()> { let listed = string_list(&gsettings(&["get", LIST_SCHEMA, "custom-keybindings"])?); let ours = |path: &str| { ENTRIES .iter() .find(|id| path == format!("{BASE}{id}/")) .copied() }; for id in ENTRIES.iter().filter(|id| !kept.contains(id)) { if listed.iter().any(|path| ours(path) == Some(id)) { gsettings(&["reset-recursively", &format!("{ENTRY_SCHEMA}:{BASE}{id}/")])?; } } let mut paths = listed .iter() .filter(|path| ours(path).is_none()) .cloned() .collect::>(); paths.extend(kept.iter().map(|id| format!("{BASE}{id}/"))); let paths = paths.iter().map(String::as_str).collect::>(); gsettings(&[ "set", LIST_SCHEMA, "custom-keybindings", &string_list_text(&paths), ])?; Ok(()) } /// Hex's entries for the shortcuts `settings` records. A shortcut GNOME /// can't bind (modifiers alone, a mouse button) gets none. fn entries(settings: &AppSettings) -> Vec { let mut entries = Vec::new(); let mut add = |id, name, arguments, binding: Option<&HotkeyBinding>| { if let Some(accelerator) = binding.and_then(accelerator) { entries.push(Entry { id, name, arguments, accelerator, }); } }; add( "hex-dictation", "Hex: dictation", "dictation toggle", Some(&settings.dictation_hotkey), ); add( "hex-paste-last", "Hex: paste last dictation", "paste-last", settings.paste_last_hotkey.as_ref(), ); // Only while Labs › Transform typed text is on and its key is bound. if settings.labs.typed_text { add( "hex-typed-text", "Hex: transform typed text", "typed-text", settings.active_typed_text_hotkey(), ); } #[cfg(hex_capture)] if settings.capture.enabled { add( "hex-annotate", "Hex: annotate", "annotate toggle", Some(&settings.capture.hotkey), ); } entries } /// `binding` as a GTK accelerator (`space`), when GNOME can /// bind it. fn accelerator(binding: &HotkeyBinding) -> Option { let key = binding.key.as_ref().filter(|key| !key.is_mouse())?; let mut accelerator = String::new(); let modifiers = &binding.modifiers; for (held, name) in [ (modifiers.control.is_some(), ""), (modifiers.option.is_some(), ""), (modifiers.shift.is_some(), ""), (modifiers.command.is_some(), ""), ] { if held { accelerator.push_str(name); } } accelerator.push_str(&crate::linux::input::keysym(&key.name())?.name); Some(accelerator) } /// `word` as one argument for GNOME, which splits the command as a shell /// would. fn shell_word(word: &str) -> String { if word .chars() .all(|c| c.is_ascii_alphanumeric() || "/._-+".contains(c)) { return word.into(); } format!("'{}'", word.replace('\'', "'\\''")) } #[cfg(test)] mod tests { use super::*; use crate::app_settings::{HotkeyKey, HotkeyModifiers}; fn chord(modifiers: HotkeyModifiers, key: &str) -> HotkeyBinding { HotkeyBinding { modifiers, key: Some(HotkeyKey::named(key)), } } #[test] fn shortcuts_read_as_gtk_accelerators() { assert_eq!( accelerator(&chord(HotkeyModifiers::control(), "space")).as_deref(), Some("space") ); assert_eq!( accelerator(&chord(HotkeyModifiers::control_option(), "v")).as_deref(), Some("v") ); assert_eq!( accelerator(&chord(HotkeyModifiers::default(), "f9")).as_deref(), Some("F9") ); let modifiers_only = HotkeyBinding { modifiers: HotkeyModifiers::option(), key: None, }; assert_eq!(accelerator(&modifiers_only), None); } /// #931: the entries only stand in for a missing portal; with the portal /// bound they'd toggle on every press and repeat. #[test] fn entries_exist_only_without_the_portal() { assert_eq!(wanted(true, Some(DesktopShortcuts::Commands)), Some(true)); assert_eq!( wanted(true, Some(DesktopShortcuts::Portal(Vec::new()))), Some(false) ); assert_eq!( wanted(true, Some(DesktopShortcuts::Registered)), Some(false) ); assert_eq!(wanted(true, Some(DesktopShortcuts::Unregistered)), None); assert_eq!(wanted(true, None), None); assert_eq!(wanted(false, Some(DesktopShortcuts::Commands)), Some(false)); assert_eq!(wanted(false, None), Some(false)); } #[test] fn dictation_toggles_and_paths_quote() { let settings = AppSettings { dictation_hotkey: chord(HotkeyModifiers::control(), "space"), paste_last_hotkey: None, ..AppSettings::default() }; let entries = entries(&settings); assert_eq!(entries[0].arguments, "dictation toggle"); assert!(entries.iter().all(|entry| entry.id != "hex-paste-last")); assert_eq!( shell_word("/home/a/.local/bin/hex"), "/home/a/.local/bin/hex" ); assert_eq!(shell_word("/home/a b/hex"), "'/home/a b/hex'"); } /// Transform typed text gets a `hex typed-text` entry only while its lab /// is on and its shortcut is bound; paste-last stays as it was. #[test] fn typed_text_joins_the_commands_only_while_its_lab_is_on() { let mut settings = AppSettings { dictation_hotkey: chord(HotkeyModifiers::control(), "space"), paste_last_hotkey: Some(chord(HotkeyModifiers::control_option(), "v")), typed_text_hotkey: Some(chord(HotkeyModifiers::control_option(), "t")), ..AppSettings::default() }; let off = entries(&settings); assert!(off.iter().all(|entry| entry.id != "hex-typed-text")); assert!(off.iter().any(|entry| entry.id == "hex-paste-last")); settings.labs.typed_text = true; let on = entries(&settings); let typed = on .iter() .find(|entry| entry.id == "hex-typed-text") .expect("typed text entry"); assert_eq!(typed.arguments, "typed-text"); assert_eq!(typed.accelerator, "t"); settings.typed_text_hotkey = None; assert!( entries(&settings) .iter() .all(|entry| entry.id != "hex-typed-text") ); } }