diff --git a/README.md b/README.md index be1a4b58..6fd7a151 100644 --- a/README.md +++ b/README.md @@ -37,8 +37,8 @@ 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, give the focus to another -window, move the focused window to another tile, change the layout, retile -every monitor, or stop the daemon. [`komorebi-client`](komorebi-client) writes them, and `komorebic`, +window, move the focused window to another tile, change the layout, resize a +tile, retile every monitor, or stop the daemon. [`komorebi-client`](komorebi-client) writes them, and `komorebic`, the command line, is how a person sends them. `komorebic start` runs the `komorebi` on the `PATH`, and passes it what follows a `--`. In a Plasma session: @@ -137,8 +137,9 @@ one in the layout, or to the next one in the workspace's order, and `move` and `cycle-move` swap the focused container with that one and tile the workspace again. `change-layout`, `cycle-layout` and `flip-layout` tile the workspace in another layout, `layout-ratios` and `scrolling-layout-columns` tune it, -`toggle-tiling` stops it moving windows and starts it again, and -`preselect-direction` reserves a tile for the next window. The scrolling layout +`toggle-tiling` stops it moving windows and starts it again, +`preselect-direction` reserves a tile for the next window, and `resize-edge` +and `resize-axis` move the edges of the focused tile. 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. diff --git a/docs/cli/load-resize.md b/docs/cli/load-resize.md new file mode 100644 index 00000000..2cd2b591 --- /dev/null +++ b/docs/cli/load-resize.md @@ -0,0 +1,14 @@ +```text +Load the resize layout dimensions from a file + +Usage: load-resize + +Arguments: + + File from which the resize layout dimensions should be loaded + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/quick-load-resize.md b/docs/cli/quick-load-resize.md new file mode 100644 index 00000000..fcec7fe3 --- /dev/null +++ b/docs/cli/quick-load-resize.md @@ -0,0 +1,10 @@ +```text +Load the last quicksaved resize layout dimensions + +Usage: quick-load-resize + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/quick-save-resize.md b/docs/cli/quick-save-resize.md new file mode 100644 index 00000000..f8a8208b --- /dev/null +++ b/docs/cli/quick-save-resize.md @@ -0,0 +1,10 @@ +```text +Quicksave the current resize layout dimensions + +Usage: quick-save-resize + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/resize-axis.md b/docs/cli/resize-axis.md new file mode 100644 index 00000000..cbebabab --- /dev/null +++ b/docs/cli/resize-axis.md @@ -0,0 +1,22 @@ +```text +Resize the focused window or primary column along the specified axis + +Usage: resize-axis + +Arguments: + + Possible values: + - horizontal: Horizontal axis + - vertical: Vertical axis + - horizontal-and-vertical: Both horizontal and vertical axes + + + Possible values: + - increase: Increase + - decrease: Decrease + +Options: + -h, --help + Print help (see a summary with '-h') + +``` diff --git a/docs/cli/resize-delta.md b/docs/cli/resize-delta.md new file mode 100644 index 00000000..d7337700 --- /dev/null +++ b/docs/cli/resize-delta.md @@ -0,0 +1,14 @@ +```text +Set the resize delta (used by resize-edge and resize-axis) + +Usage: resize-delta + +Arguments: + + The delta of pixels by which to increase or decrease window dimensions when resizing + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/resize-edge.md b/docs/cli/resize-edge.md new file mode 100644 index 00000000..90fb5663 --- /dev/null +++ b/docs/cli/resize-edge.md @@ -0,0 +1,19 @@ +```text +Resize the focused window in the specified direction + +Usage: resize-edge + +Arguments: + + [possible values: left, right, up, down] + + + Possible values: + - increase: Increase + - decrease: Decrease + +Options: + -h, --help + Print help (see a summary with '-h') + +``` diff --git a/docs/cli/save-resize.md b/docs/cli/save-resize.md new file mode 100644 index 00000000..c63e784e --- /dev/null +++ b/docs/cli/save-resize.md @@ -0,0 +1,14 @@ +```text +Save the current resize layout dimensions to a file + +Usage: save-resize + +Arguments: + + File to which the resize layout dimensions should be saved + +Options: + -h, --help + Print help + +``` diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index b3f0fefb..c2c60932 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -27,7 +27,7 @@ its place here. - **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 - (focus a window, move it, change the layout, retile, stop) or a question (the state, the monitors, one [`StateQuery`]). + (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 ([`OperationDirection`]), or the next or the previous container of the workspace ([`CycleDirection`]). @@ -285,6 +285,16 @@ focused container has changed, which scrolls the strip to it. KWin keeps part of resizes on an output, so the bridge asks again for the position of a window KWin pulled back within a second of the command, three times at most ([`bridge.js`]'s `settle`). +`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 +the tiles; before every tiling, the workspace clears the parts of each adjustment that its layout +cannot apply, such as the top and the bottom of a column. The adjustment is the one +`komorebi-layouts` gives for the edge and [`WindowManager::resize_delta`], cut down until no tile +would be smaller than a tenth of the work area, or than it is already. The adjustments are kept +until a `Retile`, which drops them; `RetileWithResizeDimensions` tiles with them, and `Save`, +`Load`, `QuickSave` and `QuickLoad` write them to a file as JSON and read them back. + `PreselectDirection` reserves the index on one side of the focused container for the next window ([`WindowManager::preselect_container_in_direction`]). The workspace inserts an empty container there ([`Container::preselect`]), which [`Workspace::update`] keeps and the layout @@ -342,7 +352,8 @@ module's unit. changes its containers. - [`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). + window out, move the focus, move the focused container, change the layout, resize the + focused container). - [`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 @@ -426,6 +437,7 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | 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` | | A container moved onto a locked index is locked in its place, and the lock leaves the container that moved away | framework path: [`Workspace::swap_containers`] swaps through `LockableSequence`, which keeps the lock with the index | `test_swap_respecting_locks_various_cases`, `a_lock_stays_with_its_index_when_a_window_is_moved_onto_it` | `containers_mut()` is the `VecDeque` itself | | A window komorebi puts off the screen stays there | framework path: the bridge asks again for the position of a window KWin pulled back after a `geo` command, for a second, three times at most | `a window KWin pulls back from where it was asked to be is asked for the position again`, `a window that cannot go where it was asked is asked again three times at most`, `vm-scrolling` | a window that cannot go where it was asked is left where KWin put it | +| A resize leaves no tile smaller than a tenth of the work area, or than it was | framework path: [`WindowManager::resize_window`] calculates the tiles for the adjustment, and cuts the adjustment down until they all fit | `a_resize_leaves_every_tile_about_a_tenth_of_the_work_area_wide_at_least` | the paddings are taken off afterwards, so a tile can end up a little smaller | | A workspace whose tiling is off moves no window | framework path: [`Workspace::update`] returns before the layout when [`Workspace::tile`] is false | `with_tiling_off_no_window_is_moved_until_it_is_back_on` | none | | Moving the focus moves no window | test | `focus_gives_the_focus_to_the_window_on_that_side_and_moves_nothing`, `vm-core-e2e` ("moving the focus moved no window") | none | | A subscriber that is gone is dropped, not retried | test | `a_subscriber_that_is_gone_is_dropped_and_not_tried_again` | none | @@ -541,7 +553,7 @@ A window is shown, and ends up on a tile: commands against the fake; [`komorebi/tests/layout_options.rs`](../../komorebi/tests/layout_options.rs) and [`komorebi/tests/scrolling.rs`](../../komorebi/tests/scrolling.rs), the layout options and the - scrolling layout. + scrolling layout; [`komorebi/tests/resize.rs`](../../komorebi/tests/resize.rs), resizing. - [`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, @@ -579,6 +591,9 @@ A window is shown, and ends up on a tile: [`Workspace::swap_containers`]: ../../komorebi/src/workspace.rs [`Workspace::layout_flip`]: ../../komorebi/src/workspace.rs [`Workspace::layout_options`]: ../../komorebi/src/workspace.rs +[`Workspace::resize_dimensions`]: ../../komorebi/src/workspace.rs +[`WindowManager::resize_window`]: ../../komorebi/src/window_manager.rs +[`WindowManager::resize_delta`]: ../../komorebi/src/window_manager.rs [`Workspace::latest_layout`]: ../../komorebi/src/workspace.rs [`LayoutOptions`]: ../../komorebi/src/core/mod.rs [`Workspace::tile`]: ../../komorebi/src/workspace.rs diff --git a/docs/index.md b/docs/index.md index 8da35f5d..6a2a93a4 100644 --- a/docs/index.md +++ b/docs/index.md @@ -33,8 +33,9 @@ the flake's module, which also starts komorebi with every Plasma session, and fr anywhere else. [Running komorebi](usage/running-komorebi.md) explains how to start and stop the 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, and -[Layouts](usage/layouts.md) how to change the arrangement of the tiles. +[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, and +[Resizing windows](usage/resizing-windows.md) how to change the size of one. [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/resizing-windows.md b/docs/usage/resizing-windows.md new file mode 100644 index 00000000..4425d7f3 --- /dev/null +++ b/docs/usage/resizing-windows.md @@ -0,0 +1,63 @@ +# Resizing windows + +komorebi resizes the focused window by moving the edges of its tile, and its neighbors give up +the room. The size a tile has been given is kept until the workspace is retiled with +`komorebic retile`, so it lasts while windows open and close around it. + +## An edge + +[`komorebic resize-edge`](../cli/resize-edge.md) (or `resize`) moves one edge of the focused +window: `left`, `right`, `up` or `down`, and `increase` moves it outwards, `decrease` inwards. + +```sh +komorebic resize-edge left increase +komorebic resize-edge right decrease +``` + +An edge with no tile on the other side of it, such as the left edge of the first window in the +BSP layout, does not move. Neither does an edge the layout keeps where it is: the grid layout +has no resizing at all, and in the columns layout a window can only be made wider or narrower. + +## An axis + +[`komorebic resize-axis`](../cli/resize-axis.md) moves both edges of the focused window along an +axis: `horizontal` the left and the right edge, `vertical` the top and the bottom edge, and +`horizontal-and-vertical` all four. + +```sh +komorebic resize-axis horizontal increase +``` + +## How far + +[`komorebic resize-delta`](../cli/resize-delta.md) sets how far a resize goes, in pixels: an +edge moves by half of it. The delta starts at 50, so an edge moves by 25 pixels. + +```sh +komorebic resize-delta 100 +``` + +A resize never makes a tile narrower or shorter than a tenth of the monitor's work area, unless +the tile is smaller than that already: a resize that would is carried out as far as it can go. + +## Back to the layout + +[`komorebic retile`](../cli/retile.md) tiles every monitor again in its layout, without the +sizes the tiles were given. To tile again and keep them, send the `RetileWithResizeDimensions` +message, which has no subcommand of its own. + +## Saving and loading the sizes + +The sizes the tiles of the focused workspace were given can be saved to a file and loaded back, +on the same workspace or another one with as many windows: + +```sh +komorebic save-resize ~/sizes.json +komorebic load-resize ~/sizes.json +``` + +[`komorebic quick-save-resize`](../cli/quick-save-resize.md) and +[`komorebic quick-load-resize`](../cli/quick-load-resize.md) do the same with one file the daemon +keeps in its temporary directory, `komorebi.quicksave.json` in `$TMPDIR` (or `/tmp`). A path +given to `save-resize` and `load-resize` can name environment variables, which `komorebic` +expands. diff --git a/komorebi-client/src/lib.rs b/komorebi-client/src/lib.rs index f06c7f7c..af51ea46 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},"work_area_offset":null,"mouse_follows_focus":true}"#; +/// # let state = r#"{"monitors":{"elements":[],"focused":0},"resize_delta":50,"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},"work_area_offset":null,"mouse_follows_focus":true}"#; +/// # let state = r#"{"monitors":{"elements":[],"focused":0},"resize_delta":50,"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-client/tests/daemon.rs b/komorebi-client/tests/daemon.rs index 434bf5d5..d41f977b 100644 --- a/komorebi-client/tests/daemon.rs +++ b/komorebi-client/tests/daemon.rs @@ -40,7 +40,7 @@ fn daemon() -> Arc { let mut wm = WindowManager::new(window_manager_event_listener::event_rx(), None).unwrap(); wm.init().unwrap(); - wm.retile_all().unwrap(); + wm.retile_all(false).unwrap(); listen_for_commands(Arc::new(Mutex::new(wm))); fake diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index 48b1c403..8198e213 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -12,11 +12,13 @@ //! [`OperationDirection`] is a side of the focused tile, and a [`CycleDirection`] the next or the //! previous container in the order of the workspace. +use crate::core::pathext::ResolvedPathBuf; use clap::ValueEnum; use color_eyre::eyre; use serde::Deserialize; use serde::Serialize; use std::num::NonZeroUsize; +use std::path::PathBuf; use std::str::FromStr; use strum::Display; use strum::EnumString; @@ -344,6 +346,8 @@ pub enum SocketMessage { CancelPreselect, CycleFocusWindow(CycleDirection), CycleMoveWindow(CycleDirection), + ResizeWindowEdge(OperationDirection, Sizing), + ResizeWindowAxis(Axis, Sizing), // Current Workspace Commands ChangeLayout(DefaultLayout), CycleLayout(CycleDirection), @@ -356,6 +360,12 @@ pub enum SocketMessage { ToggleTiling, Stop, Retile, + RetileWithResizeDimensions, + QuickSave, + QuickLoad, + Save(#[serde_as(as = "ResolvedPathBuf")] PathBuf), + Load(#[serde_as(as = "ResolvedPathBuf")] PathBuf), + ResizeDelta(i32), State, MonitorInformation, Query(StateQuery), diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs index b3ca5641..79d8ade2 100644 --- a/komorebi/src/lib.rs +++ b/komorebi/src/lib.rs @@ -124,7 +124,7 @@ pub enum NotificationEvent { /// use komorebi::core::SocketMessage; /// use komorebi::window_manager_event::WindowManagerEvent; /// -/// let state = r#"{"monitors":{"elements":[],"focused":0},"work_area_offset":null,"mouse_follows_focus":true}"#; +/// let state = r#"{"monitors":{"elements":[],"focused":0},"resize_delta":50,"work_area_offset":null,"mouse_follows_focus":true}"#; /// /// let shown = format!( /// r#"{{"event":{{"type":"Show","content":[{{"type":"KWin","content":"WindowAdded"}},{{"id":7}}]}},"state":{state}}}"# @@ -199,7 +199,7 @@ pub struct Notification { /// ]); /// /// let state: State = serde_json::from_str( -/// r#"{"monitors":{"elements":[],"focused":0},"work_area_offset":null,"mouse_follows_focus":true}"#, +/// r#"{"monitors":{"elements":[],"focused":0},"resize_delta":50,"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/main.rs b/komorebi/src/main.rs index 71948819..378150ed 100644 --- a/komorebi/src/main.rs +++ b/komorebi/src/main.rs @@ -179,7 +179,7 @@ fn main() -> eyre::Result<()> { )?)); wm.lock().init()?; - wm.lock().retile_all()?; + wm.lock().retile_all(false)?; listen_for_commands(wm.clone()); listen_for_events(wm.clone()); diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index 3713f743..319e058c 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -32,7 +32,12 @@ //! already, and **CancelPreselect** gives the reserved place up. //! - **MouseFollowsFocus** and **ToggleMouseFollowsFocus** set whether the pointer is moved to //! the window that is given the focus. -//! - **Retile** tiles the focused workspace of every monitor again. +//! - **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 +//! focused workspace's containers to a file and read them back. +//! - **Retile** tiles the focused workspace of every monitor again, without the resize +//! adjustments, and **RetileWithResizeDimensions** with them. //! - **AddSubscriberSocket** and **AddSubscriberSocketWithOptions** add a subscriber by the name //! of its socket in the data directory, and **RemoveSubscriberSocket** removes one. //! - **Stop** stops the daemon ([`WindowManager::stop`]). @@ -45,8 +50,11 @@ use crate::Notification; use crate::NotificationEvent; use crate::SUBSCRIPTION_SOCKET_OPTIONS; use crate::SUBSCRIPTION_SOCKETS; +use crate::core::Axis; use crate::core::Layout; use crate::core::LayoutOptions; +use crate::core::OperationDirection; +use crate::core::Rect; use crate::core::ScrollingLayoutOptions; use crate::core::SocketMessage; use crate::core::StateQuery; @@ -55,8 +63,11 @@ use crate::notify_subscribers; use crate::state::State; use crate::window_manager::WindowManager; use color_eyre::eyre; +use color_eyre::eyre::Context; use color_eyre::eyre::OptionExt; use parking_lot::Mutex; +use std::fs::File; +use std::fs::OpenOptions; use std::io::BufRead; use std::io::BufReader; use std::os::unix::net::UnixStream; @@ -126,8 +137,10 @@ impl WindowManager { /// - The focused container cannot be moved, for one of the reasons /// [`WindowManager::move_container_in_direction`] and /// [`WindowManager::move_container_in_cycle_direction`] give. - /// - There is no focused workspace to change the layout or the tiling of, or to preselect a - /// place in, or it cannot be tiled again. + /// - There is no focused workspace to change the layout or the tiling of, to preselect a + /// place in, or to resize a container of, or it cannot be tiled again. + /// - 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 /// [`WindowManager::retile_all`] gives. /// - The answer cannot be written to `reply`. @@ -180,10 +193,74 @@ impl WindowManager { SocketMessage::CycleMoveWindow(direction) => { self.move_container_in_cycle_direction(direction)?; } + SocketMessage::ResizeWindowEdge(direction, sizing) => { + self.resize_window(direction, sizing, self.resize_delta, true)?; + } + SocketMessage::ResizeWindowAxis(axis, sizing) => { + match axis { + Axis::Horizontal => { + self.resize_window( + OperationDirection::Left, + sizing, + self.resize_delta, + false, + )?; + self.resize_window( + OperationDirection::Right, + sizing, + self.resize_delta, + false, + )?; + } + Axis::Vertical => { + self.resize_window( + OperationDirection::Up, + sizing, + self.resize_delta, + false, + )?; + self.resize_window( + OperationDirection::Down, + sizing, + self.resize_delta, + false, + )?; + } + Axis::HorizontalAndVertical => { + self.resize_window( + OperationDirection::Left, + sizing, + self.resize_delta, + false, + )?; + self.resize_window( + OperationDirection::Right, + sizing, + self.resize_delta, + false, + )?; + self.resize_window( + OperationDirection::Up, + sizing, + self.resize_delta, + false, + )?; + self.resize_window( + OperationDirection::Down, + sizing, + self.resize_delta, + false, + )?; + } + } + + self.update_focused_workspace(false, false)?; + } 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::Retile => self.retile_all()?, + SocketMessage::Retile => self.retile_all(false)?, + SocketMessage::RetileWithResizeDimensions => self.retile_all(true)?, SocketMessage::ToggleTiling => { self.toggle_tiling()?; } @@ -253,6 +330,9 @@ impl WindowManager { reply.write_all(response.as_bytes())?; } + SocketMessage::ResizeDelta(delta) => { + self.resize_delta = delta; + } SocketMessage::ScrollingLayoutColumns(count) => { let focused_workspace = self.focused_workspace_mut()?; @@ -327,6 +407,58 @@ impl WindowManager { SocketMessage::Stop => { self.stop()?; } + SocketMessage::QuickSave => { + let workspace = self.focused_workspace()?; + let resize = &workspace.resize_dimensions; + + let quicksave_json = std::env::temp_dir().join("komorebi.quicksave.json"); + + let file = OpenOptions::new() + .write(true) + .truncate(true) + .create(true) + .open(quicksave_json)?; + + serde_json::to_writer_pretty(&file, &resize)?; + } + SocketMessage::QuickLoad => { + let workspace = self.focused_workspace_mut()?; + + let quicksave_json = std::env::temp_dir().join("komorebi.quicksave.json"); + + let file = File::open(&quicksave_json).wrap_err(format!( + "no quicksave found at {}", + quicksave_json.display() + ))?; + + let resize: Vec> = serde_json::from_reader(file)?; + + workspace.resize_dimensions = resize; + self.update_focused_workspace(false, false)?; + } + SocketMessage::Save(ref path) => { + let workspace = self.focused_workspace_mut()?; + let resize = &workspace.resize_dimensions; + + let file = OpenOptions::new() + .write(true) + .truncate(true) + .create(true) + .open(path)?; + + serde_json::to_writer_pretty(&file, &resize)?; + } + SocketMessage::Load(ref path) => { + let workspace = self.focused_workspace_mut()?; + + let file = + File::open(path).wrap_err(format!("no file found at {}", path.display()))?; + + let resize: Vec> = serde_json::from_reader(file)?; + + workspace.resize_dimensions = resize; + self.update_focused_workspace(false, false)?; + } } self.update_known_window_ids(); diff --git a/komorebi/src/state.rs b/komorebi/src/state.rs index 65ebf6ad..0ee1f767 100644 --- a/komorebi/src/state.rs +++ b/komorebi/src/state.rs @@ -53,6 +53,7 @@ use std::collections::VecDeque; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct State { pub monitors: Ring, + pub resize_delta: i32, pub work_area_offset: Option, pub mouse_follows_focus: bool, } @@ -85,6 +86,7 @@ impl From<&WindowManager> for State { workspace_padding: workspace.workspace_padding, container_padding: workspace.container_padding, latest_layout: workspace.latest_layout.clone(), + resize_dimensions: workspace.resize_dimensions.clone(), tile: workspace.tile, globals: workspace.globals, preselected_container_idx: None, @@ -102,6 +104,7 @@ impl From<&WindowManager> for State { Self { monitors: stripped_monitors, work_area_offset: wm.work_area_offset, + resize_delta: wm.resize_delta, mouse_follows_focus: wm.mouse_follows_focus, } } diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index 171f18ed..630d9058 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -21,12 +21,14 @@ use crate::LibraryError; use crate::SUBSCRIPTION_SOCKETS; use crate::backend::backend; use crate::container::Container; +use crate::core::Arrangement; use crate::core::Axis; use crate::core::CycleDirection; use crate::core::DefaultLayout; use crate::core::Layout; use crate::core::OperationDirection; use crate::core::Rect; +use crate::core::Sizing; use crate::desktop; use crate::monitor::Monitor; use crate::ring::Ring; @@ -40,16 +42,22 @@ use crossbeam_channel::Receiver; use std::collections::HashMap; use std::io::ErrorKind; use std::net::Shutdown; +use std::num::NonZeroUsize; use std::os::unix::net::UnixListener; use std::os::unix::net::UnixStream; use std::path::PathBuf; +/// A tile cannot be resized to less than this fraction of the work area (or less than it already is) +const MINIMUM_TILE_FRACTION: i32 = 10; + #[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, + /// How many pixels `ResizeWindowEdge` and `ResizeWindowAxis` resize by + pub resize_delta: i32, /// Whether the pointer is moved to the window that is given the focus, which is the default pub mouse_follows_focus: bool, pub work_area_offset: Option, @@ -102,6 +110,7 @@ impl WindowManager { Ok(Self { monitors: Ring::default(), command_listener: listener, + resize_delta: 50, mouse_follows_focus: true, work_area_offset: None, incoming_events: incoming, @@ -343,6 +352,13 @@ impl WindowManager { .ok_or_eyre("there is no window") } + pub fn focused_monitor_work_area(&self) -> eyre::Result { + Ok(self + .focused_monitor() + .ok_or_eyre("there is no monitor")? + .work_area_size) + } + /// Takes a window the user minimized out of the focused workspace, and keeps it until it is /// restored pub fn extract_minimized_window(&mut self, window_id: u32) -> eyre::Result<()> { @@ -390,9 +406,179 @@ impl WindowManager { std::process::exit(0) } - /// Tiles the focused workspace of every monitor + /// Resizes the focused container by `delta` pixels on its `direction` side, by giving it a + /// resize adjustment that the layout applies, and tiles the workspace again if `update` is set + /// + /// The neighbors on that side give up the room, and none of the tiles may end up smaller than + /// a tenth of the monitor's work area, measured before the paddings are taken off, or than it + /// already is: a resize that would make one smaller is granted as far as it can be. Where + /// there is no container on that side, nothing changes. + /// + /// # Errors + /// + /// - There is no focused monitor, workspace or container. + /// - The workspace cannot be tiled again. #[tracing::instrument(skip(self))] - pub fn retile_all(&mut self) -> eyre::Result<()> { + pub fn resize_window( + &mut self, + direction: OperationDirection, + sizing: Sizing, + delta: i32, + update: bool, + ) -> eyre::Result<()> { + let focused_monitor_work_area = self.focused_monitor_work_area()?; + let workspace = self.focused_workspace_mut()?; + + match workspace.layout { + Layout::Default(layout) => { + tracing::debug!("resizing window"); + let len = NonZeroUsize::new(workspace.containers().len()) + .ok_or_eyre("there must be at least one container")?; + let focused_idx = workspace.focused_container_idx(); + let focused_idx_resize = workspace + .resize_dimensions + .get(focused_idx) + .ok_or_eyre("there is no resize adjustment for this container")?; + + if direction + .destination( + workspace.layout.as_boxed_direction().as_ref(), + workspace.layout_flip, + focused_idx, + len, + workspace.layout_options, + ) + .is_some() + { + let unaltered = layout.calculate( + &focused_monitor_work_area, + len, + workspace.container_padding, + workspace.layout_flip, + &[], + workspace.focused_container_idx(), + workspace.layout_options, + &workspace.latest_layout, + ); + + let mut direction = direction; + + // We only ever want to operate on the unflipped Rect positions when resizing, then we + // can flip them however they need to be flipped once the resizing has been done + if let Some(flip) = workspace.layout_flip { + match flip { + Axis::Horizontal => { + if matches!(direction, OperationDirection::Left) + || matches!(direction, OperationDirection::Right) + { + direction = direction.opposite(); + } + } + Axis::Vertical => { + if matches!(direction, OperationDirection::Up) + || matches!(direction, OperationDirection::Down) + { + direction = direction.opposite(); + } + } + Axis::HorizontalAndVertical => direction = direction.opposite(), + } + } + + let unaltered_tile = *unaltered + .get(focused_idx) + .ok_or_eyre("there is no last layout")?; + + // How much of what was asked for the layout can take. The layout crate no + // longer turns a resize down by the size of the container being resized + // (the wrong measure: the room is in the neighbours, and a narrow tile + // could not be dragged by more than half its own width, however much its + // neighbours had to give); the right one is what every tile looks like + // afterwards. None may end up smaller than a tenth of the work area, or + // than it already is, and a request that would is granted as far as it + // can be rather than dropped. + let min_width = focused_monitor_work_area.right / MINIMUM_TILE_FRACTION; + let min_height = focused_monitor_work_area.bottom / MINIMUM_TILE_FRACTION; + + let calculate = |dimensions: &[Option]| { + layout.calculate( + &focused_monitor_work_area, + len, + workspace.container_padding, + workspace.layout_flip, + dimensions, + focused_idx, + workspace.layout_options, + &workspace.latest_layout, + ) + }; + let now = calculate(&workspace.resize_dimensions); + let candidate = |amount: i32| { + layout.resize( + &unaltered_tile, + focused_idx_resize, + direction, + sizing, + amount, + ) + }; + let fits = |amount: i32| { + let mut dimensions = workspace.resize_dimensions.clone(); + dimensions[focused_idx] = candidate(amount); + calculate(&dimensions) + .iter() + .zip(now.iter()) + .all(|(tile, before)| { + tile.right >= min_width.min(before.right) + && tile.bottom >= min_height.min(before.bottom) + }) + }; + + let granted = if fits(delta) { + delta + } else { + // the tiles only ever get smaller as the amount grows + let (mut fits_at, mut fails_at) = (0, delta); + while fails_at - fits_at > 1 { + let middle = fits_at + (fails_at - fits_at) / 2; + if fits(middle) { + fits_at = middle; + } else { + fails_at = middle; + } + } + fits_at + }; + + if granted != delta { + tracing::debug!( + "granting {granted} of the {delta} asked for: a tile would get smaller than {min_width}x{min_height}" + ); + } + + if granted > 0 { + let resize = candidate(granted); + workspace.resize_dimensions[focused_idx] = resize; + } + + return if update { + self.update_focused_workspace(false, false) + } else { + Ok(()) + }; + } + + tracing::debug!("cannot resize container in this direction"); + } + } + + Ok(()) + } + + /// Tiles the focused workspace of every monitor, without the resize adjustments of its + /// containers unless `preserve_resize_dimensions` is set + #[tracing::instrument(skip(self))] + pub fn retile_all(&mut self, preserve_resize_dimensions: bool) -> eyre::Result<()> { let offset = self.work_area_offset; for monitor in self.monitors_mut() { @@ -409,6 +595,11 @@ impl WindowManager { .focused_workspace_mut() .ok_or_eyre("there is no workspace")?; + // Reset any resize adjustments if we want to force a retile + if !preserve_resize_dimensions { + workspace.resize_dimensions.fill(None); + } + workspace.update()?; } @@ -800,7 +991,7 @@ mod tests { with_backend(fake.clone(), || { wm.init()?; - wm.retile_all() + wm.retile_all(false) })?; // the default workspace and container padding are 5 each, and the second monitor has no diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index 689e8765..468a070f 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -33,6 +33,7 @@ pub struct Workspace { pub workspace_padding: Option, pub container_padding: Option, pub latest_layout: Vec, + pub resize_dimensions: Vec>, pub tile: bool, #[serde(skip)] pub globals: WorkspaceGlobals, @@ -48,6 +49,7 @@ impl Default for Workspace { containers: Default::default(), workspace_padding: None, container_padding: None, + resize_dimensions: vec![], layout: Layout::Default(DefaultLayout::BSP), latest_layout: vec![], layout_flip: None, @@ -206,6 +208,12 @@ impl Workspace { .containers_mut() .insert_respecting_locks(idx, container); + if insertion_idx > self.resize_dimensions.len() { + self.resize_dimensions.push(None); + } else { + self.resize_dimensions.insert(insertion_idx, None); + } + self.focus_container(insertion_idx); insertion_idx @@ -289,7 +297,13 @@ impl Workspace { // this fn respects locked container indexes - we should use it for pretty much everything // except monocle and maximize toggles pub fn remove_container_by_idx(&mut self, idx: usize) -> Option { - self.containers_mut().remove_respecting_locks(idx) + let container = self.containers_mut().remove_respecting_locks(idx); + + if idx < self.resize_dimensions.len() { + self.resize_dimensions.remove(idx); + } + + container } pub fn focus_previous_container(&mut self) { @@ -356,8 +370,9 @@ impl Workspace { /// part of the window is in view is first centered in the work area. A workspace whose tiling /// is off ([`Workspace::tile`] is false) moves no window. /// - /// The tiles are kept in [`Workspace::latest_layout`], which the scrolling layout scrolls - /// from. + /// The layout applies the resize adjustment of each container ([`Workspace::resize_dimensions`]) + /// after the parts its layout cannot apply have been cleared. The tiles are kept in + /// [`Workspace::latest_layout`], which the scrolling layout scrolls from. pub fn update(&mut self) -> eyre::Result<()> { // make sure we are never holding on to empty containers self.prune_duplicate_windows()?; @@ -396,6 +411,8 @@ impl Workspace { adjusted_work_area.add_padding(workspace_padding); + self.enforce_resize_constraints(); + if self.tile { // the backend batches the commands this produces and sends them together let result = (|| -> eyre::Result<()> { @@ -407,12 +424,13 @@ impl Workspace { )?, Some(container_padding), self.layout_flip, - &[], + &self.resize_dimensions, self.focused_container_idx(), self.layout_options, &self.latest_layout, ); + let resize_dimensions_is_empty = self.resize_dimensions.is_empty(); let is_scrolling = matches!(self.layout, Layout::Default(DefaultLayout::Scrolling)); @@ -459,7 +477,8 @@ impl Workspace { let percentage_override = proposed_percentage == 0.0 && current_percentage > 0.1 - && current_percentage < 100.0; + && current_percentage < 100.0 + && resize_dimensions_is_empty; if percentage_override { window.center(&work_area)?; @@ -478,10 +497,296 @@ impl Workspace { result?; } + // Always make sure that the length of the resize dimensions vec is the same as the + // number of layouts / containers. This should never actually truncate as the remove_window + // function takes care of cleaning up resize dimensions when destroying empty containers + let container_count = self.containers().len(); + self.resize_dimensions.resize(container_count, None); + Ok(()) } } +impl Workspace { + fn enforce_resize_constraints(&mut self) { + match self.layout { + Layout::Default(DefaultLayout::BSP) => self.enforce_resize_constraints_for_bsp(), + Layout::Default(DefaultLayout::Columns) => self.enforce_resize_for_columns(), + Layout::Default(DefaultLayout::Rows) => self.enforce_resize_for_rows(), + Layout::Default(DefaultLayout::VerticalStack) => { + self.enforce_resize_for_vertical_stack(); + } + Layout::Default(DefaultLayout::RightMainVerticalStack) => { + self.enforce_resize_for_right_vertical_stack(); + } + Layout::Default(DefaultLayout::HorizontalStack) => { + self.enforce_resize_for_horizontal_stack(); + } + Layout::Default(DefaultLayout::UltrawideVerticalStack) => { + self.enforce_resize_for_ultrawide(); + } + Layout::Default(DefaultLayout::Scrolling) => { + self.enforce_resize_for_scrolling(); + } + _ => self.enforce_no_resize(), + } + } + + fn enforce_resize_constraints_for_bsp(&mut self) { + for (i, rect) in self.resize_dimensions.iter_mut().enumerate() { + if let Some(rect) = rect { + // Even containers can't be resized to the bottom + if i % 2 == 0 { + rect.bottom = 0; + // Odd containers can't be resized to the right + } else { + rect.right = 0; + } + } + } + + // The first container can never be resized to the left or the top + if let Some(Some(first)) = self.resize_dimensions.first_mut() { + first.top = 0; + first.left = 0; + } + + // The last container can never be resized to the bottom or the right + if let Some(Some(last)) = self.resize_dimensions.last_mut() { + last.bottom = 0; + last.right = 0; + } + } + + fn enforce_resize_for_columns(&mut self) { + let resize_dimensions = &mut self.resize_dimensions; + match resize_dimensions.len() { + 0 | 1 => self.enforce_no_resize(), + _ => { + let len = resize_dimensions.len(); + for (i, rect) in resize_dimensions.iter_mut().enumerate() { + if let Some(rect) = rect { + rect.top = 0; + rect.bottom = 0; + + if i == 0 { + rect.left = 0; + } + if i == len - 1 { + rect.right = 0; + } + } + } + } + } + } + + fn enforce_resize_for_rows(&mut self) { + let resize_dimensions = &mut self.resize_dimensions; + match resize_dimensions.len() { + 0 | 1 => self.enforce_no_resize(), + _ => { + let len = resize_dimensions.len(); + for (i, rect) in resize_dimensions.iter_mut().enumerate() { + if let Some(rect) = rect { + rect.left = 0; + rect.right = 0; + + if i == 0 { + rect.top = 0; + } + if i == len - 1 { + rect.bottom = 0; + } + } + } + } + } + } + + fn enforce_resize_for_vertical_stack(&mut self) { + let resize_dimensions = &mut self.resize_dimensions; + match resize_dimensions.len() { + // Single window can not be resized at all + 0 | 1 => self.enforce_no_resize(), + _ => { + // Zero is actually on the left + if let Some(left) = resize_dimensions[0].as_mut() { + left.top = 0; + left.bottom = 0; + left.left = 0; + } + + // Handle stack on the right + let stack_size = resize_dimensions[1..].len(); + for (i, rect) in resize_dimensions[1..].iter_mut().enumerate() { + if let Some(rect) = rect { + // No containers can resize to the right + rect.right = 0; + + // First container in stack cant resize up + if i == 0 { + rect.top = 0; + } else if i == stack_size - 1 { + // Last cant be resized to the bottom + rect.bottom = 0; + } + } + } + } + } + } + + fn enforce_resize_for_right_vertical_stack(&mut self) { + let resize_dimensions = &mut self.resize_dimensions; + match resize_dimensions.len() { + // Single window can not be resized at all + 0 | 1 => self.enforce_no_resize(), + _ => { + // Zero is actually on the right + if let Some(left) = resize_dimensions[1].as_mut() { + left.top = 0; + left.bottom = 0; + left.right = 0; + } + + // Handle stack on the right + let stack_size = resize_dimensions[1..].len(); + for (i, rect) in resize_dimensions[1..].iter_mut().enumerate() { + if let Some(rect) = rect { + // No containers can resize to the left + rect.left = 0; + + // First container in stack cant resize up + if i == 0 { + rect.top = 0; + } else if i == stack_size - 1 { + // Last cant be resized to the bottom + rect.bottom = 0; + } + } + } + } + } + } + + fn enforce_resize_for_horizontal_stack(&mut self) { + let resize_dimensions = &mut self.resize_dimensions; + match resize_dimensions.len() { + 0 | 1 => self.enforce_no_resize(), + _ => { + if let Some(left) = resize_dimensions[0].as_mut() { + left.top = 0; + left.left = 0; + left.right = 0; + } + + let stack_size = resize_dimensions[1..].len(); + for (i, rect) in resize_dimensions[1..].iter_mut().enumerate() { + if let Some(rect) = rect { + rect.bottom = 0; + + if i == 0 { + rect.left = 0; + } + if i == stack_size - 1 { + rect.right = 0; + } + } + } + } + } + } + + fn enforce_resize_for_ultrawide(&mut self) { + let resize_dimensions = &mut self.resize_dimensions; + match resize_dimensions.len() { + // Single window can not be resized at all + 0 | 1 => self.enforce_no_resize(), + // Two windows can only be resized in the middle + 2 => { + // Zero is actually on the right + if let Some(right) = resize_dimensions[0].as_mut() { + right.top = 0; + right.bottom = 0; + right.right = 0; + } + + // One is on the left + if let Some(left) = resize_dimensions[1].as_mut() { + left.top = 0; + left.bottom = 0; + left.left = 0; + } + } + // Three or more windows means 0 is in center, 1 is at the left, 2.. are a vertical + // stack on the right + _ => { + // Central can be resized left or right + if let Some(right) = resize_dimensions[0].as_mut() { + right.top = 0; + right.bottom = 0; + } + + // Left one can only be resized to the right + if let Some(left) = resize_dimensions[1].as_mut() { + left.top = 0; + left.bottom = 0; + left.left = 0; + } + + // Handle stack on the right + let stack_size = resize_dimensions[2..].len(); + for (i, rect) in resize_dimensions[2..].iter_mut().enumerate() { + if let Some(rect) = rect { + // No containers can resize to the right + rect.right = 0; + + // First container in stack cant resize up + if i == 0 { + rect.top = 0; + } else if i == stack_size - 1 { + // Last cant be resized to the bottom + rect.bottom = 0; + } + } + } + } + } + } + + fn enforce_resize_for_scrolling(&mut self) { + let resize_dimensions = &mut self.resize_dimensions; + match resize_dimensions.len() { + 0 | 1 => self.enforce_no_resize(), + _ => { + let len = resize_dimensions.len(); + + for (i, rect) in resize_dimensions.iter_mut().enumerate() { + if let Some(rect) = rect { + rect.top = 0; + rect.bottom = 0; + + if i == 0 { + rect.left = 0; + } else if i == len - 1 { + rect.right = 0; + } + } + } + } + } + } + fn enforce_no_resize(&mut self) { + for rect in self.resize_dimensions.iter_mut().flatten() { + rect.left = 0; + rect.right = 0; + rect.top = 0; + rect.bottom = 0; + } + } +} + #[cfg(test)] mod tests { use super::*; @@ -1017,6 +1322,118 @@ mod tests { assert_eq!(focused_container.focused_window_idx(), 1); } + #[test] + fn test_layout_boundary_clamping() { + use crate::core::Rect; + use komorebi_layouts::default_layout::DefaultLayout; + use std::num::NonZeroUsize; + + // Simulate an ultrawide monitor at 5120px width + let work_area = Rect { + left: 0, + top: 0, + right: 5120, + bottom: 1440, + }; + + // Create a workspace with 2 containers in Columns layout + let layout = Layout::Default(DefaultLayout::Columns); + + // Simulate a resize adjustment that would cause overflow + // Container 0 gets expanded by 2100px to the right + let resize_dimensions = vec![ + Some(Rect { + left: 0, + top: 0, + right: 2100, + bottom: 0, + }), + None, + ]; + + // Calculate the layout + let mut layouts = layout.as_boxed_arrangement().calculate( + &work_area, + NonZeroUsize::new(2).unwrap(), + None, + None, + &resize_dimensions, + 0, + None, + &[], + ); + + // Apply boundary clamping (mimicking the logic in workspace.rs update()) + for layout in &mut layouts { + // Check horizontal boundaries + if layout.left < work_area.left { + layout.right -= work_area.left - layout.left; + layout.left = work_area.left; + } + let max_right_edge = work_area.left + work_area.right; + let current_right_edge = layout.left + layout.right; + if current_right_edge > max_right_edge { + layout.right = max_right_edge - layout.left; + } + + // Check vertical boundaries + if layout.top < work_area.top { + layout.bottom -= work_area.top - layout.top; + layout.top = work_area.top; + } + let max_bottom_edge = work_area.top + work_area.bottom; + let current_bottom_edge = layout.top + layout.bottom; + if current_bottom_edge > max_bottom_edge { + layout.bottom = max_bottom_edge - layout.top; + } + } + + // Verify that all layouts stay within work area boundaries + for layout in &layouts { + // Horizontal bounds + assert!( + layout.left >= work_area.left, + "Layout left ({}) should be >= work_area left ({})", + layout.left, + work_area.left + ); + let right_edge = layout.left + layout.right; + let max_right_edge = work_area.left + work_area.right; + assert!( + right_edge <= max_right_edge, + "Layout right edge ({}) should be <= work_area right edge ({})", + right_edge, + max_right_edge + ); + + // Vertical bounds + assert!( + layout.top >= work_area.top, + "Layout top ({}) should be >= work_area top ({})", + layout.top, + work_area.top + ); + let bottom_edge = layout.top + layout.bottom; + let max_bottom_edge = work_area.top + work_area.bottom; + assert!( + bottom_edge <= max_bottom_edge, + "Layout bottom edge ({}) should be <= work_area bottom edge ({})", + bottom_edge, + max_bottom_edge + ); + } + + // Additionally verify that with the resize adjustment, + // the second container doesn't bleed beyond 5120 + assert_eq!(layouts.len(), 2); + let container1_right_edge = layouts[1].left + layouts[1].right; + assert!( + container1_right_edge <= 5120, + "Container 1 right edge ({}) should not exceed monitor width (5120)", + container1_right_edge + ); + } + fn tile(left: i32, top: i32, right: i32, bottom: i32) -> Rect { Rect { left, diff --git a/komorebi/tests/resize.rs b/komorebi/tests/resize.rs new file mode 100644 index 00000000..8be939c5 --- /dev/null +++ b/komorebi/tests/resize.rs @@ -0,0 +1,237 @@ +//! Resizing the focused window from the command line, `resize-edge`, `resize-axis` and +//! `resize-delta`, and saving and loading the sizes, against an in-memory desktop: the messages go +//! in through [`WindowManager::process_command`], and what comes out is where the backend is asked +//! to put each window. +//! +//! Window ids are in the 23_000s. + +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::core::Axis; +use komorebi::core::DefaultLayout; +use komorebi::core::OperationDirection; +use komorebi::core::Rect; +use komorebi::core::Sizing; +use komorebi::core::SocketMessage; +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 std::sync::Arc; + +fn added(id: u32) -> WindowManagerEvent { + WindowManagerEvent::Show( + SystemNotification::KWin(KWinNotification::WindowAdded), + Window::from(id), + ) +} + +/// A window manager over a fake desktop with one 1920x1080 monitor (1920x1050 without the panel) +/// in `layout`, and a window for each of `ids`, opened in that order. The last one has the focus. +fn desktop_with(layout: DefaultLayout, 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/kmr-{}-{}.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 + }); + send(&fake, &mut wm, SocketMessage::ChangeLayout(layout)); + for &id in ids { + fake.open_window(id, "foot", "foot", &format!("terminal {id}")); + with_backend(fake.clone(), || wm.process_event(added(id))).unwrap(); + } + + (fake, wm) +} + +fn send(fake: &Arc, wm: &mut WindowManager, message: SocketMessage) { + with_backend(fake.clone(), || wm.process_command(message, Vec::new())).unwrap(); +} + +fn edge(direction: OperationDirection, sizing: Sizing) -> SocketMessage { + SocketMessage::ResizeWindowEdge(direction, sizing) +} + +fn rects(fake: &FakeBackend, ids: &[u32]) -> Vec { + ids.iter().map(|&id| fake.rect_of(id).unwrap()).collect() +} + +#[test] +fn resize_edge_moves_the_edge_between_the_focused_window_and_its_neighbor() { + let ids = [23_001, 23_002]; + let (fake, mut wm) = desktop_with(DefaultLayout::BSP, &ids); + let before = rects(&fake, &ids); + + // the second window has the focus, on the right: its left edge goes left by half the delta + // of 50, which is how komorebi-layouts moves an edge + send( + &fake, + &mut wm, + edge(OperationDirection::Left, Sizing::Increase), + ); + + let after = rects(&fake, &ids); + assert_eq!(after[1].left, before[1].left - 25, "{before:?} {after:?}"); + assert_eq!(after[1].right, before[1].right + 25); + assert_eq!(after[0].right, before[0].right - 25); + + send( + &fake, + &mut wm, + edge(OperationDirection::Left, Sizing::Decrease), + ); + + assert_eq!(rects(&fake, &ids), before); +} + +#[test] +fn resize_edge_on_a_side_with_no_neighbor_changes_nothing() { + let ids = [23_011, 23_012]; + let (fake, mut wm) = desktop_with(DefaultLayout::BSP, &ids); + let before = rects(&fake, &ids); + + send( + &fake, + &mut wm, + edge(OperationDirection::Right, Sizing::Increase), + ); + + assert_eq!(rects(&fake, &ids), before); + assert_eq!( + wm.focused_workspace().unwrap().resize_dimensions, + [None, None] + ); +} + +#[test] +fn resize_axis_moves_both_edges_along_the_axis() { + let ids = [23_021, 23_022, 23_023]; + let (fake, mut wm) = desktop_with(DefaultLayout::Columns, &ids); + send( + &fake, + &mut wm, + SocketMessage::CycleFocusWindow(komorebi::core::CycleDirection::Previous), + ); + assert_eq!(wm.focused_window().unwrap().id, 23_022); + let before = rects(&fake, &ids); + + send( + &fake, + &mut wm, + SocketMessage::ResizeWindowAxis(Axis::Horizontal, Sizing::Increase), + ); + + let after = rects(&fake, &ids); + assert_eq!(after[1].left, before[1].left - 25, "{before:?} {after:?}"); + assert_eq!(after[1].right, before[1].right + 50); + assert_eq!(after[0].right, before[0].right - 25); + assert_eq!(after[2].right, before[2].right - 25); +} + +#[test] +fn resize_delta_sets_how_far_a_resize_goes() { + let ids = [23_031, 23_032]; + let (fake, mut wm) = desktop_with(DefaultLayout::BSP, &ids); + let before = rects(&fake, &ids); + + send(&fake, &mut wm, SocketMessage::ResizeDelta(120)); + send( + &fake, + &mut wm, + edge(OperationDirection::Left, Sizing::Increase), + ); + + assert_eq!(wm.resize_delta, 120); + assert_eq!(fake.rect_of(23_032).unwrap().left, before[1].left - 60); +} + +#[test] +fn a_resize_leaves_every_tile_about_a_tenth_of_the_work_area_wide_at_least() { + let ids = [23_041, 23_042]; + let (fake, mut wm) = desktop_with(DefaultLayout::BSP, &ids); + + send(&fake, &mut wm, SocketMessage::ResizeDelta(5000)); + send( + &fake, + &mut wm, + edge(OperationDirection::Left, Sizing::Increase), + ); + + // a tenth of the work area, measured before the paddings are taken off the tiles + let after = rects(&fake, &ids); + assert!(after[0].right >= 1920 / 10 - 20, "{after:?}"); + assert!( + after[0].right < 400, + "it was granted as far as it goes: {after:?}" + ); +} + +#[test] +fn retile_forgets_the_resizes_and_retile_with_resize_dimensions_keeps_them() { + let ids = [23_051, 23_052]; + let (fake, mut wm) = desktop_with(DefaultLayout::BSP, &ids); + let before = rects(&fake, &ids); + send( + &fake, + &mut wm, + edge(OperationDirection::Left, Sizing::Increase), + ); + let resized = rects(&fake, &ids); + + send(&fake, &mut wm, SocketMessage::RetileWithResizeDimensions); + assert_eq!(rects(&fake, &ids), resized); + + send(&fake, &mut wm, SocketMessage::Retile); + assert_eq!(rects(&fake, &ids), before); +} + +#[test] +fn sizes_saved_to_a_file_are_loaded_back_from_it() { + let ids = [23_061, 23_062]; + let (fake, mut wm) = desktop_with(DefaultLayout::BSP, &ids); + let path = + std::env::temp_dir().join(format!("komorebi-resize-test-{}.json", std::process::id())); + send( + &fake, + &mut wm, + edge(OperationDirection::Left, Sizing::Increase), + ); + let resized = rects(&fake, &ids); + + send(&fake, &mut wm, SocketMessage::Save(path.clone())); + send(&fake, &mut wm, SocketMessage::Retile); + assert_ne!(rects(&fake, &ids), resized); + send(&fake, &mut wm, SocketMessage::Load(path.clone())); + + assert_eq!(rects(&fake, &ids), resized); + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn loading_sizes_from_a_file_that_is_not_there_is_an_error() { + let (fake, mut wm) = desktop_with(DefaultLayout::BSP, &[23_071]); + + let result = with_backend(fake.clone(), || { + wm.process_command( + SocketMessage::Load("/nonexistent/komorebi-resize.json".into()), + Vec::new(), + ) + }); + + assert_eq!( + result.map_err(|error| error.to_string()), + Err(String::from( + "no file found at /nonexistent/komorebi-resize.json" + )) + ); +} diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs index 5f6eb776..8fd4942a 100644 --- a/komorebic/src/main.rs +++ b/komorebic/src/main.rs @@ -5,13 +5,18 @@ //! is written and the answer is printed. The messages are [`komorebi_client::SocketMessage`]s, //! sent with [`komorebi_client::send_message`] and [`komorebi_client::send_query`]. //! -//! `focus` and `cycle-focus` give the focus to another window of the focused workspace, and -//! `mouse-follows-focus` and `toggle-mouse-follows-focus` set whether the pointer goes with it. -//! `move` and `cycle-move` move the focused window to another tile. `change-layout`, -//! `cycle-layout` and `flip-layout` change the layout of the focused workspace, `toggle-tiling` -//! turns its tiling off and on, `scrolling-layout-columns` and `layout-ratios` tune the layouts, -//! and `preselect-direction` and `cancel-preselect` reserve the place of the next window and give -//! it up. +//! The orders that change what the daemon tiles: +//! +//! - `focus` and `cycle-focus` give the focus to another window of the focused workspace, and +//! `mouse-follows-focus` and `toggle-mouse-follows-focus` set whether the pointer goes with it. +//! - `move` and `cycle-move` move the focused window to another tile. +//! - `change-layout`, `cycle-layout` and `flip-layout` change the layout of the focused +//! workspace, `scrolling-layout-columns` and `layout-ratios` tune it, `toggle-tiling` turns its +//! tiling off and on, and `preselect-direction` and `cancel-preselect` reserve the place of the +//! next window and give it up. +//! - `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. //! //! `subscribe-socket` and `unsubscribe-socket` add and remove a subscriber: a program that listens //! on a socket in the daemon's data directory, to which the daemon sends a notification after each @@ -32,8 +37,10 @@ use komorebi_client::Axis; use komorebi_client::CycleDirection; use komorebi_client::DefaultLayout; use komorebi_client::OperationDirection; +use komorebi_client::Sizing; use komorebi_client::SocketMessage; use komorebi_client::StateQuery; +use komorebi_client::replace_env_in_path; use komorebi_client::send_message; use komorebi_client::send_query; use std::fs::File; @@ -90,6 +97,28 @@ gen_enum_subcommand_args! { Query: StateQuery, } +#[derive(Parser)] +struct Resize { + #[clap(value_enum)] + edge: OperationDirection, + #[clap(value_enum)] + sizing: Sizing, +} + +#[derive(Parser)] +struct ResizeAxis { + #[clap(value_enum)] + axis: Axis, + #[clap(value_enum)] + sizing: Sizing, +} + +#[derive(Parser)] +struct ResizeDelta { + /// The delta of pixels by which to increase or decrease window dimensions when resizing + pixels: i32, +} + #[derive(Parser)] struct SubscribeSocket { /// Name of the socket to send event notifications to @@ -113,6 +142,20 @@ struct Start { #[derive(Parser)] struct Stop {} +#[derive(Parser)] +struct SaveResize { + /// File to which the resize layout dimensions should be saved + #[clap(value_parser = replace_env_in_path)] + path: PathBuf, +} + +#[derive(Parser)] +struct LoadResize { + /// File from which the resize layout dimensions should be loaded + #[clap(value_parser = replace_env_in_path)] + path: PathBuf, +} + #[derive(Parser)] struct ScrollingLayoutColumns { /// Desired number of visible columns @@ -187,6 +230,20 @@ enum SubCommand { // UnsubscribePipe(UnsubscribePipe), /// Tail komorebi's process logs (cancel with Ctrl-C) Log, + /// Quicksave the current resize layout dimensions + #[clap(alias = "quick-save")] + QuickSaveResize, + /// Load the last quicksaved resize layout dimensions + #[clap(alias = "quick-load")] + QuickLoadResize, + /// Save the current resize layout dimensions to a file + #[clap(arg_required_else_help = true)] + #[clap(alias = "save")] + SaveResize(SaveResize), + /// Load the resize layout dimensions from a file + #[clap(arg_required_else_help = true)] + #[clap(alias = "load")] + LoadResize(LoadResize), /// Change focus to the window in the specified direction #[clap(arg_required_else_help = true)] Focus(Focus), @@ -204,6 +261,16 @@ enum SubCommand { /// Move the focused window in the specified cycle direction #[clap(arg_required_else_help = true)] CycleMove(CycleMove), + /// Resize the focused window in the specified direction + #[clap(arg_required_else_help = true)] + #[clap(alias = "resize")] + ResizeEdge(Resize), + /// Resize the focused window or primary column along the specified axis + #[clap(arg_required_else_help = true)] + ResizeAxis(ResizeAxis), + /// Set the resize delta (used by resize-edge and resize-axis) + #[clap(arg_required_else_help = true)] + ResizeDelta(ResizeDelta), /// Set the layout on the focused workspace #[clap(arg_required_else_help = true)] ChangeLayout(ChangeLayout), @@ -375,6 +442,12 @@ fn main() -> eyre::Result<()> { SubCommand::FlipLayout(args) => { send_message(&SocketMessage::FlipLayout(args.axis))?; } + SubCommand::ResizeEdge(args) => { + send_message(&SocketMessage::ResizeWindowEdge(args.edge, args.sizing))?; + } + SubCommand::ResizeAxis(args) => { + send_message(&SocketMessage::ResizeWindowAxis(args.axis, args.sizing))?; + } SubCommand::Retile => { send_message(&SocketMessage::Retile)?; } @@ -390,6 +463,9 @@ fn main() -> eyre::Result<()> { SubCommand::MonitorInformation => { print_query(&SocketMessage::MonitorInformation); } + SubCommand::ResizeDelta(args) => { + send_message(&SocketMessage::ResizeDelta(args.pixels))?; + } SubCommand::ScrollingLayoutColumns(args) => { send_message(&SocketMessage::ScrollingLayoutColumns(args.count))?; } @@ -414,6 +490,18 @@ fn main() -> eyre::Result<()> { SubCommand::UnsubscribeSocket(args) => { send_message(&SocketMessage::RemoveSubscriberSocket(args.socket))?; } + SubCommand::QuickSaveResize => { + send_message(&SocketMessage::QuickSave)?; + } + SubCommand::QuickLoadResize => { + send_message(&SocketMessage::QuickLoad)?; + } + SubCommand::SaveResize(args) => { + send_message(&SocketMessage::Save(args.path))?; + } + SubCommand::LoadResize(args) => { + send_message(&SocketMessage::Load(args.path))?; + } } Ok(()) diff --git a/komorebic/tests/cli.rs b/komorebic/tests/cli.rs index 63882b84..2e3847a9 100644 --- a/komorebic/tests/cli.rs +++ b/komorebic/tests/cli.rs @@ -254,6 +254,36 @@ fn scrolling_layout_columns_refuses_zero() { assert!(!output.status.success(), "{output:?}"); } +#[test] +fn the_resize_subcommands_send_what_they_are_given() { + sends( + &["resize-edge", "left", "increase"], + r#"{"type":"ResizeWindowEdge","content":["Left","Increase"]}"#, + ); + sends( + &["resize", "down", "decrease"], + r#"{"type":"ResizeWindowEdge","content":["Down","Decrease"]}"#, + ); + sends( + &["resize-axis", "horizontal-and-vertical", "increase"], + r#"{"type":"ResizeWindowAxis","content":["HorizontalAndVertical","Increase"]}"#, + ); + sends( + &["resize-delta", "75"], + r#"{"type":"ResizeDelta","content":75}"#, + ); + sends(&["quick-save-resize"], r#"{"type":"QuickSave"}"#); + sends(&["quick-load"], r#"{"type":"QuickLoad"}"#); + sends( + &["save-resize", "/tmp/sizes.json"], + r#"{"type":"Save","content":"/tmp/sizes.json"}"#, + ); + sends( + &["load", "/tmp/sizes.json"], + r#"{"type":"Load","content":"/tmp/sizes.json"}"#, + ); +} + #[test] fn mouse_follows_focus_is_set_with_enable_and_disable_or_toggled() { sends( @@ -319,13 +349,20 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "flip-layout.md", "focus.md", "layout-ratios.md", + "load-resize.md", "log.md", "monitor-information.md", "mouse-follows-focus.md", "move.md", "preselect-direction.md", "query.md", + "quick-load-resize.md", + "quick-save-resize.md", + "resize-axis.md", + "resize-delta.md", + "resize-edge.md", "retile.md", + "save-resize.md", "scrolling-layout-columns.md", "start.md", "state.md", diff --git a/nix/tests/vm/suites/commands/test.py b/nix/tests/vm/suites/commands/test.py index 3e33bc8a..a29f4dcc 100644 --- a/nix/tests/vm/suites/commands/test.py +++ b/nix/tests/vm/suites/commands/test.py @@ -157,6 +157,14 @@ cycle-focus next cycle-focus previous cycle-move next cycle-move previous +resize-edge left increase +resize-edge right decrease +resize-edge up increase +resize-edge down decrease +resize-axis horizontal increase +resize-axis vertical decrease +resize-delta 50 +resize-delta 100 retile flip-layout horizontal flip-layout vertical @@ -202,6 +210,17 @@ for query in [ ]: status, out = kde.run(f"komorebic query {query}") checks.check(f"query {query} answers", status == 0 and out.strip() != "") +checks.check( + "quick-save-resize and quick-load-resize", + kde.run("komorebic quick-save-resize && komorebic quick-load-resize")[0] == 0, +) +checks.check( + "save-resize and load-resize", + kde.run( + "komorebic save-resize /tmp/e2e-resize.json && komorebic load-resize /tmp/e2e-resize.json" + )[0] + == 0, +) print("== 5. still all there") checks.check("komorebi has every window KWin has, and answers", healthy() == 0)