CI / test (push) Has been cancelled
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 <noreply@anthropic.com>
184 lines
7.6 KiB
Rust
184 lines
7.6 KiB
Rust
//! i3 IPC over its Unix socket (frame `"i3-ipc"` + u32 length + u32 type, native endian).
|
|
use std::path::PathBuf;
|
|
|
|
use anyhow::{bail, Context, Result};
|
|
use serde_json::Value;
|
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
|
use tokio::net::UnixStream;
|
|
|
|
pub const RUN_COMMAND: u32 = 0;
|
|
pub const GET_WORKSPACES: u32 = 1;
|
|
pub const SUBSCRIBE: u32 = 2;
|
|
pub const GET_OUTPUTS: u32 = 3;
|
|
pub const GET_TREE: u32 = 4;
|
|
pub const EVENT_WINDOW: u32 = 0x8000_0003;
|
|
pub const EVENT_OUTPUT: u32 = 0x8000_0001;
|
|
const MAX_PAYLOAD: usize = 32 << 20;
|
|
|
|
pub fn encode(kind: u32, payload: &[u8]) -> Vec<u8> {
|
|
let mut out = b"i3-ipc".to_vec();
|
|
out.extend((payload.len() as u32).to_ne_bytes());
|
|
out.extend(kind.to_ne_bytes());
|
|
out.extend(payload);
|
|
out
|
|
}
|
|
|
|
/// Socket path: `$I3SOCK`, else the root window property `I3_SOCKET_PATH`.
|
|
pub fn socket_path() -> Result<PathBuf> {
|
|
if let Some(p) = std::env::var_os("I3SOCK") {
|
|
return Ok(p.into());
|
|
}
|
|
use x11rb::connection::Connection as _;
|
|
use x11rb::protocol::xproto::{AtomEnum, ConnectionExt};
|
|
let (conn, screen) = x11rb::connect(None)?;
|
|
let root = conn.setup().roots[screen].root;
|
|
let atom = conn.intern_atom(true, b"I3_SOCKET_PATH")?.reply()?.atom;
|
|
let reply = conn.get_property(false, root, atom, AtomEnum::ANY, 0, 1024)?.reply()?;
|
|
if reply.value.is_empty() {
|
|
bail!("i3 is unavailable.");
|
|
}
|
|
Ok(PathBuf::from(String::from_utf8_lossy(&reply.value).trim_end_matches('\0').to_string()))
|
|
}
|
|
|
|
pub struct I3 {
|
|
stream: UnixStream,
|
|
}
|
|
|
|
impl I3 {
|
|
pub async fn connect() -> Result<Self> {
|
|
let path = socket_path()?;
|
|
Ok(Self { stream: UnixStream::connect(path).await.context("i3 is unavailable.")? })
|
|
}
|
|
|
|
async fn read(&mut self) -> Result<(u32, Value)> {
|
|
let mut head = [0u8; 14];
|
|
self.stream.read_exact(&mut head).await?;
|
|
if &head[..6] != b"i3-ipc" {
|
|
bail!("Invalid i3 reply");
|
|
}
|
|
let len = u32::from_ne_bytes(head[6..10].try_into().unwrap()) as usize;
|
|
let kind = u32::from_ne_bytes(head[10..14].try_into().unwrap());
|
|
if len > MAX_PAYLOAD {
|
|
bail!("i3 reply too large");
|
|
}
|
|
let mut body = vec![0; len];
|
|
self.stream.read_exact(&mut body).await?;
|
|
Ok((kind, serde_json::from_slice(&body)?))
|
|
}
|
|
|
|
pub async fn request(&mut self, kind: u32, payload: &str) -> Result<Value> {
|
|
self.stream.write_all(&encode(kind, payload.as_bytes())).await?;
|
|
let reply = tokio::time::timeout(std::time::Duration::from_secs(3), self.read()).await.context("i3 is unavailable.")??;
|
|
Ok(reply.1)
|
|
}
|
|
|
|
/// Turns this connection into an event stream (`["window","output"]`...).
|
|
pub async fn subscribe(&mut self, events: &[&str]) -> Result<()> {
|
|
let reply = self.request(SUBSCRIBE, &serde_json::to_string(events)?).await?;
|
|
if reply["success"] != true {
|
|
bail!("i3 refused the subscription");
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
pub async fn next_event(&mut self) -> Result<(u32, Value)> {
|
|
self.read().await
|
|
}
|
|
}
|
|
|
|
/// A leaf container holding an X window (`capri_linux/x11.py` `_collect`).
|
|
#[derive(Clone, Debug, PartialEq)]
|
|
pub struct Leaf {
|
|
pub window: u32,
|
|
pub title: String,
|
|
pub rect: (i32, i32, u32, u32),
|
|
pub fullscreen: bool,
|
|
pub dialog: bool,
|
|
pub class: String,
|
|
pub output: String,
|
|
pub focused: bool,
|
|
pub floating: bool,
|
|
/// Workspace name (`__i3_scratch` for the scratchpad).
|
|
pub workspace: String,
|
|
}
|
|
|
|
pub const SCRATCHPAD: &str = "__i3_scratch";
|
|
|
|
/// Every leaf of the tree in tree order, with its workspace.
|
|
fn collect(tree: &Value) -> Vec<Leaf> {
|
|
fn walk(node: &Value, workspace: &str, output: &str, floating: bool, out: &mut Vec<Leaf>) {
|
|
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: workspace.into(),
|
|
});
|
|
}
|
|
for child in node["nodes"].as_array().into_iter().flatten() {
|
|
walk(child, workspace, output, floating, out);
|
|
}
|
|
for child in node["floating_nodes"].as_array().into_iter().flatten() {
|
|
walk(child, workspace, output, true, out);
|
|
}
|
|
}
|
|
let mut found = Vec::new();
|
|
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<Leaf> {
|
|
let mut result: Vec<Leaf> = 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<Leaf> {
|
|
collect(tree).into_iter().filter(|l| !l.workspace.is_empty() && !shown(l, visible)).collect()
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use serde_json::json;
|
|
|
|
#[test]
|
|
fn codec_and_tree() {
|
|
let frame = encode(GET_TREE, b"");
|
|
assert_eq!(&frame[..6], b"i3-ipc");
|
|
assert_eq!(u32::from_ne_bytes(frame[10..14].try_into().unwrap()), 4);
|
|
let tree = json!({"type":"root","nodes":[{"type":"output","name":"DP-1","nodes":[
|
|
{"type":"workspace","name":"1","nodes":[
|
|
{"type":"con","window":11,"name":"Editor","rect":{"x":0,"y":0,"width":960,"height":1080},"focused":false,"window_properties":{"class":"Kate"}},
|
|
{"type":"con","window":12,"name":"Web","rect":{"x":960,"y":0,"width":960,"height":1080},"focused":true}],
|
|
"floating_nodes":[{"type":"floating_con","nodes":[{"type":"con","window":13,"name":"Dialog","window_type":"dialog","rect":{"x":10,"y":10,"width":100,"height":100}}]}]},
|
|
{"type":"workspace","name":"2","nodes":[{"type":"con","window":14,"name":"Hidden","rect":{"x":0,"y":0,"width":1,"height":1}}]},
|
|
{"type":"workspace","name":"__i3_scratch","nodes":[{"type":"con","window":15,"name":"S","rect":{}}]}]}]});
|
|
let l = leaves(&tree, &["1".into()]);
|
|
assert_eq!(l.iter().map(|w| w.window).collect::<Vec<_>>(), 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<_>>(), vec![(14, "2"), (15, SCRATCHPAD)]);
|
|
}
|
|
}
|