From 8413198f425347f44710c8bfdb5540cf0ff290c0 Mon Sep 17 00:00:00 2001 From: nocode Date: Fri, 13 Nov 2026 17:11:12 +0100 Subject: [PATCH] Computer control: reach windows on other workspaces and virtual desktops Opening a web service in a browser whose window sat on another i3 workspace failed with "I could not select the intended window": the window list only covered visible workspaces, so the browser window was never found nor activated. - i3: leaves carry their workspace; hidden_leaves() lists windows on other workspaces and in the scratchpad. - KWin: the list script reports the desktop of non-current windows and activation switches to that desktop first. - Desktop::state(true) now includes those windows (minimized = true, desktop = workspace/desktop name), after the on-screen ones; state(false) is unchanged, so input and capture still only target visible windows. - App window lists given to the model tag them with otherDesktop. Co-Authored-By: Claude Opus 5.5 --- crates/capri-computer/src/apps.rs | 16 +++++- crates/capri-perception/src/i3.rs | 66 +++++++++++++++---------- crates/capri-perception/src/kwin.rs | 8 ++- crates/capri-perception/src/platform.rs | 66 +++++++++++++++++++++---- 4 files changed, 119 insertions(+), 37 deletions(-) diff --git a/crates/capri-computer/src/apps.rs b/crates/capri-computer/src/apps.rs index 911e70c..4624951 100644 --- a/crates/capri-computer/src/apps.rs +++ b/crates/capri-computer/src/apps.rs @@ -418,10 +418,22 @@ impl Catalog { // ------------------------------------------------------------------ catalog actions fn windows_payload(ws: &[DesktopWindow]) -> Value { - Value::Array(ws.iter().map(|w| json!({"windowId": w.id, "untrustedTitle": w.title.chars().take(180).collect::()})).collect()) + Value::Array( + ws.iter() + .map(|w| { + let mut v = json!({"windowId": w.id, "untrustedTitle": w.title.chars().take(180).collect::()}); + if !w.desktop.is_empty() { + // Choosing it switches the owner's screen to that virtual desktop / workspace. + v["otherDesktop"] = json!(w.desktop.chars().take(60).collect::()); + } + v + }) + .collect(), + ) } -/// Visible titled windows owned by the entry (<= 20). +/// Titled windows owned by the entry (<= 20): on screen first, then minimized ones and those on +/// other virtual desktops / i3 workspaces, which activation brings back. pub async fn windows_of(entry: &Entry, windows: &dyn Windows) -> Result> { Ok(windows.state(true).await?.windows.into_iter().filter(|w| !w.title.trim().is_empty() && entry.owns(w)).take(20).collect()) } diff --git a/crates/capri-perception/src/i3.rs b/crates/capri-perception/src/i3.rs index 1f7c1c6..c0bb5dc 100644 --- a/crates/capri-perception/src/i3.rs +++ b/crates/capri-perception/src/i3.rs @@ -98,32 +98,33 @@ pub struct Leaf { pub output: String, pub focused: bool, pub floating: bool, + /// Workspace name (`__i3_scratch` for the scratchpad). + pub workspace: String, } -/// Leaves on visible workspaces (or focused), scratchpad excluded, ordered fullscreen, floating, -/// tiled, focus breaking ties (stacking approximation). -pub fn leaves(tree: &Value, visible: &[String]) -> Vec { - fn walk(node: &Value, workspace: Option<&str>, output: &str, floating: bool, out: &mut Vec<(Leaf, Option)>) { - let workspace = if node["type"] == "workspace" { node["name"].as_str() } else { workspace }; +pub const SCRATCHPAD: &str = "__i3_scratch"; + +/// Every leaf of the tree in tree order, with its workspace. +fn collect(tree: &Value) -> Vec { + fn walk(node: &Value, workspace: &str, output: &str, floating: bool, out: &mut Vec) { + let workspace = if node["type"] == "workspace" { node["name"].as_str().unwrap_or("") } else { workspace }; let output = if node["type"] == "output" { node["name"].as_str().unwrap_or("") } else { output }; if let Some(window) = node["window"].as_u64().filter(|w| *w > 0) && node["type"] == "con" { let r = &node["rect"]; - out.push(( - Leaf { - window: window as u32, - title: node["name"].as_str().unwrap_or("").into(), - rect: (r["x"].as_i64().unwrap_or(0) as i32, r["y"].as_i64().unwrap_or(0) as i32, r["width"].as_u64().unwrap_or(0) as u32, r["height"].as_u64().unwrap_or(0) as u32), - fullscreen: node["fullscreen_mode"].as_i64().unwrap_or(0) != 0, - dialog: node["window_type"] == "dialog", - class: node["window_properties"]["class"].as_str().unwrap_or("").into(), - output: node["output"].as_str().unwrap_or(output).into(), - focused: node["focused"] == true, - floating, - }, - workspace.map(String::from), - )); + out.push(Leaf { + window: window as u32, + title: node["name"].as_str().unwrap_or("").into(), + rect: (r["x"].as_i64().unwrap_or(0) as i32, r["y"].as_i64().unwrap_or(0) as i32, r["width"].as_u64().unwrap_or(0) as u32, r["height"].as_u64().unwrap_or(0) as u32), + fullscreen: node["fullscreen_mode"].as_i64().unwrap_or(0) != 0, + dialog: node["window_type"] == "dialog", + class: node["window_properties"]["class"].as_str().unwrap_or("").into(), + output: node["output"].as_str().unwrap_or(output).into(), + focused: node["focused"] == true, + floating, + workspace: workspace.into(), + }); } for child in node["nodes"].as_array().into_iter().flatten() { walk(child, workspace, output, floating, out); @@ -133,16 +134,29 @@ pub fn leaves(tree: &Value, visible: &[String]) -> Vec { } } let mut found = Vec::new(); - walk(tree, None, "", false, &mut found); - let mut result: Vec = found - .into_iter() - .filter(|(leaf, ws)| ws.as_deref() != Some("__i3_scratch") && (leaf.focused || ws.as_ref().is_some_and(|w| visible.contains(w)))) - .map(|(leaf, _)| leaf) - .collect(); + walk(tree, "", "", false, &mut found); + found +} + +/// A leaf the owner can see: on a visible workspace (or focused), never in the scratchpad. +fn shown(leaf: &Leaf, visible: &[String]) -> bool { + leaf.workspace != SCRATCHPAD && (leaf.focused || visible.contains(&leaf.workspace)) +} + +/// Leaves on visible workspaces (or focused), scratchpad excluded, ordered fullscreen, floating, +/// tiled, focus breaking ties (stacking approximation). +pub fn leaves(tree: &Value, visible: &[String]) -> Vec { + let mut result: Vec = collect(tree).into_iter().filter(|l| shown(l, visible)).collect(); result.sort_by_key(|w| (!w.fullscreen, !w.floating, !w.focused)); result } +/// Leaves on the other workspaces and in the scratchpad, in tree order: `[id=…] focus` switches +/// to their workspace (or shows the scratchpad window). +pub fn hidden_leaves(tree: &Value, visible: &[String]) -> Vec { + collect(tree).into_iter().filter(|l| !l.workspace.is_empty() && !shown(l, visible)).collect() +} + #[cfg(test)] mod tests { use super::*; @@ -163,5 +177,7 @@ mod tests { let l = leaves(&tree, &["1".into()]); assert_eq!(l.iter().map(|w| w.window).collect::>(), vec![13, 12, 11]); assert!(l[0].dialog && l[0].floating && l[2].class == "Kate" && l[1].output == "DP-1"); + let h = hidden_leaves(&tree, &["1".into()]); + assert_eq!(h.iter().map(|w| (w.window, w.workspace.as_str())).collect::>(), vec![(14, "2"), (15, SCRATCHPAD)]); } } diff --git a/crates/capri-perception/src/kwin.rs b/crates/capri-perception/src/kwin.rs index 49ff5e3..f1253a6 100644 --- a/crates/capri-perception/src/kwin.rs +++ b/crates/capri-perception/src/kwin.rs @@ -48,7 +48,8 @@ for (let i = order.length - 1; i >= 0; i--) { 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 : ""}); + dialog: w.dialog, current: current, output: w.output ? w.output.name : "", + desktop: current || !w.desktops.length ? "" : w.desktops[w.desktops.length - 1].name}); } const outputs = workspace.screens.map(o => ({name: o.name, rect: [o.geometry.x, o.geometry.y, o.geometry.width, o.geometry.height]})); @@ -63,6 +64,8 @@ let ok = false; for (const w of workspace.stackingOrder) { if (String(w.internalId) !== "%ID%") continue; if (w.minimized) w.minimized = false; + if (!w.onAllDesktops && w.desktops.length && !w.desktops.some(d => d === workspace.currentDesktop)) + workspace.currentDesktop = w.desktops[w.desktops.length - 1]; workspace.activeWindow = w; ok = workspace.activeWindow === w; } @@ -89,6 +92,9 @@ pub struct KWindow { pub current: bool, #[serde(default)] pub output: String, + /// Name of the window's virtual desktop when it is not the current one. + #[serde(default)] + pub desktop: String, } #[derive(Debug, Clone, Deserialize)] diff --git a/crates/capri-perception/src/platform.rs b/crates/capri-perception/src/platform.rs index e79bdf5..6d0b46a 100644 --- a/crates/capri-perception/src/platform.rs +++ b/crates/capri-perception/src/platform.rs @@ -56,9 +56,14 @@ pub struct DesktopWindow { pub fullscreen: bool, pub modal: bool, pub dialog: bool, + /// Not on screen: minimized, or on another virtual desktop / i3 workspace (see `desktop`). + /// Such windows are only listed with `include_minimized`; activating one brings it back. pub minimized: bool, pub wm_class: String, pub output: String, + /// The virtual desktop / i3 workspace holding the window when it is not a visible one + /// (`scratchpad` for i3's scratchpad); empty for windows on screen. + pub desktop: String, } #[derive(Clone, Debug, PartialEq)] @@ -69,7 +74,8 @@ pub struct Output { #[derive(Clone, Debug, Default)] pub struct DesktopState { - /// Top-most first; current virtual desktop / visible workspaces only. + /// Top-most first; current virtual desktop / visible workspaces only, then (with + /// `include_minimized`) the hidden windows, including those on other desktops. pub windows: Vec, pub outputs: Vec, pub cursor: (i32, i32), @@ -142,9 +148,11 @@ impl Desktop { 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 { + let hidden = if include_minimized { i3::hidden_leaves(&tree, &visible) } else { vec![] }; + let shown = i3::leaves(&tree, &visible).into_iter().map(|l| (l, false)); + let windows = shown + .chain(hidden.into_iter().map(|l| (l, true))) + .map(|(l, hidden)| DesktopWindow { id: l.window.to_string(), native: l.window.to_string(), pid: x.pid_of(l.window), @@ -155,9 +163,14 @@ impl Desktop { fullscreen: l.fullscreen, modal: l.dialog, dialog: l.dialog, - minimized: false, + minimized: hidden, wm_class: l.class, output: l.output, + desktop: match hidden { + false => String::new(), + true if l.workspace == i3::SCRATCHPAD => "scratchpad".into(), + true => l.workspace, + }, }) .collect(); let outputs = outputs @@ -172,7 +185,8 @@ impl Desktop { } } - /// Brings a window to the foreground and confirms it is active. + /// Brings a window to the foreground and confirms it is active, switching to its virtual + /// desktop / i3 workspace (or out of the scratchpad) when it is elsewhere. pub async fn activate(&self, w: &DesktopWindow) -> Result { match self { Self::Kde(k) => { @@ -202,7 +216,7 @@ 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)) + .filter(|w| include_minimized || (w.current && !w.minimized)) .map(|w| DesktopWindow { id: kwin::numeric_id(&w.id), native: w.id, @@ -214,11 +228,15 @@ pub fn from_kwin(s: kwin::KState, include_minimized: bool) -> DesktopState { fullscreen: w.full_screen, modal: w.modal, dialog: w.dialog, - minimized: w.minimized, + minimized: w.minimized || !w.current, wm_class: w.cls, output: w.output, + desktop: if w.current { String::new() } else { w.desktop }, }) - .collect(); + .collect::>(); + // Windows on screen first, as with i3. + let (mut windows, hidden): (Vec<_>, Vec<_>) = windows.into_iter().partition(|w| w.desktop.is_empty()); + windows.extend(hidden); 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) } } @@ -345,4 +363,34 @@ mod tests { assert_eq!(s.desktop_bounds().unwrap(), Rect { x: 0, y: 0, width: 3200, height: 1080 }); assert_eq!(s.active().unwrap().id, "1"); } + + /// Live session check (read-only): `cargo test -p capri-perception live_window_list -- --ignored --nocapture`. + #[tokio::test] + #[ignore] + async fn live_window_list() { + let desktop = Desktop::connect().await.unwrap(); + let visible = desktop.state(false).await.unwrap().windows; + let all = desktop.state(true).await.unwrap().windows; + for w in &all { + println!("{:>12} {:<14} hidden={:<5} desktop={:<10} {}", w.id, w.wm_class, w.minimized, w.desktop, w.title.chars().take(50).collect::()); + } + assert!(visible.iter().all(|w| w.desktop.is_empty() && !w.minimized)); + assert!(all.len() >= visible.len()); + } + + #[test] + fn other_desktops_only_when_hidden_windows_are_wanted() { + let state: kwin::KState = serde_json::from_value(serde_json::json!({ + "windows": [ + {"id": "{b}", "caption": "Firefox", "frame": [0, 0, 10, 10], "client": [0, 0, 10, 10], "active": false, "minimized": false, "fullScreen": false, "modal": false, "dialog": false, "current": false, "desktop": "Desktop 2"}, + {"id": "{a}", "caption": "Kate", "frame": [0, 0, 10, 10], "client": [0, 0, 10, 10], "active": true, "minimized": false, "fullScreen": false, "modal": false, "dialog": false, "current": true} + ], + "outputs": [], "cursor": [0, 0] + })) + .unwrap(); + let shown = from_kwin(state.clone(), false); + assert_eq!(shown.windows.iter().map(|w| w.title.as_str()).collect::>(), ["Kate"]); + let all = from_kwin(state, true); + assert_eq!(all.windows.iter().map(|w| (w.title.as_str(), w.minimized, w.desktop.as_str())).collect::>(), [("Kate", false, ""), ("Firefox", true, "Desktop 2")]); + } }