From f5933d1ff8f934234dcdf24168dacbe1d01963bc Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 17:23:18 -0700 Subject: [PATCH] feat(wm): drag to swap A window the user drags with the pointer onto the tile of another window swaps places with it, and a window let go where there is no tile goes back to its own. It is the first thing komorebi does about what the user does with the pointer. KWin reports the start and the end of a drag on the window (interactiveMoveResizeStarted and Finished). The bridge sends both with the window's frame, and the end with the position of the pointer: the window manager asks where the pointer is right after a drag, and when the bridge does not answer that in time, the table's last position is the one the drag ended at. The table turns a move into MoveStart and MoveEnd; a resize raises nothing yet. The bridge also stops asking KWin again for the position komorebi gave the window, which is the user's now. Where the window is let go decides the rest. On another monitor it goes there, with its stack, in the place of the container under the pointer. With the window container behavior Append it joins the container under the pointer instead of swapping with it, and with the float override on it floats where it was let go. A terminal that keeps its frame a few pixels short of its tile is not taken for a move on its own monitor, as in the spike; the usage page says so. --- README.md | 5 +- docs/dev/ARCHITECTURE.md | 55 ++- docs/dev/DESIGN.md | 10 + docs/dev/PLATFORM.md | 10 +- docs/index.md | 2 +- docs/usage/moving-windows.md | 37 +- komorebi/src/kwin/bridge.js | 19 +- komorebi/src/kwin/bridge.test.js | 61 ++- komorebi/src/kwin/fixtures/events.json | 14 +- komorebi/src/kwin/kwin-api.d.ts | 5 + komorebi/src/kwin/mod.rs | 2 +- komorebi/src/kwin/state.rs | 131 ++++++- komorebi/src/process_event.rs | 231 +++++++++++ komorebi/src/static_config.rs | 1 + komorebi/src/window_manager.rs | 4 + komorebi/src/window_manager_event.rs | 13 + komorebi/src/workspace.rs | 20 + komorebi/tests/drag_swap.rs | 517 +++++++++++++++++++++++++ 18 files changed, 1111 insertions(+), 26 deletions(-) create mode 100644 komorebi/tests/drag_swap.rs diff --git a/README.md b/README.md index ffa7aaea..bfd4c761 100644 --- a/README.md +++ b/README.md @@ -170,8 +170,9 @@ area, and every window of a container is moved onto its tile. At startup the 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 open at startup goes to the -workspace whose desktop it is on. +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. 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 2869dc27..a607c54b 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -9,9 +9,10 @@ This page describes that trait, who implements and calls it, where each of its r enforced, the model of the desktop the window manager tiles, the backend that reaches KWin, how an event about a window becomes a tile, how workspaces are the compositor's desktops, how a stack hides its windows, how a message on the daemon's socket is answered, how subscribers -are notified of both, what the orders a message gives do, how the compositor is asked to draw the -borders, how `komorebi.json` configures the daemon, and how the NixOS module runs the daemon. It -grows with the code: each part of the daemon that is added has its place here. +are notified of both, what the orders a message gives do, what a drag with the pointer does, how +the compositor is asked to draw the borders, how `komorebi.json` configures the daemon, and how +the NixOS module runs the daemon. It grows with the code: each part of the daemon that is added +has its place here. ## Vocabulary @@ -48,9 +49,9 @@ grows with the code: each part of the daemon that is added has its place here. container, so it has left the layout, until it is put back in a container of its own where it was ([`Workspace::maximized_window`]). - **Event**: what the compositor reports about a window: it was shown, destroyed, given - the focus, minimized or restored, or put on another workspace's desktop; and that a monitor - shows another workspace ([`WindowManagerEvent`]). Two events come from komorebi itself: a - command asks it to manage the focused window, or to stop managing it. + the focus, minimized or restored, dragged by the user, or put on another workspace's desktop; + and that a monitor shows another workspace ([`WindowManagerEvent`]). Two events come from + komorebi itself: a command asks it to manage the focused window, or to stop managing it. - **Message**: what a client sends the daemon on its socket, a [`SocketMessage`]: an order (focus a window, move it, change the layout, resize it, show a workspace, retile, stop) or a question (the state, the monitors, one [`StateQuery`]). @@ -652,6 +653,35 @@ gives a tile, and [`Workspace::new_container_for_window`] puts the next window i `CancelPreselect` removes it. A workspace reserves one place at a time, and the grid layout 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. + +`MoveStart` records the monitor, the workspace and the window +([`WindowManager::pending_move_op`]). `MoveEnd` takes the record, and when it names the same +window, looks at the monitor under the pointer. On another monitor than the one the move began +on, the window's container goes there and takes the place of the container whose tile the +pointer is on ([`WindowManager::transfer_window`]); a floating window joins the floating +windows there, a monocle container is put back among the containers first, and a maximized +window stays where it is. Both monitors are tiled again. + +On the same monitor, `MoveEnd` compares the frame of the focused container's window with the +tile the layout last gave it ([`Workspace::latest_layout`]). A frame as wide and as tall as its +tile makes the drag a move. With the float override on, the window is then made a floating one +where it was let go. Otherwise the container under the pointer +([`Workspace::container_idx_from_current_point`], through the backend's `cursor_pos`) is the +target: the focused container swaps with it, or, with the window container behavior `Append`, +the window joins it ([`Workspace::move_window_to_container`]). The workspace is tiled again, +which puts a window let go where there is no tile back on its own. A frame of another size +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. + ## Configuration The daemon is configured by `komorebi.json`, which [`StaticConfig`] reads. `main.rs` takes the @@ -1112,6 +1142,11 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | A daemon that is told to stop leaves no socket behind | framework path: [`WindowManager::stop`] removes it before it exits | `the_daemon_answers_on_its_socket_and_stops_when_it_is_told_to` | `SIGKILL` | | A container moved onto a locked index is locked in its place, and the lock leaves the container that moved away | framework path: [`Workspace::swap_containers`] swaps through `LockableSequence`, which keeps the lock with the index | `test_swap_respecting_locks_various_cases`, `a_lock_stays_with_its_index_when_a_window_is_moved_onto_it` | `containers_mut()` is the `VecDeque` itself | | A window komorebi puts off the screen stays there | framework path: the bridge asks again for the position of a window KWin pulled back after a `geo` command, for a second, three times at most | `a window KWin pulls back from where it was asked to be is asked for the position again`, `a window that cannot go where it was asked is asked again three times at most`, `vm-scrolling` | a window that cannot go where it was asked is left where KWin put it | +| A window dragged onto the tile of another swaps places with it, and a window let go of elsewhere goes back to its tile | framework path: `handle_event`'s `MoveEnd` swaps the focused container with the one under the pointer through [`Workspace::swap_containers`], and tiles the workspace again | `dragging_a_window_onto_another_swaps_them`, `a_window_let_go_of_where_there_is_no_tile_goes_back_to_its_own` | a frame that is not as wide and as tall as its tile is not taken for a move, and stays where it was let go | +| A floating window dragged onto a tile takes nothing from it | framework path: `MoveEnd` acts only on a window that is in a container ([`Workspace::contains_managed_window`]) | `a_floating_window_dragged_onto_a_tile_takes_nothing_from_it` | none | +| 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 | | 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 | @@ -1345,7 +1380,9 @@ A window is shown, and ends up on a tile: [`komorebi/tests/padding.rs`](../../komorebi/tests/padding.rs), the paddings and the work area offsets; [`komorebi/tests/rules.rs`](../../komorebi/tests/rules.rs) and [`komorebi/tests/rule_commands.rs`](../../komorebi/tests/rule_commands.rs), the rules and the - messages that add and show them. + 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. - [`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 @@ -1527,6 +1564,10 @@ A window is shown, and ends up on a tile: [`Workspace::promotion_swap_container_idx`]: ../../komorebi/src/workspace.rs [`WindowManager::resize_delta`]: ../../komorebi/src/window_manager.rs [`Workspace::latest_layout`]: ../../komorebi/src/workspace.rs +[`Workspace::container_idx_from_current_point`]: ../../komorebi/src/workspace.rs +[`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 [`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 06ccc62c..1a1f4589 100644 --- a/docs/dev/DESIGN.md +++ b/docs/dev/DESIGN.md @@ -532,3 +532,13 @@ working without komorebi, with the settings the stock effect has: The patches are derivative works of the effects and are under the effects' license, the GNU General Public License version 3 ([PLATFORM.md](PLATFORM.md#the-patches)). + +## Why does the end of a drag carry the position of the pointer? + +A window dragged onto another tile swaps places with the window there, and one dragged onto +another monitor goes to that monitor. The window manager finds the tile and the monitor by +asking the backend where the pointer is. Only the bridge can read the pointer, so the KWin +backend asks it through the held call, and returns the last position the table has when no +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. diff --git a/docs/dev/PLATFORM.md b/docs/dev/PLATFORM.md index 8709ef5f..cc227fd1 100644 --- a/docs/dev/PLATFORM.md +++ b/docs/dev/PLATFORM.md @@ -123,8 +123,9 @@ It connects to the session bus as `org.komorebi.Bridge`, writes the bridge to `$XDG_RUNTIME_DIR/komorebi/bridge.js`, and asks KWin to load it under the name `komorebi-bridge`, replacing a script of that name left by an earlier run. The script reports the windows and outputs it finds, and from then on every window that opens, closes, takes the -focus, is minimized or brought back, moves or changes size. The daemon waits up to 10 seconds -for the first report and does not start without it. +focus, is minimized or brought back, moves or changes size, and the start and the end of every +drag of a window by the user. The daemon waits up to 10 seconds for the first report and does +not start without it. Before it loads the script, it turns on KWin's per-output virtual desktops in the user's `kwinrc` (`[Windows] PerOutputVirtualDesktops=true`), unless they are on, and asks KWin to @@ -368,6 +369,11 @@ TypeScript are needed only for those checks: in the session the bridge needs KWi - A script's `print()` goes to KWin's log, which shows it only when the `kwin_scripting` logging category is enabled (`QT_LOGGING_RULES="kwin_scripting.debug=true"`, as the VM tests do). +- A drag of a window by the user is `interactiveMoveResizeStarted` on the window, then a + `frameGeometryChanged` for every frame the pointer moves it by, then + `interactiveMoveResizeFinished`. While it goes on, the window's `move` or `resize` is true, + which tells the two kinds apart. A drag injected as pointer input in a KWin 6.8 session gave + the start, 25 geometry changes and the finish. ## How clients answer a frame diff --git a/docs/index.md b/docs/index.md index 6542999d..2a951293 100644 --- a/docs/index.md +++ b/docs/index.md @@ -33,7 +33,7 @@ the flake's module, which also starts komorebi with every Plasma session, and fr anywhere else. [Running komorebi](usage/running-komorebi.md) explains how to start and stop the daemon, ask it what it is doing and read its log. [Focusing windows](usage/focusing-windows.md) explains how to give the focus to another window, -[Moving windows](usage/moving-windows.md) how to move the focused window to another tile, +[Moving windows](usage/moving-windows.md) how to move a window to another tile, [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, diff --git a/docs/usage/moving-windows.md b/docs/usage/moving-windows.md index 62b4db47..cd3d4319 100644 --- a/docs/usage/moving-windows.md +++ b/docs/usage/moving-windows.md @@ -1,8 +1,8 @@ # Moving windows -komorebi moves the focused window to another tile of its workspace when it is told to. The -window swaps places with the window on that tile, the workspace is tiled again, and the window -that moved keeps the focus. +komorebi moves the focused window to another tile of its workspace when it is told to, or when +the window is dragged there. The window swaps places with the window on that tile, the workspace +is tiled again, and the window that moved keeps the focus. ## In a direction @@ -97,7 +97,36 @@ The `LockMonitorWorkspaceContainer` and `UnlockMonitorWorkspaceContainer` messag unlock a container by the index of its monitor, its workspace and itself, for a program such as a status bar. They have no subcommand. +## By dragging + +A window can be moved with the pointer too: drag it by its title bar and let go. Where it goes +depends on where the pointer is: + +- On the tile of another window of the same monitor, the two windows swap places, and the + workspace is tiled again. With the + [window container behavior](stacking-windows.md#windows-that-open-into-a-stack) set to `append`, + the window joins the stack on that tile instead, in front. +- On another monitor, the window goes there, with the stack it is in, and takes the place of the + container whose tile it was let go on, which moves one place on. On a monitor with no window it + is the first container. Both monitors are tiled again. +- Where there is no tile, on a panel for example, the window goes back to its own. + +With the [float override](floating-windows.md#windows-that-open-floating) on, a window let go on a +tile of its own monitor floats where it was let go instead. A floating window can be dragged +anywhere and takes no tile. Let go on another monitor, it is one of the floating windows there, +but only when the workspace it came from has a tile: with nothing else on it, komorebi does not +notice that the window changed monitors. + +komorebi takes a drag for a move when the window's frame is as wide and as tall as its tile at +the end of it, or when it ends on another monitor. A client that sizes itself in steps, such as +a terminal that keeps to whole cells of its font, can be a few pixels short of its tile: dragging +it on its own monitor swaps nothing, and it stays where it was let go until the workspace is +tiled again, which the next change of focus does. + ## The pointer The pointer follows the window that moved, unless -[mouse follows focus](focusing-windows.md#the-pointer) is off. +[mouse follows focus](focusing-windows.md#the-pointer) is off. A drag is the exception: the +pointer is where it was let go, whether the windows swapped, the window joined another or went +back to its tile. Only a window let go on another monitor takes the pointer with it, to the +middle of its tile, unless mouse follows focus is off. diff --git a/komorebi/src/kwin/bridge.js b/komorebi/src/kwin/bridge.js index fc1ac17d..6bd46e2a 100644 --- a/komorebi/src/kwin/bridge.js +++ b/komorebi/src/kwin/bridge.js @@ -54,8 +54,9 @@ * `activated` with no `id` means no window has the focus; `caption` is a window's new title; * `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; - * `cursor` answers a cursor query, and `failed` gives back the commands of a batch that could not - * be carried out. + * `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 + * 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[], @@ -70,10 +71,15 @@ * @typedef {{ type: "desktops", id: string, desktops: string[] }} Desktops * @typedef {{ type: "desktop_list", desktops: Desktop[] }} DesktopList * @typedef {{ type: "current_desktops", current: CurrentDesktop[] }} CurrentDesktops + * @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: "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 | CursorAnswer | Failed} BridgeEvent + * | DesktopList | CurrentDesktops | MoveResizeStarted | MoveResizeFinished | CursorAnswer + * | Failed} BridgeEvent */ /** @@ -361,6 +367,13 @@ function track(w, announce) { w.desktopsChanged.connect(function () { emit("desktops", { id: id, desktops: desktopIds(w) }); }); + w.interactiveMoveResizeStarted.connect(function () { + delete want[id]; + emit("move_resize_started", { id: id, move: !!w.move, resize: !!w.resize, geo: rect(w.frameGeometry) }); + }); + w.interactiveMoveResizeFinished.connect(function () { + emit("move_resize_finished", { id: id, geo: rect(w.frameGeometry), cursor: cursor() }); + }); } workspace.windowAdded.connect(function (w) { diff --git a/komorebi/src/kwin/bridge.test.js b/komorebi/src/kwin/bridge.test.js index 6cc02dd4..27a392ba 100644 --- a/komorebi/src/kwin/bridge.test.js +++ b/komorebi/src/kwin/bridge.test.js @@ -95,6 +95,8 @@ function window({ minimizedChanged: new Signal(), captionChanged: new Signal(), desktopsChanged: new Signal(), + interactiveMoveResizeStarted: new Signal(), + interactiveMoveResizeFinished: new Signal(), closeWindow: () => assert.fail("a window that is in no KWin was closed"), ...rest, }; @@ -336,15 +338,21 @@ test("what the bridge sends for a session is what the daemon's tests read", () = editor.desktops = [first]; k.workspace.setCurrentDesktopForScreen(first, DP1); - assert.deepStrictEqual(k.events(), events); - // and made see-through, which KWin does not report assert.equal(k.events().at(-1).seq, opacityCommand.after_seq); k.answer([opacityCommand.batch]); assert.equal(editor.opacity, 0.2); - assert.deepStrictEqual(k.events(), events); - assert.deepStrictEqual(editor.frameGeometry, geometry(0, 0, 960, 1050)); + // the user drags the editor by its title bar, and lets go of it further down and to the right + editor.move = true; + editor.interactiveMoveResizeStarted.emit(); + editor.frameGeometry = geometry(40.2, 30, 960, 1050); + k.workspace.cursorPos = { x: 1500.4, y: 600 }; + editor.move = false; + editor.interactiveMoveResizeFinished.emit(); + + assert.deepStrictEqual(k.events(), events); + assert.deepStrictEqual(editor.frameGeometry, geometry(40.2, 30, 960, 1050)); assert.equal(k.workspace.activeWindow, editor); assert.deepStrictEqual(k.raised, [editor]); assert.equal(editor.minimized, false); @@ -658,6 +666,51 @@ test("a window is asked for its position again for a second after the command, a assert.deepStrictEqual(w.frameGeometry, geometry(-700, 0, 800, 600)); }); +test("a drag is reported when the user takes hold of a window and when they let go", () => { + const w = window({ id: "{w}", frameGeometry: geometry(0, 0, 960, 1050) }); + const k = kwin({ windows: [w] }); + + w.resize = true; + w.interactiveMoveResizeStarted.emit(); + w.frameGeometry = geometry(0, 0, 1000.4, 1050); + k.workspace.cursorPos = { x: 1000.4, y: 500.6 }; + w.resize = false; + w.interactiveMoveResizeFinished.emit(); + + assert.deepStrictEqual(k.events().slice(1), [ + { + type: "move_resize_started", + id: "{w}", + move: false, + resize: true, + 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_finished", + id: "{w}", + geo: { x: 0, y: 0, w: 1000, h: 1050 }, + cursor: { x: 1000, y: 501 }, + seq: 4, + }, + ]); +}); + +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] }); + k.answer([{ batch: 1, cmds: [{ op: "geo", id: "{w}", x: -900, y: 0, w: 800, h: 600 }] }]); + + w.move = true; + w.interactiveMoveResizeStarted.emit(); + w.move = false; + w.interactiveMoveResizeFinished.emit(); + w.frameGeometry = geometry(-700, 0, 800, 600); + + assert.deepStrictEqual(w.frameGeometry, geometry(-700, 0, 800, 600)); +}); + test("a window the user is moving or resizing is not asked for its position again", () => { const w = window({ id: "{w}", move: true }); const k = kwin({ windows: [w] }); diff --git a/komorebi/src/kwin/fixtures/events.json b/komorebi/src/kwin/fixtures/events.json index 6ec8d199..a69c5571 100644 --- a/komorebi/src/kwin/fixtures/events.json +++ b/komorebi/src/kwin/fixtures/events.json @@ -80,5 +80,17 @@ "type": "desktops", "seq": 19, "id": "{0e5a1c3b-0000-4000-8000-00000000000a}", "desktops": ["desktop-1"] }, - {"type": "current_desktops", "seq": 20, "current": [{"output": "DP-1", "id": "desktop-1"}]} + {"type": "current_desktops", "seq": 20, "current": [{"output": "DP-1", "id": "desktop-1"}]}, + { + "type": "move_resize_started", "seq": 21, "id": "{0e5a1c3b-0000-4000-8000-00000000000a}", + "move": true, "resize": false, "geo": {"x": 0, "y": 0, "w": 960, "h": 1050} + }, + { + "type": "geometry", "seq": 22, "id": "{0e5a1c3b-0000-4000-8000-00000000000a}", + "geo": {"x": 40, "y": 30, "w": 960, "h": 1050} + }, + { + "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} + } ] diff --git a/komorebi/src/kwin/kwin-api.d.ts b/komorebi/src/kwin/kwin-api.d.ts index 63ba329e..87377c7c 100644 --- a/komorebi/src/kwin/kwin-api.d.ts +++ b/komorebi/src/kwin/kwin-api.d.ts @@ -93,6 +93,11 @@ interface KWinWindow { readonly minimizedChanged: Signal; readonly captionChanged: Signal; readonly desktopsChanged: Signal; + /** The user took hold of the window with the pointer, to move it (`move`) or resize it + * (`resize`). */ + readonly interactiveMoveResizeStarted: Signal; + /** The user let go of the window. */ + readonly interactiveMoveResizeFinished: Signal; closeWindow(): void; /** * Maximizes the window vertically and horizontally, or restores it from either. Maximizing diff --git a/komorebi/src/kwin/mod.rs b/komorebi/src/kwin/mod.rs index 6a3bf91b..32c84b15 100644 --- a/komorebi/src/kwin/mod.rs +++ b/komorebi/src/kwin/mod.rs @@ -791,7 +791,7 @@ impl Backend for KWinBackend { fn cursor_pos(&self) -> Option<(i32, i32)> { // The script is the only thing that can read the pointer, so ask it, and fall back to where - // it was last seen if it does not answer in time + // it was last seen (the end of a drag) if it does not answer in time let token = self.shared.next_token.fetch_add(1, Ordering::Relaxed); let (sender, receiver) = std::sync::mpsc::channel(); self.shared.cursor_waiters.lock().insert(token, sender); diff --git a/komorebi/src/kwin/state.rs b/komorebi/src/kwin/state.rs index 95554d8e..ca21b8a4 100644 --- a/komorebi/src/kwin/state.rs +++ b/komorebi/src/kwin/state.rs @@ -85,12 +85,22 @@ pub const PARK_DESKTOP_NAME: &str = "komorebi-park"; /// can be logged and serialized const TOMBSTONE: Duration = Duration::from_secs(60); +/// A drag of a window by the user with the pointer, which KWin calls an interactive move or +/// resize +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Drag { + Move, + Resize, +} + struct Entry { uuid: String, info: WindowInfo, /// What KWin says: a normal window, as opposed to a dialog, splash, panel, popup... kwin_normal: bool, desktops: Vec, + /// The drag the user is in the middle of, if any + drag: Option, /// komorebi put it on the parking desktop parked: bool, /// The desktop the window was on when it was parked @@ -584,6 +594,7 @@ impl Table { info, kwin_normal: w["normal"].as_bool().unwrap_or(false), desktops: strings(&w["desktops"]), + drag: None, parked: false, home: None, closed_at: None, @@ -642,6 +653,10 @@ impl Table { /// table had it on, this is a [`WindowManagerEvent::WorkspaceMove`]; komorebi's own move /// ([`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. /// - `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 @@ -670,6 +685,8 @@ impl Table { vec![] } Some("desktops") => self.on_desktops(event), + Some("move_resize_started") => self.on_drag_started(event), + Some("move_resize_finished") => self.on_drag_finished(event), Some("current_desktops") => self.on_current_desktops(event), Some("desktop_list") => { self.desktops = desktop_list(&event["desktops"]); @@ -928,6 +945,72 @@ impl Table { } } + fn on_drag_started(&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![]; + }; + + entry.info.rect = rect(&event["geo"]); + + let kind = if event["resize"].as_bool().unwrap_or(false) { + Drag::Resize + } else { + Drag::Move + }; + entry.drag = Some(kind); + + if !entry.info.normal { + return vec![]; + } + + 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![], + } + } + + 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)); + } + + let Some(id) = self.id_of(event) else { + return vec![]; + }; + + let Some(entry) = self.windows.get_mut(&id) else { + return vec![]; + }; + + entry.info.rect = rect(&event["geo"]); + let Some(kind) = entry.drag.take() else { + return vec![]; + }; + + if !entry.info.normal { + return vec![]; + } + + let window = Window::from(id); + match kind { + Drag::Move => vec![Output::Event(WindowManagerEvent::MoveEnd( + kwin(KWinNotification::InteractiveMoveFinished), + window, + ))], + Drag::Resize => vec![], + } + } + /// Some output now shows another desktop: komorebi's request, or a pager, a shortcut, an app /// raising a window (KWin switches that output to the window's desktop) fn on_current_desktops(&mut self, event: &Value) -> Vec { @@ -1190,6 +1273,10 @@ mod tests { "desktop_list -> ", "desktops -> WorkspaceMove 1 to 0", "current_desktops -> WorkspaceChange to 0", + // the user drags the editor + "move_resize_started -> MoveStart 1", + "geometry -> ", + "move_resize_finished -> MoveEnd 1", ] ); @@ -1201,7 +1288,7 @@ mod tests { 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)); - assert_eq!(t.cursor(), Some((1200, 701))); + assert_eq!(t.cursor(), Some((1500, 600)), "where the drag ended"); assert_eq!(t.workspace_count(), 3); assert_eq!(t.window_workspace(1), Some(0)); assert_eq!(t.current_workspaces(), [(t.monitors()[0].id, 0)]); @@ -1422,6 +1509,48 @@ mod tests { assert_eq!(t.window(1).unwrap().title, "renamed"); } + #[test] + fn a_drag_is_reported_as_a_move_or_a_resize_from_start_to_end() { + let mut t = table(vec![win("a", &["d1"]), win("b", &["d1"])]); + let now = Instant::now(); + let geo = json!({"x":0,"y":0,"w":100,"h":100}); + + let started = t.handle(&json!({ "type": "move_resize_started", "id": "a", "move": true, "resize": false, "geo": geo }), now); + let finished = t.handle(&json!({ "type": "move_resize_finished", "id": "a", "geo": geo, "cursor": {"x": 50, "y": 60} }), now); + assert_eq!(events(&started), vec!["MoveStart 1"]); + assert_eq!(events(&finished), vec!["MoveEnd 1"]); + assert_eq!( + t.cursor(), + Some((50, 60)), + "the cursor at the end of the drag is kept" + ); + } + + #[test] + fn a_move_is_where_the_frame_is() { + 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": true, "resize": false, "geo": start }), now); + 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.window(1).unwrap().rect.left, 50); + } + + #[test] + fn a_finish_without_a_start_is_ignored() { + let mut t = table(vec![win("a", &["d1"])]); + let out = t.handle(&json!({ "type": "move_resize_finished", "id": "a", "geo": {"x":0,"y":0,"w":1,"h":1}, "cursor": {"x":0,"y":0} }), Instant::now()); + assert!(events(&out).is_empty()); + } + #[test] fn every_desktop_is_a_workspace_and_a_window_is_on_the_one_it_is_on() { let t = table(vec![ diff --git a/komorebi/src/process_event.rs b/komorebi/src/process_event.rs index 632a58ec..b9c001a0 100644 --- a/komorebi/src/process_event.rs +++ b/komorebi/src/process_event.rs @@ -32,6 +32,15 @@ //! hid ([`struct@HIDDEN_WINDOWS`]) is not the user's, and changes nothing. //! - **TitleUpdate**: a window komorebi does not have, and that was not minimized, is announced //! again as a Show, so that a rule that matches on the title it has now decides. +//! - **MoveStart** and **MoveEnd**: the user dragged a window with the pointer. When they let go +//! on another monitor, the window's container goes there and takes the place of the container +//! whose tile the pointer is on ([`WindowManager::transfer_window`]). When they let go on the +//! same monitor, the focused container swaps places with the container whose tile the pointer +//! is on, or, when the window container behavior is `Append`, the window joins it, or, with the +//! float override on, the window floats where it was let go; the workspace is tiled again, and +//! 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. //! - **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 @@ -66,6 +75,7 @@ use crate::backend::backend; use crate::border_manager; use crate::core::DefaultLayout; use crate::core::Layout; +use crate::core::Rect; use crate::core::WindowContainerBehaviour; use crate::notify_subscribers; use crate::state::State; @@ -495,6 +505,227 @@ impl WindowManager { )); } } + WindowManagerEvent::MoveStart(_, window) => { + let window_id = window.id; + if self.pending_move_op.is_none() { + let monitor_idx = self.focused_monitor_idx(); + let workspace_idx = self + .focused_monitor() + .ok_or_eyre("there is no monitor with this idx")? + .focused_workspace_idx(); + + let pending_move_op = Arc::make_mut(&mut self.pending_move_op); + *pending_move_op = Option::from((monitor_idx, workspace_idx, window_id)); + } + } + WindowManagerEvent::MoveEnd(_, window) => { + let window_id = window.id; + // We need this because if the event ends on a different monitor, + // that monitor will already have been focused and updated in the state + let pending = *self.pending_move_op; + // Always consume the pending move op whenever this event is handled + let pending_move_op = Arc::make_mut(&mut self.pending_move_op); + *pending_move_op = None; + + if let Some((origin_monitor_idx, origin_workspace_idx, wid)) = pending { + // If the window handles don't match then something went wrong and the pending move + // is not related to this current move, if so abort this operation. + if wid != window_id { + eyre::bail!( + "window handles for move operation don't match: {} != {}", + wid, + window_id + ); + } + let known_window_ids = self.known_window_ids.clone(); + + let target_monitor_idx = self + .monitor_idx_from_current_pos() + .ok_or_eyre("cannot get monitor idx from current position")?; + + let focused_monitor_idx = self.focused_monitor_idx(); + let focused_workspace_idx = self.focused_workspace_idx().unwrap_or_default(); + let window_management_behaviour = self + .window_management_behaviour(focused_monitor_idx, focused_workspace_idx); + + let workspace = self.focused_workspace_mut()?; + let focused_container_idx = workspace.focused_container_idx(); + + if let Some(container) = workspace.focused_container() + && let Some(window) = container.focused_window() + { + // TODO: not sure about this clone + let window = *window; + let new_position = window.rect()?; + let old_position = *workspace + .latest_layout + .get(focused_container_idx) + // If the move was to another monitor with an empty workspace, the + // workspace here will refer to that empty workspace, which won't + // have any latest layout set. We fall back to a Default for Rect + // which allows us to make a reasonable guess that the drag has taken + // place across a monitor boundary to an empty workspace + .unwrap_or(&Rect::default()); + + // This will be true if we have moved to another monitor + let mut moved_across_monitors = false; + + if let Some((m_idx, _)) = known_window_ids.get(&window_id) + && *m_idx != target_monitor_idx + { + moved_across_monitors = true; + } + + // If we didn't move to another monitor with an empty workspace, it is + // still possible that we moved to another monitor with a populated workspace + if !moved_across_monitors { + // So we'll check if the origin monitor index and the target monitor index + // are different, if they are, we can set the override + moved_across_monitors = origin_monitor_idx != target_monitor_idx; + + if moved_across_monitors { + // Want to make sure that we exclude unmanaged windows from cross-monitor + // moves with a mouse, otherwise the currently focused idx container will + // be moved when we just want to drag an unmanaged window + let origin_workspace = self + .monitors() + .get(origin_monitor_idx) + .ok_or_eyre("cannot get monitor idx")? + .workspaces() + .get(origin_workspace_idx) + .ok_or_eyre("cannot get workspace idx")?; + + let managed_window = origin_workspace.contains_window(window_id); + + if !managed_window { + moved_across_monitors = false; + } + } + } + + let workspace = self.focused_workspace_mut()?; + if (workspace.tile && workspace.contains_managed_window(window_id)) + || moved_across_monitors + { + let resize = Rect { + left: new_position.left - old_position.left, + top: new_position.top - old_position.top, + right: new_position.right - old_position.right, + bottom: new_position.bottom - old_position.bottom, + }; + + // If we have moved across the monitors, use that override, otherwise determine + // if a move has taken place by ruling out a resize + let right_bottom_constant = 0; + + let is_move = moved_across_monitors + || resize.right.abs() == right_bottom_constant + && resize.bottom.abs() == right_bottom_constant; + + if is_move { + tracing::info!("moving with mouse"); + + if moved_across_monitors { + if let Some(( + origin_monitor_idx, + origin_workspace_idx, + w_hwnd, + )) = pending + { + let target_workspace_idx = self + .monitors() + .get(target_monitor_idx) + .ok_or_eyre("there is no monitor at this idx")? + .focused_workspace_idx(); + + let target_container_idx = self + .monitors() + .get(target_monitor_idx) + .ok_or_eyre("there is no monitor at this idx")? + .focused_workspace() + .ok_or_eyre( + "there is no focused workspace for this monitor", + )? + .container_idx_from_current_point() + // Default to 0 in the case of an empty workspace + .unwrap_or(0); + + let origin = + (origin_monitor_idx, origin_workspace_idx, w_hwnd); + let target = ( + target_monitor_idx, + target_workspace_idx, + target_container_idx, + ); + self.transfer_window(origin, target)?; + + // We want to make sure both the origin and target monitors are updated, + // so that we don't have ghost tiles until we force an interaction on + // the origin monitor's focused workspace + self.focus_monitor(origin_monitor_idx)?; + let origin_monitor = self + .monitors_mut() + .get_mut(origin_monitor_idx) + .ok_or_eyre("there is no monitor at this idx")?; + origin_monitor.focus_workspace(origin_workspace_idx)?; + self.update_focused_workspace(false, false)?; + + self.focus_monitor(target_monitor_idx)?; + let target_monitor = self + .monitors_mut() + .get_mut(target_monitor_idx) + .ok_or_eyre("there is no monitor at this idx")?; + target_monitor.focus_workspace(target_workspace_idx)?; + self.update_focused_workspace(false, false)?; + + // Make sure to give focus to the moved window again + window.focus(self.mouse_follows_focus)?; + } + } else if window_management_behaviour.float_override { + // TODO: unsure of this clone + workspace.floating_windows_mut().push_back(window); + self.update_focused_workspace(false, false)?; + } else { + match window_management_behaviour.current_behaviour { + WindowContainerBehaviour::Create => { + match workspace.container_idx_from_current_point() { + Some(target_idx) => { + workspace.swap_containers( + focused_container_idx, + target_idx, + ); + self.update_focused_workspace(false, false)?; + } + None => { + self.update_focused_workspace( + self.mouse_follows_focus, + false, + )?; + } + } + } + WindowContainerBehaviour::Append => { + match workspace.container_idx_from_current_point() { + Some(target_idx) => { + workspace + .move_window_to_container(target_idx)?; + self.update_focused_workspace(false, false)?; + } + None => { + self.update_focused_workspace( + self.mouse_follows_focus, + false, + )?; + } + } + } + } + } + } + } + } + } + } } // a window that was just managed is on the desktop the compositor opened it on, which is the diff --git a/komorebi/src/static_config.rs b/komorebi/src/static_config.rs index d5a6aba9..bc958310 100644 --- a/komorebi/src/static_config.rs +++ b/komorebi/src/static_config.rs @@ -1259,6 +1259,7 @@ impl StaticConfig { .unwrap_or(DEFAULT_MOUSE_FOLLOWS_FOCUS), hotwatch: Hotwatch::new()?, minimized_windows: HashMap::new(), + pending_move_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 42ada02b..13b8b546 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -150,6 +150,9 @@ pub struct WindowManager { /// [`crate::window_manager_event_listener`] pub incoming_events: Receiver, pub minimized_windows: HashMap, + /// 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 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>>, @@ -240,6 +243,7 @@ impl WindowManager { work_area_offset: None, incoming_events: incoming, minimized_windows: HashMap::new(), + pending_move_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 71470ce0..9ab3fc55 100644 --- a/komorebi/src/window_manager_event.rs +++ b/komorebi/src/window_manager_event.rs @@ -43,6 +43,10 @@ pub enum KWinNotification { WindowRestored, /// `window.captionChanged` CaptionChanged, + /// `window.interactiveMoveResizeStarted` for a move + InteractiveMoveStarted, + /// `window.interactiveMoveResizeFinished` after a move + InteractiveMoveFinished, } /// Events komorebi raises itself, for example from a command @@ -69,6 +73,11 @@ pub enum WindowManagerEvent { Manage(Window), /// The user asked komorebi to stop managing the window (`UnmanageFocusedWindow`) Unmanage(Window), + /// The user took hold of a window to move it with the pointer + MoveStart(SystemNotification, Window), + /// 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), /// 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), @@ -89,6 +98,8 @@ impl WindowManagerEvent { | WindowManagerEvent::TitleUpdate(_, window) | WindowManagerEvent::Manage(window) | WindowManagerEvent::Unmanage(window) + | WindowManagerEvent::MoveStart(_, window) + | WindowManagerEvent::MoveEnd(_, window) | WindowManagerEvent::WorkspaceMove(_, window, _) => *window, WindowManagerEvent::WorkspaceChange(..) => return None, }) @@ -111,6 +122,8 @@ impl WindowManagerEvent { | WindowManagerEvent::Minimize(n, _) | WindowManagerEvent::Restore(n, _) | WindowManagerEvent::TitleUpdate(n, _) + | WindowManagerEvent::MoveStart(n, _) + | WindowManagerEvent::MoveEnd(n, _) | WindowManagerEvent::WorkspaceChange(n, _, _) | WindowManagerEvent::WorkspaceMove(n, _, _) => match n { SystemNotification::KWin(k) => k.to_string(), diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index f5a30722..65dfc9df 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -1711,6 +1711,26 @@ impl Workspace { Ok(()) } + /// Returns the index of the container whose tile has the pointer in it, or `None` when the + /// pointer is on no tile, or the backend cannot say where it is + /// + /// The tiles are those the layout last calculated ([`Workspace::latest_layout`]). + pub fn container_idx_from_current_point(&self) -> Option { + let mut idx = None; + + let point = backend().cursor_pos()?; + + for (i, _container) in self.containers().iter().enumerate() { + if let Some(rect) = self.latest_layout.get(i) + && rect.contains_point(point) + { + idx = Option::from(i); + } + } + + idx + } + /// The container that has the window, if one of this workspace's does pub fn container_for_window(&self, window_id: u32) -> Option<&Container> { self.containers() diff --git a/komorebi/tests/drag_swap.rs b/komorebi/tests/drag_swap.rs new file mode 100644 index 00000000..09cbef14 --- /dev/null +++ b/komorebi/tests/drag_swap.rs @@ -0,0 +1,517 @@ +//! Moving a window by dragging it with the pointer, against an in-memory desktop: swapping two +//! tiles by dragging one window onto another, and what the window container behavior, the float +//! override and a second monitor change about where the window goes. +//! +//! Window ids are in the 10_000s and the 51_000s. + +use komorebi::backend::Backend; +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +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 drag(kind: KWinNotification, id: u32, start: bool, resize: bool) -> WindowManagerEvent { + let n = SystemNotification::KWin(kind); + let w = Window::from(id); + 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"), + } +} + +/// A window manager over a fake desktop with one 1920x1080 monitor (1920x1050 without the panel) +fn desktop() -> (Arc, WindowManager) { + desktop_on(FakeBackend::with_one_monitor()) +} + +fn desktop_on(fake: FakeBackend) -> (Arc, WindowManager) { + let fake = Arc::new(fake); + let (_sender, receiver) = crossbeam_channel::bounded(1); + // unix socket paths are limited to ~104 bytes on macOS, which the temp dir alone can exceed + static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let socket = std::path::PathBuf::from(format!( + "/tmp/kmb-{}-{}.sock", + std::process::id(), + NEXT.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + )); + + let wm = with_backend(fake.clone(), || { + let mut wm = WindowManager::new(receiver, Some(socket)).unwrap(); + wm.init().unwrap(); + wm + }); + + (fake, wm) +} + +fn activated(id: u32) -> WindowManagerEvent { + WindowManagerEvent::FocusChange( + SystemNotification::KWin(KWinNotification::WindowActivated), + Window::from(id), + ) +} + +fn open(fake: &FakeBackend, id: u32) { + fake.open_window(id, "foot", "foot", &format!("terminal {id}")); +} + +/// The bounds of the second monitor, on the right of the first, which is also its work area +fn right_half() -> Rect { + Rect { + left: 1920, + top: 0, + right: 1920, + bottom: 1080, + } +} + +/// A window manager over a fake desktop with the monitor of `desktop` and a second one on its +/// right +fn two_monitors() -> (Arc, WindowManager) { + let fake = FakeBackend::with_one_monitor(); + fake.add_monitor(2, "Virtual-1", right_half(), right_half()); + desktop_on(fake) +} + +/// Opens a window on the second monitor +fn open_on_right(fake: &FakeBackend, id: u32) { + open(fake, id); + fake.move_window_by_user( + id, + Rect { + left: 2020, + top: 100, + right: 800, + bottom: 600, + }, + ); +} + +/// The ids of the windows of the focused workspace of each monitor +fn windows(wm: &WindowManager) -> Vec> { + wm.monitors() + .iter() + .map(|monitor| { + monitor + .focused_workspace() + .unwrap() + .containers() + .iter() + .flat_map(|container| container.windows().iter().map(|window| window.id)) + .collect() + }) + .collect() +} + +/// The user takes hold of the window `id`, which they have given the focus, carries it to where +/// the pointer is `(x, y)` and lets go: its frame is then the same size as it was, at `to` +fn drag_to( + fake: &Arc, + wm: &mut WindowManager, + id: u32, + to: (i32, i32), + pointer: (i32, i32), +) -> color_eyre::Result<()> { + with_backend(fake.clone(), || { + fake.set_foreground(Some(id)); + wm.process_event(activated(id))?; + let frame = fake.rect_of(id).unwrap(); + + wm.process_event(drag( + KWinNotification::InteractiveMoveStarted, + id, + true, + false, + ))?; + fake.move_window_by_user( + id, + Rect { + left: to.0, + top: to.1, + ..frame + }, + ); + fake.set_cursor(pointer.0, pointer.1); + wm.process_event(drag( + KWinNotification::InteractiveMoveFinished, + id, + false, + false, + )) + }) +} + +#[test] +fn dragging_a_window_onto_another_swaps_them() { + let (fake, mut wm) = desktop(); + open(&fake, 10_091); + open(&fake, 10_092); + + with_backend(fake.clone(), || { + wm.process_event(added(10_091))?; + wm.process_event(added(10_092))?; + + let a = fake.rect_of(10_091).unwrap(); + let b = fake.rect_of(10_092).unwrap(); + assert!( + a.left < b.left, + "10_091 should be the left tile: {a:?} {b:?}" + ); + + // the user grabs the focused window (10_092, the right tile) and drops it on the left one + wm.process_event(drag( + KWinNotification::InteractiveMoveStarted, + 10_092, + true, + false, + ))?; + fake.move_window_by_user( + 10_092, + Rect { + left: a.left + 40, + top: a.top + 40, + ..b + }, + ); + fake.set_cursor(a.left + 200, a.top + 200); + wm.process_event(drag( + KWinNotification::InteractiveMoveFinished, + 10_092, + false, + false, + )) + }) + .unwrap(); + + let (a, b) = (fake.rect_of(10_091).unwrap(), fake.rect_of(10_092).unwrap()); + assert!( + b.left < a.left, + "they should have swapped sides: {a:?} {b:?}" + ); +} + +#[test] +fn a_window_let_go_of_where_there_is_no_tile_goes_back_to_its_own() { + let (fake, mut wm) = desktop(); + open(&fake, 51_001); + open(&fake, 51_002); + + with_backend(fake.clone(), || { + wm.process_event(added(51_001))?; + wm.process_event(added(51_002))?; + let b = fake.rect_of(51_002).unwrap(); + + wm.process_event(drag( + KWinNotification::InteractiveMoveStarted, + 51_002, + true, + false, + ))?; + fake.move_window_by_user( + 51_002, + Rect { + left: b.left - 300, + top: b.top + 20, + ..b + }, + ); + // on the panel, below the work area + fake.set_cursor(b.left + 100, 1070); + wm.process_event(drag( + KWinNotification::InteractiveMoveFinished, + 51_002, + false, + false, + ))?; + + assert_eq!( + fake.rect_of(51_002), + Some(b), + "it should be back on its tile" + ); + assert_eq!( + fake.cursor_pos(), + Some((b.left + 100, 1070)), + "the pointer should be where it was let go" + ); + Ok::<(), color_eyre::eyre::Report>(()) + }) + .unwrap(); +} + +#[test] +fn a_floating_window_dragged_onto_a_tile_takes_nothing_from_it() { + let (fake, mut wm) = desktop(); + open(&fake, 51_011); + open(&fake, 51_012); + + with_backend(fake.clone(), || { + wm.process_event(added(51_011))?; + wm.process_event(added(51_012))?; + fake.set_foreground(Some(51_012)); + wm.process_command(SocketMessage::ToggleFloat, Vec::new())?; + let a = fake.rect_of(51_011).unwrap(); + + wm.process_event(drag( + KWinNotification::InteractiveMoveStarted, + 51_012, + true, + false, + ))?; + let dropped = Rect { + left: a.left + 40, + top: a.top + 40, + right: 400, + bottom: 300, + }; + fake.move_window_by_user(51_012, dropped); + fake.set_cursor(a.left + 200, a.top + 200); + wm.process_event(drag( + KWinNotification::InteractiveMoveFinished, + 51_012, + false, + false, + ))?; + + assert_eq!( + fake.rect_of(51_011), + Some(a), + "the tile should be as it was" + ); + assert_eq!( + fake.rect_of(51_012), + Some(dropped), + "the floating window should be where it was let go of" + ); + Ok::<(), color_eyre::eyre::Report>(()) + }) + .unwrap(); +} + +#[test] +fn a_window_let_go_of_on_another_monitor_goes_to_that_monitor() { + let (fake, mut wm) = two_monitors(); + open(&fake, 51_021); + open(&fake, 51_022); + open_on_right(&fake, 51_023); + + with_backend(fake.clone(), || { + wm.process_event(added(51_021))?; + wm.process_event(added(51_022))?; + wm.process_event(added(51_023)) + }) + .unwrap(); + assert_eq!(windows(&wm), [vec![51_021, 51_022], vec![51_023]]); + + let tile = fake.rect_of(51_023).unwrap(); + drag_to( + &fake, + &mut wm, + 51_022, + (tile.left + 40, tile.top + 40), + (tile.left + 200, tile.top + 200), + ) + .unwrap(); + + let shown = windows(&wm); + assert_eq!( + shown, + [vec![51_021], vec![51_022, 51_023]], + "it should take the place of the container it was let go on" + ); + assert!( + fake.rect_of(51_022).unwrap().left >= 1920, + "it should be tiled on the second monitor" + ); + assert!( + fake.rect_of(51_021).unwrap().right > 1800, + "the window left behind should have the first monitor to itself" + ); + let moved = fake.rect_of(51_022).unwrap(); + assert_eq!( + fake.cursor_pos(), + Some((moved.left + moved.right / 2, moved.top + moved.bottom / 2)), + "the pointer should have followed it" + ); +} + +#[test] +fn a_window_let_go_of_on_a_monitor_with_nothing_on_it_goes_there() { + let (fake, mut wm) = two_monitors(); + open(&fake, 51_031); + open(&fake, 51_032); + + with_backend(fake.clone(), || { + wm.process_event(added(51_031))?; + wm.process_event(added(51_032)) + }) + .unwrap(); + + drag_to(&fake, &mut wm, 51_032, (2400, 300), (2500, 400)).unwrap(); + + assert_eq!(windows(&wm), [vec![51_031], vec![51_032]]); + assert!(fake.rect_of(51_032).unwrap().left >= 1920); +} + +/// The ids of the windows of each container of the focused workspace, in order +fn containers(wm: &WindowManager) -> Vec> { + wm.focused_workspace() + .unwrap() + .containers() + .iter() + .map(|container| container.windows().iter().map(|window| window.id).collect()) + .collect() +} + +#[test] +fn with_append_a_window_let_go_of_on_a_tile_joins_the_container_of_that_tile() { + let (fake, mut wm) = desktop(); + open(&fake, 51_041); + open(&fake, 51_042); + open(&fake, 51_043); + + with_backend(fake.clone(), || { + wm.process_event(added(51_041))?; + wm.process_event(added(51_042))?; + wm.process_event(added(51_043))?; + wm.process_command(SocketMessage::ToggleWindowContainerBehaviour, Vec::new()) + }) + .unwrap(); + assert_eq!(containers(&wm), [[51_041], [51_042], [51_043]]); + + let tile = fake.rect_of(51_041).unwrap(); + drag_to( + &fake, + &mut wm, + 51_043, + (tile.left + 40, tile.top + 40), + (tile.left + 200, tile.top + 200), + ) + .unwrap(); + + assert_eq!(containers(&wm), [vec![51_041, 51_043], vec![51_042]]); + assert_eq!( + fake.rect_of(51_043), + Some(tile), + "the window should be in front on the tile of the container it joined" + ); +} + +#[test] +fn with_the_float_override_a_window_let_go_of_on_a_tile_floats_where_it_was_let_go_of() { + let (fake, mut wm) = desktop(); + open(&fake, 51_051); + open(&fake, 51_052); + + with_backend(fake.clone(), || { + wm.process_event(added(51_051))?; + wm.process_event(added(51_052))?; + wm.process_command(SocketMessage::ToggleFloatOverride, Vec::new()) + }) + .unwrap(); + let (a, b) = (fake.rect_of(51_051).unwrap(), fake.rect_of(51_052).unwrap()); + + drag_to( + &fake, + &mut wm, + 51_052, + (a.left + 40, a.top + 40), + (a.left + 200, a.top + 200), + ) + .unwrap(); + + let floating: Vec = wm + .focused_workspace() + .unwrap() + .floating_windows() + .iter() + .map(|window| window.id) + .collect(); + assert_eq!(containers(&wm), [[51_051]]); + assert_eq!(floating, [51_052]); + assert_eq!( + fake.rect_of(51_052), + Some(Rect { + left: a.left + 40, + top: a.top + 40, + ..b + }), + "it should be where it was let go of" + ); + assert_eq!( + fake.rect_of(51_051), + Some(Rect { right: 1900, ..a }), + "the tile that is left should have the work area to itself" + ); +} + +#[test] +fn a_floating_window_let_go_of_on_another_monitor_is_one_of_the_floating_windows_there() { + let (fake, mut wm) = two_monitors(); + open(&fake, 51_061); + open(&fake, 51_062); + + with_backend(fake.clone(), || { + wm.process_event(added(51_061))?; + wm.process_event(added(51_062))?; + fake.set_foreground(Some(51_062)); + wm.process_command(SocketMessage::ToggleFloat, Vec::new()) + }) + .unwrap(); + let floating = |wm: &WindowManager, monitor: usize| -> Vec { + wm.monitors()[monitor] + .focused_workspace() + .unwrap() + .floating_windows() + .iter() + .map(|window| window.id) + .collect() + }; + assert_eq!(floating(&wm, 0), [51_062]); + + drag_to(&fake, &mut wm, 51_062, (2400, 300), (2500, 400)).unwrap(); + + assert_eq!(floating(&wm, 0), Vec::::new()); + assert_eq!(floating(&wm, 1), [51_062]); + assert_eq!(windows(&wm), [vec![51_061], vec![]]); +} + +#[test] +fn after_a_swap_the_pointer_is_where_it_was_let_go() { + let (fake, mut wm) = desktop(); + open(&fake, 51_081); + open(&fake, 51_082); + + with_backend(fake.clone(), || { + wm.process_event(added(51_081))?; + wm.process_event(added(51_082)) + }) + .unwrap(); + let a = fake.rect_of(51_081).unwrap(); + + drag_to( + &fake, + &mut wm, + 51_082, + (a.left + 40, a.top + 40), + (a.left + 200, a.top + 200), + ) + .unwrap(); + + assert!(fake.rect_of(51_082).unwrap().left < fake.rect_of(51_081).unwrap().left); + assert_eq!(fake.cursor_pos(), Some((a.left + 200, a.top + 200))); +}