//! 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 { 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 { 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 { 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 { 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, } /// 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 }; 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), )); } 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, 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(); result.sort_by_key(|w| (!w.fullscreen, !w.floating, !w.focused)); result } #[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![13, 12, 11]); assert!(l[0].dialog && l[0].floating && l[2].class == "Kate" && l[1].output == "DP-1"); } }