From 6ab1eb29d593af69aef18ddcfadd171c07aac2ed Mon Sep 17 00:00:00 2001 From: Irene Knapp Date: Wed, 25 Nov 2026 03:05:16 -0700 Subject: subscribing to i3 events fully works now Force-Push: yes Change-Id: I3d77977e58a8493513afe481f31c923264b5339d --- src/error.rs | 6 ++ src/facility/i3.rs | 179 +++++++++++++++++++++++++++++++++++++++++++---------- 2 files changed, 153 insertions(+), 32 deletions(-) diff --git a/src/error.rs b/src/error.rs index f7ef553..592e91b 100644 --- a/src/error.rs +++ b/src/error.rs @@ -71,6 +71,12 @@ impl From> for Error { } } +impl From for Error { + fn from(error: json_event_parser::JsonSyntaxError) -> Error { + Error(format!("JSON parsing: {}", error)) + } +} + impl From for Error { fn from(error: rustix::io::Errno) -> Error { Error(format!("Unix system-call: {}", error)) diff --git a/src/facility/i3.rs b/src/facility/i3.rs index a7a6991..0d1ad0f 100644 --- a/src/facility/i3.rs +++ b/src/facility/i3.rs @@ -4,6 +4,7 @@ use crate::unix::get_username; use crate::xdg::xdg_runtime_directory; use std::any::Any; +use std::collections::HashMap; use std::mem::size_of; use std::path::{ Path, PathBuf }; use std::slice::{ from_raw_parts, from_raw_parts_mut }; @@ -19,6 +20,7 @@ use async_task::Task; use bitflags::bitflags; use futures_lite::{ AsyncReadExt, AsyncWriteExt, StreamExt }; use futures_lite::io::{ split, ReadHalf, WriteHalf }; +use json_event_parser::{ JsonEvent, SliceJsonParser }; #[allow(unused)] @@ -26,14 +28,16 @@ const MAGIC_NUMBER: &[u8; 6] = b"i3-ipc"; pub struct I3 { - read_socket: Arc>>, + _read_socket: Arc>>, write_socket: Arc>>, - receive_task: Task<()>, + _receive_task: Task<()>, pending_commands: Arc)>>>, + event_subscribers: + Arc>>>>, } bitflags! { - #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] + #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct EventType: u32 { const WORKSPACE = 0x00000001; const OUTPUT = 0x00000002; @@ -60,6 +64,42 @@ impl EventType { _ => Err(Error::custom("Only one event type at a time.")) } } + + fn from_type_code(type_code: u32) -> Result { + match type_code & 0x7fffffff { + 0 => Ok(EventType::WORKSPACE), + 1 => Ok(EventType::OUTPUT), + 2 => Ok(EventType::MODE), + 3 => Ok(EventType::WINDOW), + 4 => Ok(EventType::BARCONFIG_UPDATE), + 5 => Ok(EventType::BINDING), + 6 => Ok(EventType::SHUTDOWN), + 7 => Ok(EventType::TICK), + code => Err(Error::custom(&format!("Unknown event code {}.", code))) + } + } + + fn subscribe_request_body(&self) -> Result { + let mut json = String::new(); + json.push_str("["); + + let mut is_first = true; + for event_type in self.iter() { + if !is_first { + json.push_str(","); + } + + json.push_str(" \""); + json.push_str(event_type.name()?); + json.push_str("\""); + + is_first = false; + } + + json.push_str(" ]"); + + Ok(json) + } } @@ -84,18 +124,30 @@ impl CreatableFacility for I3 { let write_socket = Arc::new(Mutex::new(write_socket)); let pending_commands = Arc::new(Mutex::new(Vec::new())); + let event_subscribers = Arc::new(Mutex::new(HashMap::new())); let receive_task = executor.spawn( receive_loop(Arc::clone(&read_socket), - Arc::clone(&pending_commands))); + Arc::clone(&pending_commands), + Arc::clone(&event_subscribers))); let mut i3 = I3 { - read_socket, write_socket, receive_task, pending_commands + _read_socket: read_socket, + write_socket, + _receive_task: receive_task, + pending_commands, event_subscribers, }; - let (sender, _) = unbounded(); - let response = i3.subscribe(EventType::MODE, sender).await?; - println!("it worked??? {}", response); + let (sender, receiver) = unbounded(); + if i3.subscribe(EventType::MODE, sender).await? { + executor.spawn(async move { + loop { + if let Ok((_, body)) = receiver.recv().await { + println!("it worked??? {}", body); + } + } + }).detach(); + } Ok(i3) } @@ -184,28 +236,33 @@ impl I3 { sender: Sender<(EventType, String)>) -> Result { - let mut request = String::new(); - request.push_str("["); - - let mut is_first = true; - for event_type in event_types.iter() { - if !is_first { - request.push_str(","); - } + { + /* No special ordering constraints with this lock. The rare case is + * just that we already have another subscriber to the same event type, + * and inadvertently deliver an event to the new subscriber before we've + * executed the new subscribe command. That's still correct behavior. + */ + let mut event_subscribers = self.event_subscribers.lock().await; - request.push_str(" \""); - request.push_str(event_type.name()?); - request.push_str("\""); + for event_type in event_types.iter() { + match event_subscribers.get_mut(&event_type) { + Some(senders) => { + senders.push(Sender::clone(&sender)); + } + None => { + let mut senders = Vec::new(); + senders.push(Sender::clone(&sender)); - is_first = false; + event_subscribers.insert(event_type, senders); + } + } + } } - request.push_str(" ]"); - - let result = self.command(2, &request).await?; + let request = event_types.subscribe_request_body()?; + let response = self.command(2, &request).await?; - println!("subscribed? {}", result); - Ok(true) + parse_success_object(response.as_bytes()) } } @@ -293,8 +350,11 @@ async fn try_socket_path(path: &Path) -> Result> { Ok(Some(UnixStream::connect(path).await?)) } -async fn receive_loop(socket: Arc>>, - pending_commands: Arc)>>>) +async fn receive_loop( + socket: Arc>>, + pending_commands: Arc)>>>, + event_subscribers: + Arc>>>>) { loop { /* This function is the only place we read responses or consume pending @@ -307,8 +367,36 @@ async fn receive_loop(socket: Arc>>, match read(Arc::clone(&socket)).await { Ok((type_code, body)) => { if type_code & 0x80000000 != 0 { - let event_code = type_code & 0x7fffffff; - println!("received event code {} body {}", event_code, body); + match EventType::from_type_code(type_code) { + Ok(event_code) => { + /* To avoid tempting fate, we copy the sender list and release the + * lock before dispatching. + */ + let senders = { + let event_subscribers = event_subscribers.lock().await; + + if let Some(senders) = event_subscribers.get(&event_code) { + Vec::clone(&senders) + } else { Vec::new() } + }; + + for sender in senders { + if let Err(error) = sender.send((event_code, + String::clone(&body))).await + { + Into::::into(error).log(); + } + } + + /* Receiving an event nobody subscribes to is harmless, and not + * necessarily indicative of a mistake on our end. We just ignore it, + * there's no reason to spam the logs. + */ + } + Err(error) => { + error.log(); + } + } } else { let mut pending_commands = pending_commands.lock().await; @@ -329,9 +417,9 @@ async fn receive_loop(socket: Arc>>, Into::::into(error).log(); } } else { - Error::custom(&format!( - "Unexpected response from i3 type {} body {}", - type_code, body)).log(); + Error::custom(&format!( + "Unexpected response from i3 type {} body {}", + type_code, body)).log(); } } } @@ -424,3 +512,30 @@ async fn read(socket: Arc>>) Ok((type_code, body)) } + +/* We make no attempt to parse fully general JSON; we exploit our knowledge + * of the format i3 uses. Maybe later. + */ +fn parse_success_object(json: &[u8]) -> Result { + let mut parser = SliceJsonParser::new(json); + + if let JsonEvent::StartObject = parser.parse_next()? { } else { + return Err(Error::custom("Reading i3 JSON, expected object start.")); + } + + if let JsonEvent::ObjectKey(key) = parser.parse_next()? { + if key == "success" { + if let JsonEvent::Boolean(result) = parser.parse_next()? { + /* That's our answer; exit early. */ + return Ok(result); + } else { + return Err(Error::custom("Reading i3 JSON, expected boolean.")); + } + } else { + return Err(Error::custom("Reading i3 JSON, expected \"success\" key.")); + } + } else { + return Err(Error::custom("Reading i3 JSON, expected object key.")); + } +} + -- cgit 1.4.1