//! Global hotkeys from physical keyboards. Apps (Chromium) own keyboard focus, //! so the launcher can't see these; we read evdev directly (without grabbing). //! F12 -> home //! Esc held 0.8 s -> home (a short press still means "back" in the app) use std::collections::HashSet; use std::path::PathBuf; use std::sync::{Arc, Mutex}; use std::time::Duration; use evdev::{EventType, KeyCode}; use crate::link::Link; const ESC_HOLD: Duration = Duration::from_millis(800); const OWN_DEVICE: &str = "Fennec OS Siri Remote"; pub fn spawn(link: Link) { std::thread::spawn(move || { let rt = match tokio::runtime::Builder::new_current_thread().enable_all().build() { Ok(rt) => rt, Err(e) => return log::error!("keyboard watcher: {e}"), }; rt.block_on(watch(link)); }); } async fn watch(link: Link) { let watched: Arc>> = Arc::default(); let mut rescan = tokio::time::interval(Duration::from_secs(3)); loop { rescan.tick().await; link.resend(); for (path, dev) in evdev::enumerate() { if watched.lock().unwrap().contains(&path) || dev.name() == Some(OWN_DEVICE) { continue; } let is_keyboard = dev .supported_keys() .is_some_and(|k| k.contains(KeyCode::KEY_ESC) && k.contains(KeyCode::KEY_F12)); if !is_keyboard { continue; } let Ok(mut stream) = dev.into_event_stream() else { continue }; log::info!("watching keyboard {}", path.display()); watched.lock().unwrap().insert(path.clone()); let (link, watched) = (link.clone(), watched.clone()); tokio::spawn(async move { // Deadline at which a still-held Esc turns into "home". let mut esc_deadline: Option = None; loop { let ev = match esc_deadline { Some(deadline) => tokio::select! { ev = stream.next_event() => ev, _ = tokio::time::sleep_until(deadline) => { log::info!("Esc held -> home"); esc_deadline = None; link.home(); continue; } }, None => stream.next_event().await, }; let Ok(ev) = ev else { break }; if ev.event_type() != EventType::KEY { continue; } let (code, value) = (KeyCode::new(ev.code()), ev.value()); if code == KeyCode::KEY_F12 && value == 1 { log::info!("F12 -> home"); link.home(); } else if code == KeyCode::KEY_ESC { match value { 1 => esc_deadline = Some(tokio::time::Instant::now() + ESC_HOLD), 0 => esc_deadline = None, _ => {} } } } log::info!("keyboard {} gone", path.display()); watched.lock().unwrap().remove(&path); }); } } }