diff --git a/README.md b/README.md index 90970b17..be1a4b58 100644 --- a/README.md +++ b/README.md @@ -136,8 +136,11 @@ and `cycle-focus` give the focus to the container on one side of the focused 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, `toggle-tiling` stops it moving windows and starts it again, -and `preselect-direction` reserves a tile for the next window. +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 +is a strip of columns that runs past the edges of the monitor and scrolls to +the window that has the focus. 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/layout-ratios.md b/docs/cli/layout-ratios.md new file mode 100644 index 00000000..713bf9d9 --- /dev/null +++ b/docs/cli/layout-ratios.md @@ -0,0 +1,16 @@ +```text +Set the layout column and row ratios for the focused workspace + +Usage: layout-ratios [OPTIONS] + +Options: + -c, --columns ... + Column width ratios (space-separated values between 0.1 and 0.9) + + -r, --rows ... + Row height ratios (space-separated values between 0.1 and 0.9) + + -h, --help + Print help + +``` diff --git a/docs/cli/scrolling-layout-columns.md b/docs/cli/scrolling-layout-columns.md new file mode 100644 index 00000000..a27649d5 --- /dev/null +++ b/docs/cli/scrolling-layout-columns.md @@ -0,0 +1,14 @@ +```text +Set the number of visible columns for the Scrolling layout on the focused workspace + +Usage: scrolling-layout-columns + +Arguments: + + Desired number of visible columns + +Options: + -h, --help + Print help + +``` diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index 5aa3d1d6..b3f0fefb 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -271,6 +271,20 @@ flipped layout goes to the tile on the left. `ToggleTiling` turns the workspace' and on ([`Workspace::tile`]): with it off, [`Workspace::update`] moves no window, the workspace still takes the windows that open into containers, and they are tiled when it is turned on. +`LayoutRatios` and `ScrollingLayoutColumns` set the focused workspace's [`LayoutOptions`] +([`Workspace::layout_options`]): the share of the work area its first columns and rows take, and +the number of columns of the scrolling layout in view. The layout calculates the tiles from +them, and from the tiles it calculated last ([`Workspace::latest_layout`]), which the scrolling +layout scrolls from. + +The scrolling layout is a strip of columns that runs past the edges of the work area. Its tiles +are the only ones [`Workspace::update`] does not clamp to the work area, so the windows of the +columns out of view are off the screen; a window whose tile is out of view while part of it is +in view is centered in the work area first. A `FocusChange` tiles a scrolling workspace after the +focused container has changed, which scrolls the strip to it. KWin keeps part of a window it +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`). + `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 @@ -411,6 +425,7 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | A socket left behind by a daemon that did not stop cleanly does not keep the next one from starting | framework path: [`WindowManager::new`] removes the file before it binds | `a_socket_file_left_behind_is_replaced` | none | | A daemon that is told to stop leaves no socket behind | framework path: [`WindowManager::stop`] removes it before it exits | `the_daemon_answers_on_its_socket_and_stops_when_it_is_told_to` | `SIGKILL` | | 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 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 | @@ -523,7 +538,12 @@ A window is shown, and ends up on a tile: - [`komorebi/tests/focus.rs`](../../komorebi/tests/focus.rs), [`komorebi/tests/moving.rs`](../../komorebi/tests/moving.rs) and [`komorebi/tests/layouts.rs`](../../komorebi/tests/layouts.rs): the focus, move and layout - commands against the fake. + 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. +- [`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, and every `komorebic` command, against a real KWin with two outputs. - [`nix/nixos-module.nix`](../../nix/nixos-module.nix): the NixOS module; @@ -558,6 +578,9 @@ A window is shown, and ends up on a tile: [`WindowManager::move_container_in_cycle_direction`]: ../../komorebi/src/window_manager.rs [`Workspace::swap_containers`]: ../../komorebi/src/workspace.rs [`Workspace::layout_flip`]: ../../komorebi/src/workspace.rs +[`Workspace::layout_options`]: ../../komorebi/src/workspace.rs +[`Workspace::latest_layout`]: ../../komorebi/src/workspace.rs +[`LayoutOptions`]: ../../komorebi/src/core/mod.rs [`Workspace::tile`]: ../../komorebi/src/workspace.rs [`Layout`]: ../../komorebi/src/core/mod.rs [`Container::preselect`]: ../../komorebi/src/container.rs diff --git a/docs/dev/DESIGN.md b/docs/dev/DESIGN.md index 7ee69a41..cc625c47 100644 --- a/docs/dev/DESIGN.md +++ b/docs/dev/DESIGN.md @@ -210,3 +210,16 @@ So that the tests exercise the module. Every VM suite boots a machine that impor the module's read-only `execStart`, and the session node runs the module's unit itself. A change to the module that breaks how komorebi is installed or started fails the VM suites, and not only `nixos-module-eval`. + +## Why does the bridge ask KWin twice for the position of a window? + +KWin moves a window anywhere it is asked to, but when it resizes a window it keeps 100 pixels of +it on an output, and it does so once the client has drawn at the new size, which is after the +bridge has set the frame. The scrolling layout moves the windows of the columns out of view off +the screen and resizes them in the same command, and a terminal that rounds its size to its +cells is resized again by its client, so KWin pulls both back onto the screen. By then, setting +the position alone is a plain move, which KWin honors. The bridge remembers where it was asked +to put a window for a second, and sets the position again when the window's frame changes to +another one in that time ([PLATFORM.md](PLATFORM.md#how-clients-answer-a-frame)). Three tries +at most keep it from chasing a window that cannot go where it was asked, such as a fullscreen +one. diff --git a/docs/dev/PLATFORM.md b/docs/dev/PLATFORM.md index 34773adb..2948f47a 100644 --- a/docs/dev/PLATFORM.md +++ b/docs/dev/PLATFORM.md @@ -239,6 +239,16 @@ asked for. komorebi does not ask again when a client keeps to a size of its own: manager reads the frame the window has from the table, and a window larger than its tile covers part of its neighbor's. +KWin moves a window anywhere it is asked to, off the screen too, but when it *resizes* a window +it keeps 100 pixels of it on an output, and it does that once the client has drawn at the new +size. A window that is moved off the screen and resized at once, as the scrolling layout does +with the columns out of view, is pulled back onto the screen a moment later; so is one whose +client rounds the size, as `foot` does. The bridge therefore remembers the position it was asked +for, for a second, and when the window's frame changes to another position in that time, asks +for the position again, which is a plain move. It tries three times at most, so a window that +cannot go where it was asked is left alone. The VM test `vm-scrolling` checks that the columns +out of view stay where komorebi put them. + ## How long a retile takes Measured by the VM test `vm-latency` at time of writing (2026-10-27), in a headless KWin 6.8.1 diff --git a/docs/usage/layouts.md b/docs/usage/layouts.md index 1d01b011..52dc5140 100644 --- a/docs/usage/layouts.md +++ b/docs/usage/layouts.md @@ -39,6 +39,42 @@ right main vertical stack. [`komorebic query focused-workspace-layout`](../cli/query.md) prints the layout of the focused workspace. +## Ratios + +[`komorebic layout-ratios`](../cli/layout-ratios.md) sets the share of the work area the first +columns (`--columns`) and the first rows (`--rows`) of the focused workspace's layout take, as +fractions: `--columns 0.6` gives the first column 60% of the width, and the columns after it +share the rest. + +```sh +komorebic layout-ratios --columns 0.6 +komorebic layout-ratios --columns 0.5 0.3 --rows 0.7 +``` + +Each takes five ratios at most, each kept between 0.1 and 0.9, and the ratios after the one that +would make them add up to 1 are dropped, so that there is always room for another column or row. +The ratios stay with the workspace when its layout changes. Without `--columns` or `--rows`, +`layout-ratios` changes nothing. + +## The scrolling layout + +The scrolling layout puts every container in a column of its own, the columns side by side in a +strip that runs past the edges of the monitor. The windows of the columns out of view are off +the screen, and KWin leaves them there. When a window of the workspace gets the focus, the strip +scrolls so that its column is in view, so `komorebic focus left` and `focus right` walk along +it. + +[`komorebic scrolling-layout-columns`](../cli/scrolling-layout-columns.md) sets how many columns +are in view at once on the focused workspace: + +```sh +komorebic change-layout scrolling +komorebic scrolling-layout-columns 2 +``` + +Off the screen to the right of one monitor is on the next monitor over, if there is one, so the +columns out of view can show on it. + ## Flipping the layout [`komorebic flip-layout`](../cli/flip-layout.md) mirrors the tiles of the focused workspace: diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index 0c08554f..48b1c403 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -16,6 +16,7 @@ use clap::ValueEnum; use color_eyre::eyre; use serde::Deserialize; use serde::Serialize; +use std::num::NonZeroUsize; use std::str::FromStr; use strum::Display; use strum::EnumString; @@ -346,6 +347,8 @@ pub enum SocketMessage { // Current Workspace Commands ChangeLayout(DefaultLayout), CycleLayout(CycleDirection), + ScrollingLayoutColumns(NonZeroUsize), + LayoutRatios(Option>, Option>), // ChangeLayoutCustom(#[serde_as(as = "ResolvedPathBuf")] PathBuf), FlipLayout(Axis), // Monitor and Workspace Commands diff --git a/komorebi/src/kwin/bridge.js b/komorebi/src/kwin/bridge.js index 37a64286..2c4cab02 100644 --- a/komorebi/src/kwin/bridge.js +++ b/komorebi/src/kwin/bridge.js @@ -86,6 +86,18 @@ var seq = 0; /** @type {Record} */ var known = {}; +// Where the daemon last asked a window to be, for a moment after it asked. KWin honors a plain +// move to anywhere, but when a window is *resized* it keeps 100px of it on an output, so a window +// that komorebi puts off screen (the scrolling layout does) and resizes in the same breath, or +// whose client rounds the size (a terminal snapping to its cells), is pulled back onto the screen +// once the client has committed the new size. By then asking again for the position is a plain +// move. (The first geometry change, to the requested rect, comes before the client has answered, +// so a match does not end the watch; only the clock does.) +/** @type {Record} */ +var want = {}; +var WANT_RETRIES = 3; +var WANT_MS = 1000; + /** * @template {BridgeEvent["type"]} T * @param {T} type @@ -210,6 +222,29 @@ function findWindow(id) { return null; } +// A window has moved or been resized; if it is not where komorebi asked, ask again for the +// position alone (see `want`). A few tries at most, so a window that cannot go where it was asked +// (a fullscreen one, say) is left alone rather than chased. +/** + * @param {KWinWindow} w + * @param {string} id + */ +function settle(w, id) { + var t = want[id]; + if (!t || w.move || w.resize) { + return; + } + if (Date.now() > t.until || t.tries >= WANT_RETRIES) { + delete want[id]; + return; + } + var g = w.frameGeometry; + if (Math.round(g.x) !== t.x || Math.round(g.y) !== t.y) { + t.tries++; + w.frameGeometry = { x: t.x, y: t.y, width: g.width, height: g.height }; + } +} + // ---- hooks --------------------------------------------------------------------------------- /** @@ -227,6 +262,7 @@ function track(w, announce) { } w.frameGeometryChanged.connect(function (old) { emit("geometry", { id: id, geo: rect(w.frameGeometry) }); + settle(w, id); }); w.minimizedChanged.connect(function () { emit("minimized", { id: id, v: !!w.minimized }); @@ -239,6 +275,7 @@ workspace.windowAdded.connect(function (w) { workspace.windowRemoved.connect(function (w) { var id = wid(w); delete known[id]; + delete want[id]; emit("removed", { id: id }); }); /** @type {string | null} */ @@ -292,6 +329,7 @@ function applyOne(c) { switch (c.op) { case "geo": // a plain object converts to QRectF; there is no `Qt` global in kwin scripts + want[c.id] = { x: c.x, y: c.y, tries: 0, until: Date.now() + WANT_MS }; w.frameGeometry = { x: c.x, y: c.y, width: c.w, height: c.h }; break; case "min": diff --git a/komorebi/src/kwin/bridge.test.js b/komorebi/src/kwin/bridge.test.js index 8bbe61b8..2d51ddae 100644 --- a/komorebi/src/kwin/bridge.test.js +++ b/komorebi/src/kwin/bridge.test.js @@ -58,8 +58,15 @@ function geometry(x, y, width, height) { // A window. `id` becomes its `internalId`, which is a QUuid in KWin: an object, not a string. // Setting `minimized` or `frameGeometry` raises the signal KWin raises, and `closeWindow` closes it -// once it is in a KWin. -function window({ id, minimized = false, frameGeometry = geometry(0, 0, 100, 100), ...rest }) { +// once it is in a KWin. `place` is where KWin puts the window when it is asked for a frame: where +// it was asked, unless a test says otherwise. +function window({ + id, + minimized = false, + frameGeometry = geometry(0, 0, 100, 100), + place = (g) => g, + ...rest +}) { const w = { internalId: { toString: () => id }, pid: 0, @@ -74,6 +81,8 @@ function window({ id, minimized = false, frameGeometry = geometry(0, 0, 100, 100 fullScreen: false, maximizeMode: 0, minSize: { width: 0, height: 0 }, + move: false, + resize: false, desktops: [], frameGeometryChanged: new Signal(), minimizedChanged: new Signal(), @@ -93,7 +102,7 @@ function window({ id, minimized = false, frameGeometry = geometry(0, 0, 100, 100 get: () => state.frameGeometry, set: (g) => { const old = state.frameGeometry; - state.frameGeometry = geometry(g.x, g.y, g.width, g.height); + state.frameGeometry = place(geometry(g.x, g.y, g.width, g.height)); w.frameGeometryChanged.emit(old); }, }, @@ -458,3 +467,61 @@ test("a command KWin throws on is printed and given back as failed", () => { assert.match(k.printed[0], /^komorebi bridge: Error: the window is being destroyed in /); assert.deepStrictEqual(k.events().at(-1), { type: "failed", batch: 5, cmds: [close], seq: 2 }); }); + +// KWin keeps 100 pixels of a window that it resizes on an output +function keepOnScreen(g) { + return geometry(Math.max(g.x, 100 - g.width), g.y, g.width, g.height); +} + +test("a window KWin pulls back from where it was asked to be is asked for the position again", () => { + let pulled = false; + const w = window({ + id: "{w}", + // the first time only, as when the client commits a new size + place: (g) => (pulled ? g : ((pulled = true), keepOnScreen(g))), + }); + const k = kwin({ windows: [w] }); + + k.answer([{ batch: 1, cmds: [{ op: "geo", id: "{w}", x: -900, y: 0, w: 800, h: 600 }] }]); + + assert.deepStrictEqual(w.frameGeometry, geometry(-900, 0, 800, 600)); + assert.deepStrictEqual( + k.events().slice(1).map((e) => e.geo), + [ + { x: -700, y: 0, w: 800, h: 600 }, + { x: -900, y: 0, w: 800, h: 600 }, + ], + ); +}); + +test("a window that cannot go where it was asked is asked again three times at most", () => { + let frames = 0; + const w = window({ id: "{w}", place: (g) => (frames++, keepOnScreen(g)) }); + const k = kwin({ windows: [w] }); + + k.answer([{ batch: 1, cmds: [{ op: "geo", id: "{w}", x: -900, y: 0, w: 800, h: 600 }] }]); + + assert.equal(frames, 4, "the command and three tries"); + assert.deepStrictEqual(w.frameGeometry, geometry(-700, 0, 800, 600)); +}); + +test("a window is asked for its position again for a second after the command, and no longer", () => { + const w = window({ id: "{w}" }); + const k = kwin({ windows: [w] }); + k.answer([{ batch: 1, cmds: [{ op: "geo", id: "{w}", x: -900, y: 0, w: 800, h: 600 }] }]); + + k.clock.now += 1001; + w.frameGeometry = geometry(-700, 0, 800, 600); + + assert.deepStrictEqual(w.frameGeometry, geometry(-700, 0, 800, 600)); +}); + +test("a window the user is moving or resizing is not asked for its position again", () => { + const w = window({ id: "{w}", move: true }); + const k = kwin({ windows: [w] }); + k.answer([{ batch: 1, cmds: [{ op: "geo", id: "{w}", x: -900, y: 0, w: 800, h: 600 }] }]); + + w.frameGeometry = geometry(-700, 0, 800, 600); + + assert.deepStrictEqual(w.frameGeometry, geometry(-700, 0, 800, 600)); +}); diff --git a/komorebi/src/kwin/kwin-api.d.ts b/komorebi/src/kwin/kwin-api.d.ts index 85c01a50..4b1e077e 100644 --- a/komorebi/src/kwin/kwin-api.d.ts +++ b/komorebi/src/kwin/kwin-api.d.ts @@ -78,6 +78,10 @@ interface KWinWindow { /** Set to a plain `{x, y, width, height}`: a script has no `Qt` global to make a `QRectF`. */ frameGeometry: QRectF; readonly minSize: QSizeF; + /** True while the user moves the window with the pointer. */ + readonly move: boolean; + /** True while the user resizes the window with the pointer. */ + readonly resize: boolean; readonly desktops: VirtualDesktop[]; readonly frameGeometryChanged: Signal<[oldGeometry: QRectF]>; readonly minimizedChanged: Signal; diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index 7c21c0d3..3713f743 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -24,6 +24,9 @@ //! layout, or mirror it, and **ToggleTiling** turns its tiling off and on //! ([`WindowManager::change_workspace_layout_default`], [`WindowManager::cycle_layout`], //! [`WindowManager::flip_layout`], [`WindowManager::toggle_tiling`]). +//! - **ScrollingLayoutColumns** sets how many columns the scrolling layout shows on the focused +//! workspace, and **LayoutRatios** the share of the work area its first columns and rows take, +//! and both tile the workspace again. //! - **PreselectDirection** reserves the place on one side of the focused container for the next //! window ([`WindowManager::preselect_container_in_direction`]), unless a place is reserved //! already, and **CancelPreselect** gives the reserved place up. @@ -43,6 +46,8 @@ use crate::NotificationEvent; use crate::SUBSCRIPTION_SOCKET_OPTIONS; use crate::SUBSCRIPTION_SOCKETS; use crate::core::Layout; +use crate::core::LayoutOptions; +use crate::core::ScrollingLayoutOptions; use crate::core::SocketMessage; use crate::core::StateQuery; use crate::monitor::MonitorInformation; @@ -248,6 +253,54 @@ impl WindowManager { reply.write_all(response.as_bytes())?; } + SocketMessage::ScrollingLayoutColumns(count) => { + let focused_workspace = self.focused_workspace_mut()?; + + let options = match focused_workspace.layout_options { + Some(mut opts) => { + if let Some(scrolling) = &mut opts.scrolling { + scrolling.columns = count.into(); + } + + opts + } + None => LayoutOptions { + scrolling: Some(ScrollingLayoutOptions { + columns: count.into(), + center_focused_column: Default::default(), + }), + grid: None, + column_ratios: None, + row_ratios: None, + }, + }; + + focused_workspace.layout_options = Some(options); + self.update_focused_workspace(false, false)?; + } + SocketMessage::LayoutRatios(ref columns, ref rows) => { + use crate::core::validate_ratios; + + let focused_workspace = self.focused_workspace_mut()?; + + let mut options = focused_workspace.layout_options.unwrap_or(LayoutOptions { + scrolling: None, + grid: None, + column_ratios: None, + row_ratios: None, + }); + + if let Some(cols) = columns { + options.column_ratios = Some(validate_ratios(cols)); + } + + if let Some(rws) = rows { + options.row_ratios = Some(validate_ratios(rws)); + } + + focused_workspace.layout_options = Some(options); + self.update_focused_workspace(false, false)?; + } SocketMessage::MouseFollowsFocus(enable) => { self.mouse_follows_focus = enable; } diff --git a/komorebi/src/process_event.rs b/komorebi/src/process_event.rs index c497b131..d8719f69 100644 --- a/komorebi/src/process_event.rs +++ b/komorebi/src/process_event.rs @@ -8,7 +8,8 @@ //! - **Destroy**: the window is taken out of whichever workspace has it, and if that is the one in //! front it is tiled again. //! - **FocusChange**: the workspace is tiled again and the container of the window that has the -//! focus becomes the focused container. +//! 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. //! - **Minimize**: a window the user minimized leaves its workspace and the rest are tiled //! again; **Restore** brings it back in a container of its own. //! @@ -23,6 +24,8 @@ use crate::Notification; use crate::NotificationEvent; use crate::backend::backend; +use crate::core::DefaultLayout; +use crate::core::Layout; use crate::notify_subscribers; use crate::state::State; use crate::window_manager::WindowManager; @@ -118,7 +121,11 @@ impl WindowManager { // don't want to trigger the full workspace updates when there are no managed // containers - if !self.focused_workspace()?.containers().is_empty() { + if !matches!( + self.focused_workspace()?.layout, + Layout::Default(DefaultLayout::Scrolling) + ) && !self.focused_workspace()?.containers().is_empty() + { self.update_focused_workspace(self.mouse_follows_focus, false)?; } @@ -130,6 +137,14 @@ impl WindowManager { if is_on_current_workspace { workspace.focus_container_by_window(window_id)?; } + + if matches!( + self.focused_workspace()?.layout, + Layout::Default(DefaultLayout::Scrolling) + ) && !self.focused_workspace()?.containers().is_empty() + { + self.update_focused_workspace(self.mouse_follows_focus, false)?; + } } WindowManagerEvent::Show(_, _) => { let mut create = true; diff --git a/komorebi/src/state.rs b/komorebi/src/state.rs index 68e2d91d..65ebf6ad 100644 --- a/komorebi/src/state.rs +++ b/komorebi/src/state.rs @@ -80,9 +80,11 @@ impl From<&WindowManager> for State { .map(|workspace| Workspace { containers: workspace.containers.clone(), layout: workspace.layout.clone(), + layout_options: workspace.layout_options, layout_flip: workspace.layout_flip, workspace_padding: workspace.workspace_padding, container_padding: workspace.container_padding, + latest_layout: workspace.latest_layout.clone(), tile: workspace.tile, globals: workspace.globals, preselected_container_idx: None, diff --git a/komorebi/src/window.rs b/komorebi/src/window.rs index 838e3230..76e42f74 100644 --- a/komorebi/src/window.rs +++ b/komorebi/src/window.rs @@ -191,6 +191,28 @@ impl Window { backend().unminimize(self.id) } + /// Moves the window to the middle of `work_area`, keeping its size + /// + /// # Errors + /// + /// The backend does not know the window, or refuses to move it. + pub fn center(&mut self, work_area: &Rect) -> eyre::Result<()> { + let (target_width, target_height) = { + let current_rect = self.rect()?; + (current_rect.right, current_rect.bottom) + }; + + let x = work_area.left + ((work_area.right - target_width) / 2); + let y = work_area.top + ((work_area.bottom - target_height) / 2); + + self.set_position(&Rect { + left: x, + top: y, + right: target_width, + bottom: target_height, + }) + } + /// Whether the window is one komorebi should tile: a window that is still alive and that the /// compositor considers a normal application window, as opposed to a dialog, a splash screen, /// a utility window or a dock ([`WindowInfo::normal`](crate::backend::WindowInfo::normal)). diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index 92e403a0..689e8765 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -10,6 +10,7 @@ use crate::core::Axis; use crate::core::CycleDirection; use crate::core::DefaultLayout; use crate::core::Layout; +use crate::core::LayoutOptions; use crate::core::OperationDirection; use crate::core::Rect; use crate::lockable_sequence::LockableSequence; @@ -27,9 +28,11 @@ use std::num::NonZeroUsize; pub struct Workspace { pub containers: Ring, pub layout: Layout, + pub layout_options: Option, pub layout_flip: Option, pub workspace_padding: Option, pub container_padding: Option, + pub latest_layout: Vec, pub tile: bool, #[serde(skip)] pub globals: WorkspaceGlobals, @@ -46,7 +49,9 @@ impl Default for Workspace { workspace_padding: None, container_padding: None, layout: Layout::Default(DefaultLayout::BSP), + latest_layout: vec![], layout_flip: None, + layout_options: None, globals: Default::default(), tile: true, preselected_container_idx: None, @@ -64,6 +69,29 @@ pub struct WorkspaceGlobals { pub work_area_offset: Option, } +/// `komorebi_layouts::Rect::percentage_within_horizontal_bounds`, which that crate compiles only +/// with its `darwin` feature +trait HorizontalBounds { + /// Returns how much of `other`'s width is within this rectangle's left and right edges, in + /// percent + fn percentage_within_horizontal_bounds(&self, other: &Rect) -> f64; +} + +impl HorizontalBounds for Rect { + fn percentage_within_horizontal_bounds(&self, other: &Rect) -> f64 { + let overlap_left = self.left.max(other.left); + let overlap_right = (self.left + self.right).min(other.left + other.right); + + let overlap_width = overlap_right - overlap_left; + + if overlap_width <= 0 { + 0.0 + } else { + (overlap_width as f64) / (other.right as f64) * 100.0 + } + } +} + impl Workspace { #[tracing::instrument(skip(self))] pub fn focus_container(&mut self, idx: usize) { @@ -103,7 +131,7 @@ impl Workspace { self.layout_flip, self.focused_container_idx(), len, - None, + self.layout_options, ) } @@ -323,8 +351,13 @@ impl Workspace { /// /// Containers that have no windows left are dropped first, except the one a preselection /// reserved, and so is a window that is in more than one container. A tile is clamped to the - /// work area, so it cannot bleed onto a neighboring monitor. A workspace whose tiling is off - /// ([`Workspace::tile`] is false) moves no window. + /// work area, so it cannot bleed onto a neighboring monitor, except in the scrolling layout, + /// whose strip runs past the edges of the work area. A window whose tile is out of view while + /// 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. pub fn update(&mut self) -> eyre::Result<()> { // make sure we are never holding on to empty containers self.prune_duplicate_windows()?; @@ -376,47 +409,68 @@ impl Workspace { self.layout_flip, &[], self.focused_container_idx(), - None, - &[], + self.layout_options, + &self.latest_layout, ); + let is_scrolling = + matches!(self.layout, Layout::Default(DefaultLayout::Scrolling)); + let containers = self.containers_mut(); for (i, container) in containers.iter_mut().enumerate() { if let Some(layout) = layouts.get_mut(i) { - // Every tile is clamped to the work area so it cannot bleed onto an - // adjacent monitor. + // The scrolling layout is a strip that is meant to run past the edges of + // the work area, with the windows outside the viewport sitting off screen + // (KWin does not constrain where a window is put). Everything else is + // clamped to the work area so it cannot bleed onto an adjacent monitor. + if !is_scrolling { + // horizontal + if layout.left < adjusted_work_area.left { + layout.right -= adjusted_work_area.left - layout.left; + layout.left = adjusted_work_area.left; + } + let max_right_edge = + adjusted_work_area.left + adjusted_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; + } - // horizontal - if layout.left < adjusted_work_area.left { - layout.right -= adjusted_work_area.left - layout.left; - layout.left = adjusted_work_area.left; - } - let max_right_edge = adjusted_work_area.left + adjusted_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; - } - - // vertical - if layout.top < adjusted_work_area.top { - layout.bottom -= adjusted_work_area.top - layout.top; - layout.top = adjusted_work_area.top; - } - let max_bottom_edge = - adjusted_work_area.top + adjusted_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; + // vertical + if layout.top < adjusted_work_area.top { + layout.bottom -= adjusted_work_area.top - layout.top; + layout.top = adjusted_work_area.top; + } + let max_bottom_edge = + adjusted_work_area.top + adjusted_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; + } } for window in container.windows_mut() { - if let Err(error) = window.set_position(layout) { + let current_rect = window.rect().unwrap_or_default(); + let current_percentage = + work_area.percentage_within_horizontal_bounds(¤t_rect); + let proposed_percentage = + work_area.percentage_within_horizontal_bounds(layout); + + let percentage_override = proposed_percentage == 0.0 + && current_percentage > 0.1 + && current_percentage < 100.0; + + if percentage_override { + window.center(&work_area)?; + } else if let Err(error) = window.set_position(layout) { tracing::warn!("failed to set window position: {error}") } } } } + + self.latest_layout = layouts; } Ok(()) })(); diff --git a/komorebi/tests/layout_options.rs b/komorebi/tests/layout_options.rs new file mode 100644 index 00000000..1e5626fd --- /dev/null +++ b/komorebi/tests/layout_options.rs @@ -0,0 +1,206 @@ +//! The options of the layouts, `layout-ratios` and `scrolling-layout-columns`, and the scrolling +//! layout's strip, 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 22_000s. + +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::core::DefaultLayout; +use komorebi::core::OperationDirection; +use komorebi::core::Rect; +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::num::NonZeroUsize; +use std::sync::Arc; + +fn added(id: u32) -> WindowManagerEvent { + WindowManagerEvent::Show( + SystemNotification::KWin(KWinNotification::WindowAdded), + Window::from(id), + ) +} + +fn activated(id: u32) -> WindowManagerEvent { + WindowManagerEvent::FocusChange( + SystemNotification::KWin(KWinNotification::WindowActivated), + Window::from(id), + ) +} + +/// A window manager over a fake desktop with one 1920x1080 monitor (1920x1050 without the panel) +fn desktop() -> (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/kmo-{}-{}.sock", + std::process::id(), + NEXT.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + )); + + let wm = with_backend(fake.clone(), || { + let mut wm = WindowManager::new(receiver, Some(socket)).unwrap(); + wm.init().unwrap(); + wm + }); + + (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) { + with_backend(fake.clone(), || wm.process_command(message, Vec::new())).unwrap(); +} + +fn columns(count: usize) -> SocketMessage { + SocketMessage::ScrollingLayoutColumns(NonZeroUsize::new(count).unwrap()) +} + +fn in_view(rect: Rect) -> bool { + rect.left >= 0 && rect.left + rect.right <= 1920 +} + +fn out_of_view(rect: Rect) -> bool { + rect.left >= 1920 || rect.left + rect.right <= 0 +} + +#[test] +fn layout_ratios_give_the_first_column_its_share_of_the_work_area() { + let (fake, mut wm) = desktop(); + send( + &fake, + &mut wm, + SocketMessage::ChangeLayout(DefaultLayout::Columns), + ); + open(&fake, &mut wm, 22_001); + open(&fake, &mut wm, 22_002); + let even = fake.rect_of(22_001).unwrap(); + + send( + &fake, + &mut wm, + SocketMessage::LayoutRatios(Some(vec![0.75]), None), + ); + + let (first, second) = (fake.rect_of(22_001).unwrap(), fake.rect_of(22_002).unwrap()); + assert!(first.right > even.right, "{first:?} is wider than {even:?}"); + assert!( + first.right > 2 * second.right, + "three quarters against one: {first:?} {second:?}" + ); + assert_eq!( + wm.focused_workspace() + .unwrap() + .layout_options + .and_then(|options| options.column_ratios) + .and_then(|ratios| ratios[0]), + Some(0.75) + ); +} + +#[test] +fn the_scrolling_strip_runs_past_the_edge_of_the_work_area_with_the_focused_window_in_view() { + let (fake, mut wm) = desktop(); + send( + &fake, + &mut wm, + SocketMessage::ChangeLayout(DefaultLayout::Scrolling), + ); + send(&fake, &mut wm, columns(2)); + for id in 22_011..=22_015 { + open(&fake, &mut wm, id); + } + + let rects: Vec = (22_011..=22_015) + .map(|id| fake.rect_of(id).unwrap()) + .collect(); + assert!( + in_view(rects[4]), + "the focused window is in view: {rects:?}" + ); + assert!( + in_view(rects[3]), + "two columns: so is the one before it: {rects:?}" + ); + for rect in &rects[..3] { + assert!( + out_of_view(*rect), + "the first three are scrolled out of view: {rects:?}" + ); + } + // not clamped: every column is as wide as the others, at the same distance from the next + let pitch = rects[4].left - rects[3].left; + assert_eq!(rects[0].left, rects[3].left - 3 * pitch, "{rects:?}"); + assert!( + rects.iter().all(|rect| rect.right == rects[0].right), + "{rects:?}" + ); +} + +#[test] +fn the_scrolling_strip_scrolls_to_the_window_that_has_the_focus() { + let (fake, mut wm) = desktop(); + send( + &fake, + &mut wm, + SocketMessage::ChangeLayout(DefaultLayout::Scrolling), + ); + send(&fake, &mut wm, columns(2)); + for id in 22_021..=22_025 { + open(&fake, &mut wm, id); + } + + for id in (22_021..=22_024).rev() { + send( + &fake, + &mut wm, + SocketMessage::FocusWindow(OperationDirection::Left), + ); + // the compositor reports the focus it was asked to give, which is what scrolls the strip + with_backend(fake.clone(), || wm.process_event(activated(id))).unwrap(); + } + + assert_eq!(wm.focused_window().unwrap().id, 22_021); + assert!(in_view(fake.rect_of(22_021).unwrap())); + assert!(out_of_view(fake.rect_of(22_025).unwrap())); +} + +#[test] +fn scrolling_layout_columns_sets_how_many_columns_are_in_view() { + let (fake, mut wm) = desktop(); + send( + &fake, + &mut wm, + SocketMessage::ChangeLayout(DefaultLayout::Scrolling), + ); + for id in 22_031..=22_034 { + open(&fake, &mut wm, id); + } + + send(&fake, &mut wm, columns(4)); + let four: Vec = (22_031..=22_034) + .map(|id| fake.rect_of(id).unwrap()) + .collect(); + assert!(four.iter().all(|rect| in_view(*rect)), "{four:?}"); + + send(&fake, &mut wm, columns(1)); + let one: Vec = (22_031..=22_034) + .map(|id| fake.rect_of(id).unwrap()) + .collect(); + assert_eq!( + one.iter().filter(|rect| in_view(**rect)).count(), + 1, + "{one:?}" + ); +} diff --git a/komorebi/tests/scrolling.rs b/komorebi/tests/scrolling.rs new file mode 100644 index 00000000..685d111b --- /dev/null +++ b/komorebi/tests/scrolling.rs @@ -0,0 +1,119 @@ +//! The scrolling layout, against an in-memory desktop. +//! +//! KWin lets a window sit anywhere, so the columns of a strip that are past the edge of a monitor +//! can be on the next monitor over. Those windows still belong to the monitor whose strip they are +//! in. +//! +//! Window ids are in the 10_000s. + +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::core::DefaultLayout; +use komorebi::core::Rect; +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), + ) +} + +fn desktop_on(fake: FakeBackend) -> (Arc, WindowManager) { + let fake = Arc::new(fake); + let (_sender, receiver) = crossbeam_channel::bounded(1); + // unix socket paths are limited to ~104 bytes on macOS, which the temp dir alone can exceed + static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let socket = std::path::PathBuf::from(format!( + "/tmp/kmb-{}-{}.sock", + std::process::id(), + NEXT.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + )); + + let wm = with_backend(fake.clone(), || { + let mut wm = WindowManager::new(receiver, Some(socket)).unwrap(); + wm.init().unwrap(); + wm + }); + + (fake, wm) +} + +fn open(fake: &FakeBackend, id: u32) { + fake.open_window(id, "foot", "foot", &format!("terminal {id}")); +} + +#[test] +fn a_scrolling_strip_on_the_next_monitor_over_does_not_take_focus_with_it() { + // KWin lets a window sit anywhere, so the part of the strip past the right edge of the first + // monitor is on the second one. Those windows still belong to the first. + let fake = FakeBackend::with_one_monitor(); + fake.add_monitor( + 2, + "Virtual-1", + Rect { + left: 1920, + top: 0, + right: 1920, + bottom: 1080, + }, + Rect { + left: 1920, + top: 0, + right: 1920, + bottom: 1050, + }, + ); + let (fake, mut wm) = desktop_on(fake); + for id in 10_201..=10_205 { + open(&fake, id); + } + + with_backend(fake.clone(), || { + wm.process_command( + SocketMessage::ChangeLayout(DefaultLayout::Scrolling), + Vec::new(), + )?; + wm.process_command( + SocketMessage::ScrollingLayoutColumns(std::num::NonZeroUsize::new(2).unwrap()), + Vec::new(), + )?; + for id in 10_201..=10_205 { + wm.process_event(added(id))?; + } + // back to the start of the strip, which leaves the later columns past the monitor's edge + for _ in 0..4 { + wm.process_command( + SocketMessage::FocusWindow(komorebi::core::OperationDirection::Left), + Vec::new(), + )?; + } + + // (the compositor's focus event is what scrolls the strip, and the fake sends none) + wm.update_focused_workspace(false, false)?; + + let past_the_edge = fake.rect_of(10_204).unwrap(); + assert!( + past_the_edge.left >= 1920, + "the test needs a window on the second monitor, got {past_the_edge:?}" + ); + + wm.process_event(WindowManagerEvent::FocusChange( + SystemNotification::KWin(KWinNotification::WindowActivated), + Window::from(10_204), + )) + }) + .unwrap(); + + assert_eq!( + wm.focused_monitor_idx(), + 0, + "focus moved to the monitor the strip spills onto" + ); +} diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs index c1c970b9..5f6eb776 100644 --- a/komorebic/src/main.rs +++ b/komorebic/src/main.rs @@ -9,8 +9,9 @@ //! `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, and `preselect-direction` and `cancel-preselect` reserve the -//! place of the next window and give it up. +//! 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. //! //! `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 @@ -38,6 +39,7 @@ use komorebi_client::send_query; use std::fs::File; use std::io::BufRead; use std::io::Write; +use std::num::NonZeroUsize; use std::path::PathBuf; use std::process::Command; use std::process::Stdio; @@ -111,6 +113,22 @@ struct Start { #[derive(Parser)] struct Stop {} +#[derive(Parser)] +struct ScrollingLayoutColumns { + /// Desired number of visible columns + count: NonZeroUsize, +} + +#[derive(Parser)] +struct LayoutRatios { + /// Column width ratios (space-separated values between 0.1 and 0.9) + #[clap(short, long, num_args = 1..)] + columns: Option>, + /// Row height ratios (space-separated values between 0.1 and 0.9) + #[clap(short, long, num_args = 1..)] + rows: Option>, +} + #[derive(Parser)] struct Docgen { /// Output directory for generated documentation files @@ -192,6 +210,11 @@ enum SubCommand { /// Cycle between available layouts #[clap(arg_required_else_help = true)] CycleLayout(CycleLayout), + /// Set the number of visible columns for the Scrolling layout on the focused workspace + #[clap(arg_required_else_help = true)] + ScrollingLayoutColumns(ScrollingLayoutColumns), + /// Set the layout column and row ratios for the focused workspace + LayoutRatios(LayoutRatios), // /// Load a custom layout from file for the focused workspace // #[clap(hide = true)] // #[clap(arg_required_else_help = true)] @@ -367,6 +390,18 @@ fn main() -> eyre::Result<()> { SubCommand::MonitorInformation => { print_query(&SocketMessage::MonitorInformation); } + SubCommand::ScrollingLayoutColumns(args) => { + send_message(&SocketMessage::ScrollingLayoutColumns(args.count))?; + } + SubCommand::LayoutRatios(args) => { + if args.columns.is_none() && args.rows.is_none() { + println!( + "No ratios provided, nothing to change. Use --columns or --rows to specify ratios." + ); + } else { + send_message(&SocketMessage::LayoutRatios(args.columns, args.rows))?; + } + } SubCommand::ToggleMouseFollowsFocus => { send_message(&SocketMessage::ToggleMouseFollowsFocus)?; } diff --git a/komorebic/tests/cli.rs b/komorebic/tests/cli.rs index b052d92a..63882b84 100644 --- a/komorebic/tests/cli.rs +++ b/komorebic/tests/cli.rs @@ -216,6 +216,44 @@ fn the_layout_subcommands_send_the_layout_axis_or_direction_they_are_given() { sends(&["cancel-preselect"], r#"{"type":"CancelPreselect"}"#); } +#[test] +fn scrolling_layout_columns_and_layout_ratios_send_what_they_are_given() { + sends( + &["scrolling-layout-columns", "3"], + r#"{"type":"ScrollingLayoutColumns","content":3}"#, + ); + sends( + &["layout-ratios", "--columns", "0.6", "0.25", "--rows", "0.5"], + r#"{"type":"LayoutRatios","content":[[0.6,0.25],[0.5]]}"#, + ); + sends( + &["layout-ratios", "--rows", "0.3"], + r#"{"type":"LayoutRatios","content":[null,[0.3]]}"#, + ); +} + +#[test] +fn layout_ratios_without_ratios_sends_nothing_and_says_so() { + let runtime = Runtime::new(); + + let output = runtime.komorebic(&["layout-ratios"]); + + assert!(output.status.success(), "{output:?}"); + assert!( + stdout(&output).starts_with("No ratios provided"), + "{output:?}" + ); +} + +#[test] +fn scrolling_layout_columns_refuses_zero() { + let runtime = Runtime::new(); + + let output = runtime.komorebic(&["scrolling-layout-columns", "0"]); + + assert!(!output.status.success(), "{output:?}"); +} + #[test] fn mouse_follows_focus_is_set_with_enable_and_disable_or_toggled() { sends( @@ -280,6 +318,7 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "data-directory.md", "flip-layout.md", "focus.md", + "layout-ratios.md", "log.md", "monitor-information.md", "mouse-follows-focus.md", @@ -287,6 +326,7 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "preselect-direction.md", "query.md", "retile.md", + "scrolling-layout-columns.md", "start.md", "state.md", "stop.md", diff --git a/nix/tests/vm/suites/commands/test.py b/nix/tests/vm/suites/commands/test.py index 2f6eac41..3e33bc8a 100644 --- a/nix/tests/vm/suites/commands/test.py +++ b/nix/tests/vm/suites/commands/test.py @@ -164,7 +164,9 @@ flip-layout horizontal-and-vertical flip-layout horizontal-and-vertical cycle-layout next cycle-layout previous +layout-ratios --columns 0.6 0.4 change-layout columns +scrolling-layout-columns 2 change-layout bsp preselect-direction left cancel-preselect diff --git a/nix/tests/vm/suites/scrolling/default.nix b/nix/tests/vm/suites/scrolling/default.nix new file mode 100644 index 00000000..bb57ac90 --- /dev/null +++ b/nix/tests/vm/suites/scrolling/default.nix @@ -0,0 +1,5 @@ +{ + tier = "fast"; + kind = "headless"; + timeoutMinutes = 10; +} diff --git a/nix/tests/vm/suites/scrolling/test.py b/nix/tests/vm/suites/scrolling/test.py new file mode 100644 index 00000000..420463b3 --- /dev/null +++ b/nix/tests/vm/suites/scrolling/test.py @@ -0,0 +1,89 @@ +# The scrolling layout in a real KWin. The strip runs past the edge of the work area, and KWin is +# expected to leave the windows exactly where komorebi puts them, off the screen too: KWin keeps +# part of a window it resizes on an output, and the bridge asks again for the position of a window +# that was pulled back (`settle` in `bridge.js`). `komorebi/tests/layout_options.rs` checks where +# komorebi puts the columns against the fake; this checks that KWin keeps them there, and that the +# strip scrolls with the focus that `komorebic focus` moves. +from komorebi_vm import Checks, Kde, Rect + +W, H = 1920, 1080 + +start_all() +machine.wait_for_unit("multi-user.target") +machine.wait_for_unit("user@1000.service") + +checks = Checks() +kde = Kde.headless(machine, "main", size=(W, H), scale=SCALE) + + +def n(i: int) -> Rect: + return kde.rect(kde.wid(f"win{i}")) + + +def in_view(r: Rect) -> bool: + return r.x >= 0 and r.x + r.w <= W + + +def out_of_view(r: Rect) -> bool: + return r.x >= W or r.x + r.w <= 0 + + +def focused_monitor() -> int: + return kde.state()["monitors"]["focused"] + + +def agree(title: str) -> bool: + return kde.title(kde.active()) == title and kde.focused_title() == title + + +print("== five windows in two columns") +kde.start_komorebi() +kde.wait_for(lambda: kde.run("komorebic monitor-information")[0] == 0, timeout=30) +kde.komorebic("change-layout", "scrolling") +kde.komorebic("scrolling-layout-columns", "2") +for i in range(1, 6): + kde.spawn(f"foot -T win{i} sleep 3000") + kde.wait_for(lambda i=i: kde.wid(f"win{i}") != "", timeout=30) +checks.check("komorebi manages all five", kde.wait_for(lambda: kde.managed() == 5, timeout=20)) +checks.check( + "the focused (last) window is in view, and so is the one before it", + kde.wait_for(lambda: in_view(n(5)) and in_view(n(4)), timeout=20), +) +checks.check( + "the first three are scrolled out of view", + kde.wait_for(lambda: all(out_of_view(n(i)) for i in (1, 2, 3)), timeout=20), +) +for i in range(1, 6): + print(f" win{i}: {n(i)}") +# not an absolute x: the paddings move every column +pitch = n(5).x - n(4).x +checks.check( + f"KWin left them where komorebi put them: win1 is three columns left of win4" + f" ({n(1).x} = {n(4).x} - 3 x {pitch}), not pulled back", + kde.wait_for(lambda: n(1).x == n(4).x - 3 * pitch, timeout=10), +) +checks.check("KWin and komorebi agree on the focus", kde.wait_for(lambda: agree("win5"))) + +print("== focus to the far left and back") +for _ in range(4): + kde.komorebic("focus", "left") + kde.wait_for(lambda: kde.title(kde.active()) == kde.focused_title()) +checks.check( + "focusing to the far left scrolls the strip back: win1 in view", + kde.wait_for(lambda: in_view(n(1)), timeout=10), +) +checks.check("... and win5 is past the right edge", kde.wait_for(lambda: out_of_view(n(5)))) +checks.check("... and the focus is win1 on both sides", kde.wait_for(lambda: agree("win1"))) +checks.check("... on the first monitor", focused_monitor() == 0) + +for _ in range(4): + kde.komorebic("focus", "right") + kde.wait_for(lambda: kde.title(kde.active()) == kde.focused_title()) +checks.check("walking right again reaches win5", kde.wait_for(lambda: agree("win5"))) +checks.check("... without the focus having left the first monitor", focused_monitor() == 0) +checks.check("... and win5 is in view", kde.wait_for(lambda: in_view(n(5)), timeout=10)) + +kde.komorebic("stop") +kde.wait_for(lambda: not kde.komorebi_running()) +kde.stop() +checks.finish()