From da6bc6bdbf50da0eeeb4b544395c1b392d228d21 Mon Sep 17 00:00:00 2001 From: Irene Knapp Date: Tue, 24 Nov 2026 19:20:10 -0700 Subject: switch to Send mutices; make the i3 protocol work that was a lot of painful debugging, but not much code in the end Force-Push: yes Change-Id: Ib38842ac3dafb4ab71ee041d0425accee1e9f067 --- Cargo.lock | 1 + Cargo.toml | 1 + src/facility.rs | 11 +++-- src/facility/envsys.rs | 3 +- src/facility/i3.rs | 131 ++++++++++++++++++++++++++++++++++++++++++++++--- src/main.rs | 72 +++++++++++++-------------- src/x/text/line.rs | 6 ++- 7 files changed, 172 insertions(+), 53 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ccf64c0..246104b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -346,6 +346,7 @@ dependencies = [ "async-executor", "async-fs", "async-io", + "async-lock", "async-net", "bitflags", "futures-lite", diff --git a/Cargo.toml b/Cargo.toml index 72f5d3b..2eeffdf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,6 +8,7 @@ edition = "2024" async-channel = "2.0.0" async-fs = "2.0.0" async-io = "2.1.0" +async-lock = "3.0.0" async-net = "2.0.0" libc = "0.2.191" json-event-parser = "0.2.3" diff --git a/src/facility.rs b/src/facility.rs index 56afaf4..182b6bb 100644 --- a/src/facility.rs +++ b/src/facility.rs @@ -3,6 +3,7 @@ use crate::error::Result; use std::any::Any; use std::collections::BTreeMap; +use async_executor::StaticExecutor; use bitflags::bitflags; pub use envsys::EnvSys; @@ -55,7 +56,7 @@ pub trait CreatableFacility: Facility + Sized { * As far as why the compiler can't reach that conclusion on its own and * skip it, we have no specific information. */ - async fn new() -> Result; + async fn new(executor: &'static StaticExecutor) -> Result; /* The only way to coerce to dyn is to return as it! */ fn as_box<'a>(self) -> Box @@ -76,10 +77,12 @@ bitflags! { } impl FacilityType { - pub async fn new(&self) -> Result> { + pub async fn new(&self, executor: &'static StaticExecutor) + -> Result> + { match self { - &FacilityType::ENVSYS => Ok(EnvSys::new().await?.as_box()), - &FacilityType::I3 => Ok(I3::new().await?.as_box()), + &FacilityType::ENVSYS => Ok(EnvSys::new(executor).await?.as_box()), + &FacilityType::I3 => Ok(I3::new(executor).await?.as_box()), _ => todo!() } } diff --git a/src/facility/envsys.rs b/src/facility/envsys.rs index 0f5582b..cb2f004 100644 --- a/src/facility/envsys.rs +++ b/src/facility/envsys.rs @@ -6,6 +6,7 @@ use std::any::Any; use std::ffi::c_void; use std::slice::from_raw_parts; +use async_executor::StaticExecutor; use async_fs::File; use futures_lite::future; use rustix::ioctl::{ ioctl, Opcode, Getter }; @@ -42,7 +43,7 @@ impl Facility for EnvSys { impl CreatableFacility for EnvSys { const FACILITY_TYPE: FacilityType = FacilityType::ENVSYS; - async fn new() -> Result { + async fn new(_executor: &StaticExecutor) -> Result { let sysmon = File::open("/dev/sysmon").await?; let dictionary = get_dictionary(&sysmon).await?; diff --git a/src/facility/i3.rs b/src/facility/i3.rs index c2f9878..141b6d8 100644 --- a/src/facility/i3.rs +++ b/src/facility/i3.rs @@ -4,16 +4,27 @@ use crate::unix::get_username; use crate::xdg::xdg_runtime_directory; use std::any::Any; +use std::mem::size_of; use std::path::{ Path, PathBuf }; +use std::slice::{ from_raw_parts, from_raw_parts_mut }; +use std::sync::Arc; +use async_executor::StaticExecutor; use async_fs::{ metadata, read_dir }; use async_fs::unix::FileTypeExt; +use async_lock::Mutex; use async_net::unix::UnixStream; -use futures_lite::StreamExt; +use futures_lite::{ AsyncReadExt, AsyncWriteExt, StreamExt }; +use futures_lite::io::{ split, ReadHalf, WriteHalf }; + + +#[allow(unused)] +const MAGIC_NUMBER: &[u8; 6] = b"i3-ipc"; pub struct I3 { - socket: UnixStream, + read_socket: Arc>>, + write_socket: Arc>>, } @@ -30,10 +41,20 @@ impl Facility for I3 { impl CreatableFacility for I3 { const FACILITY_TYPE: FacilityType = FacilityType::I3; - async fn new() -> Result { + async fn new(executor: &'static StaticExecutor) -> Result { let socket = Self::find_socket().await?; - Ok(I3 { socket }) + let (read_socket, write_socket) = split(socket); + let read_socket = Arc::new(Mutex::new(read_socket)); + let write_socket = Arc::new(Mutex::new(write_socket)); + + let receive_task = executor.spawn( + I3::receive_loop(Arc::clone(&read_socket))); + receive_task.detach(); + + I3::write(Arc::clone(&write_socket), 2, b"[ \"mode\" ]").await?; + + Ok(I3 { read_socket, write_socket }) } } @@ -176,11 +197,107 @@ impl I3 { * filesystem. If you think about it, that makes sense: Each process that * opens it gets its own send/receive pair. It's not like a pipe. */ - let socket = UnixStream::connect(path).await?; + Ok(Some(UnixStream::connect(path).await?)) + } + + async fn receive_loop(socket: Arc>>) { + loop { + match I3::read(Arc::clone(&socket)).await { + Ok((type_code, body)) => { + let body = String::from_utf8(body).unwrap(); // TODO + + if type_code & 0x80000000 != 0 { + let event_code = type_code & 0x7fffffff; + println!("received event code {} body {}", event_code, body); + } else { + println!("received type code {} body {}", type_code, body); + } + } + Err(error) => { error.log() } + } + } + } + + async fn write(socket: Arc>>, type_code: u32, + body: &[u8]) + -> Result<()> + { + let mut socket = socket.lock().await; + + /* After extensive debugging culminating in socat MITM, it turns out that + * i3 is picky about the header being received in a single packet; if it's + * split, i3 doesn't think it's received a message. + * + * We originally used a repr(C) struct for the header, but the magic + * number is six bytes long, which breaks alignment, so it had to be done + * as two parts, which provoked the misbehavior. Of course we have no + * control over what splitting lower layers of the system might do, but in + * practice as long as we put everything in a single syscall we'll be fine. + * + * So, rather than using a struct, we allocate the whole header as a byte + * array. This is tedious to code, but better for performance anyhow, as + * it's less copying. + * + * We use pointer casts because i3 specifies that it uses the + * architecture's preferred endianness, and this is the easiest way to get + * that. It brings up bad memories of patching other people's programs in + * the 90s to swab their bytes, back when people were in the habit of being + * inadvertently architecture-dependent. Communal trauma notwithstanding, + * in Rust it's about as safe as it can reasonably be. + */ + let length = body.len() as u32; + let mut header: [u8; 14] = [0; 14]; + header[0 .. 6].copy_from_slice(MAGIC_NUMBER); + header[6 .. 10].copy_from_slice(unsafe { + from_raw_parts(&raw const length as *const u8, size_of::()) + }); + header[10 .. 14].copy_from_slice(unsafe { + from_raw_parts(&raw const type_code as *const u8, size_of::()) + }); + + socket.write_all(&header).await?; + socket.write_all(body).await?; + + Ok(()) + } + + /* The two calls to read_exact() in here need to be done without releasing + * the mutex. Since they are async functions, doing so holds the lock across + * threads. That means we are in Send-future-land, and must use the Send + * mutices from async_lock, not the non-Send mutices from std. + * + * This is the entire reason we use async_lock. That's fine, it's worth it, + * it's just also worth knowing what we're getting for it. + */ + async fn read(socket: Arc>>) + -> Result<(u32, Vec)> + { + let mut socket = socket.lock().await; + + /* While it might be nice to use uninitialized memory for this, doing so + * is a giant pain. + */ + let mut header: [u8; 14] = [0; 14]; + socket.read_exact(&mut header).await?; + + if &header[0 .. 6] != MAGIC_NUMBER { + return Err(Error::custom("Received wrong magic number from i3")); + } + + let mut length: u32 = 0; + unsafe { + from_raw_parts_mut(&raw mut length as *mut u8, size_of::()) + }.copy_from_slice(&header[6 .. 10]); + + let mut type_code: u32 = 0; + unsafe { + from_raw_parts_mut(&raw mut type_code as *mut u8, size_of::()) + }.copy_from_slice(&header[10 .. 14]); - println!("Found i3 socket {}", path.display()); + let mut body: Vec = [0].repeat(length as usize); + socket.read_exact(&mut body).await?; - Ok(Some(socket)) + Ok((type_code, body)) } } diff --git a/src/main.rs b/src/main.rs index c1e7323..9223a0b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -22,11 +22,11 @@ use crate::x::text::{ FontGraphicContext, FontList, Line }; use std::borrow::BorrowMut; use std::process::ExitCode; use std::sync::Arc; -use std::sync::Mutex; use std::time::Duration; use async_channel::{ Sender, Receiver }; use async_executor::StaticExecutor; +use async_lock::Mutex; use futures_lite::future; use xcb::{ Xid }; use xcb::x::{ @@ -189,12 +189,12 @@ impl Dock { })?; let fonts = Arc::new(Mutex::new(FontList::new(Arc::clone(&display))?)); - fonts.lock()?.append( + fonts.lock().await.append( "FantasqueSansM Nerd Font Mono:style=Regular:size=18")?; - fonts.lock()?.append("Symbola:size=18")?; - fonts.lock()?.append("Sazanami Mincho:size=18")?; + fonts.lock().await.append("Symbola:size=18")?; + fonts.lock().await.append("Sazanami Mincho:size=18")?; - let primary_font = fonts.lock()?.primary_font()?; + let primary_font = fonts.lock().await.primary_font()?; let font_height = primary_font.ascent() + primary_font.descent(); let vertical_padding = (dock_bounds.height - font_height) / 2; let baseline_position = primary_font.ascent() as i16 @@ -208,13 +208,13 @@ impl Dock { let facilities = Arc::new(Mutex::new(FacilityMap::new())); for facility_type in required_facilities.iter() { - facilities.lock()?.insert(facility_type.clone(), - facility_type.new().await?); + facilities.lock().await.insert(facility_type.clone(), + facility_type.new(&EXECUTOR).await?); } let mut modules = Vec::new(); { - let mut facilities = facilities.lock()?; + let mut facilities = facilities.lock().await; modules.push((Arc::new(Mutex::new(TimeModule::new( facilities.borrow_mut())?.as_box())), @@ -367,7 +367,7 @@ impl Dock { &mut open_parcel, Alignment::Left)?; { - let mut facilities = self.facilities.lock()?; + let mut facilities = self.facilities.lock().await; /* Before we handle any modules, we update all the facilities. This is * the easy way to make sure each facility gets updated exactly once per @@ -380,7 +380,7 @@ impl Dock { for (module, framing) in &self.modules { let text = { - let mut module = module.lock()?; + let mut module = module.lock().await; let text = module.format(facilities.borrow_mut())?; @@ -401,7 +401,7 @@ impl Dock { let mut shortest_duration = None; for (module, _) in &self.modules { - let next_duration = module.lock()?.sleep_duration(); + let next_duration = module.lock().await.sleep_duration(); shortest_duration = shorter_duration(shortest_duration, next_duration); } @@ -545,22 +545,20 @@ async fn event_loop(display: Arc, result@Err(_) => log_and_ignore_errors(result), Ok(xcb::Event::X(xcb::x::Event::Expose(_event))) => { - if let Ok(mut dock) = dock.lock() { - dock.is_visible = true; - } + dock.lock().await.is_visible = true; log_and_ignore_errors(redraw_sender.send(()).await); } Ok(xcb::Event::X(xcb::x::Event::VisibilityNotify(event))) => { - if let Ok(mut dock) = dock.lock() { - if event.window() == dock.window.window_id() { - dock.is_visible = event.state() != Visibility::FullyObscured; + let mut dock = dock.lock().await; - /* We don't initiate a redraw here, instead waiting for the - * redraw event. - */ - } + if event.window() == dock.window.window_id() { + dock.is_visible = event.state() != Visibility::FullyObscured; + + /* We don't initiate a redraw here, instead waiting for the + * redraw event. + */ } } @@ -605,28 +603,24 @@ async fn redraw_loop(dock: Arc>, { loop { if let Ok(()) = redraw_receiver.recv().await { - let duration = match dock.lock() { - Ok(dock) => { - if !dock.is_visible { continue } + let duration = { + let dock = dock.lock().await; - match dock.redraw().await { - Ok(Some(duration)) => { - if let Err(error) = dock.connection().flush() { - Into::::into(error).log(); - } + if !dock.is_visible { continue } - Some(duration) - } - Ok(None) => None, - result@Err(_) => { - log_and_ignore_errors(result); - None + match dock.redraw().await { + Ok(Some(duration)) => { + if let Err(error) = dock.connection().flush() { + Into::::into(error).log(); } + + Some(duration) + } + Ok(None) => None, + result@Err(_) => { + log_and_ignore_errors(result); + None } - } - result@Err(_) => { - log_and_ignore_errors(result); - None } }; diff --git a/src/x/text/line.rs b/src/x/text/line.rs index 5e328ed..5f02742 100644 --- a/src/x/text/line.rs +++ b/src/x/text/line.rs @@ -4,7 +4,9 @@ use crate::layout::Parcel; use crate::x::Color; use crate::x::text::{ Font, FontGraphicContext, FontList, Span }; -use std::sync::{ Arc, Mutex }; +use std::sync::Arc; + +use async_lock::Mutex; pub struct Line { @@ -27,7 +29,7 @@ impl Line { for char in text.chars() { let codepoint = char as u32; - let new_font = &self.fonts.lock()?.find_codepoint(codepoint)?; + let new_font = &self.fonts.lock_blocking().find_codepoint(codepoint)?; if let Some(old_font) = ¤t_span_font { if old_font != new_font { let span = old_font.text_span(¤t_span_text)?; -- cgit 1.4.1