From 56294e1cd377e189345ce92676ba74fb940a2571 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 17:03:29 -0700 Subject: [PATCH] feat(wm): manage, minimize and close Every normal window KWin reports is tiled, and the only way to take one out of the layout was to float it, which keeps it a window komorebi manages. `komorebic unmanage` takes the focused window out of the layout, and komorebi leaves it alone until `komorebic manage` takes it back or the window closes. Both are events komorebi raises itself on the channel KWin's events go through, so they are handled in order with what KWin reports. `komorebic minimize` and `close` ask KWin to minimize or close the focused window, which leaves the layout when KWin reports that it did. `komorebic toggle-pause` pauses the daemon: it acts on no event, and takes only `toggle-pause`, `state` and `stop` on its socket until it is resumed. With `unmanaged-window-operation-behaviour no-op`, the daemon refuses every message while the focused window is not one it tiles. The vm-commands sweep pauses and resumes, sets the operation behavior, manages and closes the focused window, and a section of its own minimizes, unmanages and manages a window. --- README.md | 5 +- docs/cli/close.md | 10 + docs/cli/manage.md | 10 + docs/cli/minimize.md | 10 + docs/cli/toggle-pause.md | 10 + docs/cli/unmanage.md | 10 + .../unmanaged-window-operation-behaviour.md | 16 ++ docs/dev/ARCHITECTURE.md | 37 ++- docs/index.md | 6 +- docs/usage/managing-windows.md | 69 +++++ komorebi-client/src/lib.rs | 4 +- komorebi/src/core/mod.rs | 7 + komorebi/src/lib.rs | 7 +- komorebi/src/process_command.rs | 91 ++++++- komorebi/src/process_event.rs | 69 ++++- komorebi/src/state.rs | 17 +- komorebi/src/window_manager.rs | 83 ++++++ komorebi/src/window_manager_event.rs | 27 +- komorebi/src/workspace.rs | 44 ++++ komorebi/tests/manage.rs | 245 ++++++++++++++++++ komorebic/src/main.rs | 41 +++ komorebic/tests/cli.rs | 23 ++ nix/tests/vm/suites/commands/test.py | 47 +++- 23 files changed, 857 insertions(+), 31 deletions(-) create mode 100644 docs/cli/close.md create mode 100644 docs/cli/manage.md create mode 100644 docs/cli/minimize.md create mode 100644 docs/cli/toggle-pause.md create mode 100644 docs/cli/unmanage.md create mode 100644 docs/cli/unmanaged-window-operation-behaviour.md create mode 100644 docs/usage/managing-windows.md create mode 100644 komorebi/tests/manage.rs diff --git a/README.md b/README.md index 7b0828c3..c7a87e3f 100644 --- a/README.md +++ b/README.md @@ -143,7 +143,10 @@ another layout, `layout-ratios` and `scrolling-layout-columns` tune it, focused window to the largest tile, `toggle-float` takes it out of the layout, and `toggle-lock` keeps its container at its place. The scrolling layout is a strip of columns that runs past the edges of the monitor and scrolls to -the window that has the focus. +the window that has the focus. `minimize` and `close` ask KWin to minimize or +close the focused window, `unmanage` takes it out of the layout until `manage` +takes it back, and `toggle-pause` stops the daemon acting on events and orders +until it is resumed. A program such as a status bar can subscribe to the daemon's notifications: it listens on a socket of its own, and after each event and each message, the diff --git a/docs/cli/close.md b/docs/cli/close.md new file mode 100644 index 00000000..7f311fec --- /dev/null +++ b/docs/cli/close.md @@ -0,0 +1,10 @@ +```text +Close the focused window + +Usage: close + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/manage.md b/docs/cli/manage.md new file mode 100644 index 00000000..b898d165 --- /dev/null +++ b/docs/cli/manage.md @@ -0,0 +1,10 @@ +```text +Force komorebi to manage the focused window + +Usage: manage + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/minimize.md b/docs/cli/minimize.md new file mode 100644 index 00000000..0e15a9b7 --- /dev/null +++ b/docs/cli/minimize.md @@ -0,0 +1,10 @@ +```text +Minimize the focused window + +Usage: minimize + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/toggle-pause.md b/docs/cli/toggle-pause.md new file mode 100644 index 00000000..0f21d57b --- /dev/null +++ b/docs/cli/toggle-pause.md @@ -0,0 +1,10 @@ +```text +Toggle the paused state for all window tiling + +Usage: toggle-pause + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/unmanage.md b/docs/cli/unmanage.md new file mode 100644 index 00000000..0f779d5a --- /dev/null +++ b/docs/cli/unmanage.md @@ -0,0 +1,10 @@ +```text +Unmanage a window that was forcibly managed + +Usage: unmanage + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/unmanaged-window-operation-behaviour.md b/docs/cli/unmanaged-window-operation-behaviour.md new file mode 100644 index 00000000..8166e331 --- /dev/null +++ b/docs/cli/unmanaged-window-operation-behaviour.md @@ -0,0 +1,16 @@ +```text +Set the operation behavior when the focused window is not managed + +Usage: unmanaged-window-operation-behaviour + +Arguments: + + Possible values: + - op: Process commands on temporarily unmanaged/floated windows + - no-op: Ignore commands on temporarily unmanaged/floated windows + +Options: + -h, --help + Print help (see a summary with '-h') + +``` diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index 00d68065..ef6a4405 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -25,7 +25,8 @@ its place here. - **Layout**: the arrangement (BSP, columns, rows, ...) that turns a work area and a 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`]). + the focus, minimized or restored ([`WindowManagerEvent`]). Two events come from komorebi + itself: a command asks it to manage the focused window, or to stop managing it. - **Message**: what a client sends the daemon on its socket, a [`SocketMessage`]: an order (focus a window, move it, change the layout, resize it, retile, stop) or a question (the state, the monitors, one [`StateQuery`]). - **Direction**: where an order goes from the focused container: a side of its tile @@ -307,6 +308,26 @@ stays where it is. container given by its indices. A lock changes nothing until containers are inserted, removed or swapped around it, which the workspace does through `LockableSequence`. +`Minimize` and `Close` ask the backend to minimize or close the window the compositor has +focused, and change nothing else: the window leaves the layout when the compositor reports it, +through the `Minimize` and `Destroy` events. `UnmanageFocusedWindow` and `ManageFocusedWindow` +do not change the model either: they raise an `Unmanage` or a `Manage` event for the focused +window on the channel the backend's events go through +([`WindowManager::unmanage_focused_window`], [`WindowManager::manage_focused_window`]), and +the window manager handles them in order with the compositor's. An `Unmanage` is handled like a +`Destroy` of a window that stays open: the window leaves its workspace, is centered in the work +area, and its id goes into a list of unmanaged windows that `handle_event` checks before it acts +on any other event about a window; a `Manage` takes the id out of the list and is handled like a +`Show`. A `Destroy` takes the id out of the list too. + +`TogglePause` sets [`WindowManager::is_paused`]: while it is set, `handle_event` returns at once +for every event, and [`read_commands_uds`] hands only `TogglePause`, `State` and `Stop` to the +window manager. `UnmanagedWindowOperationBehaviour` sets +[`WindowManager::unmanaged_window_operation_behaviour`]: with `NoOp`, +[`WindowManager::process_command`] refuses every message while the window the compositor has +focused is in no container of the focused workspace +([`WindowManager::handle_unmanaged_window_behaviour`]). + `ResizeWindowEdge` and `ResizeWindowAxis` resize the focused container ([`WindowManager::resize_window`]). A resize is an adjustment of the container's tile, kept in [`Workspace::resize_dimensions`], one per container, which the layout applies when it calculates @@ -375,7 +396,8 @@ module's unit. - [`window_manager`](../../komorebi/src/window_manager.rs): the [`WindowManager`] and the operations on it (tile the workspace in front, tile every monitor, take a minimized window out, move the focus, move the focused container, change the layout, resize or - promote the focused container, float a window, lock a container). + promote the focused container, float a window, lock a container, manage and unmanage a + window). - [`desktop`](../../komorebi/src/desktop.rs): loads the monitors and the open windows from the backend. - [`window_manager_event`](../../komorebi/src/window_manager_event.rs) and @@ -441,6 +463,8 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | A command about a missing window is an error, not a panic | test | `a_command_about_a_window_nobody_opened_is_an_error` and `a_command_about_a_closed_window_is_an_error` against the fake, `a_command_about_a_window_the_table_does_not_know_is_an_error_and_sends_nothing` against the KWin backend | none | | A locked container keeps its index | framework path: a [`Workspace`] inserts, removes and swaps its containers through `LockableSequence` | `test_locked_containers_with_new_window`, `test_locked_containers_remove_window`, `a_window_that_opens_does_not_push_a_locked_container_from_its_index` | `containers_mut()` is the `VecDeque` itself | | A window komorebi does not manage is never moved | framework path: `handle_event` asks [`Window::should_manage`] before it acts on any event but a destroy | `dialogs_and_other_non_normal_windows_are_left_alone` | none | +| A window the user unmanaged stays out of the layout until it is managed again | framework path: `handle_event` checks the list of unmanaged windows before it acts on any event but a removal | `unmanage_takes_the_focused_window_out_until_manage_takes_it_back` | none | +| A paused window manager moves no window | framework path: `handle_event` returns before anything else, and [`read_commands_uds`] drops every message but `TogglePause`, `State` and `Stop` | `while_paused_no_event_changes_the_layout_and_manage_takes_in_a_window_it_missed`, `while_paused_only_toggle_pause_state_and_stop_are_handled` | none | | 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 | @@ -578,7 +602,9 @@ A window is shown, and ends up on a tile: scrolling layout; [`komorebi/tests/resize.rs`](../../komorebi/tests/resize.rs), resizing; [`komorebi/tests/promote.rs`](../../komorebi/tests/promote.rs), promoting; [`komorebi/tests/float.rs`](../../komorebi/tests/float.rs), floating; - [`komorebi/tests/lock.rs`](../../komorebi/tests/lock.rs), locking. + [`komorebi/tests/lock.rs`](../../komorebi/tests/lock.rs), locking; + [`komorebi/tests/manage.rs`](../../komorebi/tests/manage.rs), minimizing, closing, + unmanaging and managing the focused window, and pausing. - [`nix/tests/vm/suites/scrolling`](../../nix/tests/vm/suites/scrolling/test.py): the scrolling strip in a real KWin, with its columns out of view off the screen. - [`nix/tests/vm/suites/commands`](../../nix/tests/vm/suites/commands/test.py): every layout, @@ -620,6 +646,11 @@ A window is shown, and ends up on a tile: [`WindowManager::resize_window`]: ../../komorebi/src/window_manager.rs [`WindowManager::toggle_float`]: ../../komorebi/src/window_manager.rs [`WindowManager::toggle_lock`]: ../../komorebi/src/window_manager.rs +[`WindowManager::manage_focused_window`]: ../../komorebi/src/window_manager.rs +[`WindowManager::unmanage_focused_window`]: ../../komorebi/src/window_manager.rs +[`WindowManager::is_paused`]: ../../komorebi/src/window_manager.rs +[`WindowManager::unmanaged_window_operation_behaviour`]: ../../komorebi/src/window_manager.rs +[`WindowManager::handle_unmanaged_window_behaviour`]: ../../komorebi/src/window_manager.rs [`WindowManagementBehaviour::toggle_float_placement`]: ../../komorebi/src/core/mod.rs [`WindowManager::promote_container_to_front`]: ../../komorebi/src/window_manager.rs [`WindowManager::promote_container_swap`]: ../../komorebi/src/window_manager.rs diff --git a/docs/index.md b/docs/index.md index 77226bf8..e198924c 100644 --- a/docs/index.md +++ b/docs/index.md @@ -35,8 +35,10 @@ daemon, ask it what it is doing and read its log. [Focusing windows](usage/focusing-windows.md) explains how to give the focus to another window, [Moving windows](usage/moving-windows.md) how to move the focused window to another tile, [Layouts](usage/layouts.md) how to change the arrangement of the tiles, -[Resizing windows](usage/resizing-windows.md) how to change the size of one, and -[Floating windows](usage/floating-windows.md) how to take a window out of the layout. +[Resizing windows](usage/resizing-windows.md) how to change the size of one, +[Floating windows](usage/floating-windows.md) how to take a window out of the layout, and +[Managing windows](usage/managing-windows.md) how to minimize, close and unmanage the focused +window and pause the daemon. [Subscribing to notifications](usage/subscribing-to-notifications.md) explains how a program such as a status bar follows what komorebi does. The [CLI reference](cli/start.md) has a page for every `komorebic` command, generated from its help. diff --git a/docs/usage/managing-windows.md b/docs/usage/managing-windows.md new file mode 100644 index 00000000..f12cba3a --- /dev/null +++ b/docs/usage/managing-windows.md @@ -0,0 +1,69 @@ +# Managing windows + +komorebi tiles every normal application window that KWin reports, and leaves dialogs, splash +screens and other windows that are not for tiling alone. The commands here act on the window +that has the focus in KWin, take a window out of the layout or back into it, and pause the +daemon. + +## Minimizing and closing + +[`komorebic minimize`](../cli/minimize.md) asks KWin to minimize the window that has the focus, +and [`komorebic close`](../cli/close.md) asks it to close the window, as the buttons of its title +bar do. + +```sh +komorebic minimize +komorebic close +``` + +The window leaves the layout when KWin reports that it was minimized or closed, and the other +windows of the workspace share the work area. A minimized window comes back into the layout, in a +container of its own, when it is restored. + +## Taking a window out of the layout + +[`komorebic unmanage`](../cli/unmanage.md) takes the window that has the focus out of the layout. +It stays open, in the middle of the work area with the size it had, and komorebi leaves it alone +from then on: it does not tile it again, and it does not move it. +[`komorebic manage`](../cli/manage.md), with that window focused, puts it back in the layout, +after the focused window. + +```sh +komorebic unmanage +komorebic manage +``` + +`komorebic manage` also takes in a window komorebi missed, such as one that opened while the +daemon was paused. The daemon forgets an unmanaged window when it closes, and when the daemon +stops. + +## Commands while the focused window is not tiled + +By default, a command acts on the workspace whatever window has the focus. With +[`komorebic unmanaged-window-operation-behaviour no-op`](../cli/unmanaged-window-operation-behaviour.md), +the daemon ignores every command while the window that has the focus is not one of the windows it +tiles: a floating window, a window it does not manage, or one taken out with +`komorebic unmanage`. The daemon logs "ignoring commands while active window is not managed by +komorebi" for each. + +```sh +komorebic unmanaged-window-operation-behaviour no-op +komorebic unmanaged-window-operation-behaviour op +``` + +The commands that are ignored include `komorebic state`, `komorebic stop` and the command that +sets the behavior back to `op`: give the focus to a tiled window first. + +## Pausing + +[`komorebic toggle-pause`](../cli/toggle-pause.md) pauses the daemon, and the same command +resumes it. While it is paused, komorebi does not act on what KWin reports, so it moves no +window, and of its commands it carries out only `toggle-pause`, `state` and `stop`. The daemon's +state says whether it is paused, as `is_paused`. + +```sh +komorebic toggle-pause +``` + +What KWin reported while the daemon was paused is not acted on afterwards: a window that opened +in the meantime is not tiled until it is managed with `komorebic manage`. diff --git a/komorebi-client/src/lib.rs b/komorebi-client/src/lib.rs index af51ea46..699ebbc3 100644 --- a/komorebi-client/src/lib.rs +++ b/komorebi-client/src/lib.rs @@ -198,7 +198,7 @@ where /// # 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},"resize_delta":50,"work_area_offset":null,"mouse_follows_focus":true}"#; +/// # let state = r#"{"monitors":{"elements":[],"focused":0},"is_paused":false,"resize_delta":50,"unmanaged_window_operation_behaviour":"Op","work_area_offset":null,"mouse_follows_focus":true}"#; /// # stream.write_all(state.as_bytes()) /// # }); /// use komorebi_client::SocketMessage; @@ -260,7 +260,7 @@ pub fn send_query(message: &SocketMessage) -> std::io::Result { /// # 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},"resize_delta":50,"work_area_offset":null,"mouse_follows_focus":true}"#; +/// # let state = r#"{"monitors":{"elements":[],"focused":0},"is_paused":false,"resize_delta":50,"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) diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index cff153ae..ca685759 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -348,6 +348,9 @@ pub enum SocketMessage { CycleMoveWindow(CycleDirection), ResizeWindowEdge(OperationDirection, Sizing), ResizeWindowAxis(Axis, Sizing), + // ForceFocus, + Close, + Minimize, Promote, PromoteSwap, PromoteFocus, @@ -356,7 +359,10 @@ pub enum SocketMessage { UnlockMonitorWorkspaceContainer(usize, usize, usize), ToggleLock, ToggleFloat, + UnmanagedWindowOperationBehaviour(OperationBehaviour), // Current Workspace Commands + ManageFocusedWindow, + UnmanageFocusedWindow, ChangeLayout(DefaultLayout), CycleLayout(CycleDirection), ScrollingLayoutColumns(NonZeroUsize), @@ -367,6 +373,7 @@ pub enum SocketMessage { // MonitorIndexPreference(usize, i32, i32, i32, i32), ToggleTiling, Stop, + TogglePause, Retile, RetileWithResizeDimensions, QuickSave, diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs index a7397297..bdfedbb5 100644 --- a/komorebi/src/lib.rs +++ b/komorebi/src/lib.rs @@ -95,6 +95,9 @@ lazy_static! { static ref FLOATING_WINDOW_TOGGLE_ASPECT_RATIO: Arc> = Arc::new(Mutex::new( AspectRatio::Predefined(PredefinedAspectRatio::Widescreen) )); + /// The windows `UnmanageFocusedWindow` took out of the layout: komorebi leaves them alone + /// until `ManageFocusedWindow` takes them back, or until they close + static ref UNMANAGED_WINDOW_IDS: Arc>> = Arc::new(Mutex::new(vec![])); } /// The padding, in pixels, between the edge of a monitor's work area and the tiles of its @@ -131,7 +134,7 @@ pub enum NotificationEvent { /// use komorebi::core::SocketMessage; /// use komorebi::window_manager_event::WindowManagerEvent; /// -/// let state = r#"{"monitors":{"elements":[],"focused":0},"resize_delta":50,"work_area_offset":null,"mouse_follows_focus":true}"#; +/// let state = r#"{"monitors":{"elements":[],"focused":0},"is_paused":false,"resize_delta":50,"unmanaged_window_operation_behaviour":"Op","work_area_offset":null,"mouse_follows_focus":true}"#; /// /// let shown = format!( /// r#"{{"event":{{"type":"Show","content":[{{"type":"KWin","content":"WindowAdded"}},{{"id":7}}]}},"state":{state}}}"# @@ -206,7 +209,7 @@ pub struct Notification { /// ]); /// /// let state: State = serde_json::from_str( -/// r#"{"monitors":{"elements":[],"focused":0},"resize_delta":50,"work_area_offset":null,"mouse_follows_focus":true}"#, +/// r#"{"monitors":{"elements":[],"focused":0},"is_paused":false,"resize_delta":50,"unmanaged_window_operation_behaviour":"Op","work_area_offset":null,"mouse_follows_focus":true}"#, /// )?; /// let event = NotificationEvent::Socket(SocketMessage::Retile); /// notify_subscribers(Notification { event, state }, false)?; diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index 9a610dbb..1964cf0c 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -44,6 +44,17 @@ //! - **ToggleFloat** takes the focused window out of the layout into the floating windows of the //! workspace, which komorebi does not move, or puts a floating window back //! ([`WindowManager::toggle_float`]). +//! - **Minimize** and **Close** ask the compositor to minimize or close the window that has the +//! focus. The window leaves the layout when the compositor reports that it did. +//! - **UnmanageFocusedWindow** takes the window that has the focus out of the layout and leaves it +//! alone until it closes, and **ManageFocusedWindow** takes it back +//! ([`WindowManager::unmanage_focused_window`], [`WindowManager::manage_focused_window`]). +//! - **UnmanagedWindowOperationBehaviour** sets whether a message is carried out while the window +//! that has the focus is not tiled ([`WindowManager::handle_unmanaged_window_behaviour`]). With +//! `NoOp`, every message is refused then, this one included. +//! - **TogglePause** pauses the window manager, or resumes it: while it is paused, it handles no +//! event, and of the messages only **TogglePause**, **State** and **Stop** +//! ([`read_commands_uds`]). //! - **ResizeWindowEdge** and **ResizeWindowAxis** resize the focused container by the //! [`WindowManager::resize_delta`] that **ResizeDelta** sets ([`WindowManager::resize_window`]), //! and **QuickSave**, **QuickLoad**, **Save** and **Load** write the resize adjustments of the @@ -62,6 +73,7 @@ use crate::Notification; use crate::NotificationEvent; use crate::SUBSCRIPTION_SOCKET_OPTIONS; use crate::SUBSCRIPTION_SOCKETS; +use crate::backend::backend; use crate::core::Axis; use crate::core::Layout; use crate::core::LayoutOptions; @@ -73,6 +85,7 @@ use crate::core::StateQuery; use crate::monitor::MonitorInformation; use crate::notify_subscribers; use crate::state::State; +use crate::window::Window; use crate::window_manager::WindowManager; use color_eyre::eyre; use color_eyre::eyre::Context; @@ -142,6 +155,8 @@ impl WindowManager { /// /// # Errors /// + /// - The unmanaged window operation behavior is `NoOp` and the window that has the focus is not + /// tiled, for one of the reasons [`WindowManager::handle_unmanaged_window_behaviour`] gives. /// - A query about the focused monitor, workspace or container when there is none. /// - The focus cannot be moved, for one of the reasons /// [`WindowManager::focus_container_in_direction`] and @@ -155,6 +170,8 @@ impl WindowManager { /// `UnlockMonitorWorkspaceContainer` is not there (a container that is not there is ignored). /// - The focused window cannot be floated or put back, for one of the reasons /// [`WindowManager::toggle_float`] gives. + /// - `Minimize`, `Close`, `ManageFocusedWindow` or `UnmanageFocusedWindow` when the compositor + /// reports no focused window, or the backend refuses to minimize or close it. /// - The file of `QuickSave` or `Save` cannot be written, or the file of `QuickLoad` or /// `Load` cannot be read or is not a list of resize adjustments. /// - The window manager fails to retile, for one of the reasons @@ -174,6 +191,8 @@ impl WindowManager { // We don't have From implemented for &mut WindowManager let initial_state = State::from(self.as_ref()); + self.handle_unmanaged_window_behaviour()?; + match message { SocketMessage::Promote => self.promote_container_to_front()?, SocketMessage::PromoteSwap => self.promote_container_swap()?, @@ -280,6 +299,24 @@ impl WindowManager { self.update_focused_workspace(false, false)?; } + SocketMessage::Minimize => { + let foreground_window = backend() + .foreground_window() + .ok_or_eyre("there is no foreground window")?; + Window::from(foreground_window).minimize()?; + } + SocketMessage::Close => { + let foreground_window = backend() + .foreground_window() + .ok_or_eyre("there is no foreground window")?; + Window::from(foreground_window).close()?; + } + SocketMessage::ManageFocusedWindow => { + self.manage_focused_window()?; + } + SocketMessage::UnmanageFocusedWindow => { + self.unmanage_focused_window()?; + } SocketMessage::LockMonitorWorkspaceContainer( monitor_idx, workspace_idx, @@ -321,6 +358,15 @@ impl WindowManager { SocketMessage::FlipLayout(layout_flip) => self.flip_layout(layout_flip)?, SocketMessage::ChangeLayout(layout) => self.change_workspace_layout_default(layout)?, SocketMessage::CycleLayout(direction) => self.cycle_layout(direction)?, + SocketMessage::TogglePause => { + if self.is_paused { + tracing::info!("resuming"); + } else { + tracing::info!("pausing"); + } + + self.is_paused = !self.is_paused; + } SocketMessage::Retile => self.retile_all(false)?, SocketMessage::RetileWithResizeDimensions => self.retile_all(true)?, SocketMessage::ToggleLock => self.toggle_lock()?, @@ -450,6 +496,9 @@ impl WindowManager { SocketMessage::ToggleMouseFollowsFocus => { self.mouse_follows_focus = !self.mouse_follows_focus; } + SocketMessage::UnmanagedWindowOperationBehaviour(behaviour) => { + self.unmanaged_window_operation_behaviour = behaviour; + } SocketMessage::AddSubscriberSocket(ref socket) => { let mut sockets = SUBSCRIPTION_SOCKETS.lock(); let socket_path = DATA_DIR.join(socket); @@ -544,7 +593,9 @@ impl WindowManager { /// [`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. +/// dropped. While the window manager is paused, the first message that is not `TogglePause`, +/// `State` or `Stop` is dropped, and the first that is one of them is handled; either way, the +/// lines after it are not read. /// /// # Errors /// @@ -570,6 +621,18 @@ pub fn read_commands_uds( ); } Some(mut wm) => { + if wm.is_paused { + return match message { + SocketMessage::TogglePause | SocketMessage::State | SocketMessage::Stop => { + Ok(wm.process_command(message, &mut stream)?) + } + _ => { + tracing::trace!("ignoring while paused"); + Ok(()) + } + }; + } + wm.process_command(message.clone(), &mut stream)?; } } @@ -767,6 +830,32 @@ mod tests { Ok(()) } + #[test] + fn while_paused_only_toggle_pause_state_and_stop_are_handled() -> eyre::Result<()> { + let daemon = Daemon::new(two_windows(741)); + daemon.ask(SocketMessage::Retile)?; + let tile = daemon.fake.rect_of(741); + daemon.ask(SocketMessage::TogglePause)?; + daemon + .fake + .move_window_by_user(741, rect(300, 300, 400, 400)); + + assert_eq!(daemon.ask(SocketMessage::Retile)?, ""); + assert_eq!(daemon.fake.rect_of(741), Some(rect(300, 300, 400, 400))); + // the message that is dropped is the last one read on its connection + assert_eq!( + daemon.send("{\"type\":\"Retile\"}\n{\"type\":\"State\"}\n")?, + "" + ); + let state: serde_json::Value = serde_json::from_str(&daemon.ask(SocketMessage::State)?)?; + assert_eq!(state["is_paused"], true); + + daemon.ask(SocketMessage::TogglePause)?; + daemon.ask(SocketMessage::Retile)?; + assert_eq!(daemon.fake.rect_of(741), tile); + Ok(()) + } + #[test] fn a_line_that_is_not_a_message_is_an_error() { let daemon = Daemon::new(FakeBackend::with_one_monitor()); diff --git a/komorebi/src/process_event.rs b/komorebi/src/process_event.rs index d8719f69..8b052d74 100644 --- a/komorebi/src/process_event.rs +++ b/komorebi/src/process_event.rs @@ -1,12 +1,16 @@ //! How the window manager answers what the compositor reports: [`WindowManager::process_event`]. //! -//! An event about a window komorebi does not manage ([`Window::should_manage`]) changes nothing. -//! Otherwise: +//! Nothing changes while the window manager is paused (`TogglePause`). An event about a window +//! komorebi does not manage ([`Window::should_manage`]), or about one the user took out of the +//! layout with `UnmanageFocusedWindow`, changes nothing either. Otherwise: //! -//! - **Show**: the window gets a container of its own after the focused one, and the workspace is -//! tiled again. The first window on an empty workspace is given the focus. -//! - **Destroy**: the window is taken out of whichever workspace has it, and if that is the one in -//! front it is tiled again. +//! - **Show**, and **Manage** (`ManageFocusedWindow`): the window gets a container of its own after +//! the focused one, and the workspace is tiled again. The first window on an empty workspace is +//! given the focus. +//! - **Destroy**, and **Unmanage** (`UnmanageFocusedWindow`): the window is taken out of whichever +//! workspace has it, and if that is the one in front it is tiled again. A window that is +//! unmanaged stays open, centered in the work area so that it is not left behind the tiles, and +//! komorebi leaves it alone until it is managed again. //! - **FocusChange**: the workspace is tiled again and the container of the window that has the //! focus becomes the focused container. In the scrolling layout the workspace is tiled after //! that instead, so that the strip scrolls to the window that has the focus. @@ -23,6 +27,7 @@ use crate::Notification; use crate::NotificationEvent; +use crate::UNMANAGED_WINDOW_IDS; use crate::backend::backend; use crate::core::DefaultLayout; use crate::core::Layout; @@ -86,16 +91,25 @@ impl WindowManager { #[instrument(skip_all)] fn handle_event(&mut self, event: WindowManagerEvent) -> eyre::Result<()> { + if self.is_paused { + tracing::trace!("ignoring while paused"); + return Ok(()); + } + let Some(window) = event.window() else { return Ok(()); }; let window_id = window.id; - // A destroyed window can no longer be asked whether it should be managed, so a removal is - // let through without asking - let is_removal = matches!(event, WindowManagerEvent::Destroy(_, _)); + // A destroyed window can no longer be asked whether it should be managed, and a window the + // user unmanaged is let go of whatever it is, so a removal is let through without asking + let is_removal = matches!( + event, + WindowManagerEvent::Destroy(_, _) | WindowManagerEvent::Unmanage(_) + ); - let should_manage = is_removal || window.should_manage(); + let should_manage = is_removal + || (window.should_manage() && !UNMANAGED_WINDOW_IDS.lock().contains(&window_id)); if !should_manage { tracing::debug!("ignoring event as window should not be managed: {window}"); @@ -146,7 +160,7 @@ impl WindowManager { self.update_focused_workspace(self.mouse_follows_focus, false)?; } } - WindowManagerEvent::Show(_, _) => { + WindowManagerEvent::Show(_, _) | WindowManagerEvent::Manage(_) => { let mut create = true; if self.focused_workspace()?.contains_window(window_id) { @@ -179,11 +193,14 @@ impl WindowManager { } } } - WindowManagerEvent::Destroy(_, _) => { + WindowManagerEvent::Destroy(_, _) | WindowManagerEvent::Unmanage(_) => { + let destroyed = matches!(event, WindowManagerEvent::Destroy(_, _)); + // the window may be on any workspace, not only the one in front let location = self.known_window_ids.get(&window_id).cloned(); if let Some((m_idx, w_idx)) = location { + let behaviour = self.window_management_behaviour; let focused = m_idx == self.focused_monitor_idx() && Some(w_idx) == self.focused_workspace_idx().ok(); @@ -192,7 +209,25 @@ impl WindowManager { .get_mut(m_idx) .and_then(|m| m.workspaces_mut().get_mut(w_idx)) { - let _ = workspace.remove_window(window_id); + let removed = workspace.remove_window(window_id); + + if !destroyed + && focused + && let Ok(mut window) = removed + { + // we stopped managing a window that is still open, so it should not end up + // hidden behind the ones we do manage + let placement = if behaviour.floating_layer_override { + behaviour.floating_layer_placement + } else if behaviour.float_override { + behaviour.float_override_placement + } else { + behaviour.float_rule_placement + }; + + window + .center(&workspace.globals.work_area, placement.should_resize())?; + } } if focused { @@ -201,7 +236,13 @@ impl WindowManager { } } - self.minimized_windows.remove(&window_id); + if destroyed { + self.minimized_windows.remove(&window_id); + UNMANAGED_WINDOW_IDS.lock().retain(|id| *id != window_id); + } else { + // we only want to add the window ID after the window has been removed + UNMANAGED_WINDOW_IDS.lock().push(window_id); + } } WindowManagerEvent::Minimize(_, _) => { self.extract_minimized_window(window_id)?; diff --git a/komorebi/src/state.rs b/komorebi/src/state.rs index 9d497d84..a75fcbbf 100644 --- a/komorebi/src/state.rs +++ b/komorebi/src/state.rs @@ -8,6 +8,7 @@ //! [`SocketMessage::State`]: crate::core::SocketMessage::State //! [`Notification`]: crate::Notification +use crate::core::OperationBehaviour; use crate::core::Rect; use crate::monitor::Monitor; use crate::ring::Ring; @@ -53,7 +54,9 @@ use std::collections::VecDeque; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct State { pub monitors: Ring, + pub is_paused: bool, pub resize_delta: i32, + pub unmanaged_window_operation_behaviour: OperationBehaviour, pub work_area_offset: Option, pub mouse_follows_focus: bool, } @@ -105,17 +108,19 @@ impl From<&WindowManager> for State { Self { monitors: stripped_monitors, + is_paused: wm.is_paused, work_area_offset: wm.work_area_offset, resize_delta: wm.resize_delta, mouse_follows_focus: wm.mouse_follows_focus, + unmanaged_window_operation_behaviour: wm.unmanaged_window_operation_behaviour, } } } impl State { /// Returns true if and only if the window manager's monitors (with their workspaces, - /// containers and windows), its work area offset or its mouse follows focus setting differ - /// from this state's + /// containers and windows), whether it is paused, its unmanaged window operation behavior, its + /// work area offset or its mouse follows focus setting differ from this state's /// /// A window is compared by its id only, so a window that moved or was renamed is not a /// change. @@ -126,6 +131,14 @@ impl State { return true; } + if self.is_paused != new.is_paused { + return true; + } + + if self.unmanaged_window_operation_behaviour != new.unmanaged_window_operation_behaviour { + return true; + } + if self.work_area_offset != new.work_area_offset { return true; } diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index 815fbd04..e317fc3b 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -19,6 +19,7 @@ use crate::DATA_DIR; use crate::LibraryError; use crate::SUBSCRIPTION_SOCKETS; +use crate::UNMANAGED_WINDOW_IDS; use crate::backend::backend; use crate::container::Container; use crate::core::Arrangement; @@ -26,6 +27,7 @@ use crate::core::Axis; use crate::core::CycleDirection; use crate::core::DefaultLayout; use crate::core::Layout; +use crate::core::OperationBehaviour; use crate::core::OperationDirection; use crate::core::Rect; use crate::core::Sizing; @@ -36,6 +38,7 @@ use crate::monitor::Monitor; use crate::ring::Ring; use crate::window::Window; use crate::window_manager_event::WindowManagerEvent; +use crate::window_manager_event_listener; use crate::workspace::Workspace; use color_eyre::eyre; use color_eyre::eyre::OptionExt; @@ -58,8 +61,14 @@ pub struct WindowManager { /// The socket the daemon takes messages on, `komorebi.sock` in [`struct@DATA_DIR`] unless /// [`WindowManager::new`] was given another path pub command_listener: UnixListener, + /// Whether `TogglePause` has paused the window manager: while it is paused, it handles no + /// event, and of the messages only `TogglePause`, `State` and `Stop` + pub is_paused: bool, /// How many pixels `ResizeWindowEdge` and `ResizeWindowAxis` resize by pub resize_delta: i32, + /// Whether a message is carried out while the window that has the focus is not one komorebi + /// tiles ([`WindowManager::handle_unmanaged_window_behaviour`]) + pub unmanaged_window_operation_behaviour: OperationBehaviour, /// How new and floated windows are placed: `ToggleFloat` reads its `toggle_float_placement` pub window_management_behaviour: WindowManagementBehaviour, /// Whether the pointer is moved to the window that is given the focus, which is the default @@ -114,7 +123,9 @@ impl WindowManager { Ok(Self { monitors: Ring::default(), command_listener: listener, + is_paused: false, resize_delta: 50, + unmanaged_window_operation_behaviour: Default::default(), window_management_behaviour: WindowManagementBehaviour::default(), mouse_follows_focus: true, work_area_offset: None, @@ -949,6 +960,36 @@ impl WindowManager { self.update_focused_workspace(self.mouse_follows_focus, true) } + /// With [`OperationBehaviour::NoOp`], refuses a message while the window that has the focus + /// in the compositor is not in a container of the focused workspace: a window komorebi does + /// not manage, one the user unmanaged, or a floating window + /// + /// With [`OperationBehaviour::Op`], the default, every message is carried out. + /// + /// # Errors + /// + /// With [`OperationBehaviour::NoOp`]: + /// + /// - There is no focused workspace, or the compositor reports no focused window. + /// - The focused window is not in a container of the focused workspace. + #[tracing::instrument(skip(self))] + pub fn handle_unmanaged_window_behaviour(&self) -> eyre::Result<()> { + if matches!( + self.unmanaged_window_operation_behaviour, + OperationBehaviour::NoOp + ) { + let workspace = self.focused_workspace()?; + let focused_hwnd = backend() + .foreground_window() + .ok_or_eyre("there is no foreground window")?; + if !workspace.contains_managed_window(focused_hwnd) { + bail!("ignoring commands while active window is not managed by komorebi"); + } + } + + Ok(()) + } + pub fn update_known_window_ids(&mut self) { tracing::trace!("updating list of known window_ids"); let mut known_window_ids = HashMap::new(); @@ -971,6 +1012,48 @@ impl WindowManager { self.known_window_ids = known_window_ids; } } + + /// Asks the window manager to manage the window that has the focus in the compositor again + /// after [`WindowManager::unmanage_focused_window`], by raising a + /// [`WindowManagerEvent::Manage`] for it, which is handled like a window that opens + /// + /// # Errors + /// + /// The compositor reports no focused window. + #[tracing::instrument(skip(self))] + pub fn manage_focused_window(&mut self) -> eyre::Result<()> { + let window_id = backend() + .foreground_window() + .ok_or_eyre("there is no foreground window")?; + + UNMANAGED_WINDOW_IDS.lock().retain(|id| *id != window_id); + + window_manager_event_listener::send_notification(WindowManagerEvent::Manage(Window::from( + window_id, + ))); + + Ok(()) + } + + /// Asks the window manager to stop managing the window that has the focus in the compositor, + /// by raising a [`WindowManagerEvent::Unmanage`] for it: the window leaves the layout, and + /// komorebi leaves it alone until [`WindowManager::manage_focused_window`] or until it closes + /// + /// # Errors + /// + /// The compositor reports no focused window. + #[tracing::instrument(skip(self))] + pub fn unmanage_focused_window(&mut self) -> eyre::Result<()> { + let window_id = backend() + .foreground_window() + .ok_or_eyre("there is no foreground window")?; + + window_manager_event_listener::send_notification(WindowManagerEvent::Unmanage( + Window::from(window_id), + )); + + Ok(()) + } } #[cfg(test)] diff --git a/komorebi/src/window_manager_event.rs b/komorebi/src/window_manager_event.rs index 15e6a6f2..d815bd80 100644 --- a/komorebi/src/window_manager_event.rs +++ b/komorebi/src/window_manager_event.rs @@ -3,19 +3,23 @@ //! ([`WindowManager::process_event`](crate::window_manager::WindowManager::process_event)). //! //! An event is about one window and carries it, and the compositor signal it came from -//! ([`SystemNotification`]), which is only for logging. +//! ([`SystemNotification`]), which is only for logging. Two events come from komorebi itself +//! rather than from the compositor: [`WindowManagerEvent::Manage`] and +//! [`WindowManagerEvent::Unmanage`], which the commands that manage and unmanage the focused window +//! raise. use crate::window::Window; use serde::Deserialize; use serde::Serialize; use strum::Display; -/// The compositor signal a [`WindowManagerEvent`] came from +/// Where a [`WindowManagerEvent`] came from: a compositor signal, or komorebi itself #[derive(Debug, Copy, Clone, Serialize, Deserialize, Display, PartialEq, Eq)] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] #[serde(tag = "type", content = "content")] pub enum SystemNotification { KWin(KWinNotification), + Manual(ManualNotification), } /// The KWin script signals the bridge listens to @@ -34,6 +38,14 @@ pub enum KWinNotification { WindowRestored, } +/// Events komorebi raises itself, for example from a command +#[derive(Debug, Copy, Clone, Serialize, Deserialize, Display, PartialEq, Eq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub enum ManualNotification { + Manage, + Unmanage, +} + /// Window events: each carries the window it is about. #[derive(Debug, Copy, Clone, Serialize, Deserialize, Display)] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] @@ -44,6 +56,10 @@ pub enum WindowManagerEvent { Destroy(SystemNotification, Window), Minimize(SystemNotification, Window), Restore(SystemNotification, Window), + /// The user asked komorebi to manage the window (`ManageFocusedWindow`) + Manage(Window), + /// The user asked komorebi to stop managing the window (`UnmanageFocusedWindow`) + Unmanage(Window), } impl WindowManagerEvent { @@ -54,7 +70,9 @@ impl WindowManagerEvent { | WindowManagerEvent::Show(_, window) | WindowManagerEvent::Destroy(_, window) | WindowManagerEvent::Minimize(_, window) - | WindowManagerEvent::Restore(_, window) => *window, + | WindowManagerEvent::Restore(_, window) + | WindowManagerEvent::Manage(window) + | WindowManagerEvent::Unmanage(window) => *window, }) } @@ -75,7 +93,10 @@ impl WindowManagerEvent { | WindowManagerEvent::Minimize(n, _) | WindowManagerEvent::Restore(n, _) => match n { SystemNotification::KWin(k) => k.to_string(), + SystemNotification::Manual(m) => m.to_string(), }, + WindowManagerEvent::Manage(_) => ManualNotification::Manage.to_string(), + WindowManagerEvent::Unmanage(_) => ManualNotification::Unmanage.to_string(), } } } diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index 61f48c14..bd2ca5d7 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -368,6 +368,18 @@ impl Workspace { false } + /// Returns true if and only if the window is in one of the containers, which leaves out the + /// floating windows: the windows komorebi tiles + pub fn contains_managed_window(&self, window_id: u32) -> bool { + for container in self.containers() { + if container.contains_window(window_id) { + return true; + } + } + + false + } + pub fn remove_focused_container(&mut self) -> Option { let focused_idx = self.focused_container_idx(); let container = self.remove_container_by_idx(focused_idx); @@ -1520,6 +1532,38 @@ mod tests { assert_eq!(focused_container.focused_window_idx(), 1); } + #[test] + fn test_contains_managed_window() { + let mut workspace = Workspace::default(); + + { + // Container with 3 windows + let mut container = Container::default(); + for i in 0..3 { + container.windows_mut().push_back(Window::from(i)); + } + workspace.add_container_to_back(container); + } + + { + // Container with 1 window + let mut container = Container::default(); + container.windows_mut().push_back(Window::from(4)); + workspace.add_container_to_back(container); + } + + // Should return true, window is in container 1 + assert!(workspace.contains_managed_window(4)); + + // Should return true, all the windows are in container 0 + for i in 0..3 { + assert!(workspace.contains_managed_window(i)); + } + + // Should return false since window was never added + assert!(!workspace.contains_managed_window(5)); + } + #[test] fn test_new_floating_window() { let mut workspace = Workspace::default(); diff --git a/komorebi/tests/manage.rs b/komorebi/tests/manage.rs new file mode 100644 index 00000000..173d2b7c --- /dev/null +++ b/komorebi/tests/manage.rs @@ -0,0 +1,245 @@ +//! Minimizing, closing, unmanaging and managing the focused window, pausing the window manager, +//! and the unmanaged window operation behavior, against an in-memory desktop: the messages go in +//! through [`WindowManager::process_command`], and what comes out is what the backend was asked +//! for and the order of the containers. +//! +//! `UnmanageFocusedWindow` and `ManageFocusedWindow` raise an event on the process-wide channel of +//! [`window_manager_event_listener`], where the daemon's events thread would take it: the tests +//! that read the channel hold [`CHANNEL`] so that they do not take each other's events. +//! +//! Window ids are in the 27_000s. + +use komorebi::backend::fake::Command; +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::core::OperationBehaviour; +use komorebi::core::Rect; +use komorebi::core::SocketMessage; +use komorebi::state::State; +use komorebi::window::Window; +use komorebi::window_manager::WindowManager; +use komorebi::window_manager_event::KWinNotification; +use komorebi::window_manager_event::SystemNotification; +use komorebi::window_manager_event::WindowManagerEvent; +use komorebi::window_manager_event_listener; +use std::sync::Arc; +use std::sync::Mutex; +use std::time::Duration; + +static CHANNEL: Mutex<()> = Mutex::new(()); + +fn added(id: u32) -> WindowManagerEvent { + WindowManagerEvent::Show( + SystemNotification::KWin(KWinNotification::WindowAdded), + Window::from(id), + ) +} + +fn minimized(id: u32) -> WindowManagerEvent { + WindowManagerEvent::Minimize( + SystemNotification::KWin(KWinNotification::WindowMinimized), + Window::from(id), + ) +} + +/// A window manager over a fake desktop with one 1920x1080 monitor, and a window for each of +/// `ids`, opened in that order. The last one has the focus. +fn desktop_with(ids: &[u32]) -> (Arc, WindowManager) { + let fake = Arc::new(FakeBackend::with_one_monitor()); + 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/kmm-{}-{}.sock", + std::process::id(), + NEXT.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + )); + + let mut wm = with_backend(fake.clone(), || { + let mut wm = WindowManager::new(receiver, Some(socket)).unwrap(); + wm.init().unwrap(); + wm + }); + for &id in ids { + open(&fake, &mut wm, id); + } + fake.set_foreground(ids.last().copied()); + + (fake, wm) +} + +fn open(fake: &Arc, wm: &mut WindowManager, id: u32) { + fake.open_window(id, "foot", "foot", &format!("terminal {id}")); + with_backend(fake.clone(), || wm.process_event(added(id))).unwrap(); +} + +fn send( + fake: &Arc, + wm: &mut WindowManager, + message: SocketMessage, +) -> color_eyre::Result<()> { + with_backend(fake.clone(), || wm.process_command(message, Vec::new())) +} + +/// Takes the event about window `id` off the channel the daemon's events thread reads, and has +/// the window manager handle it, as that thread does +fn handle_raised(fake: &Arc, wm: &mut WindowManager, id: u32) -> WindowManagerEvent { + let events = window_manager_event_listener::event_rx(); + loop { + let event = events + .recv_timeout(Duration::from_secs(5)) + .expect("an event about the window is raised"); + if event.window_id() == Some(id) { + with_backend(fake.clone(), || wm.process_event(event)).unwrap(); + return event; + } + } +} + +/// The window of each container of the focused workspace, in order +fn order(wm: &WindowManager) -> Vec { + wm.focused_workspace() + .unwrap() + .containers() + .iter() + .map(|container| container.focused_window().unwrap().id) + .collect() +} + +#[test] +fn minimize_and_close_ask_the_compositor_about_the_window_that_has_the_focus() { + let (fake, mut wm) = desktop_with(&[27_001, 27_002]); + fake.clear_commands(); + + send(&fake, &mut wm, SocketMessage::Minimize).unwrap(); + assert_eq!(fake.commands(), [Command::Minimize(27_002)]); + // the window leaves the layout when the compositor reports it minimized, not before + assert_eq!(order(&wm), [27_001, 27_002]); + with_backend(fake.clone(), || wm.process_event(minimized(27_002))).unwrap(); + assert_eq!(order(&wm), [27_001]); + + fake.set_foreground(Some(27_001)); + fake.clear_commands(); + send(&fake, &mut wm, SocketMessage::Close).unwrap(); + assert_eq!(fake.commands(), [Command::Close(27_001)]); + + fake.set_foreground(None); + assert_eq!( + send(&fake, &mut wm, SocketMessage::Close).map_err(|error| error.to_string()), + Err(String::from("there is no foreground window")) + ); +} + +#[test] +fn unmanage_takes_the_focused_window_out_until_manage_takes_it_back() { + let _channel = CHANNEL + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let (fake, mut wm) = desktop_with(&[27_011, 27_012]); + let tile = fake.rect_of(27_012).unwrap(); + + send(&fake, &mut wm, SocketMessage::UnmanageFocusedWindow).unwrap(); + let event = handle_raised(&fake, &mut wm, 27_012); + assert!( + matches!(event, WindowManagerEvent::Unmanage(_)), + "{event:?}" + ); + + assert_eq!(order(&wm), [27_011]); + // the window stays open, centered in the 1920x1050 work area with the size of its tile + assert_eq!( + fake.rect_of(27_012), + Some(Rect { + left: (1920 - tile.right) / 2, + top: (1050 - tile.bottom) / 2, + right: tile.right, + bottom: tile.bottom, + }) + ); + + // the compositor announcing it again does not bring it back + with_backend(fake.clone(), || wm.process_event(added(27_012))).unwrap(); + assert_eq!(order(&wm), [27_011]); + + send(&fake, &mut wm, SocketMessage::ManageFocusedWindow).unwrap(); + let event = handle_raised(&fake, &mut wm, 27_012); + assert!(matches!(event, WindowManagerEvent::Manage(_)), "{event:?}"); + + assert_eq!(order(&wm), [27_011, 27_012]); +} + +#[test] +fn while_paused_no_event_changes_the_layout_and_manage_takes_in_a_window_it_missed() { + let _channel = CHANNEL + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let (fake, mut wm) = desktop_with(&[27_021]); + + send(&fake, &mut wm, SocketMessage::TogglePause).unwrap(); + assert!(State::from(&wm).is_paused); + open(&fake, &mut wm, 27_022); + assert_eq!(order(&wm), [27_021], "a window that opens is left alone"); + + send(&fake, &mut wm, SocketMessage::TogglePause).unwrap(); + assert!(!State::from(&wm).is_paused); + open(&fake, &mut wm, 27_023); + assert_eq!( + order(&wm), + [27_021, 27_023], + "the event that was missed is not handled afterwards" + ); + + fake.set_foreground(Some(27_022)); + send(&fake, &mut wm, SocketMessage::ManageFocusedWindow).unwrap(); + handle_raised(&fake, &mut wm, 27_022); + assert_eq!(order(&wm), [27_021, 27_023, 27_022]); +} + +#[test] +fn with_no_op_every_message_is_refused_while_the_focused_window_is_not_tiled() { + let (fake, mut wm) = desktop_with(&[27_031, 27_032]); + // a dialog, which komorebi does not manage, takes the focus + fake.open_window(27_033, "foot", "foot", "a dialog"); + fake.set_normal(27_033, false); + + send( + &fake, + &mut wm, + SocketMessage::UnmanagedWindowOperationBehaviour(OperationBehaviour::NoOp), + ) + .unwrap(); + assert_eq!( + State::from(&wm).unmanaged_window_operation_behaviour, + OperationBehaviour::NoOp + ); + send(&fake, &mut wm, SocketMessage::Retile).unwrap(); + + fake.set_foreground(Some(27_033)); + let refused = Err(String::from( + "ignoring commands while active window is not managed by komorebi", + )); + assert_eq!( + send(&fake, &mut wm, SocketMessage::Retile).map_err(|error| error.to_string()), + refused + ); + // this message too, while the dialog has the focus + assert_eq!( + send( + &fake, + &mut wm, + SocketMessage::UnmanagedWindowOperationBehaviour(OperationBehaviour::Op), + ) + .map_err(|error| error.to_string()), + refused + ); + + fake.set_foreground(Some(27_032)); + send( + &fake, + &mut wm, + SocketMessage::UnmanagedWindowOperationBehaviour(OperationBehaviour::Op), + ) + .unwrap(); + fake.set_foreground(Some(27_033)); + send(&fake, &mut wm, SocketMessage::Retile).unwrap(); +} diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs index c55c6a7d..c6d19657 100644 --- a/komorebic/src/main.rs +++ b/komorebic/src/main.rs @@ -18,6 +18,10 @@ //! tile, or the focus to it. //! - `toggle-float` takes the focused window out of the layout, or puts it back, and //! `toggle-lock` locks the focused container at its index, or unlocks it. +//! - `minimize` and `close` minimize and close the focused window, `unmanage` takes it out of +//! the layout until `manage` takes it back, `unmanaged-window-operation-behaviour` sets whether +//! the daemon carries out an order while the focused window is not one it tiles, and +//! `toggle-pause` pauses the daemon and resumes it. //! - `resize-edge` and `resize-axis` resize the focused window by the `resize-delta`, and //! `quick-save-resize`, `quick-load-resize`, `save-resize` and `load-resize` save the sizes of //! the tiles of the focused workspace and load them back. @@ -40,6 +44,7 @@ use fs_tail::TailedFile; use komorebi_client::Axis; use komorebi_client::CycleDirection; use komorebi_client::DefaultLayout; +use komorebi_client::OperationBehaviour; use komorebi_client::OperationDirection; use komorebi_client::Sizing; use komorebi_client::SocketMessage; @@ -99,6 +104,7 @@ gen_enum_subcommand_args! { // WatchConfiguration: BooleanState, MouseFollowsFocus: BooleanState, Query: StateQuery, + UnmanagedWindowOperationBehaviour: OperationBehaviour, PromoteWindow: OperationDirection, } @@ -260,6 +266,12 @@ enum SubCommand { PreselectDirection(PreselectDirection), /// Cancel a workspace preselect set by the preselect-direction command, if one exists CancelPreselect, + /// Minimize the focused window + Minimize, + /// Close the focused window + Close, + // /// Forcibly focus the window at the cursor with a left mouse click + // ForceFocus, /// Change focus to the window in the specified cycle direction #[clap(arg_required_else_help = true)] CycleFocus(CycleFocus), @@ -304,12 +316,21 @@ enum SubCommand { PromoteWindow(PromoteWindow), /// Force the retiling of all managed windows Retile, + /// Toggle the paused state for all window tiling + TogglePause, /// Toggle window tiling on the focused workspace ToggleTiling, /// Toggle floating mode for the focused window ToggleFloat, /// Toggle a lock for the focused container, ensuring it will not be displaced by any new windows ToggleLock, + /// Force komorebi to manage the focused window + Manage, + /// Unmanage a window that was forcibly managed + Unmanage, + /// Set the operation behavior when the focused window is not managed + #[clap(arg_required_else_help = true)] + UnmanagedWindowOperationBehaviour(UnmanagedWindowOperationBehaviour), /// Enable or disable mouse follows focus on all workspaces #[clap(arg_required_else_help = true)] MouseFollowsFocus(MouseFollowsFocus), @@ -450,6 +471,9 @@ fn main() -> eyre::Result<()> { SubCommand::CycleMove(args) => { send_message(&SocketMessage::CycleMoveWindow(args.cycle_direction))?; } + SubCommand::TogglePause => { + send_message(&SocketMessage::TogglePause)?; + } SubCommand::ChangeLayout(args) => { send_message(&SocketMessage::ChangeLayout(args.default_layout))?; } @@ -471,6 +495,18 @@ fn main() -> eyre::Result<()> { SubCommand::Retile => { send_message(&SocketMessage::Retile)?; } + SubCommand::Close => { + send_message(&SocketMessage::Close)?; + } + SubCommand::Minimize => { + send_message(&SocketMessage::Minimize)?; + } + SubCommand::Manage => { + send_message(&SocketMessage::ManageFocusedWindow)?; + } + SubCommand::Unmanage => { + send_message(&SocketMessage::UnmanageFocusedWindow)?; + } SubCommand::Promote => { send_message(&SocketMessage::Promote)?; } @@ -513,6 +549,11 @@ fn main() -> eyre::Result<()> { send_message(&SocketMessage::LayoutRatios(args.columns, args.rows))?; } } + SubCommand::UnmanagedWindowOperationBehaviour(args) => { + send_message(&SocketMessage::UnmanagedWindowOperationBehaviour( + args.operation_behaviour, + ))?; + } SubCommand::ToggleMouseFollowsFocus => { send_message(&SocketMessage::ToggleMouseFollowsFocus)?; } diff --git a/komorebic/tests/cli.rs b/komorebic/tests/cli.rs index 27338ffd..93f36fbd 100644 --- a/komorebic/tests/cli.rs +++ b/komorebic/tests/cli.rs @@ -297,6 +297,23 @@ fn the_promote_subcommands_send_their_message() { ); } +#[test] +fn the_subcommands_about_the_focused_window_and_pausing_send_their_message() { + sends(&["minimize"], r#"{"type":"Minimize"}"#); + sends(&["close"], r#"{"type":"Close"}"#); + sends(&["manage"], r#"{"type":"ManageFocusedWindow"}"#); + sends(&["unmanage"], r#"{"type":"UnmanageFocusedWindow"}"#); + sends(&["toggle-pause"], r#"{"type":"TogglePause"}"#); + sends( + &["unmanaged-window-operation-behaviour", "no-op"], + r#"{"type":"UnmanagedWindowOperationBehaviour","content":"NoOp"}"#, + ); + sends( + &["unmanaged-window-operation-behaviour", "op"], + r#"{"type":"UnmanagedWindowOperationBehaviour","content":"Op"}"#, + ); +} + #[test] fn mouse_follows_focus_is_set_with_enable_and_disable_or_toggled() { sends( @@ -354,6 +371,7 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { [ "cancel-preselect.md", "change-layout.md", + "close.md", "completions.md", "cycle-focus.md", "cycle-layout.md", @@ -364,6 +382,8 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "layout-ratios.md", "load-resize.md", "log.md", + "manage.md", + "minimize.md", "monitor-information.md", "mouse-follows-focus.md", "move.md", @@ -388,7 +408,10 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "toggle-float.md", "toggle-lock.md", "toggle-mouse-follows-focus.md", + "toggle-pause.md", "toggle-tiling.md", + "unmanage.md", + "unmanaged-window-operation-behaviour.md", "unsubscribe-socket.md", ] ); diff --git a/nix/tests/vm/suites/commands/test.py b/nix/tests/vm/suites/commands/test.py index 984b5f63..118fc25a 100644 --- a/nix/tests/vm/suites/commands/test.py +++ b/nix/tests/vm/suites/commands/test.py @@ -5,7 +5,9 @@ # windows are inside the outputs and do not lie on each other. A command is also expected to be # understood (exit status 0). The Rust tests check what each command does against the fake; this # suite checks that none of them breaks the daemon in a real session, and that what the daemon -# asks KWin for is what KWin carries out. Every command `komorebic` has is in the sweep. +# asks KWin for is what KWin carries out. Every command `komorebic` has is in the sweep, but +# `minimize` and `unmanage`, which take a window out of komorebi's hands and have a section of +# their own. import shlex from komorebi_vm import Checks, Kde, daemon @@ -188,10 +190,17 @@ toggle-lock toggle-lock toggle-tiling toggle-tiling +toggle-pause +toggle-pause +unmanaged-window-operation-behaviour op +unmanaged-window-operation-behaviour no-op +unmanaged-window-operation-behaviour op mouse-follows-focus enable mouse-follows-focus disable toggle-mouse-follows-focus toggle-mouse-follows-focus +manage +close retile """ for line in SWEEP.strip().splitlines(): @@ -204,6 +213,42 @@ for line in SWEEP.strip().splitlines(): continue checks.ok(f"komorebic {line}") +print("== 3b. minimize, unmanage and manage the focused window") +focused = kde.active() +title = kde.title(focused) +before = kde.managed() +kde.wait_for(lambda: kde.focused_title() == title, timeout=10) +kde.komorebic("minimize") +checks.check( + f"minimize: komorebi lets go of {title} when KWin minimizes it", + kde.wait_for(lambda: kde.managed() == before - 1, timeout=10) + and kde.wid(title) != "", +) +kde.activate(focused) +checks.check( + f"{title}, restored, is tiled again", + kde.wait_for(lambda: kde.managed() == before and healthy() == 0, timeout=10), +) +kde.wait_for(lambda: kde.focused_title() == title, timeout=10) +kde.komorebic("unmanage") +checks.check( + f"unmanage: komorebi lets go of {title}, which stays open", + kde.wait_for(lambda: kde.managed() == before - 1, timeout=10) and kde.wid(title) != "", +) + + +def centered() -> bool: + r = kde.rect(focused) + return abs(r.x + r.w // 2 - W // 2) <= CELL and abs(r.y + r.h // 2 - H // 2) <= CELL + + +checks.check(f"{title} is in the middle of the work area", kde.wait_for(centered, timeout=10)) +kde.komorebic("manage") +checks.check( + f"manage: {title} is tiled again", + kde.wait_for(lambda: kde.managed() == before and healthy() == 0, timeout=10), +) + print("== 4. what komorebic only prints") for args in ["state", "monitor-information", "data-directory"]: checks.check(f"komorebic {args}", kde.run(f"komorebic {args}")[0] == 0)