refactor(client): one komorebi-client package that re-exports the daemon of the target OS

The root komorebi-client package (0.1.42) is the one client: src/lib.rs is a cfg_select! over target_os
that re-exports the module of the platform. The three lib.rs files move to komorebi-client/src/{windows,
linux,macos}.rs (they were made equal in socket code by the previous revision), the KDE integration tests to
tests/linux_{daemon,subscribe}.rs (#![cfg(target_os = "linux")]). The daemon crate of each platform has a
dependency key of its own (cargo allows one path per key) and the module names it (use crate::komorebi_linux
as komorebi). The old komorebi-client-linux and komorebi-client-macos packages stay as shims that include
the moved module, so the old names build until the cutover (the macOS bar and komorebic-macos still use
them). komorebic now depends on the one komorebi-client on all three platforms. The KDE and macOS flakes
build the unified client (-p komorebi-client) and take its manifest, lib.rs and their module in the source
filter; the Windows filter leaves the other platforms' modules and tests out. Windows API for komorebi-bar,
komorebi-gui and komorebic is unchanged.

Gates run: Windows clippy --all-targets -D warnings PASS (client, bar, gui, komorebic); KDE cargo test -p
komorebi-client -p komorebi-client-linux -p komorebic -p komorebi-linux: 775 passed 0 failed (the client
tests and doctests included); cargo check of komorebic-linux and komorebi-client-linux PASS; macOS fake-CC
check --locked of komorebi-client, komorebic, komorebi-client-macos, komorebi-bar-macos, komorebic-macos
--all-targets PASS (type check only); CLI docs oracle byte-identical x3; nix evaluation PASS; by evaluation an
edit of komorebi-client/src/windows.rs changes only Windows derivations, linux.rs only kfde, macos.rs
neither. Not run: nix builds, the e2e (komorebi-client is in the closure of komorebi.exe's users: Windows e2e
OWED), any macOS link or run.
This commit is contained in:
LGUG2Z committed 2026-10-31 12:34:59 -07:00
1 parent e69346e918
commit 19162f3367
15 files changed
+960 -879

No files matched your search

Generated
+4 -2
View File
@@ -3501,7 +3501,11 @@ dependencies = [
name = "komorebi-client"
version = "0.1.42"
dependencies = [
"komorebi-linux",
"komorebi-macos",
"komorebi-themes",
"komorebi-windows",
"parking_lot 0.13.0",
"serde_json_lenient",
"uds_windows",
]
@@ -3835,8 +3839,6 @@ dependencies = [
"dunce",
"fs-tail",
"komorebi-client",
"komorebi-client-linux",
"komorebi-client-macos",
"komorebi-config",
"komorebi-hotkeys",
"komorebi-linux",
+1 -1
View File
@@ -224,7 +224,7 @@
# the other platforms' crates are added as stubs below
!(pkgs.lib.hasInfix "/komorebi-for-kde" path || pkgs.lib.hasInfix "/komorebi-for-mac" path)
# the Linux and macOS files of komorebic are not read when building for Windows
&& !(builtins.match ".*/komorebic/(src/(linux|macos)|tests/(linux|macos)_).*" path != null)
&& !(builtins.match ".*/komorebi(c/(src/(linux|macos)|tests/(linux|macos)_)|-client/(src/(linux|macos)\\.rs|tests/(linux|macos)_))[^/]*.*" path != null)
&& (
(craneLib.filterCargoSources path type)
|| (pkgs.lib.hasInfix "/docs/" path)
+19 -4
View File
@@ -5,12 +5,27 @@ edition = "2024"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
komorebi = { package = "komorebi-windows", path = "../komorebi", default-features = false }
# One dependency key has one path, so the daemon of each platform has a key of its own, and the module of
# the platform names it (`use crate::komorebi_linux as komorebi`).
uds_windows = { workspace = true }
[dependencies]
serde_json = { workspace = true }
[target.'cfg(windows)'.dependencies]
komorebi = { package = "komorebi-windows", path = "../komorebi", default-features = false }
uds_windows = { workspace = true }
[target.'cfg(target_os = "linux")'.dependencies]
komorebi-linux = { package = "komorebi-linux", path = "../komorebi-for-kde/komorebi", default-features = false }
komorebi-themes = { path = "../komorebi-themes" }
[target.'cfg(target_os = "macos")'.dependencies]
komorebi-macos = { package = "komorebi-macos", path = "../komorebi-for-mac/komorebi", default-features = false }
komorebi-themes = { path = "../komorebi-themes" }
[target.'cfg(target_os = "linux")'.dev-dependencies]
parking_lot = "0.13"
[features]
default = ["schemars"]
schemars = ["komorebi/default"]
schemars = ["komorebi/default", "komorebi-linux/default", "komorebi-macos/default"]
+16 -207
View File
@@ -1,215 +1,24 @@
#![warn(clippy::all)]
#![allow(clippy::missing_errors_doc)]
pub use komorebi::AnimationsConfig;
pub use komorebi::AppSpecificConfigurationPath;
pub use komorebi::AspectRatio;
pub use komorebi::BorderColours;
pub use komorebi::Colour;
pub use komorebi::CrossBoundaryBehaviour;
pub use komorebi::GridLayoutOptions;
pub use komorebi::KomorebiTheme;
pub use komorebi::LayoutOptions;
pub use komorebi::MonitorConfig;
pub use komorebi::Notification;
pub use komorebi::NotificationEvent;
pub use komorebi::Placement;
pub use komorebi::PredefinedAspectRatio;
pub use komorebi::Rgb;
pub use komorebi::RuleDebug;
pub use komorebi::ScrollingLayoutOptions;
pub use komorebi::StackbarConfig;
pub use komorebi::StaticConfig;
pub use komorebi::SubscribeOptions;
pub use komorebi::TabsConfig;
pub use komorebi::ThemeOptions;
pub use komorebi::VirtualDesktopNotification;
pub use komorebi::Wallpaper;
pub use komorebi::WindowContainerBehaviour;
pub use komorebi::WindowHandlingBehaviour;
pub use komorebi::WindowsApi;
pub use komorebi::WorkspaceConfig;
pub use komorebi::animation::PerAnimationPrefixConfig;
pub use komorebi::animation::prefix::AnimationPrefix;
pub use komorebi::asc::ApplicationSpecificConfiguration;
pub use komorebi::border_manager::BorderInfo;
pub use komorebi::config_generation::ApplicationConfiguration;
pub use komorebi::config_generation::IdWithIdentifier;
pub use komorebi::config_generation::IdWithIdentifierAndComment;
pub use komorebi::config_generation::MatchingRule;
pub use komorebi::config_generation::MatchingStrategy;
pub use komorebi::container::Container;
pub use komorebi::core::AnimationStyle;
pub use komorebi::core::ApplicationIdentifier;
pub use komorebi::core::Arrangement;
pub use komorebi::core::Axis;
pub use komorebi::core::BorderImplementation;
pub use komorebi::core::BorderStyle;
pub use komorebi::core::Column;
pub use komorebi::core::ColumnSplit;
pub use komorebi::core::ColumnSplitWithCapacity;
pub use komorebi::core::ColumnWidth;
pub use komorebi::core::CustomLayout;
pub use komorebi::core::CycleDirection;
pub use komorebi::core::DefaultLayout;
pub use komorebi::core::Direction;
pub use komorebi::core::FloatingLayerBehaviour;
pub use komorebi::core::FocusFollowsMouseImplementation;
pub use komorebi::core::HidingBehaviour;
pub use komorebi::core::Layout;
pub use komorebi::core::MonocleFocusBehaviour;
pub use komorebi::core::MoveBehaviour;
pub use komorebi::core::OperationBehaviour;
pub use komorebi::core::OperationDirection;
pub use komorebi::core::PanDirection;
pub use komorebi::core::PanGesture;
pub use komorebi::core::PathExt;
pub use komorebi::core::Rect;
pub use komorebi::core::Sizing;
pub use komorebi::core::SocketMessage;
pub use komorebi::core::StackbarLabel;
pub use komorebi::core::StackbarMode;
pub use komorebi::core::StateQuery;
pub use komorebi::core::WindowKind;
pub use komorebi::core::config_generation::ApplicationConfigurationGenerator;
pub use komorebi::core::replace_env_in_path;
pub use komorebi::monitor::Monitor;
pub use komorebi::monitor_reconciliator::MonitorNotification;
pub use komorebi::ring::Ring;
pub use komorebi::splash;
pub use komorebi::state::GlobalState;
pub use komorebi::state::State;
pub use komorebi::win32_display_data;
pub use komorebi::window::Window;
pub use komorebi::window_manager_event::WindowManagerEvent;
pub use komorebi::workspace::Workspace;
pub use komorebi::workspace::WorkspaceGlobals;
pub use komorebi::workspace::WorkspaceLayer;
//! The client of the komorebi daemon, for Windows, KDE Plasma and macOS: one crate, with the module
//! of the target OS re-exported at its root. The functions that talk to the daemon's socket and the
//! types they send are the same in the three modules; what differs is the daemon crate they
//! re-export from and the socket type (`uds_windows` on Windows, `std::os::unix` elsewhere).
pub use komorebi::DATA_DIR;
use std::borrow::Borrow;
use std::io::BufReader;
use std::io::Read;
use std::io::Write;
use std::net::Shutdown;
use std::time::Duration;
pub use uds_windows::UnixListener;
use uds_windows::UnixStream;
const KOMOREBI: &str = "komorebi.sock";
pub fn send_message(message: &SocketMessage) -> std::io::Result<()> {
let socket = DATA_DIR.join(KOMOREBI);
let mut stream = UnixStream::connect(socket)?;
stream.set_write_timeout(Some(Duration::from_secs(1)))?;
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 {
pub fn open() -> std::io::Result<Self> {
let socket = DATA_DIR.join(KOMOREBI);
Self::from_stream(UnixStream::connect(socket)?)
cfg_select! {
target_os = "windows" => {
mod windows;
pub use windows::*;
}
fn from_stream(stream: UnixStream) -> std::io::Result<Self> {
stream.set_write_timeout(Some(Duration::from_secs(1)))?;
Ok(Self { stream })
target_os = "linux" => {
extern crate komorebi_linux;
mod linux;
pub use linux::*;
}
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())
target_os = "macos" => {
extern crate komorebi_macos;
mod macos;
pub use macos::*;
}
}
pub fn send_batch<Q>(messages: impl IntoIterator<Item = Q>) -> std::io::Result<()>
where
Q: Borrow<SocketMessage>,
{
let socket = DATA_DIR.join(KOMOREBI);
let mut stream = UnixStream::connect(socket)?;
stream.set_write_timeout(Some(Duration::from_secs(1)))?;
let msgs = messages.into_iter().fold(String::new(), |mut s, m| {
if let Ok(m_str) = serde_json::to_string(m.borrow()) {
s.push_str(&m_str);
s.push('\n');
}
s
});
stream.write_all(msgs.as_bytes())
}
pub fn send_query(message: &SocketMessage) -> std::io::Result<String> {
let socket = DATA_DIR.join(KOMOREBI);
let mut stream = UnixStream::connect(socket)?;
stream.set_read_timeout(Some(Duration::from_secs(1)))?;
stream.set_write_timeout(Some(Duration::from_secs(1)))?;
stream.write_all(serde_json::to_string(message)?.as_bytes())?;
stream.shutdown(Shutdown::Write)?;
let mut reader = BufReader::new(stream);
let mut response = String::new();
reader.read_to_string(&mut response)?;
Ok(response)
}
pub fn subscribe(name: &str) -> std::io::Result<UnixListener> {
let socket = DATA_DIR.join(name);
match std::fs::remove_file(&socket) {
Ok(()) => {}
Err(error) => match error.kind() {
std::io::ErrorKind::NotFound => {}
_ => {
return Err(error);
}
},
};
let listener = UnixListener::bind(&socket)?;
send_message(&SocketMessage::AddSubscriberSocket(name.to_string()))?;
Ok(listener)
}
pub fn subscribe_with_options(
name: &str,
options: SubscribeOptions,
) -> std::io::Result<UnixListener> {
let socket = DATA_DIR.join(name);
match std::fs::remove_file(&socket) {
Ok(()) => {}
Err(error) => match error.kind() {
std::io::ErrorKind::NotFound => {}
_ => {
return Err(error);
}
},
};
let listener = UnixListener::bind(&socket)?;
send_message(&SocketMessage::AddSubscriberSocketWithOptions(
name.to_string(),
options,
))?;
Ok(listener)
}
+435
View File
@@ -0,0 +1,435 @@
//! A client for the komorebi daemon: it writes [`SocketMessage`]s on the daemon's socket and reads
//! the daemon's answers.
//!
//! The daemon listens on `komorebi.sock` in [`struct@DATA_DIR`], which is
//! `$XDG_RUNTIME_DIR/komorebi` in a desktop session. Every function here opens a new connection
//! and writes each message as one line of JSON. [`send_message`] and [`send_batch`] give
//! orders and read nothing back; [`send_query`] asks a question and returns the answer, which the
//! daemon ends by closing the connection. A function fails with the error of the connection, so a
//! daemon that is not running is an [`std::io::ErrorKind::NotFound`] or a
//! [`std::io::ErrorKind::ConnectionRefused`].
//!
//! [`subscribe`] and [`subscribe_with_options`] make the program a subscriber: they listen on a
//! socket of its own in [`struct@DATA_DIR`], and ask the daemon to send a [`Notification`] to it
//! after each event and each message the window manager handles.
//!
//! The crate also re-exports the types the messages and the answers are made of, so that a client
//! needs nothing else, and [`check`], the checks `komorebic check` runs.
//!
//! # Example
//!
//! The examples on this page answer for the daemon: each one listens on the socket itself, in a
//! runtime directory made for it, before it sends anything.
//!
//! ```rust
//! # use std::io::{BufRead, BufReader, Write};
//! # let runtime = format!("/tmp/komorebi-client-doc-crate-{}", std::process::id());
//! # std::fs::create_dir_all(format!("{runtime}/komorebi"))?;
//! # unsafe { std::env::set_var("XDG_RUNTIME_DIR", &runtime) }; // the socket is in it
//! # let socket = komorebi_client::DATA_DIR.join("komorebi.sock");
//! # let listener = std::os::unix::net::UnixListener::bind(&socket)?;
//! # let daemon = std::thread::spawn(move || -> std::io::Result<String> {
//! # let (mut stream, _) = listener.accept()?;
//! # let mut line = String::new();
//! # BufReader::new(stream.try_clone()?).read_line(&mut line)?;
//! # stream.write_all(b"2")?;
//! # Ok(line)
//! # });
//! use komorebi_client::SocketMessage;
//! use komorebi_client::StateQuery;
//! use komorebi_client::send_query;
//!
//! let workspace = send_query(&SocketMessage::Query(StateQuery::FocusedWorkspaceIndex))?;
//! assert_eq!(workspace, "2");
//!
//! # assert_eq!(
//! # daemon.join().unwrap()?,
//! # r#"{"type":"Query","content":"FocusedWorkspaceIndex"}"#
//! # );
//! # std::fs::remove_dir_all(&runtime)?;
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! `komorebi-client/tests/daemon.rs` sends the same messages to a window manager that listens the
//! way the daemon does, over an in-memory desktop.
use crate::komorebi_linux as komorebi;
pub use komorebi::DATA_DIR;
pub use komorebi::LOG_DIR;
pub use komorebi::Notification;
pub use komorebi::NotificationEvent;
pub use komorebi::animation::AnimationPrefix;
pub use komorebi::check;
pub use komorebi::container::Container;
pub use komorebi::core::ApplicationIdentifier;
pub use komorebi::core::Axis;
pub use komorebi::core::CycleDirection;
pub use komorebi::core::DefaultLayout;
pub use komorebi::core::FocusFollowsMouseImplementation;
pub use komorebi::core::Layout;
pub use komorebi::core::MonocleFocusBehaviour;
pub use komorebi::core::MoveBehaviour;
pub use komorebi::core::OperationBehaviour;
pub use komorebi::core::OperationDirection;
pub use komorebi::core::PanDirection;
pub use komorebi::core::Rect;
pub use komorebi::core::ScrollingCentering;
pub use komorebi::core::Sizing;
pub use komorebi::core::SocketMessage;
pub use komorebi::core::StateQuery;
pub use komorebi::core::SubscribeOptions;
pub use komorebi::core::WindowKind;
pub use komorebi::core::animation::AnimationStyle;
pub use komorebi::core::asc::ApplicationSpecificConfiguration;
pub use komorebi::core::pathext::PathExt;
pub use komorebi::core::pathext::replace_env_in_path;
pub use komorebi::monitor_reconciliator::MonitorNotification;
pub use komorebi::state::State;
pub use komorebi::static_config::StaticConfig;
pub use komorebi::window::Window;
pub use komorebi::workspace::Workspace;
pub use komorebi::workspace::WorkspaceLayer;
pub use komorebi_themes::KomorebiTheme;
pub use komorebi_themes::colour::Colour;
pub use komorebi_themes::colour::Rgb;
use std::borrow::Borrow;
use std::io::BufReader;
use std::io::Read;
use std::io::Write;
use std::net::Shutdown;
use std::os::unix::net::UnixListener;
use std::os::unix::net::UnixStream;
use std::time::Duration;
const KOMOREBI: &str = "komorebi.sock";
/// Sends one message to the daemon, and does not wait for it to be handled
///
/// # Errors
///
/// - The daemon's socket cannot be connected to, for example because the daemon is not running.
/// - The message cannot be written within a second.
///
/// # Example
///
/// ```rust
/// # use std::io::{BufRead, BufReader};
/// # let runtime = format!("/tmp/komorebi-client-doc-message-{}", std::process::id());
/// # std::fs::create_dir_all(format!("{runtime}/komorebi"))?;
/// # unsafe { std::env::set_var("XDG_RUNTIME_DIR", &runtime) }; // the socket is in it
/// # let socket = komorebi_client::DATA_DIR.join("komorebi.sock");
/// # let listener = std::os::unix::net::UnixListener::bind(&socket)?;
/// # let daemon = std::thread::spawn(move || -> std::io::Result<String> {
/// # let (stream, _) = listener.accept()?;
/// # let mut line = String::new();
/// # BufReader::new(stream).read_line(&mut line)?;
/// # Ok(line)
/// # });
/// use komorebi_client::SocketMessage;
/// use komorebi_client::send_message;
///
/// send_message(&SocketMessage::Retile)?;
///
/// # assert_eq!(daemon.join().unwrap()?, r#"{"type":"Retile"}"#);
/// # std::fs::remove_dir_all(&runtime)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn send_message(message: &SocketMessage) -> std::io::Result<()> {
let socket = DATA_DIR.join(KOMOREBI);
let mut stream = UnixStream::connect(socket)?;
stream.set_write_timeout(Some(Duration::from_secs(1)))?;
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<Self> {
let socket = DATA_DIR.join(KOMOREBI);
Self::from_stream(UnixStream::connect(socket)?)
}
fn from_stream(stream: UnixStream) -> std::io::Result<Self> {
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
///
/// # Errors
///
/// The same as [`send_message`].
///
/// # Example
///
/// ```rust
/// # use std::io::{BufRead, BufReader};
/// # let runtime = format!("/tmp/komorebi-client-doc-batch-{}", std::process::id());
/// # std::fs::create_dir_all(format!("{runtime}/komorebi"))?;
/// # unsafe { std::env::set_var("XDG_RUNTIME_DIR", &runtime) }; // the socket is in it
/// # let socket = komorebi_client::DATA_DIR.join("komorebi.sock");
/// # let listener = std::os::unix::net::UnixListener::bind(&socket)?;
/// # let daemon = std::thread::spawn(move || -> std::io::Result<Vec<String>> {
/// # let (stream, _) = listener.accept()?;
/// # BufReader::new(stream).lines().collect()
/// # });
/// use komorebi_client::SocketMessage;
/// use komorebi_client::send_batch;
///
/// send_batch([SocketMessage::Retile, SocketMessage::Stop])?;
///
/// # assert_eq!(daemon.join().unwrap()?, [r#"{"type":"Retile"}"#, r#"{"type":"Stop"}"#]);
/// # std::fs::remove_dir_all(&runtime)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn send_batch<Q>(messages: impl IntoIterator<Item = Q>) -> std::io::Result<()>
where
Q: Borrow<SocketMessage>,
{
let socket = DATA_DIR.join(KOMOREBI);
let mut stream = UnixStream::connect(socket)?;
stream.set_write_timeout(Some(Duration::from_secs(1)))?;
let msgs = messages.into_iter().fold(String::new(), |mut s, m| {
if let Ok(m_str) = serde_json::to_string(m.borrow()) {
s.push_str(&m_str);
s.push('\n');
}
s
});
stream.write_all(msgs.as_bytes())
}
/// Sends one message to the daemon and returns its answer: JSON for
/// [`SocketMessage::State`] and [`SocketMessage::MonitorInformation`], one value as text for
/// [`SocketMessage::Query`], and nothing for a message that is not a question
///
/// # Errors
///
/// - The daemon's socket cannot be connected to, for example because the daemon is not running.
/// - The message cannot be written within a second.
/// - The daemon sends nothing for a second before its answer is complete.
///
/// # Example
///
/// The answer to [`SocketMessage::State`] reads back as a [`State`]:
///
/// ```rust
/// # use std::io::{BufRead, BufReader, Write};
/// # let runtime = format!("/tmp/komorebi-client-doc-query-{}", std::process::id());
/// # std::fs::create_dir_all(format!("{runtime}/komorebi"))?;
/// # unsafe { std::env::set_var("XDG_RUNTIME_DIR", &runtime) }; // the socket is in it
/// # let socket = komorebi_client::DATA_DIR.join("komorebi.sock");
/// # let listener = std::os::unix::net::UnixListener::bind(&socket)?;
/// # let daemon = std::thread::spawn(move || -> std::io::Result<()> {
/// # let (mut stream, _) = listener.accept()?;
/// # BufReader::new(stream.try_clone()?).read_line(&mut String::new())?;
/// # let state = r#"{"monitors":{"elements":[],"focused":0},"monitor_usr_idx_map":{},"is_paused":false,"resize_delta":50,"new_window_behaviour":"Create","float_override":false,"cross_monitor_move_behaviour":"Swap","monocle_focus_behaviour":"NoOp","unmanaged_window_operation_behaviour":"Op","work_area_offset":null,"mouse_follows_focus":true}"#;
/// # stream.write_all(state.as_bytes())
/// # });
/// use komorebi_client::SocketMessage;
/// use komorebi_client::State;
/// use komorebi_client::send_query;
///
/// let state: State = serde_json::from_str(&send_query(&SocketMessage::State)?)?;
/// assert!(state.mouse_follows_focus);
///
/// # daemon.join().unwrap()?;
/// # std::fs::remove_dir_all(&runtime)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn send_query(message: &SocketMessage) -> std::io::Result<String> {
let socket = DATA_DIR.join(KOMOREBI);
let mut stream = UnixStream::connect(socket)?;
stream.set_read_timeout(Some(Duration::from_secs(1)))?;
stream.set_write_timeout(Some(Duration::from_secs(1)))?;
stream.write_all(serde_json::to_string(message)?.as_bytes())?;
stream.shutdown(Shutdown::Write)?;
let mut reader = BufReader::new(stream);
let mut response = String::new();
reader.read_to_string(&mut response)?;
Ok(response)
}
/// Listens on the socket `name` in [`struct@DATA_DIR`], and asks the daemon to send a
/// [`Notification`] to it after each event and each message the window manager handles
///
/// A socket file that is left over at that path is removed first. Each notification comes on a
/// new connection, as JSON, and ends when the daemon closes the connection; the first is the
/// notification of the subscription itself. When the daemon stops, it connects and closes the
/// connection without writing anything.
///
/// A subscriber that the daemon cannot connect to, because its program has exited or its socket
/// was removed, is removed at the next notification, with its socket file. It has to subscribe
/// again: the daemon does not try it again, and does not keep its subscribers when it restarts.
///
/// # Errors
///
/// - The socket file left over at that path cannot be removed.
/// - The socket cannot be bound, for example because [`struct@DATA_DIR`] does not exist.
/// - The subscription cannot be sent, for one of the reasons [`send_message`] gives.
///
/// # Example
///
/// ```rust
/// # use std::io::{BufRead, BufReader, Write};
/// # let runtime = format!("/tmp/komorebi-client-doc-subscribe-{}", std::process::id());
/// # std::fs::create_dir_all(format!("{runtime}/komorebi"))?;
/// # unsafe { std::env::set_var("XDG_RUNTIME_DIR", &runtime) }; // the sockets are in it
/// # let socket = komorebi_client::DATA_DIR.join("komorebi.sock");
/// # let listener = std::os::unix::net::UnixListener::bind(&socket)?;
/// # let daemon = std::thread::spawn(move || -> std::io::Result<String> {
/// # let (stream, _) = listener.accept()?;
/// # let mut message = String::new();
/// # BufReader::new(stream).read_line(&mut message)?;
/// # let subscriber = komorebi_client::DATA_DIR.join("bar.sock");
/// # let state = r#"{"monitors":{"elements":[],"focused":0},"monitor_usr_idx_map":{},"is_paused":false,"resize_delta":50,"new_window_behaviour":"Create","float_override":false,"cross_monitor_move_behaviour":"Swap","monocle_focus_behaviour":"NoOp","unmanaged_window_operation_behaviour":"Op","work_area_offset":null,"mouse_follows_focus":true}"#;
/// # let notification = format!(r#"{{"event":{message},"state":{state}}}"#);
/// # std::os::unix::net::UnixStream::connect(subscriber)?.write_all(notification.as_bytes())?;
/// # Ok(message)
/// # });
/// use std::io::Read;
///
/// use komorebi_client::Notification;
/// use komorebi_client::NotificationEvent;
/// use komorebi_client::SocketMessage;
/// use komorebi_client::subscribe;
///
/// let listener = subscribe("bar.sock")?;
///
/// // the first notification is the one of the subscription
/// let (mut connection, _) = listener.accept()?;
/// let mut json = String::new();
/// connection.read_to_string(&mut json)?;
/// let notification: Notification = serde_json::from_str(&json)?;
/// assert!(matches!(
/// notification.event,
/// NotificationEvent::Socket(SocketMessage::AddSubscriberSocket(name)) if name == "bar.sock"
/// ));
///
/// # assert_eq!(
/// # daemon.join().unwrap()?,
/// # r#"{"type":"AddSubscriberSocket","content":"bar.sock"}"#
/// # );
/// # std::fs::remove_dir_all(&runtime)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn subscribe(name: &str) -> std::io::Result<UnixListener> {
let socket = DATA_DIR.join(name);
match std::fs::remove_file(&socket) {
Ok(()) => {}
Err(error) => match error.kind() {
std::io::ErrorKind::NotFound => {}
_ => {
return Err(error);
}
},
};
let listener = UnixListener::bind(&socket)?;
send_message(&SocketMessage::AddSubscriberSocket(name.to_string()))?;
Ok(listener)
}
/// The same as [`subscribe`], with the [`SubscribeOptions`] the daemon applies to this subscriber
///
/// With `filter_state_changes`, the daemon sends a notification only when the event or the message
/// changed the [`State`], and always when a window is shown, when a subscriber is added, when a
/// theme is set and when the configuration is reloaded.
///
/// # Errors
///
/// The same as [`subscribe`].
///
/// # Example
///
/// ```rust
/// # use std::io::{BufRead, BufReader};
/// # let runtime = format!("/tmp/komorebi-client-doc-options-{}", std::process::id());
/// # std::fs::create_dir_all(format!("{runtime}/komorebi"))?;
/// # unsafe { std::env::set_var("XDG_RUNTIME_DIR", &runtime) }; // the sockets are in it
/// # let socket = komorebi_client::DATA_DIR.join("komorebi.sock");
/// # let listener = std::os::unix::net::UnixListener::bind(&socket)?;
/// # let daemon = std::thread::spawn(move || -> std::io::Result<String> {
/// # let (stream, _) = listener.accept()?;
/// # let mut message = String::new();
/// # BufReader::new(stream).read_line(&mut message)?;
/// # Ok(message)
/// # });
/// use komorebi_client::DATA_DIR;
/// use komorebi_client::SubscribeOptions;
/// use komorebi_client::subscribe_with_options;
///
/// let options = SubscribeOptions {
/// filter_state_changes: true,
/// };
/// let listener = subscribe_with_options("bar.sock", options)?;
///
/// let socket = DATA_DIR.join("bar.sock");
/// assert_eq!(listener.local_addr()?.as_pathname(), Some(socket.as_path()));
///
/// # assert_eq!(
/// # daemon.join().unwrap()?,
/// # r#"{"type":"AddSubscriberSocketWithOptions","content":["bar.sock",{"filter_state_changes":true}]}"#
/// # );
/// # std::fs::remove_dir_all(&runtime)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn subscribe_with_options(
name: &str,
options: SubscribeOptions,
) -> std::io::Result<UnixListener> {
let socket = DATA_DIR.join(name);
match std::fs::remove_file(&socket) {
Ok(()) => {}
Err(error) => match error.kind() {
std::io::ErrorKind::NotFound => {}
_ => {
return Err(error);
}
},
};
let listener = UnixListener::bind(&socket)?;
send_message(&SocketMessage::AddSubscriberSocketWithOptions(
name.to_string(),
options,
))?;
Ok(listener)
}
+227
View File
@@ -0,0 +1,227 @@
use crate::komorebi_macos as komorebi;
pub use komorebi::DATA_DIR;
pub use komorebi::Notification;
pub use komorebi::NotificationEvent;
pub use komorebi::animation::AnimationPrefix;
pub use komorebi::container::Container;
pub use komorebi::core::ApplicationIdentifier;
pub use komorebi::core::Axis;
pub use komorebi::core::CycleDirection;
pub use komorebi::core::DefaultLayout;
pub use komorebi::core::Layout;
pub use komorebi::core::MonocleFocusBehaviour;
pub use komorebi::core::MoveBehaviour;
pub use komorebi::core::OperationBehaviour;
pub use komorebi::core::OperationDirection;
pub use komorebi::core::PanDirection;
pub use komorebi::core::PanGesture;
pub use komorebi::core::Rect;
pub use komorebi::core::Sizing;
pub use komorebi::core::SocketMessage;
pub use komorebi::core::StateQuery;
pub use komorebi::core::SubscribeOptions;
pub use komorebi::core::WindowKind;
pub use komorebi::core::animation::AnimationStyle;
pub use komorebi::core::asc::ApplicationSpecificConfiguration;
pub use komorebi::core::pathext::PathExt;
pub use komorebi::core::pathext::replace_env_in_path;
pub use komorebi::monitor_reconciliator::MonitorNotification;
pub use komorebi::splash;
pub use komorebi::state::State;
pub use komorebi::static_config::StaticConfig;
pub use komorebi::window::Window;
pub use komorebi::workspace::Workspace;
pub use komorebi::workspace::WorkspaceLayer;
pub use komorebi_themes::KomorebiTheme;
pub use komorebi_themes::colour::Colour;
pub use komorebi_themes::colour::Rgb;
use std::borrow::Borrow;
use std::io::BufReader;
use std::io::Read;
use std::io::Write;
use std::net::Shutdown;
use std::os::unix::net::UnixListener;
use std::os::unix::net::UnixStream;
use std::time::Duration;
const KOMOREBI: &str = "komorebi.sock";
pub fn send_message(message: &SocketMessage) -> std::io::Result<()> {
let socket = DATA_DIR.join(KOMOREBI);
let mut stream = UnixStream::connect(socket)?;
stream.set_write_timeout(Some(Duration::from_secs(1)))?;
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 {
pub fn open() -> std::io::Result<Self> {
let socket = DATA_DIR.join(KOMOREBI);
Self::from_stream(UnixStream::connect(socket)?)
}
fn from_stream(stream: UnixStream) -> std::io::Result<Self> {
stream.set_write_timeout(Some(Duration::from_secs(1)))?;
Ok(Self { stream })
}
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())
}
}
pub fn send_batch<Q>(messages: impl IntoIterator<Item = Q>) -> std::io::Result<()>
where
Q: Borrow<SocketMessage>,
{
let socket = DATA_DIR.join(KOMOREBI);
let mut stream = UnixStream::connect(socket)?;
stream.set_write_timeout(Some(Duration::from_secs(1)))?;
let msgs = messages.into_iter().fold(String::new(), |mut s, m| {
if let Ok(m_str) = serde_json::to_string(m.borrow()) {
s.push_str(&m_str);
s.push('\n');
}
s
});
stream.write_all(msgs.as_bytes())
}
pub fn send_query(message: &SocketMessage) -> std::io::Result<String> {
let socket = DATA_DIR.join(KOMOREBI);
let mut stream = UnixStream::connect(socket)?;
stream.set_read_timeout(Some(Duration::from_secs(1)))?;
stream.set_write_timeout(Some(Duration::from_secs(1)))?;
stream.write_all(serde_json::to_string(message)?.as_bytes())?;
stream.shutdown(Shutdown::Write)?;
let mut reader = BufReader::new(stream);
let mut response = String::new();
reader.read_to_string(&mut response)?;
Ok(response)
}
pub fn subscribe(name: &str) -> std::io::Result<UnixListener> {
let socket = DATA_DIR.join(name);
match std::fs::remove_file(&socket) {
Ok(()) => {}
Err(error) => match error.kind() {
std::io::ErrorKind::NotFound => {}
_ => {
return Err(error);
}
},
};
let listener = UnixListener::bind(&socket)?;
send_message(&SocketMessage::AddSubscriberSocket(name.to_string()))?;
Ok(listener)
}
pub fn subscribe_with_options(
name: &str,
options: SubscribeOptions,
) -> std::io::Result<UnixListener> {
let socket = DATA_DIR.join(name);
match std::fs::remove_file(&socket) {
Ok(()) => {}
Err(error) => match error.kind() {
std::io::ErrorKind::NotFound => {}
_ => {
return Err(error);
}
},
};
let listener = UnixListener::bind(&socket)?;
send_message(&SocketMessage::AddSubscriberSocketWithOptions(
name.to_string(),
options,
))?;
Ok(listener)
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::BufRead;
use std::str::FromStr;
#[test]
fn messages_are_written_to_a_connection_a_line_each_in_the_order_that_they_were_sent() {
let (ours, theirs) = UnixStream::pair().unwrap();
let mut connection = Connection::from_stream(ours).unwrap();
connection
.send(&SocketMessage::PanGesture(PanGesture::Begin))
.unwrap();
connection
.send(&SocketMessage::Pan(PanDirection::Right))
.unwrap();
connection
.send(&SocketMessage::PanGesture(PanGesture::Move {
dx: 0.5,
dy: 0.0,
t: 12.0,
}))
.unwrap();
drop(connection);
let lines: Vec<String> = BufReader::new(theirs)
.lines()
.collect::<Result<_, _>>()
.unwrap();
assert_eq!(lines.len(), 3, "one line to a message: {lines:?}");
let messages: Vec<SocketMessage> = lines
.iter()
.map(|line| SocketMessage::from_str(line).unwrap())
.collect();
assert!(matches!(
messages[0],
SocketMessage::PanGesture(PanGesture::Begin)
));
assert!(matches!(
messages[1],
SocketMessage::Pan(PanDirection::Right)
));
assert!(matches!(
messages[2],
SocketMessage::PanGesture(PanGesture::Move { dx, t, .. }) if dx == 0.5 && t == 12.0
));
}
#[test]
fn writing_to_a_connection_that_was_let_go_of_is_an_error() {
let (ours, theirs) = UnixStream::pair().unwrap();
let mut connection = Connection::from_stream(ours).unwrap();
drop(theirs);
assert!(
connection
.send(&SocketMessage::PanGesture(PanGesture::Cancel))
.is_err()
);
}
}
+213
View File
@@ -0,0 +1,213 @@
pub use komorebi::AnimationsConfig;
pub use komorebi::AppSpecificConfigurationPath;
pub use komorebi::AspectRatio;
pub use komorebi::BorderColours;
pub use komorebi::Colour;
pub use komorebi::CrossBoundaryBehaviour;
pub use komorebi::GridLayoutOptions;
pub use komorebi::KomorebiTheme;
pub use komorebi::LayoutOptions;
pub use komorebi::MonitorConfig;
pub use komorebi::Notification;
pub use komorebi::NotificationEvent;
pub use komorebi::Placement;
pub use komorebi::PredefinedAspectRatio;
pub use komorebi::Rgb;
pub use komorebi::RuleDebug;
pub use komorebi::ScrollingLayoutOptions;
pub use komorebi::StackbarConfig;
pub use komorebi::StaticConfig;
pub use komorebi::SubscribeOptions;
pub use komorebi::TabsConfig;
pub use komorebi::ThemeOptions;
pub use komorebi::VirtualDesktopNotification;
pub use komorebi::Wallpaper;
pub use komorebi::WindowContainerBehaviour;
pub use komorebi::WindowHandlingBehaviour;
pub use komorebi::WindowsApi;
pub use komorebi::WorkspaceConfig;
pub use komorebi::animation::PerAnimationPrefixConfig;
pub use komorebi::animation::prefix::AnimationPrefix;
pub use komorebi::asc::ApplicationSpecificConfiguration;
pub use komorebi::border_manager::BorderInfo;
pub use komorebi::config_generation::ApplicationConfiguration;
pub use komorebi::config_generation::IdWithIdentifier;
pub use komorebi::config_generation::IdWithIdentifierAndComment;
pub use komorebi::config_generation::MatchingRule;
pub use komorebi::config_generation::MatchingStrategy;
pub use komorebi::container::Container;
pub use komorebi::core::AnimationStyle;
pub use komorebi::core::ApplicationIdentifier;
pub use komorebi::core::Arrangement;
pub use komorebi::core::Axis;
pub use komorebi::core::BorderImplementation;
pub use komorebi::core::BorderStyle;
pub use komorebi::core::Column;
pub use komorebi::core::ColumnSplit;
pub use komorebi::core::ColumnSplitWithCapacity;
pub use komorebi::core::ColumnWidth;
pub use komorebi::core::CustomLayout;
pub use komorebi::core::CycleDirection;
pub use komorebi::core::DefaultLayout;
pub use komorebi::core::Direction;
pub use komorebi::core::FloatingLayerBehaviour;
pub use komorebi::core::FocusFollowsMouseImplementation;
pub use komorebi::core::HidingBehaviour;
pub use komorebi::core::Layout;
pub use komorebi::core::MonocleFocusBehaviour;
pub use komorebi::core::MoveBehaviour;
pub use komorebi::core::OperationBehaviour;
pub use komorebi::core::OperationDirection;
pub use komorebi::core::PanDirection;
pub use komorebi::core::PanGesture;
pub use komorebi::core::PathExt;
pub use komorebi::core::Rect;
pub use komorebi::core::Sizing;
pub use komorebi::core::SocketMessage;
pub use komorebi::core::StackbarLabel;
pub use komorebi::core::StackbarMode;
pub use komorebi::core::StateQuery;
pub use komorebi::core::WindowKind;
pub use komorebi::core::config_generation::ApplicationConfigurationGenerator;
pub use komorebi::core::replace_env_in_path;
pub use komorebi::monitor::Monitor;
pub use komorebi::monitor_reconciliator::MonitorNotification;
pub use komorebi::ring::Ring;
pub use komorebi::splash;
pub use komorebi::state::GlobalState;
pub use komorebi::state::State;
pub use komorebi::win32_display_data;
pub use komorebi::window::Window;
pub use komorebi::window_manager_event::WindowManagerEvent;
pub use komorebi::workspace::Workspace;
pub use komorebi::workspace::WorkspaceGlobals;
pub use komorebi::workspace::WorkspaceLayer;
pub use komorebi::DATA_DIR;
use std::borrow::Borrow;
use std::io::BufReader;
use std::io::Read;
use std::io::Write;
use std::net::Shutdown;
use std::time::Duration;
pub use uds_windows::UnixListener;
use uds_windows::UnixStream;
const KOMOREBI: &str = "komorebi.sock";
pub fn send_message(message: &SocketMessage) -> std::io::Result<()> {
let socket = DATA_DIR.join(KOMOREBI);
let mut stream = UnixStream::connect(socket)?;
stream.set_write_timeout(Some(Duration::from_secs(1)))?;
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 {
pub fn open() -> std::io::Result<Self> {
let socket = DATA_DIR.join(KOMOREBI);
Self::from_stream(UnixStream::connect(socket)?)
}
fn from_stream(stream: UnixStream) -> std::io::Result<Self> {
stream.set_write_timeout(Some(Duration::from_secs(1)))?;
Ok(Self { stream })
}
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())
}
}
pub fn send_batch<Q>(messages: impl IntoIterator<Item = Q>) -> std::io::Result<()>
where
Q: Borrow<SocketMessage>,
{
let socket = DATA_DIR.join(KOMOREBI);
let mut stream = UnixStream::connect(socket)?;
stream.set_write_timeout(Some(Duration::from_secs(1)))?;
let msgs = messages.into_iter().fold(String::new(), |mut s, m| {
if let Ok(m_str) = serde_json::to_string(m.borrow()) {
s.push_str(&m_str);
s.push('\n');
}
s
});
stream.write_all(msgs.as_bytes())
}
pub fn send_query(message: &SocketMessage) -> std::io::Result<String> {
let socket = DATA_DIR.join(KOMOREBI);
let mut stream = UnixStream::connect(socket)?;
stream.set_read_timeout(Some(Duration::from_secs(1)))?;
stream.set_write_timeout(Some(Duration::from_secs(1)))?;
stream.write_all(serde_json::to_string(message)?.as_bytes())?;
stream.shutdown(Shutdown::Write)?;
let mut reader = BufReader::new(stream);
let mut response = String::new();
reader.read_to_string(&mut response)?;
Ok(response)
}
pub fn subscribe(name: &str) -> std::io::Result<UnixListener> {
let socket = DATA_DIR.join(name);
match std::fs::remove_file(&socket) {
Ok(()) => {}
Err(error) => match error.kind() {
std::io::ErrorKind::NotFound => {}
_ => {
return Err(error);
}
},
};
let listener = UnixListener::bind(&socket)?;
send_message(&SocketMessage::AddSubscriberSocket(name.to_string()))?;
Ok(listener)
}
pub fn subscribe_with_options(
name: &str,
options: SubscribeOptions,
) -> std::io::Result<UnixListener> {
let socket = DATA_DIR.join(name);
match std::fs::remove_file(&socket) {
Ok(()) => {}
Err(error) => match error.kind() {
std::io::ErrorKind::NotFound => {}
_ => {
return Err(error);
}
},
};
let listener = UnixListener::bind(&socket)?;
send_message(&SocketMessage::AddSubscriberSocketWithOptions(
name.to_string(),
options,
))?;
Ok(listener)
}
@@ -1,7 +1,9 @@
#![cfg(target_os = "linux")]
//! The client against a window manager that listens the way the daemon does, with
//! [`listen_for_commands`], over an in-memory desktop with one monitor and two windows.
//!
//! The tests share the window manager, and its socket in a runtime directory of this process.
extern crate komorebi_linux as komorebi;
use komorebi::backend::fake::FakeBackend;
use komorebi::backend::set_backend;
@@ -1,3 +1,4 @@
#![cfg(target_os = "linux")]
//! Subscribers against a window manager that listens the way the daemon does, with
//! [`listen_for_commands`], over an in-memory desktop with one monitor: each subscriber listens on a
//! socket of its own in a runtime directory of this process, subscribes with `komorebi-client`, and
@@ -6,6 +7,7 @@
//! The tests share the window manager, and take turns: every subscriber is sent every
//! notification, so a test that ran at the same time as another would read the other's
//! notifications too. Window ids are 901 and up.
extern crate komorebi_linux as komorebi;
use komorebi::SUBSCRIPTION_SOCKETS;
use komorebi::backend::fake::FakeBackend;
+14 -3
View File
@@ -86,8 +86,19 @@
]
|| pkgs.lib.hasPrefix "komorebic/src/linux" relative
|| pkgs.lib.hasPrefix "komorebic/tests/linux_" relative;
# the unified komorebi-client package: its manifest, lib.rs, the Linux module and tests
komorebiClient =
builtins.elem relative [
"komorebi-client"
"komorebi-client/Cargo.toml"
"komorebi-client/src"
"komorebi-client/src/lib.rs"
"komorebi-client/src/linux.rs"
"komorebi-client/tests"
]
|| pkgs.lib.hasPrefix "komorebi-client/tests/linux_" relative;
in
((rootCrate || rootCrateParent || komorebic) && !(pkgs.lib.hasSuffix "/Cargo.lock" path) || relative == "Cargo.toml" || relative == "Cargo.lock" || inTree)
((rootCrate || rootCrateParent || komorebic || komorebiClient) && !(pkgs.lib.hasSuffix "/Cargo.lock" path) || relative == "Cargo.toml" || relative == "Cargo.lock" || inTree)
&&
# the VM tests (their library, scripts and the states they keep) are not built, so
# editing one does not change the source the daemon is built from
@@ -119,9 +130,10 @@
member:
pkgs.lib.hasPrefix "${platformDir}/" member
|| member == "komorebic"
|| member == "komorebi-client"
|| builtins.any (crate: member == crate || pkgs.lib.hasPrefix "${crate}/" member) rootCrates;
};
packages = "-p komorebi-linux -p komorebic -p komorebi-client-linux -p komorebi-hotkeys";
packages = "-p komorebi-linux -p komorebic -p komorebi-client -p komorebi-hotkeys";
workspaceArgs = {
pname = "komorebi-workspace";
version = (builtins.fromTOML (builtins.readFile ./komorebi/Cargo.toml)).package.version;
@@ -341,7 +353,6 @@
"--workspace "
+ lib.concatMapStringsSep " " (p: "--exclude ${p}") [
"komorebi-windows"
"komorebi-client"
"komorebi-gui"
"komorebic-no-console"
"komorebi-bar"
+6 -430
View File
@@ -1,433 +1,9 @@
//! A client for the komorebi daemon: it writes [`SocketMessage`]s on the daemon's socket and reads
//! the daemon's answers.
//!
//! The daemon listens on `komorebi.sock` in [`struct@DATA_DIR`], which is
//! `$XDG_RUNTIME_DIR/komorebi` in a desktop session. Every function here opens a new connection
//! and writes each message as one line of JSON. [`send_message`] and [`send_batch`] give
//! orders and read nothing back; [`send_query`] asks a question and returns the answer, which the
//! daemon ends by closing the connection. A function fails with the error of the connection, so a
//! daemon that is not running is an [`std::io::ErrorKind::NotFound`] or a
//! [`std::io::ErrorKind::ConnectionRefused`].
//!
//! [`subscribe`] and [`subscribe_with_options`] make the program a subscriber: they listen on a
//! socket of its own in [`struct@DATA_DIR`], and ask the daemon to send a [`Notification`] to it
//! after each event and each message the window manager handles.
//!
//! The crate also re-exports the types the messages and the answers are made of, so that a client
//! needs nothing else, and [`check`], the checks `komorebic check` runs.
//!
//! # Example
//!
//! The examples on this page answer for the daemon: each one listens on the socket itself, in a
//! runtime directory made for it, before it sends anything.
//!
//! ```rust
//! # use std::io::{BufRead, BufReader, Write};
//! # let runtime = format!("/tmp/komorebi-client-doc-crate-{}", std::process::id());
//! # std::fs::create_dir_all(format!("{runtime}/komorebi"))?;
//! # unsafe { std::env::set_var("XDG_RUNTIME_DIR", &runtime) }; // the socket is in it
//! # let socket = komorebi_client::DATA_DIR.join("komorebi.sock");
//! # let listener = std::os::unix::net::UnixListener::bind(&socket)?;
//! # let daemon = std::thread::spawn(move || -> std::io::Result<String> {
//! # let (mut stream, _) = listener.accept()?;
//! # let mut line = String::new();
//! # BufReader::new(stream.try_clone()?).read_line(&mut line)?;
//! # stream.write_all(b"2")?;
//! # Ok(line)
//! # });
//! use komorebi_client::SocketMessage;
//! use komorebi_client::StateQuery;
//! use komorebi_client::send_query;
//!
//! let workspace = send_query(&SocketMessage::Query(StateQuery::FocusedWorkspaceIndex))?;
//! assert_eq!(workspace, "2");
//!
//! # assert_eq!(
//! # daemon.join().unwrap()?,
//! # r#"{"type":"Query","content":"FocusedWorkspaceIndex"}"#
//! # );
//! # std::fs::remove_dir_all(&runtime)?;
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! `komorebi-client/tests/daemon.rs` sends the same messages to a window manager that listens the
//! way the daemon does, over an in-memory desktop.
//! `komorebi-client-linux`: the client of the unified `komorebi-client` package, kept under its old
//! package name until the cutover. The code is in `komorebi-client/src/linux.rs`.
pub use komorebi::DATA_DIR;
pub use komorebi::LOG_DIR;
pub use komorebi::Notification;
pub use komorebi::NotificationEvent;
pub use komorebi::animation::AnimationPrefix;
pub use komorebi::check;
pub use komorebi::container::Container;
pub use komorebi::core::ApplicationIdentifier;
pub use komorebi::core::Axis;
pub use komorebi::core::CycleDirection;
pub use komorebi::core::DefaultLayout;
pub use komorebi::core::FocusFollowsMouseImplementation;
pub use komorebi::core::Layout;
pub use komorebi::core::MonocleFocusBehaviour;
pub use komorebi::core::MoveBehaviour;
pub use komorebi::core::OperationBehaviour;
pub use komorebi::core::OperationDirection;
pub use komorebi::core::PanDirection;
pub use komorebi::core::Rect;
pub use komorebi::core::ScrollingCentering;
pub use komorebi::core::Sizing;
pub use komorebi::core::SocketMessage;
pub use komorebi::core::StateQuery;
pub use komorebi::core::SubscribeOptions;
pub use komorebi::core::WindowKind;
pub use komorebi::core::animation::AnimationStyle;
pub use komorebi::core::asc::ApplicationSpecificConfiguration;
pub use komorebi::core::pathext::PathExt;
pub use komorebi::core::pathext::replace_env_in_path;
pub use komorebi::monitor_reconciliator::MonitorNotification;
pub use komorebi::state::State;
pub use komorebi::static_config::StaticConfig;
pub use komorebi::window::Window;
pub use komorebi::workspace::Workspace;
pub use komorebi::workspace::WorkspaceLayer;
pub use komorebi_themes::KomorebiTheme;
pub use komorebi_themes::colour::Colour;
pub use komorebi_themes::colour::Rgb;
use std::borrow::Borrow;
use std::io::BufReader;
use std::io::Read;
use std::io::Write;
use std::net::Shutdown;
use std::os::unix::net::UnixListener;
use std::os::unix::net::UnixStream;
use std::time::Duration;
extern crate komorebi as komorebi_linux;
const KOMOREBI: &str = "komorebi.sock";
#[path = "../../../komorebi-client/src/linux.rs"]
mod platform;
/// Sends one message to the daemon, and does not wait for it to be handled
///
/// # Errors
///
/// - The daemon's socket cannot be connected to, for example because the daemon is not running.
/// - The message cannot be written within a second.
///
/// # Example
///
/// ```rust
/// # use std::io::{BufRead, BufReader};
/// # let runtime = format!("/tmp/komorebi-client-doc-message-{}", std::process::id());
/// # std::fs::create_dir_all(format!("{runtime}/komorebi"))?;
/// # unsafe { std::env::set_var("XDG_RUNTIME_DIR", &runtime) }; // the socket is in it
/// # let socket = komorebi_client::DATA_DIR.join("komorebi.sock");
/// # let listener = std::os::unix::net::UnixListener::bind(&socket)?;
/// # let daemon = std::thread::spawn(move || -> std::io::Result<String> {
/// # let (stream, _) = listener.accept()?;
/// # let mut line = String::new();
/// # BufReader::new(stream).read_line(&mut line)?;
/// # Ok(line)
/// # });
/// use komorebi_client::SocketMessage;
/// use komorebi_client::send_message;
///
/// send_message(&SocketMessage::Retile)?;
///
/// # assert_eq!(daemon.join().unwrap()?, r#"{"type":"Retile"}"#);
/// # std::fs::remove_dir_all(&runtime)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn send_message(message: &SocketMessage) -> std::io::Result<()> {
let socket = DATA_DIR.join(KOMOREBI);
let mut stream = UnixStream::connect(socket)?;
stream.set_write_timeout(Some(Duration::from_secs(1)))?;
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<Self> {
let socket = DATA_DIR.join(KOMOREBI);
Self::from_stream(UnixStream::connect(socket)?)
}
fn from_stream(stream: UnixStream) -> std::io::Result<Self> {
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
///
/// # Errors
///
/// The same as [`send_message`].
///
/// # Example
///
/// ```rust
/// # use std::io::{BufRead, BufReader};
/// # let runtime = format!("/tmp/komorebi-client-doc-batch-{}", std::process::id());
/// # std::fs::create_dir_all(format!("{runtime}/komorebi"))?;
/// # unsafe { std::env::set_var("XDG_RUNTIME_DIR", &runtime) }; // the socket is in it
/// # let socket = komorebi_client::DATA_DIR.join("komorebi.sock");
/// # let listener = std::os::unix::net::UnixListener::bind(&socket)?;
/// # let daemon = std::thread::spawn(move || -> std::io::Result<Vec<String>> {
/// # let (stream, _) = listener.accept()?;
/// # BufReader::new(stream).lines().collect()
/// # });
/// use komorebi_client::SocketMessage;
/// use komorebi_client::send_batch;
///
/// send_batch([SocketMessage::Retile, SocketMessage::Stop])?;
///
/// # assert_eq!(daemon.join().unwrap()?, [r#"{"type":"Retile"}"#, r#"{"type":"Stop"}"#]);
/// # std::fs::remove_dir_all(&runtime)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn send_batch<Q>(messages: impl IntoIterator<Item = Q>) -> std::io::Result<()>
where
Q: Borrow<SocketMessage>,
{
let socket = DATA_DIR.join(KOMOREBI);
let mut stream = UnixStream::connect(socket)?;
stream.set_write_timeout(Some(Duration::from_secs(1)))?;
let msgs = messages.into_iter().fold(String::new(), |mut s, m| {
if let Ok(m_str) = serde_json::to_string(m.borrow()) {
s.push_str(&m_str);
s.push('\n');
}
s
});
stream.write_all(msgs.as_bytes())
}
/// Sends one message to the daemon and returns its answer: JSON for
/// [`SocketMessage::State`] and [`SocketMessage::MonitorInformation`], one value as text for
/// [`SocketMessage::Query`], and nothing for a message that is not a question
///
/// # Errors
///
/// - The daemon's socket cannot be connected to, for example because the daemon is not running.
/// - The message cannot be written within a second.
/// - The daemon sends nothing for a second before its answer is complete.
///
/// # Example
///
/// The answer to [`SocketMessage::State`] reads back as a [`State`]:
///
/// ```rust
/// # use std::io::{BufRead, BufReader, Write};
/// # let runtime = format!("/tmp/komorebi-client-doc-query-{}", std::process::id());
/// # std::fs::create_dir_all(format!("{runtime}/komorebi"))?;
/// # unsafe { std::env::set_var("XDG_RUNTIME_DIR", &runtime) }; // the socket is in it
/// # let socket = komorebi_client::DATA_DIR.join("komorebi.sock");
/// # let listener = std::os::unix::net::UnixListener::bind(&socket)?;
/// # let daemon = std::thread::spawn(move || -> std::io::Result<()> {
/// # let (mut stream, _) = listener.accept()?;
/// # BufReader::new(stream.try_clone()?).read_line(&mut String::new())?;
/// # let state = r#"{"monitors":{"elements":[],"focused":0},"monitor_usr_idx_map":{},"is_paused":false,"resize_delta":50,"new_window_behaviour":"Create","float_override":false,"cross_monitor_move_behaviour":"Swap","monocle_focus_behaviour":"NoOp","unmanaged_window_operation_behaviour":"Op","work_area_offset":null,"mouse_follows_focus":true}"#;
/// # stream.write_all(state.as_bytes())
/// # });
/// use komorebi_client::SocketMessage;
/// use komorebi_client::State;
/// use komorebi_client::send_query;
///
/// let state: State = serde_json::from_str(&send_query(&SocketMessage::State)?)?;
/// assert!(state.mouse_follows_focus);
///
/// # daemon.join().unwrap()?;
/// # std::fs::remove_dir_all(&runtime)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn send_query(message: &SocketMessage) -> std::io::Result<String> {
let socket = DATA_DIR.join(KOMOREBI);
let mut stream = UnixStream::connect(socket)?;
stream.set_read_timeout(Some(Duration::from_secs(1)))?;
stream.set_write_timeout(Some(Duration::from_secs(1)))?;
stream.write_all(serde_json::to_string(message)?.as_bytes())?;
stream.shutdown(Shutdown::Write)?;
let mut reader = BufReader::new(stream);
let mut response = String::new();
reader.read_to_string(&mut response)?;
Ok(response)
}
/// Listens on the socket `name` in [`struct@DATA_DIR`], and asks the daemon to send a
/// [`Notification`] to it after each event and each message the window manager handles
///
/// A socket file that is left over at that path is removed first. Each notification comes on a
/// new connection, as JSON, and ends when the daemon closes the connection; the first is the
/// notification of the subscription itself. When the daemon stops, it connects and closes the
/// connection without writing anything.
///
/// A subscriber that the daemon cannot connect to, because its program has exited or its socket
/// was removed, is removed at the next notification, with its socket file. It has to subscribe
/// again: the daemon does not try it again, and does not keep its subscribers when it restarts.
///
/// # Errors
///
/// - The socket file left over at that path cannot be removed.
/// - The socket cannot be bound, for example because [`struct@DATA_DIR`] does not exist.
/// - The subscription cannot be sent, for one of the reasons [`send_message`] gives.
///
/// # Example
///
/// ```rust
/// # use std::io::{BufRead, BufReader, Write};
/// # let runtime = format!("/tmp/komorebi-client-doc-subscribe-{}", std::process::id());
/// # std::fs::create_dir_all(format!("{runtime}/komorebi"))?;
/// # unsafe { std::env::set_var("XDG_RUNTIME_DIR", &runtime) }; // the sockets are in it
/// # let socket = komorebi_client::DATA_DIR.join("komorebi.sock");
/// # let listener = std::os::unix::net::UnixListener::bind(&socket)?;
/// # let daemon = std::thread::spawn(move || -> std::io::Result<String> {
/// # let (stream, _) = listener.accept()?;
/// # let mut message = String::new();
/// # BufReader::new(stream).read_line(&mut message)?;
/// # let subscriber = komorebi_client::DATA_DIR.join("bar.sock");
/// # let state = r#"{"monitors":{"elements":[],"focused":0},"monitor_usr_idx_map":{},"is_paused":false,"resize_delta":50,"new_window_behaviour":"Create","float_override":false,"cross_monitor_move_behaviour":"Swap","monocle_focus_behaviour":"NoOp","unmanaged_window_operation_behaviour":"Op","work_area_offset":null,"mouse_follows_focus":true}"#;
/// # let notification = format!(r#"{{"event":{message},"state":{state}}}"#);
/// # std::os::unix::net::UnixStream::connect(subscriber)?.write_all(notification.as_bytes())?;
/// # Ok(message)
/// # });
/// use std::io::Read;
///
/// use komorebi_client::Notification;
/// use komorebi_client::NotificationEvent;
/// use komorebi_client::SocketMessage;
/// use komorebi_client::subscribe;
///
/// let listener = subscribe("bar.sock")?;
///
/// // the first notification is the one of the subscription
/// let (mut connection, _) = listener.accept()?;
/// let mut json = String::new();
/// connection.read_to_string(&mut json)?;
/// let notification: Notification = serde_json::from_str(&json)?;
/// assert!(matches!(
/// notification.event,
/// NotificationEvent::Socket(SocketMessage::AddSubscriberSocket(name)) if name == "bar.sock"
/// ));
///
/// # assert_eq!(
/// # daemon.join().unwrap()?,
/// # r#"{"type":"AddSubscriberSocket","content":"bar.sock"}"#
/// # );
/// # std::fs::remove_dir_all(&runtime)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn subscribe(name: &str) -> std::io::Result<UnixListener> {
let socket = DATA_DIR.join(name);
match std::fs::remove_file(&socket) {
Ok(()) => {}
Err(error) => match error.kind() {
std::io::ErrorKind::NotFound => {}
_ => {
return Err(error);
}
},
};
let listener = UnixListener::bind(&socket)?;
send_message(&SocketMessage::AddSubscriberSocket(name.to_string()))?;
Ok(listener)
}
/// The same as [`subscribe`], with the [`SubscribeOptions`] the daemon applies to this subscriber
///
/// With `filter_state_changes`, the daemon sends a notification only when the event or the message
/// changed the [`State`], and always when a window is shown, when a subscriber is added, when a
/// theme is set and when the configuration is reloaded.
///
/// # Errors
///
/// The same as [`subscribe`].
///
/// # Example
///
/// ```rust
/// # use std::io::{BufRead, BufReader};
/// # let runtime = format!("/tmp/komorebi-client-doc-options-{}", std::process::id());
/// # std::fs::create_dir_all(format!("{runtime}/komorebi"))?;
/// # unsafe { std::env::set_var("XDG_RUNTIME_DIR", &runtime) }; // the sockets are in it
/// # let socket = komorebi_client::DATA_DIR.join("komorebi.sock");
/// # let listener = std::os::unix::net::UnixListener::bind(&socket)?;
/// # let daemon = std::thread::spawn(move || -> std::io::Result<String> {
/// # let (stream, _) = listener.accept()?;
/// # let mut message = String::new();
/// # BufReader::new(stream).read_line(&mut message)?;
/// # Ok(message)
/// # });
/// use komorebi_client::DATA_DIR;
/// use komorebi_client::SubscribeOptions;
/// use komorebi_client::subscribe_with_options;
///
/// let options = SubscribeOptions {
/// filter_state_changes: true,
/// };
/// let listener = subscribe_with_options("bar.sock", options)?;
///
/// let socket = DATA_DIR.join("bar.sock");
/// assert_eq!(listener.local_addr()?.as_pathname(), Some(socket.as_path()));
///
/// # assert_eq!(
/// # daemon.join().unwrap()?,
/// # r#"{"type":"AddSubscriberSocketWithOptions","content":["bar.sock",{"filter_state_changes":true}]}"#
/// # );
/// # std::fs::remove_dir_all(&runtime)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn subscribe_with_options(
name: &str,
options: SubscribeOptions,
) -> std::io::Result<UnixListener> {
let socket = DATA_DIR.join(name);
match std::fs::remove_file(&socket) {
Ok(()) => {}
Err(error) => match error.kind() {
std::io::ErrorKind::NotFound => {}
_ => {
return Err(error);
}
},
};
let listener = UnixListener::bind(&socket)?;
send_message(&SocketMessage::AddSubscriberSocketWithOptions(
name.to_string(),
options,
))?;
Ok(listener)
}
pub use platform::*;
+14 -3
View File
@@ -72,8 +72,19 @@
"komorebic/src/main.rs"
]
|| pkgs.lib.hasPrefix "komorebic/src/macos" relative;
# the unified komorebi-client package: its manifest, lib.rs and the module of this platform
komorebiClient =
builtins.elem relative [
"komorebi-client"
"komorebi-client/Cargo.toml"
"komorebi-client/src"
"komorebi-client/src/lib.rs"
"komorebi-client/src/macos.rs"
"komorebi-client/tests"
];
in
((rootCrate || komorebic) && !(pkgs.lib.hasSuffix "/Cargo.lock" path) || relative == "Cargo.toml" || relative == "Cargo.lock" || inTree)
((rootCrate || komorebic || komorebiClient) && !(pkgs.lib.hasSuffix "/Cargo.lock" path) || relative == "Cargo.toml" || relative == "Cargo.lock" || inTree)
&& (
(craneLib.filterCargoSources path type)
|| (pkgs.lib.hasInfix "/docs/" path)
@@ -91,9 +102,10 @@
member:
pkgs.lib.hasPrefix "${platformDir}/" member
|| member == "komorebic"
|| member == "komorebi-client"
|| builtins.any (crate: member == crate || pkgs.lib.hasPrefix "${crate}/" member) rootCrates;
};
packages = "-p komorebi-macos -p komorebic -p komorebi-client-macos -p komorebi-bar-macos";
packages = "-p komorebi-macos -p komorebic -p komorebi-client -p komorebi-bar-macos";
workspaceArgs = {
pname = "komorebi-workspace";
inherit version;
@@ -239,7 +251,6 @@
"--workspace "
+ pkgs.lib.concatMapStringsSep " " (p: "--exclude ${p}") [
"komorebi-windows"
"komorebi-client"
"komorebi-gui"
"komorebic-no-console"
"komorebi-bar"
+6 -222
View File
@@ -1,225 +1,9 @@
pub use komorebi::DATA_DIR;
pub use komorebi::Notification;
pub use komorebi::NotificationEvent;
pub use komorebi::animation::AnimationPrefix;
pub use komorebi::container::Container;
pub use komorebi::core::ApplicationIdentifier;
pub use komorebi::core::Axis;
pub use komorebi::core::CycleDirection;
pub use komorebi::core::DefaultLayout;
pub use komorebi::core::Layout;
pub use komorebi::core::MonocleFocusBehaviour;
pub use komorebi::core::MoveBehaviour;
pub use komorebi::core::OperationBehaviour;
pub use komorebi::core::OperationDirection;
pub use komorebi::core::PanDirection;
pub use komorebi::core::PanGesture;
pub use komorebi::core::Rect;
pub use komorebi::core::Sizing;
pub use komorebi::core::SocketMessage;
pub use komorebi::core::StateQuery;
pub use komorebi::core::SubscribeOptions;
pub use komorebi::core::WindowKind;
pub use komorebi::core::animation::AnimationStyle;
pub use komorebi::core::asc::ApplicationSpecificConfiguration;
pub use komorebi::core::pathext::PathExt;
pub use komorebi::core::pathext::replace_env_in_path;
pub use komorebi::monitor_reconciliator::MonitorNotification;
pub use komorebi::splash;
pub use komorebi::state::State;
pub use komorebi::static_config::StaticConfig;
pub use komorebi::window::Window;
pub use komorebi::workspace::Workspace;
pub use komorebi::workspace::WorkspaceLayer;
pub use komorebi_themes::KomorebiTheme;
pub use komorebi_themes::colour::Colour;
pub use komorebi_themes::colour::Rgb;
use std::borrow::Borrow;
use std::io::BufReader;
use std::io::Read;
use std::io::Write;
use std::net::Shutdown;
use std::os::unix::net::UnixListener;
use std::os::unix::net::UnixStream;
use std::time::Duration;
//! `komorebi-client-macos`: the client of the unified `komorebi-client` package, kept under its old
//! package name until the cutover. The code is in `komorebi-client/src/macos.rs`.
const KOMOREBI: &str = "komorebi.sock";
extern crate komorebi as komorebi_macos;
pub fn send_message(message: &SocketMessage) -> std::io::Result<()> {
let socket = DATA_DIR.join(KOMOREBI);
let mut stream = UnixStream::connect(socket)?;
stream.set_write_timeout(Some(Duration::from_secs(1)))?;
stream.write_all(serde_json::to_string(message)?.as_bytes())
}
#[path = "../../../komorebi-client/src/macos.rs"]
mod platform;
/// 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 {
pub fn open() -> std::io::Result<Self> {
let socket = DATA_DIR.join(KOMOREBI);
Self::from_stream(UnixStream::connect(socket)?)
}
fn from_stream(stream: UnixStream) -> std::io::Result<Self> {
stream.set_write_timeout(Some(Duration::from_secs(1)))?;
Ok(Self { stream })
}
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())
}
}
pub fn send_batch<Q>(messages: impl IntoIterator<Item = Q>) -> std::io::Result<()>
where
Q: Borrow<SocketMessage>,
{
let socket = DATA_DIR.join(KOMOREBI);
let mut stream = UnixStream::connect(socket)?;
stream.set_write_timeout(Some(Duration::from_secs(1)))?;
let msgs = messages.into_iter().fold(String::new(), |mut s, m| {
if let Ok(m_str) = serde_json::to_string(m.borrow()) {
s.push_str(&m_str);
s.push('\n');
}
s
});
stream.write_all(msgs.as_bytes())
}
pub fn send_query(message: &SocketMessage) -> std::io::Result<String> {
let socket = DATA_DIR.join(KOMOREBI);
let mut stream = UnixStream::connect(socket)?;
stream.set_read_timeout(Some(Duration::from_secs(1)))?;
stream.set_write_timeout(Some(Duration::from_secs(1)))?;
stream.write_all(serde_json::to_string(message)?.as_bytes())?;
stream.shutdown(Shutdown::Write)?;
let mut reader = BufReader::new(stream);
let mut response = String::new();
reader.read_to_string(&mut response)?;
Ok(response)
}
pub fn subscribe(name: &str) -> std::io::Result<UnixListener> {
let socket = DATA_DIR.join(name);
match std::fs::remove_file(&socket) {
Ok(()) => {}
Err(error) => match error.kind() {
std::io::ErrorKind::NotFound => {}
_ => {
return Err(error);
}
},
};
let listener = UnixListener::bind(&socket)?;
send_message(&SocketMessage::AddSubscriberSocket(name.to_string()))?;
Ok(listener)
}
pub fn subscribe_with_options(
name: &str,
options: SubscribeOptions,
) -> std::io::Result<UnixListener> {
let socket = DATA_DIR.join(name);
match std::fs::remove_file(&socket) {
Ok(()) => {}
Err(error) => match error.kind() {
std::io::ErrorKind::NotFound => {}
_ => {
return Err(error);
}
},
};
let listener = UnixListener::bind(&socket)?;
send_message(&SocketMessage::AddSubscriberSocketWithOptions(
name.to_string(),
options,
))?;
Ok(listener)
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::BufRead;
use std::str::FromStr;
#[test]
fn messages_are_written_to_a_connection_a_line_each_in_the_order_that_they_were_sent() {
let (ours, theirs) = UnixStream::pair().unwrap();
let mut connection = Connection::from_stream(ours).unwrap();
connection
.send(&SocketMessage::PanGesture(PanGesture::Begin))
.unwrap();
connection
.send(&SocketMessage::Pan(PanDirection::Right))
.unwrap();
connection
.send(&SocketMessage::PanGesture(PanGesture::Move {
dx: 0.5,
dy: 0.0,
t: 12.0,
}))
.unwrap();
drop(connection);
let lines: Vec<String> = BufReader::new(theirs)
.lines()
.collect::<Result<_, _>>()
.unwrap();
assert_eq!(lines.len(), 3, "one line to a message: {lines:?}");
let messages: Vec<SocketMessage> = lines
.iter()
.map(|line| SocketMessage::from_str(line).unwrap())
.collect();
assert!(matches!(
messages[0],
SocketMessage::PanGesture(PanGesture::Begin)
));
assert!(matches!(
messages[1],
SocketMessage::Pan(PanDirection::Right)
));
assert!(matches!(
messages[2],
SocketMessage::PanGesture(PanGesture::Move { dx, t, .. }) if dx == 0.5 && t == 12.0
));
}
#[test]
fn writing_to_a_connection_that_was_let_go_of_is_an_error() {
let (ours, theirs) = UnixStream::pair().unwrap();
let mut connection = Connection::from_stream(ours).unwrap();
drop(theirs);
assert!(
connection
.send(&SocketMessage::PanGesture(PanGesture::Cancel))
.is_err()
);
}
}
pub use platform::*;
+1 -5
View File
@@ -12,6 +12,7 @@ edition = "2024"
# are renamed (`komorebi-client-linux`, ...) and main.rs gives them the names the modules use.
[dependencies]
komorebi-client = { path = "../komorebi-client", default-features = false }
komorebi-config = { path = "../crates/komorebi-config", default-features = false }
komorebic-core = { path = "../crates/komorebic-core" }
@@ -25,7 +26,6 @@ schemars = { workspace = true, optional = true }
serde_json = { workspace = true }
[target.'cfg(windows)'.dependencies]
komorebi-client = { path = "../komorebi-client", default-features = false }
dunce = { workspace = true }
miette = { version = "7", features = ["fancy"] }
open = "5"
@@ -40,7 +40,6 @@ win-msgbox = "0.2"
windows = { workspace = true }
[target.'cfg(target_os = "linux")'.dependencies]
komorebi-client-linux = { package = "komorebi-client-linux", path = "../komorebi-for-kde/komorebi-client", default-features = false }
komorebi-linux = { package = "komorebi-linux", path = "../komorebi-for-kde/komorebi", default-features = false }
komorebi-hotkeys = { path = "../komorebi-for-kde/komorebi-hotkeys" }
version-linux = { package = "version-linux", path = "../komorebi-for-kde/version" }
@@ -48,7 +47,6 @@ clap_complete = "4"
sysinfo = "0.40"
[target.'cfg(target_os = "macos")'.dependencies]
komorebi-client-macos = { package = "komorebi-client-macos", path = "../komorebi-for-mac/komorebi-client", default-features = false }
version-macos = { package = "version-macos", path = "../komorebi-for-mac/version" }
clap_complete = "4"
reqwest = { version = "0.12", features = ["blocking"] }
@@ -62,8 +60,6 @@ default = ["schemars"]
schemars = [
"dep:schemars",
"komorebi-client/default",
"komorebi-client-linux/default",
"komorebi-client-macos/default",
"komorebi-config/schemars",
]
-2
View File
@@ -11,14 +11,12 @@ cfg_select! {
use windows as platform;
}
target_os = "linux" => {
extern crate komorebi_client_linux as komorebi_client;
extern crate komorebi_linux as komorebi;
extern crate version_linux as version;
mod linux;
use linux as platform;
}
target_os = "macos" => {
extern crate komorebi_client_macos as komorebi_client;
extern crate version_macos as version;
mod macos;
use macos as platform;