1use 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
91pub const PLUGIN: PluginId = PluginId::from_static("egui_pop.system_keys");
93pub const STEP_PRESSED: StepId = StepId::from_static("keys.system");
95
96#[derive(Clone, Debug, PartialEq, Eq)]
98pub struct Shortcut {
99 pub keys: String,
101 pub chord: Chord,
102 pub command: CommandId,
103 pub description: String,
106}
107
108#[derive(Clone, Debug)]
110pub struct Presses {
111 tx: Sender<String>,
112 waker: egui::Context,
113}
114
115impl Presses {
116 pub fn send(&self, keys: &str) {
118 let _ = self.tx.send(keys.into());
119 self.waker.request_repaint();
120 }
121}
122
123pub trait Backend: 'static {
127 fn name(&self) -> String;
129 fn start(&mut self, presses: Presses, status: Arc<SystemKeys>) -> Support;
132 fn register(&mut self, shortcuts: &[Shortcut]);
135 fn stop(&mut self);
137}
138
139pub 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
150fn egui_key(chord: &Chord) -> Option<egui::Key> {
152 egui_pop_core::keys::key_of(chord).map(|(_, k)| k)
153}
154
155#[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 #[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#[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#[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
401pub 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#[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#[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 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 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 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 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 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) = ®istered {
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 let bound = bound.map_err(|e| match ®istered {
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#[derive(Clone, Debug, Default)]
692pub struct Simulated(Arc<Mutex<SimState>>);
693
694impl Simulated {
695 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 pub fn taken(self, keys: &str) -> Self {
707 lock(&self.0).taken.push(keys.into());
708 self
709 }
710
711 pub fn registered(&self) -> Vec<Shortcut> {
713 lock(&self.0).registered.clone()
714 }
715
716 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
778fn 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
811type Running = Rc<RefCell<Option<Box<dyn Backend>>>>;
813
814pub 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 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 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 } 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}