diff --git a/README.md b/README.md index e5602e81..8e983b6e 100644 --- a/README.md +++ b/README.md @@ -222,8 +222,9 @@ another layout, `layout-ratios` and `scrolling-layout-columns` tune it, focused window to the largest tile, `toggle-float` takes it out of the layout, `toggle-monocle` gives its container the whole work area, hiding the others, and puts it back, `toggle-maximize` has KWin maximize the focused window -and restore it, `toggle-workspace-layer` switches the focus commands between the -tiles and the floating windows, and `toggle-lock` keeps its container at its +and restore it (a window the user maximizes leaves the layout the same way), +`toggle-workspace-layer` switches the focus commands between the tiles and the +floating windows, and `toggle-lock` keeps its container at its place. The scrolling layout is a strip of columns that runs past the edges of the monitor and scrolls to the window that has the focus. `minimize` and `close` ask KWin to minimize or close the focused window, `unmanage` takes it out of the diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index 359fa622..81c05b4b 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -46,14 +46,14 @@ that is added has its place here. containers are hidden, until it is put back where it was ([`Workspace::monocle_container`]). - **Layer**: which of a workspace's two kinds of windows the focus, move and resize commands act on: its tiles (`Tiling`) or its floating windows (`Floating`) ([`WorkspaceLayer`]). -- **Maximized window**: a workspace's one window that the compositor has maximized. It is in no - container, so it has left the layout, until it is put back in a container of its own where it - was ([`Workspace::maximized_window`]). +- **Maximized window**: a workspace's one window that the compositor has maximized, whether + komorebi asked for it or the user did. It is in no 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, dragged by the user, put on another workspace's desktop, or - moved to another output; 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, maximized or restored from it, dragged by the user, put on + another workspace's desktop, or moved to another output; 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`]). @@ -113,10 +113,10 @@ the same logic runs against both. The reasons are in The desktop, as the window manager sees it, is two lists and a pointer: - **Windows**, each a [`WindowInfo`]: its id, process, title, `app_id`, executable, frame, - whether it is minimized, whether it is a normal application window (as opposed to a - dialog, a splash screen or a dock), and whether it is alive. A window that has been - destroyed stays in the table for a short time with `alive` false, so that the event that - mentions it can still be logged. + whether it is minimized, whether it is maximized, whether it is a normal application window + (as opposed to a dialog, a splash screen or a dock), and whether it is alive. A window that + has been destroyed stays in the table for a short time with `alive` false, so that the event + that mentions it can still be logged. - **Monitors**, each a [`MonitorInfo`]: its id, name, an identity that survives a hot-plug, its bounds and its work area. - **The pointer**, a position if the compositor says where it is, and the **focus**, the id @@ -349,7 +349,9 @@ copy, with its workspaces and settings, in a cache that lives as long as the dae that are left ([`WindowManager::evacuate_monitor`]). Each container and floating window goes to the workspace of the same number on the monitor that now holds the middle of its window's frame, or on the first monitor that is left when the window is on none; a stack goes as the container it -is, and a monocle and a maximized window come as ordinary containers. The monitor is then removed. +is, a monocle comes as an ordinary container, and a maximized window stays maximized, as the +maximized window of the workspace it goes to ([`Workspace::adopt_maximized_window`]). The monitor +is then removed. A monitor that is new to the window manager is added by [`load_monitor_information`], and when the cache has a monitor with its serial number id, the new monitor takes the cached workspaces and settings, less the windows that have closed or that the window manager has elsewhere now, and the @@ -623,6 +625,19 @@ container's window (the code has a TODO for what it should do). A maximized wind with the rest of its workspace, and restored and focused ahead of the containers' windows when the workspace is shown again ([`Workspace::hide`], [`Workspace::restore`]). +A window the user maximizes, with its title bar, a double click or a shortcut, is the same from +then on. KWin does it without komorebi's being asked, and the bridge reports it as a `maximized` +event, which the table turns into a `MaximizeChange` ([`WindowManager::adopt_maximize_change`]). +The window leaves its container, or the floating windows, or the monocle, for the workspace's +maximized window, with the index it goes back to ([`Workspace::adopt_maximized_window`]), and the +workspace is tiled again. It is not asked to maximize: it already is. A workspace has room for one +maximized window, so the one it had is put back in its container first. When the user restores +the window, it goes back in a container of its own at that index; a window that was floating comes +back as a tile, as it does after `ToggleMaximize`. komorebi's own maximize and restore are +reported too, and find the workspace as they leave it, so they change nothing. A window that is +already maximized when komorebi starts ([`load_workspace_information`]) or when it opens (a +`Show`) is the maximized window the same way. + A workspace is on one of two layers ([`Workspace::layer`]), and the focus, move and resize messages go to the windows of that layer. `ToggleFloat` puts the workspace on the floating layer, and putting the window back, or a `FocusChange` to a window that is not floating, a new tiled @@ -1260,6 +1275,12 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | A clean stop, and the next start after a crash, bring back the windows a monocle hid | VM test | `vm-core-e2e` ("and every window is on a workspace's desktop", "after a crash and a restart a monocle still hides the other window") | none | | A maximized window goes back in a container of its own at the index it came from, and the tiles are where they were | framework path: [`Workspace::new_maximized_window`] keeps the index and [`Workspace::reintegrate_maximized_window`] inserts at it, after asking the backend to restore the window, and nothing else moves in between | `toggle_maximize_takes_the_window_out_of_the_layout_and_back`, `maximizing_works_in_every_layout`, `a_window_goes_back_in_a_container_of_its_own_at_the_index_it_came_from` | none | | What is about the tiles does nothing while a window is maximized | framework path: `is_layout_command` in [`WindowManager::process_command`] drops the message before it is handled | `while_a_window_is_maximized_what_is_about_the_tiles_does_nothing` | none | +| A window the user maximizes leaves the layout as `toggle-maximize` makes a window leave it, and comes back to its tile when the user restores it | framework path: `handle_event` hands a `MaximizeChange` to [`WindowManager::adopt_maximize_change`], which uses [`Workspace::adopt_maximized_window`] and [`Workspace::reintegrate_maximized_window`] | `a_window_the_user_maximizes_leaves_the_layout_like_toggle_maximize_makes_it`, `the_user_restoring_the_window_with_its_title_bar_puts_it_back_in_its_tile`, `a_floating_window_the_user_maximizes_leaves_the_floating_windows_and_comes_back_as_a_tile`, `the_window_in_the_monocle_that_the_user_maximizes_leaves_the_monocle`, `a_second_window_the_user_maximizes_puts_the_first_back_in_its_tile` | none | +| What komorebi asked for, reported back by the compositor, changes nothing | framework path: [`WindowManager::adopt_maximize_change`] returns when the window already is, or is not, the workspace's maximized window | `komorebis_own_maximize_echoing_back_changes_nothing`, `toggle_maximize_restores_a_window_the_user_maximized`, `restoring_a_window_that_is_not_maximized_changes_nothing` | none | +| A window that is maximized when komorebi starts or when it opens is the maximized window, and is not asked to leave that state | framework path: [`load_workspace_information`] and the `Show` arm of `handle_event` read [`WindowInfo::maximized`] | `a_window_that_is_maximized_when_komorebi_starts_is_the_maximized_one`, `a_window_that_opens_maximized_is_the_maximized_one` | none | +| A change to a window komorebi does not have is ignored | framework path: [`WindowManager::adopt_maximize_change`] looks the window up in the index of managed windows first | `a_change_for_a_window_komorebi_has_not_taken_in_is_ignored` | none | +| The bridge reports a window as maximized only when KWin has it maximized both ways | test: `isMaximized` in [`bridge.js`] reads KWin's `maximizeMode`, which is 3 for both ways | `bridge.test.js` ("a window maximized one way only is not maximized", "a window the user maximizes or restores is reported, and one maximized one way is not") | none | +| In a real KWin, a window the user maximizes is komorebi's maximized window, the layout does nothing meanwhile, and the window goes back to its tile | VM test | `vm-user-maximize` | none | | A window stays maximized through a retile | framework path: [`Workspace::update`] asks the backend to maximize it again, and moves no container | `a_retile_while_a_window_is_maximized_asks_the_compositor_to_maximize_it_again` | none | | A maximized window that closes takes the maximize with it | framework path: [`Workspace::remove_window`] looks at the maximized window first, which the index of managed windows lists | `a_maximized_window_that_closes_leaves_the_layout_whole` | none | | In a real KWin, the maximized window fills the work area, is on top, and goes back to its tile | VM test | `vm-features` ("the focused window fills the work area", "and is the one on top", "toggled back, it is in its tile again") | none | @@ -1334,7 +1355,7 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | Nothing is moved while the user drags a window | framework path: [`WindowManager::follow_windows_to_their_monitors`] returns at once while [`WindowManager::pending_move_op`] or [`WindowManager::pending_resize_op`] holds a drag | `nothing_is_followed_while_the_user_drags_a_window` | none | | The windows of a monitor that is unplugged are tiled on the monitors that are left | framework path: [`reconcile_display_change`] has [`WindowManager::evacuate_monitor`] move each container and floating window to the monitor that holds it, before it removes the monitor | `the_windows_of_a_monitor_that_goes_are_tiled_on_the_one_that_is_left`, `vm-hotplug` ("tiled inside the screen that is left") | none | | A stack moves with its monitor as a stack | framework path: [`WindowManager::evacuate_monitor`] moves whole containers | `a_stack_goes_with_the_monitor_as_a_stack` | none | -| A monocle or a maximized window of a monitor that goes is not lost | framework path: [`WindowManager::evacuate_monitor`] takes both out of the workspace and puts each in a container on the monitor that is left | `a_monocle_of_a_monitor_that_goes_comes_back_as_a_container_with_the_windows_it_hid`, `a_maximized_window_of_a_monitor_that_goes_is_not_lost` | none | +| A monocle of a monitor that goes comes back as a container, and a maximized window stays maximized | framework path: [`WindowManager::evacuate_monitor`] takes both out of the workspace; the monocle is put in a container on the monitor that is left, and the maximized window becomes the maximized window of its workspace there ([`Workspace::adopt_maximized_window`]), and the one that workspace had goes back to its tile | `a_monocle_of_a_monitor_that_goes_comes_back_as_a_container_with_the_windows_it_hid`, `a_maximized_window_of_a_monitor_that_goes_is_not_lost`, `a_maximized_window_of_a_monitor_that_goes_stays_maximized`, `a_maximized_window_that_comes_to_a_workspace_with_one_takes_its_place` | none | | A monitor that is plugged in again has the settings it had, and none of the windows it had | framework path: [`reconcile_display_change`] keeps the monitor in a cache when it goes, and applies it, less the windows the window manager has elsewhere, when a monitor with its serial number id comes | `a_monitor_that_comes_back_gets_what_was_kept_of_it_and_none_of_the_windows_it_had` | none | | A monitor komorebi has not seen gets workspaces of its own | framework path: [`load_monitor_information`] adds the monitors the window manager does not have | `a_monitor_that_was_never_there_gets_windows_of_its_own` | none | | When KWin reports no output, the window manager keeps the monitors it has | framework path: [`reconcile_display_change`] returns before it removes any | `a_desktop_that_reports_no_monitor_is_left_as_it_was` | none | @@ -1550,6 +1571,9 @@ A window is shown, and ends up on a tile: [`komorebi/tests/monocle.rs`](../../komorebi/tests/monocle.rs), the monocle; [`komorebi/tests/maximize.rs`](../../komorebi/tests/maximize.rs) and [`komorebi/tests/maximize_commands.rs`](../../komorebi/tests/maximize_commands.rs), maximizing; + [`komorebi/tests/user_maximize.rs`](../../komorebi/tests/user_maximize.rs) and + [`komorebi/tests/user_maximize_cases.rs`](../../komorebi/tests/user_maximize_cases.rs), a window + the user maximizes; [`komorebi/tests/manage.rs`](../../komorebi/tests/manage.rs), minimizing, closing, unmanaging and managing the focused window, and pausing; [`komorebi/tests/padding.rs`](../../komorebi/tests/padding.rs), the paddings and the work area @@ -1565,6 +1589,8 @@ A window is shown, and ends up on a tile: strip in a real KWin, with its columns out of view off the screen. - [`nix/tests/vm/suites/features`](../../nix/tests/vm/suites/features/test.py): what is on the screen of a real compositing session, read from screenshots. +- [`nix/tests/vm/suites/user-maximize`](../../nix/tests/vm/suites/user-maximize/test.py): a window + the user maximizes, in a real KWin. - [`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 @@ -1743,6 +1769,10 @@ A window is shown, and ends up on a tile: [`Workspace::maximized_window`]: ../../komorebi/src/workspace.rs [`Workspace::new_maximized_window`]: ../../komorebi/src/workspace.rs [`Workspace::reintegrate_maximized_window`]: ../../komorebi/src/workspace.rs +[`Workspace::adopt_maximized_window`]: ../../komorebi/src/workspace.rs +[`WindowManager::adopt_maximize_change`]: ../../komorebi/src/window_manager.rs +[`WindowInfo::maximized`]: ../../komorebi/src/backend/mod.rs +[`load_workspace_information`]: ../../komorebi/src/desktop.rs [`WindowManager::adjust_workspace_padding`]: ../../komorebi/src/window_manager.rs [`Workspace::apply_window_based_work_area_offset`]: ../../komorebi/src/workspace.rs [`Monitor::update_workspace_globals`]: ../../komorebi/src/monitor.rs diff --git a/docs/dev/DESIGN.md b/docs/dev/DESIGN.md index ba7559a2..fa663e0b 100644 --- a/docs/dev/DESIGN.md +++ b/docs/dev/DESIGN.md @@ -644,3 +644,17 @@ Because after the screen is unlocked the window that is active again is not alwa and komorebi's idea of the focus would stay the one it had. Once a second the bridge compares the window KWin has active with the one it last announced, and announces the active one when they differ. It costs a comparison of two ids a second. + +## Why is a window the user maximizes treated like one komorebi maximized? + +Because the compositor reports both the same way, and komorebi has to follow it. The comment on the +`MaximizeChange` event says that komorebi's own `toggle-maximize` "does this too and finds the window +already as it asked, but the user's title bar does it without komorebi's knowing". A window that +stayed a tile would be asked to move at the next retile: the code that reads the windows that are +open when komorebi starts says a window that is already maximized is "the maximized window, not a tile +that would be asked to leave the maximized state". So +[`WindowManager::adopt_maximize_change`](../../komorebi/src/window_manager.rs) takes the window out of +the layout as `toggle-maximize` makes a window leave it, and what is asked of the layout does +nothing "until it is restored, by `toggle-maximize` or by the user" (the comment in +`process_command`). Because the report is the same either way, one comparison serves both: a window +that is, or is not, already the workspace's maximized window changes nothing. diff --git a/docs/dev/PLATFORM.md b/docs/dev/PLATFORM.md index 795d8e1b..04bebf3d 100644 --- a/docs/dev/PLATFORM.md +++ b/docs/dev/PLATFORM.md @@ -123,12 +123,12 @@ 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 start and the end of every drag -of a window by the user, and every change of the outputs (one that changes resolution or scale, -and the room a panel leaves). KWin has no signal for that room, so the script looks at the -outputs again when a dock window opens, closes or moves, and once a second; it also compares -KWin's active window with the one it last reported once a second. The daemon waits up to 10 -seconds for the first report and does not start without it. +focus, is minimized or brought back, is maximized or restored, moves or changes size, the start +and the end of every drag of a window by the user, and every change of the outputs (one that +changes resolution or scale, and the room a panel leaves). KWin has no signal for that room, so +the script looks at the outputs again when a dock window opens, closes or moves, and once a +second; it also compares KWin's active window with the one it last reported once a second. The +daemon waits up to 10 seconds for the first report and does not start without it. It also watches for the machine waking up and the screen being unlocked, with two signals that are not KWin's ([D-Bus](#d-bus)): logind's `PrepareForSleep` on the system bus, and the lock @@ -167,6 +167,13 @@ checks that the window fills the work area and is on top. The script API cannot so when the pointer follows the focus komorebi invokes KWin's own "Move Mouse to Focus" shortcut, which puts the pointer in the middle of the window KWin has focused. +Some of what the bridge reports is the user's doing, not the answer to a command. KWin raises +`maximizedChanged` for komorebi's maximize and for the user's (the title bar, a double click, a +shortcut) alike, and the bridge reports a window as maximized only when it is maximized both +ways (`maximizeMode` 3): a window maximized in one direction is a restored window to komorebi. +The VM test `vm-user-maximize` maximizes windows with `kdotool windowstate`, in both directions, +and passes against KWin 6.8.1 at time of writing (2026-10-27). + #### When KWin restarts KWin can go away while the session goes on: it crashed, or `kwin_wayland --replace` took its diff --git a/docs/dev/vm-tests.md b/docs/dev/vm-tests.md index 869501bc..087c9656 100644 --- a/docs/dev/vm-tests.md +++ b/docs/dev/vm-tests.md @@ -121,8 +121,9 @@ the run. - `Kde.session(machine, scale=)` attaches to the session node's own Plasma session once its desktop is up, and `shot(name)` returns a screenshot as a Pillow image, keeping `NAME.png` in the output directory. -- `activate`, `minimize` and `close` act on a window through `kdotool`, as the - user would, and `wid_by_class` finds a window by its app id or X11 class. +- `activate`, `minimize`, `maximize`, `unmaximize` and `close` act on a window through + `kdotool`, as the user would (`maximize` does what the title bar's button does, and the + daemon is not asked), and `wid_by_class` finds a window by its app id or X11 class. `Kde.headless(..., xwayland=True)` gives the session XWayland, for X11 clients. - `start_komorebi(*args)` starts the daemon in the session, with the module's diff --git a/docs/index.md b/docs/index.md index 48d3b843..75d8a229 100644 --- a/docs/index.md +++ b/docs/index.md @@ -42,7 +42,8 @@ out of sight and bring one of them to the front, [Floating windows](usage/floating-windows.md) how to take a window out of the layout and work with the floating ones, [Monocle](usage/monocle.md) how to give one window the whole work area, -[Maximizing windows](usage/maximizing-windows.md) how to have KWin maximize one, +[Maximizing windows](usage/maximizing-windows.md) how to have KWin maximize one, and what +komorebi does when you maximize one yourself, [Managing windows](usage/managing-windows.md) how to minimize, close and unmanage the focused window and pause the daemon, and [Padding and work area offsets](usage/padding-and-offsets.md) how to put gaps around the tiles diff --git a/docs/usage/changing-monitors.md b/docs/usage/changing-monitors.md index 9fe8f747..f444563e 100644 --- a/docs/usage/changing-monitors.md +++ b/docs/usage/changing-monitors.md @@ -41,8 +41,9 @@ KWin takes the windows of an output that goes (it is unplugged, or disabled with likes. komorebi takes the monitor's workspaces over there: every container, and every floating window, goes to the workspace with the same number on the monitor KWin put its window on, and the workspaces that changed are tiled again. A [stack](stacking-windows.md) goes as a stack. A -monocle window and a maximized window come as tiles of their own, and the windows the monocle hid -are shown again. +monocle window comes as a tile of its own, and the windows the monocle hid are shown again. A +[maximized window](maximizing-windows.md) stays maximized, on the workspace it goes to; if that +workspace has a maximized window already, it goes back to its tile. A moment after an output goes or comes back (1.5 seconds), komorebi looks at where every window is once more, because KWin moves windows about for a while after the outputs change: the windows diff --git a/docs/usage/maximizing-windows.md b/docs/usage/maximizing-windows.md index 77eb5c12..5797587d 100644 --- a/docs/usage/maximizing-windows.md +++ b/docs/usage/maximizing-windows.md @@ -4,6 +4,8 @@ focus: it takes the work area of its monitor, the panels left alone, and has no padding around it. The window leaves the layout while it is maximized, and the same command restores it and puts it back in a container of its own, at the place in the order of the workspace it was taken from. +A window you maximize yourself, with its title bar, a double click or a shortcut, is treated the +same way: see [A window you maximize](#a-window-you-maximize). ```sh komorebic toggle-maximize @@ -15,14 +17,31 @@ maximized: it covers them. A window that opens meanwhile is added to the layout, container, and has its tile when the maximized window is restored. A window that closes while it is maximized takes the maximize with it, and the other windows are tiled again. -A window in [monocle](monocle.md) that is maximized leaves the monocle. +A window in [monocle](monocle.md) that is maximized leaves the monocle. When the monitor of a +maximized window is unplugged, the window goes to a monitor that is left and stays maximized: see +[Changing monitors](changing-monitors.md#a-monitor-is-unplugged). + +## A window you maximize + +KWin tells komorebi when a window is maximized or restored, whoever did it. A window you maximize +leaves the layout as it does for `toggle-maximize`, and the tiles that were left are not moved +while it is maximized. A window that was floating or in [monocle](monocle.md) leaves that as well. +If another window is maximized already, it goes back to its tile. A window that is already +maximized when komorebi starts, or that opens maximized, is the maximized window from the start. + +When you restore the window, with its title bar, a double click or a shortcut, it goes back in a +container of its own at the place it came from, as if `toggle-maximize` had restored it; a window +that was floating comes back as a tile. `toggle-maximize` restores a window you maximized, too. +Only a window that KWin has maximized both ways counts: a window maximized in one direction only, +which a shortcut can do, is a restored window to komorebi. ## What is left alone -While a window is maximized, the commands that are about the tiles of the layout do nothing, and -the daemon logs that it ignores them: [`move`](../cli/move.md), [`cycle-move`](../cli/cycle-move.md), -the [stack](stacking-windows.md) commands, [`promote`](../cli/promote.md) and the other promote -commands, [`resize-edge`](../cli/resize-edge.md) and [`resize-axis`](../cli/resize-axis.md), +While a window is maximized, by `toggle-maximize` or by you, the commands that are about the tiles +of the layout do nothing, and the daemon logs that it ignores them: [`move`](../cli/move.md), +[`cycle-move`](../cli/cycle-move.md), the [stack](stacking-windows.md) commands, +[`promote`](../cli/promote.md) and the other promote commands, +[`resize-edge`](../cli/resize-edge.md) and [`resize-axis`](../cli/resize-axis.md), [`preselect-direction`](../cli/preselect-direction.md), [`toggle-lock`](../cli/toggle-lock.md), [`toggle-float`](../cli/toggle-float.md), [`toggle-monocle`](../cli/toggle-monocle.md), and the commands that move or send a container to another monitor or workspace, such as diff --git a/komorebi/src/backend/fake.rs b/komorebi/src/backend/fake.rs index 982a1b1b..9d4bcd50 100644 --- a/komorebi/src/backend/fake.rs +++ b/komorebi/src/backend/fake.rs @@ -282,6 +282,7 @@ impl FakeBackend { bottom: 600, }, minimized: false, + maximized: false, normal: true, alive: true, }, @@ -346,8 +347,15 @@ impl FakeBackend { self.state.lock().cursor = Some((x, y)); } - /// Returns true if and only if the window has been maximized by a command and not restored - /// since. + /// Maximizes or restores a window as the user does with its title bar: the compositor does it + /// and nobody asks the window manager, so no command is recorded. A test sends the event that + /// says so. + pub fn user_maximize(&self, id: u32, maximize: bool) { + self.state.lock().set_maximized(id, maximize); + } + + /// Returns true if and only if the window is maximized, by a command or by + /// [`FakeBackend::user_maximize`], and has not been restored since. pub fn is_maximized(&self, id: u32) -> bool { self.state.lock().maximized.contains_key(&id) } @@ -481,6 +489,7 @@ fn permissive_window(id: u32) -> WindowInfo { path: format!("/usr/bin/exe{id}"), rect: Rect::default(), minimized: false, + maximized: false, normal: true, alive: true, } @@ -494,6 +503,10 @@ impl Backend for FakeBackend { .values() .filter(|w| w.alive) .cloned() + .map(|mut w| { + w.maximized = state.maximized.contains_key(&w.id); + w + }) .collect(); windows.sort_by_key(|w| w.id); windows @@ -504,7 +517,11 @@ impl Backend for FakeBackend { if state.permissive && !state.windows.contains_key(&id) { state.windows.insert(id, permissive_window(id)); } - state.windows.get(&id).cloned() + let maximized = state.maximized.contains_key(&id); + state.windows.get(&id).cloned().map(|mut w| { + w.maximized = maximized; + w + }) } fn foreground_window(&self) -> Option { @@ -789,6 +806,26 @@ mod tests { Ok(()) } + #[test] + fn a_window_the_user_maximizes_is_maximized_and_no_command_is_recorded() { + let fake = fake_with(&[1]); + fake.set_rect(1, &tile(100, 200)).unwrap(); + fake.clear_commands(); + + fake.user_maximize(1, true); + + assert!(fake.is_maximized(1)); + assert!(fake.window(1).expect("window 1 was opened").maximized); + assert!(fake.windows()[0].maximized); + assert_eq!(fake.rect_of(1), Some(tile(0, 1920))); + assert!(fake.commands().is_empty()); + + fake.user_maximize(1, false); + + assert!(!fake.window(1).expect("window 1 was opened").maximized); + assert_eq!(fake.rect_of(1), Some(tile(100, 200))); + } + #[test] fn a_command_about_a_window_nobody_opened_is_an_error() { let fake = fake_with(&[1]); diff --git a/komorebi/src/backend/mod.rs b/komorebi/src/backend/mod.rs index 5ba87df8..bea99f8d 100644 --- a/komorebi/src/backend/mod.rs +++ b/komorebi/src/backend/mod.rs @@ -77,6 +77,9 @@ pub struct WindowInfo { pub rect: Rect, /// Whether the window is minimized. pub minimized: bool, + /// Whether the window is maximized, whether by the user (the title bar, a double click, a + /// shortcut) or because komorebi asked ([`Backend::maximize`]). + pub maximized: bool, /// Whether the compositor considers this a normal application window, as opposed to a dialog, /// a splash screen, a utility window, a dock and so on. pub normal: bool, diff --git a/komorebi/src/desktop.rs b/komorebi/src/desktop.rs index f7a8b73e..a78c2256 100644 --- a/komorebi/src/desktop.rs +++ b/komorebi/src/desktop.rs @@ -287,7 +287,9 @@ pub fn update_monitor_work_areas(wm: &mut WindowManager) -> eyre::Result<()> { /// the one in front; a window on every desktop goes to the one in front. The monitor gets as many /// workspaces as that takes. A window that is minimized, that komorebi does not manage /// ([`Window::should_manage`]: not a normal window, or one the rules ignore), or that is on no -/// monitor is left alone. Nothing is moved: tiling is [`WindowManager::retile_all`]'s job. +/// monitor is left alone. A window that is already maximized is the workspace's maximized window +/// ([`Workspace::adopt_maximized_window`](crate::workspace::Workspace::adopt_maximized_window)), not +/// a container. Nothing is moved: tiling is [`WindowManager::retile_all`]'s job. /// /// [`Backend::current_workspaces`]: crate::backend::Backend::current_workspaces /// [`Backend::window_workspace`]: crate::backend::Backend::window_workspace @@ -312,6 +314,8 @@ pub fn update_monitor_work_areas(wm: &mut WindowManager) -> eyre::Result<()> { /// fake.open_window(1, "foot", "foot", "a terminal"); /// fake.open_window(2, "foot", "foot", "a dialog"); /// fake.set_normal(2, false); +/// fake.open_window(3, "foot", "foot", "a maximized terminal"); +/// fake.user_maximize(3, true); /// /// let (_sender, events) = crossbeam_channel::bounded(1); /// let socket = PathBuf::from(format!("/tmp/komorebi-windows-doc-{}.sock", std::process::id())); @@ -325,6 +329,8 @@ pub fn update_monitor_work_areas(wm: &mut WindowManager) -> eyre::Result<()> { /// assert!(workspace.contains_window(1)); /// assert!(!workspace.contains_window(2)); /// assert_eq!(wm.focused_workspace_idx()?, 0); +/// assert_eq!(workspace.maximized_window.map(|window| window.id), Some(3)); +/// assert_eq!(workspace.containers().len(), 1); /// # std::fs::remove_file(socket)?; /// # Ok::<(), color_eyre::eyre::Report>(()) /// ``` @@ -377,6 +383,14 @@ pub fn load_workspace_information(wm: &mut WindowManager) -> eyre::Result<()> { container.windows_mut().push_back(window); workspace.containers_mut().push_back(container); valid_window_count += 1; + + // already maximized when komorebi started: it is the maximized window, not a tile that + // would be asked to leave the maximized state + if info.maximized + && let Err(error) = workspace.adopt_maximized_window(info.id) + { + tracing::warn!("could not take the maximized window {}: {error}", info.id); + } } } diff --git a/komorebi/src/kwin/bridge.js b/komorebi/src/kwin/bridge.js index be56812e..71d62e4a 100644 --- a/komorebi/src/kwin/bridge.js +++ b/komorebi/src/kwin/bridge.js @@ -51,17 +51,17 @@ /** * What the bridge sends, as the one argument of `Event`. `emit` adds `seq` to each, which counts * them from 1. `snapshot` is everything on the desktop, sent once, when the script starts; an - * `activated` with no `id` means no window has the focus; `caption` is a window's new title; - * `output` says that a window is on another output, by the output's name (empty for none), with - * the frame the window has there; `screens` says which outputs there are, with their geometry and - * work area, `desktops` which desktops a window is on now, `desktop_list` which desktops there - * are, and `current_desktops` which desktop each output shows, each sent when it is not what was - * last sent; `move_resize_started` and `move_resize_finished` are the start and the end of a drag - * of a window by the user, with its frame, and at the end where the pointer is and the frame the - * user last 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. + * `activated` with no `id` means no window has the focus; `maximized` says whether a window is + * maximized both ways now, whoever maximized it; `caption` is a window's new title; `output` says + * that a window is on another output, by the output's name (empty for none), with the frame the + * window has there; `screens` says which outputs there are, with their geometry and work area, + * `desktops` which desktops a window is on now, `desktop_list` which desktops there are, and + * `current_desktops` which desktop each output shows, each sent when it is not what was last sent; + * `move_resize_started` and `move_resize_finished` are the start and the end of a drag of a window + * by the user, with its frame, and at the end where the pointer is and the frame the user last + * 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[], @@ -71,6 +71,7 @@ * @typedef {{ type: "removed", id: string }} Removed * @typedef {{ type: "activated", id: string | null }} Activated * @typedef {{ type: "minimized", id: string, v: boolean }} Minimized + * @typedef {{ type: "maximized", id: string, v: boolean }} Maximized * @typedef {{ type: "geometry", id: string, geo: Rect }} Geometry * @typedef {{ type: "screens", screens: Screen[] }} Screens * @typedef {{ type: "output", id: string, geo: Rect, output: string }} OutputChange @@ -87,8 +88,8 @@ * @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 | Screens | OutputChange - * | Caption | Desktops | DesktopList | CurrentDesktops | MoveResizeStarted + * @typedef {Snapshot | Added | Removed | Activated | Minimized | Maximized | Geometry | Screens + * | OutputChange | Caption | Desktops | DesktopList | CurrentDesktops | MoveResizeStarted * | MoveResizeFinished | MoveResizeStep | CursorAnswer | Failed} BridgeEvent */ @@ -448,6 +449,10 @@ function track(w, announce) { w.outputChanged.connect(function () { emit("output", { id: id, geo: rect(w.frameGeometry), output: w.output ? String(w.output.name) : "" }); }); + // by the title bar, a double click, a shortcut: or by komorebi's own `maximize`, which it knows + w.maximizedChanged.connect(function () { + emit("maximized", { id: id, v: isMaximized(w) }); + }); w.captionChanged.connect(function () { emit("caption", { id: id, caption: String(w.caption) }); }); diff --git a/komorebi/src/kwin/bridge.test.js b/komorebi/src/kwin/bridge.test.js index 977957cb..3dfbdb1a 100644 --- a/komorebi/src/kwin/bridge.test.js +++ b/komorebi/src/kwin/bridge.test.js @@ -59,8 +59,10 @@ function geometry(x, y, width, height) { // A window. `id` becomes its `internalId`, which is a QUuid in KWin: an object, not a string. // Setting `minimized`, `frameGeometry` or `desktops` raises the signal KWin raises, and // `closeWindow` closes it once it is in a KWin. `setMaximize` sets `maximizeMode` the way KWin's -// does and records what it was asked in `maximizations`. `place` is where KWin puts the window -// when it is asked for a frame: where it was asked, unless a test says otherwise. +// does, raises `maximizedChanged` when the mode changes, and records what it was asked in +// `maximizations`: the user's title bar calls it too, so a test maximizes a window for the user by +// calling it. `place` is where KWin puts the window when it is asked for a frame: where it was +// asked, unless a test says otherwise. function window({ id, minimized = false, @@ -88,7 +90,11 @@ function window({ maximizations: [], setMaximize: (vertically, horizontally) => { w.maximizations.push([vertically, horizontally]); - w.maximizeMode = (vertically ? 1 : 0) | (horizontally ? 2 : 0); + const mode = (vertically ? 1 : 0) | (horizontally ? 2 : 0); + if (mode !== w.maximizeMode) { + w.maximizeMode = mode; + w.maximizedChanged.emit(); + } }, move: false, resize: false, @@ -96,6 +102,7 @@ function window({ frameGeometryChanged: new Signal(), minimizedChanged: new Signal(), outputChanged: new Signal(), + maximizedChanged: new Signal(), captionChanged: new Signal(), desktopsChanged: new Signal(), interactiveMoveResizeStarted: new Signal(), @@ -636,6 +643,25 @@ test("a window maximized one way only is not maximized", () => { ); }); +test("a window the user maximizes or restores is reported, and one maximized one way is not", () => { + const w = window({ id: "{w}" }); + const k = kwin({ windows: [w] }); + + // the title bar's button maximizes both ways and restores both ways; a shortcut can do one way + w.setMaximize(true, true); + w.setMaximize(true, false); + w.setMaximize(false, false); + + assert.deepStrictEqual( + k.events().slice(1).map((e) => [e.type, e.id, e.v]), + [ + ["maximized", "{w}", true], + ["maximized", "{w}", false], + ["maximized", "{w}", false], + ], + ); +}); + test("a title change is reported with the title the window has now", () => { const w = window({ id: "{beta}", caption: "beta" }); const k = kwin({ windows: [w] }); diff --git a/komorebi/src/kwin/fixtures/commands.json b/komorebi/src/kwin/fixtures/commands.json index 18f92e86..19afaf44 100644 --- a/komorebi/src/kwin/fixtures/commands.json +++ b/komorebi/src/kwin/fixtures/commands.json @@ -24,7 +24,7 @@ } }, { - "after_seq": 15, + "after_seq": 17, "batch": { "batch": 3, "cmds": [ @@ -34,7 +34,7 @@ } }, { - "after_seq": 20, + "after_seq": 22, "batch": { "batch": 4, "cmds": [ diff --git a/komorebi/src/kwin/fixtures/events.json b/komorebi/src/kwin/fixtures/events.json index eee0bbd3..c929f72a 100644 --- a/komorebi/src/kwin/fixtures/events.json +++ b/komorebi/src/kwin/fixtures/events.json @@ -54,9 +54,11 @@ {"type": "activated", "seq": 11, "id": "{0e5a1c3b-0000-4000-8000-00000000000a}"}, {"type": "minimized", "seq": 12, "id": "{0e5a1c3b-0000-4000-8000-00000000000a}", "v": true}, {"type": "minimized", "seq": 13, "id": "{0e5a1c3b-0000-4000-8000-00000000000a}", "v": false}, - {"type": "removed", "seq": 14, "id": "{c4b8a2f0-0000-4000-8000-00000000000c}"}, + {"type": "maximized", "seq": 14, "id": "{0e5a1c3b-0000-4000-8000-00000000000a}", "v": true}, + {"type": "maximized", "seq": 15, "id": "{0e5a1c3b-0000-4000-8000-00000000000a}", "v": false}, + {"type": "removed", "seq": 16, "id": "{c4b8a2f0-0000-4000-8000-00000000000c}"}, { - "type": "failed", "seq": 15, "batch": 2, + "type": "failed", "seq": 17, "batch": 2, "cmds": [ { "op": "geo", "id": "{7f3d9e21-0000-4000-8000-00000000000b}", "x": 960, "y": 0, @@ -65,54 +67,54 @@ ] }, { - "type": "desktops", "seq": 16, "id": "{0e5a1c3b-0000-4000-8000-00000000000a}", + "type": "desktops", "seq": 18, "id": "{0e5a1c3b-0000-4000-8000-00000000000a}", "desktops": ["desktop-2"] }, - {"type": "current_desktops", "seq": 17, "current": [{"output": "DP-1", "id": "desktop-2"}]}, + {"type": "current_desktops", "seq": 19, "current": [{"output": "DP-1", "id": "desktop-2"}]}, { - "type": "desktop_list", "seq": 18, + "type": "desktop_list", "seq": 20, "desktops": [ {"id": "desktop-1", "name": "Desktop 1"}, {"id": "desktop-2", "name": "Desktop 2"}, {"id": "desktop-3", "name": "mail"} ] }, { - "type": "desktops", "seq": 19, "id": "{0e5a1c3b-0000-4000-8000-00000000000a}", + "type": "desktops", "seq": 21, "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": 22, "current": [{"output": "DP-1", "id": "desktop-1"}]}, { - "type": "move_resize_started", "seq": 21, "id": "{0e5a1c3b-0000-4000-8000-00000000000a}", + "type": "move_resize_started", "seq": 23, "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}", + "type": "geometry", "seq": 24, "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}", + "type": "move_resize_finished", "seq": 25, "id": "{0e5a1c3b-0000-4000-8000-00000000000a}", "geo": {"x": 40, "y": 30, "w": 960, "h": 1050}, "requested": null, "cursor": {"x": 1500, "y": 600} }, { - "type": "move_resize_started", "seq": 24, "id": "{0e5a1c3b-0000-4000-8000-00000000000a}", + "type": "move_resize_started", "seq": 26, "id": "{0e5a1c3b-0000-4000-8000-00000000000a}", "move": false, "resize": true, "geo": {"x": 40, "y": 30, "w": 960, "h": 1050} }, { - "type": "move_resize_step", "seq": 25, "id": "{0e5a1c3b-0000-4000-8000-00000000000a}", + "type": "move_resize_step", "seq": 27, "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}", + "type": "geometry", "seq": 28, "id": "{0e5a1c3b-0000-4000-8000-00000000000a}", "geo": {"x": 40, "y": 30, "w": 1040, "h": 1050} }, { - "type": "move_resize_finished", "seq": 27, "id": "{0e5a1c3b-0000-4000-8000-00000000000a}", + "type": "move_resize_finished", "seq": 29, "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} }, { - "type": "screens", "seq": 28, + "type": "screens", "seq": 30, "screens": [ { "name": "DP-1", "manufacturer": "ACME", "model": "M1", "serial": "S1", @@ -122,7 +124,7 @@ ] }, { - "type": "output", "seq": 29, "id": "{0e5a1c3b-0000-4000-8000-00000000000a}", + "type": "output", "seq": 31, "id": "{0e5a1c3b-0000-4000-8000-00000000000a}", "geo": {"x": 40, "y": 30, "w": 1040, "h": 1050}, "output": "DP-2" } ] diff --git a/komorebi/src/kwin/kwin-api.d.ts b/komorebi/src/kwin/kwin-api.d.ts index 53745733..e047f51f 100644 --- a/komorebi/src/kwin/kwin-api.d.ts +++ b/komorebi/src/kwin/kwin-api.d.ts @@ -97,6 +97,7 @@ interface KWinWindow { readonly frameGeometryChanged: Signal<[oldGeometry: QRectF]>; readonly minimizedChanged: Signal; readonly outputChanged: Signal; + readonly maximizedChanged: Signal; readonly captionChanged: Signal; readonly desktopsChanged: Signal; /** The user took hold of the window with the pointer, to move it (`move`) or resize it diff --git a/komorebi/src/kwin/state.rs b/komorebi/src/kwin/state.rs index 7947b157..8422230e 100644 --- a/komorebi/src/kwin/state.rs +++ b/komorebi/src/kwin/state.rs @@ -610,6 +610,7 @@ impl Table { path, rect: rect(&w["geo"]), minimized: w["minimized"].as_bool().unwrap_or(false), + maximized: w["maximized"].as_bool().unwrap_or(false), normal: false, alive: true, }; @@ -674,6 +675,8 @@ impl Table { /// with no `id`, took it away from every window. /// - `minimized`: a window was minimized or brought back ([`WindowManagerEvent::Minimize`], /// [`WindowManagerEvent::Restore`]). + /// - `maximized`: a window was maximized or restored, by the user or by komorebi's own + /// command ([`WindowManagerEvent::MaximizeChange`]). /// - `output`: a window is on another output. It carries the frame the window has now, which /// goes with the output, since the two events arrive in no fixed order /// ([`WindowManagerEvent::OutputChange`]). @@ -718,6 +721,7 @@ impl Table { Some("removed") => self.on_removed(event, now), Some("activated") => self.on_activated(event), Some("minimized") => self.on_minimized(event), + Some("maximized") => self.on_maximized(event), Some("move_resize_step") => self.on_drag_step(event), Some("output") => self.on_output(event), Some("caption") => self.on_caption(event), @@ -987,6 +991,28 @@ impl Table { ))] } + fn on_maximized(&mut self, event: &Value) -> Vec { + let maximized = event["v"].as_bool().unwrap_or(false); + let Some(id) = self.id_of(event) else { + return vec![]; + }; + + let Some(entry) = self.windows.get_mut(&id) else { + return vec![]; + }; + entry.info.maximized = maximized; + + if !entry.info.normal { + return vec![]; + } + + vec![Output::Event(WindowManagerEvent::MaximizeChange( + kwin(KWinNotification::WindowMaximizedChanged), + Window::from(id), + maximized, + ))] + } + fn on_caption(&mut self, event: &Value) -> Vec { let Some(id) = self.id_of(event) else { return vec![]; @@ -1357,7 +1383,7 @@ mod tests { // what komorebi asks for next (fixtures/commands.json, batch 3): the editor on the // second workspace, and the output showing it - if event["seq"] == 15 { + if event["seq"] == 17 { let monitor = t.monitors()[0].id; t.window_workspace_commands(1, 1).unwrap(); t.switch_commands(monitor, 1).unwrap(); @@ -1366,7 +1392,7 @@ mod tests { // the end of the resize is where the user took the edge, and the window's frame is // the one KWin has: the frame at the end of the session is the one the editor has on // the other output - if event["seq"] == 27 { + if event["seq"] == 29 { assert_eq!( t.drag_end(1).unwrap().right, 1100, @@ -1411,6 +1437,8 @@ mod tests { "activated -> FocusChange 1", "minimized -> Minimize 1", "minimized -> Restore 1", + "maximized -> MaximizeChange 1", + "maximized -> MaximizeChange 1", "removed -> ", "failed -> ", // komorebi's own move and switch, coming back @@ -1635,6 +1663,53 @@ mod tests { ); } + #[test] + fn maximizing_and_restoring_are_events_and_are_remembered() { + let mut t = table(vec![win("a", &["d1"])]); + let now = Instant::now(); + assert!(!t.window(1).unwrap().maximized); + + assert_eq!( + events(&t.handle(&json!({ "type": "maximized", "id": "a", "v": true }), now)), + vec!["MaximizeChange 1"] + ); + assert!(t.window(1).unwrap().maximized); + assert_eq!( + events(&t.handle(&json!({ "type": "maximized", "id": "a", "v": false }), now)), + vec!["MaximizeChange 1"] + ); + assert!(!t.window(1).unwrap().maximized); + } + + #[test] + fn a_window_that_is_maximized_when_the_script_starts_is_maximized() { + let mut maximized = win("a", &["d1"]); + maximized["maximized"] = json!(true); + let t = table(vec![maximized, win("b", &["d1"])]); + + assert!(t.window(1).unwrap().maximized); + assert!(!t.window(2).unwrap().maximized); + } + + #[test] + fn a_dialog_that_is_maximized_is_remembered_and_raises_nothing() { + let mut dialog = win("dlg", &["d1"]); + dialog["normal"] = json!(false); + let mut t = table(vec![dialog]); + + let out = t.handle( + &json!({ "type": "maximized", "id": "dlg", "v": true }), + Instant::now(), + ); + + assert!(out.is_empty()); + assert!(t.window(1).unwrap().maximized); + assert!( + t.windows().is_empty(), + "it is not a window komorebi may manage" + ); + } + #[test] fn geometry_updates_the_rect_silently() { let mut t = table(vec![win("a", &["d1"])]); diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index cc165804..2cbc246a 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -108,11 +108,12 @@ //! **MonocleFocusBehaviour** sets what focusing in a direction does meanwhile, cycle the //! monocle or nothing, and **ToggleMonocleFocusBehaviour** switches between the two. //! - **ToggleMaximize** has the compositor maximize the focused window, which leaves the layout, -//! or restores it and puts it back in its tile ([`WindowManager::toggle_maximize`]). While a -//! window is maximized, the messages about the tiles (**MoveWindow**, **CycleMoveWindow**, the -//! stack messages, the resize, promote and preselect messages, **ToggleLock**, **ToggleFloat**, -//! **ToggleMonocle** and the ones that send a container to another monitor or workspace) are -//! ignored. +//! or restores it and puts it back in its tile ([`WindowManager::toggle_maximize`]). A window +//! the user maximizes leaves the layout the same way +//! ([`WindowManager::adopt_maximize_change`]). While a window is maximized, by either, the +//! messages about the tiles (**MoveWindow**, **CycleMoveWindow**, the stack messages, the +//! resize, promote and preselect messages, **ToggleLock**, **ToggleFloat**, **ToggleMonocle** +//! and the ones that send a container to another monitor or workspace) are ignored. //! - **WorkspacePadding** and **ContainerPadding** set the paddings of a workspace given by the //! index of its monitor and its own, **NamedWorkspacePadding** and //! **NamedWorkspaceContainerPadding** those of the workspace with a name @@ -432,9 +433,9 @@ impl WindowManager { tracing::info!("processing command: {message}"); } - // a window that is maximized (by `toggle-maximize`) is not in the layout, and what is - // asked of the layout is not asked of it: nothing happens until it is restored, by - // `toggle-maximize` + // a window that is maximized (by `toggle-maximize`, or by the user with its title bar) is + // not in the layout, and what is asked of the layout is not asked of it: nothing happens + // until it is restored, by `toggle-maximize` or by the user if is_layout_command(&message) && self .focused_workspace() diff --git a/komorebi/src/process_event.rs b/komorebi/src/process_event.rs index e3a5465c..532df225 100644 --- a/komorebi/src/process_event.rs +++ b/komorebi/src/process_event.rs @@ -30,6 +30,12 @@ //! - **Minimize**: a window the user minimized leaves its workspace and the rest are tiled //! again; **Restore** brings it back in a container of its own. A minimize of a window komorebi //! hid ([`struct@HIDDEN_WINDOWS`]) is not the user's, and changes nothing. +//! - **MaximizeChange**: a window the compositor maximized, which komorebi did not ask for (the +//! title bar, a double click, a shortcut), becomes the workspace's maximized window, as +//! `ToggleMaximize` makes the focused window, and one the user restored goes back in a container +//! of its own ([`WindowManager::adopt_maximize_change`]). The maximize and the restore that +//! `ToggleMaximize` asks for come back as this event too, and change nothing. A window that +//! opens maximized is taken the same way, after its Show. //! - **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 @@ -296,6 +302,9 @@ impl WindowManager { WindowManagerEvent::OutputChange(..) => { self.follow_window_to_its_monitor(window)?; } + WindowManagerEvent::MaximizeChange(_, _, maximized) => { + self.adopt_maximize_change(window_id, maximized)?; + } 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.) @@ -430,6 +439,12 @@ impl WindowManager { } } + // an app that remembers it was maximized opens that way + if backend().window(window_id).is_some_and(|w| w.maximized) { + self.update_known_window_ids(); + self.adopt_maximize_change(window_id, true)?; + } + if workspace_contains_window { let mut monocle_window_event = false; if let Some(ref monocle) = monocle_container diff --git a/komorebi/src/reconcile.rs b/komorebi/src/reconcile.rs index 0debc19f..edd2ba45 100644 --- a/komorebi/src/reconcile.rs +++ b/komorebi/src/reconcile.rs @@ -28,9 +28,10 @@ //! | The windows of a monitor that is gone are tiled on the monitors that are left | [`WindowManager::evacuate_monitor`], called by the monitor reconciliator | `tests/follow_output.rs::the_windows_of_a_monitor_that_goes_are_tiled_on_the_one_that_is_left_and_come_back_with_it` | //! | A stack moves as a stack | [`WindowManager::follow_windows_to_their_monitors`] and [`WindowManager::evacuate_monitor`] move whole containers | `tests/hotplug.rs::a_stack_goes_with_the_monitor_as_a_stack` | //! | Nothing is moved while the user drags a window: the drag decides where that window goes | [`WindowManager::follow_windows_to_their_monitors`] returns at once | `tests/follow_output.rs::nothing_is_followed_while_the_user_drags_a_window` | -//! | A monocle or a maximized window of a monitor that is gone is not lost | [`WindowManager::evacuate_monitor`] takes both out of the workspace and puts each in a container | `tests/hotplug.rs::a_monocle_of_a_monitor_that_goes_comes_back_as_a_container_with_the_windows_it_hid`, `tests/hotplug.rs::a_maximized_window_of_a_monitor_that_goes_is_not_lost` | +//! | A monocle of a monitor that is gone comes back as a container, and a maximized window stays maximized | [`WindowManager::evacuate_monitor`] takes both out of the workspace: the monocle is put in a container, the maximized window becomes the maximized window of the workspace it goes to ([`Workspace::adopt_maximized_window`]) | `tests/hotplug.rs::a_monocle_of_a_monitor_that_goes_comes_back_as_a_container_with_the_windows_it_hid`, `tests/hotplug.rs::a_maximized_window_of_a_monitor_that_goes_is_not_lost`, `tests/hotplug.rs::a_maximized_window_of_a_monitor_that_goes_stays_maximized`, `tests/hotplug.rs::a_maximized_window_that_comes_to_a_workspace_with_one_takes_its_place` | //! //! [`reconcile_display_change`]: crate::monitor_reconciliator::reconcile_display_change +//! [`Workspace::adopt_maximized_window`]: crate::workspace::Workspace::adopt_maximized_window #![deny(missing_docs)] @@ -238,17 +239,21 @@ impl WindowManager { /// /// Each container and floating window goes to the workspace of the same number on the monitor /// that now has it, or on the first monitor that is left when that is not clear yet. A monocle - /// and a maximized window come back as ordinary containers. The monitor itself stays in the - /// list, empty, for the caller to remove. Nothing is done when there is no such monitor, or no - /// other. + /// comes back as an ordinary container, with the windows it hid shown again. A maximized window + /// stays maximized, as the maximized window of the workspace it goes to; the one that workspace + /// had goes back to its tile. The monitor itself stays in the list, empty, for the caller to + /// remove. Nothing is done when there is no such monitor, or no other. /// /// # Errors /// /// Returns an error if a monitor or workspace it moves windows between is not there, or if a - /// maximized window cannot be put in a container. + /// maximized window cannot be put in a container. A maximized window that cannot be kept + /// maximized is logged, and stays a tile. /// /// Covered by `tests/hotplug.rs::a_stack_goes_with_the_monitor_as_a_stack`, - /// `tests/hotplug.rs::the_windows_of_a_monitor_that_goes_are_tiled_on_the_one_that_is_left` and + /// `tests/hotplug.rs::the_windows_of_a_monitor_that_goes_are_tiled_on_the_one_that_is_left`, + /// `tests/hotplug.rs::a_maximized_window_of_a_monitor_that_goes_stays_maximized`, + /// `tests/hotplug.rs::a_maximized_window_that_comes_to_a_workspace_with_one_takes_its_place` and /// `tests/follow_output.rs::the_windows_of_a_monitor_that_goes_are_tiled_on_the_one_that_is_left_and_come_back_with_it`. pub fn evacuate_monitor(&mut self, serial_number_id: &str) -> eyre::Result<()> { let Some(gone) = self @@ -342,14 +347,20 @@ impl WindowManager { )?; } - // a maximized window is a window of an ordinary container on the monitor it goes to + // already maximized, and the compositor keeps it so on the monitor it has gone to if let Some(window) = maximized { + let id = window.id; let mut container = crate::container::Container::default(); container.add_window(&window)?; place( self, Some(window), - Box::new(move |workspace| workspace.containers_mut().push_back(container)), + Box::new(move |workspace| { + workspace.containers_mut().push_back(container); + if let Err(error) = workspace.adopt_maximized_window(id) { + tracing::warn!("could not keep window {id} maximized: {error}"); + } + }), )?; } } diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index 6683e85b..b006aff9 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -1556,6 +1556,57 @@ impl WindowManager { workspace.reintegrate_maximized_window() } + /// Follows the compositor when it maximizes or restores a window: a window the user maximized + /// (the title bar, a double click, a shortcut) leaves the layout as `toggle-maximize` makes a + /// window leave it, and a window the user restored is put back in a container of its own, where + /// it was. + /// + /// The window may be on any workspace, and that workspace is tiled again when it is the one in + /// front. A window komorebi does not have is ignored. So is a change komorebi made itself, + /// which the compositor reports too: the workspace is already as the change leaves it. + /// + /// # Errors + /// + /// See [`Workspace::adopt_maximized_window`], [`Workspace::reintegrate_maximized_window`] and + /// [`Monitor::update_focused_workspace`]. + #[tracing::instrument(skip(self))] + pub fn adopt_maximize_change(&mut self, window_id: u32, maximized: bool) -> eyre::Result<()> { + let Some((m_idx, w_idx)) = self.known_window_ids.get(&window_id).cloned() else { + return Ok(()); + }; + + let offset = self.work_area_offset; + let Some(monitor) = self.monitors_mut().get_mut(m_idx) else { + return Ok(()); + }; + let Some(workspace) = monitor.workspaces_mut().get_mut(w_idx) else { + return Ok(()); + }; + + let is_the_maximized_one = workspace + .maximized_window + .is_some_and(|w| w.id == window_id); + + if maximized == is_the_maximized_one { + return Ok(()); + } + + if maximized { + tracing::info!("window {window_id} was maximized by the user"); + workspace.adopt_maximized_window(window_id)?; + } else { + tracing::info!("window {window_id} was restored by the user"); + workspace.reintegrate_maximized_window()?; + } + + if monitor.focused_workspace_idx() == w_idx { + monitor.update_focused_workspace(offset)?; + } + self.update_known_window_ids(); + + Ok(()) + } + /// Takes the focused container out of the layout of the focused workspace and makes it the /// monocle container, which the next tiling gives the whole work area, and hides the windows /// of the other containers diff --git a/komorebi/src/window_manager_event.rs b/komorebi/src/window_manager_event.rs index db970922..770c153c 100644 --- a/komorebi/src/window_manager_event.rs +++ b/komorebi/src/window_manager_event.rs @@ -41,6 +41,8 @@ pub enum KWinNotification { WindowMinimized, /// `window.minimizedChanged` to false WindowRestored, + /// `window.maximizedChanged` + WindowMaximizedChanged, /// `window.outputChanged` WindowOutputChanged, /// `window.captionChanged` @@ -80,6 +82,10 @@ pub enum WindowManagerEvent { /// A window is on another output than it was: the user moved it (a shortcut), or KWin did when /// an output went away or came back. Where it is now is what the window reports. OutputChange(SystemNotification, Window), + /// A window was maximized (`true`) or restored (`false`) by the compositor: komorebi's own + /// `toggle-maximize` does this too and finds the window already as it asked, but the user's + /// title bar does it without komorebi's knowing + MaximizeChange(SystemNotification, Window, bool), /// The user asked komorebi to manage the window (`ManageFocusedWindow`) Manage(Window), /// The user asked komorebi to stop managing the window (`UnmanageFocusedWindow`) @@ -116,6 +122,7 @@ impl WindowManagerEvent { | WindowManagerEvent::Minimize(_, window) | WindowManagerEvent::Restore(_, window) | WindowManagerEvent::TitleUpdate(_, window) + | WindowManagerEvent::MaximizeChange(_, window, _) | WindowManagerEvent::OutputChange(_, window) | WindowManagerEvent::Manage(window) | WindowManagerEvent::Unmanage(window) @@ -146,6 +153,7 @@ impl WindowManagerEvent { | WindowManagerEvent::Minimize(n, _) | WindowManagerEvent::Restore(n, _) | WindowManagerEvent::TitleUpdate(n, _) + | WindowManagerEvent::MaximizeChange(n, _, _) | WindowManagerEvent::OutputChange(n, _) | WindowManagerEvent::MoveStart(n, _) | WindowManagerEvent::MoveEnd(n, _) @@ -206,4 +214,21 @@ mod tests { assert_eq!(event.window_id(), None); assert_eq!(event.notification(), "WorkspaceChanged"); } + + #[test] + fn a_maximize_change_says_whether_the_window_was_maximized_or_restored() { + let event = WindowManagerEvent::MaximizeChange( + SystemNotification::KWin(KWinNotification::WindowMaximizedChanged), + Window::from(302), + true, + ); + + assert_eq!(event.window_id(), Some(302)); + assert_eq!(event.notification(), "WindowMaximizedChanged"); + assert_eq!(event.to_string(), "MaximizeChange"); + assert!(matches!( + event, + WindowManagerEvent::MaximizeChange(_, _, true) + )); + } } diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index 65dfc9df..6944d0b0 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -1293,6 +1293,101 @@ impl Workspace { Ok(()) } + /// Takes a window the compositor has maximized without komorebi's being asked (the user's title + /// bar, a double click, a shortcut) out of the layout, as [`Workspace::new_maximized_window`] + /// does for the focused window: it becomes the workspace's maximized window, with the index it + /// goes back to, until it is restored by `toggle-maximize` or by the user. The window is + /// already maximized, so it is not asked to be. + /// + /// A window that is the maximized window already changes nothing. A workspace has room for one + /// maximized window: the one it had goes back in the layout first, and a window that was + /// floating or in the monocle container leaves it. The window goes back to the index of the + /// focused container when it was floating, to the one the monocle container was taken from when + /// it was in the monocle, and to its container's index otherwise. A stack or a monocle container + /// that the window leaves shows the window that has the focus in it now, and hides the others. + /// + /// # Errors + /// + /// - The workspace has no such window in its floating windows, its monocle container or its + /// containers. + /// - The maximized window it had cannot be put back, for one of the reasons + /// [`Workspace::reintegrate_maximized_window`] gives. + pub fn adopt_maximized_window(&mut self, window_id: u32) -> eyre::Result<()> { + if self.maximized_window.is_some_and(|w| w.id == window_id) { + return Ok(()); + } + + // there is room for one: the one that was is a tile again + if self.maximized_window.is_some() { + self.reintegrate_maximized_window()?; + } + + let focused_idx = self.focused_container_idx(); + + if let Some(window) = self.remove_floating_window(window_id) { + self.maximized_window = Option::from(window); + self.maximized_window_restore_idx = Option::from(focused_idx); + return Ok(()); + } + + let monocle_restore_idx = self.monocle_container_restore_idx; + if let Some(monocle_container) = &mut self.monocle_container + && let Some(window_idx) = monocle_container + .windows() + .iter() + .position(|window| window.id == window_id) + { + let window = monocle_container + .remove_window_by_idx(window_idx) + .ok_or_eyre("there is no window")?; + + if monocle_container.windows().is_empty() { + self.monocle_container = None; + self.monocle_container_restore_idx = None; + } else { + monocle_container.load_focused_window()?; + } + + self.maximized_window = Option::from(window); + self.maximized_window_restore_idx = monocle_restore_idx; + return Ok(()); + } + + let container_idx = self + .container_idx_for_window(window_id) + .ok_or_eyre("there is no such window to maximize")?; + + let container = self + .containers_mut() + .get_mut(container_idx) + .ok_or_eyre("there is no container")?; + + let window_idx = container + .windows() + .iter() + .position(|window| window.id == window_id) + .ok_or_eyre("there is no window")?; + + let window = container + .remove_window_by_idx(window_idx) + .ok_or_eyre("there is no window")?; + + if container.windows().is_empty() { + // as for `toggle-maximize`: the index is kept free for the window to come back to + self.containers_mut().remove(container_idx); + if self.resize_dimensions.get(container_idx).is_some() { + self.resize_dimensions.remove(container_idx); + } + } else { + container.load_focused_window()?; + } + + self.maximized_window = Option::from(window); + self.maximized_window_restore_idx = Option::from(container_idx); + + Ok(()) + } + /// The maximized window is a tile again, in a container of its own at the index it was taken /// from, and the compositor gives it back the frame it had /// diff --git a/komorebi/tests/hotplug.rs b/komorebi/tests/hotplug.rs index d67e514e..c282c6aa 100644 --- a/komorebi/tests/hotplug.rs +++ b/komorebi/tests/hotplug.rs @@ -344,3 +344,72 @@ fn a_maximized_window_of_a_monitor_that_goes_is_not_lost() { ); } } + +#[test] +fn a_maximized_window_of_a_monitor_that_goes_stays_maximized() { + let (fake, mut wm) = desktop_of(&["Test-S", "Test-T"]); + open_on(&fake, &mut wm, 50_951, 0); + for id in [50_952, 50_953] { + open_on(&fake, &mut wm, id, 1920); + } + wm.focus_monitor(1).unwrap(); + with_backend(fake.clone(), || { + wm.process_command(SocketMessage::ToggleMaximize, Vec::new()) + }) + .unwrap(); + let maximized = wm.monitors()[1] + .focused_workspace() + .unwrap() + .maximized_window + .map(|window| window.id) + .expect("there is no maximized window"); + + fake.remove_monitor(51); + for id in [50_952, 50_953] { + fake.move_window_by_user(id, somewhere_in(100)); + } + with_backend(fake.clone(), || reconcile_display_change(&mut wm)).unwrap(); + + assert_eq!(wm.monitors().len(), 1); + let workspace = wm.monitors()[0].focused_workspace().unwrap(); + assert_eq!(workspace.maximized_window.map(|w| w.id), Some(maximized)); + assert!(fake.is_maximized(maximized), "it was restored on the way"); + assert_eq!( + containers_on(&wm, 0), + 2, + "the windows it was not maximized with are tiles, and the maximized window is none" + ); +} + +#[test] +fn a_maximized_window_that_comes_to_a_workspace_with_one_takes_its_place() { + let (fake, mut wm) = desktop_of(&["Test-U", "Test-V"]); + open_on(&fake, &mut wm, 50_961, 0); + open_on(&fake, &mut wm, 50_962, 1920); + for monitor in [0, 1] { + wm.focus_monitor(monitor).unwrap(); + with_backend(fake.clone(), || { + wm.process_command(SocketMessage::ToggleMaximize, Vec::new()) + }) + .unwrap(); + } + assert!(fake.is_maximized(50_961) && fake.is_maximized(50_962)); + + fake.remove_monitor(51); + fake.move_window_by_user(50_962, somewhere_in(100)); + with_backend(fake.clone(), || reconcile_display_change(&mut wm)).unwrap(); + + let workspace = wm.monitors()[0].focused_workspace().unwrap(); + assert_eq!( + workspace.maximized_window.map(|w| w.id), + Some(50_962), + "the window that came is the maximized one" + ); + assert!(fake.is_maximized(50_962)); + assert!( + !fake.is_maximized(50_961), + "the window that was maximized is restored" + ); + assert_eq!(containers_on(&wm, 0), 1, "it is a tile again"); + assert!(workspace.container_idx_for_window(50_961).is_some()); +} diff --git a/komorebi/tests/user_maximize.rs b/komorebi/tests/user_maximize.rs new file mode 100644 index 00000000..d4282e83 --- /dev/null +++ b/komorebi/tests/user_maximize.rs @@ -0,0 +1,237 @@ +//! A window the user maximizes (with its title bar, or by opening it maximized), against an +//! in-memory desktop. +//! +//! The compositor does the maximizing and reports it. komorebi takes the window out of the layout +//! as `komorebic toggle-maximize` does, leaves the layout alone while it is maximized, and puts it +//! back in its tile when it is restored, by the user or by komorebi. +//! +//! Window ids are in the 30_000s. + +use komorebi::backend::fake::Command; +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::core::OperationDirection; +use komorebi::core::Rect; +use komorebi::core::SocketMessage; +use komorebi::window::Window; +use komorebi::window_manager::WindowManager; +use komorebi::window_manager_event::KWinNotification; +use komorebi::window_manager_event::SystemNotification; +use komorebi::window_manager_event::WindowManagerEvent; +use std::sync::Arc; + +fn added(id: u32) -> WindowManagerEvent { + WindowManagerEvent::Show( + SystemNotification::KWin(KWinNotification::WindowAdded), + Window::from(id), + ) +} + +fn 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/kmf-{}-{}.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 tiled(first: u32, count: u32) -> (Arc, WindowManager) { + let (fake, mut wm) = desktop(); + with_backend(fake.clone(), || { + for id in first..first + count { + fake.open_window(id, "foot", "foot", &format!("terminal {id}")); + wm.process_event(added(id)).unwrap(); + } + }); + (fake, wm) +} + +fn command(fake: &Arc, wm: &mut WindowManager, message: SocketMessage) { + with_backend(fake.clone(), || wm.process_command(message, Vec::new())).unwrap(); +} + +fn work_area() -> Rect { + Rect { + left: 0, + top: 0, + right: 1920, + bottom: 1050, + } +} + +fn maximized(id: u32, on: bool) -> WindowManagerEvent { + WindowManagerEvent::MaximizeChange( + SystemNotification::KWin(KWinNotification::WindowMaximizedChanged), + Window::from(id), + on, + ) +} + +/// the user maximizes a window with its title bar: the compositor does it, and says so +fn user_maximizes(fake: &Arc, wm: &mut WindowManager, id: u32, on: bool) { + fake.user_maximize(id, on); + with_backend(fake.clone(), || wm.process_event(maximized(id, on))).unwrap(); +} + +#[test] +fn a_window_the_user_maximizes_leaves_the_layout_like_toggle_maximize_makes_it() { + let (fake, mut wm) = tiled(30_061, 3); + + user_maximizes(&fake, &mut wm, 30_062, true); + + let workspace = wm.focused_workspace().unwrap(); + assert_eq!(workspace.maximized_window.map(|w| w.id), Some(30_062)); + assert_eq!(workspace.containers().len(), 2, "its tile is gone"); + assert!(fake.is_maximized(30_062)); + assert_eq!(fake.rect_of(30_062).unwrap(), work_area()); + + // the others fill the room it left, and do not overlap + let (a, b) = (fake.rect_of(30_061).unwrap(), fake.rect_of(30_063).unwrap()); + assert!(a.right > 800 && b.right > 800, "{a:?} {b:?}"); +} + +#[test] +fn nothing_that_is_about_the_layout_happens_while_a_window_is_maximized() { + let (fake, mut wm) = tiled(30_071, 3); + user_maximizes(&fake, &mut wm, 30_072, true); + let rects: Vec = [30_071, 30_072, 30_073] + .iter() + .map(|id| fake.rect_of(*id).unwrap()) + .collect(); + fake.clear_commands(); + + for message in [ + SocketMessage::MoveWindow(OperationDirection::Left), + SocketMessage::MoveWindow(OperationDirection::Right), + SocketMessage::StackWindow(OperationDirection::Left), + SocketMessage::UnstackWindow, + SocketMessage::StackAll, + SocketMessage::Promote, + SocketMessage::ToggleFloat, + SocketMessage::ToggleMonocle, + SocketMessage::ToggleLock, + SocketMessage::SendContainerToWorkspaceNumber(1), + SocketMessage::MoveContainerToWorkspaceNumber(1), + ] { + let name = message.to_string(); + command(&fake, &mut wm, message); + + let workspace = wm.focused_workspace().unwrap(); + assert_eq!( + workspace.maximized_window.map(|w| w.id), + Some(30_072), + "{name} took the window out of its maximized state" + ); + assert_eq!(workspace.containers().len(), 2, "{name} changed the tiles"); + assert!(workspace.floating_windows().is_empty(), "{name}"); + assert!(workspace.monocle_container.is_none(), "{name}"); + assert!(fake.is_maximized(30_072), "{name}"); + } + + let now: Vec = [30_071, 30_072, 30_073] + .iter() + .map(|id| fake.rect_of(*id).unwrap()) + .collect(); + assert_eq!(rects, now, "a window moved"); + assert!( + !fake + .commands() + .iter() + .any(|c| matches!(c, Command::SetRect(..) | Command::SetWindowWorkspace(..))), + "{:?}", + fake.commands() + ); +} + +#[test] +fn toggle_maximize_restores_a_window_the_user_maximized() { + let (fake, mut wm) = tiled(30_081, 3); + let before: Vec = (30_081..30_084) + .map(|id| fake.rect_of(id).unwrap()) + .collect(); + user_maximizes(&fake, &mut wm, 30_083, true); + + command(&fake, &mut wm, SocketMessage::ToggleMaximize); + // the compositor says the window was restored; komorebi did that itself + with_backend(fake.clone(), || wm.process_event(maximized(30_083, false))).unwrap(); + + let workspace = wm.focused_workspace().unwrap(); + assert!(workspace.maximized_window.is_none()); + assert_eq!(workspace.containers().len(), 3); + assert!(!fake.is_maximized(30_083)); + let after: Vec = (30_081..30_084) + .map(|id| fake.rect_of(id).unwrap()) + .collect(); + assert_eq!(before, after); +} + +#[test] +fn the_user_restoring_the_window_with_its_title_bar_puts_it_back_in_its_tile() { + let (fake, mut wm) = tiled(30_091, 3); + let before: Vec = (30_091..30_094) + .map(|id| fake.rect_of(id).unwrap()) + .collect(); + user_maximizes(&fake, &mut wm, 30_091, true); + assert_eq!(wm.focused_workspace().unwrap().containers().len(), 2); + + user_maximizes(&fake, &mut wm, 30_091, false); + + let workspace = wm.focused_workspace().unwrap(); + assert!(workspace.maximized_window.is_none()); + assert_eq!(workspace.containers().len(), 3); + let after: Vec = (30_091..30_094) + .map(|id| fake.rect_of(id).unwrap()) + .collect(); + assert_eq!(before, after, "every tile is where it was"); + + // and the commands work again + command( + &fake, + &mut wm, + SocketMessage::MoveWindow(OperationDirection::Right), + ); + let moved: Vec = (30_091..30_094) + .map(|id| fake.rect_of(id).unwrap()) + .collect(); + assert_ne!(before, moved, "the move did nothing after the restore"); +} + +#[test] +fn komorebis_own_maximize_echoing_back_changes_nothing() { + let (fake, mut wm) = tiled(30_101, 2); + command(&fake, &mut wm, SocketMessage::ToggleMaximize); + let workspace = wm.focused_workspace().unwrap(); + assert_eq!(workspace.containers().len(), 1); + + // the compositor reports the maximize komorebi asked for + with_backend(fake.clone(), || wm.process_event(maximized(30_102, true))).unwrap(); + + let workspace = wm.focused_workspace().unwrap(); + assert_eq!(workspace.maximized_window.map(|w| w.id), Some(30_102)); + assert_eq!(workspace.containers().len(), 1); +} + +#[test] +fn a_window_that_opens_maximized_is_the_maximized_one() { + let (fake, mut wm) = tiled(30_111, 2); + + fake.open_window(30_113, "firefox", "firefox", "web"); + fake.user_maximize(30_113, true); + with_backend(fake.clone(), || wm.process_event(added(30_113))).unwrap(); + + let workspace = wm.focused_workspace().unwrap(); + assert_eq!(workspace.maximized_window.map(|w| w.id), Some(30_113)); + assert_eq!(workspace.containers().len(), 2, "the two tiles that were"); + assert!(fake.is_maximized(30_113)); +} diff --git a/komorebi/tests/user_maximize_cases.rs b/komorebi/tests/user_maximize_cases.rs new file mode 100644 index 00000000..beb7b5ec --- /dev/null +++ b/komorebi/tests/user_maximize_cases.rs @@ -0,0 +1,225 @@ +//! Where a window the user maximizes can come from and go to, against an in-memory desktop: a +//! floating window, the window of the monocle, a second window, a window komorebi has not seen, and +//! a window that was already maximized when komorebi started. +//! +//! `user_maximize.rs` has the plain case. Window ids are in the 59_000s. + +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 activated(id: u32) -> WindowManagerEvent { + WindowManagerEvent::FocusChange( + SystemNotification::KWin(KWinNotification::WindowActivated), + Window::from(id), + ) +} + +fn maximize_change(id: u32, on: bool) -> WindowManagerEvent { + WindowManagerEvent::MaximizeChange( + SystemNotification::KWin(KWinNotification::WindowMaximizedChanged), + Window::from(id), + on, + ) +} + +fn socket() -> std::path::PathBuf { + // 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); + std::path::PathBuf::from(format!( + "/tmp/kmu-{}-{}.sock", + std::process::id(), + NEXT.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + )) +} + +/// A window manager over a fake desktop with one 1920x1080 monitor (1920x1050 without the panel), +/// and a window for each of `ids`, opened in that order +fn desktop_with(ids: &[u32]) -> (Arc, WindowManager) { + let fake = Arc::new(FakeBackend::with_one_monitor()); + let (_sender, receiver) = crossbeam_channel::bounded(1); + + let wm = with_backend(fake.clone(), || { + let mut wm = WindowManager::new(receiver, Some(socket())).unwrap(); + wm.init().unwrap(); + for &id in ids { + fake.open_window(id, "foot", "foot", &format!("terminal {id}")); + wm.process_event(added(id)).unwrap(); + } + wm + }); + + (fake, wm) +} + +fn send(fake: &Arc, wm: &mut WindowManager, message: SocketMessage) { + with_backend(fake.clone(), || wm.process_command(message, Vec::new())).unwrap(); +} + +fn event(fake: &Arc, wm: &mut WindowManager, event: WindowManagerEvent) { + with_backend(fake.clone(), || wm.process_event(event)).unwrap(); +} + +/// the compositor maximizes or restores a window for the user, and says so +fn user_maximizes(fake: &Arc, wm: &mut WindowManager, id: u32, on: bool) { + fake.user_maximize(id, on); + event(fake, wm, maximize_change(id, on)); +} + +/// give a window the focus the way the user does, which is what `toggle-float` and the others read +fn focus(fake: &Arc, wm: &mut WindowManager, id: u32) { + fake.set_foreground(Some(id)); + event(fake, wm, activated(id)); +} + +/// The windows the layout tiles, in the order of their containers +fn tiled(wm: &WindowManager) -> Vec { + wm.focused_workspace() + .unwrap() + .containers() + .iter() + .map(|container| container.focused_window().unwrap().id) + .collect() +} + +fn maximized(wm: &WindowManager) -> Option { + wm.focused_workspace() + .unwrap() + .maximized_window + .map(|window| window.id) +} + +fn work_area() -> Rect { + Rect { + left: 0, + top: 0, + right: 1920, + bottom: 1050, + } +} + +#[test] +fn a_floating_window_the_user_maximizes_leaves_the_floating_windows_and_comes_back_as_a_tile() { + let (fake, mut wm) = desktop_with(&[59_001, 59_002, 59_003]); + focus(&fake, &mut wm, 59_002); + send(&fake, &mut wm, SocketMessage::ToggleFloat); + let workspace = wm.focused_workspace().unwrap(); + assert_eq!(workspace.floating_windows().len(), 1); + assert_eq!(tiled(&wm), [59_001, 59_003]); + + user_maximizes(&fake, &mut wm, 59_002, true); + + let workspace = wm.focused_workspace().unwrap(); + assert_eq!(maximized(&wm), Some(59_002)); + assert!(workspace.floating_windows().is_empty()); + assert_eq!(tiled(&wm), [59_001, 59_003]); + + user_maximizes(&fake, &mut wm, 59_002, false); + + // it is a tile now: the layer it was on is not one it can go back to + assert_eq!(maximized(&wm), None); + assert!( + wm.focused_workspace() + .unwrap() + .floating_windows() + .is_empty() + ); + assert!(tiled(&wm).contains(&59_002)); + assert_eq!(tiled(&wm).len(), 3); +} + +#[test] +fn the_window_in_the_monocle_that_the_user_maximizes_leaves_the_monocle() { + let (fake, mut wm) = desktop_with(&[59_011, 59_012, 59_013]); + focus(&fake, &mut wm, 59_012); + send(&fake, &mut wm, SocketMessage::ToggleMonocle); + assert!(wm.focused_workspace().unwrap().monocle_container.is_some()); + + user_maximizes(&fake, &mut wm, 59_012, true); + + let workspace = wm.focused_workspace().unwrap(); + assert!(workspace.monocle_container.is_none()); + assert_eq!(maximized(&wm), Some(59_012)); + assert_eq!(tiled(&wm), [59_011, 59_013]); + + user_maximizes(&fake, &mut wm, 59_012, false); + + assert_eq!(maximized(&wm), None); + assert_eq!(tiled(&wm), [59_011, 59_012, 59_013]); +} + +#[test] +fn a_second_window_the_user_maximizes_puts_the_first_back_in_its_tile() { + let (fake, mut wm) = desktop_with(&[59_021, 59_022, 59_023]); + user_maximizes(&fake, &mut wm, 59_021, true); + assert_eq!(tiled(&wm), [59_022, 59_023]); + + user_maximizes(&fake, &mut wm, 59_023, true); + + assert_eq!(maximized(&wm), Some(59_023)); + assert_eq!(tiled(&wm), [59_021, 59_022]); + assert!(!fake.is_maximized(59_021), "the first one was restored"); + assert!(fake.is_maximized(59_023)); + assert_eq!(fake.rect_of(59_023), Some(work_area())); +} + +#[test] +fn a_change_for_a_window_komorebi_has_not_taken_in_is_ignored() { + let (fake, mut wm) = desktop_with(&[59_031, 59_032]); + // open, and a normal window, but never shown to komorebi + fake.open_window(59_033, "foot", "foot", "late"); + + user_maximizes(&fake, &mut wm, 59_033, true); + + assert_eq!(maximized(&wm), None); + assert_eq!(tiled(&wm), [59_031, 59_032]); +} + +#[test] +fn restoring_a_window_that_is_not_maximized_changes_nothing() { + let (fake, mut wm) = desktop_with(&[59_041, 59_042]); + let before = (fake.rect_of(59_041), fake.rect_of(59_042)); + fake.clear_commands(); + + event(&fake, &mut wm, maximize_change(59_041, false)); + + assert_eq!(maximized(&wm), None); + assert_eq!(tiled(&wm), [59_041, 59_042]); + assert_eq!((fake.rect_of(59_041), fake.rect_of(59_042)), before); + assert!(fake.commands().is_empty()); +} + +#[test] +fn a_window_that_is_maximized_when_komorebi_starts_is_the_maximized_one() { + let fake = Arc::new(FakeBackend::with_one_monitor()); + for id in [59_051, 59_052, 59_053] { + fake.open_window(id, "foot", "foot", &format!("terminal {id}")); + } + fake.user_maximize(59_052, true); + let (_sender, receiver) = crossbeam_channel::bounded(1); + + let wm = with_backend(fake.clone(), || { + let mut wm = WindowManager::new(receiver, Some(socket())).unwrap(); + wm.init().unwrap(); + wm + }); + + assert_eq!(maximized(&wm), Some(59_052)); + assert_eq!(tiled(&wm), [59_051, 59_053]); + assert!(fake.is_maximized(59_052)); + assert_eq!(fake.rect_of(59_052), Some(work_area())); +} diff --git a/nix/tests/vm/lib/komorebi_vm/daemon.py b/nix/tests/vm/lib/komorebi_vm/daemon.py index 5546bfc2..22b6ec41 100644 --- a/nix/tests/vm/lib/komorebi_vm/daemon.py +++ b/nix/tests/vm/lib/komorebi_vm/daemon.py @@ -25,7 +25,7 @@ class Event: """A window event the daemon handled.""" kind: str - """The event (`Show`, `Destroy`, `FocusChange`, `Minimize`, `Restore`).""" + """The event (`Show`, `Destroy`, `FocusChange`, `Minimize`, `Restore`, `MaximizeChange`).""" window: int """The daemon's id for the window.""" notification: str diff --git a/nix/tests/vm/lib/komorebi_vm/kde.py b/nix/tests/vm/lib/komorebi_vm/kde.py index b38115dd..c5b02ad3 100644 --- a/nix/tests/vm/lib/komorebi_vm/kde.py +++ b/nix/tests/vm/lib/komorebi_vm/kde.py @@ -542,6 +542,19 @@ class Kde: """Asks KWin to minimize the window, as its title bar button would.""" self.sh(f"kdotool windowminimize {shlex.quote(wid)}") + def maximize(self, wid: str) -> None: + """Asks KWin to maximize the window both ways, as its title bar button would. + + It is the user's maximize: the daemon is not asked, and learns of it from KWin. + """ + for state in ("MAXIMIZED_VERT", "MAXIMIZED_HORZ"): + self.sh(f"kdotool windowstate --add {state} {shlex.quote(wid)}") + + def unmaximize(self, wid: str) -> None: + """Asks KWin to restore the window from being maximized, as its title bar button would.""" + for state in ("MAXIMIZED_VERT", "MAXIMIZED_HORZ"): + self.sh(f"kdotool windowstate --remove {state} {shlex.quote(wid)}") + def close(self, wid: str) -> None: """Asks KWin to close the window, as its title bar button would.""" self.sh(f"kdotool windowclose {shlex.quote(wid)}") diff --git a/nix/tests/vm/lib/tests/test_kde.py b/nix/tests/vm/lib/tests/test_kde.py index c3227bc0..b3cc9dec 100644 --- a/nix/tests/vm/lib/tests/test_kde.py +++ b/nix/tests/vm/lib/tests/test_kde.py @@ -271,11 +271,17 @@ def test_window_actions_go_through_kdotool_inside_the_session(machine: FakeMachi kde.activate("{a}") kde.minimize("{a}") + kde.maximize("{a}") + kde.unmaximize("{a}") kde.close("{a}") assert [inner(command) for command in machine.commands] == [ "kdotool windowactivate '{a}'", "kdotool windowminimize '{a}'", + "kdotool windowstate --add MAXIMIZED_VERT '{a}'", + "kdotool windowstate --add MAXIMIZED_HORZ '{a}'", + "kdotool windowstate --remove MAXIMIZED_VERT '{a}'", + "kdotool windowstate --remove MAXIMIZED_HORZ '{a}'", "kdotool windowclose '{a}'", ] assert all("WAYLAND_DISPLAY=wayland-main" in command for command in machine.commands) diff --git a/nix/tests/vm/suites/user-maximize/default.nix b/nix/tests/vm/suites/user-maximize/default.nix new file mode 100644 index 00000000..bb57ac90 --- /dev/null +++ b/nix/tests/vm/suites/user-maximize/default.nix @@ -0,0 +1,5 @@ +{ + tier = "fast"; + kind = "headless"; + timeoutMinutes = 10; +} diff --git a/nix/tests/vm/suites/user-maximize/test.py b/nix/tests/vm/suites/user-maximize/test.py new file mode 100644 index 00000000..02332bcd --- /dev/null +++ b/nix/tests/vm/suites/user-maximize/test.py @@ -0,0 +1,168 @@ +# A window the user maximizes, in a real headless KWin. The user's title bar maximizes a window +# without asking komorebi: KWin does it and reports it, and komorebi has to take the window out of +# the layout as it does for `toggle-maximize`, leave the layout alone while the window is maximized, +# and put the window back in its tile when it is restored, by the user or by komorebi. +# `komorebi/tests/user_maximize.rs` checks what the window manager does against the fake; this +# checks that KWin reports the user's maximize, and the restore, the way komorebi reads them. +import json +import shlex +import time +from typing import Any + +from komorebi_vm import Checks, Kde, Rect, daemon + +W, H = 1920, 1080 +# The windows are tiled with a gap of 10 pixels around the workspace and between the tiles: a tile +# has padding, and a maximized window has none. The windows are not animated. +CONFIG = "/tmp/user-maximize-config.json" + +start_all() +machine.wait_for_unit("multi-user.target") +machine.wait_for_unit("user@1000.service") + +checks = Checks() +kde = Kde.headless(machine, "main", size=(W, H), scale=SCALE) + + +def workspace() -> dict[str, Any]: + return kde.state()["monitors"]["elements"][0]["workspaces"]["elements"][0] + + +def containers() -> int: + return len(workspace()["containers"]["elements"]) + + +def maximized_title() -> str | None: + window = workspace()["maximized_window"] + return None if window is None else window["details"]["title"] + + +def fills(r: Rect) -> bool: + """The work area is the whole output: a virtual KWin has no panel.""" + return r.w >= W - 40 and r.h >= H - 80 + + +def rect_of(title: str) -> Rect: + return kde.rect(kde.wid(title)) + + +def open_window(title: str) -> None: + kde.spawn(f"foot -T {title} sleep 3000") + kde.wait_for(lambda: kde.wid(title) != "", timeout=30) + + +print("== three windows, tiled") +kde.sh( + "printf %s " + + shlex.quote( + json.dumps( + { + "default_workspace_padding": 10, + "default_container_padding": 10, + "animation": {"enabled": False}, + } + ) + ) + + f" > {CONFIG}" +) +kde.start_komorebi("--config", CONFIG) +kde.wait_for(lambda: kde.run("komorebic monitor-information")[0] == 0, timeout=30) +for title in ("um-a", "um-b", "um-c"): + open_window(title) +checks.check("komorebi has three tiles", kde.wait_for(lambda: containers() == 3, timeout=20)) +# The bridge asks again for the position of a window that is not where komorebi put it for a second +# after it did (PLATFORM.md, "How clients answer a frame"), which would put a window that is +# maximized in that second back where its tile was: wait that second out, as a person would. +kde.wait_for(lambda: kde.focused_title() == "um-c", timeout=20) +time.sleep(3 * SCALE) +tiles = {title: rect_of(title) for title in ("um-a", "um-b", "um-c")} +print(f" the tiles are {tiles}") + +print("== 1. the user maximizes a window with its title bar") +kde.maximize(kde.wid("um-b")) +checks.check( + "komorebi has it as its maximized window", + kde.wait_for(lambda: maximized_title() == "um-b", timeout=20), +) +checks.check( + f"it fills the work area ({rect_of('um-b')})", + kde.wait_for(lambda: fills(rect_of("um-b")), timeout=10), +) +checks.check("and its tile is gone: two are left", containers() == 2) +checks.check( + "komorebi handled it as a change of the window's maximized state", + any( + event.kind == "MaximizeChange" and event.notification == "WindowMaximizedChanged" + for event in daemon.events(kde.komorebi_log()) + ), +) +checks.check("it still has all three windows", kde.managed_all() == 3) + +print("== 2. what is asked of the layout does nothing") +beside = {title: rect_of(title) for title in ("um-a", "um-c")} +for command in [ + "move left", + "move right", + "move up", + "move down", + "stack left", + "stack right", + "unstack", + "cycle-move next", + "promote", + "toggle-float", + "toggle-monocle", + "resize-edge left increase", + "send-to-workspace 1", + "move-to-workspace 1", + "toggle-lock", +]: + kde.komorebic(*command.split()) +time.sleep(1 * SCALE) +checks.check( + "it is still maximized, and still komorebi's maximized window", + fills(rect_of("um-b")) and maximized_title() == "um-b", +) +checks.check( + "the others did not move, and nothing floats or is in the monocle", + {title: rect_of(title) for title in ("um-a", "um-c")} == beside + and containers() == 2 + and workspace()["floating_windows"]["elements"] == [] + and workspace()["monocle_container"] is None, +) +checks.check( + "komorebi noted that it ignored them", + "ignoring" in kde.komorebi_log() and "the window in front is maximized" in kde.komorebi_log(), +) + +print("== 3. toggle-maximize restores it") +kde.komorebic("toggle-maximize") +checks.check( + f"it is back in its tile ({tiles['um-b']})", + kde.wait_for(lambda: rect_of("um-b") == tiles["um-b"], timeout=20), +) +checks.check( + "and nothing is maximized", + maximized_title() is None and containers() == 3, +) + +print("== 4. the user restores it with the title bar") +kde.maximize(kde.wid("um-c")) +checks.check( + "maximized again", + kde.wait_for(lambda: maximized_title() == "um-c" and containers() == 2, timeout=20), +) +kde.unmaximize(kde.wid("um-c")) +checks.check( + f"restored by the user, it is back in its tile ({tiles['um-c']})", + kde.wait_for(lambda: rect_of("um-c") == tiles["um-c"], timeout=20), +) +checks.check( + "and nothing is maximized", + kde.wait_for(lambda: maximized_title() is None and containers() == 3, timeout=10), +) + +kde.komorebic("stop") +kde.wait_for(lambda: not kde.komorebi_running()) +kde.stop() +checks.finish()