Skip to main content

egui_pop_platform/
keys.rs

1//! Global shortcuts: the key bindings of the system scope, registered
2//! with the desktop so their command runs while the application is not
3//! focused.
4//!
5//! <div class="warning">Experimental: may change in any release
6//! (docs/stability.md).</div>
7//!
8//! A command declares one like any key, with a scope:
9//! `CommandSpec::key_with("Ctrl+Alt+P", BindOptions::system())` (`system`
10//! in keymap files). It shows in the shortcuts editor, the user rebinds
11//! it there (it stays in the system scope), and inside the window it
12//! fires as a global binding does. [`SystemKeysPlugin`] registers the
13//! live ones ([`AppHandle::system_bindings`]) with the desktop at start
14//! and after each change, and says how it went through the
15//! `SYSTEM_KEYS` service (`egui_pop_api::system_keys`), which the
16//! shortcuts editor shows: also outside the window, waiting for the
17//! desktop, refused and why, or only in the window because the desktop
18//! takes no global shortcuts.
19//!
20//! Its step (ADR 0011):
21//!
22//! - `keys.system`: a global shortcut was pressed, `{ "command", "keys",
23//!   "backend" }`. By default the command runs through the host. Veto
24//!   it while a modal task runs; replace it to bring the window up
25//!   first.
26//!
27//! Backends: [`HotKeys`] through global-hotkey (Windows, macOS, X11),
28//! [`Portal`] through the XDG GlobalShortcuts portal on Wayland (GNOME
29//! 48 and later, KDE Plasma 5.27 and later; the desktop asks the user to
30//! accept the shortcuts, and may let them pick other keys), [`detect`]
31//! choosing between them, and [`Simulated`] for tests.
32//!
33//! A global shortcut is one chord (`Ctrl+Alt+P`); a sequence
34//! (`Ctrl+K Ctrl+P`) is refused, and the editor says so. `Ctrl` is
35//! Command on macOS, as in egui-pop's other bindings.
36//!
37//! ```
38//! use egui_pop_api::App;
39//! use egui_pop_api::system_keys::{KeyStatus, SYSTEM_KEYS};
40//! use egui_pop_api::{Ctx, Plugin, PluginError};
41//! use egui_pop_model::commands::CommandSpec;
42//! use egui_pop_model::ids::{CommandId, PluginId};
43//! use egui_pop_model::keymap::BindOptions;
44//! use egui_pop_platform::keys::{Simulated, SystemKeysPlugin};
45//!
46//! struct Player;
47//!
48//! impl Plugin for Player {
49//!     fn id(&self) -> PluginId { PluginId::from_static("player") }
50//!     fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
51//!         ctx.command(
52//!             CommandSpec::new(CommandId::from_static("player.toggle"), "Play or pause", "Player")
53//!                 .key_with("Ctrl+Alt+P", BindOptions::system()),
54//!             |_| Ok(serde_json::Value::Null),
55//!         )?;
56//!         Ok(())
57//!     }
58//! }
59//!
60//! let desktop = Simulated::default();
61//! let ctx = egui::Context::default();
62//! let mut app = App::builder()
63//!     .plugin(Player)
64//!     .plugin(SystemKeysPlugin::new("org.example.Player").backend(desktop.clone()))
65//!     .build(&ctx)
66//!     .unwrap();
67//! app.logic(&ctx);
68//! let keys = app.handle().service(&SYSTEM_KEYS).unwrap();
69//! assert_eq!(keys.status("Ctrl+Alt+P"), Some(KeyStatus::Registered));
70//! desktop.press("Ctrl+Alt+P");
71//! app.logic(&ctx);
72//! assert_eq!(app.handle().history()[0].id.as_str(), "player.toggle");
73//! ```
74
75use std::cell::RefCell;
76use std::collections::BTreeMap;
77use std::rc::Rc;
78use std::sync::mpsc::{Receiver, Sender, channel};
79use std::sync::{Arc, Mutex};
80
81use egui_pop_api::hooks::On;
82use egui_pop_api::steps::StepSpec;
83use egui_pop_api::system_keys::{KeyStatus, SYSTEM_KEYS, Support, SystemKeys};
84use egui_pop_api::{AppHandle, Ctx, Plugin, PluginError};
85use egui_pop_core::lock;
86use egui_pop_model::commands::Origin;
87use egui_pop_model::ids::{CommandId, PluginId, StepId};
88use egui_pop_model::keymap::{Action, Chord};
89use serde_json::json;
90
91/// The plugin's id.
92pub const PLUGIN: PluginId = PluginId::from_static("egui_pop.system_keys");
93/// A global shortcut was pressed: `{ "command", "keys", "backend" }`.
94pub const STEP_PRESSED: StepId = StepId::from_static("keys.system");
95
96/// A shortcut to register.
97#[derive(Clone, Debug, PartialEq, Eq)]
98pub struct Shortcut {
99    /// Its keys as shown (`Ctrl+Alt+P`): its id with the desktop too.
100    pub keys: String,
101    pub chord: Chord,
102    pub command: CommandId,
103    /// What it does, for desktops that list shortcuts (the command's
104    /// title).
105    pub description: String,
106}
107
108/// Hands presses to the plugin from any thread, waking the interface.
109#[derive(Clone, Debug)]
110pub struct Presses {
111    tx: Sender<String>,
112    waker: egui::Context,
113}
114
115impl Presses {
116    /// The shortcut with these keys was pressed.
117    pub fn send(&self, keys: &str) {
118        let _ = self.tx.send(keys.into());
119        self.waker.request_repaint();
120    }
121}
122
123/// What registers global shortcuts with the desktop. It lives on the
124/// interface thread (global-hotkey's manager is tied to it on Windows
125/// and macOS); its threads write each registration's state to `status`.
126pub trait Backend: 'static {
127    /// A short name: `x11`, `windows`, `macos`, `portal`, `simulated`.
128    fn name(&self) -> String;
129    /// Starts; says whether the desktop takes global shortcuts (it may
130    /// say later, through `status`).
131    fn start(&mut self, presses: Presses, status: Arc<SystemKeys>) -> Support;
132    /// Registers exactly these (the earlier ones go), each one's state
133    /// written to `status` now or later.
134    fn register(&mut self, shortcuts: &[Shortcut]);
135    /// Takes every shortcut back.
136    fn stop(&mut self);
137}
138
139/// The backend for this session: the portal on Wayland, global-hotkey
140/// elsewhere (nothing on the web).
141pub fn detect(app_id: &str) -> Box<dyn Backend> {
142    #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))]
143    if crate::window::wayland() {
144        return Box::new(Portal::new(app_id));
145    }
146    let _ = app_id;
147    Box::new(HotKeys::default())
148}
149
150/// The key of a chord as egui names it, for the desktops' names.
151fn egui_key(chord: &Chord) -> Option<egui::Key> {
152    egui_pop_core::keys::key_of(chord).map(|(_, k)| k)
153}
154
155/// Global shortcuts through global-hotkey: Windows, macOS, X11.
156#[derive(Default)]
157pub struct HotKeys {
158    #[cfg(not(target_arch = "wasm32"))]
159    manager: Option<global_hotkey::GlobalHotKeyManager>,
160    #[cfg(not(target_arch = "wasm32"))]
161    registered: Vec<global_hotkey::hotkey::HotKey>,
162    /// Keys by hotkey id, read by the event handler.
163    #[cfg_attr(
164        target_arch = "wasm32",
165        allow(
166            dead_code,
167            reason = "no global shortcuts on the web: only the native event handler reads it"
168        )
169    )]
170    ids: Arc<Mutex<BTreeMap<u32, String>>>,
171    #[cfg_attr(
172        target_arch = "wasm32",
173        allow(
174            dead_code,
175            reason = "no global shortcuts on the web: only the native event handler reads it"
176        )
177    )]
178    status: Option<Arc<SystemKeys>>,
179}
180
181impl std::fmt::Debug for HotKeys {
182    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
183        f.debug_struct("HotKeys").finish_non_exhaustive()
184    }
185}
186
187/// global-hotkey's code for an egui key.
188#[cfg(not(target_arch = "wasm32"))]
189pub fn code_of(key: egui::Key) -> Option<global_hotkey::hotkey::Code> {
190    use egui::Key as K;
191    use global_hotkey::hotkey::Code as C;
192    let letters = [
193        (K::A, C::KeyA),
194        (K::B, C::KeyB),
195        (K::C, C::KeyC),
196        (K::D, C::KeyD),
197        (K::E, C::KeyE),
198        (K::F, C::KeyF),
199        (K::G, C::KeyG),
200        (K::H, C::KeyH),
201        (K::I, C::KeyI),
202        (K::J, C::KeyJ),
203        (K::K, C::KeyK),
204        (K::L, C::KeyL),
205        (K::M, C::KeyM),
206        (K::N, C::KeyN),
207        (K::O, C::KeyO),
208        (K::P, C::KeyP),
209        (K::Q, C::KeyQ),
210        (K::R, C::KeyR),
211        (K::S, C::KeyS),
212        (K::T, C::KeyT),
213        (K::U, C::KeyU),
214        (K::V, C::KeyV),
215        (K::W, C::KeyW),
216        (K::X, C::KeyX),
217        (K::Y, C::KeyY),
218        (K::Z, C::KeyZ),
219        (K::Num0, C::Digit0),
220        (K::Num1, C::Digit1),
221        (K::Num2, C::Digit2),
222        (K::Num3, C::Digit3),
223        (K::Num4, C::Digit4),
224        (K::Num5, C::Digit5),
225        (K::Num6, C::Digit6),
226        (K::Num7, C::Digit7),
227        (K::Num8, C::Digit8),
228        (K::Num9, C::Digit9),
229        (K::F1, C::F1),
230        (K::F2, C::F2),
231        (K::F3, C::F3),
232        (K::F4, C::F4),
233        (K::F5, C::F5),
234        (K::F6, C::F6),
235        (K::F7, C::F7),
236        (K::F8, C::F8),
237        (K::F9, C::F9),
238        (K::F10, C::F10),
239        (K::F11, C::F11),
240        (K::F12, C::F12),
241        (K::F13, C::F13),
242        (K::F14, C::F14),
243        (K::F15, C::F15),
244        (K::F16, C::F16),
245        (K::F17, C::F17),
246        (K::F18, C::F18),
247        (K::F19, C::F19),
248        (K::F20, C::F20),
249        (K::F21, C::F21),
250        (K::F22, C::F22),
251        (K::F23, C::F23),
252        (K::F24, C::F24),
253        (K::ArrowUp, C::ArrowUp),
254        (K::ArrowDown, C::ArrowDown),
255        (K::ArrowLeft, C::ArrowLeft),
256        (K::ArrowRight, C::ArrowRight),
257        (K::Home, C::Home),
258        (K::End, C::End),
259        (K::PageUp, C::PageUp),
260        (K::PageDown, C::PageDown),
261        (K::Insert, C::Insert),
262        (K::Delete, C::Delete),
263        (K::Backspace, C::Backspace),
264        (K::Enter, C::Enter),
265        (K::Escape, C::Escape),
266        (K::Tab, C::Tab),
267        (K::Space, C::Space),
268        (K::Minus, C::Minus),
269        (K::Equals, C::Equal),
270        (K::Comma, C::Comma),
271        (K::Period, C::Period),
272        (K::Slash, C::Slash),
273        (K::Backslash, C::Backslash),
274        (K::Semicolon, C::Semicolon),
275        (K::Quote, C::Quote),
276        (K::Backtick, C::Backquote),
277        (K::OpenBracket, C::BracketLeft),
278        (K::CloseBracket, C::BracketRight),
279    ];
280    letters.iter().find(|(k, _)| *k == key).map(|(_, c)| *c)
281}
282
283/// The hotkey of a chord, or why there is none.
284#[cfg(not(target_arch = "wasm32"))]
285pub fn hotkey_of(chord: &Chord) -> Result<global_hotkey::hotkey::HotKey, String> {
286    use global_hotkey::hotkey::{CMD_OR_CTRL, HotKey, Modifiers};
287    let key = egui_key(chord).ok_or_else(|| format!("`{}` is not a key", chord.key))?;
288    let code =
289        code_of(key).ok_or_else(|| format!("`{}` cannot be a global shortcut", chord.key))?;
290    let mut mods = Modifiers::empty();
291    if chord.ctrl {
292        mods |= CMD_OR_CTRL;
293    }
294    if chord.alt {
295        mods |= Modifiers::ALT;
296    }
297    if chord.shift {
298        mods |= Modifiers::SHIFT;
299    }
300    if chord.meta {
301        mods |= Modifiers::SUPER;
302    }
303    Ok(HotKey::new(Some(mods), code))
304}
305
306impl Backend for HotKeys {
307    fn name(&self) -> String {
308        if cfg!(windows) {
309            "windows"
310        } else if cfg!(target_os = "macos") {
311            "macos"
312        } else if cfg!(target_arch = "wasm32") {
313            "none"
314        } else {
315            "x11"
316        }
317        .into()
318    }
319
320    #[cfg(not(target_arch = "wasm32"))]
321    fn start(&mut self, presses: Presses, status: Arc<SystemKeys>) -> Support {
322        use global_hotkey::{GlobalHotKeyEvent, GlobalHotKeyManager, HotKeyState};
323        if cfg!(all(unix, not(target_os = "macos"))) && std::env::var_os("DISPLAY").is_none() {
324            return Support::Unavailable {
325                reason: "no X display to grab keys on".into(),
326            };
327        }
328        let manager = match GlobalHotKeyManager::new() {
329            Ok(m) => m,
330            Err(e) => {
331                return Support::Unavailable {
332                    reason: e.to_string(),
333                };
334            }
335        };
336        let ids = self.ids.clone();
337        GlobalHotKeyEvent::set_event_handler(Some(move |e: GlobalHotKeyEvent| {
338            if e.state() == HotKeyState::Pressed
339                && let Some(keys) = lock(&ids).get(&e.id()).cloned()
340            {
341                presses.send(&keys);
342            }
343        }));
344        self.manager = Some(manager);
345        self.status = Some(status);
346        Support::Available {
347            backend: self.name(),
348        }
349    }
350
351    #[cfg(target_arch = "wasm32")]
352    fn start(&mut self, _: Presses, _: Arc<SystemKeys>) -> Support {
353        Support::Unavailable {
354            reason: "no global shortcuts on the web".into(),
355        }
356    }
357
358    fn register(&mut self, shortcuts: &[Shortcut]) {
359        #[cfg(not(target_arch = "wasm32"))]
360        {
361            let (Some(manager), Some(status)) = (&self.manager, &self.status) else {
362                return;
363            };
364            let _ = manager.unregister_all(&self.registered);
365            self.registered.clear();
366            let mut ids = lock(&self.ids);
367            ids.clear();
368            for s in shortcuts {
369                let state = match hotkey_of(&s.chord) {
370                    Ok(hk) => match manager.register(hk) {
371                        Ok(()) => {
372                            ids.insert(hk.id(), s.keys.clone());
373                            self.registered.push(hk);
374                            KeyStatus::Registered
375                        }
376                        Err(e) => KeyStatus::Failed(e.to_string()),
377                    },
378                    Err(e) => KeyStatus::Failed(e),
379                };
380                status.set_status(&s.keys, state);
381            }
382        }
383        #[cfg(target_arch = "wasm32")]
384        let _ = shortcuts;
385    }
386
387    fn stop(&mut self) {
388        #[cfg(not(target_arch = "wasm32"))]
389        {
390            use global_hotkey::GlobalHotKeyEvent;
391            if let Some(m) = &self.manager {
392                let _ = m.unregister_all(&self.registered);
393            }
394            GlobalHotKeyEvent::set_event_handler(None::<fn(GlobalHotKeyEvent)>);
395            self.registered.clear();
396            self.manager = None;
397        }
398    }
399}
400
401/// The XDG shortcuts specification's trigger for a chord
402/// (`CTRL+ALT+p`), as the GlobalShortcuts portal takes it.
403pub fn xdg_trigger(chord: &Chord) -> Option<String> {
404    use egui::Key as K;
405    let key = egui_key(chord)?;
406    let name = match key {
407        K::ArrowUp => "Up".into(),
408        K::ArrowDown => "Down".into(),
409        K::ArrowLeft => "Left".into(),
410        K::ArrowRight => "Right".into(),
411        K::PageUp => "Page_Up".into(),
412        K::PageDown => "Page_Down".into(),
413        K::Backspace => "BackSpace".into(),
414        K::Enter => "Return".into(),
415        K::Space => "space".into(),
416        K::Minus => "minus".into(),
417        K::Equals => "equal".into(),
418        K::Plus => "plus".into(),
419        K::Comma => "comma".into(),
420        K::Period => "period".into(),
421        K::Slash => "slash".into(),
422        K::Backslash => "backslash".into(),
423        K::Semicolon => "semicolon".into(),
424        K::Quote => "apostrophe".into(),
425        K::Backtick => "grave".into(),
426        K::OpenBracket => "bracketleft".into(),
427        K::CloseBracket => "bracketright".into(),
428        K::Home | K::End | K::Insert | K::Delete | K::Escape | K::Tab => format!("{key:?}"),
429        k => {
430            let n = k.name();
431            if n.len() == 1 {
432                n.to_lowercase()
433            } else if n.starts_with('F') && n[1..].chars().all(|c| c.is_ascii_digit()) {
434                n.to_string()
435            } else {
436                return None;
437            }
438        }
439    };
440    let mut out = String::new();
441    for (on, m) in [
442        (chord.ctrl, "CTRL"),
443        (chord.alt, "ALT"),
444        (chord.shift, "SHIFT"),
445        (chord.meta, "LOGO"),
446    ] {
447        if on {
448            out.push_str(m);
449            out.push('+');
450        }
451    }
452    out.push_str(&name);
453    Some(out)
454}
455
456/// Global shortcuts through the XDG GlobalShortcuts portal (Wayland).
457/// Its thread holds a portal session; each registration replaces the
458/// session, and the desktop asks the user to accept the shortcuts.
459#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))]
460pub struct Portal {
461    app_id: String,
462    requests: Option<async_channel_lite::Sender<Vec<Shortcut>>>,
463}
464
465#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))]
466impl std::fmt::Debug for Portal {
467    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
468        f.debug_struct("Portal")
469            .field("app_id", &self.app_id)
470            .finish_non_exhaustive()
471    }
472}
473
474/// A channel the portal's thread waits on with its other futures: a
475/// queue and an `async_io` timer polling it (requests are rare).
476#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))]
477mod async_channel_lite {
478    use std::sync::mpsc;
479    use std::time::Duration;
480
481    pub type Sender<T> = mpsc::Sender<T>;
482
483    /// The next value, waiting asynchronously; none when the sender is
484    /// gone.
485    pub async fn recv<T>(rx: &mpsc::Receiver<T>) -> Option<T> {
486        loop {
487            match rx.try_recv() {
488                Ok(v) => return Some(v),
489                Err(mpsc::TryRecvError::Disconnected) => return None,
490                Err(mpsc::TryRecvError::Empty) => {
491                    async_io::Timer::after(Duration::from_millis(100)).await;
492                }
493            }
494        }
495    }
496}
497
498#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))]
499impl Portal {
500    /// `app_id`: the application's id (`org.example.App`), registered
501    /// with the portal for an application outside a sandbox.
502    pub fn new(app_id: &str) -> Self {
503        Self {
504            app_id: app_id.into(),
505            requests: None,
506        }
507    }
508}
509
510#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))]
511impl Backend for Portal {
512    fn name(&self) -> String {
513        "portal".into()
514    }
515
516    fn start(&mut self, presses: Presses, status: Arc<SystemKeys>) -> Support {
517        let (tx, rx) = std::sync::mpsc::channel::<Vec<Shortcut>>();
518        let app_id = self.app_id.clone();
519        let waker = presses.waker.clone();
520        let spawned = std::thread::Builder::new()
521            .name("egui-pop global shortcuts".into())
522            .spawn(move || {
523                futures_lite::future::block_on(portal_loop(&app_id, rx, presses, &status));
524                waker.request_repaint();
525            });
526        match spawned {
527            Ok(_) => {
528                self.requests = Some(tx);
529                // Said by the thread once the portal answers.
530                Support::Unknown
531            }
532            Err(e) => Support::Unavailable {
533                reason: e.to_string(),
534            },
535        }
536    }
537
538    fn register(&mut self, shortcuts: &[Shortcut]) {
539        if let Some(tx) = &self.requests {
540            let _ = tx.send(shortcuts.to_vec());
541        }
542    }
543
544    fn stop(&mut self) {
545        // The thread ends when its queue goes.
546        self.requests = None;
547    }
548}
549
550#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))]
551async fn portal_loop(
552    app_id: &str,
553    rx: std::sync::mpsc::Receiver<Vec<Shortcut>>,
554    presses: Presses,
555    status: &SystemKeys,
556) {
557    use ashpd::desktop::CreateSessionOptions;
558    use ashpd::desktop::global_shortcuts::{BindShortcutsOptions, GlobalShortcuts, NewShortcut};
559    use futures_lite::StreamExt as _;
560
561    let unavailable = |reason: String| {
562        status.set_support(Support::Unavailable { reason });
563        presses.waker.request_repaint();
564    };
565    // Outside a sandbox the portal knows the application by its id,
566    // registered first (it needs the application's desktop file).
567    let registered = match app_id.parse::<ashpd::AppID>() {
568        Ok(id) => ashpd::register_host_app(id)
569            .await
570            .map_err(|e| e.to_string()),
571        Err(e) => Err(format!("`{app_id}` is not an application id: {e}")),
572    };
573    if let Err(e) = &registered {
574        log::warn!(target: "egui_pop", "global shortcuts: the portal does not know the application: {e}");
575    }
576    let portal = match GlobalShortcuts::new().await {
577        Ok(p) => p,
578        Err(e) => {
579            return unavailable(format!(
580                "the desktop offers no global shortcuts portal ({e})"
581            ));
582        }
583    };
584    status.set_support(Support::Available {
585        backend: "portal".into(),
586    });
587    presses.waker.request_repaint();
588    let mut activated = match portal.receive_activated().await {
589        Ok(s) => Box::pin(s),
590        Err(e) => return unavailable(e.to_string()),
591    };
592    let mut session: Option<ashpd::desktop::Session<GlobalShortcuts>> = None;
593    loop {
594        enum Next {
595            Request(Option<Vec<Shortcut>>),
596            Pressed(Option<String>),
597        }
598        let next = futures_lite::future::or(
599            async { Next::Request(async_channel_lite::recv(&rx).await) },
600            async { Next::Pressed(activated.next().await.map(|a| a.shortcut_id().to_string())) },
601        )
602        .await;
603        match next {
604            Next::Request(None) | Next::Pressed(None) => break,
605            Next::Pressed(Some(keys)) => presses.send(&keys),
606            Next::Request(Some(shortcuts)) => {
607                if let Some(old) = session.take() {
608                    let _ = old.close().await;
609                }
610                for s in &shortcuts {
611                    status.set_status(&s.keys, KeyStatus::Pending);
612                }
613                presses.waker.request_repaint();
614                if shortcuts.is_empty() {
615                    continue;
616                }
617                let new: Vec<NewShortcut> = shortcuts
618                    .iter()
619                    .map(|s| {
620                        NewShortcut::new(s.keys.clone(), s.description.clone())
621                            .preferred_trigger(xdg_trigger(&s.chord).as_deref())
622                    })
623                    .collect();
624                let created = portal.create_session(CreateSessionOptions::default()).await;
625                let s = match created {
626                    Ok(s) => s,
627                    Err(e) => {
628                        for sc in &shortcuts {
629                            status.set_status(&sc.keys, KeyStatus::Failed(e.to_string()));
630                        }
631                        continue;
632                    }
633                };
634                let bound = match portal
635                    .bind_shortcuts(&s, &new, None, BindShortcutsOptions::default())
636                    .await
637                {
638                    Ok(request) => request.response().map_err(|e| e.to_string()),
639                    Err(e) => Err(e.to_string()),
640                };
641                // Say what the user can do about it.
642                let bound = bound.map_err(|e| match &registered {
643                    Err(why) if e.contains("app id") => format!(
644                        "the portal does not know the application: install its desktop file `{app_id}.desktop` ({why})"
645                    ),
646                    _ if e.contains("no information") => {
647                        "the desktop refused them (does the compositor offer global shortcuts?)".into()
648                    }
649                    _ => e,
650                });
651                match bound {
652                    Ok(answer) => {
653                        let granted: Vec<&str> =
654                            answer.shortcuts().iter().map(|s| s.id()).collect();
655                        for sc in &shortcuts {
656                            let state = if granted.contains(&sc.keys.as_str()) {
657                                KeyStatus::Registered
658                            } else {
659                                KeyStatus::Failed("not accepted on the desktop".into())
660                            };
661                            status.set_status(&sc.keys, state);
662                        }
663                    }
664                    Err(e) => {
665                        for sc in &shortcuts {
666                            status.set_status(&sc.keys, KeyStatus::Failed(e.clone()));
667                        }
668                    }
669                }
670                presses.waker.request_repaint();
671                session = Some(s);
672            }
673        }
674    }
675    if let Some(old) = session.take() {
676        let _ = old.close().await;
677    }
678}
679
680#[derive(Debug, Default)]
681struct SimState {
682    support: Option<Support>,
683    registered: Vec<Shortcut>,
684    taken: Vec<String>,
685    presses: Option<Presses>,
686    status: Option<Arc<SystemKeys>>,
687}
688
689/// A desktop that records what is registered and presses keys as a
690/// user would. For tests and the gallery.
691#[derive(Clone, Debug, Default)]
692pub struct Simulated(Arc<Mutex<SimState>>);
693
694impl Simulated {
695    /// A desktop taking no global shortcuts, saying why.
696    pub fn unavailable(reason: &str) -> Self {
697        let s = Self::default();
698        lock(&s.0).support = Some(Support::Unavailable {
699            reason: reason.into(),
700        });
701        s
702    }
703
704    /// These keys are taken by another application: registering them
705    /// fails.
706    pub fn taken(self, keys: &str) -> Self {
707        lock(&self.0).taken.push(keys.into());
708        self
709    }
710
711    /// What is registered.
712    pub fn registered(&self) -> Vec<Shortcut> {
713        lock(&self.0).registered.clone()
714    }
715
716    /// The user presses these keys; false when nothing is registered on
717    /// them.
718    pub fn press(&self, keys: &str) -> bool {
719        let s = lock(&self.0);
720        let found = s.registered.iter().any(|r| r.keys == keys);
721        match (&s.presses, found) {
722            (Some(p), true) => {
723                p.send(keys);
724                true
725            }
726            _ => false,
727        }
728    }
729}
730
731impl Backend for Simulated {
732    fn name(&self) -> String {
733        "simulated".into()
734    }
735
736    fn start(&mut self, presses: Presses, status: Arc<SystemKeys>) -> Support {
737        let mut s = lock(&self.0);
738        let support = s.support.clone().unwrap_or(Support::Available {
739            backend: "simulated".into(),
740        });
741        if matches!(support, Support::Available { .. }) {
742            s.presses = Some(presses);
743            s.status = Some(status);
744        }
745        support
746    }
747
748    fn register(&mut self, shortcuts: &[Shortcut]) {
749        let mut s = lock(&self.0);
750        let taken = s.taken.clone();
751        s.registered = shortcuts
752            .iter()
753            .filter(|sc| !taken.contains(&sc.keys))
754            .cloned()
755            .collect();
756        if let Some(status) = &s.status {
757            for sc in shortcuts {
758                status.set_status(
759                    &sc.keys,
760                    if taken.contains(&sc.keys) {
761                        KeyStatus::Failed("taken by another application".into())
762                    } else {
763                        KeyStatus::Registered
764                    },
765                );
766            }
767        }
768    }
769
770    fn stop(&mut self) {
771        let mut s = lock(&self.0);
772        s.registered.clear();
773        s.presses = None;
774        s.status = None;
775    }
776}
777
778/// The shortcuts of the system scope now, and the bindings refused
779/// before any desktop sees them (a sequence of chords, keys of no
780/// desktop's).
781fn shortcuts(app: &AppHandle) -> (Vec<Shortcut>, Vec<(String, String)>) {
782    let mut ok = Vec::new();
783    let mut refused = Vec::new();
784    for b in app.system_bindings() {
785        let Action::Run(command) = &b.action else {
786            continue;
787        };
788        let keys = b.keys.to_string();
789        if b.keys.0.len() != 1 {
790            refused.push((keys, "a global shortcut is a single chord".into()));
791            continue;
792        }
793        if egui_key(&b.keys.0[0]).is_none() {
794            refused.push((keys, format!("`{}` is not a key", b.keys.0[0].key)));
795            continue;
796        }
797        let description = app
798            .command(command)
799            .map(|s| app.command_menu_title(&s))
800            .unwrap_or_else(|| command.to_string());
801        ok.push(Shortcut {
802            keys,
803            chord: b.keys.0[0].clone(),
804            command: command.clone(),
805            description,
806        });
807    }
808    (ok, refused)
809}
810
811/// The backend while connected.
812type Running = Rc<RefCell<Option<Box<dyn Backend>>>>;
813
814/// Global shortcuts, as a plugin (see the module).
815pub struct SystemKeysPlugin {
816    app_id: String,
817    backend: Option<Box<dyn Backend>>,
818    running: Option<Running>,
819}
820
821impl std::fmt::Debug for SystemKeysPlugin {
822    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
823        f.debug_struct("SystemKeysPlugin")
824            .field("app_id", &self.app_id)
825            .finish_non_exhaustive()
826    }
827}
828
829impl SystemKeysPlugin {
830    /// The session's backend ([`detect`]), for the application
831    /// `app_id` (`org.example.App`).
832    pub fn new(app_id: &str) -> Self {
833        Self {
834            app_id: app_id.into(),
835            backend: None,
836            running: None,
837        }
838    }
839
840    /// Another backend ([`Simulated`] in tests).
841    pub fn backend(mut self, backend: impl Backend) -> Self {
842        self.backend = Some(Box::new(backend));
843        self
844    }
845}
846
847impl Plugin for SystemKeysPlugin {
848    fn id(&self) -> PluginId {
849        PLUGIN
850    }
851
852    fn title(&self) -> String {
853        "Global shortcuts".into()
854    }
855
856    fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
857        ctx.step(
858            StepSpec::new(
859                STEP_PRESSED,
860                "A global shortcut was pressed (`command`, `keys`, `backend`); by default its command runs.",
861            )
862            .args(json!({ "command": "player.toggle", "keys": "Ctrl+Alt+P", "backend": "x11" })),
863        )?;
864        ctx.service(&SYSTEM_KEYS, SystemKeys::default())?;
865        let status = ctx
866            .app()
867            .service(&SYSTEM_KEYS)
868            .ok_or_else(|| PluginError::Failed("the service is not there".into()))?;
869        let mut backend = self.backend.take().unwrap_or_else(|| detect(&self.app_id));
870        let name = backend.name();
871        let (tx, rx): (Sender<String>, Receiver<String>) = channel();
872        let presses = Presses {
873            tx,
874            waker: ctx.app().egui(),
875        };
876        let support = backend.start(presses, status.clone());
877        if support != Support::Unknown || status.support() == Support::Unknown {
878            status.set_support(support);
879        }
880        let backend: Running = Rc::new(RefCell::new(Some(backend)));
881        self.running = Some(backend.clone());
882        let mut last: Option<Vec<Shortcut>> = None;
883        ctx.on(On::Pass, move |app, _| {
884            let (list, refused) = shortcuts(app);
885            if last.as_ref() != Some(&list) {
886                status.clear();
887                for (keys, why) in &refused {
888                    status.set_status(keys, KeyStatus::Failed(why.clone()));
889                }
890                if let Support::Unavailable { .. } = status.support() {
891                    // Nothing to register with: the editor says why.
892                } else if let Some(b) = backend.borrow_mut().as_mut() {
893                    b.register(&list);
894                }
895                last = Some(list.clone());
896            }
897            for keys in rx.try_iter() {
898                let Some(s) = list.iter().find(|s| s.keys == keys) else {
899                    continue;
900                };
901                let command = s.command.clone();
902                app.step(
903                    &STEP_PRESSED,
904                    json!({ "command": command, "keys": keys, "backend": name }),
905                    |app, args| {
906                        let command = args["command"]
907                            .as_str()
908                            .and_then(|c| CommandId::new(c).ok())
909                            .ok_or("`command` is missing")?;
910                        app.run_as(command.clone(), serde_json::Value::Null, Origin::User);
911                        Ok(json!({ "ran": command }))
912                    },
913                );
914            }
915        });
916        Ok(())
917    }
918
919    fn disconnect(&mut self, _ctx: &mut Ctx<'_>) {
920        if let Some(b) = self.running.take()
921            && let Some(mut b) = b.borrow_mut().take()
922        {
923            b.stop();
924            self.backend = Some(b);
925        }
926    }
927}