diff --git a/crates/capri-perception/src/kwin.rs b/crates/capri-perception/src/kwin.rs new file mode 100644 index 0000000..49ff5e3 --- /dev/null +++ b/crates/capri-perception/src/kwin.rs @@ -0,0 +1,219 @@ +//! KWin scripting over D-Bus (KDE Plasma 6 Wayland), as `capri_linux/kwin.py` does it: +//! Capri owns `org.capri.bridge.x` with an `org.capri.Report.Report(s)` method, loads a +//! script that calls back with JSON, then unloads it. Persistent scripts (awareness, cursor) +//! keep reporting on the same connection; reports are routed by a tag prefix. +use std::collections::HashMap; +use std::sync::Arc; +use std::time::Duration; + +use anyhow::{anyhow, bail, Context, Result}; +use parking_lot::Mutex; +use serde::Deserialize; +use tokio::sync::mpsc; +use zbus::Connection; + +type Routes = Arc>>>; + +struct Reporter { + routes: Routes, +} + +#[zbus::interface(name = "org.capri.Report")] +impl Reporter { + /// `"\n"`; unknown tags are ignored. + fn report(&self, message: String) { + if let Some((tag, payload)) = message.split_once('\n') + && let Some(tx) = self.routes.lock().get(tag) + { + let _ = tx.send(payload.to_string()); + } + } +} + +pub struct KWin { + conn: Connection, + name: String, + routes: Routes, +} + +/// Top-most first window list + outputs + cursor. +pub const LIST_SCRIPT: &str = r#" +const out = [], active = workspace.activeWindow; +const 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 f = w.frameGeometry, c = w.clientGeometry; + const current = w.onAllDesktops || w.desktops.some(d => d === workspace.currentDesktop); + out.push({id: String(w.internalId), caption: w.caption, pid: w.pid, cls: w.resourceClass, + frame: [f.x, f.y, f.width, f.height], client: [c.x, c.y, c.width, c.height], + active: w === active, minimized: w.minimized, fullScreen: w.fullScreen, modal: w.modal, + dialog: w.dialog, current: current, output: w.output ? w.output.name : ""}); +} +const outputs = workspace.screens.map(o => ({name: o.name, + rect: [o.geometry.x, o.geometry.y, o.geometry.width, o.geometry.height]})); +const p = workspace.cursorPos; +callDBus("%NAME%", "/", "org.capri.Report", "Report", + "%TAG%\n" + JSON.stringify({windows: out, outputs: outputs, cursor: [p.x, p.y]})); +"#; + +/// Activates one window by internal id, bypassing focus-stealing prevention. +pub const ACTIVATE_SCRIPT: &str = r#" +let ok = false; +for (const w of workspace.stackingOrder) { + if (String(w.internalId) !== "%ID%") continue; + if (w.minimized) w.minimized = false; + workspace.activeWindow = w; + ok = workspace.activeWindow === w; +} +callDBus("%NAME%", "/", "org.capri.Report", "Report", "%TAG%\n" + JSON.stringify({ok: ok})); +"#; + +#[derive(Debug, Clone, Deserialize)] +pub struct KWindow { + pub id: String, + #[serde(default)] + pub caption: String, + #[serde(default)] + pub pid: i64, + #[serde(default)] + pub cls: String, + pub frame: [f64; 4], + pub client: [f64; 4], + pub active: bool, + pub minimized: bool, + #[serde(rename = "fullScreen")] + pub full_screen: bool, + pub modal: bool, + pub dialog: bool, + pub current: bool, + #[serde(default)] + pub output: String, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct KOutput { + pub name: String, + pub rect: [f64; 4], +} + +#[derive(Debug, Clone, Deserialize)] +pub struct KState { + pub windows: Vec, + pub outputs: Vec, + pub cursor: [f64; 2], +} + +/// Decimal window id from the KWin UUID (first 15 hex digits), as the Python bridge does. +pub fn numeric_id(internal: &str) -> String { + let hex: String = internal.chars().filter(|c| c.is_ascii_hexdigit()).take(15).collect(); + u64::from_str_radix(&hex, 16).ok().filter(|v| *v > 0).unwrap_or(1).to_string() +} + +fn token() -> String { + uuid::Uuid::new_v4().simple().to_string()[..12].to_string() +} + +impl KWin { + pub async fn connect() -> Result> { + let routes: Routes = Arc::default(); + let name = format!("org.capri.bridge.x{}", token()); + let conn = zbus::connection::Builder::session()? + .name(name.as_str())? + .serve_at("/", Reporter { routes: routes.clone() })? + .build() + .await + .context("KWin is unavailable")?; + Ok(Arc::new(Self { conn, name, routes })) + } + + pub fn connection(&self) -> &Connection { + &self.conn + } + + async fn load(&self, source: &str, tag: &str, plugin: &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-kwin-{}.js", token())); + let script = source.replace("%NAME%", &self.name).replace("%TAG%", tag); + { + use std::io::Write; + use std::os::unix::fs::OpenOptionsExt; + let mut f = std::fs::OpenOptions::new().write(true).create_new(true).mode(0o600).open(&path)?; + f.write_all(script.as_bytes())?; + } + let result = async { + let id: i32 = self + .conn + .call_method(Some("org.kde.KWin"), "/Scripting", Some("org.kde.kwin.Scripting"), "loadScript", &(path.to_string_lossy().as_ref(), plugin)) + .await? + .body() + .deserialize()?; + if id < 0 { + bail!("KWin refused the window query."); + } + self.conn.call_method(Some("org.kde.KWin"), format!("/Scripting/Script{id}").as_str(), Some("org.kde.kwin.Script"), "run", &()).await?; + Ok(()) + } + .await; + // KWin reads the file during loadScript. + let _ = std::fs::remove_file(&path); + result + } + + pub async fn unload(&self, plugin: &str) { + let _ = self.conn.call_method(Some("org.kde.KWin"), "/Scripting", Some("org.kde.kwin.Scripting"), "unloadScript", &(plugin,)).await; + } + + /// Runs a one-shot script and returns its first report (3 s), always unloading it. + pub async fn run_once(&self, source: &str) -> Result { + let tag = token(); + let plugin = format!("capri-bridge-{tag}"); + let (tx, mut rx) = mpsc::unbounded_channel(); + self.routes.lock().insert(tag.clone(), tx); + let result = async { + self.load(source, &tag, &plugin).await?; + tokio::time::timeout(Duration::from_secs(3), rx.recv()).await.ok().flatten().ok_or_else(|| anyhow!("KWin did not answer the window query.")) + } + .await; + self.routes.lock().remove(&tag); + self.unload(&plugin).await; + result + } + + /// Loads a long-lived script (plugin name fixed so a stale copy is replaced). Call `unload` to stop. + pub async fn persistent(&self, plugin: &str, source: &str) -> Result> { + self.unload(plugin).await; + let (tx, rx) = mpsc::unbounded_channel(); + self.routes.lock().insert(plugin.to_string(), tx); + if let Err(e) = self.load(source, plugin, plugin).await { + self.routes.lock().remove(plugin); + return Err(e); + } + Ok(rx) + } + + pub async fn state(&self) -> Result { + Ok(serde_json::from_str(&self.run_once(LIST_SCRIPT).await?)?) + } + + pub async fn activate(&self, internal_id: &str) -> Result { + anyhow::ensure!(internal_id.chars().all(|c| c.is_ascii_hexdigit() || "{}-".contains(c)), "Invalid window id"); + let reply: serde_json::Value = serde_json::from_str(&self.run_once(&ACTIVATE_SCRIPT.replace("%ID%", internal_id)).await?)?; + Ok(reply["ok"] == true) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ids_and_state_shape() { + assert_eq!(numeric_id("{00000000-0000-0000-0000-000000000000}"), "1"); + assert_eq!(numeric_id("{1a2b3c4d-0000-4000-8000-000000000000}"), u64::from_str_radix("1a2b3c4d0000400", 16).unwrap().to_string()); + // Recorded payload shape of LIST_SCRIPT (synthetic values). + let s: KState = serde_json::from_str(r#"{"windows":[{"id":"{a}","caption":"Doc","pid":1234,"cls":"org.kde.kate","frame":[0,0,800,600],"client":[0,30,800,570],"active":true,"minimized":false,"fullScreen":false,"modal":false,"dialog":false,"current":true,"output":"DP-1"}],"outputs":[{"name":"DP-1","rect":[0,0,2560,1440]}],"cursor":[1200,640]}"#).unwrap(); + assert!(s.windows[0].active && s.outputs[0].rect[2] == 2560.0); + assert!(LIST_SCRIPT.contains("%NAME%") && ACTIVATE_SCRIPT.contains("%ID%")); + } +}