//! Desktop session detection and a common window/output view over KWin (KDE Wayland) and //! i3 + X11, shared by capture, awareness and computer control. use std::sync::Arc; use anyhow::{bail, Result}; use x11rb::connection::Connection as _; use x11rb::protocol::xproto::{AtomEnum, ConnectionExt}; use x11rb::rust_connection::RustConnection; use crate::i3::{self, I3}; use crate::imaging::Rect; use crate::kwin::{self, KWin}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Platform { Kde, X11, } impl Platform { /// `WAYLAND_DISPLAY` + `XDG_CURRENT_DESKTOP` containing KDE → KWin; else `DISPLAY` → X11/i3. pub fn detect() -> Result { Self::from_env(|k| std::env::var(k).ok()) } pub fn from_env(var: impl Fn(&str) -> Option) -> Result { if var("WAYLAND_DISPLAY").is_some_and(|v| !v.is_empty()) && var("XDG_CURRENT_DESKTOP").unwrap_or_default().to_uppercase().contains("KDE") { return Ok(Self::Kde); } if var("DISPLAY").is_some_and(|v| !v.is_empty()) { return Ok(Self::X11); } bail!("Desktop control requires KDE Plasma (Wayland) or i3 (X11).") } } /// A top-level window. `id` is a decimal string (`^[1-9]\d{0,19}$`); `native` is the KWin UUID /// or the X window id. #[derive(Clone, Debug, Default, PartialEq)] pub struct DesktopWindow { pub id: String, pub native: String, pub pid: u32, pub title: String, pub rect: Rect, /// Origin of window-relative accessibility coordinates (KWin client area). pub client: (i32, i32), pub active: bool, pub fullscreen: bool, pub modal: bool, pub dialog: bool, pub minimized: bool, pub wm_class: String, pub output: String, } #[derive(Clone, Debug, PartialEq)] pub struct Output { pub name: String, pub rect: Rect, } #[derive(Clone, Debug, Default)] pub struct DesktopState { /// Top-most first; current virtual desktop / visible workspaces only. pub windows: Vec, pub outputs: Vec, pub cursor: (i32, i32), } impl DesktopState { pub fn active(&self) -> Option<&DesktopWindow> { self.windows.iter().find(|w| w.active && !w.minimized) } /// Output of a window: by name, else the one containing its centre. pub fn output_of(&self, w: &DesktopWindow) -> Option<&Output> { let (cx, cy) = (w.rect.x + w.rect.width as i32 / 2, w.rect.y + w.rect.height as i32 / 2); self.outputs.iter().find(|o| !w.output.is_empty() && o.name == w.output).or_else(|| self.outputs.iter().find(|o| o.rect.contains(cx, cy))) } /// Bounding box of all outputs. pub fn desktop_bounds(&self) -> Option { let left = self.outputs.iter().map(|o| o.rect.x).min()?; let top = self.outputs.iter().map(|o| o.rect.y).min()?; let right = self.outputs.iter().map(|o| o.rect.x + o.rect.width as i32).max()?; let bottom = self.outputs.iter().map(|o| o.rect.y + o.rect.height as i32).max()?; Some(Rect { x: left, y: top, width: (right - left) as u32, height: (bottom - top) as u32 }) } } /// Live desktop connection. #[derive(Clone)] pub enum Desktop { Kde(Arc), X11(Arc), } pub struct X11 { pub conn: RustConnection, pub root: u32, } impl Desktop { pub async fn connect() -> Result { Ok(match Platform::detect()? { Platform::Kde => Self::Kde(KWin::connect().await?), Platform::X11 => { let (conn, screen) = x11rb::connect(None)?; let root = conn.setup().roots[screen].root; Self::X11(Arc::new(X11 { conn, root })) } }) } pub fn platform(&self) -> Platform { match self { Self::Kde(_) => Platform::Kde, Self::X11(_) => Platform::X11, } } pub async fn state(&self, include_minimized: bool) -> Result { match self { Self::Kde(k) => Ok(from_kwin(k.state().await?, include_minimized)), Self::X11(x) => { let mut ipc = I3::connect().await?; let visible: Vec = ipc.request(i3::GET_WORKSPACES, "").await?.as_array().into_iter().flatten().filter(|w| w["visible"] == true).filter_map(|w| w["name"].as_str().map(String::from)).collect(); let tree = ipc.request(i3::GET_TREE, "").await?; let outputs = ipc.request(i3::GET_OUTPUTS, "").await?; let windows = i3::leaves(&tree, &visible) .into_iter() .map(|l| DesktopWindow { id: l.window.to_string(), native: l.window.to_string(), pid: x.pid_of(l.window), title: l.title, rect: Rect { x: l.rect.0, y: l.rect.1, width: l.rect.2, height: l.rect.3 }, client: (l.rect.0, l.rect.1), active: l.focused, fullscreen: l.fullscreen, modal: l.dialog, dialog: l.dialog, minimized: false, wm_class: l.class, output: l.output, }) .collect(); let outputs = outputs .as_array() .into_iter() .flatten() .filter(|o| o["active"] == true) .map(|o| Output { name: o["name"].as_str().unwrap_or("").into(), rect: rect_of(&o["rect"]) }) .collect(); Ok(DesktopState { windows, outputs, cursor: x.pointer().map(|p| (p.0, p.1)).unwrap_or_default() }) } } } /// Brings a window to the foreground and confirms it is active. pub async fn activate(&self, w: &DesktopWindow) -> Result { match self { Self::Kde(k) => { let ok = k.activate(&w.native).await?; tokio::time::sleep(std::time::Duration::from_millis(100)).await; Ok(ok && self.state(false).await?.active().is_some_and(|a| a.id == w.id)) } Self::X11(_) => { let id: u32 = w.native.parse()?; I3::connect().await?.request(i3::RUN_COMMAND, &format!("[id={id}] focus")).await?; tokio::time::sleep(std::time::Duration::from_millis(100)).await; Ok(self.state(false).await?.active().is_some_and(|a| a.id == w.id)) } } } } fn rect_of(v: &serde_json::Value) -> Rect { Rect { x: v["x"].as_i64().unwrap_or(0) as i32, y: v["y"].as_i64().unwrap_or(0) as i32, width: v["width"].as_u64().unwrap_or(0) as u32, height: v["height"].as_u64().unwrap_or(0) as u32 } } fn rect4(r: [f64; 4]) -> Rect { Rect { x: r[0].round() as i32, y: r[1].round() as i32, width: r[2].round().max(0.0) as u32, height: r[3].round().max(0.0) as u32 } } pub fn from_kwin(s: kwin::KState, include_minimized: bool) -> DesktopState { let windows = s .windows .into_iter() .filter(|w| w.current && (include_minimized || !w.minimized)) .map(|w| DesktopWindow { id: kwin::numeric_id(&w.id), native: w.id, pid: w.pid.max(0) as u32, title: w.caption, rect: rect4(w.frame), client: (w.client[0].round() as i32, w.client[1].round() as i32), active: w.active, fullscreen: w.full_screen, modal: w.modal, dialog: w.dialog, minimized: w.minimized, wm_class: w.cls, output: w.output, }) .collect(); let outputs = s.outputs.into_iter().map(|o| Output { name: o.name, rect: rect4(o.rect) }).collect(); DesktopState { windows, outputs, cursor: (s.cursor[0].round() as i32, s.cursor[1].round() as i32) } } impl X11 { pub fn atom(&self, name: &str) -> Result { Ok(self.conn.intern_atom(false, name.as_bytes())?.reply()?.atom) } /// XRes client PID, `_NET_WM_PID` fallback, 0 when unknown. pub fn pid_of(&self, window: u32) -> u32 { use x11rb::protocol::res::{ClientIdMask, ClientIdSpec, ConnectionExt as _}; let spec = ClientIdSpec { client: window, mask: ClientIdMask::LOCAL_CLIENT_PID }; if let Ok(Ok(reply)) = self.conn.res_query_client_ids(&[spec]).map(|c| c.reply()) && let Some(pid) = reply.ids.iter().filter_map(|v| v.value.first().copied()).find(|p| *p > 0) { return pid; } self.atom("_NET_WM_PID") .ok() .and_then(|a| self.conn.get_property(false, window, a, AtomEnum::CARDINAL, 0, 1).ok()?.reply().ok()) .and_then(|r| r.value32()?.next()) .unwrap_or(0) } /// Pointer position and button/modifier mask. pub fn pointer(&self) -> Result<(i32, i32, u16)> { let r = self.conn.query_pointer(self.root)?.reply()?; Ok((r.root_x as i32, r.root_y as i32, u16::from(r.mask))) } } /// Process identity helpers (`capri_linux/common.py`). pub mod process { use std::path::PathBuf; /// Start time in clock ticks since boot (`/proc//stat` field 22), `""` when gone. pub fn started_ticks(pid: u32) -> String { std::fs::read_to_string(format!("/proc/{pid}/stat")).ok().and_then(|s| stat_field(&s, 22)).unwrap_or_default() } /// Field `n` (1-based) of a stat line whose comm may contain spaces and `)`. pub fn stat_field(stat: &str, n: usize) -> Option { let rest = &stat[stat.rfind(')')? + 2..]; rest.split_whitespace().nth(n - 3).map(String::from) } pub fn executable(pid: u32) -> Option { std::fs::canonicalize(format!("/proc/{pid}/exe")).ok() } pub fn name(pid: u32) -> String { std::fs::read_to_string(format!("/proc/{pid}/comm")).map(|s| s.trim().to_string()).unwrap_or_default() } pub fn owned_by_me(pid: u32) -> bool { use std::os::unix::fs::MetadataExt; std::fs::metadata(format!("/proc/{pid}")).is_ok_and(|m| m.uid() == unsafe { libc::getuid() }) } /// Flatpak application id from `/proc//cgroup`. pub fn flatpak_app(pid: u32) -> String { let text = std::fs::read_to_string(format!("/proc/{pid}/cgroup")).unwrap_or_default(); flatpak_from_cgroup(&text) } pub fn flatpak_from_cgroup(text: &str) -> String { let Some(start) = text.find("app-flatpak-") else { return String::new() }; let rest = &text[start + 12..]; let Some(end) = rest.find(".scope") else { return String::new() }; let unit = &rest[..end]; unit.rsplit_once('-').map(|(id, _)| id.replace("\\x2d", "-")).unwrap_or_default() } /// Capri itself is never an input target (own binary, any executable named `capri`). pub fn is_capri(pid: u32) -> bool { let own = std::env::current_exe().ok().and_then(|p| std::fs::canonicalize(p).ok()); match executable(pid) { Some(exe) => Some(&exe) == own.as_ref() || exe.file_name().is_some_and(|n| n.eq_ignore_ascii_case("capri")), None => true, } } /// A verifiable process of the same user that is not Capri. pub fn allowed(pid: u32, ignored: u32) -> bool { pid > 0 && pid != ignored && pid != std::process::id() && owned_by_me(pid) && !is_capri(pid) } } #[cfg(test)] mod tests { use super::*; #[test] fn detection() { let env = |pairs: &'static [(&'static str, &'static str)]| move |k: &str| pairs.iter().find(|p| p.0 == k).map(|p| p.1.to_string()); assert_eq!(Platform::from_env(env(&[("WAYLAND_DISPLAY", "wayland-0"), ("XDG_CURRENT_DESKTOP", "KDE"), ("DISPLAY", ":0")])).unwrap(), Platform::Kde); assert_eq!(Platform::from_env(env(&[("DISPLAY", ":0"), ("XDG_CURRENT_DESKTOP", "i3")])).unwrap(), Platform::X11); assert!(Platform::from_env(env(&[])).is_err()); } #[test] fn proc_parsing() { let stat = "42 (we ird) prog) S 1 42 42 0 -1 4194560 0 0 0 0 5 6 0 0 20 0 1 0 98765 0"; assert_eq!(process::stat_field(stat, 22).as_deref(), Some("98765")); assert_eq!(process::stat_field(stat, 4).as_deref(), Some("1")); assert_eq!(process::flatpak_from_cgroup("0::/user.slice/app-flatpak-org.mozilla.firefox-12345.scope\n"), "org.mozilla.firefox"); assert_eq!(process::flatpak_from_cgroup("0::/user.slice/app.slice"), ""); assert!(!process::started_ticks(std::process::id()).is_empty()); assert!(!process::allowed(std::process::id(), 0), "never Capri's own process"); } #[test] fn state_helpers() { let w = DesktopWindow { id: "1".into(), rect: Rect { x: 1950, y: 10, width: 100, height: 100 }, active: true, ..Default::default() }; let s = DesktopState { windows: vec![w.clone()], outputs: vec![Output { name: "A".into(), rect: Rect { x: 0, y: 0, width: 1920, height: 1080 } }, Output { name: "B".into(), rect: Rect { x: 1920, y: 0, width: 1280, height: 1024 } }], cursor: (0, 0), }; assert_eq!(s.output_of(&w).unwrap().name, "B"); assert_eq!(s.desktop_bounds().unwrap(), Rect { x: 0, y: 0, width: 3200, height: 1080 }); assert_eq!(s.active().unwrap().id, "1"); } }