From 88aa78b874d79c8271c7a8ba1df84d4d498fb7b4 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 13:09:41 -0700 Subject: [PATCH] feat(wm): a command socket and the first messages Until now the daemon tiled what KWin reported and nothing else could reach it. komorebi takes its orders on a socket, as it does on Windows and on macOS: it handles no key itself, and whatever binds keys runs a command that writes a message. The daemon binds komorebi.sock in $XDG_RUNTIME_DIR/komorebi (DATA_DIR), reads one JSON SocketMessage per line on a thread per connection, and handles each message with the window manager locked, as the thread that handles events does. The first messages are the ones the first komorebic needs: State (the window manager as JSON, from state.rs), MonitorInformation, Query with a StateQuery, Retile and Stop. A question is answered on the same connection, and the answer ends when the daemon closes it. Stop unloads the bridge from KWin, removes the socket and exits; so does a stop signal. The socket is bound once the daemon is connected to KWin, so a komorebi that cannot connect, such as a second one in the same session, which the bus refuses, leaves the socket of the one that runs alone. With --fake-backend the daemon answers on its socket with no compositor at all, which is how the tests run it. komorebi-client is the other end: send_message, send_batch and send_query, and the types the messages are made of. Its doctests serve the socket themselves, tests/daemon.rs runs it against a window manager over the fake desktop, and komorebi/tests/socket.rs runs the daemon binary from its start to a Stop. --- Cargo.lock | 11 + Cargo.toml | 2 +- README.md | 16 +- deny.toml | 5 + docs/dev/ARCHITECTURE.md | 91 ++++++- docs/dev/DESIGN.md | 9 + docs/dev/PLATFORM.md | 14 +- komorebi-client/Cargo.toml | 16 ++ komorebi-client/src/lib.rs | 220 +++++++++++++++++ komorebi-client/tests/daemon.rs | 111 +++++++++ komorebi/Cargo.toml | 3 + komorebi/src/core/mod.rs | 68 ++++++ komorebi/src/desktop.rs | 15 +- komorebi/src/lib.rs | 12 +- komorebi/src/main.rs | 22 +- komorebi/src/monitor.rs | 28 +++ komorebi/src/process_command.rs | 412 ++++++++++++++++++++++++++++++++ komorebi/src/state.rs | 100 ++++++++ komorebi/src/window_manager.rs | 127 +++++++++- komorebi/tests/no_kwin.rs | 47 +++- komorebi/tests/socket.rs | 88 +++++++ komorebi/tests/wm_events.rs | 9 +- 22 files changed, 1389 insertions(+), 37 deletions(-) create mode 100644 komorebi-client/Cargo.toml create mode 100644 komorebi-client/src/lib.rs create mode 100644 komorebi-client/tests/daemon.rs create mode 100644 komorebi/src/process_command.rs create mode 100644 komorebi/src/state.rs create mode 100644 komorebi/tests/socket.rs diff --git a/Cargo.lock b/Cargo.lock index 1474f253..1b67cc30 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -975,10 +975,20 @@ dependencies = [ "tokio", "tracing", "tracing-subscriber", + "uuid", "version", "zbus", ] +[[package]] +name = "komorebi-client" +version = "0.1.0" +dependencies = [ + "komorebi", + "parking_lot", + "serde_json_lenient", +] + [[package]] name = "komorebi-layouts" version = "0.1.42" @@ -2086,6 +2096,7 @@ version = "1.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a0e2d11620c50695fe12bbbfde96b3477fe606e7284c22d505c12ce51214514" dependencies = [ + "getrandom 0.4.3", "js-sys", "serde_core", "wasm-bindgen", diff --git a/Cargo.toml b/Cargo.toml index c4bf2334..46b0675d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [workspace] resolver = "2" -members = ["komorebi", "version"] +members = ["komorebi", "komorebi-client", "version"] [workspace.package] version = "0.1.0" diff --git a/README.md b/README.md index ae7bceef..72eeade3 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,12 @@ session. Outside a Plasma session it exits with an error that says what is missing. `--fake-backend` runs the window manager against an in-memory desktop with one monitor and no windows instead. +While it runs, the daemon takes messages on a Unix socket, `komorebi.sock` in +`$XDG_RUNTIME_DIR/komorebi` (the local data directory when there is no runtime +directory): a message can ask for the state of the window manager, ask which +monitor, workspace or container has the focus, retile every monitor, or stop +the daemon. [`komorebi-client`](komorebi-client) writes them. + `nix develop` provides the Rust toolchain that [`rust-toolchain.toml`](rust-toolchain.toml) selects, a nightly `rustfmt`, and the tools `just check` and the flake's checks use. With [direnv](https://direnv.net), the [`.envrc`](.envrc) does it on @@ -41,7 +47,11 @@ without a checkout of the toolchain. backend (`desktop`) and changes it when the compositor reports an event (`window_manager_event`, `window_manager_event_listener`, `process_event`), the `Ring` that holds monitors, workspaces and containers, and the lists in which - some elements are locked in place. + some elements are locked in place. It answers the messages on the daemon's + socket (`core::SocketMessage`, `process_command`) and shows its state + (`state`). +- [`komorebi-client`](komorebi-client): a library that sends messages to the + daemon and reads its answers, and re-exports the types they are made of. - [`version`](version): the version string every binary reports. The layouts, which turn a work area and a number of containers into a rectangle @@ -87,6 +97,10 @@ backend and tiles them; after that it changes the model when the compositor reports that a window was shown, closed, focused, minimized or restored, and tiles the workspace in front again. +Everything else reaches the daemon as a message on its socket: one JSON +`SocketMessage` per line, handled one at a time with the window manager +locked. A message that asks a question is answered on the same connection. + ## Documentation `cargo doc --workspace --no-deps --open` builds the API documentation. diff --git a/deny.toml b/deny.toml index 8ce0cea6..71131d7a 100644 --- a/deny.toml +++ b/deny.toml @@ -34,6 +34,11 @@ crate = "komorebi" expression = "LicenseRef-Komorebi-2.0" license-files = [] +[[licenses.clarify]] +crate = "komorebi-client" +expression = "LicenseRef-Komorebi-2.0" +license-files = [] + [[licenses.clarify]] crate = "komorebi-layouts" expression = "LicenseRef-Komorebi-2.0" diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index 1583aeb4..c82ca934 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -7,8 +7,8 @@ tested, without one. This page describes that trait, who implements and calls it, where each of its rules is enforced, the model of the desktop the window manager tiles, the backend that reaches KWin, -and how an event about a window becomes a tile. It grows with the code: each part of the -daemon that is added has its place here. +how an event about a window becomes a tile, and how a message on the daemon's socket is +answered. It grows with the code: each part of the daemon that is added has its place here. ## Vocabulary @@ -24,6 +24,10 @@ daemon that is added has its place here. number of containers into one rectangle, a **tile**, for each container. - **Event**: what the compositor reports about a window: it was shown, destroyed, given the focus, minimized or restored ([`WindowManagerEvent`]). +- **Message**: what a client sends the daemon on its socket, a [`SocketMessage`]: an order + (retile, stop) or a question (the state, the monitors, one [`StateQuery`]). +- **State**: the window manager's monitors, workspaces, containers and windows, and its + settings, as the daemon answers a `State` message with them ([`State`]). - **Compositor**: the program that owns the screen and the windows. On KDE Plasma it is KWin. - **Backend**: the implementation of the [`Backend`](../../komorebi/src/backend/mod.rs) @@ -154,6 +158,39 @@ and returns once the snapshot has arrived, so that the window manager reads a fu it starts. [PLATFORM.md](PLATFORM.md) has the D-Bus names, the files and the environment variables; [DESIGN.md](DESIGN.md#why-does-komorebi-run-a-script-inside-kwin) has the reasons. +## The command socket + +The daemon takes messages on a Unix socket, `komorebi.sock` in [`DATA_DIR`] +(`$XDG_RUNTIME_DIR/komorebi`, or the local data directory without a runtime directory). +[`WindowManager::new`] binds it, after it removes a socket file that a daemon that did not +stop cleanly left behind, and the window manager keeps the listener. The daemon connects to +KWin before it makes the window manager, so a komorebi that cannot connect, such as a second +one in the same session, whose bus refuses it `org.komorebi.Bridge`, exits before it touches +the socket of the one that is running. + +[`listen_for_commands`] starts a thread that accepts connections, and reads each connection +on a separate thread ([`read_commands_uds`]). A connection carries one [`SocketMessage`] +per line, as JSON with the variant's name in `type` and its arguments in `content`: +`{"type":"Query","content":"FocusedWorkspaceIndex"}`. Each message is handled by +[`WindowManager::process_command`] with the window manager locked, so messages are handled +one at a time. A message that waited a second for the lock is logged and dropped. + +A question is answered on the same connection: the [`State`] or the monitors as JSON, or +the answer to a [`StateQuery`] as one value in plain text. The answer has no framing; it +ends when the daemon closes the connection, which it does once it has read the last line. +A client therefore shuts down its side for writing after its message, and reads until the +end ([`send_query`]). An order is answered with nothing, and a client that sends only +orders can close the connection as soon as it has written them ([`send_message`], +[`send_batch`]). + +A message that fails (a query about the focused container when the workspace has none) is +logged, and the lines after it on that connection are not read. The client sees the +connection close with no answer. + +`Stop` ends the daemon: [`WindowManager::stop`] removes the socket, lets the backend give up +what it set up in the compositor (the KWin backend unloads the bridge), and exits with +status 0. `SIGINT` and `SIGTERM` do the same from `main.rs`, with the exit status 130. + ## The parts - [`backend`](../../komorebi/src/backend/mod.rs): the trait, the two data types, and the @@ -181,9 +218,15 @@ variables; [DESIGN.md](DESIGN.md#why-does-komorebi-run-a-script-inside-kwin) has - [`kwin`](../../komorebi/src/kwin/mod.rs): the KWin backend, its D-Bus service and the held call; [`kwin::state`](../../komorebi/src/kwin/state.rs), the table; and [`bridge.js`](../../komorebi/src/kwin/bridge.js), the bridge. +- [`process_command`](../../komorebi/src/process_command.rs): the thread that listens on the + socket, and what the window manager does with each message. +- [`state`](../../komorebi/src/state.rs): the [`State`] a `State` message is answered with. +- [`komorebi-client`](../../komorebi-client/src/lib.rs): a library that writes messages on + the socket and reads the answers, for programs that talk to the daemon. - [`main.rs`](../../komorebi/src/main.rs): the daemon. It connects to KWin, or installs the - fake with `--fake-backend`, loads and tiles the desktop, starts the thread that handles - events, and waits to be stopped. + fake with `--fake-backend`, makes the window manager, which binds the socket, loads and + tiles the desktop, starts the threads that listen on the socket and handle events, and + waits to be stopped. The handle is a process-wide singleton so that a window can be a small `Copy` value that carries only its id, and ask the backend for what it needs. A test replaces it for @@ -222,6 +265,7 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | A destroyed window leaves whichever workspace has it | framework path: the destroy is looked up in the index of managed windows, which is rebuilt at startup and before and after every event | `a_window_that_was_open_before_komorebi_started_is_removed_when_it_closes` | none | | The daemon does not start without KWin, unless it is told to run against the fake | startup check: [`connect`] fails, and the daemon exits with the error, code 1 | `without_a_session_bus_komorebi_exits_with_an_error_naming_it` | `--fake-backend` | | One komorebi per session | startup check: the session bus gives `org.komorebi.Bridge` to one connection | none | none | +| A komorebi that cannot connect to KWin leaves the socket of the running one alone | startup order: `main.rs` connects to KWin before [`WindowManager::new`] binds the socket | `without_kwin_komorebi_leaves_the_socket_it_finds_alone` | `--fake-backend` asks no bus, and takes the socket | | Events reach the window manager in the order KWin raised them | framework path: the `Event` interface is `spawn = false`, so the calls are handled inline, and one channel and one thread carry the events to the window manager | `vm-kwin-events` ("the Show came first") | none | | No event names a window before the event that announces it | convention in the bridge, which announces a window it has not seen when it is activated; the table shows a window once | `a_new_window_raises_show_and_then_focus_in_that_order`, `announcing_the_same_window_twice_shows_it_once`, `vm-kwin-events` | none | | A window's id names one window while the daemon runs | framework path: the table numbers each KWin window the first time it sees it, and never gives a number out twice | `ids_are_assigned_once_per_window_and_survive_a_new_snapshot`, `tombstones_are_dropped_after_a_while_and_their_ids_are_not_reused` | none | @@ -231,6 +275,9 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | The window manager sees a frame it asked for at once | framework path: the KWin backend's `set_rect` records it in the table before KWin answers | `a_requested_rect_is_visible_at_once_and_replaced_by_the_real_one` | none | | A KWin that restarts gets the bridge again, and the windows of the old one leave the layout | framework path: the connection's thread watches `NameOwnerChanged` for `org.kde.KWin`, and the table destroys every window when the name is lost | `when_kwin_goes_away_every_window_it_had_is_destroyed`, `vm-kwin-restart` | none | | After KWin restarts, the commands go to the new bridge | framework path: a `Poll` held since before KWin last left the bus is answered with nothing, and passes on the wake-up it got | `a_poll_held_by_the_bridge_of_a_kwin_that_has_gone_gets_no_commands`, `vm-kwin-restart` ("a window opened in the third KWin is tiled") | none | +| Messages are handled one at a time, and in order on one connection | framework path: [`read_commands_uds`] reads a connection line by line and handles each message with the window manager locked | `the_messages_on_one_connection_are_handled_in_order` | none | +| A socket left behind by a daemon that did not stop cleanly does not keep the next one from starting | framework path: [`WindowManager::new`] removes the file before it binds | `a_socket_file_left_behind_is_replaced` | none | +| A daemon that is told to stop leaves no socket behind | framework path: [`WindowManager::stop`] removes it before it exits | `the_daemon_answers_on_its_socket_and_stops_when_it_is_told_to` | `SIGKILL` | | The bridge holds no window manager logic | convention, with every decision about an event in the table, which the `kwin::state` unit tests pin | the unit tests in `komorebi/src/kwin/state.rs` | none | | What the bridge sends is what the table reads | type checker: the JSDoc types of the messages in [`bridge.js`]; tests: the events of [`fixtures`] are what the bridge's tests check it sends and what the table's tests feed it | `what the bridge sends for a session is what the daemon's tests read`, `the_bridges_events_for_a_session_are_the_window_events_komorebi_expects` | none | | What the backend sends is what the bridge carries out | tests: the commands of [`fixtures`] are what the backend's tests check it sends and what the bridge's tests answer it with, checking what KWin is asked to do for each | `the_commands_of_a_session_go_to_the_bridge_as_the_bridges_tests_answer_it`, `what the bridge sends for a session is what the daemon's tests read`, `a command for a window KWin no longer has is given back, and the rest are carried out` | none | @@ -276,6 +323,24 @@ A window is shown, and ends up on a tile: shortcut). 8. The index is rebuilt again, so the next event finds the window. +## One message, end to end + +A client asks for the state of the window manager: + +1. [`send_query`] connects to `komorebi.sock` in [`DATA_DIR`], writes + `{"type":"State"}`, and shuts down its side of the connection for writing. +2. The thread that [`listen_for_commands`] started accepts the connection and starts a + thread for it, which calls [`read_commands_uds`]. +3. `read_commands_uds` reads the line, parses it into [`SocketMessage`]`::State`, and locks + the window manager, waiting up to a second. +4. [`WindowManager::process_command`] makes a [`State`] from the window manager, a copy of + every monitor with its workspaces, containers and windows. Each window is serialized + with what the backend reports about it now: its frame, title, executable, class and path. +5. The state is written to the connection as pretty-printed JSON, and the index of managed + windows is rebuilt, as after every message. +6. There are no more lines, so `read_commands_uds` returns and the connection is closed. + `send_query` has read to the end, and returns the JSON. + ## Where to look in the code - [`komorebi/src/backend/mod.rs`](../../komorebi/src/backend/mod.rs): the trait. @@ -289,6 +354,10 @@ A window is shown, and ends up on a tile: offset a monitor gives the workspace it shows. - [`komorebi/src/process_event.rs`](../../komorebi/src/process_event.rs): what each event does, and the thread that handles them. +- [`komorebi/src/process_command.rs`](../../komorebi/src/process_command.rs): the socket, what + each message does, and the tests that send messages through a real socket. +- [`komorebi-client/src/lib.rs`](../../komorebi-client/src/lib.rs): the client side of the + socket. - [`komorebi/src/kwin/mod.rs`](../../komorebi/src/kwin/mod.rs): the KWin backend, its D-Bus service and the held call. - [`komorebi/src/kwin/state.rs`](../../komorebi/src/kwin/state.rs): the table, with the @@ -305,6 +374,8 @@ A window is shown, and ends up on a tile: restarting under the daemon. - [`komorebi/tests/wm_events.rs`](../../komorebi/tests/wm_events.rs): the window manager driven end to end against the fake. +- [`komorebi/tests/socket.rs`](../../komorebi/tests/socket.rs): the daemon over its socket, + from its start to a `Stop`. [`Backend`]: ../../komorebi/src/backend/mod.rs [`WindowInfo`]: ../../komorebi/src/backend/mod.rs @@ -339,3 +410,15 @@ A window is shown, and ends up on a tile: [`kwin-api.d.ts`]: ../../komorebi/src/kwin/kwin-api.d.ts [`bridge.test.js`]: ../../komorebi/src/kwin/bridge.test.js [`fixtures`]: ../../komorebi/src/kwin/fixtures +[`DATA_DIR`]: ../../komorebi/src/lib.rs +[`SocketMessage`]: ../../komorebi/src/core/mod.rs +[`StateQuery`]: ../../komorebi/src/core/mod.rs +[`State`]: ../../komorebi/src/state.rs +[`WindowManager::new`]: ../../komorebi/src/window_manager.rs +[`WindowManager::stop`]: ../../komorebi/src/window_manager.rs +[`WindowManager::process_command`]: ../../komorebi/src/process_command.rs +[`listen_for_commands`]: ../../komorebi/src/process_command.rs +[`read_commands_uds`]: ../../komorebi/src/process_command.rs +[`send_query`]: ../../komorebi-client/src/lib.rs +[`send_message`]: ../../komorebi-client/src/lib.rs +[`send_batch`]: ../../komorebi-client/src/lib.rs diff --git a/docs/dev/DESIGN.md b/docs/dev/DESIGN.md index cf1a65cb..0049df8d 100644 --- a/docs/dev/DESIGN.md +++ b/docs/dev/DESIGN.md @@ -155,3 +155,12 @@ bus itself: `NameOwnerChanged` says that `org.kde.KWin` has lost its owner, and has a new one. So losing the name counts as every window closing, and getting it back as the moment to load the bridge into the new KWin, which then reports its desktop as it does at start. + +## Why does komorebi take its orders on a socket? + +komorebi responds to two things: what the compositor reports about windows, and the +messages it receives on its socket. It handles no keyboard or mouse input. Binding a key to +an action is the job of another program, which runs a command that writes a message on the +socket. This is the architecture that bspwm made popular on Linux and yabai on macOS, and +the one komorebi has on Windows and on macOS +([the design notes of komorebi for Mac](https://github.com/LGUG2Z/komorebi-for-mac/blob/master/docs/design.md)). diff --git a/docs/dev/PLATFORM.md b/docs/dev/PLATFORM.md index 9d2a41ce..b775bc7d 100644 --- a/docs/dev/PLATFORM.md +++ b/docs/dev/PLATFORM.md @@ -88,10 +88,11 @@ an owner again; the VM test `vm-kwin-restart` restarts KWin twice under a runnin #### What komorebi leaves behind -When it is stopped with `SIGINT` or `SIGTERM` it asks KWin to unload the script. The file -`bridge.js` stays in the runtime directory, which is removed at logout. A daemon that is -killed leaves the script running in KWin, reporting to nobody, until the next start replaces -it or the session ends. +When it is stopped with `SIGINT`, `SIGTERM` or a `Stop` message on its socket, it asks KWin +to unload the script and removes the socket. The file `bridge.js` stays in the runtime +directory, which is removed at logout. A daemon that is killed leaves the script running in +KWin, reporting to nobody, and the socket file in the runtime directory, until the next start +replaces both or the session ends. ### A headless KWin @@ -142,6 +143,7 @@ What komorebi calls: | Path | What | Lifetime | |---|---|---| | `$XDG_RUNTIME_DIR/komorebi/bridge.js` | the script KWin loads, with its configuration (the D-Bus names and the hold time of `Poll`) on its first line | written at every start; the directory is removed at logout | +| `$XDG_RUNTIME_DIR/komorebi/komorebi.sock` | the command socket | bound once the daemon is connected to KWin, after a file left there is removed; removed when the daemon stops | Without `XDG_RUNTIME_DIR` the directory is `komorebi` in the local data directory instead (see [`XDG_DATA_HOME`](#xdg_data_home)). @@ -157,11 +159,11 @@ either. An address with no bus behind it is the first error under [No KWin](#no- ### `XDG_RUNTIME_DIR` The runtime directory of the user, normally `/run/user/`: komorebi writes the bridge to -the `komorebi` directory in it. +the `komorebi` directory in it, and binds its command socket there. ### `XDG_DATA_HOME` -Read only when `XDG_RUNTIME_DIR` is not set: the bridge is then written to +Read only when `XDG_RUNTIME_DIR` is not set: the bridge and the socket then go to `$XDG_DATA_HOME/komorebi` (`~/.local/share/komorebi` if `XDG_DATA_HOME` is not set either). ### `RUST_LOG` diff --git a/komorebi-client/Cargo.toml b/komorebi-client/Cargo.toml new file mode 100644 index 00000000..066c69bd --- /dev/null +++ b/komorebi-client/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "komorebi-client" +version.workspace = true +edition = "2024" + +[dependencies] +komorebi = { path = "../komorebi", default-features = false } + +serde_json = { workspace = true } + +[dev-dependencies] +parking_lot = "0.12" + +[features] +default = ["schemars"] +schemars = ["komorebi/default"] diff --git a/komorebi-client/src/lib.rs b/komorebi-client/src/lib.rs new file mode 100644 index 00000000..5ac831fa --- /dev/null +++ b/komorebi-client/src/lib.rs @@ -0,0 +1,220 @@ +//! 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`]. +//! +//! The crate also re-exports the types the messages and the answers are made of, so that a client +//! needs nothing else. +//! +//! # 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 { +//! # 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>(()) +//! ``` +//! +//! `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. + +pub use komorebi::DATA_DIR; +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::Rect; +pub use komorebi::core::Sizing; +pub use komorebi::core::SocketMessage; +pub use komorebi::core::StateQuery; +pub use komorebi::core::WindowKind; +pub use komorebi::core::pathext::PathExt; +pub use komorebi::core::pathext::replace_env_in_path; +pub use komorebi::state::State; +pub use komorebi::window::Window; +pub use komorebi::workspace::Workspace; +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::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 { +/// # 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>(()) +/// ``` +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()) +} + +/// 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> { +/// # 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>(()) +/// ``` +pub fn send_batch(messages: impl IntoIterator) -> std::io::Result<()> +where + Q: Borrow, +{ + 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},"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>(()) +/// ``` +pub fn send_query(message: &SocketMessage) -> std::io::Result { + 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) +} diff --git a/komorebi-client/tests/daemon.rs b/komorebi-client/tests/daemon.rs new file mode 100644 index 00000000..434bf5d5 --- /dev/null +++ b/komorebi-client/tests/daemon.rs @@ -0,0 +1,111 @@ +//! 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. + +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::set_backend; +use komorebi::core::Rect; +use komorebi::process_command::listen_for_commands; +use komorebi::window_manager::WindowManager; +use komorebi::window_manager_event_listener; +use komorebi_client::DATA_DIR; +use komorebi_client::SocketMessage; +use komorebi_client::State; +use komorebi_client::StateQuery; +use komorebi_client::send_batch; +use komorebi_client::send_message; +use komorebi_client::send_query; +use parking_lot::Mutex; +use std::sync::Arc; +use std::sync::OnceLock; +use std::time::Duration; +use std::time::Instant; + +/// Starts the window manager once, with the windows 801 and 802 open, and returns the desktop +fn daemon() -> Arc { + static FAKE: OnceLock> = OnceLock::new(); + + FAKE.get_or_init(|| { + // /tmp: short enough for a unix socket path on macOS + let runtime = format!("/tmp/komorebi-client-test-{}", std::process::id()); + // SAFETY: the first test to get here sets it, before any thread reads the environment + unsafe { std::env::set_var("XDG_RUNTIME_DIR", &runtime) }; + std::fs::create_dir_all(&*DATA_DIR).unwrap(); + + let fake = Arc::new(FakeBackend::with_one_monitor()); + fake.open_window(801, "foot", "foot", "first"); + fake.open_window(802, "foot", "foot", "second"); + set_backend(fake.clone()); + + let mut wm = WindowManager::new(window_manager_event_listener::event_rx(), None).unwrap(); + wm.init().unwrap(); + wm.retile_all().unwrap(); + listen_for_commands(Arc::new(Mutex::new(wm))); + + fake + }) + .clone() +} + +/// Waits up to five seconds for `done`, since a message that is sent is handled on another thread +fn eventually(done: impl Fn() -> bool) -> bool { + let started = Instant::now(); + while started.elapsed() < Duration::from_secs(5) { + if done() { + return true; + } + std::thread::sleep(Duration::from_millis(10)); + } + false +} + +#[test] +fn the_state_reads_back_as_the_window_managers_state() -> Result<(), Box> { + daemon(); + + let state: State = serde_json::from_str(&send_query(&SocketMessage::State)?)?; + + let workspace = &state.monitors.elements()[0].workspaces()[0]; + let windows = workspace + .containers() + .iter() + .flat_map(|container| container.windows().iter().map(|window| window.id)) + .collect::>(); + assert_eq!(windows, [801, 802]); + Ok(()) +} + +#[test] +fn a_query_is_answered_with_one_value() -> Result<(), Box> { + daemon(); + + let kind = send_query(&SocketMessage::Query(StateQuery::FocusedContainerKind))?; + let layout = send_query(&SocketMessage::Query(StateQuery::FocusedWorkspaceLayout))?; + + assert_eq!(kind, "Single"); + assert_eq!(layout, "BSP"); + Ok(()) +} + +#[test] +fn a_retile_puts_a_window_moved_by_hand_back_on_its_tile() -> Result<(), Box> +{ + let fake = daemon(); + let tile = fake.rect_of(802); + let elsewhere = Rect { + left: 300, + top: 300, + right: 400, + bottom: 400, + }; + + fake.move_window_by_user(802, elsewhere); + send_message(&SocketMessage::Retile)?; + assert!(eventually(|| fake.rect_of(802) == tile)); + + fake.move_window_by_user(802, elsewhere); + send_batch(vec![SocketMessage::Retile; 2])?; + assert!(eventually(|| fake.rect_of(802) == tile)); + Ok(()) +} diff --git a/komorebi/Cargo.toml b/komorebi/Cargo.toml index d419f055..fb152296 100644 --- a/komorebi/Cargo.toml +++ b/komorebi/Cargo.toml @@ -28,6 +28,9 @@ tracing-subscriber = { workspace = true } zbus = { version = "5", default-features = false, features = ["tokio"] } futures-util = "0.3" +[dev-dependencies] +uuid = { version = "1", features = ["v4"] } + [features] default = ["schemars"] deadlock_detection = ["parking_lot/deadlock_detection"] diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index a3e0c917..91d37c9b 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -5,10 +5,15 @@ //! those of `komorebi-layouts`, re-exported here so that the rest of the crate has one place to //! import from. [`pathext`] resolves environment variables in configured paths and //! [`config_generation`] holds the rules that match applications by what they are called. +//! +//! [`SocketMessage`] is every message the daemon takes on its socket, and [`StateQuery`] every +//! question [`SocketMessage::Query`] can ask. use clap::ValueEnum; +use color_eyre::eyre; use serde::Deserialize; use serde::Serialize; +use std::str::FromStr; use strum::Display; use strum::EnumString; @@ -252,3 +257,66 @@ pub enum WindowKind { UnfocusedLocked, Floating, } + +/// A question about the window manager that [`SocketMessage::Query`] asks, answered with one +/// value as text: an index, the name of a layout or of a container kind, or the version of the +/// daemon. +#[derive(Copy, Clone, Debug, Serialize, Deserialize, Display, EnumString, ValueEnum)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub enum StateQuery { + FocusedMonitorIndex, + FocusedWorkspaceIndex, + FocusedContainerIndex, + FocusedWindowIndex, + FocusedWorkspaceLayout, + FocusedContainerKind, + Version, +} + +/// A message to the daemon, as it is written on its socket: JSON, with the variant's name in +/// `type` and its arguments, if it has any, in `content`. +/// +/// # Example +/// +/// ```rust +/// use komorebi::core::SocketMessage; +/// use komorebi::core::StateQuery; +/// +/// let query = SocketMessage::Query(StateQuery::FocusedWorkspaceIndex); +/// assert_eq!( +/// String::from_utf8(query.as_bytes()?)?, +/// r#"{"type":"Query","content":"FocusedWorkspaceIndex"}"#, +/// ); +/// +/// let stop: SocketMessage = r#"{"type":"Stop"}"#.parse()?; +/// assert!(matches!(stop, SocketMessage::Stop)); +/// +/// # Ok::<(), Box>(()) +/// ``` +// serde_as must be before derive +#[serde_with::serde_as] +#[derive(Clone, Debug, Serialize, Deserialize, Display)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[serde(tag = "type", content = "content")] +pub enum SocketMessage { + Stop, + Retile, + State, + MonitorInformation, + Query(StateQuery), +} + +impl SocketMessage { + /// Returns the message as JSON, the way the daemon reads it from its socket + pub fn as_bytes(&self) -> eyre::Result> { + Ok(serde_json::to_string(self)?.as_bytes().to_vec()) + } +} + +impl FromStr for SocketMessage { + type Err = serde_json::Error; + + fn from_str(s: &str) -> Result { + serde_json::from_str(s) + } +} diff --git a/komorebi/src/desktop.rs b/komorebi/src/desktop.rs index a7af3f01..65eee012 100644 --- a/komorebi/src/desktop.rs +++ b/komorebi/src/desktop.rs @@ -8,6 +8,7 @@ //! # Example //! //! ```rust +//! use std::path::PathBuf; //! use std::sync::Arc; //! //! use komorebi::backend::fake::FakeBackend; @@ -20,7 +21,8 @@ //! fake.open_window(1, "foot", "foot", "a terminal"); //! //! let (_sender, events) = crossbeam_channel::bounded(1); -//! let mut wm = WindowManager::new(events)?; +//! let socket = PathBuf::from(format!("/tmp/komorebi-desktop-doc-{}.sock", std::process::id())); +//! let mut wm = WindowManager::new(events, Some(socket.clone()))?; //! with_backend(fake, || { //! load_monitor_information(&mut wm)?; //! load_workspace_information(&mut wm) @@ -28,6 +30,7 @@ //! //! assert_eq!(wm.monitors().len(), 1); //! assert!(wm.focused_workspace()?.contains_window(1)); +//! # std::fs::remove_file(socket)?; //! # Ok::<(), color_eyre::eyre::Report>(()) //! ``` @@ -96,6 +99,7 @@ pub fn latest_monitor_information() -> eyre::Result> { /// # Example /// /// ```rust +/// use std::path::PathBuf; /// use std::sync::Arc; /// /// use komorebi::backend::fake::FakeBackend; @@ -105,7 +109,8 @@ pub fn latest_monitor_information() -> eyre::Result> { /// /// let fake = Arc::new(FakeBackend::with_one_monitor()); /// let (_sender, events) = crossbeam_channel::bounded(1); -/// let mut wm = WindowManager::new(events)?; +/// let socket = PathBuf::from(format!("/tmp/komorebi-monitors-doc-{}.sock", std::process::id())); +/// let mut wm = WindowManager::new(events, Some(socket.clone()))?; /// /// with_backend(fake, || { /// load_monitor_information(&mut wm)?; @@ -113,6 +118,7 @@ pub fn latest_monitor_information() -> eyre::Result> { /// })?; /// /// assert_eq!(wm.monitors().len(), 1); +/// # std::fs::remove_file(socket)?; /// # Ok::<(), color_eyre::eyre::Report>(()) /// ``` #[tracing::instrument(skip_all)] @@ -148,6 +154,7 @@ pub fn load_monitor_information(wm: &mut WindowManager) -> eyre::Result<()> { /// # Example /// /// ```rust +/// use std::path::PathBuf; /// use std::sync::Arc; /// /// use komorebi::backend::fake::FakeBackend; @@ -162,7 +169,8 @@ pub fn load_monitor_information(wm: &mut WindowManager) -> eyre::Result<()> { /// fake.set_normal(2, false); /// /// let (_sender, events) = crossbeam_channel::bounded(1); -/// let mut wm = WindowManager::new(events)?; +/// let socket = PathBuf::from(format!("/tmp/komorebi-windows-doc-{}.sock", std::process::id())); +/// let mut wm = WindowManager::new(events, Some(socket.clone()))?; /// with_backend(fake, || { /// load_monitor_information(&mut wm)?; /// load_workspace_information(&mut wm) @@ -171,6 +179,7 @@ pub fn load_monitor_information(wm: &mut WindowManager) -> eyre::Result<()> { /// let workspace = wm.focused_workspace()?; /// assert!(workspace.contains_window(1)); /// assert!(!workspace.contains_window(2)); +/// # std::fs::remove_file(socket)?; /// # Ok::<(), color_eyre::eyre::Report>(()) /// ``` #[tracing::instrument(skip_all)] diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs index ac675ddd..6a1b14a5 100644 --- a/komorebi/src/lib.rs +++ b/komorebi/src/lib.rs @@ -12,6 +12,10 @@ //! [`window_manager_event_listener`]. //! //! On KDE Plasma the backend is [`kwin::KWinBackend`], which talks to a script it loads into KWin. +//! +//! The daemon also listens on a socket, `komorebi.sock` in [`struct@DATA_DIR`], for the messages +//! in [`core::SocketMessage`]: [`process_command`] reads them and answers, with the window +//! manager's [`state::State`] for one. use color_eyre::eyre; use lazy_static::lazy_static; @@ -28,7 +32,9 @@ pub mod desktop; pub mod kwin; pub mod lockable_sequence; pub mod monitor; +pub mod process_command; pub mod process_event; +pub mod state; pub mod window; pub mod window_manager; pub mod window_manager_event; @@ -41,9 +47,9 @@ pub type LibraryError = eyre::Report; lazy_static! { /// Where komorebi keeps the files it needs while it runs, such as the script it loads into - /// KWin: `$XDG_RUNTIME_DIR/komorebi`, which is per-user, on tmpfs and removed at logout. - /// Without a runtime directory (a bare ssh session, or the tests on a Mac) it falls back to the - /// local data directory. + /// KWin and its command socket: `$XDG_RUNTIME_DIR/komorebi`, which is per-user, on tmpfs and + /// removed at logout. Without a runtime directory (a bare ssh session, or the tests on a Mac) + /// it falls back to the local data directory. pub static ref DATA_DIR: PathBuf = std::env::var_os("XDG_RUNTIME_DIR") .filter(|dir| !dir.is_empty()) .map(|dir| PathBuf::from(dir).join("komorebi")) diff --git a/komorebi/src/main.rs b/komorebi/src/main.rs index fe9d0065..7ab2e5ec 100644 --- a/komorebi/src/main.rs +++ b/komorebi/src/main.rs @@ -6,15 +6,18 @@ //! The backend is KWin's ([`komorebi::kwin`]): the daemon connects to the session bus, loads its //! script into KWin and waits for the script to report the desktop. `--fake-backend` replaces it //! with an in-memory desktop with one monitor and no windows, for development and testing. The -//! daemon then loads the monitors and the windows that are open, tiles them, handles the events -//! the backend reports on a thread of their own, and runs until it is stopped with `SIGINT` or -//! `SIGTERM`. +//! daemon then loads the monitors and the windows that are open, tiles them, listens for +//! messages on `komorebi.sock` in [`struct@DATA_DIR`], handles the events the backend reports on +//! a thread of their own, and runs until it is stopped, with `SIGINT`, `SIGTERM` or a `Stop` +//! message. use clap::Parser; use clap::ValueEnum; use color_eyre::eyre; +use komorebi::DATA_DIR; use komorebi::backend; use komorebi::backend::fake::FakeBackend; +use komorebi::process_command::listen_for_commands; use komorebi::process_event::listen_for_events; use komorebi::window_manager::WindowManager; use komorebi::window_manager_event_listener; @@ -118,8 +121,8 @@ struct Opts { /// Level of log output verbosity #[clap(long, value_enum, default_value_t=LogLevel::Info)] log_level: LogLevel, - /// Run against an in-memory desktop instead of KWin, for development and testing. Windows - /// and monitors are not real. + /// Run against an in-memory desktop instead of KWin, for development and testing of the + /// socket interface. Windows and monitors are not real. #[clap(long, hide = true)] fake_backend: bool, } @@ -128,6 +131,10 @@ fn main() -> eyre::Result<()> { let opts: Opts = Opts::parse(); setup(opts.log_level)?; + if !DATA_DIR.is_dir() { + std::fs::create_dir_all(&*DATA_DIR)?; + } + if opts.fake_backend { tracing::warn!("running against an in-memory desktop; nothing here is a real window"); backend::set_backend(Arc::new(FakeBackend::with_one_monitor())); @@ -141,11 +148,13 @@ fn main() -> eyre::Result<()> { let wm = Arc::new(Mutex::new(WindowManager::new( window_manager_event_listener::event_rx(), + None, )?)); wm.lock().init()?; wm.lock().retile_all()?; + listen_for_commands(wm.clone()); listen_for_events(wm.clone()); let (quit_sender, quit_receiver) = std::sync::mpsc::channel(); @@ -160,5 +169,8 @@ fn main() -> eyre::Result<()> { backend::backend().shutdown(); + let socket = DATA_DIR.join("komorebi.sock"); + let _ = std::fs::remove_file(socket); + std::process::exit(130); } diff --git a/komorebi/src/monitor.rs b/komorebi/src/monitor.rs index e672748a..6bfa64a6 100644 --- a/komorebi/src/monitor.rs +++ b/komorebi/src/monitor.rs @@ -9,6 +9,7 @@ use crate::DEFAULT_CONTAINER_PADDING; use crate::DEFAULT_WORKSPACE_PADDING; use crate::container::Container; +use crate::core::Layout; use crate::core::Rect; use crate::ring::Ring; use crate::workspace::Workspace; @@ -20,6 +21,27 @@ use serde::Serialize; use std::collections::VecDeque; use std::sync::atomic::Ordering; +/// A monitor's identity and bounds, as the daemon answers +/// [`SocketMessage::MonitorInformation`](crate::core::SocketMessage::MonitorInformation) with them +#[derive(Debug, Serialize, Deserialize)] +pub struct MonitorInformation { + pub id: u32, + pub device: String, + pub serial_number_id: String, + pub size: Rect, +} + +impl From<&Monitor> for MonitorInformation { + fn from(value: &Monitor) -> Self { + Self { + id: value.id, + device: value.device.clone(), + serial_number_id: value.serial_number_id.clone(), + size: value.size, + } + } +} + impl_ring_elements!(Monitor, Workspace); #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] @@ -164,6 +186,12 @@ impl Monitor { .resize(ensure_count, Workspace::default()); } } + + /// The layout of the focused workspace, if the monitor has one + pub fn focused_workspace_layout(&self) -> Option { + self.focused_workspace() + .map(|workspace| workspace.layout.clone()) + } } #[cfg(test)] diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs new file mode 100644 index 00000000..37759873 --- /dev/null +++ b/komorebi/src/process_command.rs @@ -0,0 +1,412 @@ +//! How the daemon answers the messages on its socket: [`listen_for_commands`] and +//! [`WindowManager::process_command`]. +//! +//! A client connects to `komorebi.sock` in [`struct@DATA_DIR`](crate::DATA_DIR) and writes one +//! [`SocketMessage`] as JSON per line. Each connection is read on a separate thread, and each +//! message is handled with the window manager locked. A message that asks a question is answered +//! on the same connection, and the answer ends when the daemon closes it: +//! +//! - **State**: the window manager's [`State`], as JSON. +//! - **MonitorInformation**: the id, the name and the bounds of each monitor, as JSON. +//! - **Query**: one value as text, the answer to a [`StateQuery`]. +//! +//! The others answer nothing: **Retile** tiles the focused workspace of every monitor again, and +//! **Stop** stops the daemon ([`WindowManager::stop`]). + +use crate::core::Layout; +use crate::core::SocketMessage; +use crate::core::StateQuery; +use crate::monitor::MonitorInformation; +use crate::state::State; +use crate::window_manager::WindowManager; +use color_eyre::eyre; +use color_eyre::eyre::OptionExt; +use parking_lot::Mutex; +use std::io::BufRead; +use std::io::BufReader; +use std::os::unix::net::UnixStream; +use std::str::FromStr; +use std::sync::Arc; +use std::time::Duration; +use version::build; + +/// Starts the thread that accepts connections on the window manager's +/// [`command_listener`](WindowManager::command_listener), and reads each connection on a separate +/// thread ([`read_commands_uds`]) +/// +/// When accepting fails, the error is logged and the listening thread is started again. +#[tracing::instrument] +pub fn listen_for_commands(wm: Arc>) { + std::thread::spawn(move || { + loop { + let wm = wm.clone(); + + let _ = std::thread::spawn(move || { + let listener = wm + .lock() + .command_listener + .try_clone() + .expect("could not clone unix listener"); + + tracing::info!("listening on komorebi.sock"); + for client in listener.incoming() { + match client { + Ok(stream) => { + let wm_clone = wm.clone(); + std::thread::spawn(move || { + match read_commands_uds(&wm_clone, stream) { + Ok(()) => {} + Err(error) => { + tracing::error!("{error}") + } + } + }); + } + Err(error) => { + tracing::error!("failed to get unix stream {}", error); + break; + } + } + } + }) + .join(); + + tracing::error!("restarting failed thread"); + } + }); +} + +impl WindowManager { + /// Handles one message, and writes the answer to a question to `reply` + /// + /// # Errors + /// + /// - A query about the focused monitor, workspace or container when there is none. + /// - The window manager fails to retile, for one of the reasons + /// [`WindowManager::retile_all`] gives. + /// - The answer cannot be written to `reply`. + #[tracing::instrument(skip(self, reply, message))] + pub fn process_command( + &mut self, + message: SocketMessage, + mut reply: impl std::io::Write, + ) -> eyre::Result<()> { + tracing::info!("processing command: {message}"); + + match message { + SocketMessage::Retile => self.retile_all()?, + SocketMessage::State => { + let state = match serde_json::to_string_pretty(&State::from(&*self)) { + Ok(state) => state, + Err(error) => error.to_string(), + }; + + tracing::info!("replying to state"); + + reply.write_all(state.as_bytes())?; + + tracing::info!("replying to state done"); + } + SocketMessage::MonitorInformation => { + let mut monitors = vec![]; + for monitor in self.monitors() { + monitors.push(MonitorInformation::from(monitor)); + } + + let monitors_state = serde_json::to_string_pretty(&monitors) + .unwrap_or_else(|error| error.to_string()); + + reply.write_all(monitors_state.as_bytes())?; + } + SocketMessage::Query(query) => { + let response = match query { + StateQuery::FocusedMonitorIndex => self.focused_monitor_idx().to_string(), + StateQuery::FocusedWorkspaceIndex => self + .focused_monitor() + .ok_or_eyre("there is no monitor")? + .focused_workspace_idx() + .to_string(), + StateQuery::FocusedContainerIndex => self + .focused_workspace()? + .focused_container_idx() + .to_string(), + StateQuery::FocusedWindowIndex => { + self.focused_container()?.focused_window_idx().to_string() + } + StateQuery::Version => build::VERSION.to_string(), + StateQuery::FocusedWorkspaceLayout => { + let focused_monitor = + self.focused_monitor().ok_or_eyre("there is no monitor")?; + + focused_monitor.focused_workspace_layout().map_or_else( + || "None".to_string(), + |layout| match layout { + Layout::Default(default_layout) => default_layout.to_string(), + }, + ) + } + StateQuery::FocusedContainerKind => { + match self.focused_workspace()?.focused_container() { + None => "None".to_string(), + Some(container) => { + if container.windows().len() > 1 { + "Stack".to_string() + } else { + "Single".to_string() + } + } + } + } + }; + + reply.write_all(response.as_bytes())?; + } + SocketMessage::Stop => { + self.stop()?; + } + } + + self.update_known_window_ids(); + + tracing::info!("processed command: {message}"); + + Ok(()) + } +} + +/// Reads the messages on one connection, one per line, and hands each to +/// [`WindowManager::process_command`] with the connection to answer on +/// +/// A message that arrives while the window manager has been locked for a second is logged and +/// dropped. +/// +/// # Errors +/// +/// - The connection cannot be read, or cloned to be read and written at once. +/// - A line is not a [`SocketMessage`]: the lines after it are not read. +/// - [`WindowManager::process_command`] fails: the lines after it are not read. +pub fn read_commands_uds( + wm: &Arc>, + mut stream: UnixStream, +) -> eyre::Result<()> { + let reader = BufReader::new(stream.try_clone()?); + // TODO(raggi): while this processes more than one command, if there are + // replies there is no clearly defined protocol for framing yet - it's + // perhaps whole-json objects for now, but termination is signalled by + // socket shutdown. + for line in reader.lines() { + let message = SocketMessage::from_str(&line?)?; + + match wm.try_lock_for(Duration::from_secs(1)) { + None => { + tracing::warn!( + "could not acquire window manager lock, not processing message: {message}" + ); + } + Some(mut wm) => { + wm.process_command(message.clone(), &mut stream)?; + } + } + } + + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::backend::fake::FakeBackend; + use crate::backend::with_backend; + use crate::core::Rect; + use std::io::Read; + use std::io::Write; + use std::net::Shutdown; + use std::path::PathBuf; + use uuid::Uuid; + + /// A window manager over `fake`, listening on a socket for this test alone in /tmp, which is + /// short enough for a unix socket path on macOS. The socket is removed when the test is done. + struct Daemon { + fake: Arc, + wm: Arc>, + socket: PathBuf, + } + + impl Drop for Daemon { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.socket); + } + } + + impl Daemon { + fn new(fake: FakeBackend) -> Self { + let fake = Arc::new(fake); + let socket = PathBuf::from(format!("/tmp/komorebi-test-{}.sock", Uuid::new_v4())); + + let (_sender, events) = crossbeam_channel::bounded(1); + + let wm = with_backend(fake.clone(), || { + let mut wm = WindowManager::new(events, Some(socket.clone())).unwrap(); + wm.init().unwrap(); + wm + }); + + Self { + fake, + wm: Arc::new(Mutex::new(wm)), + socket, + } + } + + /// Writes `lines` on a new connection, has the window manager read the connection the + /// way the daemon does, and returns what it wrote back + fn send(&self, lines: &str) -> eyre::Result { + let mut client = UnixStream::connect(&self.socket)?; + client.write_all(lines.as_bytes())?; + client.shutdown(Shutdown::Write)?; + + // the client reads on another thread, so that an answer bigger than the + // socket's buffer does not block the window manager writing it + let reading = std::thread::spawn(move || { + let mut reply = String::new(); + client.read_to_string(&mut reply).map(|_| reply) + }); + + let (stream, _) = self.wm.lock().command_listener.accept()?; + let handled = with_backend(self.fake.clone(), || read_commands_uds(&self.wm, stream)); + + let reply = reading.join().expect("the client does not panic")?; + handled.map(|()| reply) + } + + fn ask(&self, message: SocketMessage) -> eyre::Result { + self.send(&serde_json::to_string(&message)?) + } + } + + fn rect(left: i32, top: i32, right: i32, bottom: i32) -> Rect { + Rect { + left, + top, + right, + bottom, + } + } + + fn two_windows(first: u32) -> FakeBackend { + let fake = FakeBackend::with_one_monitor(); + fake.open_window(first, "foot", "foot", "first"); + fake.open_window(first + 1, "foot", "foot", "second"); + fake + } + + #[test] + fn the_state_has_every_window_of_every_workspace() -> eyre::Result<()> { + let daemon = Daemon::new(two_windows(701)); + + let state: serde_json::Value = serde_json::from_str(&daemon.ask(SocketMessage::State)?)?; + + let windows = &state["monitors"]["elements"][0]["workspaces"]["elements"][0]["containers"] + ["elements"]; + assert_eq!(windows[0]["windows"]["elements"][0]["id"], 701); + assert_eq!(windows[1]["windows"]["elements"][0]["id"], 702); + assert_eq!( + windows[1]["windows"]["elements"][0]["details"]["title"], + "second" + ); + assert_eq!(state["mouse_follows_focus"], true); + Ok(()) + } + + #[test] + fn monitor_information_names_each_monitor_and_its_bounds() -> eyre::Result<()> { + let fake = FakeBackend::with_one_monitor(); + fake.add_monitor( + 2, + "Virtual-1", + rect(1920, 0, 1920, 1080), + rect(1920, 0, 1920, 1080), + ); + let daemon = Daemon::new(fake); + + let monitors: serde_json::Value = + serde_json::from_str(&daemon.ask(SocketMessage::MonitorInformation)?)?; + + assert_eq!(monitors.as_array().map(Vec::len), Some(2)); + assert_eq!(monitors[1]["id"], 2); + assert_eq!(monitors[1]["device"], "Virtual-1"); + assert_eq!(monitors[1]["size"]["left"], 1920); + assert_eq!(monitors[0]["size"]["right"], 1920); + Ok(()) + } + + #[test] + fn a_query_is_answered_with_one_value() -> eyre::Result<()> { + let daemon = Daemon::new(two_windows(711)); + let query = |query| daemon.ask(SocketMessage::Query(query)); + + assert_eq!(query(StateQuery::FocusedMonitorIndex)?, "0"); + assert_eq!(query(StateQuery::FocusedWorkspaceIndex)?, "0"); + assert_eq!(query(StateQuery::FocusedContainerIndex)?, "0"); + assert_eq!(query(StateQuery::FocusedWindowIndex)?, "0"); + assert_eq!(query(StateQuery::FocusedWorkspaceLayout)?, "BSP"); + assert_eq!(query(StateQuery::FocusedContainerKind)?, "Single"); + // the version is shadow-rs's description of the build, the package version first + let version = format!("pkg_version:{}", env!("CARGO_PKG_VERSION")); + assert!(query(StateQuery::Version)?.contains(&version)); + Ok(()) + } + + #[test] + fn a_query_about_a_container_on_an_empty_workspace_is_an_error() { + let daemon = Daemon::new(FakeBackend::with_one_monitor()); + + let answer = daemon.ask(SocketMessage::Query(StateQuery::FocusedWindowIndex)); + + assert_eq!( + answer.map_err(|error| error.to_string()), + Err(String::from("there is no container")) + ); + } + + #[test] + fn retile_puts_a_window_moved_by_hand_back_on_its_tile() -> eyre::Result<()> { + let daemon = Daemon::new(two_windows(721)); + daemon.ask(SocketMessage::Retile)?; + let tile = daemon.fake.rect_of(721); + + daemon + .fake + .move_window_by_user(721, rect(300, 300, 400, 400)); + assert_ne!(daemon.fake.rect_of(721), tile); + + assert_eq!(daemon.ask(SocketMessage::Retile)?, ""); + assert_eq!(daemon.fake.rect_of(721), tile); + Ok(()) + } + + #[test] + fn the_messages_on_one_connection_are_handled_in_order() -> eyre::Result<()> { + let daemon = Daemon::new(two_windows(731)); + daemon + .fake + .move_window_by_user(731, rect(300, 300, 400, 400)); + + let reply = daemon.send( + "{\"type\":\"Retile\"}\n{\"type\":\"Query\",\"content\":\"FocusedContainerKind\"}\n", + )?; + + assert_eq!(reply, "Single"); + assert_ne!(daemon.fake.rect_of(731), Some(rect(300, 300, 400, 400))); + Ok(()) + } + + #[test] + fn a_line_that_is_not_a_message_is_an_error() { + let daemon = Daemon::new(FakeBackend::with_one_monitor()); + + let reply = daemon.send("{\"type\":\"Nonsense\"}\n"); + + assert!(reply.is_err()); + } +} diff --git a/komorebi/src/state.rs b/komorebi/src/state.rs new file mode 100644 index 00000000..885dc280 --- /dev/null +++ b/komorebi/src/state.rs @@ -0,0 +1,100 @@ +//! [`State`], the window manager as the daemon shows it: every monitor, with its workspaces, their +//! containers and the windows in them, and the settings that apply to all of them. +//! +//! The daemon writes it as JSON in answer to [`SocketMessage::State`]. +//! +//! [`SocketMessage::State`]: crate::core::SocketMessage::State + +use crate::core::Rect; +use crate::monitor::Monitor; +use crate::ring::Ring; +use crate::window_manager::WindowManager; +use crate::workspace::Workspace; +use serde::Deserialize; +use serde::Serialize; +use std::collections::VecDeque; + +/// A copy of the window manager's monitors, with their workspaces, containers and windows, and +/// of its settings, which serializes to JSON +/// +/// # Example +/// +/// ```rust +/// use std::path::PathBuf; +/// use std::sync::Arc; +/// +/// use komorebi::backend::fake::FakeBackend; +/// use komorebi::backend::with_backend; +/// use komorebi::state::State; +/// use komorebi::window_manager::WindowManager; +/// +/// let fake = Arc::new(FakeBackend::with_one_monitor()); +/// fake.open_window(9, "foot", "foot", "a terminal"); +/// let (_sender, events) = crossbeam_channel::bounded(1); +/// let socket = PathBuf::from(format!("/tmp/komorebi-state-doc-{}.sock", std::process::id())); +/// +/// let state = with_backend(fake, || -> color_eyre::Result { +/// let mut wm = WindowManager::new(events, Some(socket.clone()))?; +/// wm.init()?; +/// Ok(State::from(&wm)) +/// })?; +/// # std::fs::remove_file(&socket)?; +/// +/// let workspace = &state.monitors.elements()[0].workspaces()[0]; +/// assert_eq!(workspace.containers()[0].windows()[0].id, 9); +/// +/// # Ok::<(), Box>(()) +/// ``` +#[allow(clippy::struct_excessive_bools)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct State { + pub monitors: Ring, + pub work_area_offset: Option, + pub mouse_follows_focus: bool, +} + +impl From<&WindowManager> for State { + fn from(wm: &WindowManager) -> Self { + // Every field of a monitor and of a workspace is copied by name here, so that what does + // not need to be shown in the state can be left out of the copy. + let mut stripped_monitors = Ring::default(); + *stripped_monitors.elements_mut() = wm + .monitors() + .iter() + .map(|monitor| Monitor { + id: monitor.id, + device: monitor.device.clone(), + serial_number_id: monitor.serial_number_id.clone(), + size: monitor.size, + work_area_size: monitor.work_area_size, + work_area_offset: monitor.work_area_offset, + workspaces: { + let mut ws = Ring::default(); + *ws.elements_mut() = monitor + .workspaces() + .iter() + .map(|workspace| Workspace { + containers: workspace.containers.clone(), + layout: workspace.layout.clone(), + workspace_padding: workspace.workspace_padding, + container_padding: workspace.container_padding, + globals: workspace.globals, + }) + .collect::>(); + ws.focus(monitor.workspaces.focused_idx()); + ws + }, + container_padding: monitor.container_padding, + workspace_padding: monitor.workspace_padding, + }) + .collect::>(); + stripped_monitors.focus(wm.monitors.focused_idx()); + + Self { + monitors: stripped_monitors, + work_area_offset: wm.work_area_offset, + mouse_follows_focus: wm.mouse_follows_focus, + } + } +} diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index 6898a75d..b662efce 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -5,8 +5,16 @@ //! workspace each window it manages is on. It changes when an event comes in //! ([`WindowManager::process_event`]), and every change ends with the focused workspace tiled //! again ([`WindowManager::update_focused_workspace`]). +//! +//! It also owns the daemon's command socket, which [`listen_for_commands`] reads +//! ([`WindowManager::process_command`]), and stops the daemon when it is asked to +//! ([`WindowManager::stop`]). +//! +//! [`listen_for_commands`]: crate::process_command::listen_for_commands +use crate::DATA_DIR; use crate::LibraryError; +use crate::backend::backend; use crate::container::Container; use crate::core::Rect; use crate::desktop; @@ -19,10 +27,16 @@ use color_eyre::eyre; use color_eyre::eyre::OptionExt; use crossbeam_channel::Receiver; use std::collections::HashMap; +use std::io::ErrorKind; +use std::os::unix::net::UnixListener; +use std::path::PathBuf; #[derive(Debug)] pub struct WindowManager { pub monitors: Ring, + /// The socket the daemon takes messages on, `komorebi.sock` in [`struct@DATA_DIR`] unless + /// [`WindowManager::new`] was given another path + pub command_listener: UnixListener, pub mouse_follows_focus: bool, pub work_area_offset: Option, /// The events the backend has reported and the window manager has yet to handle, from @@ -37,10 +51,37 @@ impl_ring_elements!(WindowManager, Monitor); impl WindowManager { /// Returns a window manager with no monitors, which handles the events that arrive on - /// `incoming`: [`WindowManager::init`] loads the monitors from the backend - pub fn new(incoming: Receiver) -> eyre::Result { + /// `incoming` and listens on `custom_socket_path`, or on `komorebi.sock` in + /// [`struct@DATA_DIR`] when that is `None`: [`WindowManager::init`] loads the monitors from + /// the backend + /// + /// A socket file that is left over at that path is removed first. + /// + /// # Errors + /// + /// - The leftover socket file is there but cannot be removed. + /// - The socket cannot be bound, for example because its directory does not exist. + pub fn new( + incoming: Receiver, + custom_socket_path: Option, + ) -> eyre::Result { + let socket = custom_socket_path.unwrap_or_else(|| DATA_DIR.join("komorebi.sock")); + + match std::fs::remove_file(&socket) { + Ok(()) => {} + Err(error) => match error.kind() { + ErrorKind::NotFound => {} + _ => { + return Err(error.into()); + } + }, + }; + + let listener = UnixListener::bind(&socket)?; + Ok(Self { monitors: Ring::default(), + command_listener: listener, mouse_follows_focus: true, work_area_offset: None, incoming_events: incoming, @@ -155,6 +196,20 @@ impl WindowManager { self.update_focused_workspace(false, false) } + /// Stops the daemon: removes the command socket, lets the backend give up what it set up in + /// the compositor, and exits the process with status 0 + #[tracing::instrument(skip(self))] + pub fn stop(&mut self) -> eyre::Result<()> { + tracing::info!("received stop command, terminating process"); + + let socket = DATA_DIR.join("komorebi.sock"); + let _ = std::fs::remove_file(socket); + + backend().shutdown(); + + std::process::exit(0) + } + /// Tiles the focused workspace of every monitor #[tracing::instrument(skip(self))] pub fn retile_all(&mut self) -> eyre::Result<()> { @@ -205,23 +260,73 @@ mod tests { use super::*; use crate::backend::fake::FakeBackend; use crate::backend::with_backend; + use crossbeam_channel::Sender; + use crossbeam_channel::bounded; + use std::path::PathBuf; use std::sync::Arc; + use uuid::Uuid; - fn setup_window_manager() -> WindowManager { - let (_sender, receiver) = crossbeam_channel::bounded(1); + struct TestContext { + socket_path: Option, + } + + impl Drop for TestContext { + fn drop(&mut self) { + if let Some(socket_path) = &self.socket_path { + // Clean up the socket file + std::fs::remove_file(socket_path).unwrap(); + } + } + } + + fn setup_window_manager() -> (WindowManager, TestContext) { + let (_sender, receiver): (Sender, Receiver) = + bounded(1); + + // Temporary socket path for testing + // /tmp: short enough for a unix socket path on macOS, and writable wherever the tests run + let socket_name = format!("/tmp/komorebi-test-{}.sock", Uuid::new_v4()); + let socket_path = PathBuf::from(socket_name); // Create a new WindowManager instance - let wm = WindowManager::new(receiver); + let wm = WindowManager::new(receiver, Some(socket_path.clone())); // Window Manager should be created successfully assert!(wm.is_ok()); - wm.unwrap() + ( + wm.unwrap(), + TestContext { + socket_path: Some(socket_path), + }, + ) } #[test] fn test_create_window_manager() { - let _wm = setup_window_manager(); + let (_wm, _test_context) = setup_window_manager(); + } + + #[test] + fn a_socket_file_left_behind_is_replaced() -> eyre::Result<()> { + let socket_path = PathBuf::from(format!("/tmp/komorebi-test-{}.sock", Uuid::new_v4())); + std::fs::write(&socket_path, "left behind by a daemon that crashed")?; + let _test_context = TestContext { + socket_path: Some(socket_path.clone()), + }; + + let (_sender, receiver): (Sender, Receiver) = + bounded(1); + let wm = WindowManager::new(receiver, Some(socket_path.clone()))?; + + assert_eq!( + wm.command_listener + .local_addr()? + .as_pathname() + .map(PathBuf::from), + Some(socket_path) + ); + Ok(()) } fn rect(left: i32, top: i32, right: i32, bottom: i32) -> Rect { @@ -256,7 +361,7 @@ mod tests { #[test] fn init_puts_each_open_window_on_the_monitor_it_is_on() -> eyre::Result<()> { let fake = two_monitors(&[601]); - let mut wm = setup_window_manager(); + let (mut wm, _test_context) = setup_window_manager(); with_backend(fake, || wm.init())?; @@ -273,7 +378,7 @@ mod tests { #[test] fn retile_all_tiles_the_focused_workspace_of_every_monitor() -> eyre::Result<()> { let fake = two_monitors(&[611]); - let mut wm = setup_window_manager(); + let (mut wm, _test_context) = setup_window_manager(); with_backend(fake.clone(), || { wm.init()?; @@ -292,7 +397,7 @@ mod tests { let fake = Arc::new(FakeBackend::with_one_monitor()); fake.open_window(621, "foot", "foot", "stays"); fake.open_window(622, "foot", "foot", "closes"); - let mut wm = setup_window_manager(); + let (mut wm, _test_context) = setup_window_manager(); with_backend(fake.clone(), || { wm.init()?; @@ -309,7 +414,7 @@ mod tests { fn a_minimized_window_is_kept_out_of_the_workspace() -> eyre::Result<()> { let fake = Arc::new(FakeBackend::with_one_monitor()); fake.open_window(631, "foot", "foot", "minimized"); - let mut wm = setup_window_manager(); + let (mut wm, _test_context) = setup_window_manager(); with_backend(fake, || { wm.init()?; diff --git a/komorebi/tests/no_kwin.rs b/komorebi/tests/no_kwin.rs index eea65d3f..8c03143e 100644 --- a/komorebi/tests/no_kwin.rs +++ b/komorebi/tests/no_kwin.rs @@ -1,6 +1,10 @@ -//! `komorebi` connects to KWin unless it is told to run against the in-memory desktop, and says -//! what went wrong when it cannot. +//! `komorebi` connects to KWin unless it is told to run against the in-memory desktop, says +//! what went wrong when it cannot, and then leaves the socket of a komorebi that is running +//! alone. +use std::os::unix::net::UnixListener; +use std::os::unix::net::UnixStream; +use std::path::Path; use std::process::Command; use std::process::Stdio; use std::time::Duration; @@ -8,12 +12,26 @@ use std::time::Duration; /// A bus that is not there, so that a test never reaches the KWin of the session it runs in const NO_BUS: &str = "unix:path=/nonexistent/komorebi-test.bus"; +/// A runtime directory of the test's own, made empty: komorebi makes its data directory, and +/// binds its socket there with `--fake-backend`, before anything else, so the user's runtime +/// directory is kept out of it, and it is writable where the user's home is not (the nix +/// sandbox). /tmp: short enough for a unix socket path on macOS. +fn runtime(test: &str) -> String { + let runtime = format!("/tmp/komorebi-no-kwin-{test}-{}", std::process::id()); + let _ = std::fs::remove_dir_all(&runtime); + std::fs::create_dir_all(&runtime).unwrap(); + runtime +} + #[test] fn without_a_session_bus_komorebi_exits_with_an_error_naming_it() { + let runtime = runtime("bus"); let output = Command::new(env!("CARGO_BIN_EXE_komorebi")) .env("DBUS_SESSION_BUS_ADDRESS", NO_BUS) + .env("XDG_RUNTIME_DIR", &runtime) .output() .expect("komorebi runs"); + let _ = std::fs::remove_dir_all(&runtime); assert_eq!(output.status.code(), Some(1)); @@ -24,11 +42,35 @@ fn without_a_session_bus_komorebi_exits_with_an_error_naming_it() { ); } +#[test] +fn without_kwin_komorebi_leaves_the_socket_it_finds_alone() { + let runtime = runtime("socket"); + let socket = Path::new(&runtime).join("komorebi").join("komorebi.sock"); + std::fs::create_dir_all(socket.parent().unwrap()).unwrap(); + // the socket of the komorebi that is running + let running = UnixListener::bind(&socket).unwrap(); + + let output = Command::new(env!("CARGO_BIN_EXE_komorebi")) + .env("DBUS_SESSION_BUS_ADDRESS", NO_BUS) + .env("XDG_RUNTIME_DIR", &runtime) + .output() + .expect("komorebi runs"); + + let still_there = UnixStream::connect(&socket).is_ok(); + drop(running); + let _ = std::fs::remove_dir_all(&runtime); + + assert_eq!(output.status.code(), Some(1)); + assert!(still_there, "the socket of the running komorebi was taken"); +} + #[test] fn with_the_fake_backend_komorebi_runs_without_a_session_bus() { + let runtime = runtime("fake"); let mut daemon = Command::new(env!("CARGO_BIN_EXE_komorebi")) .args(["--fake-backend", "--log-level", "error"]) .env("DBUS_SESSION_BUS_ADDRESS", NO_BUS) + .env("XDG_RUNTIME_DIR", &runtime) .stdout(Stdio::null()) .stderr(Stdio::null()) .spawn() @@ -39,5 +81,6 @@ fn with_the_fake_backend_komorebi_runs_without_a_session_bus() { daemon.kill().expect("komorebi can be stopped"); daemon.wait().expect("komorebi can be waited for"); + let _ = std::fs::remove_dir_all(&runtime); assert!(exited.is_none(), "komorebi exited: {exited:?}"); } diff --git a/komorebi/tests/socket.rs b/komorebi/tests/socket.rs new file mode 100644 index 00000000..43b0b6d1 --- /dev/null +++ b/komorebi/tests/socket.rs @@ -0,0 +1,88 @@ +//! The daemon over its socket: `komorebi --fake-backend` answers on `komorebi.sock` in its +//! runtime directory, and stops when it is sent `Stop`. + +use std::io::Read; +use std::io::Write; +use std::net::Shutdown; +use std::os::unix::net::UnixStream; +use std::path::Path; +use std::process::Child; +use std::process::Command; +use std::process::Stdio; +use std::time::Duration; +use std::time::Instant; + +/// The daemon, which is killed if the test ends before it stopped +struct Daemon(Child); + +impl Drop for Daemon { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } +} + +/// Waits up to ten seconds for `done` +fn eventually(mut done: impl FnMut() -> bool) -> bool { + let started = Instant::now(); + while started.elapsed() < Duration::from_secs(10) { + if done() { + return true; + } + std::thread::sleep(Duration::from_millis(20)); + } + false +} + +/// Writes `message` on a new connection to `socket` and returns the answer +fn send(socket: &Path, message: &str) -> std::io::Result { + let mut stream = UnixStream::connect(socket)?; + stream.write_all(message.as_bytes())?; + stream.shutdown(Shutdown::Write)?; + + let mut answer = String::new(); + stream.read_to_string(&mut answer)?; + Ok(answer) +} + +#[test] +fn the_daemon_answers_on_its_socket_and_stops_when_it_is_told_to() { + // /tmp: short enough for a unix socket path on macOS + let runtime = format!("/tmp/komorebi-socket-test-{}", std::process::id()); + let socket = Path::new(&runtime).join("komorebi").join("komorebi.sock"); + let _ = std::fs::remove_dir_all(&runtime); + std::fs::create_dir_all(&runtime).unwrap(); + + let mut daemon = Daemon( + Command::new(env!("CARGO_BIN_EXE_komorebi")) + .arg("--fake-backend") + .env("XDG_RUNTIME_DIR", &runtime) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .expect("komorebi runs"), + ); + + assert!( + eventually(|| send(&socket, r#"{"type":"State"}"#).is_ok()), + "nothing answers on {}", + socket.display() + ); + + let monitors: serde_json::Value = + serde_json::from_str(&send(&socket, r#"{"type":"MonitorInformation"}"#).unwrap()).unwrap(); + // the fake's one monitor + assert_eq!(monitors[0]["size"]["right"], 1920); + + send(&socket, r#"{"type":"Stop"}"#).unwrap(); + + let mut status = None; + assert!(eventually(|| { + status = daemon.0.try_wait().unwrap(); + status.is_some() + })); + assert_eq!(status.and_then(|status| status.code()), Some(0)); + assert!(!socket.exists(), "the socket is left behind"); + + let _ = std::fs::remove_dir_all(&runtime); +} diff --git a/komorebi/tests/wm_events.rs b/komorebi/tests/wm_events.rs index 34f79af9..4ecdf1bf 100644 --- a/komorebi/tests/wm_events.rs +++ b/komorebi/tests/wm_events.rs @@ -57,9 +57,16 @@ fn desktop() -> (Arc, WindowManager) { fn desktop_on(fake: FakeBackend) -> (Arc, WindowManager) { let fake = Arc::new(fake); let (_sender, receiver) = crossbeam_channel::bounded(1); + // unix socket paths are limited to ~104 bytes on macOS, which the temp dir alone can exceed + static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let socket = std::path::PathBuf::from(format!( + "/tmp/kmb-{}-{}.sock", + std::process::id(), + NEXT.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + )); let wm = with_backend(fake.clone(), || { - let mut wm = WindowManager::new(receiver).unwrap(); + let mut wm = WindowManager::new(receiver, Some(socket)).unwrap(); wm.init().unwrap(); wm });