diff --git a/komorebi-client/src/lib.rs b/komorebi-client/src/lib.rs index a2eb0a28..98f3c7a7 100644 --- a/komorebi-client/src/lib.rs +++ b/komorebi-client/src/lib.rs @@ -86,7 +86,7 @@ pub use komorebi::workspace::Workspace; pub use komorebi::workspace::WorkspaceGlobals; pub use komorebi::workspace::WorkspaceLayer; -use komorebi::DATA_DIR; +pub use komorebi::DATA_DIR; use std::borrow::Borrow; use std::io::BufReader; @@ -117,7 +117,11 @@ pub struct Connection { impl Connection { pub fn open() -> std::io::Result { let socket = DATA_DIR.join(KOMOREBI); - let stream = UnixStream::connect(socket)?; + + Self::from_stream(UnixStream::connect(socket)?) + } + + fn from_stream(stream: UnixStream) -> std::io::Result { stream.set_write_timeout(Some(Duration::from_secs(1)))?; Ok(Self { stream }) diff --git a/komorebi-for-kde/komorebi-client/src/lib.rs b/komorebi-for-kde/komorebi-client/src/lib.rs index 3b55f8bd..ffff6063 100644 --- a/komorebi-for-kde/komorebi-client/src/lib.rs +++ b/komorebi-for-kde/komorebi-client/src/lib.rs @@ -140,6 +140,45 @@ pub fn send_message(message: &SocketMessage) -> std::io::Result<()> { stream.write_all(serde_json::to_string(message)?.as_bytes()) } +/// A connection to komorebi that messages are written to one after the other, which komorebi +/// handles in the order that they were written, as it does the lines of a batch. Messages sent +/// with [`send_message`] are each on a connection of their own, which komorebi handles on a +/// thread of its own, so two that are sent together can be handled in either order. +pub struct Connection { + stream: UnixStream, +} + +impl Connection { + /// Opens a connection to the daemon's socket. + /// + /// # Errors + /// + /// The daemon's socket cannot be connected to, or written to within a second. + pub fn open() -> std::io::Result { + let socket = DATA_DIR.join(KOMOREBI); + + Self::from_stream(UnixStream::connect(socket)?) + } + + fn from_stream(stream: UnixStream) -> std::io::Result { + stream.set_write_timeout(Some(Duration::from_secs(1)))?; + + Ok(Self { stream }) + } + + /// Writes one message as a line. + /// + /// # Errors + /// + /// The message cannot be written, for example because the daemon let go of the connection. + pub fn send(&mut self, message: &SocketMessage) -> std::io::Result<()> { + let mut line = serde_json::to_string(message)?; + line.push('\n'); + + self.stream.write_all(line.as_bytes()) + } +} + /// Sends several messages to the daemon on one connection, which handles them in order, and does /// not wait for them to be handled ///