@@ -0,0 +1,337 @@ |
| 1 | +//! i3-compatible IPC server for polybar and other i3 ecosystem tools. |
| 2 | +//! |
| 3 | +//! Implements a subset of i3's IPC protocol: |
| 4 | +//! - GET_WORKSPACES (type 1) |
| 5 | +//! - SUBSCRIBE (type 2) |
| 6 | +//! - GET_OUTPUTS (type 3) |
| 7 | +//! - GET_VERSION (type 7) |
| 8 | +//! |
| 9 | +//! Socket path is set via I3SOCK environment variable. |
| 10 | + |
| 11 | +use std::collections::HashSet; |
| 12 | +use std::io::{BufReader, BufWriter}; |
| 13 | +use std::os::unix::net::{UnixListener, UnixStream}; |
| 14 | +use std::path::PathBuf; |
| 15 | + |
| 16 | +use super::i3_compat::{read_message, write_event, write_response, EventType, I3Message}; |
| 17 | + |
| 18 | +/// Result of reading from a client. |
| 19 | +enum ReadResult { |
| 20 | + Message(I3Message), |
| 21 | + WouldBlock, |
| 22 | + Disconnected, |
| 23 | +} |
| 24 | + |
| 25 | +/// A connected i3 IPC client. |
| 26 | +struct I3Client { |
| 27 | + stream: UnixStream, |
| 28 | + reader: BufReader<UnixStream>, |
| 29 | + writer: BufWriter<UnixStream>, |
| 30 | + subscriptions: HashSet<String>, |
| 31 | +} |
| 32 | + |
| 33 | +impl I3Client { |
| 34 | + fn new(stream: UnixStream) -> std::io::Result<Self> { |
| 35 | + stream.set_nonblocking(true)?; |
| 36 | + let reader = BufReader::new(stream.try_clone()?); |
| 37 | + let writer = BufWriter::new(stream.try_clone()?); |
| 38 | + Ok(Self { |
| 39 | + stream, |
| 40 | + reader, |
| 41 | + writer, |
| 42 | + subscriptions: HashSet::new(), |
| 43 | + }) |
| 44 | + } |
| 45 | + |
| 46 | + fn read_message(&mut self) -> ReadResult { |
| 47 | + match read_message(&mut self.reader) { |
| 48 | + Ok(Some(msg)) => ReadResult::Message(msg), |
| 49 | + Ok(None) => ReadResult::WouldBlock, |
| 50 | + Err(e) => { |
| 51 | + tracing::debug!("i3 IPC client read error: {}", e); |
| 52 | + ReadResult::Disconnected |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + fn send_response(&mut self, msg_type: u32, json: &str) -> std::io::Result<()> { |
| 58 | + write_response(&mut self.writer, msg_type, json) |
| 59 | + } |
| 60 | + |
| 61 | + fn send_event(&mut self, event_type: EventType, json: &str) -> std::io::Result<()> { |
| 62 | + write_event(&mut self.writer, event_type, json) |
| 63 | + } |
| 64 | + |
| 65 | + fn is_subscribed(&self, event: &str) -> bool { |
| 66 | + self.subscriptions.contains(event) |
| 67 | + } |
| 68 | + |
| 69 | + fn subscribe(&mut self, events: Vec<String>) { |
| 70 | + for event in events { |
| 71 | + self.subscriptions.insert(event); |
| 72 | + } |
| 73 | + } |
| 74 | +} |
| 75 | + |
| 76 | +/// i3-compatible IPC server. |
| 77 | +pub struct I3IpcServer { |
| 78 | + listener: UnixListener, |
| 79 | + clients: Vec<I3Client>, |
| 80 | + socket_path: PathBuf, |
| 81 | +} |
| 82 | + |
| 83 | +impl I3IpcServer { |
| 84 | + /// Create a new i3-compatible IPC server. |
| 85 | + /// Sets the I3SOCK environment variable for client discovery. |
| 86 | + pub fn new() -> std::io::Result<Self> { |
| 87 | + let socket_path = Self::socket_path(); |
| 88 | + |
| 89 | + // Remove existing socket |
| 90 | + let _ = std::fs::remove_file(&socket_path); |
| 91 | + |
| 92 | + // Create parent directory if needed |
| 93 | + if let Some(parent) = socket_path.parent() { |
| 94 | + std::fs::create_dir_all(parent)?; |
| 95 | + } |
| 96 | + |
| 97 | + let listener = UnixListener::bind(&socket_path)?; |
| 98 | + listener.set_nonblocking(true)?; |
| 99 | + |
| 100 | + // Set socket permissions to user-only |
| 101 | + #[cfg(unix)] |
| 102 | + { |
| 103 | + use std::os::unix::fs::PermissionsExt; |
| 104 | + std::fs::set_permissions(&socket_path, std::fs::Permissions::from_mode(0o600))?; |
| 105 | + } |
| 106 | + |
| 107 | + // Set I3SOCK environment variable so polybar and other tools can find us |
| 108 | + // SAFETY: We're setting this at startup before any threads are spawned |
| 109 | + unsafe { std::env::set_var("I3SOCK", &socket_path); } |
| 110 | + |
| 111 | + tracing::info!("i3-compatible IPC server listening on {:?}", socket_path); |
| 112 | + tracing::info!("I3SOCK={}", socket_path.display()); |
| 113 | + |
| 114 | + Ok(Self { |
| 115 | + listener, |
| 116 | + clients: Vec::new(), |
| 117 | + socket_path, |
| 118 | + }) |
| 119 | + } |
| 120 | + |
| 121 | + /// Get the socket path. |
| 122 | + fn socket_path() -> PathBuf { |
| 123 | + std::env::var("XDG_RUNTIME_DIR") |
| 124 | + .map(|dir| PathBuf::from(dir).join("gar-i3.sock")) |
| 125 | + .unwrap_or_else(|_| PathBuf::from("/tmp/gar-i3.sock")) |
| 126 | + } |
| 127 | + |
| 128 | + /// Accept new connections (non-blocking). |
| 129 | + pub fn accept_connections(&mut self) { |
| 130 | + loop { |
| 131 | + match self.listener.accept() { |
| 132 | + Ok((stream, _addr)) => { |
| 133 | + tracing::debug!("New i3 IPC client connected"); |
| 134 | + match I3Client::new(stream) { |
| 135 | + Ok(client) => self.clients.push(client), |
| 136 | + Err(e) => tracing::warn!("Failed to setup i3 IPC client: {}", e), |
| 137 | + } |
| 138 | + } |
| 139 | + Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => break, |
| 140 | + Err(e) => { |
| 141 | + tracing::warn!("Failed to accept i3 IPC connection: {}", e); |
| 142 | + break; |
| 143 | + } |
| 144 | + } |
| 145 | + } |
| 146 | + } |
| 147 | + |
| 148 | + /// Process incoming requests from all clients. |
| 149 | + /// Returns a list of (client_index, message) pairs. |
| 150 | + pub fn poll_requests(&mut self) -> Vec<(usize, I3Message)> { |
| 151 | + let mut requests = Vec::new(); |
| 152 | + let mut disconnected = Vec::new(); |
| 153 | + |
| 154 | + for (i, client) in self.clients.iter_mut().enumerate() { |
| 155 | + match client.read_message() { |
| 156 | + ReadResult::Message(msg) => requests.push((i, msg)), |
| 157 | + ReadResult::Disconnected => disconnected.push(i), |
| 158 | + ReadResult::WouldBlock => {} |
| 159 | + } |
| 160 | + } |
| 161 | + |
| 162 | + // Remove disconnected clients (in reverse order to preserve indices) |
| 163 | + for i in disconnected.into_iter().rev() { |
| 164 | + tracing::debug!("i3 IPC client disconnected"); |
| 165 | + self.clients.remove(i); |
| 166 | + } |
| 167 | + |
| 168 | + requests |
| 169 | + } |
| 170 | + |
| 171 | + /// Send a response to a specific client. |
| 172 | + pub fn send_response(&mut self, client_idx: usize, msg_type: u32, json: &str) { |
| 173 | + if let Some(client) = self.clients.get_mut(client_idx) { |
| 174 | + if let Err(e) = client.send_response(msg_type, json) { |
| 175 | + tracing::warn!("Failed to send i3 IPC response: {}", e); |
| 176 | + } |
| 177 | + } |
| 178 | + } |
| 179 | + |
| 180 | + /// Subscribe a client to events. |
| 181 | + pub fn subscribe(&mut self, client_idx: usize, events: Vec<String>) { |
| 182 | + if let Some(client) = self.clients.get_mut(client_idx) { |
| 183 | + client.subscribe(events); |
| 184 | + } |
| 185 | + } |
| 186 | + |
| 187 | + /// Broadcast a workspace event to all subscribed clients. |
| 188 | + pub fn broadcast_workspace_event(&mut self, json: &str) { |
| 189 | + let mut disconnected = Vec::new(); |
| 190 | + |
| 191 | + for (i, client) in self.clients.iter_mut().enumerate() { |
| 192 | + if client.is_subscribed("workspace") { |
| 193 | + if client.send_event(EventType::Workspace, json).is_err() { |
| 194 | + disconnected.push(i); |
| 195 | + } |
| 196 | + } |
| 197 | + } |
| 198 | + |
| 199 | + // Remove failed clients |
| 200 | + for i in disconnected.into_iter().rev() { |
| 201 | + self.clients.remove(i); |
| 202 | + } |
| 203 | + } |
| 204 | + |
| 205 | + /// Broadcast an output event to all subscribed clients. |
| 206 | + pub fn broadcast_output_event(&mut self, json: &str) { |
| 207 | + let mut disconnected = Vec::new(); |
| 208 | + |
| 209 | + for (i, client) in self.clients.iter_mut().enumerate() { |
| 210 | + if client.is_subscribed("output") { |
| 211 | + if client.send_event(EventType::Output, json).is_err() { |
| 212 | + disconnected.push(i); |
| 213 | + } |
| 214 | + } |
| 215 | + } |
| 216 | + |
| 217 | + // Remove failed clients |
| 218 | + for i in disconnected.into_iter().rev() { |
| 219 | + self.clients.remove(i); |
| 220 | + } |
| 221 | + } |
| 222 | + |
| 223 | + /// Get client count. |
| 224 | + pub fn client_count(&self) -> usize { |
| 225 | + self.clients.len() |
| 226 | + } |
| 227 | +} |
| 228 | + |
| 229 | +impl Drop for I3IpcServer { |
| 230 | + fn drop(&mut self) { |
| 231 | + // Clean up socket file |
| 232 | + let _ = std::fs::remove_file(&self.socket_path); |
| 233 | + // Clear I3SOCK env var |
| 234 | + // SAFETY: We're removing this during cleanup, single-threaded context |
| 235 | + unsafe { std::env::remove_var("I3SOCK"); } |
| 236 | + tracing::debug!("i3 IPC server shutdown, socket removed"); |
| 237 | + } |
| 238 | +} |
| 239 | + |
| 240 | +/// Build GET_WORKSPACES response JSON. |
| 241 | +pub fn build_workspaces_json(workspaces: &[WorkspaceInfo]) -> String { |
| 242 | + serde_json::to_string(workspaces).unwrap_or_else(|_| "[]".to_string()) |
| 243 | +} |
| 244 | + |
| 245 | +/// Build GET_OUTPUTS response JSON. |
| 246 | +pub fn build_outputs_json(outputs: &[OutputInfo]) -> String { |
| 247 | + serde_json::to_string(outputs).unwrap_or_else(|_| "[]".to_string()) |
| 248 | +} |
| 249 | + |
| 250 | +/// Build workspace event JSON. |
| 251 | +pub fn build_workspace_event_json(change: &str, current: &WorkspaceInfo, old: Option<&WorkspaceInfo>) -> String { |
| 252 | + let event = WorkspaceEvent { |
| 253 | + change: change.to_string(), |
| 254 | + current: current.clone(), |
| 255 | + old: old.cloned(), |
| 256 | + }; |
| 257 | + serde_json::to_string(&event).unwrap_or_else(|_| r#"{"change":"focus"}"#.to_string()) |
| 258 | +} |
| 259 | + |
| 260 | +/// Build output event JSON. |
| 261 | +pub fn build_output_event_json() -> String { |
| 262 | + r#"{"change":"unspecified"}"#.to_string() |
| 263 | +} |
| 264 | + |
| 265 | +/// Build GET_VERSION response JSON. |
| 266 | +pub fn build_version_json() -> String { |
| 267 | + let version = VersionInfo { |
| 268 | + major: 0, |
| 269 | + minor: 1, |
| 270 | + patch: 0, |
| 271 | + human_readable: "gar 0.1.0 (i3-compat)".to_string(), |
| 272 | + loaded_config_file_name: "~/.config/gar/init.lua".to_string(), |
| 273 | + }; |
| 274 | + serde_json::to_string(&version).unwrap_or_else(|_| r#"{"human_readable":"gar"}"#.to_string()) |
| 275 | +} |
| 276 | + |
| 277 | +/// Build SUBSCRIBE success response JSON. |
| 278 | +pub fn build_subscribe_success_json() -> String { |
| 279 | + r#"{"success":true}"#.to_string() |
| 280 | +} |
| 281 | + |
| 282 | +// ============================================================================ |
| 283 | +// Data structures for JSON serialization (i3-compatible) |
| 284 | +// ============================================================================ |
| 285 | + |
| 286 | +use serde::{Deserialize, Serialize}; |
| 287 | + |
| 288 | +/// Workspace info for GET_WORKSPACES response. |
| 289 | +#[derive(Debug, Clone, Serialize, Deserialize)] |
| 290 | +pub struct WorkspaceInfo { |
| 291 | + pub id: i64, |
| 292 | + pub num: i32, |
| 293 | + pub name: String, |
| 294 | + pub visible: bool, |
| 295 | + pub focused: bool, |
| 296 | + pub urgent: bool, |
| 297 | + pub rect: Rect, |
| 298 | + pub output: String, |
| 299 | +} |
| 300 | + |
| 301 | +/// Output info for GET_OUTPUTS response. |
| 302 | +#[derive(Debug, Clone, Serialize, Deserialize)] |
| 303 | +pub struct OutputInfo { |
| 304 | + pub name: String, |
| 305 | + pub active: bool, |
| 306 | + pub primary: bool, |
| 307 | + pub current_workspace: Option<String>, |
| 308 | + pub rect: Rect, |
| 309 | +} |
| 310 | + |
| 311 | +/// Rectangle for geometry info. |
| 312 | +#[derive(Debug, Clone, Serialize, Deserialize)] |
| 313 | +pub struct Rect { |
| 314 | + pub x: i32, |
| 315 | + pub y: i32, |
| 316 | + pub width: i32, |
| 317 | + pub height: i32, |
| 318 | +} |
| 319 | + |
| 320 | +/// Version info for GET_VERSION response. |
| 321 | +#[derive(Debug, Clone, Serialize, Deserialize)] |
| 322 | +pub struct VersionInfo { |
| 323 | + pub major: i32, |
| 324 | + pub minor: i32, |
| 325 | + pub patch: i32, |
| 326 | + pub human_readable: String, |
| 327 | + pub loaded_config_file_name: String, |
| 328 | +} |
| 329 | + |
| 330 | +/// Workspace event payload. |
| 331 | +#[derive(Debug, Clone, Serialize, Deserialize)] |
| 332 | +pub struct WorkspaceEvent { |
| 333 | + pub change: String, |
| 334 | + pub current: WorkspaceInfo, |
| 335 | + #[serde(skip_serializing_if = "Option::is_none")] |
| 336 | + pub old: Option<WorkspaceInfo>, |
| 337 | +} |