From af560f47d72b5f567c4213426352fe6f0eef1af5 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 17:36:26 -0700 Subject: [PATCH] feat(wm): resize by dragging an edge Dragging an edge or a corner of a tiled window resizes its tile when the user lets go: each edge of the tile moves by what the pointer moved it, the neighbors give up or take the room, and the window is put on its tile. A drag is measured from the frame the window had when the user took hold of it, edge by edge, and resizes the container of the window that was dragged, through resize_window and so within its bound (no tile below a tenth of the work area). KWin reports the window's frame all through a drag, so the table keeps the frame of the start for the window manager (Backend::drag_origin). At the end the frame can still be short of the pointer, because KWin changes it once the client has drawn at the new size; the bridge keeps the frame the last step of the drag asked for and sends it as `requested`, and the end of a resize is that frame. The window of a stack has the tile of the stack; a floating window and the window of a monocle have none, and are left as the user made them. The end of a resize is read apart from the window's frame, and that deviates from the spike. The spike stores the frame the last step asked for as the window's own frame, where the next frame event replaces it. KWin sends one a millisecond after the end, with what the client has drawn so far (660 pixels of the 672 asked for), and a window manager that is busy with an earlier event reads that frame when it handles the end: a tile moved by 60 pixels for a drag of 72. Here the table keeps the end apart (Table::drag_end, and Backend::drag_end for the window manager, None by default), ResizeEnd reads it as ResizeStart reads drag_origin, and the window's frame stays the one KWin reports. A resize that sent no step ends at the frame. The order that failed is a test of the KWin backend with the real table and window manager, in which the tile took 140 of the 200 pixels without this. komorebi-layouts at the pinned revision has the fix of LGUG2Z/komorebi#1765, so nothing is vendored, and docs/drag-resize.md says what a drag does and why each rule is there. vm-drag-resize drags edges and corners of three tiles with the pointer that the session node has (komorebi_vm.Pointer), whose moves are batched in the guest. The suite drags against the daemon the module starts with the session, and reads the drags that daemon has handled from the unit's journal. vm-drag-resize waits, for 30 seconds at most, for the daemon to have the room KWin takes for the panel before it opens the windows (Kde.wait_for_panel_room). The panel moved every tile in the middle of a case that began before the daemon learned of it, which showed as an edge that was not dragged. It is a wait and not a check, since a session that is too slow may never take the room. --- README.md | 5 +- docs/dev/ARCHITECTURE.md | 51 ++- docs/dev/DESIGN.md | 22 + docs/dev/PLATFORM.md | 12 + docs/drag-resize.md | 83 ++++ docs/index.md | 3 +- docs/usage/resizing-windows.md | 16 +- komorebi/src/backend/fake.rs | 13 + komorebi/src/backend/mod.rs | 55 +++ komorebi/src/kwin/bridge.js | 22 +- komorebi/src/kwin/bridge.test.js | 17 +- komorebi/src/kwin/fixtures/events.json | 16 +- komorebi/src/kwin/kwin-api.d.ts | 3 + komorebi/src/kwin/mod.rs | 110 ++++- komorebi/src/kwin/state.rs | 203 ++++++++- komorebi/src/process_event.rs | 145 ++++++- komorebi/src/static_config.rs | 1 + komorebi/src/window_manager.rs | 4 + komorebi/src/window_manager_event.rs | 13 + komorebi/tests/drag_resize.rs | 440 ++++++++++++++++++++ komorebi/tests/drag_swap.rs | 3 +- nix/tests/vm/suites/drag-resize/default.nix | 8 + nix/tests/vm/suites/drag-resize/test.py | 244 +++++++++++ 23 files changed, 1442 insertions(+), 47 deletions(-) create mode 100644 docs/drag-resize.md create mode 100644 komorebi/tests/drag_resize.rs create mode 100644 nix/tests/vm/suites/drag-resize/default.nix create mode 100644 nix/tests/vm/suites/drag-resize/test.py diff --git a/README.md b/README.md index bfd4c761..2bad97b2 100644 --- a/README.md +++ b/README.md @@ -171,8 +171,9 @@ window manager loads the monitors and the windows that are open from the backend and tiles them; after that it changes the model when the compositor reports that a window was shown, closed, focused, minimized or restored, and tiles the workspace in front again. A window the user drags with the pointer -onto the tile of another swaps places with it. A window open at startup goes to -the workspace whose desktop it is on. +onto the tile of another swaps places with it, and dragging the edge of a tile +resizes it, as `resize-edge` does. A window open at startup goes to the +workspace whose desktop it is on. A container with more than one window is a stack: the layout gives it one tile, and the window in front is in sight. The others are hidden, which on KWin means diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index a607c54b..756da10c 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -655,12 +655,12 @@ none. ## Dragging -The user can move a window with the pointer. KWin reports the start and the end of a drag -(`interactiveMoveResizeStarted` and `interactiveMoveResizeFinished`), the bridge sends both with -the window's frame, and the end with where the pointer is, and the table turns a move into a -`MoveStart` and a `MoveEnd` ([`Table::handle`]). A drag that resizes the window raises no event. -The bridge also stops asking KWin again for the position komorebi gave the window (`settle`): -the window is the user's now. +The user can move a window with the pointer, and resize it by dragging an edge. KWin reports the +start and the end of a drag (`interactiveMoveResizeStarted` and `interactiveMoveResizeFinished`), +the bridge sends both with the window's frame, and the end with where the pointer is, and the +table turns a move into a `MoveStart` and a `MoveEnd`, and a resize into a `ResizeStart` and a +`ResizeEnd` ([`Table::handle`]). The bridge also stops asking KWin again for the position komorebi +gave the window (`settle`): the window is the user's now. `MoveStart` records the monitor, the workspace and the window ([`WindowManager::pending_move_op`]). `MoveEnd` takes the record, and when it names the same @@ -682,6 +682,25 @@ changes nothing, and neither does a floating window, which is in no container ([`Workspace::contains_managed_window`]). The swap goes through `LockableSequence`, as `MoveWindow`'s does. +A resize is measured from the frame the window had when the user took hold of it. The table keeps +that frame at the start ([`Table::drag_origin`], the backend's `drag_origin`), because the +`geometry` events of the drag change the window's frame before the window manager gets to the start; +a backend that keeps none, as the fake, gives the frame the window has when `ResizeStart` is +handled. `ResizeStart` records the window and that frame ([`WindowManager::pending_resize_op`]). At +the end the edges are where the user took them, which is not where the window's frame is: KWin +changes the frame once the client has drawn at the new size, and goes on reporting the client's +frames after the end of the drag, which can be before the window manager, busy with an earlier +event, gets to the end. The bridge therefore keeps the frame the last step of the drag asked for +(`interactiveMoveResizeStepped`) and sends it with the end as `requested`, and the table keeps it +apart from the window's frame ([`Table::drag_end`], the backend's `drag_end`), where a frame event +cannot reach it. `ResizeEnd` compares each edge of that frame, or of the window's frame when there +is none (a drag with no step), with the same edge of the frame the drag began with, focuses the +container of the dragged window, and calls [`WindowManager::resize_window`] for each edge that +moved, with twice the distance, since the layout moves a shared edge by half of what it is given. If +the window is in a container of a workspace that tiles, and the frame changed, the workspace is +tiled again, which also puts back a window whose edge had no neighbor to take room from. +[drag-resize.md](../drag-resize.md) has the rules and the reasons for each. + ## Configuration The daemon is configured by `komorebi.json`, which [`StaticConfig`] reads. `main.rs` takes the @@ -1091,7 +1110,9 @@ the fake. The window manager is its only caller, through [`backend`]. The contra It does nothing when it is asked for the look it applied last. - `shutdown`, `is_window`, `window_rect` and `monitor_from_point` have defaults, written in terms of the queries. An implementor should not need to override them, except `shutdown` - when it created something in the compositor that has to be given up. + when it created something in the compositor that has to be given up. `drag_origin` and + `drag_end` have defaults that keep nothing; a backend whose frames change during a drag and + after it, as KWin's do, overrides them. ## What is guaranteed, and by what @@ -1147,7 +1168,11 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | A window let go of on another monitor goes there, in the place of the container under the pointer | framework path: `MoveEnd` sees that the monitor under the pointer is not the one the drag began on, and hands the window to [`WindowManager::transfer_window`] without comparing its frame with its tile | `a_window_let_go_of_on_another_monitor_goes_to_that_monitor`, `a_window_let_go_of_on_a_monitor_with_nothing_on_it_goes_there`, `a_floating_window_let_go_of_on_another_monitor_is_one_of_the_floating_windows_there` | a floating window that is the only window of its workspace is not noticed to have moved | | With the window container behavior `Append` a window let go of on a tile joins its container, and with the float override on it floats where it was let go of | framework path: `MoveEnd` reads [`WindowManager::window_management_behaviour`] for the focused workspace | `with_append_a_window_let_go_of_on_a_tile_joins_the_container_of_that_tile`, `with_the_float_override_a_window_let_go_of_on_a_tile_floats_where_it_was_let_go_of` | none | | The bridge leaves a window the user has taken hold of where the user puts it | framework path: the bridge forgets the position it was asking again for when a drag of the window starts | `a window the user has taken hold of is not asked again for the position komorebi gave it` | none | -| 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 drag of an edge resizes the tile of the window that was dragged, by what the pointer moved the edge, and moves no other edge | framework path: `ResizeEnd` compares each edge with the frame the drag began with ([`Table::drag_origin`]) and resizes the dragged window's container | `resizing_a_tile_by_hand_moves_the_split`, `a_drag_is_measured_from_where_the_window_was_not_from_its_tile`, `the_window_that_was_dragged_is_the_one_resized_not_the_focused_one`, `a_corner_resizes_both_of_its_edges`, `vm-drag-resize` | none | +| The end of a resize is where the user took the edge, not the frame KWin has then, or reports a moment later | framework path: the bridge sends the frame of the last step as `requested`, the table keeps it for a resize apart from the window's frame ([`Table::drag_end`]), which the frame events that follow the end do not reach, and `ResizeEnd` reads it ([`Backend::drag_end`]) | `the_end_of_a_resize_is_where_the_user_took_it_not_where_the_frame_had_got_to`, `a_frame_that_follows_the_end_of_a_resize_does_not_change_where_the_user_took_it`, `the_end_of_a_resize_is_where_the_user_took_the_edge_when_the_frame_has_not_got_there`, `a drag is reported when the user takes hold of a window and when they let go`, `vm-drag-resize` | a drag with no step ends at the frame | +| A dragged edge with no neighbor puts the window back on its tile | framework path: `ResizeEnd` tiles the workspace again when the frame changed | `dragging_an_edge_that_has_no_neighbour_puts_the_window_back`, `vm-drag-resize` | none | +| Only a tile is resized by dragging: the window of a stack resizes the tile of the stack, and a floating window or the window of a monocle is left as the user made it | framework path: `ResizeEnd` looks for the container of the dragged window among the workspace's containers ([`Workspace::container_idx_for_window`]), which leaves out the floating windows and the monocle container, and does nothing when there is none | `the_edge_of_a_stack_is_the_edge_of_its_tile`, `a_floating_window_dragged_by_its_edge_is_left_as_the_user_made_it`, `the_window_of_a_monocle_dragged_by_its_edge_is_left_as_the_user_made_it` | none | +| 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`, `a_drag_further_than_the_neighbour_can_give_goes_as_far_as_it_can`, `shrinking_a_tile_by_more_than_it_can_is_granted_as_far_as_it_goes` | the paddings are taken off afterwards, so a tile can end up a little smaller | | The offset of a workspace wins over its monitor's, which wins over the window manager's | framework path: [`Monitor::update_workspace_globals`] gives the workspace the monitor's offset or else the window manager's, and [`Workspace::update`] takes its own before that | `the_workspaces_offset_wins_over_the_monitors_which_wins_over_the_global_one` | none | | 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 | | komorebi hides no window to leave a workspace | framework path: showing a workspace is one request to the compositor ([`Backend::switch_workspace`]), which shows and hides the windows of its desktops | `switching_workspace_asks_the_compositor_to_show_the_other_desktop`, `vm-workspace-switch` ("KWin shows the desktop, komorebi hides nothing") | none | @@ -1382,13 +1407,16 @@ A window is shown, and ends up on a tile: [`komorebi/tests/rule_commands.rs`](../../komorebi/tests/rule_commands.rs), the rules and the messages that add and show them; [`komorebi/tests/drag_swap.rs`](../../komorebi/tests/drag_swap.rs), dragging a window onto - another tile and onto another monitor. + another tile and onto another monitor; + [`komorebi/tests/drag_resize.rs`](../../komorebi/tests/drag_resize.rs), dragging an edge. - [`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/features`](../../nix/tests/vm/suites/features/test.py): what is on the screen of a real compositing session, read from screenshots. - [`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/tests/vm/suites/drag-resize`](../../nix/tests/vm/suites/drag-resize/test.py): edges and + corners dragged with a pointer in a Plasma session. - [`komorebi/tests/workspaces.rs`](../../komorebi/tests/workspaces.rs): workspaces as the fake's desktops; [`komorebi/tests/workspace_commands.rs`](../../komorebi/tests/workspace_commands.rs), naming, @@ -1568,6 +1596,11 @@ A window is shown, and ends up on a tile: [`Workspace::contains_managed_window`]: ../../komorebi/src/workspace.rs [`WindowManager::pending_move_op`]: ../../komorebi/src/window_manager.rs [`WindowManager::transfer_window`]: ../../komorebi/src/window_manager.rs +[`WindowManager::pending_resize_op`]: ../../komorebi/src/window_manager.rs +[`Workspace::container_idx_for_window`]: ../../komorebi/src/workspace.rs +[`Table::drag_origin`]: ../../komorebi/src/kwin/state.rs +[`Table::drag_end`]: ../../komorebi/src/kwin/state.rs +[`Backend::drag_end`]: ../../komorebi/src/backend/mod.rs [`LayoutOptions`]: ../../komorebi/src/core/mod.rs [`Workspace::tile`]: ../../komorebi/src/workspace.rs [`Layout`]: ../../komorebi/src/core/mod.rs diff --git a/docs/dev/DESIGN.md b/docs/dev/DESIGN.md index 1a1f4589..c65bcb5c 100644 --- a/docs/dev/DESIGN.md +++ b/docs/dev/DESIGN.md @@ -542,3 +542,25 @@ backend asks it through the held call, and returns the last position the table h answer comes within 250 ms. The end of a drag is the moment the window manager asks, and the event that reports it brings the position of the pointer with it, so the last position the table has is the one that counts. + +## Why is a drag of an edge measured from where the window was when it began? + +A window is not always on its tile. A client that sizes itself to a grid, such as a terminal that +keeps to whole cells of its font, is a few pixels short of it, and a window with a minimum size +can be larger. Measured against the tile, every drag of such a window would look as if it had +moved the other edges too, and they would be resized as well. The frame the window had when the +drag began is what the user had under the pointer, so the drag is measured from it. KWin reports +the window's frame all through a drag, so the table keeps the frame of the start apart from it, +and the window manager reads that one when it handles the start. + +## Why is the end of a resize the frame the user asked for and not the window's frame? + +KWin changes the window's frame only once the client has drawn at the new size, so when the user +lets go the frame can be short of where they took the edge +([PLATFORM.md](PLATFORM.md#how-clients-answer-a-frame)). The frame the last step of the drag asked +for is where the user took it. The table keeps it apart from the window's frame, because the window +manager does not handle the end of the drag at once: it may be busy with an earlier event, and the +frame event KWin sends a millisecond after the end changes the frame in the table before the window +manager reads it. The end of the drag has to survive that, so it is not the window's frame. The +frame events go on updating the window's frame, and the retile that ends the drag puts the window on +its tile. A move changes no size, so the end of a move is the frame. diff --git a/docs/dev/PLATFORM.md b/docs/dev/PLATFORM.md index cc227fd1..3738d76f 100644 --- a/docs/dev/PLATFORM.md +++ b/docs/dev/PLATFORM.md @@ -409,6 +409,18 @@ cannot go where it was asked is left alone. A maximize makes the bridge forget t window's frame then changes to the work area, which is not where it was last asked to be. The VM test `vm-scrolling` checks that the columns out of view stay where komorebi put them. +The same holds for a frame the user asks for. While the user drags an edge of a window, KWin reports +at every step of the drag the frame the pointer asks for (`interactiveMoveResizeStepped`), and the +window's frame follows once the client has drawn at that size. When the user lets go, the frame can +be well short of where they took the edge: at time of writing (2026-10-27), in the spike, the frame +at the end of a 72-pixel drag of a terminal's edge had moved 12 or 48 pixels. KWin goes on reporting +the client's frames after the end of the drag: in a run of `vm-drag-resize` at time of writing +(2026-10-28), a frame of 660 pixels, which is what `foot` had drawn of the 672 asked for, came 1 ms +after the end, and the window manager, busy with an earlier event, handled the end 17 ms after that. +The bridge sends the frame of the last step with the end of the drag, and the end of a resize is +that frame, which the daemon keeps apart from the frames that follow. The VM test `vm-drag-resize` +drags edges in a Plasma session with a pointer device that the session node makes with uinput. + ## 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/drag-resize.md b/docs/drag-resize.md new file mode 100644 index 00000000..7e0e2e4b --- /dev/null +++ b/docs/drag-resize.md @@ -0,0 +1,83 @@ +# Resizing a tile by dragging its edge + +A tiled window can be resized with the pointer: take hold of one of its edges or corners, drag +it, and let go. komorebi then moves the edges of the window's tile by as much as the pointer +moved them, as [`komorebic resize-edge`](cli/resize-edge.md) would, the tiles next to it give up +or take the room, and the window is put on its tile. This page says what komorebi does with a +drag, the rules it keeps to, and why each of them is there. + +## What a drag does + +1. KWin reports that the user took hold of a window to resize it, and the window manager records + the frame the window had at that moment. +2. When the user lets go, KWin reports the end of the drag, and the window manager compares the + frame the user left the window with to the frame it recorded, edge by edge: the left, the top, + the right and the bottom. +3. For each edge that moved, it asks the layout to move that edge of the tile by the same number + of pixels, outward or inward. A corner is two edges. +4. The workspace is tiled again: the dragged window goes onto its tile, wherever the user left it, + and so do its neighbors. + +## The rules + +- **A drag is measured from where the window was when it began, not from its tile.** A window is + not always exactly on its tile: a terminal sizes itself to whole cells of its font and is a few + pixels short, and a window with a minimum size can be larger. Measured against the tile, a drag + of one edge of such a window would look as if the other edges had moved too, and those would be + resized as well. +- **Each edge is compared with its own start.** A rectangle in komorebi is a position and a size, + so the right and the bottom edges are worked out from them. Comparing the sizes instead would + make a drag of the left edge look like a drag of the right one. +- **The tile of the window that was dragged is resized**, which is not always the focused one: the + press that began the drag may not have given it the focus yet. +- **Only a tile is resized.** The window of a stack has the tile of the stack, so the drag + resizes that. A floating window and the window of a monocle are in no tile of the layout, and + are left as the user made them. +- **An edge with no neighbor does not move.** The left edge of the leftmost tile has nothing to + take room from: dragging it changes no tile, and the window is put back on its tile. +- **A drag that ends where it began changes nothing**, not even a tile next to it. +- **A drag is granted as far as it can go.** No tile is made narrower or shorter than a tenth of + the monitor's work area, or than it is already, so a drag further than a neighbor can give + moves the edge as far as the neighbor allows, and a drag that would shrink the window past that + shrinks it that far. The same bound applies to `komorebic resize-edge`, and a drag of any + length is granted, however narrow the dragged tile is. +- **The end of a resize is where the user took the edge.** KWin changes a window's frame once its + client has drawn at the new size, so when the user lets go the frame can still be short of the + pointer, and the frames KWin reports after that change it again before the window manager gets to + the end of the drag, which it may do while it is busy with an earlier event. The bridge keeps the + frame the user last asked for during the drag, the daemon keeps it apart from the window's frame, + and the window manager reads that one at the end, whenever it gets there; the window's frame + follows a moment later. The end of a move is the frame, and so is the end of a resize that had no + step. + +## The layouts + +The layouts that move the edges are `komorebi-layouts` from +[komorebi](https://github.com/LGUG2Z/komorebi), at the revision `Cargo.toml` pins. That revision +has the fix of [LGUG2Z/komorebi#1765]: `DefaultLayout::resize` adds the whole adjustment to the +tile and leaves the bound to the window manager, which knows the other tiles. The window manager +grants the largest part of the adjustment that leaves every tile at least as large as the rule +above says (`WindowManager::resize_window`), looking for it by bisection, since the tiles only get +smaller as the adjustment grows. The BSP, columns, rows, vertical stack, right main vertical +stack, horizontal stack, ultrawide vertical stack and scrolling layouts can be resized this way; +the grid layout cannot, and in a layout some edges cannot move, such as the top and the bottom +of a column. + +[LGUG2Z/komorebi#1765]: https://github.com/LGUG2Z/komorebi/issues/1765 + +## How it is tested + +- `komorebi/tests/drag_resize.rs`, against the fake desktop: a drag of the split between two + tiles; a long drag of the narrow right-hand stack of the ultrawide vertical stack; a drag past + what the neighbor can give; a shrink past what the tile can lose; a drag of a window that is + short of its tile, which must not move the divider on its other side; a drag of a window that is + not the focused one; an edge with no neighbor; a drag that changed nothing; a corner; the edge + of a stack; a floating window and the window of a monocle; a drag whose frame had not got to + where the user took the edge when the window manager read the end. +- `komorebi/src/kwin/state.rs`: the end of a resize is the frame the user asked for and a frame + event after it does not change that, the end of a move is the frame, and the frame a drag began + with is kept while the frame changes. +- `vm-drag-resize`, in a Plasma session with a pointer device: edges and corners of three tiles + are dragged with the pointer, and the tiles are checked exactly (the dragged edge moved by what + the pointer moved, the neighbor's with it, nothing else), the frames within a cell of the + terminal's font. diff --git a/docs/index.md b/docs/index.md index 2a951293..4186e420 100644 --- a/docs/index.md +++ b/docs/index.md @@ -37,7 +37,8 @@ daemon, ask it what it is doing and read its log. [Stacking windows](usage/stacking-windows.md) how to put windows on one tile, have the others wait out of sight and bring one of them to the front, [Layouts](usage/layouts.md) how to change the arrangement of the tiles, -[Resizing windows](usage/resizing-windows.md) how to change the size of one, +[Resizing windows](usage/resizing-windows.md) how to change the size of one (and +[Resizing a tile by dragging its edge](drag-resize.md) what a drag with the pointer does), [Floating windows](usage/floating-windows.md) how to take a window out of the layout and work with the floating ones, [Monocle](usage/monocle.md) how to give one window the whole work area, diff --git a/docs/usage/resizing-windows.md b/docs/usage/resizing-windows.md index 4425d7f3..5d6391d4 100644 --- a/docs/usage/resizing-windows.md +++ b/docs/usage/resizing-windows.md @@ -1,8 +1,9 @@ # 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. +the room. A window can also be resized by dragging one of its edges. 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 @@ -40,6 +41,17 @@ 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. +## By dragging an edge + +Take hold of an edge or a corner of a tiled window with the pointer, drag it, and let go: the +edges of the window's tile move by as much as the pointer moved them, the neighbors give up or +take the room, and the window is put on its tile. A corner moves two edges. The rules are those +of `resize-edge`: an edge with no tile on the other side of it does not move, and the window goes +back to its tile; no tile is made smaller than a tenth of the work area, so a long drag goes as +far as it can. The window of a stack has the tile of the stack. A floating window and the window +of a monocle have no tile: they are left as the user made them. [Resizing a tile by dragging its +edge](../drag-resize.md) says how a drag is measured. + ## Back to the layout [`komorebic retile`](../cli/retile.md) tiles every monitor again in its layout, without the diff --git a/komorebi/src/backend/fake.rs b/komorebi/src/backend/fake.rs index a0edd408..7a7d30e5 100644 --- a/komorebi/src/backend/fake.rs +++ b/komorebi/src/backend/fake.rs @@ -89,6 +89,8 @@ struct State { /// the windows that are hidden, in the order they were hidden: Vec, min_sizes: HashMap, + /// the frame the user asked for when they last let go of an edge of each window + drag_ends: HashMap, monitors: Vec, foreground: Option, cursor: Option<(i32, i32)>, @@ -298,6 +300,13 @@ impl FakeBackend { } } + /// Sets what [`Backend::drag_end`] answers for a window: the frame the user asked for when + /// they let go of one of its edges, as a client that has not finished drawing is short of it. + /// [`FakeBackend::move_window_by_user`] puts the frame the window has. + pub fn set_drag_end(&self, id: u32, rect: Rect) { + self.state.lock().drag_ends.insert(id, rect); + } + /// Gives a window a minimum size. A [`Backend::set_rect`] for something smaller leaves it at /// the minimum, which is how a GTK4 client answers. pub fn set_min_size(&self, id: u32, width: i32, height: i32) { @@ -494,6 +503,10 @@ impl Backend for FakeBackend { self.state.lock().cursor } + fn drag_end(&self, id: u32) -> Option { + self.state.lock().drag_ends.get(&id).copied() + } + fn set_rect(&self, id: u32, rect: &Rect) -> eyre::Result<()> { let rect = *rect; self.record(id, Command::SetRect(id, rect), |state| { diff --git a/komorebi/src/backend/mod.rs b/komorebi/src/backend/mod.rs index 4a50d29e..5ba87df8 100644 --- a/komorebi/src/backend/mod.rs +++ b/komorebi/src/backend/mod.rs @@ -251,6 +251,61 @@ pub trait Backend: Send + Sync + 'static { /// Returns where the pointer is, if the compositor says. fn cursor_pos(&self) -> Option<(i32, i32)>; + /// Returns the frame the window had when the user last began to drag it, if the backend has + /// kept it. + /// + /// A resize by dragging is measured from that frame, and not from the frame the window has by + /// the time the window manager handles the start of the drag: a compositor that reports the + /// frame all through the drag has moved on by then. The default keeps nothing and returns + /// `None`, and the window manager then takes the frame the window has when it handles the + /// start, as it does with the fake. + /// + /// # Example + /// + /// ```rust + /// use komorebi::backend::Backend; + /// use komorebi::backend::fake::FakeBackend; + /// + /// let fake = FakeBackend::with_one_monitor(); + /// fake.open_window(1, "foot", "foot", "a terminal"); + /// + /// assert_eq!(fake.drag_origin(1), None); + /// ``` + fn drag_origin(&self, _id: u32) -> Option { + None + } + + /// Returns the frame the user asked for when they last let go of an edge of the window, if + /// the backend has kept it. + /// + /// A resize by dragging ends at that frame, and not at the frame the window has by the time + /// the window manager handles the end of the drag. A compositor changes the frame once the + /// client has drawn at the new size, and goes on reporting the client's frames after the + /// drag is over, which can be before the window manager, busy with an earlier event, gets to + /// the end: the frame it would read is then one the client has not finished drawing, and the + /// drag would count for less than the user made it. The default keeps nothing and returns + /// `None`, and the window manager then takes the frame the window has, as it does for a drag + /// that had no steps. + /// + /// # Example + /// + /// ```rust + /// use komorebi::backend::Backend; + /// use komorebi::backend::fake::FakeBackend; + /// use komorebi::core::Rect; + /// + /// let fake = FakeBackend::with_one_monitor(); + /// fake.open_window(1, "foot", "foot", "a terminal"); + /// assert_eq!(fake.drag_end(1), None); + /// + /// let asked = Rect { left: 0, top: 0, right: 672, bottom: 704 }; + /// fake.set_drag_end(1, asked); + /// assert_eq!(fake.drag_end(1), Some(asked)); + /// ``` + fn drag_end(&self, _id: u32) -> Option { + None + } + // ---- commands ------------------------------------------------------------------------------ /// Moves and resizes the window to `rect`, a position and a size. diff --git a/komorebi/src/kwin/bridge.js b/komorebi/src/kwin/bridge.js index 6bd46e2a..261e5396 100644 --- a/komorebi/src/kwin/bridge.js +++ b/komorebi/src/kwin/bridge.js @@ -55,7 +55,8 @@ * `desktops` says which desktops a window is on now, `desktop_list` which desktops there are, and * `current_desktops` which desktop each output shows, each sent when it is not what was last sent; * `move_resize_started` and `move_resize_finished` are the start and the end of a drag of a window - * by the user, with its frame, and at the end where the pointer is; `cursor` answers a cursor + * by the user, with its frame, and at the end where the pointer is and the frame the user last + * asked for (`requested`, or `null` when the drag asked for none); `cursor` answers a cursor * query, and `failed` gives back the commands of a batch that could not be carried out. * * @typedef {{ @@ -74,7 +75,9 @@ * @typedef {{ * type: "move_resize_started", id: string, move: boolean, resize: boolean, geo: Rect * }} MoveResizeStarted - * @typedef {{ type: "move_resize_finished", id: string, geo: Rect, cursor: Point }} MoveResizeFinished + * @typedef {{ + * type: "move_resize_finished", id: string, geo: Rect, requested: Rect | null, cursor: Point + * }} MoveResizeFinished * @typedef {{ type: "cursor", token: number, x: number, y: number }} CursorAnswer * @typedef {{ type: "failed", batch: number, cmds: Command[] }} Failed * @typedef {Snapshot | Added | Removed | Activated | Minimized | Geometry | Caption | Desktops @@ -123,6 +126,9 @@ var known = {}; // so a match does not end the watch; only the clock does.) /** @type {Record} */ var want = {}; +// where each window being dragged was last asked to be: the frame lags behind it +/** @type {Record} */ +var stepped = {}; var WANT_RETRIES = 3; var WANT_MS = 1000; @@ -369,10 +375,19 @@ function track(w, announce) { }); w.interactiveMoveResizeStarted.connect(function () { delete want[id]; + delete stepped[id]; emit("move_resize_started", { id: id, move: !!w.move, resize: !!w.resize, geo: rect(w.frameGeometry) }); }); + // What the user is asking for, every step of the drag. For a Wayland client the frame only + // follows once the client has drawn at the new size, so at the end of a drag it can be well + // short of where the pointer took the edge. + w.interactiveMoveResizeStepped.connect(function (g) { + stepped[id] = rect(g); + }); w.interactiveMoveResizeFinished.connect(function () { - emit("move_resize_finished", { id: id, geo: rect(w.frameGeometry), cursor: cursor() }); + var requested = stepped[id] || null; + delete stepped[id]; + emit("move_resize_finished", { id: id, geo: rect(w.frameGeometry), requested: requested, cursor: cursor() }); }); } @@ -383,6 +398,7 @@ workspace.windowRemoved.connect(function (w) { var id = wid(w); delete known[id]; delete want[id]; + delete stepped[id]; emit("removed", { id: id }); }); /** @type {string | null} */ diff --git a/komorebi/src/kwin/bridge.test.js b/komorebi/src/kwin/bridge.test.js index 27a392ba..e0bb0fa0 100644 --- a/komorebi/src/kwin/bridge.test.js +++ b/komorebi/src/kwin/bridge.test.js @@ -96,6 +96,7 @@ function window({ captionChanged: new Signal(), desktopsChanged: new Signal(), interactiveMoveResizeStarted: new Signal(), + interactiveMoveResizeStepped: new Signal(), interactiveMoveResizeFinished: new Signal(), closeWindow: () => assert.fail("a window that is in no KWin was closed"), ...rest, @@ -350,9 +351,17 @@ test("what the bridge sends for a session is what the daemon's tests read", () = k.workspace.cursorPos = { x: 1500.4, y: 600 }; editor.move = false; editor.interactiveMoveResizeFinished.emit(); + // and drags its right edge further right: the client draws the new size after the pointer + // has moved on, so the frame is short of the edge when they let go + editor.resize = true; + editor.interactiveMoveResizeStarted.emit(); + editor.interactiveMoveResizeStepped.emit(geometry(40, 30, 1100.4, 1050)); + editor.frameGeometry = geometry(40, 30, 1040, 1050); + editor.resize = false; + editor.interactiveMoveResizeFinished.emit(); assert.deepStrictEqual(k.events(), events); - assert.deepStrictEqual(editor.frameGeometry, geometry(40.2, 30, 960, 1050)); + assert.deepStrictEqual(editor.frameGeometry, geometry(40, 30, 1040, 1050)); assert.equal(k.workspace.activeWindow, editor); assert.deepStrictEqual(k.raised, [editor]); assert.equal(editor.minimized, false); @@ -672,8 +681,9 @@ test("a drag is reported when the user takes hold of a window and when they let w.resize = true; w.interactiveMoveResizeStarted.emit(); + w.interactiveMoveResizeStepped.emit(geometry(0, 0, 1080.6, 1050)); w.frameGeometry = geometry(0, 0, 1000.4, 1050); - k.workspace.cursorPos = { x: 1000.4, y: 500.6 }; + k.workspace.cursorPos = { x: 1080.6, y: 500.6 }; w.resize = false; w.interactiveMoveResizeFinished.emit(); @@ -691,7 +701,8 @@ test("a drag is reported when the user takes hold of a window and when they let type: "move_resize_finished", id: "{w}", geo: { x: 0, y: 0, w: 1000, h: 1050 }, - cursor: { x: 1000, y: 501 }, + requested: { x: 0, y: 0, w: 1081, h: 1050 }, + cursor: { x: 1081, y: 501 }, seq: 4, }, ]); diff --git a/komorebi/src/kwin/fixtures/events.json b/komorebi/src/kwin/fixtures/events.json index a69c5571..581a14d0 100644 --- a/komorebi/src/kwin/fixtures/events.json +++ b/komorebi/src/kwin/fixtures/events.json @@ -91,6 +91,20 @@ }, { "type": "move_resize_finished", "seq": 23, "id": "{0e5a1c3b-0000-4000-8000-00000000000a}", - "geo": {"x": 40, "y": 30, "w": 960, "h": 1050}, "cursor": {"x": 1500, "y": 600} + "geo": {"x": 40, "y": 30, "w": 960, "h": 1050}, "requested": null, + "cursor": {"x": 1500, "y": 600} + }, + { + "type": "move_resize_started", "seq": 24, "id": "{0e5a1c3b-0000-4000-8000-00000000000a}", + "move": false, "resize": true, "geo": {"x": 40, "y": 30, "w": 960, "h": 1050} + }, + { + "type": "geometry", "seq": 25, "id": "{0e5a1c3b-0000-4000-8000-00000000000a}", + "geo": {"x": 40, "y": 30, "w": 1040, "h": 1050} + }, + { + "type": "move_resize_finished", "seq": 26, "id": "{0e5a1c3b-0000-4000-8000-00000000000a}", + "geo": {"x": 40, "y": 30, "w": 1040, "h": 1050}, + "requested": {"x": 40, "y": 30, "w": 1100, "h": 1050}, "cursor": {"x": 1500, "y": 600} } ] diff --git a/komorebi/src/kwin/kwin-api.d.ts b/komorebi/src/kwin/kwin-api.d.ts index 87377c7c..1d2da9b6 100644 --- a/komorebi/src/kwin/kwin-api.d.ts +++ b/komorebi/src/kwin/kwin-api.d.ts @@ -96,6 +96,9 @@ interface KWinWindow { /** The user took hold of the window with the pointer, to move it (`move`) or resize it * (`resize`). */ readonly interactiveMoveResizeStarted: Signal; + /** A step of the drag, with the frame the user is asking for, which the window's frame follows + * once the client has drawn at that size. */ + readonly interactiveMoveResizeStepped: Signal<[geometry: QRectF]>; /** The user let go of the window. */ readonly interactiveMoveResizeFinished: Signal; closeWindow(): void; diff --git a/komorebi/src/kwin/mod.rs b/komorebi/src/kwin/mod.rs index 32c84b15..e43b4559 100644 --- a/komorebi/src/kwin/mod.rs +++ b/komorebi/src/kwin/mod.rs @@ -277,7 +277,9 @@ impl Poll { /// /// The queries are answered from a [`state::Table`] that the script's events keep up to date, so /// they do not wait for KWin, except [`Backend::cursor_pos`]: only the script can read the pointer, -/// so it is asked, and given 250 ms to answer. +/// so it is asked, and given 250 ms to answer. The table also keeps the frame a window had when the +/// user began to drag it, for [`Backend::drag_origin`], and the frame the user asked for when they +/// let go of an edge of it, for [`Backend::drag_end`]. /// /// A command ([`Backend::set_rect`], [`Backend::focus`] and the rest) is queued for the script and /// returns: the script gets the queue as the answer to its held `Poll` call, and carries the @@ -781,6 +783,14 @@ impl Backend for KWinBackend { self.shared.table.lock().foreground() } + fn drag_origin(&self, id: u32) -> Option { + self.shared.table.lock().drag_origin(id) + } + + fn drag_end(&self, id: u32) -> Option { + self.shared.table.lock().drag_end(id) + } + fn monitors(&self) -> eyre::Result> { let monitors = self.shared.table.lock().monitors(); if monitors.is_empty() { @@ -1228,6 +1238,104 @@ mod tests { } } + /// The end of a resize in the order of a run of `vm-drag-resize` that failed. The user lets go + /// of the left edge of the right tile after pulling it 200 pixels. The client has drawn 140 of + /// them, and KWin reports that frame a millisecond after the end of the drag. The window + /// manager is busy with something else, and gets to the end later: the tile has to take the 200 + /// pixels the user asked for, and not the 140 of the frame it finds by then. + #[test] + fn a_frame_that_follows_the_end_of_a_resize_does_not_make_the_drag_count_for_less() { + let (_runtime, backend) = offline(); + let backend = Arc::new(backend); + + let snapshot = json!({ + "type": "snapshot", + "windows": [], + "screens": [{ + "name": "DP-1", "manufacturer": "ACME", "model": "M1", "serial": "S1", + "geo": { "x": 0, "y": 0, "w": 1920, "h": 1080 }, + "area": { "x": 0, "y": 0, "w": 1920, "h": 1050 }, + }], + "desktops": [{ "id": "d1", "name": "Desktop 1" }], + "current_desktops": [{ "output": "DP-1", "id": "d1" }], + "active": null, + "cursor": { "x": 5, "y": 6 }, + }); + backend + .shared + .table + .lock() + .handle(&snapshot, Instant::now()); + + let (_sender, receiver) = crossbeam_channel::bounded(1); + let socket = std::path::PathBuf::from(format!( + "/tmp/komorebi-kwin-drag-{}.sock", + std::process::id() + )); + let mut wm = crate::backend::with_backend(backend.clone(), || { + let mut wm = + crate::window_manager::WindowManager::new(receiver, Some(socket.clone())).unwrap(); + wm.init().unwrap(); + wm + }); + + // what KWin reports, as the events the window manager gets + let report = |event: Value| -> Vec { + let out = backend.shared.table.lock().handle(&event, Instant::now()); + out.into_iter() + .filter_map(|output| match output { + Output::Event(event) => Some(event), + _ => None, + }) + .collect() + }; + let process = |wm: &mut crate::window_manager::WindowManager, events: Vec<_>| { + crate::backend::with_backend(backend.clone(), || { + for event in events { + wm.process_event(event).unwrap(); + } + }); + }; + let frame = |left: i32| json!({ "x": left, "y": 0, "w": 1920 - left, "h": 1050 }); + + // two windows open, and are tiled + for (uuid, title) in [("{a}", "left"), ("{b}", "right")] { + let shown = report(json!({ + "type": "added", "id": uuid, "pid": 0, "class": "foot", "caption": title, + "normal": true, "minimized": false, "desktops": ["d1"], + "geo": { "x": 0, "y": 0, "w": 100, "h": 100 }, + })); + process(&mut wm, shown); + } + + // the right tile, as the window manager put it + let tile = backend.window_rect(2).unwrap(); + assert!(tile.left > 900, "{tile:?}"); + + let started = report(json!({ + "type": "move_resize_started", "id": "{b}", "move": false, "resize": true, + "geo": frame(tile.left) + })); + process(&mut wm, started); + + // the end is waiting for the window manager, and a frame event comes + let waiting = report(json!({ + "type": "move_resize_finished", "id": "{b}", "geo": frame(tile.left - 140), + "requested": frame(tile.left - 200), "cursor": { "x": 1, "y": 1 } + })); + report(json!({ "type": "geometry", "id": "{b}", "geo": frame(tile.left - 140) })); + assert_eq!(waiting.len(), 1, "the end: {waiting:?}"); + + process(&mut wm, waiting); + + assert_eq!( + backend.window_rect(2).unwrap().left, + tile.left - 200, + "the tile took what the user asked for" + ); + let _ = std::fs::remove_file(socket); + } + #[test] fn a_command_about_a_window_the_table_does_not_know_is_an_error_and_sends_nothing() { let (runtime, backend) = offline(); diff --git a/komorebi/src/kwin/state.rs b/komorebi/src/kwin/state.rs index ca21b8a4..44db841d 100644 --- a/komorebi/src/kwin/state.rs +++ b/komorebi/src/kwin/state.rs @@ -101,6 +101,15 @@ struct Entry { desktops: Vec, /// The drag the user is in the middle of, if any drag: Option, + /// The frame the window had when the drag began, which a drag is measured from. It is kept + /// apart from `info.rect`, which the frame events go on changing before the window manager has + /// handled the start + drag_origin: Option, + /// The frame the user asked for when they let go of an edge of the window, which the end of + /// the resize is. It is kept apart from `info.rect`, which the frame events that follow the + /// end of the drag go on changing before the window manager has handled it, and the client + /// is short of it until it has drawn at the new size + drag_end: Option, /// komorebi put it on the parking desktop parked: bool, /// The desktop the window was on when it was parked @@ -231,6 +240,19 @@ impl Table { self.windows.get(&id).map(|e| e.info.clone()) } + /// Returns the frame the window had when the user last began to drag it, or `None` if they + /// have not since the table first saw it. + pub fn drag_origin(&self, id: u32) -> Option { + self.windows.get(&id).and_then(|e| e.drag_origin) + } + + /// Returns the frame the user asked for when they last let go of an edge of the window, or + /// `None` if the last drag was a move, or a resize that sent no step, or if they have not + /// dragged it since the table first saw it. + pub fn drag_end(&self, id: u32) -> Option { + self.windows.get(&id).and_then(|e| e.drag_end) + } + /// Returns the windows komorebi may manage that are open right now, ordered by id. pub fn windows(&self) -> Vec { let mut windows: Vec<_> = self @@ -595,6 +617,8 @@ impl Table { kwin_normal: w["normal"].as_bool().unwrap_or(false), desktops: strings(&w["desktops"]), drag: None, + drag_origin: None, + drag_end: None, parked: false, home: None, closed_at: None, @@ -654,9 +678,13 @@ impl Table { /// ([`Table::window_workspace_commands`]) is on it already, and raises nothing, and neither /// does a window on the parking desktop. /// - `move_resize_started`, `move_resize_finished`: the user took hold of a window with the - /// pointer (`geo` is its frame then) and let go of it (`geo` is its frame, `cursor` where the - /// pointer is). For a move, they are a [`WindowManagerEvent::MoveStart`] and a - /// [`WindowManagerEvent::MoveEnd`]; a resize raises no event. + /// pointer (`geo` is its frame then, which [`Table::drag_origin`] keeps) and let go of it + /// (`geo` is its frame, `cursor` where the pointer is). For a move, they are a + /// [`WindowManagerEvent::MoveStart`] and a [`WindowManagerEvent::MoveEnd`]. For a resize + /// they are a [`WindowManagerEvent::ResizeStart`] and a [`WindowManagerEvent::ResizeEnd`], + /// and the end of the resize is `requested`, where the user took the edges, when the event + /// has one ([`Table::drag_end`]): the window's frame stays the one KWin reports, which the + /// `geometry` events that follow go on changing. /// - `current_desktops`: the desktop each output shows. An output that shows another desktop /// than the table had it showing is a [`WindowManagerEvent::WorkspaceChange`]; komorebi's own /// switch ([`Table::switch_commands`]) raises nothing. An output that shows the parking @@ -955,11 +983,13 @@ impl Table { }; entry.info.rect = rect(&event["geo"]); + entry.drag_origin = Some(entry.info.rect); + entry.drag_end = None; - let kind = if event["resize"].as_bool().unwrap_or(false) { - Drag::Resize + let (kind, notification) = if event["resize"].as_bool().unwrap_or(false) { + (Drag::Resize, KWinNotification::InteractiveResizeStarted) } else { - Drag::Move + (Drag::Move, KWinNotification::InteractiveMoveStarted) }; entry.drag = Some(kind); @@ -968,15 +998,10 @@ impl Table { } let window = Window::from(id); - match kind { - Drag::Move => vec![Output::Event(WindowManagerEvent::MoveStart( - kwin(KWinNotification::InteractiveMoveStarted), - window, - ))], - // the window manager is not told of a resize: the window keeps the size the user gave - // it until the workspace is tiled again - Drag::Resize => vec![], - } + vec![Output::Event(match kind { + Drag::Move => WindowManagerEvent::MoveStart(kwin(notification), window), + Drag::Resize => WindowManagerEvent::ResizeStart(kwin(notification), window), + })] } fn on_drag_finished(&mut self, event: &Value) -> Vec { @@ -992,7 +1017,16 @@ impl Table { return vec![]; }; + // The window's frame is the one KWin has, and goes on changing as the client draws. For a + // resize, where the user took the edges to is the end of the drag, and is kept apart from + // the frame: the frame follows when the client has drawn at the new size, at the end of a + // drag it can be well short of that, and the frame events that follow it come before the + // window manager, which may be busy with an earlier event, handles the end. entry.info.rect = rect(&event["geo"]); + entry.drag_end = match (entry.drag, event["requested"].is_object()) { + (Some(Drag::Resize), true) => Some(rect(&event["requested"])), + _ => None, + }; let Some(kind) = entry.drag.take() else { return vec![]; }; @@ -1002,13 +1036,15 @@ impl Table { } let window = Window::from(id); - match kind { - Drag::Move => vec![Output::Event(WindowManagerEvent::MoveEnd( - kwin(KWinNotification::InteractiveMoveFinished), + vec![Output::Event(match kind { + Drag::Move => { + WindowManagerEvent::MoveEnd(kwin(KWinNotification::InteractiveMoveFinished), window) + } + Drag::Resize => WindowManagerEvent::ResizeEnd( + kwin(KWinNotification::InteractiveResizeFinished), window, - ))], - Drag::Resize => vec![], - } + ), + })] } /// Some output now shows another desktop: komorebi's request, or a pager, a shortcut, an app @@ -1273,10 +1309,13 @@ mod tests { "desktop_list -> ", "desktops -> WorkspaceMove 1 to 0", "current_desktops -> WorkspaceChange to 0", - // the user drags the editor + // the user drags the editor, and then its right edge "move_resize_started -> MoveStart 1", "geometry -> ", "move_resize_finished -> MoveEnd 1", + "move_resize_started -> ResizeStart 1", + "geometry -> ", + "move_resize_finished -> ResizeEnd 1", ] ); @@ -1284,7 +1323,12 @@ mod tests { let windows = t.windows(); assert_eq!(windows.len(), 1); assert_eq!(windows[0].title, "notes.txt — Kate"); - assert_eq!(windows[0].rect.right, 960, "the frame komorebi asked for"); + assert_eq!(windows[0].rect.right, 1040, "the frame KWin has"); + assert_eq!( + t.drag_end(1).unwrap().right, + 1100, + "where the user took the edge" + ); assert_eq!(t.window(3).map(|w| w.alive), Some(false)); assert_eq!(t.window(2).unwrap().rect.bottom, 532, "the geometry event"); assert_eq!(t.foreground(), Some(1)); @@ -1524,6 +1568,119 @@ mod tests { Some((50, 60)), "the cursor at the end of the drag is kept" ); + + let started = t.handle(&json!({ "type": "move_resize_started", "id": "b", "move": false, "resize": true, "geo": geo }), now); + let finished = t.handle(&json!({ "type": "move_resize_finished", "id": "b", "geo": geo, "cursor": {"x": 1, "y": 1} }), now); + assert_eq!(events(&started), vec!["ResizeStart 2"]); + assert_eq!(events(&finished), vec!["ResizeEnd 2"]); + } + + #[test] + fn the_end_of_a_resize_is_where_the_user_took_it_not_where_the_frame_had_got_to() { + let mut t = table(vec![win("a", &["d1"])]); + let now = Instant::now(); + let start = json!({"x":10,"y":10,"w":100,"h":100}); + + t.handle(&json!({ "type": "move_resize_started", "id": "a", "move": false, "resize": true, "geo": start }), now); + t.handle( + &json!({ "type": "move_resize_finished", "id": "a", + "geo": {"x":10,"y":10,"w":112,"h":100}, + "requested": {"x":10,"y":10,"w":172,"h":100}, + "cursor": {"x": 1, "y": 1} }), + now, + ); + + let end = t.drag_end(1).unwrap(); + assert_eq!((end.left, end.right), (10, 172), "{end:?}"); + let frame = t.window(1).unwrap().rect; + assert_eq!( + (frame.left, frame.right), + (10, 112), + "the frame is KWin's: {frame:?}" + ); + } + + /// The order of a run of the VM test that failed: the user lets go, the client has not drawn + /// at the size they asked for, KWin reports its frame a millisecond after the end, and the + /// window manager, busy with an earlier event, gets to the end 17 ms after that + #[test] + fn a_frame_that_follows_the_end_of_a_resize_does_not_change_where_the_user_took_it() { + let mut t = table(vec![win("a", &["d1"])]); + let now = Instant::now(); + + t.handle(&json!({ "type": "move_resize_started", "id": "a", "move": false, "resize": true, "geo": {"x":10,"y":10,"w":100,"h":100} }), now); + let finished = t.handle( + &json!({ "type": "move_resize_finished", "id": "a", + "geo": {"x":10,"y":10,"w":112,"h":100}, + "requested": {"x":10,"y":10,"w":172,"h":100}, + "cursor": {"x": 1, "y": 1} }), + now, + ); + assert_eq!(events(&finished), vec!["ResizeEnd 1"]); + + t.handle( + &json!({ "type": "geometry", "id": "a", "geo": {"x":10,"y":10,"w":160,"h":100} }), + now + Duration::from_millis(1), + ); + + // what the window manager reads when it handles the end, 17 ms after the end + let end = t.drag_end(1).unwrap(); + assert_eq!((end.left, end.right), (10, 172), "{end:?}"); + let frame = t.window(1).unwrap().rect; + assert_eq!(frame.right, 160, "the frame is the one KWin reported last"); + } + + #[test] + fn a_resize_with_no_step_or_a_move_has_no_end_of_its_own() { + let mut t = table(vec![win("a", &["d1"])]); + let now = Instant::now(); + let start = json!({"x":10,"y":10,"w":100,"h":100}); + let end = json!({ "type": "move_resize_finished", "id": "a", + "geo": {"x":10,"y":10,"w":112,"h":100}, "cursor": {"x": 1, "y": 1} }); + + // a resize that sent no step: its end is the frame + t.handle(&json!({ "type": "move_resize_started", "id": "a", "move": false, "resize": true, "geo": start }), now); + t.handle(&end, now); + assert_eq!(t.drag_end(1), None); + + // the end of the last resize is forgotten when the window is taken hold of again + t.handle(&json!({ "type": "move_resize_started", "id": "a", "move": false, "resize": true, "geo": start }), now); + t.handle( + &json!({ "type": "move_resize_finished", "id": "a", + "geo": {"x":10,"y":10,"w":112,"h":100}, + "requested": {"x":10,"y":10,"w":172,"h":100}, + "cursor": {"x": 1, "y": 1} }), + now, + ); + assert!(t.drag_end(1).is_some()); + t.handle(&json!({ "type": "move_resize_started", "id": "a", "move": true, "resize": false, "geo": start }), now); + assert_eq!(t.drag_end(1), None, "a new drag has no end yet"); + + // and a move has none, whatever the event says + t.handle( + &json!({ "type": "move_resize_finished", "id": "a", + "geo": {"x":50,"y":60,"w":100,"h":100}, + "requested": {"x":999,"y":999,"w":100,"h":100}, + "cursor": {"x": 1, "y": 1} }), + now, + ); + assert_eq!(t.drag_end(1), None); + } + + #[test] + fn the_frame_a_drag_began_with_is_kept_while_the_frame_changes() { + let mut t = table(vec![win("a", &["d1"])]); + let now = Instant::now(); + + t.handle(&json!({ "type": "move_resize_started", "id": "a", "move": false, "resize": true, "geo": {"x":10,"y":10,"w":100,"h":100} }), now); + t.handle( + &json!({ "type": "geometry", "id": "a", "geo": {"x":10,"y":10,"w":140,"h":100} }), + now, + ); + + assert_eq!(t.window(1).unwrap().rect.right, 140); + let origin = t.drag_origin(1).unwrap(); + assert_eq!((origin.left, origin.right), (10, 100), "{origin:?}"); } #[test] diff --git a/komorebi/src/process_event.rs b/komorebi/src/process_event.rs index b9c001a0..24d17dac 100644 --- a/komorebi/src/process_event.rs +++ b/komorebi/src/process_event.rs @@ -41,6 +41,10 @@ //! a window let go where there is no tile goes back to its own. On the same monitor a drag //! counts as a move when the window's frame is as wide and as tall as its tile, and a floating //! window is not swapped. +//! - **ResizeStart** and **ResizeEnd**: the user dragged an edge or a corner of a window. When they +//! let go, each edge of the frame they left it with is compared with the same edge of the frame +//! it had when the drag began, the edges of its tile move by as much +//! ([`WindowManager::resize_window`]), and the workspace is tiled again. //! - **WorkspaceChange**: a monitor shows another workspace, because something other than komorebi //! switched it (a pager, a shortcut, an app raising a window of another desktop). The window //! manager follows ([`WindowManager::adopt_workspace_change`]) and asks the compositor for @@ -75,12 +79,15 @@ use crate::backend::backend; use crate::border_manager; use crate::core::DefaultLayout; use crate::core::Layout; +use crate::core::OperationDirection; use crate::core::Rect; +use crate::core::Sizing; use crate::core::WindowContainerBehaviour; use crate::notify_subscribers; use crate::state::State; use crate::transparency_manager; use crate::window::RuleDebug; +use crate::window::Window; use crate::window::should_act; use crate::window_manager::WindowManager; use crate::window_manager_event::KWinNotification; @@ -507,7 +514,7 @@ impl WindowManager { } WindowManagerEvent::MoveStart(_, window) => { let window_id = window.id; - if self.pending_move_op.is_none() { + if self.pending_move_op.is_none() && self.pending_resize_op.is_none() { let monitor_idx = self.focused_monitor_idx(); let workspace_idx = self .focused_monitor() @@ -726,6 +733,65 @@ impl WindowManager { } } } + WindowManagerEvent::ResizeStart(_, window) => { + let window_id = window.id; + + // A drag is measured from the frame the window has when it begins, which is what + // the user had under the pointer, and not from the tile the layout gave it: an app + // that snaps its size to a grid (a terminal), or has a minimum, is never exactly on + // its tile, and every drag would then look as if it had moved the other edges too. + // A start reported again during the same drag changes nothing: the first one is + // the one that counts. + let already_started = matches!( + *self.pending_resize_op, + Some((started, Some(_))) if started == window_id + ); + + if !already_started { + let started_from = match crate::backend::backend().drag_origin(window_id) { + Some(origin) => origin, + None => window.rect()?, + }; + let pending_resize_op = Arc::make_mut(&mut self.pending_resize_op); + *pending_resize_op = Option::from((window_id, Some(started_from))); + } + } + WindowManagerEvent::ResizeEnd(_, window) => { + let window_id = window.id; + let pending = *self.pending_resize_op; + // Always consume the pending resize op whenever this event is handled + let pending_resize_op = Arc::make_mut(&mut self.pending_resize_op); + *pending_resize_op = None; + + if let Some((wid, Some(started_from))) = pending { + // If the window handles don't match then something went wrong and the pending resize + // is not related to this current resize, if so abort this operation. + if wid != window_id { + eyre::bail!( + "window handles for resize operation don't match: {} != {}", + wid, + window_id + ); + } + + // where the user took the edges, which is not the window's frame while the + // client is still drawing at the new size, and the frame events after the + // drag can have changed that by now: the end of a resize does not wait for + // them + let new_position = match crate::backend::backend().drag_end(window_id) { + Some(asked) => asked, + None => window.rect()?, + }; + let resized = self.apply_mouse_resize(window, started_from, new_position)?; + + // put every window where the layout now says: the dragged one too when + // nothing could be done with what it was given (an edge at the edge of the + // screen has no neighbor to take room from) + if resized && new_position != started_from { + self.update_focused_workspace(false, false)?; + } + } + } } // a window that was just managed is on the desktop the compositor opened it on, which is the @@ -756,3 +822,80 @@ impl WindowManager { Ok(()) } } + +impl WindowManager { + /// Work out what the user did to the edges of a tile and ask the layout for it. The edges are + /// compared from where the window was when the drag began; the layout moves a shared edge by half + /// of what it is given. Returns whether there was a tile to resize. + fn apply_mouse_resize( + &mut self, + window: Window, + started_from: Rect, + new_position: Rect, + ) -> eyre::Result { + let window_id = window.id; + let workspace = self.focused_workspace_mut()?; + + // The container that was dragged, which is not necessarily the focused one: the press that + // began the drag may not have been given focus yet + let Some(container_idx) = workspace + .container_idx_for_window(window_id) + .filter(|_| workspace.tile) + else { + return Ok(false); + }; + + if container_idx != workspace.focused_container_idx() { + workspace.focus_container(container_idx); + } + + // How far each edge went. (A rect is left, top, width, height, so the right and bottom edges + // have to be worked out: comparing the widths, which is what comparing the rects field by + // field does, makes a drag of the left edge look like a drag of the right one too, and the + // code that then had to tell them apart did so by guessing.) + let edges = |rect: &Rect| { + ( + rect.left, + rect.top, + rect.left + rect.right, + rect.top + rect.bottom, + ) + }; + let (start_left, start_top, start_right, start_bottom) = edges(&started_from); + let (end_left, end_top, end_right, end_bottom) = edges(&new_position); + + let moved = [ + (OperationDirection::Left, end_left - start_left), + (OperationDirection::Up, end_top - start_top), + (OperationDirection::Right, end_right - start_right), + (OperationDirection::Down, end_bottom - start_bottom), + ]; + + tracing::debug!( + "resizing with mouse: {started_from:?} -> {new_position:?}, edges moved (left, up, right, down): {:?}", + moved.map(|(_, by)| by) + ); + + for (edge, by) in moved { + if by == 0 { + continue; + } + + // an edge that goes outward makes the tile bigger, inward smaller; the layout moves a + // shared edge by half of what it is given + let outward = match edge { + OperationDirection::Left | OperationDirection::Up => by < 0, + OperationDirection::Right | OperationDirection::Down => by > 0, + }; + let sizing = if outward { + Sizing::Increase + } else { + Sizing::Decrease + }; + + self.resize_window(edge, sizing, by.abs() * 2, false)?; + } + + Ok(true) + } +} diff --git a/komorebi/src/static_config.rs b/komorebi/src/static_config.rs index bc958310..bd4c2213 100644 --- a/komorebi/src/static_config.rs +++ b/komorebi/src/static_config.rs @@ -1260,6 +1260,7 @@ impl StaticConfig { hotwatch: Hotwatch::new()?, minimized_windows: HashMap::new(), pending_move_op: Arc::new(None), + pending_resize_op: Arc::new(None), already_moved_window_handles: Default::default(), known_window_ids: HashMap::new(), }; diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index 13b8b546..53b3e67b 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -153,6 +153,9 @@ pub struct WindowManager { /// The monitor, the workspace and the window of a move the user began with the pointer and /// has not let go of yet pub pending_move_op: Arc>, + /// The window of a resize the user began with the pointer and has not let go of yet, and the + /// frame it had when they took hold of it + pub pending_resize_op: Arc)>>, /// The windows an `initial_only` workspace rule has moved already, so that it moves each of /// them once, until it closes pub already_moved_window_handles: Arc>>, @@ -244,6 +247,7 @@ impl WindowManager { incoming_events: incoming, minimized_windows: HashMap::new(), pending_move_op: Arc::new(None), + pending_resize_op: Arc::new(None), already_moved_window_handles: Default::default(), known_window_ids: Default::default(), }) diff --git a/komorebi/src/window_manager_event.rs b/komorebi/src/window_manager_event.rs index 9ab3fc55..c2eab626 100644 --- a/komorebi/src/window_manager_event.rs +++ b/komorebi/src/window_manager_event.rs @@ -47,6 +47,10 @@ pub enum KWinNotification { InteractiveMoveStarted, /// `window.interactiveMoveResizeFinished` after a move InteractiveMoveFinished, + /// `window.interactiveMoveResizeStarted` for a resize + InteractiveResizeStarted, + /// `window.interactiveMoveResizeFinished` after a resize + InteractiveResizeFinished, } /// Events komorebi raises itself, for example from a command @@ -78,6 +82,11 @@ pub enum WindowManagerEvent { /// The user let go of a window they were moving: where it is now is what the window reports, /// and the pointer is where they let go MoveEnd(SystemNotification, Window), + /// The user took hold of an edge or a corner of a window to resize it with the pointer + ResizeStart(SystemNotification, Window), + /// The user let go of the edge or the corner they were dragging: where they took it is what the + /// window reports + ResizeEnd(SystemNotification, Window), /// A monitor (by id) now shows another workspace: komorebi did that itself, or a pager, a /// shortcut or an app raising a window did. Not about any one window. WorkspaceChange(SystemNotification, u32, usize), @@ -100,6 +109,8 @@ impl WindowManagerEvent { | WindowManagerEvent::Unmanage(window) | WindowManagerEvent::MoveStart(_, window) | WindowManagerEvent::MoveEnd(_, window) + | WindowManagerEvent::ResizeStart(_, window) + | WindowManagerEvent::ResizeEnd(_, window) | WindowManagerEvent::WorkspaceMove(_, window, _) => *window, WindowManagerEvent::WorkspaceChange(..) => return None, }) @@ -124,6 +135,8 @@ impl WindowManagerEvent { | WindowManagerEvent::TitleUpdate(n, _) | WindowManagerEvent::MoveStart(n, _) | WindowManagerEvent::MoveEnd(n, _) + | WindowManagerEvent::ResizeStart(n, _) + | WindowManagerEvent::ResizeEnd(n, _) | WindowManagerEvent::WorkspaceChange(n, _, _) | WindowManagerEvent::WorkspaceMove(n, _, _) => match n { SystemNotification::KWin(k) => k.to_string(), diff --git a/komorebi/tests/drag_resize.rs b/komorebi/tests/drag_resize.rs new file mode 100644 index 00000000..aa0d465d --- /dev/null +++ b/komorebi/tests/drag_resize.rs @@ -0,0 +1,440 @@ +//! Resizing a tile by dragging an edge, against an in-memory desktop. See docs/drag-resize.md for +//! what went wrong and why these cases exist. +//! +//! A rect is `left, top, width, height` (`right` and `bottom` are the size); the work area of the +//! fake monitor is 1920x1050. Window ids are in the 10_000s, the 20_000s and the 53_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::sync::Arc; + +fn added(id: u32) -> WindowManagerEvent { + WindowManagerEvent::Show( + SystemNotification::KWin(KWinNotification::WindowAdded), + Window::from(id), + ) +} + +fn resize_started(id: u32) -> WindowManagerEvent { + WindowManagerEvent::ResizeStart( + SystemNotification::KWin(KWinNotification::InteractiveResizeStarted), + Window::from(id), + ) +} + +fn resize_finished(id: u32) -> WindowManagerEvent { + WindowManagerEvent::ResizeEnd( + SystemNotification::KWin(KWinNotification::InteractiveResizeFinished), + Window::from(id), + ) +} + +fn desktop() -> (Arc, WindowManager) { + let fake = Arc::new(FakeBackend::with_one_monitor()); + let (_sender, receiver) = crossbeam_channel::bounded(1); + 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 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}")); +} + +/// Windows `first..first+count`, tiled in a layout, the last one focused +fn tiled(layout: DefaultLayout, first: u32, count: u32) -> (Arc, WindowManager) { + let (fake, mut wm) = desktop(); + with_backend(fake.clone(), || { + wm.process_command(SocketMessage::ChangeLayout(layout), Vec::new()) + .unwrap(); + for id in first..first + count { + fake.open_window(id, "foot", "foot", &format!("terminal {id}")); + wm.process_event(added(id)).unwrap(); + } + }); + (fake, wm) +} + +/// The user drags an edge of a window: `to` is what the frame is when they let go +fn drag(fake: &Arc, wm: &mut WindowManager, id: u32, to: Rect) { + with_backend(fake.clone(), || { + wm.process_event(resize_started(id)).unwrap(); + fake.move_window_by_user(id, to); + wm.process_event(resize_finished(id)).unwrap(); + }); +} + +fn grown_left(r: Rect, by: i32) -> Rect { + Rect { + left: r.left - by, + right: r.right + by, + ..r + } +} + +fn overlap(a: &Rect, b: &Rect) -> bool { + a.left < b.left + b.right + && b.left < a.left + a.right + && a.top < b.top + b.bottom + && b.top < a.top + a.bottom +} + +fn assert_tiling(fake: &FakeBackend, ids: &[u32]) { + let rects: Vec = ids.iter().map(|id| fake.rect_of(*id).unwrap()).collect(); + for (i, a) in rects.iter().enumerate() { + assert!( + a.left >= 0 && a.top >= 0 && a.left + a.right <= 1920 && a.top + a.bottom <= 1050, + "{a:?} is outside the work area" + ); + for b in &rects[i + 1..] { + assert!(!overlap(a, b), "{a:?} and {b:?} overlap"); + } + } +} + +#[test] +fn resizing_a_tile_by_hand_moves_the_split() { + let (fake, mut wm) = desktop(); + open(&fake, 10_101); + open(&fake, 10_102); + + with_backend(fake.clone(), || { + wm.process_event(added(10_101))?; + wm.process_event(added(10_102))?; + let b = fake.rect_of(10_102).unwrap(); + + // the focused window is the right tile; the user drags its left edge 200px to the left + wm.process_event(resize_started(10_102))?; + fake.move_window_by_user( + 10_102, + Rect { + left: b.left - 200, + right: b.right + 200, + ..b + }, + ); + wm.process_event(resize_finished(10_102)) + }) + .unwrap(); + + let (a, b) = (fake.rect_of(10_101).unwrap(), fake.rect_of(10_102).unwrap()); + assert!( + a.right < 900, + "the left tile should have shrunk: {a:?} {b:?}" + ); + assert!( + b.right > 1000, + "the right tile should have grown: {a:?} {b:?}" + ); + assert!(!overlap(&a, &b)); +} + +#[test] +fn a_long_drag_of_a_narrow_tile_is_not_dropped() { + // an ultrawide layout's right-hand stack is the narrowest thing there is, and the layout used to + // refuse any drag of more than half of a tile's own width, without a word + let (fake, mut wm) = tiled(DefaultLayout::UltrawideVerticalStack, 20_001, 5); + // 20_001 is the center, 20_002 the left column, 20_003..20_005 the stack on the right + let tile = fake.rect_of(20_003).unwrap(); + assert!(tile.left > 1000, "{tile:?} should be on the right"); + + // the focused window is 20_005, not the one being dragged + drag(&fake, &mut wm, 20_003, grown_left(tile, 300)); + + let after = fake.rect_of(20_003).unwrap(); + assert!( + after.right >= tile.right + 290, + "dragged by 300 and got {tile:?} -> {after:?}" + ); + let center = fake.rect_of(20_001).unwrap(); + assert!(center.right > 0 && center.left + center.right <= after.left); + assert_tiling(&fake, &[20_001, 20_002, 20_003, 20_004, 20_005]); + + // and the whole stack moved with it: they share the edge + for id in [20_004, 20_005] { + assert_eq!(fake.rect_of(id).unwrap().left, after.left, "window {id}"); + } +} + +#[test] +fn a_drag_further_than_the_neighbour_can_give_goes_as_far_as_it_can() { + let (fake, mut wm) = tiled(DefaultLayout::UltrawideVerticalStack, 20_011, 5); + let tile = fake.rect_of(20_013).unwrap(); + + // far past the center tile's whole width + drag(&fake, &mut wm, 20_013, grown_left(tile, 1000)); + + let after = fake.rect_of(20_013).unwrap(); + let center = fake.rect_of(20_011).unwrap(); + assert!( + after.right > tile.right + 400, + "it grew: {tile:?} -> {after:?}" + ); + // the floor is a tenth of the work area, before the paddings the layout then takes off + assert!( + center.right >= 140 && center.right < 300, + "the center tile is squeezed to about a tenth of the screen, not out of existence: {center:?}" + ); + assert_tiling(&fake, &[20_011, 20_012, 20_013, 20_014, 20_015]); +} + +#[test] +fn shrinking_a_tile_by_more_than_it_can_is_granted_as_far_as_it_goes() { + let (fake, mut wm) = tiled(DefaultLayout::UltrawideVerticalStack, 20_021, 5); + let tile = fake.rect_of(20_023).unwrap(); + + // the user pulls the left edge inward by more than the tile is wide + drag( + &fake, + &mut wm, + 20_023, + Rect { + left: tile.left + tile.right - 20, + right: 20, + ..tile + }, + ); + + let after = fake.rect_of(20_023).unwrap(); + assert!(after.right < tile.right, "it shrank: {tile:?} -> {after:?}"); + assert!(after.right >= 140, "but not to nothing: {after:?}"); + assert_tiling(&fake, &[20_021, 20_022, 20_023, 20_024, 20_025]); +} + +#[test] +fn a_drag_is_measured_from_where_the_window_was_not_from_its_tile() { + // a terminal snaps its size to its cells, so it never quite fills its tile; the horizontal split + // between the two windows on the right must stay where it is when the *left* edge is dragged + let (fake, mut wm) = tiled(DefaultLayout::BSP, 20_031, 3); + let top_right = fake.rect_of(20_032).unwrap(); + let split_before = fake.rect_of(20_033).unwrap().top; + + let snapped = Rect { + right: top_right.right - 1, + bottom: top_right.bottom - 8, + ..top_right + }; + fake.move_window_by_user(20_032, snapped); + + drag(&fake, &mut wm, 20_032, grown_left(snapped, 100)); + + let after = fake.rect_of(20_032).unwrap(); + assert!( + after.left <= top_right.left - 90, + "{top_right:?} -> {after:?}" + ); + assert_eq!( + fake.rect_of(20_033).unwrap().top, + split_before, + "the split between the two on the right moved, though only a left edge was dragged" + ); + assert_tiling(&fake, &[20_031, 20_032, 20_033]); +} + +#[test] +fn the_window_that_was_dragged_is_the_one_resized_not_the_focused_one() { + let (fake, mut wm) = tiled(DefaultLayout::BSP, 20_041, 3); + // 20_043 (the bottom right tile) has focus; 20_042 (top right) is dragged by its bottom edge + let top_right = fake.rect_of(20_042).unwrap(); + let bottom_right = fake.rect_of(20_043).unwrap(); + + drag( + &fake, + &mut wm, + 20_042, + Rect { + bottom: top_right.bottom + 100, + ..top_right + }, + ); + + let (a, b) = (fake.rect_of(20_042).unwrap(), fake.rect_of(20_043).unwrap()); + assert!(a.bottom >= top_right.bottom + 90, "{top_right:?} -> {a:?}"); + assert!( + b.bottom <= bottom_right.bottom - 90, + "{bottom_right:?} -> {b:?}" + ); + assert_tiling(&fake, &[20_041, 20_042, 20_043]); +} + +#[test] +fn dragging_an_edge_that_has_no_neighbour_puts_the_window_back() { + let (fake, mut wm) = tiled(DefaultLayout::BSP, 20_051, 2); + let left = fake.rect_of(20_051).unwrap(); + let right = fake.rect_of(20_052).unwrap(); + + // the outer left edge of the left tile has nothing to take room from + drag(&fake, &mut wm, 20_051, grown_left(left, 80)); + + assert_eq!(fake.rect_of(20_051).unwrap(), left); + assert_eq!(fake.rect_of(20_052).unwrap(), right); +} + +#[test] +fn a_drag_that_changed_nothing_changes_nothing() { + let (fake, mut wm) = tiled(DefaultLayout::BSP, 20_061, 3); + let before: Vec = (20_061..20_064) + .map(|id| fake.rect_of(id).unwrap()) + .collect(); + + // a click on an edge: started, finished, nowhere + drag(&fake, &mut wm, 20_062, fake.rect_of(20_062).unwrap()); + + let after: Vec = (20_061..20_064) + .map(|id| fake.rect_of(id).unwrap()) + .collect(); + assert_eq!(before, after); +} + +#[test] +fn a_corner_resizes_both_of_its_edges() { + let (fake, mut wm) = tiled(DefaultLayout::BSP, 20_071, 3); + // the bottom right tile, by its top left corner: up into the tile above, left into the one beside + let tile = fake.rect_of(20_073).unwrap(); + let above = fake.rect_of(20_072).unwrap(); + let beside = fake.rect_of(20_071).unwrap(); + + drag( + &fake, + &mut wm, + 20_073, + Rect { + left: tile.left - 100, + top: tile.top - 100, + right: tile.right + 100, + bottom: tile.bottom + 100, + }, + ); + + let after = fake.rect_of(20_073).unwrap(); + assert!( + after.left <= tile.left - 90 && after.top <= tile.top - 90, + "{tile:?} -> {after:?}" + ); + assert!(fake.rect_of(20_072).unwrap().bottom < above.bottom); + assert!(fake.rect_of(20_071).unwrap().right < beside.right); + assert_tiling(&fake, &[20_071, 20_072, 20_073]); +} + +#[test] +fn the_edge_of_a_stack_is_the_edge_of_its_tile() { + let (fake, mut wm) = tiled(DefaultLayout::BSP, 53_001, 3); + // 53_003 has the focus: it goes in front of 53_002, whose tile is the top right one + with_backend(fake.clone(), || { + wm.process_command( + SocketMessage::StackWindow(OperationDirection::Up), + Vec::new(), + ) + }) + .unwrap(); + let tile = fake.rect_of(53_003).unwrap(); + let beside = fake.rect_of(53_001).unwrap(); + assert_eq!(wm.focused_workspace().unwrap().containers().len(), 2); + + drag(&fake, &mut wm, 53_003, grown_left(tile, 100)); + + let after = fake.rect_of(53_003).unwrap(); + assert!( + after.left <= tile.left - 90, + "the stack's tile grew: {tile:?} -> {after:?}" + ); + assert!( + fake.rect_of(53_001).unwrap().right <= beside.right - 90, + "and the tile beside it gave up the room" + ); + assert_tiling(&fake, &[53_001, 53_003]); +} + +#[test] +fn a_floating_window_dragged_by_its_edge_is_left_as_the_user_made_it() { + let (fake, mut wm) = tiled(DefaultLayout::BSP, 53_011, 2); + with_backend(fake.clone(), || { + // 53_012 has the focus + wm.process_command(SocketMessage::ToggleFloat, Vec::new()) + }) + .unwrap(); + let tile = fake.rect_of(53_011).unwrap(); + let floating = fake.rect_of(53_012).unwrap(); + let dragged = grown_left(floating, 100); + + drag(&fake, &mut wm, 53_012, dragged); + + assert_eq!(fake.rect_of(53_012), Some(dragged)); + assert_eq!( + fake.rect_of(53_011), + Some(tile), + "a floating window has no tile to resize, and takes nothing from the one that has" + ); +} + +#[test] +fn the_window_of_a_monocle_dragged_by_its_edge_is_left_as_the_user_made_it() { + let (fake, mut wm) = tiled(DefaultLayout::BSP, 53_021, 2); + with_backend(fake.clone(), || { + // 53_022 has the focus + wm.process_command(SocketMessage::ToggleMonocle, Vec::new()) + }) + .unwrap(); + let monocle = fake.rect_of(53_022).unwrap(); + let dragged = Rect { + right: monocle.right - 100, + ..monocle + }; + + drag(&fake, &mut wm, 53_022, dragged); + + assert_eq!(fake.rect_of(53_022), Some(dragged)); + assert!(wm.focused_workspace().unwrap().monocle_container.is_some()); +} + +#[test] +fn the_end_of_a_resize_is_where_the_user_took_the_edge_when_the_frame_has_not_got_there() { + // KWin's frame is the client's, and when the user lets go the client is still drawing at the + // size they asked for: here 140 of the 200 pixels, with the frame events that follow the end + // having come before the window manager gets to it. The backend has kept what the user asked + // for, and the drag counts for that + let (fake, mut wm) = desktop(); + open(&fake, 53_031); + open(&fake, 53_032); + + with_backend(fake.clone(), || { + wm.process_event(added(53_031))?; + wm.process_event(added(53_032))?; + let tile = fake.rect_of(53_032).unwrap(); + + wm.process_event(resize_started(53_032))?; + fake.move_window_by_user(53_032, grown_left(tile, 140)); + fake.set_drag_end(53_032, grown_left(tile, 200)); + wm.process_event(resize_finished(53_032))?; + + assert_eq!( + fake.rect_of(53_032).unwrap().left, + tile.left - 200, + "the tile took the 200 pixels the user asked for" + ); + Ok::<(), color_eyre::eyre::Report>(()) + }) + .unwrap(); + + assert_tiling(&fake, &[53_031, 53_032]); +} diff --git a/komorebi/tests/drag_swap.rs b/komorebi/tests/drag_swap.rs index 09cbef14..8fe3c437 100644 --- a/komorebi/tests/drag_swap.rs +++ b/komorebi/tests/drag_swap.rs @@ -29,7 +29,8 @@ fn drag(kind: KWinNotification, id: u32, start: bool, resize: bool) -> WindowMan match (start, resize) { (true, false) => WindowManagerEvent::MoveStart(n, w), (false, false) => WindowManagerEvent::MoveEnd(n, w), - (_, true) => unreachable!("the window manager is not told of a resize"), + (true, true) => WindowManagerEvent::ResizeStart(n, w), + (false, true) => WindowManagerEvent::ResizeEnd(n, w), } } diff --git a/nix/tests/vm/suites/drag-resize/default.nix b/nix/tests/vm/suites/drag-resize/default.nix new file mode 100644 index 00000000..66c2aff7 --- /dev/null +++ b/nix/tests/vm/suites/drag-resize/default.nix @@ -0,0 +1,8 @@ +{ + tier = "slow"; + kind = "session"; + timeoutMinutes = 15; + # The module's unit starts komorebi when the session does, and the test drags against that + # daemon, reading the drags it has handled from the unit's journal. The pointer is a uinput + # device the session node has (komorebi_vm.Pointer). +} diff --git a/nix/tests/vm/suites/drag-resize/test.py b/nix/tests/vm/suites/drag-resize/test.py new file mode 100644 index 00000000..bd633b0a --- /dev/null +++ b/nix/tests/vm/suites/drag-resize/test.py @@ -0,0 +1,244 @@ +# Resizing a tile by dragging its edge, in a Plasma session, with a pointer device the test drives +# from inside the guest (`komorebi_vm.Pointer`). Edges and corners of three tiles are grabbed and +# dragged, and what happened is checked against what a user expects +# (`komorebi/tests/drag_resize.rs` checks the window manager's side against the fake): +# +# * a dragged edge that has a neighbor moves by what the pointer moved, and the neighbor's edge +# moves with it: they share it +# * a dragged edge with no neighbor (the edge of the screen) does not move, and the window is put +# back +# * edges that were not dragged do not move, and every edge of every other tile either stays or +# moves with a dragged one +# * the windows still tile: inside the screen, not overlapping +# +# The strict checks are on the tiles, which are komorebi's own layout (`latest_layout` in +# `komorebic state`). A terminal's frame is checked loosely: it sizes itself to whole cells of its +# font, so it is a few pixels short of its tile. +import re +import time + +from komorebi_vm import Checks, Kde, Pointer, daemon + +# the module's unit, which the session starts when it logs in: the daemon the suite drags against +UNIT = "komorebi.service" + +# what an edge of a terminal's frame may be off by: up to a cell of its font +CELL = 24 +# how far from its frame a window's resize border is pressed: in the gap between two tiles +OFFSET = 4 +WINDOWS = 3 + +GRABS = { + "left": "L", + "right": "R", + "top": "T", + "bottom": "B", + "topleft": "LT", + "topright": "RT", + "bottomleft": "LB", + "bottomright": "RB", +} + +start_all() +machine.wait_for_unit("multi-user.target") + +checks = Checks() +kde = Kde.session(machine, scale=SCALE) + +# the session started the module's unit when it logged in +checks.check( + "komorebi answers", kde.wait_for(lambda: kde.run("komorebic state")[0] == 0, timeout=120) +) + +# The windows tiled before the daemon has the panel's room are put in the room that was there, and a +# case that begins then ends with every tile moved by the panel. The wait is not a check: a session +# may never take the room, and it ends after a while. +kde.wait_for_panel_room() + +size = kde.state()["monitors"]["elements"][0]["size"] +W, H = size["right"], size["bottom"] +pointer = Pointer.start(machine, (W, H), scale=SCALE) + + +def where() -> tuple[int, int]: + found = re.search(r"x:(-?\d+) y:(-?\d+)", kde.sh("kdotool getmouselocation")) + assert found, "kdotool says nowhere" + return int(found.group(1)), int(found.group(2)) + + +# the pointer goes where it is asked, to the pixel +worst = 0 +for x, y in [(1, 1), (W - 2, 1), (W // 3, H // 2), (W - 2, H - 2), (17, H - 2)]: + pointer.move(x, y) + kde.wait_for(lambda x=x, y=y: where() == (x, y), timeout=3) + gx, gy = where() + worst = max(worst, abs(gx - x), abs(gy - y)) +checks.check(f"the pointer is put within a pixel of where it is asked ({worst})", worst <= 1) + +for n in range(1, WINDOWS + 1): + kde.spawn(f"foot -T win{n} sleep 3000") + kde.wait_for(lambda n=n: kde.managed() == n, timeout=30) +checks.check(f"the {WINDOWS} windows are tiled", kde.managed() == WINDOWS) + +Box = tuple[int, int, int, int] + + +def frames() -> dict[str, Box]: + out = {} + for n in range(1, WINDOWS + 1): + r = kde.rect(kde.wid(f"win{n}")) + out[f"win{n}"] = (r.x, r.y, r.w, r.h) + return out + + +def tiles() -> dict[str, Box]: + """komorebi's layout: the tile it gave each window, by title""" + workspace = kde.state()["monitors"]["elements"][0]["workspaces"]["elements"][0] + out = {} + for i, container in enumerate(workspace["containers"]["elements"]): + windows = container["windows"] + title = windows["elements"][windows["focused"]]["details"]["title"] + tile = workspace["latest_layout"][i] + out[title] = (tile["left"], tile["top"], tile["right"], tile["bottom"]) + return out + + +def edges(r: Box) -> dict[str, int]: + x, y, w, h = r + return {"L": x, "T": y, "R": x + w, "B": y + h} + + +def settled() -> dict[str, Box]: + """The frames once they have stopped changing""" + last = frames() + deadline = time.monotonic() + 10 * SCALE + while time.monotonic() < deadline: + time.sleep(0.5) + now = frames() + if now == last: + return now + last = now + return last + + +def resize_ends() -> int: + """How many drags of an edge the daemon has handled the end of, by the unit's log""" + log = kde.run(f"journalctl --user -u {UNIT} --no-pager -o cat")[1] + return sum(1 for e in daemon.events(log) if e.kind == "ResizeEnd") + + +def press_point(grab: str, r: Box) -> tuple[int, int]: + x, y, w, h = r + left, right, top, bottom = x - OFFSET, x + w + OFFSET, y - OFFSET, y + h + OFFSET + cx, cy = x + w // 2, y + h // 2 + return { + "left": (left, cy), + "right": (right, cy), + "top": (cx, top), + "bottom": (cx, bottom), + "topleft": (left, top), + "topright": (right, top), + "bottomleft": (left, bottom), + "bottomright": (right, bottom), + }[grab] + + +def has_neighbor(edge: str, name: str, before: dict[str, Box]) -> bool: + """Is there another window within a gap's reach on that side of this one, overlapping it""" + mx, my, mw, mh = before[name] + for other, (ox, oy, ow, oh) in before.items(): + if other == name: + continue + vertical_overlap = oy < my + mh and my < oy + oh + horizontal_overlap = ox < mx + mw and mx < ox + ow + if edge == "L" and vertical_overlap and 0 <= mx - (ox + ow) <= 80: + return True + if edge == "R" and vertical_overlap and 0 <= ox - (mx + mw) <= 80: + return True + if edge == "T" and horizontal_overlap and 0 <= my - (oy + oh) <= 80: + return True + if edge == "B" and horizontal_overlap and 0 <= oy - (my + mh) <= 80: + return True + return False + + +def run_case(spec: str) -> list[str]: + name, grab, d = spec.split(":") + dx, dy = (int(v) for v in d.split(",")) + + kde.komorebic("retile") + before = settled() + tiles_before = tiles() + ends = resize_ends() + + px, py = press_point(grab, before[name]) + pointer.drag((px, py), (px + dx, py + dy)) + kde.wait_for(lambda: resize_ends() > ends, timeout=10) + after = settled() + tiles_after = tiles() + + held = GRABS[grab] + want = {"L": dx, "R": dx, "T": dy, "B": dy} + problems = [] + + # the frame the user sees: it did what was asked, give or take the client's cells + moved = {e: edges(after[name])[e] - edges(before[name])[e] for e in "LTRB"} + for e in "LTRB": + if e in held and has_neighbor(e, name, before): + if abs(moved[e] - want[e]) > CELL: + problems.append(f"frame {e} moved {moved[e]}, the pointer moved {want[e]}") + elif abs(moved[e]) > CELL: + why = "was not dragged" if e not in held else "has no neighbor" + problems.append(f"frame {e} moved {moved[e]} but {why}") + + # the layout, which is exact + tile_moved = {e: edges(tiles_after[name])[e] - edges(tiles_before[name])[e] for e in "LTRB"} + for e in "LTRB": + if e in held and has_neighbor(e, name, before): + if abs(tile_moved[e] - want[e]) > 2: + problems.append(f"tile {e} moved {tile_moved[e]}, the pointer moved {want[e]}") + elif abs(tile_moved[e]) > 1: + why = "was not dragged" if e not in held else "has no neighbor" + problems.append(f"tile {e} moved {tile_moved[e]} but {why}") + + # nothing else moves, but with a dragged edge: they share it + follows = [m for m in tile_moved.values() if abs(m) > 1] + for other in tiles_after: + if other == name: + continue + for e in "LTRB": + m = edges(tiles_after[other])[e] - edges(tiles_before[other])[e] + if abs(m) > 1 and not any(abs(m - f) <= 2 for f in follows): + problems.append(f"{other} tile {e} moved {m}: not with the dragged edge") + + # still a tiling + names = list(after) + for i, n1 in enumerate(names): + x, y, w, h = after[n1] + if x < 0 or y < 0 or x + w > W or y + h > H: + problems.append(f"{n1} {after[n1]} is off the screen") + for n2 in names[i + 1 :]: + ox, oy, ow, oh = after[n2] + if x < ox + ow and ox < x + w and y < oy + oh and oy < y + h: + problems.append(f"{n1} and {n2} overlap") + + print(f"{spec}: frame {before[name]} -> {after[name]}, tile edges {tile_moved}") + return problems + + +# BSP: win1 is the left half, win2 the top right and win3 the bottom right +cases = [ + "win1:right:72,0", + "win1:right:-72,0", + "win2:left:-72,0", + "win2:left:-240,0", + "win2:bottom:0,72", + "win3:top:0,-72", + "win2:bottomleft:-72,72", + "win1:left:-72,0", +] +for spec in cases: + problems = run_case(spec) + checks.check(f"{spec}: " + ("as expected" if not problems else "; ".join(problems)), not problems) + +checks.finish()