//! Platform backends: window list/activation (KWin script or i3 IPC via `capri-perception`), //! input injection (KDE RemoteDesktop portal held in-process; X11 XTest) and Escape watching //! (KDE kglobalaccel shortcut; X11 `XGrabKey` on the root window). use std::collections::HashMap; use std::path::PathBuf; use std::sync::Arc; use std::time::Duration; use anyhow::{anyhow, bail, Context, Result}; use async_trait::async_trait; use capri_perception::platform::{Desktop, DesktopState, DesktopWindow}; use futures::StreamExt; use tokio_util::sync::CancellationToken; use x11rb::connection::Connection as _; use x11rb::protocol::xproto::{ConnectionExt as _, GrabMode, ModMask}; use x11rb::protocol::xtest::ConnectionExt as _; use zbus::zvariant::{ObjectPath, OwnedObjectPath, OwnedValue, Value}; use crate::error::{fail, preflight, Fail, NResult, INPUT_UNAVAILABLE}; use crate::keys; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Button { Left, Middle, Right, } impl Button { pub fn parse(s: &str) -> NResult { match s { "left" => Ok(Self::Left), "right" => Ok(Self::Right), "middle" => Ok(Self::Middle), _ => Err(fail("Invalid pointer button.")), } } } #[async_trait] pub trait Windows: Send + Sync { async fn state(&self, include_minimized: bool) -> Result; async fn activate(&self, w: &DesktopWindow) -> Result; /// KDE toolkits report window-relative accessibility coordinates. fn relative_a11y(&self) -> bool; } #[async_trait] impl Windows for Desktop { async fn state(&self, include_minimized: bool) -> Result { Desktop::state(self, include_minimized).await } async fn activate(&self, w: &DesktopWindow) -> Result { Desktop::activate(self, w).await } fn relative_a11y(&self) -> bool { matches!(self, Desktop::Kde(_)) } } #[async_trait] pub trait Input: Send + Sync { /// Ensures input is possible (KDE: portal consent). Refusal is `COMPUTER_INPUT_UNAVAILABLE`. async fn ready(&self) -> NResult<()>; async fn move_to(&self, x: i32, y: i32) -> NResult<()>; async fn button(&self, b: Button, down: bool) -> NResult<()>; async fn key(&self, keysym: u32, down: bool) -> NResult<()>; async fn type_text(&self, text: &str) -> NResult<()>; /// Positive = up. async fn scroll(&self, amount: i32) -> NResult<()>; /// Mouse buttons or modifiers physically held (Wayland: unknown → false). async fn busy(&self) -> bool; } // ---------------------------------------------------------------- X11 / XTest pub struct XInput { conn: x11rb::rust_connection::RustConnection, root: u32, } const BUSY_MASK: u16 = (1 << 0) | (1 << 2) | (1 << 3) | (1 << 6) | (1 << 8) | (1 << 9) | (1 << 10); impl XInput { pub fn connect() -> Result { let (conn, screen) = x11rb::connect(None).context("The X display is unavailable.")?; let root = conn.setup().roots[screen].root; Ok(Self { conn, root }) } fn fake(&self, kind: u8, detail: u8, x: i16, y: i16) -> NResult<()> { self.conn.xtest_fake_input(kind, detail, x11rb::CURRENT_TIME, if kind == 6 { self.root } else { x11rb::NONE }, x, y, 0).map_err(|e| fail(e.to_string()))?; self.conn.flush().map_err(|e| fail(e.to_string()))?; Ok(()) } fn keycode(&self, keysym: u32) -> NResult> { let setup = self.conn.setup(); let (min, max) = (setup.min_keycode, setup.max_keycode); let map = self.conn.get_keyboard_mapping(min, max - min + 1).map_err(|e| fail(e.to_string()))?.reply().map_err(|e| fail(e.to_string()))?; let per = map.keysyms_per_keycode as usize; Ok(map.keysyms.chunks(per).position(|syms| syms.iter().take(2).any(|s| *s == keysym)).map(|i| min + i as u8)) } /// Types one keysym missing from the layout by binding it to a spare keycode (xdotool's approach). fn type_remapped(&self, keysym: u32) -> NResult<()> { let setup = self.conn.setup(); let (min, max) = (setup.min_keycode, setup.max_keycode); let map = self.conn.get_keyboard_mapping(min, max - min + 1).map_err(|e| fail(e.to_string()))?.reply().map_err(|e| fail(e.to_string()))?; let per = map.keysyms_per_keycode; let spare = map.keysyms.chunks(per as usize).rposition(|s| s.iter().all(|k| *k == 0)).map(|i| min + i as u8).ok_or_else(|| fail("This key is not available on the current keyboard layout."))?; let set = |sym: u32| -> NResult<()> { self.conn.change_keyboard_mapping(1, spare, per, &vec![sym; per as usize]).map_err(|e| fail(e.to_string()))?; self.conn.get_input_focus().map_err(|e| fail(e.to_string()))?.reply().map(|_| ()).map_err(|e| fail(e.to_string())) }; set(keysym)?; std::thread::sleep(Duration::from_millis(8)); let result = self.fake(2, spare, 0, 0).and_then(|_| self.fake(3, spare, 0, 0)); std::thread::sleep(Duration::from_millis(8)); set(0)?; result } } #[async_trait] impl Input for XInput { async fn ready(&self) -> NResult<()> { Ok(()) } async fn move_to(&self, x: i32, y: i32) -> NResult<()> { self.fake(6, 0, x as i16, y as i16) } async fn button(&self, b: Button, down: bool) -> NResult<()> { let detail = match b { Button::Left => 1, Button::Middle => 2, Button::Right => 3, }; self.fake(if down { 4 } else { 5 }, detail, 0, 0) } async fn key(&self, keysym: u32, down: bool) -> NResult<()> { let code = self.keycode(keysym)?.ok_or_else(|| fail("This key is not available on the current keyboard layout."))?; self.fake(if down { 2 } else { 3 }, code, 0, 0) } async fn type_text(&self, text: &str) -> NResult<()> { for c in text.chars().filter(|c| *c != '\r') { let sym = keys::char_keysym(c); match self.keycode(sym)? { // TODO: Shift/AltGr characters go through the spare-keycode remap; use a modifier-aware lookup if that proves slow. Some(code) if self.conn.get_keyboard_mapping(code, 1).ok().and_then(|c| c.reply().ok()).is_some_and(|m| m.keysyms.first() == Some(&sym)) => { self.fake(2, code, 0, 0)?; self.fake(3, code, 0, 0)?; } _ => self.type_remapped(sym)?, } tokio::time::sleep(Duration::from_millis(4)).await; } Ok(()) } async fn scroll(&self, amount: i32) -> NResult<()> { let button = if amount > 0 { 4 } else { 5 }; for _ in 0..amount.unsigned_abs() { self.fake(4, button, 0, 0)?; self.fake(5, button, 0, 0)?; } Ok(()) } async fn busy(&self) -> bool { self.conn.query_pointer(self.root).ok().and_then(|c| c.reply().ok()).is_some_and(|r| u16::from(r.mask) & BUSY_MASK != 0) } } // ---------------------------------------------------------------- KDE RemoteDesktop portal const PORTAL: &str = "org.freedesktop.portal.Desktop"; const PORTAL_PATH: &str = "/org/freedesktop/portal/desktop"; const RD: &str = "org.freedesktop.portal.RemoteDesktop"; #[derive(Clone, Debug, PartialEq)] pub struct Stream { pub node: u32, pub x: i32, pub y: i32, pub width: i32, pub height: i32, } /// Stream whose rectangle holds the point, with stream-relative coordinates. pub fn stream_at(streams: &[Stream], x: f64, y: f64) -> Option<(u32, f64, f64)> { streams.iter().find(|s| x >= s.x as f64 && x < (s.x + s.width) as f64 && y >= s.y as f64 && y < (s.y + s.height) as f64).map(|s| (s.node, x - s.x as f64, y - s.y as f64)) } struct Session { conn: zbus::Connection, session: OwnedObjectPath, streams: Vec, } /// Holds the RemoteDesktop portal session (what `input_daemon.py` did in a separate process). /// First use shows KDE's remote-control consent; the restore token (persist mode 2) is kept /// 0600 in `token_path` so later sessions resume silently until revoked in System Settings. pub struct PortalInput { token_path: PathBuf, session: Arc>>, /// A session start in progress (it keeps waiting for the owner's consent). starting: Arc, failure: Arc>>, } /// How long an input waits for KDE's remote-control consent before refusing (preflight). // Capri gave up after 9 s while its daemon kept waiting; here the session start keeps running. const CONSENT_WAIT: Duration = Duration::from_secs(120); impl PortalInput { pub fn new(token_path: PathBuf) -> Self { Self { token_path, session: Arc::default(), starting: Arc::default(), failure: Arc::default() } } async fn request(conn: &zbus::Connection, iface: &str, method: &str, body: impl serde::Serialize + zbus::zvariant::DynamicType + Send + Sync, token: &str, timeout: Duration) -> Result> { let sender = conn.unique_name().ok_or_else(|| anyhow!("No D-Bus name"))?.trim_start_matches(':').replace('.', "_"); let path = format!("{PORTAL_PATH}/request/{sender}/{token}"); let rule = zbus::MatchRule::builder().msg_type(zbus::message::Type::Signal).interface("org.freedesktop.portal.Request")?.member("Response")?.path(path)?.build(); let mut stream = zbus::MessageStream::for_match_rule(rule, conn, None).await?; conn.call_method(Some(PORTAL), PORTAL_PATH, Some(iface), method, &body).await?; let msg = tokio::time::timeout(timeout, stream.next()).await.context("The remote-control request timed out.")?.ok_or_else(|| anyhow!("Portal closed"))??; let (code, results): (u32, HashMap) = msg.body().deserialize()?; match code { 0 => Ok(results), 1 => bail!("The owner declined remote control in KDE."), _ => bail!("KDE could not start remote control."), } } async fn start(token_path: PathBuf) -> Result { let conn = zbus::Connection::session().await?; // Lets KDE show Capri's name in the consent dialog; must precede other portal calls. let _ = conn.call_method(Some(PORTAL), PORTAL_PATH, Some("org.freedesktop.host.portal.Registry"), "Register", &("capri", HashMap::<&str, Value>::new())).await; let tok = || format!("capri{}", &uuid::Uuid::new_v4().simple().to_string()[..12]); let t = tok(); let opts: HashMap<&str, Value> = HashMap::from([("handle_token", Value::from(t.as_str())), ("session_handle_token", Value::from(tok()))]); let r = Self::request(&conn, RD, "CreateSession", (opts,), &t, Duration::from_secs(180)).await?; let handle: String = r.get("session_handle").and_then(|v| v.downcast_ref::().ok()).ok_or_else(|| anyhow!("No portal session"))?; let session = OwnedObjectPath::try_from(handle)?; let restore = std::fs::read_to_string(&token_path).ok().map(|s| s.trim().to_string()).filter(|s| !s.is_empty()); let t = tok(); let mut opts: HashMap<&str, Value> = HashMap::from([("handle_token", Value::from(t.as_str())), ("types", Value::from(3u32)), ("persist_mode", Value::from(2u32))]); if let Some(r) = &restore { opts.insert("restore_token", Value::from(r.as_str())); } Self::request(&conn, RD, "SelectDevices", (ObjectPath::from(&session), opts), &t, Duration::from_secs(180)).await?; let t = tok(); let opts: HashMap<&str, Value> = HashMap::from([("handle_token", Value::from(t.as_str())), ("types", Value::from(1u32)), ("multiple", Value::from(true))]); Self::request(&conn, "org.freedesktop.portal.ScreenCast", "SelectSources", (ObjectPath::from(&session), opts), &t, Duration::from_secs(180)).await?; let t = tok(); let opts: HashMap<&str, Value> = HashMap::from([("handle_token", Value::from(t.as_str()))]); let r = Self::request(&conn, RD, "Start", (ObjectPath::from(&session), "", opts), &t, Duration::from_secs(300)).await?; let devices: u32 = r.get("devices").and_then(|v| v.downcast_ref::().ok()).unwrap_or(0); if devices & 3 != 3 { bail!("KDE did not grant both keyboard and pointer control."); } let raw: Vec<(u32, HashMap)> = r.get("streams").and_then(|v| v.try_clone().ok()).and_then(|v| v.try_into().ok()).unwrap_or_default(); let streams: Vec = raw .into_iter() .filter_map(|(node, p)| { let (x, y): (i32, i32) = p.get("position")?.try_clone().ok()?.try_into().ok()?; let (w, h): (i32, i32) = p.get("size")?.try_clone().ok()?.try_into().ok()?; Some(Stream { node, x, y, width: w, height: h }) }) .collect(); if streams.is_empty() { bail!("KDE did not share any monitor for pointer positioning."); } if let Some(token) = r.get("restore_token").and_then(|v| v.downcast_ref::().ok()) { if let Some(dir) = token_path.parent() { std::fs::create_dir_all(dir)?; } capri_core::fsutil::write_atomic(&token_path, token.as_bytes())?; } Ok(Session { conn, session, streams }) } async fn notify(&self, method: &str, build: impl FnOnce(&Session) -> NResult) -> NResult<()> { let guard = self.session.lock().await; let s = guard.as_ref().ok_or_else(|| preflight(INPUT_UNAVAILABLE, "Allow Capri in KDE's remote-control dialog to let it use the mouse and keyboard. No input was sent."))?; let body = build(s)?; s.conn.call_method(Some(PORTAL), PORTAL_PATH, Some(RD), method, &body).await.map_err(Fail::from)?; Ok(()) } /// Closes the portal session (Capri exit). pub async fn close(&self) { if let Some(s) = self.session.lock().await.take() { let _ = s.conn.call_method(Some(PORTAL), s.session.as_str(), Some("org.freedesktop.portal.Session"), "Close", &()).await; } } } fn empty() -> HashMap<&'static str, Value<'static>> { HashMap::new() } #[async_trait] impl Input for PortalInput { async fn ready(&self) -> NResult<()> { use std::sync::atomic::Ordering; if self.session.lock().await.is_some() { return Ok(()); } if !self.starting.swap(true, Ordering::SeqCst) { *self.failure.lock() = None; let (path, session, starting, failure) = (self.token_path.clone(), self.session.clone(), self.starting.clone(), self.failure.clone()); tokio::spawn(async move { match Self::start(path).await { Ok(s) => { tracing::info!("KDE remote-control session started ({} monitor streams)", s.streams.len()); *session.lock().await = Some(s); } Err(e) => { tracing::warn!("KDE remote control unavailable: {e:#}"); *failure.lock() = Some(e.to_string()); } } starting.store(false, Ordering::SeqCst); }); } let end = std::time::Instant::now() + CONSENT_WAIT; loop { if self.session.lock().await.is_some() { return Ok(()); } let failed = self.failure.lock().clone(); if failed.is_some() || std::time::Instant::now() >= end { let detail = failed.map(|e| format!(" ({})", e.chars().take(160).collect::())).unwrap_or_default(); return Err(preflight(INPUT_UNAVAILABLE, format!("Allow Capri in KDE's remote-control dialog to let it use the mouse and keyboard. No input was sent.{detail}"))); } tokio::time::sleep(Duration::from_millis(200)).await; } } async fn move_to(&self, x: i32, y: i32) -> NResult<()> { self.notify("NotifyPointerMotionAbsolute", |s| { let (node, rx, ry) = stream_at(&s.streams, x as f64, y as f64).ok_or_else(|| fail("Pointer coordinates are outside the desktop."))?; Ok((s.session.clone(), empty(), node, rx, ry)) }) .await } async fn button(&self, b: Button, down: bool) -> NResult<()> { let code: i32 = match b { Button::Left => 272, Button::Right => 273, Button::Middle => 274, }; self.notify("NotifyPointerButton", |s| Ok((s.session.clone(), empty(), code, down as u32))).await } async fn key(&self, keysym: u32, down: bool) -> NResult<()> { self.notify("NotifyKeyboardKeysym", |s| Ok((s.session.clone(), empty(), keysym as i32, down as u32))).await } async fn type_text(&self, text: &str) -> NResult<()> { for c in text.chars().filter(|c| *c != '\r') { let sym = keys::char_keysym(c); self.key(sym, true).await?; self.key(sym, false).await?; } Ok(()) } async fn scroll(&self, amount: i32) -> NResult<()> { // Capri: positive scrolls up; portal: positive steps scroll down. self.notify("NotifyPointerAxisDiscrete", |s| Ok((s.session.clone(), empty(), 0u32, -amount))).await } async fn busy(&self) -> bool { false // Wayland exposes no global button/modifier state to clients. } } // ---------------------------------------------------------------- Escape /// An armed Escape watcher: `pressed` fires on Escape and also when the watcher fails /// (fail closed). Dropping or `disarm` releases the grab. pub struct EscapeGuard { pub pressed: CancellationToken, stop: CancellationToken, } impl EscapeGuard { /// A guard fired through `pressed` (custom watchers, tests). pub fn new(pressed: CancellationToken) -> Self { Self { pressed, stop: CancellationToken::new() } } pub fn disarm(&self) { self.stop.cancel(); } pub fn active(&self) -> bool { !self.stop.is_cancelled() } } impl Drop for EscapeGuard { fn drop(&mut self) { self.stop.cancel(); } } #[async_trait] pub trait EscapeWatch: Send + Sync { /// Must confirm the grab within 3 s or fail (control then does not start). async fn arm(&self) -> Result; } /// KDE: a kglobalaccel global shortcut for Escape (grabbed for the session). pub struct KGlobalAccelEscape; const COMPONENT: &str = "capri-emergency-stop"; const ACTION_ID: [&str; 4] = [COMPONENT, "stop", "Capri", "Capri emergency stop"]; const QT_KEY_ESCAPE: i32 = 0x0100_0000; /// D-Bus shapes of the kglobalaccel calls (`as a(ai) u`): each shortcut is a struct of key codes. fn escape_keys(on: bool) -> (Vec<&'static str>, Vec<(Vec,)>, u32) { if on { (ACTION_ID.to_vec(), vec![(vec![QT_KEY_ESCAPE, 0, 0, 0],)], 6) } else { (ACTION_ID.to_vec(), vec![], 4) } } async fn kga_remove(conn: &zbus::Connection) { // Clear the key first so nothing stays grabbed, then forget the action. let _ = conn.call_method(Some("org.kde.kglobalaccel"), "/kglobalaccel", Some("org.kde.KGlobalAccel"), "setShortcutKeys", &escape_keys(false)).await; let _ = conn.call_method(Some("org.kde.kglobalaccel"), "/kglobalaccel", Some("org.kde.KGlobalAccel"), "unRegister", &(ACTION_ID.to_vec(),)).await; let _ = conn.call_method(Some("org.kde.kglobalaccel"), "/kglobalaccel", Some("org.kde.KGlobalAccel"), "unregister", &(COMPONENT, "stop")).await; } #[async_trait] impl EscapeWatch for KGlobalAccelEscape { async fn arm(&self) -> Result { let conn = zbus::Connection::session().await?; let armed = async { kga_remove(&conn).await; // a crashed session must not leave Escape grabbed let rule = zbus::MatchRule::builder().msg_type(zbus::message::Type::Signal).interface("org.kde.kglobalaccel.Component")?.member("globalShortcutPressed")?.path("/component/capri_emergency_stop")?.build(); let stream = zbus::MessageStream::for_match_rule(rule, &conn, None).await?; conn.call_method(Some("org.kde.kglobalaccel"), "/kglobalaccel", Some("org.kde.KGlobalAccel"), "doRegister", &(ACTION_ID.to_vec(),)).await?; conn.call_method(Some("org.kde.kglobalaccel"), "/kglobalaccel", Some("org.kde.KGlobalAccel"), "setShortcutKeys", &escape_keys(true)).await?; anyhow::Ok(stream) }; let mut stream = match tokio::time::timeout(Duration::from_secs(3), armed).await { Ok(Ok(s)) => s, other => { tracing::warn!("kglobalaccel Escape registration failed: {}", match other { Ok(Err(e)) => e.to_string(), _ => "timeout".into() }); kga_remove(&conn).await; bail!("Escape emergency stop is unavailable. Computer control did not start."); } }; let (pressed, stop) = (CancellationToken::new(), CancellationToken::new()); let (p, s) = (pressed.clone(), stop.clone()); tokio::spawn(async move { loop { tokio::select! { _ = s.cancelled() => break, m = stream.next() => match m { Some(Ok(m)) => { if let Ok((component, action, _)) = m.body().deserialize::<(String, String, i64)>() && component == COMPONENT && action == "stop" { p.cancel(); } } _ => { p.cancel(); break } // watcher lost: fail closed } } } kga_remove(&conn).await; }); Ok(EscapeGuard { pressed, stop }) } } /// X11 (i3): passive `XGrabKey` of Escape on the root window (with Lock/NumLock variants). pub struct XGrabEscape; #[async_trait] impl EscapeWatch for XGrabEscape { async fn arm(&self) -> Result { let (pressed, stop) = (CancellationToken::new(), CancellationToken::new()); let (tx, rx) = tokio::sync::oneshot::channel::>(); let (p, s) = (pressed.clone(), stop.clone()); std::thread::spawn(move || { let setup = || -> Result<(x11rb::rust_connection::RustConnection, u32, u8)> { let (conn, screen) = x11rb::connect(None)?; let root = conn.setup().roots[screen].root; let x = XInput { conn, root }; let code = x.keycode(keys::ESCAPE).ok().flatten().ok_or_else(|| anyhow!("No Escape key"))?; for m in [ModMask::from(0u16), ModMask::LOCK, ModMask::M2, ModMask::LOCK | ModMask::M2] { x.conn.grab_key(true, root, m, code, GrabMode::ASYNC, GrabMode::ASYNC)?.check()?; } Ok((x.conn, root, code)) }; let (conn, root, code) = match setup() { Ok(v) => v, Err(e) => { let _ = tx.send(Err(e)); return; } }; let _ = tx.send(Ok(())); while !s.is_cancelled() { match conn.poll_for_event() { Ok(Some(x11rb::protocol::Event::KeyPress(k))) if k.detail == code => p.cancel(), Ok(Some(_)) => {} Ok(None) => std::thread::sleep(Duration::from_millis(20)), Err(_) => { p.cancel(); break; } } } let _ = conn.ungrab_key(code, root, ModMask::ANY); let _ = conn.flush(); }); match tokio::time::timeout(Duration::from_secs(3), rx).await { Ok(Ok(Ok(()))) => Ok(EscapeGuard { pressed, stop }), _ => { stop.cancel(); bail!("Escape emergency stop is unavailable. Computer control did not start.") } } } } pub struct Backends { pub windows: Arc, pub input: Arc, pub escape: Arc, } impl Backends { /// `data_dir` keeps the KDE portal restore token (`desktop/portal-restore-token`). pub async fn connect(data_dir: &std::path::Path) -> Result<(Self, Desktop)> { let desktop = Desktop::connect().await?; let (input, escape): (Arc, Arc) = match &desktop { Desktop::Kde(_) => (Arc::new(PortalInput::new(data_dir.join("desktop/portal-restore-token"))), Arc::new(KGlobalAccelEscape)), Desktop::X11(_) => (Arc::new(XInput::connect()?), Arc::new(XGrabEscape)), }; Ok((Self { windows: Arc::new(desktop.clone()), input, escape }, desktop)) } } #[cfg(test)] mod tests { use super::*; #[test] fn streams() { let s = [Stream { node: 40, x: 0, y: 0, width: 1920, height: 1080 }, Stream { node: 41, x: 1920, y: 0, width: 1280, height: 1024 }]; assert_eq!(stream_at(&s, 2000.0, 10.0), Some((41, 80.0, 10.0))); assert_eq!(stream_at(&s, 5000.0, 10.0), None); assert!(Button::parse("left").is_ok() && Button::parse("x").is_err()); use zbus::zvariant::Type; assert_eq!(<(Vec<&str>, Vec<(Vec,)>, u32)>::SIGNATURE.to_string(), "(asa(ai)u)", "kglobalaccel setShortcutKeys"); assert_eq!(escape_keys(true).1[0].0[0], 0x0100_0000); assert_eq!(<(Vec<&str>,)>::SIGNATURE.to_string(), "(as)", "kglobalaccel doRegister/unRegister"); } }