From 7ccd26b62472ef619e223ec0afcf70a16b6e235b Mon Sep 17 00:00:00 2001 From: fkDead Date: Wed, 11 Nov 2026 20:20:48 +0100 Subject: [PATCH] capri-ui: add desktop module --- crates/capri-ui/src/desktop.rs | 319 +++++++++++++++++++++++++++++++++ 1 file changed, 319 insertions(+) create mode 100644 crates/capri-ui/src/desktop.rs diff --git a/crates/capri-ui/src/desktop.rs b/crates/capri-ui/src/desktop.rs new file mode 100644 index 0000000..0a92adc --- /dev/null +++ b/crates/capri-ui/src/desktop.rs @@ -0,0 +1,319 @@ +//! Other windows, displays and the real cursor: KWin scripting over +//! D-Bus on KDE Plasma Wayland (X11 sees neither Wayland windows, panels nor the pointer over +//! them), i3 IPC on i3, and EWMH as the X11 fallback. All coordinates are X11 root pixels. +use std::io::{Read, Write}; +use std::os::unix::fs::{MetadataExt, OpenOptionsExt}; +use std::sync::Arc; +use std::time::Duration; + +use anyhow::{bail, Context, Result}; +use parking_lot::Mutex; +use serde::Deserialize; +use tokio::sync::oneshot; + +use crate::x11::{Px, X11}; + +#[derive(Clone, Debug, Deserialize)] +pub struct Win { + pub id: String, + pub pid: u32, + pub title: String, + pub rect: Px, +} + +#[derive(Clone, Copy, Debug, Deserialize, PartialEq)] +pub struct DisplayPx { + pub bounds: Px, + pub work: Px, +} + +#[derive(Clone, Debug, Default, Deserialize)] +pub struct Snapshot { + /// Top-most first, current desktop, not minimized. + pub windows: Vec, + pub displays: Vec, +} + +impl Snapshot { + /// Windows Capri may perch on: another process of the same user, + /// at least 160 x 100, with a title. + pub fn candidates(&self) -> impl Iterator { + let me = std::process::id(); + let uid = std::fs::metadata("/proc/self").map(|m| m.uid()).ok(); + self.windows.iter().filter(move |w| { + w.pid != me + && w.rect[2] >= 160 + && w.rect[3] >= 100 + && !w.title.trim().is_empty() + && (w.pid == 0 || std::fs::metadata(format!("/proc/{}", w.pid)).map(|m| m.uid()).ok() == uid) + }) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Backend { + Kwin, + I3, + X11, +} + +struct Report { + cursor: Arc>>, + pending: Arc>>>, +} + +#[zbus::interface(name = "org.capri.Report")] +impl Report { + /// Only `x,y` cursor lines and one JSON answer per pending query are accepted. + fn report(&self, text: String) { + if text.starts_with('{') { + if let Some(tx) = self.pending.lock().take() { + let _ = tx.send(text); + } + } else if let Some((x, y)) = text.split_once(',') + && let (Ok(x), Ok(y)) = (x.trim().parse(), y.trim().parse()) + { + *self.cursor.lock() = Some((x, y)); + } + } +} + +const CURSOR_PLUGIN: &str = "capri-cursor"; +const CURSOR_SCRIPT: &str = r#" +let last = 0; +function report() { + const now = Date.now(); + if (now - last < 4) return; + last = now; + const p = workspace.cursorPos; + callDBus("NAME", "/", "org.capri.Report", "Report", Math.round(p.x) + "," + Math.round(p.y)); +} +workspace.cursorPosChanged.connect(report); +report(); +"#; +const LIST_SCRIPT: &str = r#" +const out = [], order = workspace.stackingOrder; +for (let i = order.length - 1; i >= 0; i--) { + const w = order[i]; + if (!(w.normalWindow || w.dialog) || w.desktopWindow || w.dock || (w.specialWindow && !w.dialog)) continue; + const current = w.onAllDesktops || w.desktops.some(d => d === workspace.currentDesktop); + if (!current || w.minimized) continue; + const f = w.frameGeometry; + out.push({id: String(w.internalId), title: String(w.caption), pid: w.pid || 0, + rect: [Math.round(f.x), Math.round(f.y), Math.round(f.width), Math.round(f.height)]}); +} +const displays = workspace.screens.map(o => { + const a = workspace.clientArea(KWin.PlacementArea, o, workspace.currentDesktop), g = o.geometry; + return {bounds: [g.x, g.y, g.width, g.height], work: [Math.round(a.x), Math.round(a.y), Math.round(a.width), Math.round(a.height)]}; +}); +callDBus("NAME", "/", "org.capri.Report", "Report", JSON.stringify({windows: out, displays: displays})); +"#; + +struct Kwin { + conn: zbus::Connection, + name: String, + cursor: Arc>>, + pending: Arc>>>, + query: tokio::sync::Mutex<()>, +} + +/// Script files live in the private runtime directory (mode 0600) until KWin has loaded them. +fn script_file(tag: &str, source: &str) -> Result { + let dir = std::env::var_os("XDG_RUNTIME_DIR").map(std::path::PathBuf::from).unwrap_or_else(std::env::temp_dir); + let path = dir.join(format!("capri-{tag}-{}.js", std::process::id())); + let _ = std::fs::remove_file(&path); + std::fs::OpenOptions::new().write(true).create_new(true).mode(0o600).open(&path)?.write_all(source.as_bytes())?; + Ok(path) +} + +impl Kwin { + async fn call(&self, path: &str, iface: &str, method: &str, body: &B) -> Result { + let call = self.conn.call_method(Some("org.kde.KWin"), path, Some(iface), method, body); + Ok(tokio::time::timeout(Duration::from_secs(3), call).await.context("KWin did not answer")??) + } + + async fn load(&self, tag: &str, plugin: &str, source: &str) -> Result<()> { + let _ = self.call("/Scripting", "org.kde.kwin.Scripting", "unloadScript", &(plugin,)).await; + let path = script_file(tag, &source.replace("NAME", &self.name))?; + let loaded = self.call("/Scripting", "org.kde.kwin.Scripting", "loadScript", &(path.to_string_lossy().as_ref(), plugin)).await; + let result = async { + let id: i32 = loaded?.body().deserialize()?; + if id < 0 { + bail!("KWin refused the script"); + } + self.call(&format!("/Scripting/Script{id}"), "org.kde.kwin.Script", "run", &()).await?; + Ok(()) + } + .await; + let _ = std::fs::remove_file(path); + result + } + + async fn start() -> Result { + let cursor = Arc::new(Mutex::new(None)); + let pending = Arc::new(Mutex::new(None)); + let name = format!("org.capri.ui.p{}", std::process::id()); + let conn = zbus::connection::Builder::session()? + .name(name.as_str())? + .serve_at("/", Report { cursor: cursor.clone(), pending: pending.clone() })? + .build() + .await?; + let kwin = Self { conn, name, cursor, pending, query: Default::default() }; + if let Err(e) = kwin.load("cursor", CURSOR_PLUGIN, CURSOR_SCRIPT).await { + tracing::warn!("KWin cursor script unavailable: {e:#}"); + } + Ok(kwin) + } + + async fn snapshot(&self) -> Result { + let _one = self.query.lock().await; + let (tx, rx) = oneshot::channel(); + *self.pending.lock() = Some(tx); + let plugin = format!("capri-list-{}", std::process::id()); + let run = self.load("list", &plugin, LIST_SCRIPT).await; + let answer = match run { + Ok(()) => tokio::time::timeout(Duration::from_secs(3), rx).await.ok().and_then(Result::ok), + Err(e) => return Err(e), + }; + let _ = self.call("/Scripting", "org.kde.kwin.Scripting", "unloadScript", &(plugin.as_str(),)).await; + let text = answer.context("KWin did not answer the window query")?; + Ok(serde_json::from_str(&text)?) + } + + async fn stop(&self) { + let _ = self.call("/Scripting", "org.kde.kwin.Scripting", "unloadScript", &(CURSOR_PLUGIN,)).await; + } +} + +/// i3 IPC request (`"i3-ipc"` + u32 length + u32 type + JSON). +fn i3(path: &str, kind: u32, payload: &str) -> Result { + let mut sock = std::os::unix::net::UnixStream::connect(path)?; + sock.set_read_timeout(Some(Duration::from_secs(3)))?; + let mut msg = b"i3-ipc".to_vec(); + msg.extend((payload.len() as u32).to_le_bytes()); + msg.extend(kind.to_le_bytes()); + msg.extend(payload.as_bytes()); + sock.write_all(&msg)?; + let mut header = [0u8; 14]; + sock.read_exact(&mut header)?; + let len = u32::from_le_bytes(header[6..10].try_into()?) as usize; + if len > 64 << 20 { + bail!("i3 reply too large"); + } + let mut body = vec![0; len]; + sock.read_exact(&mut body)?; + Ok(serde_json::from_slice(&body)?) +} + +fn rect(v: &serde_json::Value) -> Px { + ["x", "y", "width", "height"].map(|k| v[k].as_i64().unwrap_or(0) as i32) +} + +fn i3_snapshot(path: &str, x11: &X11) -> Result { + let workspaces = i3(path, 1, "")?; + let outputs = i3(path, 3, "")?; + let visible: Vec<&serde_json::Value> = workspaces.as_array().into_iter().flatten().filter(|w| w["visible"].as_bool() == Some(true)).collect(); + let displays = outputs + .as_array() + .into_iter() + .flatten() + .filter(|o| o["active"].as_bool() == Some(true)) + .map(|o| { + let work = visible.iter().find(|w| w["output"] == o["name"]).map(|w| rect(&w["rect"])); + DisplayPx { bounds: rect(&o["rect"]), work: work.unwrap_or(rect(&o["rect"])) } + }) + .collect(); + let names: Vec<&str> = visible.iter().filter_map(|w| w["name"].as_str()).collect(); + let tree = i3(path, 4, "")?; + let (mut floating, mut tiled) = (Vec::new(), Vec::new()); + fn walk(node: &serde_json::Value, shown: bool, float: bool, names: &[&str], x11: &X11, floating: &mut Vec, tiled: &mut Vec) { + let shown = if node["type"] == "workspace" { node["name"].as_str().is_some_and(|n| names.contains(&n)) } else { shown }; + if shown && let Some(id) = node["window"].as_u64() { + let win = Win { id: id.to_string(), pid: x11.pid_of(id as u32), title: node["name"].as_str().unwrap_or("").into(), rect: rect(&node["rect"]) }; + if float { floating.push(win) } else { tiled.push(win) } + } + for child in node["nodes"].as_array().into_iter().flatten() { + walk(child, shown, float, names, x11, floating, tiled); + } + for child in node["floating_nodes"].as_array().into_iter().flatten() { + walk(child, shown, true, names, x11, floating, tiled); + } + } + walk(&tree, false, false, &names, x11, &mut floating, &mut tiled); + floating.extend(tiled); + Ok(Snapshot { windows: floating, displays }) +} + +/// Window manager access shared by the UI thread and background queries. +pub struct Desktop { + pub backend: Backend, + pub x11: Arc, + kwin: Option, + i3_path: Option, +} + +impl Desktop { + pub async fn new(x11: Arc) -> Arc { + let kde = std::env::var("XDG_CURRENT_DESKTOP").is_ok_and(|d| d.to_uppercase().contains("KDE")) && std::env::var_os("WAYLAND_DISPLAY").is_some(); + let kwin = if kde { + match Kwin::start().await { + Ok(k) => Some(k), + Err(e) => { + tracing::warn!("KWin scripting unavailable: {e:#}"); + None + } + } + } else { + None + }; + let i3_path = std::env::var("I3SOCK").ok().or_else(|| x11.i3_socket()); + let backend = if kwin.is_some() { Backend::Kwin } else if i3_path.is_some() { Backend::I3 } else { Backend::X11 }; + Arc::new(Self { backend, x11, kwin, i3_path }) + } + + /// Real cursor position: KWin's on KDE Wayland, else X11 `QueryPointer`. + pub fn cursor(&self) -> Option<(i32, i32)> { + self.kwin.as_ref().and_then(|k| *k.cursor.lock()).or_else(|| self.x11.pointer()) + } + + pub async fn snapshot(self: Arc) -> Result { + if let Some(kwin) = &self.kwin { + return kwin.snapshot().await; + } + tokio::task::spawn_blocking(move || { + if let Some(path) = &self.i3_path { + return i3_snapshot(path, &self.x11); + } + let windows = self.x11.client_windows().into_iter().map(|w| Win { id: w.id.to_string(), pid: w.pid, title: w.title, rect: w.rect }).collect(); + let displays = self.x11.displays().into_iter().map(|(bounds, work)| DisplayPx { bounds, work }).collect(); + Ok(Snapshot { windows, displays }) + }) + .await? + } + + /// Unloads the persistent KWin script. + pub async fn stop(&self) { + if let Some(k) = &self.kwin { + k.stop().await; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn kwin_report_parsing() { + let r = Report { cursor: Default::default(), pending: Default::default() }; + r.report("12,-4".into()); + r.report("nonsense".into()); + assert_eq!(*r.cursor.lock(), Some((12, -4))); + let (tx, mut rx) = oneshot::channel(); + *r.pending.lock() = Some(tx); + r.report(r#"{"windows":[{"id":"{a}","title":"T","pid":0,"rect":[1,2,300,200]}],"displays":[{"bounds":[0,0,10,10],"work":[0,0,10,9]}]}"#.into()); + let s: Snapshot = serde_json::from_str(&rx.try_recv().unwrap()).unwrap(); + assert_eq!(s.windows[0].rect, [1, 2, 300, 200]); + assert_eq!(s.candidates().count(), 1); + } +}