diff --git a/README.md b/README.md index 2bad97b2..797e46f1 100644 --- a/README.md +++ b/README.md @@ -172,8 +172,9 @@ 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, 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. +resizes it, as `resize-edge` does, with the tiles next to the edge following it +while it is dragged. 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 756da10c..21234acc 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -701,6 +701,23 @@ the window is in a container of a workspace that tiles, and the frame changed, t 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. +The neighbors follow the edge while it is dragged, and the animation effect, which does not +animate a resize by the user, leaves them to move at once. At every step of a resize KWin reports the +frame the pointer asks for (`interactiveMoveResizeStepped`); the bridge sends one step every 16 ms +at most, the newest, from a single-shot timer that sends the last one of a burst, and the table +makes the frame the window's and raises a `ResizeStep`. [`send_notification`] keeps at most one +`ResizeStep` waiting in the channel, and drops the others: the window manager reads where the +edge is when it gets to the step. `ResizeStart` keeps the workspace's +[`Workspace::resize_dimensions`] and [`Workspace::latest_layout`] as they are when the user takes +hold ([`LiveResize`], in [`WindowManager::live_resize`]), and puts the window in the list of +windows being resized ([`live_resize_begins`]), which [`Window::set_position`] leaves alone. A +step puts the kept layout back, applies the drag so far as `ResizeEnd` does, and tiles the +workspace; it makes no notification. `ResizeEnd` takes the window out of the list, puts the kept +layout back if a step moved the neighbors, and does the whole drag on it, so a drag ends the same +with steps as without, and one that is taken back puts the neighbors back. A window that opens or +closes part way through a drag changes the number of tiles: the kept layout is dropped, and the +steps after it change nothing until the end. + ## Configuration The daemon is configured by `komorebi.json`, which [`StaticConfig`] reads. `main.rs` takes the @@ -1170,6 +1187,9 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | 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 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 | +| The window whose edge is being dragged is not moved until it is let go | framework path: [`Window::set_position`] returns without a command for a window in the list [`live_resize_begins`] adds it to, whatever tiles the workspace | `the_neighbours_follow_a_drag_while_it_is_going_on_and_the_dragged_window_is_left_alone`, `a_window_opening_part_way_through_a_drag_does_not_break_it` | none | +| A drag ends the same with its steps as without them, and one taken back puts the neighbors back | framework path: every step and the end start from the layout kept at the start ([`LiveResize`]) | `a_drag_has_the_same_result_with_the_steps_as_without_them`, `a_drag_that_is_taken_back_puts_the_neighbours_where_they_were`, `vm-live-resize` | none | +| A step of a drag never waits behind another step | framework path: the bridge sends one every 16 ms at most, and [`send_notification`] keeps at most one waiting | `the steps of a resize are sent at most every 16 ms, and the last of a burst is not lost`, `a step waiting when the user lets go is not sent after the end` | none | | 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 | @@ -1408,7 +1428,9 @@ A window is shown, and ends up on a tile: 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; - [`komorebi/tests/drag_resize.rs`](../../komorebi/tests/drag_resize.rs), dragging an edge. + [`komorebi/tests/drag_resize.rs`](../../komorebi/tests/drag_resize.rs), dragging an edge; + [`komorebi/tests/live_resize.rs`](../../komorebi/tests/live_resize.rs), the neighbors following + it. - [`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 @@ -1416,7 +1438,9 @@ A window is shown, and ends up on a tile: - [`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. + corners dragged with a pointer in a Plasma session; + [`nix/tests/vm/suites/live-resize`](../../nix/tests/vm/suites/live-resize/test.py), the + neighbors read while the edge is held. - [`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, @@ -1601,6 +1625,10 @@ A window is shown, and ends up on a tile: [`Table::drag_origin`]: ../../komorebi/src/kwin/state.rs [`Table::drag_end`]: ../../komorebi/src/kwin/state.rs [`Backend::drag_end`]: ../../komorebi/src/backend/mod.rs +[`LiveResize`]: ../../komorebi/src/window_manager.rs +[`WindowManager::live_resize`]: ../../komorebi/src/window_manager.rs +[`live_resize_begins`]: ../../komorebi/src/window.rs +[`send_notification`]: ../../komorebi/src/window_manager_event_listener.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 c65bcb5c..b9c259ce 100644 --- a/docs/dev/DESIGN.md +++ b/docs/dev/DESIGN.md @@ -564,3 +564,26 @@ frame event KWin sends a millisecond after the end changes the frame in the tabl 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. + +## Why is every step of a drag worked out from where the drag began? + +A step says where the user has the edge now, so the drag so far is the distance from the start, +not something to add to the step before. Starting each step, and the end, from the layout as it +was when the user took hold makes the result of a drag the same with its steps as without them, +and a drag that ends where it began puts the neighbors back where they were. + +## Why is the window whose edge is being dragged not moved during the drag? + +It is the user's until they let go: KWin moves its edge with the pointer, and komorebi puts it on +its tile when the drag ends. A step tiles the workspace to move the neighbors, and so can anything +else that happens during the drag, such as a window that opens. The guard is in +`Window::set_position`, for the windows being resized, so that whatever tiles the workspace leaves +the dragged window alone. + +## Why are the steps of a drag thinned out? + +The pointer makes far more steps than anyone needs. The bridge sends one every 16 ms at most, the +newest, and a single-shot timer sends the last one of a burst, so the edge's final place is not +lost. Each step says where the edge is now, so one waiting in the window manager's channel is +enough: the window manager asks the window where its edges are when it gets to the step, and that +is the newest. diff --git a/docs/dev/PLATFORM.md b/docs/dev/PLATFORM.md index 3738d76f..29951f3a 100644 --- a/docs/dev/PLATFORM.md +++ b/docs/dev/PLATFORM.md @@ -418,8 +418,14 @@ the client's frames after the end of the drag: in a run of `vm-drag-resize` at t (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. +that frame, which the daemon keeps apart from the frames that follow. It also passes the steps on, +one every 16 ms at most, so that the tiles next to the edge follow it while it is dragged; the VM +test `vm-live-resize` reads them while the button is still down. KWin's window snapping applies to +the edge the user drags, and the tiles that follow it are close to it: at time of writing +(2026-10-27), in `vm-drag-resize` with the default paddings (a gap of 10 pixels between two tiles) +and KWin's default snap zone of 10 pixels, a dragged edge once ended 9 pixels past the pointer. The +drag VM tests set KWin's snap zones to 0. 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 diff --git a/docs/drag-resize.md b/docs/drag-resize.md index 7e0e2e4b..78160c76 100644 --- a/docs/drag-resize.md +++ b/docs/drag-resize.md @@ -1,10 +1,11 @@ # 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. +it, and let go. While the edge is dragged, the tiles next to it follow it. When it is let go, +komorebi 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 @@ -18,6 +19,12 @@ drag, the rules it keeps to, and why each of them is there. 4. The workspace is tiled again: the dragged window goes onto its tile, wherever the user left it, and so do its neighbors. +Between the start and the end, KWin reports every step of the drag with the frame the pointer +asks for, and the window manager does what it does at the end, from the same start, except that +it leaves the dragged window where the user has it: the neighbors follow the edge while it is +dragged. The animation effect ([Animation](usage/animation.md)) does not animate any window while +a user resize goes on, so the neighbors move at once. + ## The rules - **A drag is measured from where the window was when it began, not from its tile.** A window is @@ -50,6 +57,30 @@ drag, the rules it keeps to, and why each of them is there. follows a moment later. The end of a move is the frame, and so is the end of a resize that had no step. +## While the edge is dragged + +- **Every step is worked out from the start of the drag**, not from the step before. When the user + takes hold of the edge, the window manager keeps the sizes the tiles had been given and where + the layout put them, and each step, and the end, starts from those: the drag so far is the + distance from the start. So a drag has the same result with its steps as without them, and a + drag that is taken back, to where it began or with Escape, puts the neighbors back where they + were. +- **The dragged window is the user's until they let go.** komorebi does not move it while the edge + is dragged, also when something else tiles the workspace, such as a window that opens. +- **A window that opens or closes part way through a drag stops the neighbors following.** The + layout the drag began on is not the layout there is any more; the end of the drag still resizes + the tile, on the layout there is then. +- **Only the newest step counts.** The pointer makes far more steps than the neighbors can follow: + the bridge sends one every 16 ms at most, the newest, and sends the last one of a burst when the + 16 ms are over; the window manager keeps at most one step waiting, and reads where the edge is + when it gets to it. A step that is still waiting when the user lets go is not sent. +- **A move has no steps.** A window dragged by its title bar moves alone; the tiles change when it + is let go ([Moving windows](usage/moving-windows.md#by-dragging)). +- **KWin's snapping applies to the edge.** KWin snaps an edge the user drags to an edge of another + window within its snap zone, 10 pixels by default, and the tiles that follow the edge are about + that close to it with the default paddings, so the edge can end a few pixels past the pointer. A + window snap zone of 0, in KWin's window behavior settings, turns that off. + ## The layouts The layouts that move the edges are `komorebi-layouts` from @@ -81,3 +112,8 @@ of a column. 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. +- `komorebi/tests/live_resize.rs`, against the fake desktop: the neighbors follow a drag while it + goes on and the dragged window is left alone; the same result with steps as without; a drag + taken back; a step with no drag going on; a window that opens part way through. +- `vm-live-resize`, in the same session: the edge is held part way and then all the way, and the + neighbors' frames are read while the button is still down, and again after it is let go. diff --git a/docs/usage/resizing-windows.md b/docs/usage/resizing-windows.md index 5d6391d4..541570ed 100644 --- a/docs/usage/resizing-windows.md +++ b/docs/usage/resizing-windows.md @@ -45,12 +45,14 @@ the tile is smaller than that already: a resize that would is carried out as far 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. +take the room, and the window is put on its tile. The neighbors follow the edge while it is +dragged, and go back if it is dragged back to where it began, without the animation of +[`animation`](animation.md): the effect leaves a user's resize alone. 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 diff --git a/komorebi/src/kwin/bridge.js b/komorebi/src/kwin/bridge.js index 261e5396..abbce7f7 100644 --- a/komorebi/src/kwin/bridge.js +++ b/komorebi/src/kwin/bridge.js @@ -56,8 +56,9 @@ * `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 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. + * asked for (`requested`, or `null` when the drag asked for none); `move_resize_step` is the + * frame the user asks for part way through a resize, at most one every 16 ms; `cursor` answers a + * cursor query, and `failed` gives back the commands of a batch that could not be carried out. * * @typedef {{ * type: "snapshot", windows: WindowInfo[], screens: Screen[], desktops: Desktop[], @@ -78,11 +79,12 @@ * @typedef {{ * type: "move_resize_finished", id: string, geo: Rect, requested: Rect | null, cursor: Point * }} MoveResizeFinished + * @typedef {{ type: "move_resize_step", id: string, geo: Rect }} MoveResizeStep * @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 - * | DesktopList | CurrentDesktops | MoveResizeStarted | MoveResizeFinished | CursorAnswer - * | Failed} BridgeEvent + * | DesktopList | CurrentDesktops | MoveResizeStarted | MoveResizeFinished | MoveResizeStep + * | CursorAnswer | Failed} BridgeEvent */ /** @@ -345,6 +347,47 @@ function settle(w, id) { } } +// While the user resizes a window the daemon is told where they have the edges, so that the +// neighbors can follow live. The pointer makes far more steps than anyone needs: one every 16 ms +// at most, the newest one (a trailing timer sends the last of a burst). +var STEP_MS = 16; +var stepLast = 0; +/** @type {{ id: string, geo: Rect } | null} */ +var stepPending = null; +var stepTimer = new QTimer(); +stepTimer.singleShot = true; +stepTimer.interval = STEP_MS; +stepTimer.timeout.connect(function () { + if (stepPending) { + var p = stepPending; + stepPending = null; + stepLast = Date.now(); + emit("move_resize_step", p); + } +}); + +/** + * @param {string} id + * @param {QRectF} g + */ +function announceStep(id, g) { + var p = { id: id, geo: rect(g) }; + if (Date.now() - stepLast >= STEP_MS && !stepTimer.active) { + stepLast = Date.now(); + emit("move_resize_step", p); + } else { + stepPending = p; + if (!stepTimer.active) { + stepTimer.start(); + } + } +} + +function cancelStep() { + stepPending = null; + stepTimer.stop(); +} + // ---- hooks --------------------------------------------------------------------------------- /** @@ -376,6 +419,7 @@ function track(w, announce) { w.interactiveMoveResizeStarted.connect(function () { delete want[id]; delete stepped[id]; + cancelStep(); 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 @@ -383,8 +427,12 @@ function track(w, announce) { // short of where the pointer took the edge. w.interactiveMoveResizeStepped.connect(function (g) { stepped[id] = rect(g); + if (w.resize) { + announceStep(id, g); + } }); w.interactiveMoveResizeFinished.connect(function () { + cancelStep(); var requested = stepped[id] || null; delete stepped[id]; emit("move_resize_finished", { id: id, geo: rect(w.frameGeometry), requested: requested, cursor: cursor() }); diff --git a/komorebi/src/kwin/bridge.test.js b/komorebi/src/kwin/bridge.test.js index e0bb0fa0..80c0223f 100644 --- a/komorebi/src/kwin/bridge.test.js +++ b/komorebi/src/kwin/bridge.test.js @@ -201,14 +201,31 @@ function kwin({ class QTimer { constructor() { this.interval = 0; + this.singleShot = false; this.timeout = new Signal(); this.running = false; timers.push(this); } + get active() { + return this.running; + } + start() { this.running = true; } + + stop() { + this.running = false; + } + + // the timer's interval has passed + fire() { + if (this.singleShot) { + this.running = false; + } + this.timeout.emit(); + } } // a window KWin has: it can close @@ -266,6 +283,9 @@ function kwin({ desktops.push(desktop); workspace.desktopsChanged.emit(); }, + // the timer that calls `Poll` again, and the one that sends the last step of a resize + watchdog: () => timers.find((t) => t.interval === 1000), + stepTimer: () => timers.find((t) => t.singleShot), }; return k; } @@ -522,7 +542,7 @@ test("the bridge always has a Poll open: one when it starts, and another after e test("the watchdog calls Poll again when the last call is older than the hold and 3 seconds", () => { const k = kwin(); - const [watchdog] = k.timers; + const watchdog = k.watchdog(); assert.equal(watchdog.interval, 1000); assert.ok(watchdog.running); @@ -539,7 +559,7 @@ test("the answer to a Poll that the watchdog replaced is dropped", () => { const k = kwin(); const [stale] = k.polls(); k.clock.now += CFG.hold_ms + 3001; - k.timers[0].timeout.emit(); + k.watchdog().timeout.emit(); stale.callback(JSON.stringify([{ batch: 1, cmds: [{ op: "cursor", token: 1 }] }])); @@ -696,18 +716,70 @@ test("a drag is reported when the user takes hold of a window and when they let geo: { x: 0, y: 0, w: 960, h: 1050 }, seq: 2, }, - { type: "geometry", id: "{w}", geo: { x: 0, y: 0, w: 1000, h: 1050 }, seq: 3 }, + { type: "move_resize_step", id: "{w}", geo: { x: 0, y: 0, w: 1081, h: 1050 }, seq: 3 }, + { type: "geometry", id: "{w}", geo: { x: 0, y: 0, w: 1000, h: 1050 }, seq: 4 }, { type: "move_resize_finished", id: "{w}", geo: { x: 0, y: 0, w: 1000, h: 1050 }, requested: { x: 0, y: 0, w: 1081, h: 1050 }, cursor: { x: 1081, y: 501 }, - seq: 4, + seq: 5, }, ]); }); +test("the steps of a resize are sent at most every 16 ms, and the last of a burst is not lost", () => { + const w = window({ id: "{w}", resize: true }); + const k = kwin({ windows: [w] }); + w.interactiveMoveResizeStarted.emit(); + + w.interactiveMoveResizeStepped.emit(geometry(0, 0, 110, 100)); + w.interactiveMoveResizeStepped.emit(geometry(0, 0, 120, 100)); + w.interactiveMoveResizeStepped.emit(geometry(0, 0, 130, 100)); + assert.ok(k.stepTimer().active, "the burst waits for the timer"); + k.clock.now += 16; + k.stepTimer().fire(); + k.stepTimer().fire(); + + assert.deepStrictEqual( + k.events() + .filter((e) => e.type === "move_resize_step") + .map((e) => e.geo.w), + [110, 130], + ); +}); + +test("a step waiting when the user lets go is not sent after the end", () => { + const w = window({ id: "{w}", resize: true }); + const k = kwin({ windows: [w] }); + w.interactiveMoveResizeStarted.emit(); + w.interactiveMoveResizeStepped.emit(geometry(0, 0, 110, 100)); + w.interactiveMoveResizeStepped.emit(geometry(0, 0, 120, 100)); + + w.interactiveMoveResizeFinished.emit(); + k.stepTimer().fire(); + + assert.deepStrictEqual( + k.events().slice(1).map((e) => e.type), + ["move_resize_started", "move_resize_step", "move_resize_finished"], + ); + assert.deepStrictEqual(k.events().at(-1).requested, { x: 0, y: 0, w: 120, h: 100 }); +}); + +test("the steps of a move are not sent", () => { + const w = window({ id: "{w}", move: true }); + const k = kwin({ windows: [w] }); + w.interactiveMoveResizeStarted.emit(); + + w.interactiveMoveResizeStepped.emit(geometry(50, 0, 100, 100)); + + assert.deepStrictEqual( + k.events().slice(1).map((e) => e.type), + ["move_resize_started"], + ); +}); + test("a window the user has taken hold of is not asked again for the position komorebi gave it", () => { const w = window({ id: "{w}" }); const k = kwin({ windows: [w] }); diff --git a/komorebi/src/kwin/fixtures/events.json b/komorebi/src/kwin/fixtures/events.json index 581a14d0..ea52812f 100644 --- a/komorebi/src/kwin/fixtures/events.json +++ b/komorebi/src/kwin/fixtures/events.json @@ -99,11 +99,15 @@ "move": false, "resize": true, "geo": {"x": 40, "y": 30, "w": 960, "h": 1050} }, { - "type": "geometry", "seq": 25, "id": "{0e5a1c3b-0000-4000-8000-00000000000a}", + "type": "move_resize_step", "seq": 25, "id": "{0e5a1c3b-0000-4000-8000-00000000000a}", + "geo": {"x": 40, "y": 30, "w": 1100, "h": 1050} + }, + { + "type": "geometry", "seq": 26, "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}", + "type": "move_resize_finished", "seq": 27, "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 1d2da9b6..6f535d47 100644 --- a/komorebi/src/kwin/kwin-api.d.ts +++ b/komorebi/src/kwin/kwin-api.d.ts @@ -159,6 +159,11 @@ declare function print(...values: unknown[]): void; declare class QTimer { interval: number; + /** Whether the timer fires once per `start`, rather than every `interval`. */ + singleShot: boolean; + /** True from `start` until a single-shot timer fires or `stop` is called. */ + readonly active: boolean; readonly timeout: Signal; start(): void; + stop(): void; } diff --git a/komorebi/src/kwin/state.rs b/komorebi/src/kwin/state.rs index 44db841d..f0cce162 100644 --- a/komorebi/src/kwin/state.rs +++ b/komorebi/src/kwin/state.rs @@ -102,8 +102,8 @@ struct Entry { /// 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 + /// apart from `info.rect`, which the steps and 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 @@ -685,6 +685,9 @@ impl Table { /// 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. + /// - `move_resize_step`: part way through a resize, the frame the user is asking for (`geo`), + /// which becomes the window's frame and a [`WindowManagerEvent::ResizeStep`]. A step of a + /// move, or with no drag going on, is nothing. /// - `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 @@ -705,6 +708,7 @@ impl Table { Some("removed") => self.on_removed(event, now), Some("activated") => self.on_activated(event), Some("minimized") => self.on_minimized(event), + Some("move_resize_step") => self.on_drag_step(event), Some("caption") => self.on_caption(event), Some("geometry") => { if let Some(entry) = self.entry_mut(event) { @@ -1004,6 +1008,30 @@ impl Table { })] } + /// Part way through a drag: for a resize, where the user has the edges now. That is what the + /// window manager is told the window is until the drag is over; the frame follows when the client + /// has drawn at the new size, and is short of it. + fn on_drag_step(&mut self, event: &Value) -> Vec { + let Some(id) = self.id_of(event) else { + return vec![]; + }; + + let Some(entry) = self.windows.get_mut(&id) else { + return vec![]; + }; + + if entry.drag != Some(Drag::Resize) || !entry.info.normal || !event["geo"].is_object() { + return vec![]; + } + + entry.info.rect = rect(&event["geo"]); + + vec![Output::Event(WindowManagerEvent::ResizeStep( + kwin(KWinNotification::InteractiveResizeStepped), + Window::from(id), + ))] + } + fn on_drag_finished(&mut self, event: &Value) -> Vec { if let (Some(x), Some(y)) = (event["cursor"]["x"].as_i64(), event["cursor"]["y"].as_i64()) { self.cursor = Some((x as i32, y as i32)); @@ -1314,6 +1342,7 @@ mod tests { "geometry -> ", "move_resize_finished -> MoveEnd 1", "move_resize_started -> ResizeStart 1", + "move_resize_step -> ResizeStep 1", "geometry -> ", "move_resize_finished -> ResizeEnd 1", ] @@ -1683,6 +1712,58 @@ mod tests { assert_eq!((origin.left, origin.right), (10, 100), "{origin:?}"); } + #[test] + fn steps_are_events_with_where_the_user_has_the_edge_and_do_not_lose_where_the_drag_began() { + 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); + let step = t.handle( + &json!({ "type": "move_resize_step", "id": "a", "geo": {"x":10,"y":10,"w":130,"h":100} }), + now, + ); + + assert_eq!(events(&step), vec!["ResizeStep 1"]); + assert_eq!( + t.window(1).unwrap().rect.right, + 130, + "the window is where the user has it" + ); + let origin = t.drag_origin(1).unwrap(); + assert_eq!( + (origin.left, origin.right), + (10, 100), + "the drag began somewhere else: {origin:?}" + ); + } + + #[test] + fn steps_of_a_move_and_steps_with_no_drag_are_nothing() { + let mut t = table(vec![win("a", &["d1"])]); + let now = Instant::now(); + let geo = json!({"x":10,"y":10,"w":100,"h":100}); + + // no drag + assert!( + t.handle( + &json!({ "type": "move_resize_step", "id": "a", "geo": geo }), + now + ) + .is_empty() + ); + + // a move + t.handle(&json!({ "type": "move_resize_started", "id": "a", "move": true, "resize": false, "geo": geo }), now); + assert!( + t.handle( + &json!({ "type": "move_resize_step", "id": "a", "geo": geo }), + now + ) + .is_empty() + ); + } + #[test] fn a_move_is_where_the_frame_is() { let mut t = table(vec![win("a", &["d1"])]); diff --git a/komorebi/src/process_event.rs b/komorebi/src/process_event.rs index 24d17dac..bf694048 100644 --- a/komorebi/src/process_event.rs +++ b/komorebi/src/process_event.rs @@ -44,7 +44,9 @@ //! - **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. +//! ([`WindowManager::resize_window`]), and the workspace is tiled again. **ResizeStep**, part +//! way through, tiles the workspace as if the drag ended there, from the layout the drag began +//! on, and leaves the dragged window where the user has it. //! - **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 @@ -88,7 +90,10 @@ use crate::state::State; use crate::transparency_manager; use crate::window::RuleDebug; use crate::window::Window; +use crate::window::live_resize_begins; +use crate::window::live_resize_ends; use crate::window::should_act; +use crate::window_manager::LiveResize; use crate::window_manager::WindowManager; use crate::window_manager_event::KWinNotification; use crate::window_manager_event::SystemNotification; @@ -157,6 +162,12 @@ impl WindowManager { return Ok(()); } + // part way through a drag: only the neighbours move, there is no notification to make + if let WindowManagerEvent::ResizeStep(_, window) = event { + crate::window_manager_event_listener::resize_step_taken(); + return self.live_resize_step(window); + } + // a monitor changed which workspace it shows; nothing to do with any window if let WindowManagerEvent::WorkspaceChange(_, monitor_id, idx) = event { let result = self.adopt_workspace_change(monitor_id, idx); @@ -275,6 +286,8 @@ impl WindowManager { } // handled before the window is looked up WindowManagerEvent::WorkspaceChange(..) => {} + // handled before the window is looked up + WindowManagerEvent::ResizeStep(..) => {} WindowManagerEvent::WorkspaceMove(_, _, idx) => { // somebody put the window on another workspace's desktop: it belongs there now. // (komorebi's own moves come back here too, and find the window already there.) @@ -754,6 +767,25 @@ impl WindowManager { }; let pending_resize_op = Arc::make_mut(&mut self.pending_resize_op); *pending_resize_op = Option::from((window_id, Some(started_from))); + + // what the layout is as the user takes hold, for the steps of the drag to be + // worked out from, and for it to go back to if they take the drag back + self.live_resize = self.focused_workspace().ok().and_then(|workspace| { + workspace + .container_idx_for_window(window_id) + .filter(|_| workspace.tile) + .map(|_| LiveResize { + window: window_id, + containers: workspace.containers().len(), + resize_dimensions: workspace.resize_dimensions.clone(), + latest_layout: workspace.latest_layout.clone(), + stepped: false, + }) + }); + + if self.live_resize.is_some() { + live_resize_begins(window_id); + } } } WindowManagerEvent::ResizeEnd(_, window) => { @@ -763,6 +795,23 @@ impl WindowManager { let pending_resize_op = Arc::make_mut(&mut self.pending_resize_op); *pending_resize_op = None; + // the drag is over: the window is komorebi's to put in its tile again, and the + // layout is what it was when the drag began, to have the whole drag done on it + live_resize_ends(window_id); + let live = self + .live_resize + .take() + .filter(|live| live.window == window_id); + let stepped = live.as_ref().is_some_and(|live| live.stepped); + if let Some(live) = live + && let Ok(workspace) = self.focused_workspace_mut() + && live.stepped + && workspace.containers().len() == live.containers + { + workspace.resize_dimensions = live.resize_dimensions; + workspace.latest_layout = live.latest_layout; + } + 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. @@ -786,8 +835,9 @@ impl WindowManager { // 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 { + // screen has no neighbor to take room from); and the others back, if they + // were moved along with the drag and the drag was taken back + if resized && (new_position != started_from || stepped) { self.update_focused_workspace(false, false)?; } } @@ -898,4 +948,48 @@ impl WindowManager { Ok(true) } + + /// The user has the edge of a tile part way: the tiles next to it take the room, as they will + /// when it is let go. The dragged window is theirs until then (`window::live_resize_begins`). + fn live_resize_step(&mut self, window: Window) -> eyre::Result<()> { + let Some((wid, Some(started_from))) = *self.pending_resize_op else { + return Ok(()); + }; + let Some(live) = self.live_resize.clone().filter(|live| live.window == wid) else { + return Ok(()); + }; + if wid != window.id { + return Ok(()); + } + + let new_position = window.rect()?; + let offset = self.work_area_offset; + + // the drag so far, on the layout as it was when the drag began + { + let workspace = self.focused_workspace_mut()?; + + if workspace.containers().len() != live.containers { + // a window opened or closed: that layout is gone, and the drag goes on without + // being shown (what is asked of the layout when it ends is what counts) + self.live_resize = None; + return Ok(()); + } + + workspace.resize_dimensions = live.resize_dimensions; + workspace.latest_layout = live.latest_layout; + } + + if !self.apply_mouse_resize(window, started_from, new_position)? { + return Ok(()); + } + + if let Some(live) = self.live_resize.as_mut() { + live.stepped = true; + } + + self.focused_monitor_mut() + .ok_or_eyre("there is no monitor")? + .update_focused_workspace(offset) + } } diff --git a/komorebi/src/static_config.rs b/komorebi/src/static_config.rs index bd4c2213..79958ad6 100644 --- a/komorebi/src/static_config.rs +++ b/komorebi/src/static_config.rs @@ -1261,6 +1261,7 @@ impl StaticConfig { minimized_windows: HashMap::new(), pending_move_op: Arc::new(None), pending_resize_op: Arc::new(None), + live_resize: None, already_moved_window_handles: Default::default(), known_window_ids: HashMap::new(), }; diff --git a/komorebi/src/window.rs b/komorebi/src/window.rs index df144fa6..9dcda09e 100644 --- a/komorebi/src/window.rs +++ b/komorebi/src/window.rs @@ -13,6 +13,9 @@ //! [`Window::hide`] takes a window out of sight, which is what a stack does with every window but //! the one in front, and records it in [`struct@HIDDEN_WINDOWS`] so that the window manager does //! not mistake what the compositor reports about it for the user's doing. +//! +//! The windows the user is resizing with the pointer are recorded too +//! ([`live_resize_begins`]): [`Window::set_position`] does not move those until the user lets go. use crate::FLOATING_APPLICATIONS; use crate::FLOATING_WINDOW_TOGGLE_ASPECT_RATIO; @@ -43,6 +46,28 @@ use std::path::PathBuf; use strum::Display; use strum::EnumString; +/// The windows the user is resizing by dragging an edge of: komorebi does not move them while they +/// are (the other tiles follow the drag, and the window is put in its tile when they let go) +static LIVE_RESIZED_WINDOWS: parking_lot::Mutex> = parking_lot::Mutex::new(Vec::new()); + +/// Records that the user has taken hold of an edge of this window: [`Window::set_position`] leaves +/// it alone until [`live_resize_ends`] +pub fn live_resize_begins(id: u32) { + let mut windows = LIVE_RESIZED_WINDOWS.lock(); + if !windows.contains(&id) { + windows.push(id); + } +} + +/// Records that the user has let go of the edge of this window they were dragging +pub fn live_resize_ends(id: u32) { + LIVE_RESIZED_WINDOWS.lock().retain(|w| *w != id); +} + +fn is_live_resized(id: u32) -> bool { + LIVE_RESIZED_WINDOWS.lock().contains(&id) +} + /// A handle to a window on the desktop: just its id. /// /// It is `Copy`, events carry it by value, and everything else (title, class, geometry, ...) is @@ -191,7 +216,15 @@ impl Window { /// Asks the compositor to move and resize the window to `rect`; where the window ends up is /// [`Window::rect`], since a client may refuse a size + /// + /// A window whose edge the user is dragging ([`live_resize_begins`]) is not moved: it is the + /// user's until they let go. pub fn set_position(self, rect: &Rect) -> eyre::Result<()> { + // the window the user is dragging an edge of is theirs until they let go + if is_live_resized(self.id) { + return Ok(()); + } + backend().set_rect(self.id, rect) } diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index 53b3e67b..6683e85b 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -105,6 +105,25 @@ use std::sync::Arc; /// A tile cannot be resized to less than this fraction of the work area (or less than it already is) const MINIMUM_TILE_FRACTION: i32 = 10; +/// What the focused workspace's layout was when a drag of one of its edges began: the sizes the +/// tiles had been given by hand, and where the layout put them. Every step of the drag is worked +/// out from that, not from the step before (the drag so far is the sum of its steps), and the end +/// of the drag, or a drag that is taken back, starts from it too. +#[derive(Debug, Clone)] +pub struct LiveResize { + /// The window whose edge is being dragged + pub window: u32, + /// how many tiles there were: when a window opens or closes part way through a drag, the + /// layout it was taken from is not the layout there is + pub containers: usize, + /// The workspace's [`Workspace::resize_dimensions`] when the drag began + pub resize_dimensions: Vec>, + /// The workspace's [`Workspace::latest_layout`] when the drag began + pub latest_layout: Vec, + /// whether the neighbours were moved while the drag was going on + pub stepped: bool, +} + #[derive(Debug)] pub struct WindowManager { pub monitors: Ring, @@ -156,6 +175,8 @@ pub struct WindowManager { /// 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)>>, + /// While the user drags an edge: what the layout was when they took hold of it + pub live_resize: Option, /// 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>>, @@ -248,6 +269,7 @@ impl WindowManager { minimized_windows: HashMap::new(), pending_move_op: Arc::new(None), pending_resize_op: Arc::new(None), + live_resize: 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 c2eab626..12de9a8e 100644 --- a/komorebi/src/window_manager_event.rs +++ b/komorebi/src/window_manager_event.rs @@ -51,6 +51,8 @@ pub enum KWinNotification { InteractiveResizeStarted, /// `window.interactiveMoveResizeFinished` after a resize InteractiveResizeFinished, + /// `window.interactiveMoveResizeStepped` of a resize: where the user has the edges now + InteractiveResizeStepped, } /// Events komorebi raises itself, for example from a command @@ -87,6 +89,10 @@ pub enum WindowManagerEvent { /// 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), + /// The user is part way through resizing a window: where they have its edges now is what the + /// window reports (`Window::rect`). Only the newest of these is ever waiting + /// (`window_manager_event_listener`), and they make no notification. + ResizeStep(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), @@ -111,6 +117,7 @@ impl WindowManagerEvent { | WindowManagerEvent::MoveEnd(_, window) | WindowManagerEvent::ResizeStart(_, window) | WindowManagerEvent::ResizeEnd(_, window) + | WindowManagerEvent::ResizeStep(_, window) | WindowManagerEvent::WorkspaceMove(_, window, _) => *window, WindowManagerEvent::WorkspaceChange(..) => return None, }) @@ -137,6 +144,7 @@ impl WindowManagerEvent { | WindowManagerEvent::MoveEnd(n, _) | WindowManagerEvent::ResizeStart(n, _) | WindowManagerEvent::ResizeEnd(n, _) + | WindowManagerEvent::ResizeStep(n, _) | WindowManagerEvent::WorkspaceChange(n, _, _) | WindowManagerEvent::WorkspaceMove(n, _, _) => match n { SystemNotification::KWin(k) => k.to_string(), diff --git a/komorebi/src/window_manager_event_listener.rs b/komorebi/src/window_manager_event_listener.rs index d72f9530..2ab31a75 100644 --- a/komorebi/src/window_manager_event_listener.rs +++ b/komorebi/src/window_manager_event_listener.rs @@ -4,12 +4,16 @@ //! [`send_notification`]. The window manager takes them, one at a time and in order, on the thread //! [`listen_for_events`](crate::process_event::listen_for_events) starts, from the receiver it was //! made with ([`event_rx`]). The channel is bounded: an event that does not fit is dropped and -//! logged, so a backend never waits for the window manager. +//! logged, so a backend never waits for the window manager. At most one step of a drag +//! ([`WindowManagerEvent::ResizeStep`]) waits at a time, and the window manager says when it has +//! taken it ([`resize_step_taken`]). use crate::window_manager_event::WindowManagerEvent; use crossbeam_channel::Receiver; use crossbeam_channel::Sender; use std::sync::OnceLock; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; static CHANNEL: OnceLock<(Sender, Receiver)> = OnceLock::new(); @@ -27,9 +31,31 @@ pub fn event_rx() -> Receiver { channel().1.clone() } +/// Whether a `ResizeStep` is already waiting in the channel. A drag makes them as fast as the pointer +/// moves, and each says where the pointer is now, so one waiting is enough: the window manager asks +/// the window where its edges are when it gets to it, and that is the newest. +static RESIZE_STEP_WAITING: AtomicBool = AtomicBool::new(false); + +/// Says that the window manager has taken the `ResizeStep` that was waiting, so that the next one +/// may be queued. +pub fn resize_step_taken() { + RESIZE_STEP_WAITING.store(false, Ordering::SeqCst); +} + /// Queues an event for the window manager, or drops it with a warning if 20 are already waiting. +/// +/// A [`WindowManagerEvent::ResizeStep`] is dropped without a word while another one is waiting. pub fn send_notification(notification: WindowManagerEvent) { + let is_step = matches!(notification, WindowManagerEvent::ResizeStep(..)); + + if is_step && RESIZE_STEP_WAITING.swap(true, Ordering::SeqCst) { + return; + } + if event_tx().try_send(notification).is_err() { + if is_step { + RESIZE_STEP_WAITING.store(false, Ordering::SeqCst); + } tracing::warn!("channel is full; dropping notification") } } diff --git a/komorebi/tests/live_resize.rs b/komorebi/tests/live_resize.rs new file mode 100644 index 00000000..960de583 --- /dev/null +++ b/komorebi/tests/live_resize.rs @@ -0,0 +1,270 @@ +//! The tiles next to an edge follow it while it is being dragged, against an in-memory desktop. +//! +//! 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 21_000s to the 25_000s. + +use komorebi::backend::fake::Command; +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 resize_started(id: u32) -> WindowManagerEvent { + WindowManagerEvent::ResizeStart( + SystemNotification::KWin(KWinNotification::InteractiveResizeStarted), + Window::from(id), + ) +} + +fn resize_stepped(id: u32) -> WindowManagerEvent { + WindowManagerEvent::ResizeStep( + SystemNotification::KWin(KWinNotification::InteractiveResizeStepped), + 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) +} + +/// 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"); + } + } +} + +/// the user has taken hold of an edge and has it at `to`, part way through the drag +fn step(fake: &Arc, wm: &mut WindowManager, id: u32, to: Rect) { + with_backend(fake.clone(), || { + fake.move_window_by_user(id, to); + wm.process_event(resize_stepped(id)).unwrap(); + }); +} + +#[test] +fn the_neighbours_follow_a_drag_while_it_is_going_on_and_the_dragged_window_is_left_alone() { + let (fake, mut wm) = tiled(DefaultLayout::BSP, 21_001, 2); + let (left, right) = (fake.rect_of(21_001).unwrap(), fake.rect_of(21_002).unwrap()); + + // the right-hand window's left edge is taken, and pulled out to the left + with_backend(fake.clone(), || { + wm.process_event(resize_started(21_002)).unwrap() + }); + fake.clear_commands(); + + step(&fake, &mut wm, 21_002, grown_left(right, 60)); + let after_60 = fake.rect_of(21_001).unwrap(); + assert!( + after_60.right < left.right, + "the left neighbour did not give way part way through: {left:?} -> {after_60:?}" + ); + + step(&fake, &mut wm, 21_002, grown_left(right, 120)); + let after_120 = fake.rect_of(21_001).unwrap(); + assert!( + after_120.right < after_60.right, + "and gave way more as the drag went on: {after_60:?} -> {after_120:?}" + ); + + // the dragged window is the user's until they let go + assert!( + !fake + .commands() + .iter() + .any(|c| matches!(c, Command::SetRect(21_002, _))), + "the dragged window was moved: {:?}", + fake.commands() + ); + assert_eq!(fake.rect_of(21_002).unwrap(), grown_left(right, 120)); + + // let go + with_backend(fake.clone(), || { + wm.process_event(resize_finished(21_002)).unwrap() + }); + assert_eq!( + fake.rect_of(21_001).unwrap(), + after_120, + "the end of the drag moved the neighbour to a place other than the one it followed to" + ); + assert_tiling(&fake, &[21_001, 21_002]); +} + +#[test] +fn a_drag_has_the_same_result_with_the_steps_as_without_them() { + let ids = [22_001, 22_002, 22_003]; + let to = |fake: &FakeBackend| grown_left(fake.rect_of(22_002).unwrap(), 90); + + // all at once + let (control, mut control_wm) = tiled(DefaultLayout::BSP, 22_001, 3); + let target = to(&control); + drag(&control, &mut control_wm, 22_002, target); + + // step by step + let (fake, mut wm) = tiled(DefaultLayout::BSP, 22_001, 3); + let from = fake.rect_of(22_002).unwrap(); + with_backend(fake.clone(), || { + wm.process_event(resize_started(22_002)).unwrap() + }); + for by in [15, 40, 75, 90] { + step(&fake, &mut wm, 22_002, grown_left(from, by)); + } + with_backend(fake.clone(), || { + wm.process_event(resize_finished(22_002)).unwrap() + }); + + for id in ids { + assert_eq!( + fake.rect_of(id), + control.rect_of(id), + "window {id} is not where a drag without steps puts it" + ); + } +} + +#[test] +fn a_drag_that_is_taken_back_puts_the_neighbours_where_they_were() { + let (fake, mut wm) = tiled(DefaultLayout::BSP, 23_001, 3); + let before: Vec = (23_001..23_004) + .map(|id| fake.rect_of(id).unwrap()) + .collect(); + let tile = fake.rect_of(23_002).unwrap(); + + with_backend(fake.clone(), || { + wm.process_event(resize_started(23_002)).unwrap() + }); + step(&fake, &mut wm, 23_002, grown_left(tile, 100)); + assert_ne!(fake.rect_of(23_001).unwrap(), before[0], "nothing followed"); + + // back to where it began (the user pressed Escape, or dragged the edge back) + fake.move_window_by_user(23_002, tile); + with_backend(fake.clone(), || { + wm.process_event(resize_finished(23_002)).unwrap() + }); + + let after: Vec = (23_001..23_004) + .map(|id| fake.rect_of(id).unwrap()) + .collect(); + assert_eq!(before, after, "the tiles are not where they were"); +} + +#[test] +fn a_step_with_no_drag_going_on_does_nothing() { + let (fake, mut wm) = tiled(DefaultLayout::BSP, 24_001, 2); + let before: Vec = (24_001..24_003) + .map(|id| fake.rect_of(id).unwrap()) + .collect(); + fake.clear_commands(); + + with_backend(fake.clone(), || { + wm.process_event(resize_stepped(24_002)).unwrap() + }); + + assert!(fake.commands().is_empty(), "{:?}", fake.commands()); + let after: Vec = (24_001..24_003) + .map(|id| fake.rect_of(id).unwrap()) + .collect(); + assert_eq!(before, after); +} + +#[test] +fn a_window_opening_part_way_through_a_drag_does_not_break_it() { + let (fake, mut wm) = tiled(DefaultLayout::BSP, 25_001, 3); + let tile = fake.rect_of(25_002).unwrap(); + + with_backend(fake.clone(), || { + wm.process_event(resize_started(25_002)).unwrap() + }); + step(&fake, &mut wm, 25_002, grown_left(tile, 50)); + + // another window opens: the layout the drag began on is not the layout there is + fake.open_window(25_004, "foot", "foot", "late"); + with_backend(fake.clone(), || wm.process_event(added(25_004)).unwrap()); + step(&fake, &mut wm, 25_002, grown_left(tile, 90)); + + with_backend(fake.clone(), || { + wm.process_event(resize_finished(25_002)).unwrap() + }); + + assert_tiling(&fake, &[25_001, 25_002, 25_003, 25_004]); +} diff --git a/nix/tests/vm/suites/drag-resize/test.py b/nix/tests/vm/suites/drag-resize/test.py index bd633b0a..40aac744 100644 --- a/nix/tests/vm/suites/drag-resize/test.py +++ b/nix/tests/vm/suites/drag-resize/test.py @@ -45,6 +45,13 @@ machine.wait_for_unit("multi-user.target") checks = Checks() kde = Kde.session(machine, scale=SCALE) +# KWin snaps an edge the user drags to an edge of another window within its snap zone, 10 pixels +# by default, and the neighbors that follow a drag are about that far from the edge: it would end +# up a few pixels past the pointer. The test measures komorebi, so KWin snaps nothing. +for zone in ("BorderSnapZone", "WindowSnapZone", "CenterSnapZone"): + kde.sh(f"kwriteconfig6 --file kwinrc --group Windows --key {zone} 0") +kde.sh("busctl --user call org.kde.KWin /KWin org.kde.KWin reconfigure") + # 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) diff --git a/nix/tests/vm/suites/live-resize/default.nix b/nix/tests/vm/suites/live-resize/default.nix new file mode 100644 index 00000000..66c2aff7 --- /dev/null +++ b/nix/tests/vm/suites/live-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/live-resize/test.py b/nix/tests/vm/suites/live-resize/test.py new file mode 100644 index 00000000..eabac134 --- /dev/null +++ b/nix/tests/vm/suites/live-resize/test.py @@ -0,0 +1,219 @@ +# The tiles next to an edge follow it while it is dragged, not only when it is let go, in a Plasma +# session with a pointer device the test drives from inside the guest (`komorebi_vm.Pointer`). For +# each case the button is pressed on an edge of a window, the pointer is taken part of the way and +# held there, and the frames of every window are read while the button is still down; then the +# rest of the way, read again, and let go (`komorebi/tests/live_resize.rs` checks the window +# manager's side against the fake). What only a real KWin can tell is that the bridge sends the +# steps of a drag and that the neighbors are moved while KWin has the dragged window: +# +# * part way and all the way, the neighbor's facing edge has moved with the pointer, give or take +# a cell of the terminal's font +# * the windows that are not next to the dragged edge have not moved +# * when the button is let go nothing jumps: the neighbors stay where they followed to +# * the windows still 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 + +OPPOSITE = {"L": "R", "R": "L", "T": "B", "B": "T"} +HELD = {"left": "L", "right": "R", "top": "T", "bottom": "B"} + +start_all() +machine.wait_for_unit("multi-user.target") + +checks = Checks() +kde = Kde.session(machine, scale=SCALE) + +# KWin snaps an edge the user drags to an edge of another window within its snap zone, 10 pixels +# by default, and the neighbors that follow a drag are about that far from the edge: it would end +# up a few pixels past the pointer. The test measures komorebi, so KWin snaps nothing. +for zone in ("BorderSnapZone", "WindowSnapZone", "CenterSnapZone"): + kde.sh(f"kwriteconfig6 --file kwinrc --group Windows --key {zone} 0") +kde.sh("busctl --user call org.kde.KWin /KWin org.kde.KWin reconfigure") + +# 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 shell makes its panel, and KWin takes room for it a while later, which the daemon learns of +# up to a second after that and tiles the windows again. A case that begins then ends with every +# tile moved by the panel, so the windows are opened after it (`Kde.wait_for_panel_room`). +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) + +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 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 + cx, cy = x + w // 2, y + h // 2 + return { + "left": (x - OFFSET, cy), + "right": (x + w + OFFSET, cy), + "top": (cx, y - OFFSET), + "bottom": (cx, y + h + OFFSET), + }[grab] + + +def neighbors(edge: str, name: str, before: dict[str, Box]) -> list[str]: + """The windows within a gap's reach on that side of this one, overlapping it""" + mx, my, mw, mh = before[name] + found = [] + for other, (ox, oy, ow, oh) in before.items(): + if other == name: + continue + v = oy < my + mh and my < oy + oh + h = ox < mx + mw and mx < ox + ow + if ( + (edge == "L" and v and 0 <= mx - (ox + ow) <= 80) + or (edge == "R" and v and 0 <= ox - (mx + mw) <= 80) + or (edge == "T" and h and 0 <= my - (oy + oh) <= 80) + or (edge == "B" and h and 0 <= oy - (my + mh) <= 80) + ): + found.append(other) + return found + + +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)) + + +def run_case(case: str) -> list[str]: + name, grab, d = case.split(":") + dx, dy = (int(v) for v in d.split(",")) + held = HELD[grab] + want = dx if held in "LR" else dy + + kde.komorebic("retile") + before = settled() + near = neighbors(held, name, before) + if not near: + return [f"{name} has nothing next to its {grab} edge"] + ends = resize_ends() + + px, py = press_point(grab, before[name]) + pointer.move(px, py) + pointer.down() + + problems = [] + held_at: dict[str, dict[str, Box]] = {} + for label, fraction in (("part way", 0.5), ("all the way", 1.0)): + pointer.glide(px + round(dx * fraction), py + round(dy * fraction), steps=12, ms=30) + expect = want * fraction + + def moved(now: dict[str, Box], n: str) -> int: + return edges(now[n])[OPPOSITE[held]] - edges(before[n])[OPPOSITE[held]] + + # the pointer is held there; the neighbors follow + kde.wait_for( + lambda expect=expect: all(abs(moved(frames(), n) - expect) <= CELL for n in near), + timeout=5, + ) + now = frames() + held_at[label] = now + print(f"{case} {label}: the pointer is at {where()}, the frames {now}") + + for n in near: + if abs(moved(now, n) - expect) > CELL: + problems.append( + f"{label}: {n}'s {OPPOSITE[held]} edge is {moved(now, n)} from where it was," + f" the pointer {expect:.0f}" + ) + for other, r in before.items(): + if other == name or other in near: + continue + if any(abs(edges(now[other])[e] - edges(r)[e]) > CELL for e in "LTRB"): + # a tile that shares the dragged edge's line may move with it; nothing else may + shared = any(abs(edges(r)[e] - edges(before[name])[held]) <= 80 for e in "LTRB") + if not shared: + problems.append(f"{label}: {other} moved, and it is not next to the edge") + + pointer.up() + kde.wait_for(lambda: resize_ends() > ends, timeout=10) + after = settled() + + for n in near: + jump = edges(after[n])[OPPOSITE[held]] - edges(held_at["all the way"][n])[OPPOSITE[held]] + if abs(jump) > CELL: + problems.append(f"{n} jumped {jump} when the button was let go") + + 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"{case}: neighbors {near}, before {before}, let go {after}") + return problems + + +# BSP: win1 is the left half, win2 the top right and win3 the bottom right +cases = [ + "win2:left:-120,0", + "win2:left:90,0", + "win2:bottom:0,100", + "win3:top:0,-80", + "win1:right:100,0", +] +for case in cases: + problems = run_case(case) + checks.check(f"{case}: " + ("as expected" if not problems else "; ".join(problems)), not problems) + +checks.finish()