feat(wm): stack out of sight on a parking desktop

A container has one tile, so the windows of a stack that are not in front have
to be out of sight. KWin has nothing a script can set to hide a window except a
virtual desktop nobody looks at, which the first spike measured to cost no focus
change where minimizing a window cost two. Backend::hide takes a window out of
sight and Backend::restore brings it back; the KWin backend parks the window on
a desktop named komorebi-park, which the table keeps out of the workspaces, and
remembers where each hidden window came from so that it is still on its
workspace.

KWin saves a desktop in kwinrc as soon as it is made, so komorebi removes the
parking desktop when it stops, after the windows are back, and the first
snapshot of the next run finds one a killed run left, sends its windows home and
removes it. The windows komorebi hid are recorded, so that a minimize the
compositor reports for one is not mistaken for the user's.

komorebic stack, unstack, stack-all and unstack-all stack and unstack windows.
The window container behavior and the float override decide whether a window
that opens joins the focused container or floats, for every workspace or for
one. vm-stacks stacks windows in a headless KWin, shows a workspace and goes
back, stops, and kills the daemon with a window parked.
This commit is contained in:
LGUG2Z committed 2026-10-28 07:20:37 -07:00
1 parent ac265de1e3
commit 331db681e2
41 files changed
+3234 -94

No files matched your search

+12 -1
View File
@@ -66,7 +66,8 @@ without a checkout of the toolchain.
the vocabulary the window manager is written in (`core`), the `Backend` trait
through which it reaches a compositor and the in-memory desktop the tests use
(`backend`), the backend that reaches KWin through a script it runs and edits
the one setting of KWin's it needs in the user's `kwinrc` (`kwin`),
the one setting of KWin's it needs in the user's `kwinrc` and the parking desktop
it hides the back of a stack on (`kwin`),
the model of what it tiles (`monitor`, `workspace`, `container`, `window`), the
window manager that keeps the model (`window_manager`), loads it from the
backend (`desktop`) and changes it when the compositor reports an event
@@ -139,6 +140,12 @@ reports that a window was shown, closed, focused, minimized or restored, and
tiles the workspace in front again. A window open at startup goes to the
workspace whose desktop it is on.
A container with more than one window is a stack: the layout gives it one tile,
and the window in front is in sight. The others are hidden, which on KWin means
moved to one more virtual desktop, `komorebi-park`, that nobody looks at and that
is not a workspace. The daemon makes it when it first needs it, removes it when
it stops, and removes one that a run that did not stop left behind.
Everything else reaches the daemon as a message on its socket: one JSON
`SocketMessage` per line, handled one at a time with the window manager
locked. A message that asks a question is answered on the same connection. A
@@ -171,6 +178,10 @@ the previous or the last workspace, `workspace-name` names a workspace for
At the edge of a monitor, `focus` and `move` cross to the monitor on that side;
`focus-monitor`, `move-to-monitor`, `send-to-monitor` and their kind work on the
monitors, and `eager-focus` finds the window of an application wherever it is.
`stack` puts the focused window and the one next to it in one stack, `unstack`
takes it out again, and `stack-all` and `unstack-all` do it for a whole
workspace. `toggle-window-container-behaviour` makes a window that opens join
the focused stack, and `toggle-float-override` makes it float.
A program such as a status bar can subscribe to the daemon's notifications: it
listens on a socket of its own, and after each event and each message, the
+10
View File
@@ -0,0 +1,10 @@
```text
Stack all windows on the focused workspace
Usage: stack-all
Options:
-h, --help
Print help
```
+14
View File
@@ -0,0 +1,14 @@
```text
Stack the focused window in the specified direction
Usage: stack <OPERATION_DIRECTION>
Arguments:
<OPERATION_DIRECTION>
[possible values: left, right, up, down]
Options:
-h, --help
Print help
```
+10
View File
@@ -0,0 +1,10 @@
```text
Enable or disable float override, which makes it so every new window opens in floating mode
Usage: toggle-float-override
Options:
-h, --help
Print help
```
@@ -0,0 +1,10 @@
```text
Toggle the behavior for new windows (stacking or dynamic tiling)
Usage: toggle-window-container-behaviour
Options:
-h, --help
Print help
```
@@ -0,0 +1,12 @@
```text
Enable or disable float override, which makes it so every new window opens in floating mode, for the
currently focused workspace. If there was no override value set for the workspace previously it
takes the opposite of the global value
Usage: toggle-workspace-float-override
Options:
-h, --help
Print help
```
@@ -0,0 +1,11 @@
```text
Toggle the behavior for new windows (stacking or dynamic tiling) for currently focused workspace. If
there was no behavior set for the workspace previously it takes the opposite of the global value
Usage: toggle-workspace-window-container-behaviour
Options:
-h, --help
Print help
```
+10
View File
@@ -0,0 +1,10 @@
```text
Unstack all windows in the focused container
Usage: unstack-all
Options:
-h, --help
Print help
```
+10
View File
@@ -0,0 +1,10 @@
```text
Unstack the focused window
Usage: unstack
Options:
-h, --help
Print help
```
+131 -14
View File
@@ -8,9 +8,9 @@ tested, without one.
This page describes that trait, who implements and calls it, where each of its rules is
enforced, the model of the desktop the window manager tiles, the backend that reaches KWin,
how an event about a window becomes a tile, how workspaces are the compositor's desktops, how
a message on the daemon's socket is answered, how subscribers are notified of both, what the
orders a message gives do, and how the NixOS module runs the daemon. It grows with the code:
each part of the daemon that is added has its place here.
a stack hides its windows, how a message on the daemon's socket is answered, how subscribers
are notified of both, what the orders a message gives do, and how the NixOS module runs the
daemon. It grows with the code: each part of the daemon that is added has its place here.
## Vocabulary
@@ -27,6 +27,13 @@ each part of the daemon that is added has its place here.
desktop of its own.
- **Container**: what a layout places. It gets one tile, and every window in it is put on
that tile.
- **Stack**: a container with more than one window. It has one tile, and the window in front
(the container's focused window) is in sight; the others are hidden.
- **Hidden window**: a window of a stack that is not in front, which komorebi has taken out of
sight ([`Backend::hide`]) and recorded in [`HIDDEN_WINDOWS`]. It is alive, not minimized, and
on its workspace.
- **Parking desktop**: the virtual desktop, named `komorebi-park`, that the KWin backend hides
windows on. It is not a workspace.
- **Layout**: the arrangement (BSP, columns, rows, ...) that turns a work area and a
number of containers into one rectangle, a **tile**, for each container.
- **Event**: what the compositor reports about a window: it was shown, destroyed, given
@@ -87,9 +94,9 @@ The desktop, as the window manager sees it, is two lists and a pointer:
- **The pointer**, a position if the compositor says where it is, and the **focus**, the id
of the window that has it.
A command is one of: move and resize a window, focus it, raise it, minimize it or bring it
back, close it, put the pointer in the middle of a rectangle, make desktops for the
workspaces, show a workspace on a monitor, and put a window on a workspace. The workspace a
A command is one of: move and resize a window, focus it, raise it, hide it or restore it,
minimize it or bring it back, close it, put the pointer in the middle of a rectangle, make
desktops for the workspaces, show a workspace on a monitor, and put a window on a workspace. The workspace a
window is on, and the one each monitor shows, are queries.
The window manager tiles a tree of four levels, each level a [`Ring`]: a list with one
@@ -103,8 +110,10 @@ the same thing at every level.
own, whether it takes the monitor's window-based offset, its containers, in order, and its
floating windows, which are in no container and which the layout does not tile.
- A **container** ([`Container`]) has its windows. A new window gets a container of its
own. A container can be locked, which keeps it at its index while others are inserted,
removed or swapped around it.
own, unless the window container behavior says to put it in the focused one. With more than
one window it is a stack: the focused window is in front and the others are hidden. A
container can be locked, which keeps it at its index while others are inserted, removed or
swapped around it.
- A **window** ([`Window`]) is a `Copy` handle that carries only the compositor's id.
Everything else about the window, and every change to it, goes through the backend.
@@ -224,6 +233,54 @@ window put on another desktop by something else (the window menu's "Move to Desk
and move come back from KWin as the same reports; the table records them when the command is
sent ([`Table::switch_commands`], [`Table::window_workspace_commands`]), so they raise nothing.
## Stacks
A container has one tile, so when it has more than one window the others have to be out of
sight, and out of the way of the pointer and the focus: the window manager hides them
([`Window::hide`]). Minimizing them would not do. KWin reports a minimize as the user's, and
the windows would be taken for ones the user does not want tiled. What komorebi uses is the one
thing KWin has that hides a window and leaves it alone: a virtual desktop nobody looks at, the
parking desktop. The reasons are in
[DESIGN.md](DESIGN.md#why-are-the-windows-behind-the-front-one-of-a-stack-moved-to-a-parking-desktop).
A container keeps its front window in sync with what is in sight ([`Container::add_window`],
[`Container::load_focused_window`]): the window that is added or focused is shown, and every
other one is hidden. Operations that change which window is in front, or which container a
window is in, end with that call: stacking and unstacking ([`Workspace::move_window_to_container`],
[`Workspace::new_container_for_focused_window`]), a window that closes
([`Workspace::remove_window`], which brings the next one forward and focuses it), a window that
is floated, and a focus change to a window that is behind ([`Workspace::focus_container_by_window`]).
[`Window::hide`] puts the window's id in [`HIDDEN_WINDOWS`] before it asks the backend, and
[`Window::restore`] takes it out, so that when the compositor reports something about the window
because of the hide the window manager knows who did it. A `Minimize` for a window in the set is
not the user's and changes nothing. On the way out, [`WindowManager::stop`] and the daemon's
`SIGINT` and `SIGTERM` handler restore every window in the set before the backend shuts down
([`WindowManager::restore_all_windows`]).
The KWin backend hides a window by putting it on the parking desktop. The table keeps for each
window whether it is parked and the desktop it came from ([`Table::hide_commands`],
[`Table::restore_commands`]): a hidden window is still on its workspace for every query
([`Table::window_workspace`]), a window put on another workspace while it is hidden is hidden
still and comes back there ([`Table::window_workspace_commands`]), and KWin's report that the
window moved to the parking desktop is not a `WorkspaceMove`. The parking desktop is made the
first time it is needed ([`NeedsPark`], `create_park_desktop` in [`kwin`]), by position, so
that it stays after the workspaces' desktops. The table checks that KWin still lists it before it
sends a window there, and asks for a new one when somebody removed it.
An application that raises a hidden window, or a click on it in the task manager, makes KWin
switch that monitor to the parking desktop. The table notices that a monitor shows it, sends the
monitor back to the desktop it showed before, and raises no `WorkspaceChange`; the window's own
`FocusChange` then brings it to the front of its stack.
KWin keeps its virtual desktops in `kwinrc` as soon as one is made, so a parking desktop that
komorebi does not remove stays for every later session. The backend removes it in `shutdown`,
after the restoring commands have reached the bridge. A daemon that was killed leaves it, with
windows on it: the first snapshot the next daemon gets lists a desktop with that name, which the
table treats as stale ([`Table::stale_park`]). It is never the parking desktop of the new run.
The snapshot sends the windows on it to the first workspace's desktop, and half a second later
the backend removes it (`sweep_stale_park`).
## The command socket
The daemon takes messages on a Unix socket, `komorebi.sock` in [`DATA_DIR`]
@@ -363,6 +420,24 @@ any other, so its events find it, and [`Workspace::update`] leaves it where it i
floated window goes is [`WindowManagementBehaviour::toggle_float_placement`]: by default it
stays where it is.
`StackWindow` puts the focused window and the window of the container in a direction in one
container ([`WindowManager::add_window_to_container`]): the focused window goes to the front of
that container, or, when the focused container is a stack and the other is not, the other
container's window goes into the stack. `UnstackWindow` takes the front window out of a stack
into a container of its own after it ([`WindowManager::remove_window_from_container`]), `StackAll`
puts every window of the workspace in one container ([`WindowManager::stack_all`]), and
`UnstackAll` takes them out again ([`WindowManager::unstack_all`]). Each ends with the workspace
tiled again, and the window that was in front has the focus.
A window that opens gets the behavior [`WindowManager::window_management_behaviour`] says for
its workspace: a container of its own (`Create`, the default), or a place in the focused
container (`Append`), and a floating window with the float override on. A workspace's own
[`Workspace::window_container_behaviour`] and [`Workspace::float_override`] win over the window
manager's, and `Append` on an empty workspace is `Create`. `ToggleWindowContainerBehaviour` and
`ToggleFloatOverride` flip the window manager's, and `ToggleWorkspaceWindowContainerBehaviour` and
`ToggleWorkspaceFloatOverride` the focused workspace's, which starts from the opposite of the
window manager's value the first time.
`ToggleLock` locks the focused container, or unlocks it ([`WindowManager::toggle_lock`]), and
`LockMonitorWorkspaceContainer` and `UnlockMonitorWorkspaceContainer` do the same for a
container given by its indices. A lock changes nothing until containers are inserted, removed or
@@ -522,10 +597,10 @@ module's unit.
operations on it (tile the workspace in front, tile every monitor, take a minimized
window out, move the focus, move the focused container, change the layout, resize or
promote the focused container, float a window, lock a container, set the padding of a
workspace, manage and unmanage a window, show a workspace, move a container to another
workspace, follow a workspace switch made by something else, name a workspace and find
it by its name, set the layout of a workspace that is not in front, focus another monitor,
and move containers and workspaces between monitors).
workspace, manage and unmanage a window, stack and unstack windows, show a workspace, move a
container to another workspace, follow a workspace switch made by something else, name a
workspace and find it by its name, set the layout of a workspace that is not in front, focus
another monitor, and move containers and workspaces between monitors).
- [`desktop`](../../komorebi/src/desktop.rs): loads the monitors and the open windows from
the backend.
- [`window_manager_event`](../../komorebi/src/window_manager_event.rs) and
@@ -537,7 +612,8 @@ module's unit.
- [`kwin`](../../komorebi/src/kwin/mod.rs): the KWin backend, its D-Bus service and the held
call; [`kwin::state`](../../komorebi/src/kwin/state.rs), the table;
[`kwin::kwinrc`](../../komorebi/src/kwin/kwinrc.rs), the editor of the user's `kwinrc`, which
keeps the values it changes and puts them back; and
keeps the values it changes and puts them back; the parking desktop is made, swept and removed
in `kwin` and tracked in `kwin::state`; and
[`bridge.js`](../../komorebi/src/kwin/bridge.js), the bridge.
- [`process_command`](../../komorebi/src/process_command.rs): the thread that listens on the
socket, and what the window manager does with each message.
@@ -583,6 +659,10 @@ the fake. The window manager is its only caller, through [`backend`]. The contra
backend asked for a workspace that has no desktop makes the desktops up to it
(`ensure_workspaces`). The compositor shows and hides the windows of the desktops, and a
backend reports a switch or a move it did not make as an event.
- A hidden window (`hide`) is out of sight, alive, not minimized, and on the workspace it was
on until `restore`: `window_workspace` still names that workspace, and
`set_window_workspace` changes where it comes back to, not where it is hidden. Only the back of
a stack is hidden: nothing is hidden to leave a workspace.
- `shutdown`, `is_window`, `window_rect` and `monitor_from_point` have defaults, written in
terms of the queries. An implementor should not need to override them, except `shutdown`
when it created something in the compositor that has to be given up.
@@ -595,7 +675,7 @@ the fake. The window manager is its only caller, through [`backend`]. The contra
| A backend can be shared between threads | type system: `Backend: Send + Sync + 'static` | `compile_fail,E0277` on [`Backend`] | none |
| The window manager asks for a backend that was never installed | runtime error: [`backend`] panics, naming [`set_backend`] and [`with_backend`] | `# Panics` on [`backend`] | none |
| A test's backend does not outlive the test | framework path: [`with_backend`] restores the previous one on drop | `with_backend_puts_the_previous_backend_back_when_the_closure_panics` | none |
| A command about a missing window is an error, not a panic | test | `a_command_about_a_window_nobody_opened_is_an_error` and `a_command_about_a_closed_window_is_an_error` against the fake, `a_command_about_a_window_the_table_does_not_know_is_an_error_and_sends_nothing` against the KWin backend | none |
| A command about a missing window is an error, not a panic | test | `a_command_about_a_window_nobody_opened_is_an_error`, `a_command_about_a_closed_window_is_an_error` and `hiding_or_restoring_a_window_nobody_opened_is_an_error` against the fake, `a_command_about_a_window_the_table_does_not_know_is_an_error_and_sends_nothing` against the KWin backend | none |
| A locked container keeps its index | framework path: a [`Workspace`] inserts, removes and swaps its containers through `LockableSequence` | `test_locked_containers_with_new_window`, `test_locked_containers_remove_window`, `a_window_that_opens_does_not_push_a_locked_container_from_its_index` | `containers_mut()` is the `VecDeque` itself |
| A window komorebi does not manage is never moved | framework path: `handle_event` asks [`Window::should_manage`] before it acts on any event but a destroy | `dialogs_and_other_non_normal_windows_are_left_alone`, `an_ignore_rule_keeps_a_window_unmanaged` | `ManageRule` |
| A window the user unmanaged stays out of the layout until it is managed again | framework path: `handle_event` checks the list of unmanaged windows before it acts on any event but a removal | `unmanage_takes_the_focused_window_out_until_manage_takes_it_back` | none |
@@ -630,6 +710,15 @@ the fake. The window manager is its only caller, through [`backend`]. The contra
| A workspace is closed only when it has no window and no name and is not the monitor's last | framework path: the `CloseWorkspace` arm of [`WindowManager::process_command`] checks all three | `new_workspace_adds_one_and_close_workspace_removes_it_when_it_is_empty_and_unnamed` | none |
| The focus and a move at the edge of a monitor go to the monitor on that side, and fail only when there is none | framework path: the `None` arms of [`WindowManager::focus_container_in_direction`] and [`WindowManager::move_container_in_direction`] | `the_focus_crosses_to_the_monitor_on_that_side`, `a_move_at_the_edge_of_a_monitor_swaps_with_the_window_on_the_next_one_by_default`, `focus_towards_a_side_with_no_window_is_an_error_and_changes_nothing` | `NoOp` keeps a move on its monitor |
| A window shown or focused on another monitor focuses that monitor, and nothing else does | framework path: `handle_event` focuses the monitor of a `Show` or `FocusChange` before it acts on it | `a_window_that_opens_on_the_monitor_that_is_not_focused_focuses_it`, `a_scrolling_strip_on_the_next_monitor_over_does_not_take_focus_with_it` | none |
| Only the window in front of a stack is in sight | framework path: [`Container::add_window`] and [`Container::load_focused_window`] hide every window of the container but the focused one, and every operation that changes the front ends with the call | `a_window_added_to_a_container_is_in_front_and_the_others_are_hidden`, `loading_the_focused_window_shows_it_and_hides_the_rest`, `stacking_puts_two_windows_in_one_container_and_hides_the_one_behind`, `vm-stacks` ("exactly one window is on it") | none |
| A hidden window is still on its workspace, and is not reported as moved | framework path: the table keeps the desktop a window came from, and a move to the parking desktop is its own | `parking_a_window_hides_it_without_unmanaging_it`, `komorebis_own_move_and_its_park_and_restore_raise_nothing_new`, `a_window_is_put_on_a_workspace_by_putting_it_on_its_desktop` | none |
| What the compositor reports about a window komorebi hid is not taken for the user's doing | framework path: [`Window::hide`] records the window in [`HIDDEN_WINDOWS`] before it asks the backend, and the `Minimize` arm of `handle_event` checks it | `a_minimize_komorebi_asked_for_is_not_mistaken_for_the_user`, `a_minimize_the_user_asked_for_takes_the_window_out_of_the_layout` | none |
| Closing the window in front of a stack brings the next one forward | framework path: [`Workspace::remove_window`] shows the container's new front window and focuses it | `closing_the_window_in_front_of_a_stack_brings_the_next_one_forward`, `vm-stacks` ("closing the window in view") | none |
| The back of a stack stays hidden when its workspace is shown again | framework path: [`Workspace::restore`] restores the front window of each container and no other | `the_back_of_a_stack_stays_hidden_across_a_workspace_round_trip`, `vm-stacks` ("a workspace round trip") | none |
| A window is never sent to a parking desktop that is not there | framework path: [`Table::hide_commands`] asks for a new one unless KWin lists the one it made | `a_parking_desktop_that_has_gone_is_made_again_not_sent_windows` | none |
| A monitor raised onto the parking desktop is sent back | framework path: the table sends the monitor back to the desktop it showed before | `following_a_hidden_window_to_the_parking_desktop_sends_that_output_back` | none |
| A clean stop leaves no window hidden and no parking desktop | framework path: [`WindowManager::stop`] and the signal handler restore every hidden window, and the backend's `shutdown` removes the desktop after the restoring commands have gone out | `restoring_every_window_brings_back_the_hidden_ones_unless_it_is_told_to_ignore_that`, `vm-stacks` ("a clean stop puts every window back") | `SIGKILL`, and `StopIgnoreRestore`, which restores nothing |
| A parking desktop a dead daemon left is swept by the next one, and its windows go home | startup check: the first snapshot marks it stale, sends its windows to the first workspace's desktop, and the backend removes it | `a_parking_desktop_left_by_a_crashed_run_is_swept`, `a_stale_parking_desktop_is_not_the_one_windows_are_hidden_on`, `vm-stacks` ("a crash leaves a parking desktop") | none |
| Moving the focus moves no window | test | `focus_gives_the_focus_to_the_window_on_that_side_and_moves_nothing`, `vm-core-e2e` ("moving the focus moved no window") | none |
| A subscriber that is gone is dropped, not retried | test | `a_subscriber_that_is_gone_is_dropped_and_not_tried_again` | none |
| The bridge holds no window manager logic | convention, with every decision about an event in the table, which the `kwin::state` unit tests pin | the unit tests in `komorebi/src/kwin/state.rs` | none |
@@ -767,6 +856,10 @@ A window is shown, and ends up on a tile:
[`komorebi/tests/monitors.rs`](../../komorebi/tests/monitors.rs), two monitors: crossing from
one to the other, the monitor commands and `EagerFocus`; [`komorebi/src/kwin/kwinrc.rs`](../../komorebi/src/kwin/kwinrc.rs), the
`kwinrc` editor and its tests.
- [`komorebi/tests/stacks.rs`](../../komorebi/tests/stacks.rs): stacking, unstacking and the windows
a stack hides, the behavior of new windows and the float override, against the fake;
[`nix/tests/vm/suites/stacks`](../../nix/tests/vm/suites/stacks/test.py), the same in a real
KWin, with the parking desktop, a crash and a stop.
- [`nix/tests/vm/suites/workspace-switch`](../../nix/tests/vm/suites/workspace-switch/test.py):
workspaces as a real KWin's desktops, switched by `komorebic` and by KWin;
[`nix/tests/vm/suites/kwin-contract`](../../nix/tests/vm/suites/kwin-contract/test.py), the
@@ -798,6 +891,30 @@ A window is shown, and ends up on a tile:
[`MatchingRule`]: ../../komorebi/src/core/config_generation.rs
[`ApplicationIdentifier`]: ../../komorebi/src/core/mod.rs
[`Window::set_position`]: ../../komorebi/src/window.rs
[`Window::hide`]: ../../komorebi/src/window.rs
[`Window::restore`]: ../../komorebi/src/window.rs
[`HIDDEN_WINDOWS`]: ../../komorebi/src/lib.rs
[`Container::add_window`]: ../../komorebi/src/container.rs
[`Container::load_focused_window`]: ../../komorebi/src/container.rs
[`Workspace::move_window_to_container`]: ../../komorebi/src/workspace.rs
[`Workspace::new_container_for_focused_window`]: ../../komorebi/src/workspace.rs
[`Workspace::remove_window`]: ../../komorebi/src/workspace.rs
[`Workspace::focus_container_by_window`]: ../../komorebi/src/workspace.rs
[`Workspace::restore`]: ../../komorebi/src/workspace.rs
[`Workspace::window_container_behaviour`]: ../../komorebi/src/workspace.rs
[`Workspace::float_override`]: ../../komorebi/src/workspace.rs
[`WindowManager::add_window_to_container`]: ../../komorebi/src/window_manager.rs
[`WindowManager::remove_window_from_container`]: ../../komorebi/src/window_manager.rs
[`WindowManager::stack_all`]: ../../komorebi/src/window_manager.rs
[`WindowManager::unstack_all`]: ../../komorebi/src/window_manager.rs
[`WindowManager::restore_all_windows`]: ../../komorebi/src/window_manager.rs
[`WindowManager::window_management_behaviour`]: ../../komorebi/src/window_manager.rs
[`Backend::hide`]: ../../komorebi/src/backend/mod.rs
[`Table::hide_commands`]: ../../komorebi/src/kwin/state.rs
[`Table::restore_commands`]: ../../komorebi/src/kwin/state.rs
[`Table::window_workspace`]: ../../komorebi/src/kwin/state.rs
[`Table::stale_park`]: ../../komorebi/src/kwin/state.rs
[`NeedsPark`]: ../../komorebi/src/kwin/state.rs
[`Workspace::new_container_for_window`]: ../../komorebi/src/workspace.rs
[`WindowManager`]: ../../komorebi/src/window_manager.rs
[`WindowManager::process_event`]: ../../komorebi/src/process_event.rs
+37
View File
@@ -259,3 +259,40 @@ plain ini, which komorebi changes line by line, and asks KWin to reload its conf
It is the user's setting, so the value komorebi found is kept in a backup file and put back
when komorebi stops; a backup a crash left behind keeps the value from before the first run,
and the next run puts it back.
## Why are the windows behind the front one of a stack moved to a parking desktop?
Because a container has one tile, so the windows of a stack that are not in front have to be out
of sight, and a virtual desktop nobody looks at was the one way to do that which the spikes found
to cost no focus change. The first spike hid six tiled windows and showed them again three ways.
Minimizing
them gave the geometry back exactly, but KWin picked a new active window as each one minimized,
two focus events nobody asked for. Moving them to a virtual desktop of their own gave no focus
event and the geometry back exactly. Moving them off the screen worked too, since KWin does not
clamp a scripted move, but the windows stay mapped on the current desktop, in the window switcher,
the overview and the task manager, so it was not offered. KWin has nothing else: `Window.hidden`
cannot be set by a script. The spike's source reading, KWin 6.8.1, is in
[PLATFORM.md](PLATFORM.md#the-parking-desktop). The other platforms have a setting that chooses
how windows are hidden; on KDE there is one way, and so no such setting.
The cost is that KWin keeps a virtual desktop in `kwinrc` as soon as it is made. A run that failed
after making the parking desktop left it there for every later session. So komorebi removes the
desktop when it stops, after the commands that bring the windows back have reached the bridge, and
the first snapshot of the next run finds a leftover, sends the windows on it to the first
workspace's desktop and removes it. A leftover is never used as the parking desktop of the new
run, since it is about to be removed and anything parked on it would go with it; the new run makes
its own the first time it needs one. Before each hide the table also checks that the desktop it
made is still listed, because somebody can remove it in System Settings, and a window sent to a
desktop that is not there has nowhere to go and nothing says so.
Activating a window that is on another desktop makes KWin switch that output to the window's
desktop (see [PLATFORM.md](PLATFORM.md#per-output-virtual-desktops)), so a click on a hidden
window in the task manager would leave the monitor showing the parking desktop, which has nothing
on it but hidden windows. The table sends the monitor straight back to the desktop it showed
before, and the window's own focus change then brings it to the front of its stack.
komorebi keeps a table of the windows it hid, [`HIDDEN_WINDOWS`](../../komorebi/src/lib.rs), and
records a window in it before it asks the backend to hide it. What the compositor reports about a
hidden window (a minimize, a move to another desktop) is the echo of a command komorebi sent, and
the window manager has to be able to tell that from the user's own: a window that the user
minimizes leaves the layout, and one komorebi hid does not.
+48 -11
View File
@@ -21,6 +21,8 @@ was measured with KWin 6.8.1, Plasma 6.8.1 and Qt 6.12.0 from nixpkgs `d3b13ad`
- **Output**: KWin's name for a monitor.
- **Desktop**: one of KWin's virtual desktops. Each output shows one; komorebi's workspace `i`
is desktop `i`.
- **Parking desktop**: the desktop named `komorebi-park`, which komorebi makes to hide the back of
a stack on. It is not a workspace.
- **Headless KWin**: `kwin_wayland --virtual`, a KWin with virtual outputs and no display,
which the VM tests run ([vm-tests.md](vm-tests.md)).
@@ -58,6 +60,29 @@ outputs:
- Desktops are global: every output has the same desktops, with the same names, and each output
shows one of them. The ids of the desktops are UUIDs; the bridge names them by id.
### The parking desktop
Why komorebi hides windows on a desktop of its own is in
[DESIGN.md](DESIGN.md#why-are-the-windows-behind-the-front-one-of-a-stack-moved-to-a-parking-desktop).
What it relies on KWin for, at time of writing (2026-10-27), measured by the spikes on KWin
6.8.1 (nixpkgs `d3b13ad`, 2026-10-24) unless it says otherwise. The VM test `vm-stacks` runs
komorebi's use of them in a headless KWin:
- A window on another desktop of its output is out of sight, and moving it there and back gives
its frame back exactly. Hiding six windows this way raised no `activated` event; minimizing
them raised two.
- KWin saves a virtual desktop in `kwinrc` as soon as it is made. A desktop that komorebi made
and did not remove, because it was killed, is in every later session.
- Activating a window that is on another desktop of its output switches that output to the
window's desktop (see [Per-output virtual desktops](#per-output-virtual-desktops)), which for a
hidden window is the parking desktop.
- `Window.hidden` is read-only to a script, and the only thing in KWin's 6.8.1 sources that sets
it is a layer-shell window (an auto-hide panel). This is a reading of the sources, not a
measurement.
- A window on the parking desktop is still a window of the session. Whether Plasma's task manager
lists it depends on the task manager's setting for showing the windows of the current desktop
only; the VM tests have no panel, so this is not measured.
### Wayland
komorebi runs in a Plasma Wayland session. There is no X11 session of Plasma 6.8 to run it in.
@@ -107,8 +132,15 @@ reload its configuration. If a workspace has no desktop, it creates the missing
`org.kde.KWin.VirtualDesktopManager`, named "Workspace 1", "Workspace 2" and so on. A desktop
that is already there keeps its name.
Every command of the window manager (move and resize, focus, raise, minimize, bring back or
close a window, show a workspace on an output, put a window on a workspace) is queued for the
When a stack hides a window for the first time, it makes one more desktop, named `komorebi-park`,
after the desktops of the workspaces (the missing workspace desktops are made by position, so that
it stays last), and moves the window there. The desktop is not a workspace: komorebi counts the
workspaces without it, and a window on it is on the workspace it will come back to. It checks that
KWin still lists the desktop before it sends another window there.
Every command of the window manager (move and resize, focus, raise, hide or restore, minimize,
bring back or close a window, show a workspace on an output, put a window on a workspace) is
queued for the
bridge, which gets the queue as the answer to its held call and carries the commands out in
KWin, in order. The script API cannot move the pointer, so
when the pointer follows the focus komorebi invokes KWin's own "Move Mouse to Focus" shortcut,
@@ -128,15 +160,20 @@ an owner again; the VM test `vm-kwin-restart` restarts KWin twice under a runnin
#### What komorebi leaves behind
When it is stopped with `SIGINT`, `SIGTERM` or a `Stop` message on its socket, it puts back
the value `PerOutputVirtualDesktops` had in `kwinrc` (or removes the key, when the user had
none) and asks KWin to reload its configuration, asks KWin to unload the script, closes an
empty connection to each subscriber, and removes the socket. The desktops it created stay:
they are the user's desktops from then on. The file `bridge.js` stays in the runtime
When it is stopped with `SIGINT`, `SIGTERM` or a `Stop` message on its socket, it brings back
the windows it hid, waits until the commands that do so have reached the bridge, removes the
parking desktop, puts back the value `PerOutputVirtualDesktops` had in `kwinrc` (or removes the
key, when the user had none) and asks KWin to reload its configuration, asks KWin to unload the
script, closes an empty connection to each subscriber, and removes the socket. The desktops it
created for workspaces stay: they are the user's desktops from then on. A `StopIgnoreRestore`
message stops it the same way, except that it does not bring the windows back: the parking desktop
is removed all the same. The file `bridge.js` stays in the runtime
directory, which is removed at logout. A daemon that is killed leaves the script running in
KWin, reporting to nobody, the socket file in the runtime directory, and per-output desktops
on, until the next start replaces the script and the socket, and its stop puts the setting
back (the backup in the runtime directory keeps the user's value), or the session ends.
KWin, reporting to nobody, the socket file in the runtime directory, per-output desktops
on, and the parking desktop with the hidden windows on it, until the next start replaces the
script and the socket, sends the windows on the parking desktop to the first workspace's desktop
and removes the desktop, and its stop puts the setting back (the backup in the runtime
directory keeps the user's value), or the session ends.
### A headless KWin
@@ -182,7 +219,7 @@ What komorebi calls:
| `org.freedesktop.DBus` | `/org/freedesktop/DBus` | `org.freedesktop.DBus` | `AddMatch(s)`, for the signal `NameOwnerChanged` | at start, to see KWin leave the bus and come back |
| `org.kde.kglobalaccel` | `/component/kwin` | `org.kde.kglobalaccel.Component` | `invokeShortcut(s)`, with `MoveMouseToFocus` | when the pointer follows the focus |
| `org.kde.KWin` | `/KWin` | `org.kde.KWin` | `reconfigure()` | after komorebi changed `kwinrc`, at start and at exit |
| `org.kde.KWin` | `/VirtualDesktopManager` | `org.kde.KWin.VirtualDesktopManager` | the property `desktops`, `createDesktop(us)`, `setDesktopName(ss)` | when a workspace has no desktop, and at start |
| `org.kde.KWin` | `/VirtualDesktopManager` | `org.kde.KWin.VirtualDesktopManager` | the properties `desktops` and `count`, `createDesktop(us)`, `setDesktopName(ss)`, `removeDesktop(s)` | when a workspace has no desktop, and at start; `createDesktop` also for the parking desktop, the first time a window is hidden, and `removeDesktop` for it when komorebi stops and for one a killed run left |
The property `desktops` is introspected as `a(iss)`, a position, an id and a name for each
desktop, and the value on the wire is `a(uss)`: komorebi reads it as that. It is read uncached,
+9 -6
View File
@@ -118,17 +118,18 @@ the run.
clients.
- `start_komorebi(*args)` starts the daemon in the session, with the module's
`execStart` and `args` after it (not `--log-level`, which `execStart` has),
`stop_komorebi()` stops it with `SIGTERM`, `komorebi_log()` returns its log
since it was last started, and `script_loaded()` asks KWin whether it runs
the bridge.
`stop_komorebi()` stops it with `SIGTERM`, `kill_komorebi()` kills it with
`SIGKILL`, as a crash does, `komorebi_log()` returns its log since it was
last started, and `script_loaded()` asks KWin whether it runs the bridge.
`restart_kwin()` stops the session's KWin and starts a new one on the same
bus, as when the compositor of a running session crashes, and waits for it.
- `komorebic(*args)` runs `komorebic` in the session and returns what it
printed, failing the test if it fails. `state()` is the daemon's state as
`komorebic state` prints it, `managed(workspace)` the number of windows the
daemon has on a workspace of the first monitor, `managed_all()` the number it
has on every workspace of every monitor (floating windows too), and
`focused_title(workspace)` the title of the window it has focused there.
has on every workspace of every monitor (floating windows too),
`containers(workspace)` the titles of the windows of each of its containers,
and `focused_title(workspace)` the title of the window it has focused there.
- `daemon` reads the daemon's view of the desktop from that log, at the debug
level the nodes set: `daemon.events(log)` lists the window events it handled,
in order, `daemon.window_ids(log)` maps a window's title to the daemon's id
@@ -136,7 +137,9 @@ the run.
for, for each window.
- `desk(wid)` is the number of the desktop a window is on and `shown()` the one
KWin shows, both counted from 1 as `kdotool` counts, `desktops()` how many
desktops KWin has, and `kwinrc(group, key)` a value of the user's `kwinrc`.
desktops KWin has, `desktop_names()` their names in order (the parking desktop
of a stack is the one named `komorebi-park`), and `kwinrc(group, key)` a value
of the user's `kwinrc`.
- `kwin_script(name, source, keep=)` runs a KWin script and returns the lines it
reported: the script calls `report(...)`, which `print`s a line marked with
`name` to KWin's log, and ends with `report("done")`. A script that is kept
+2
View File
@@ -34,6 +34,8 @@ anywhere else. [Running komorebi](usage/running-komorebi.md) explains how to sta
daemon, ask it what it is doing and read its log.
[Focusing windows](usage/focusing-windows.md) explains how to give the focus to another window,
[Moving windows](usage/moving-windows.md) how to move the focused window to another tile,
[Stacking windows](usage/stacking-windows.md) how to put windows on one tile and have the others
wait out of sight,
[Layouts](usage/layouts.md) how to change the arrangement of the tiles,
[Resizing windows](usage/resizing-windows.md) how to change the size of one,
[Floating windows](usage/floating-windows.md) how to take a window out of the layout,
+17
View File
@@ -13,3 +13,20 @@ komorebic toggle-float
A floated window keeps its size and position by default. The floating windows of a workspace are
in the daemon's state as `floating_windows`, next to its containers.
## Windows that open floating
With the float override on, every window that opens floats instead of getting a tile.
[`komorebic toggle-float-override`](../cli/toggle-float-override.md) turns it on and off for every
workspace, and
[`komorebic toggle-workspace-float-override`](../cli/toggle-workspace-float-override.md) for the
focused workspace only: the first time it takes the opposite of what every workspace has, and from
then on it follows its own setting.
```sh
komorebic toggle-float-override
komorebic toggle-workspace-float-override
```
The override is in the daemon's state, as `float_override` for every workspace and in each
workspace that has one of its own.
+4 -3
View File
@@ -45,9 +45,10 @@ komorebic start -- --log-level debug
komorebic start -- --fake-backend
```
[`komorebic stop`](../cli/stop.md) tells the daemon to stop. It asks KWin to unload its
script, removes its socket and exits. Stopping the process with `SIGINT` or `SIGTERM` does
the same.
[`komorebic stop`](../cli/stop.md) tells the daemon to stop. It brings back the windows it hid
(the back of a stack, [stacking windows](stacking-windows.md)), removes the desktop they were
hidden on, asks KWin to unload its script, removes its socket and exits. Stopping the process with
`SIGINT` or `SIGTERM` does the same.
## Asking komorebi what it is doing
+81
View File
@@ -0,0 +1,81 @@
# Stacking windows
A stack is a container with more than one window. The windows share one tile of the layout, and
one of them, the window in front, is in sight: the others are out of the way. Stacking puts two
windows on one tile, so the layout has one tile fewer to give out.
## Putting windows in a stack
[`komorebic stack`](../cli/stack.md) puts the focused window and the window on one side of it in
one stack: `left`, `right`, `up` or `down`. As with
[`komorebic focus`](focusing-windows.md#in-a-direction), the layout decides which tile is on which
side. The focused window ends up in front, and it keeps the focus. Where the layout has no tile on
that side, nothing happens.
```sh
komorebic stack left
komorebic stack down
```
[`komorebic unstack`](../cli/unstack.md) takes the window in front out of its stack and puts it
in a tile of its own after the stack, and the next window of the stack is in front again. A
window that is alone on its tile cannot be unstacked, and the daemon logs "a container must have
at least one window".
```sh
komorebic unstack
```
[`komorebic stack-all`](../cli/stack-all.md) puts every window of the focused workspace in one
stack, in the order they had, with the focused window in front.
[`komorebic unstack-all`](../cli/unstack-all.md) takes every window out of the focused stack,
each onto a tile of its own, and the window that had the focus keeps it.
```sh
komorebic stack-all
komorebic unstack-all
```
A stack moves as one: moving it with [`komorebic move`](moving-windows.md#in-a-direction) or to
another workspace takes every window in it. When the window in front closes, the next window of
the stack comes to the front and has the focus.
## Windows that open into a stack
By default a window that opens gets a tile of its own. With the window container behavior set to
`append`, a window that opens joins the focused stack instead, in front, and a workspace with no
window still gives it a tile of its own, since there is nothing to join.
[`komorebic toggle-window-container-behaviour`](../cli/toggle-window-container-behaviour.md)
switches every workspace between the two.
[`komorebic toggle-workspace-window-container-behaviour`](../cli/toggle-workspace-window-container-behaviour.md)
does it for the focused workspace only: the first time, it takes the opposite of what every
workspace has, and from then on it follows its own setting.
```sh
komorebic toggle-window-container-behaviour
komorebic toggle-workspace-window-container-behaviour
```
The setting is in the daemon's state, as `new_window_behaviour` for every workspace and as
`window_container_behaviour` in each workspace that has one of its own.
## Where the windows behind go
komorebi does not minimize the windows behind the front one: it moves them to a virtual desktop
that nobody looks at, which it makes when it first needs it and calls `komorebi-park`. A window
there is still open, still on its workspace as far as komorebi is concerned, and still in the
stack, and it comes back to the desktop of its workspace when it is brought to the front, when it
is unstacked, and when komorebi stops. The parking desktop is the last desktop, after the ones
that are workspaces, and is not one of them.
KWin keeps its virtual desktops in its configuration as soon as one is made, so the parking
desktop would be there in the next session if komorebi did not remove it. It does when it stops.
If komorebi did not get to stop (it was killed, or the session ended under it), the next komorebi
finds the parking desktop in KWin's list, sends the windows on it back to the first workspace's
desktop, and removes it. If the parking desktop is removed while komorebi runs, the next hide
makes a new one.
A window on the parking desktop can still be reached by something else. Raising one, with a
click in the task manager, makes KWin show the parking desktop on that monitor, and komorebi
sends the monitor straight back to the workspace it was showing. The window that was raised
becomes the front of its stack when komorebi handles its focus change.
+2 -2
View File
@@ -198,7 +198,7 @@ where
/// # let daemon = std::thread::spawn(move || -> std::io::Result<()> {
/// # let (mut stream, _) = listener.accept()?;
/// # BufReader::new(stream.try_clone()?).read_line(&mut String::new())?;
/// # let state = r#"{"monitors":{"elements":[],"focused":0},"monitor_usr_idx_map":{},"is_paused":false,"resize_delta":50,"cross_monitor_move_behaviour":"Swap","unmanaged_window_operation_behaviour":"Op","work_area_offset":null,"mouse_follows_focus":true}"#;
/// # let state = r#"{"monitors":{"elements":[],"focused":0},"monitor_usr_idx_map":{},"is_paused":false,"resize_delta":50,"new_window_behaviour":"Create","float_override":false,"cross_monitor_move_behaviour":"Swap","unmanaged_window_operation_behaviour":"Op","work_area_offset":null,"mouse_follows_focus":true}"#;
/// # stream.write_all(state.as_bytes())
/// # });
/// use komorebi_client::SocketMessage;
@@ -260,7 +260,7 @@ pub fn send_query(message: &SocketMessage) -> std::io::Result<String> {
/// # let mut message = String::new();
/// # BufReader::new(stream).read_line(&mut message)?;
/// # let subscriber = komorebi_client::DATA_DIR.join("bar.sock");
/// # let state = r#"{"monitors":{"elements":[],"focused":0},"monitor_usr_idx_map":{},"is_paused":false,"resize_delta":50,"cross_monitor_move_behaviour":"Swap","unmanaged_window_operation_behaviour":"Op","work_area_offset":null,"mouse_follows_focus":true}"#;
/// # let state = r#"{"monitors":{"elements":[],"focused":0},"monitor_usr_idx_map":{},"is_paused":false,"resize_delta":50,"new_window_behaviour":"Create","float_override":false,"cross_monitor_move_behaviour":"Swap","unmanaged_window_operation_behaviour":"Op","work_area_offset":null,"mouse_follows_focus":true}"#;
/// # let notification = format!(r#"{{"event":{message},"state":{state}}}"#);
/// # std::os::unix::net::UnixStream::connect(subscriber)?.write_all(notification.as_bytes())?;
/// # Ok(message)
+61 -3
View File
@@ -44,6 +44,10 @@ pub enum Command {
Focus(u32, bool),
/// [`Backend::raise`].
Raise(u32),
/// [`Backend::hide`].
Hide(u32),
/// [`Backend::restore`].
Restore(u32),
/// [`Backend::minimize`].
Minimize(u32),
/// [`Backend::unminimize`].
@@ -66,6 +70,8 @@ struct State {
/// [`FakeBackend::permissive`]).
permissive: bool,
windows: HashMap<u32, WindowInfo>,
/// the windows that are hidden, in the order they were
hidden: Vec<u32>,
min_sizes: HashMap<u32, (i32, i32)>,
monitors: Vec<MonitorInfo>,
foreground: Option<u32>,
@@ -252,8 +258,14 @@ impl FakeBackend {
self.state.lock().windows.get(&id).map(|w| w.rect)
}
/// Returns true if and only if the window can be seen: it is alive, not minimized, and on the
/// workspace its monitor shows. This is what the compositor does with desktops.
/// Returns true if and only if the window is hidden ([`Backend::hide`]), as opposed to being
/// on a workspace that is not showing.
pub fn is_hidden(&self, id: u32) -> bool {
self.state.lock().hidden.contains(&id)
}
/// Returns true if and only if the window can be seen: it is alive, not minimized, not hidden
/// and on the workspace its monitor shows. This is what the compositor does with desktops.
pub fn on_screen(&self, id: u32) -> bool {
let state = self.state.lock();
let Some(window) = state.windows.get(&id) else {
@@ -264,7 +276,10 @@ impl FakeBackend {
.and_then(|m| state.shown.get(&m))
.copied()
.unwrap_or(0);
window.alive && !window.minimized && state.window_ws.get(&id).copied().unwrap_or(0) == shown
window.alive
&& !window.minimized
&& !state.hidden.contains(&id)
&& state.window_ws.get(&id).copied().unwrap_or(0) == shown
}
/// Returns the workspace a window is on, if it was ever opened.
@@ -398,6 +413,20 @@ impl Backend for FakeBackend {
self.record(id, Command::Raise(id), |_| ())
}
fn hide(&self, id: u32) -> eyre::Result<()> {
self.record(id, Command::Hide(id), |state| {
if !state.hidden.contains(&id) {
state.hidden.push(id);
}
})
}
fn restore(&self, id: u32) -> eyre::Result<()> {
self.record(id, Command::Restore(id), |state| {
state.hidden.retain(|h| *h != id);
})
}
fn minimize(&self, id: u32) -> eyre::Result<()> {
self.record(id, Command::Minimize(id), |state| {
if let Some(w) = state.windows.get_mut(&id) {
@@ -680,6 +709,35 @@ mod tests {
Ok(())
}
#[test]
fn a_hidden_window_is_out_of_sight_on_its_workspace_until_it_is_restored() -> eyre::Result<()> {
let fake = fake_with(&[1]);
fake.hide(1)?;
fake.hide(1)?;
assert!(fake.is_hidden(1) && !fake.on_screen(1));
assert_eq!(fake.window_workspace(1), Some(0));
assert!(fake.window(1).is_some_and(|w| w.alive && !w.minimized));
fake.restore(1)?;
assert!(!fake.is_hidden(1) && fake.on_screen(1));
assert_eq!(
fake.commands(),
[Command::Hide(1), Command::Hide(1), Command::Restore(1)]
);
Ok(())
}
#[test]
fn hiding_or_restoring_a_window_nobody_opened_is_an_error() {
let fake = fake_with(&[1]);
assert!(fake.hide(9).is_err());
assert!(fake.restore(9).is_err());
}
#[test]
fn putting_a_window_nobody_opened_on_a_workspace_is_an_error() {
let fake = fake_with(&[1]);
+35
View File
@@ -28,6 +28,14 @@
//! to be put on workspace `i` ([`Backend::set_window_workspace`]), and the compositor does the
//! showing, the hiding and the focusing. When something else changes what a monitor shows, the
//! backend raises an event and the window manager follows it.
//!
//! # Hiding
//!
//! The one thing the window manager hides itself is the back of a stack: a container tiles one
//! window, so the others in it are taken out of sight ([`Backend::hide`]) and brought back
//! ([`Backend::restore`]) when they are given the tile. A hidden window stays alive, stays on its
//! workspace and is not minimized, so what the compositor reports about it is not taken for the
//! user's doing (the window manager keeps a table of the windows it has hidden).
#![deny(missing_docs)]
@@ -101,6 +109,9 @@ pub struct MonitorInfo {
/// one of them at a time ([`Backend::switch_workspace`]). The compositor shows the windows of the
/// workspace in front and hides the others; the window manager never hides a window to leave a
/// workspace.
/// - A hidden window ([`Backend::hide`]) is still alive and still on its workspace: it is out of
/// sight until [`Backend::restore`], and [`Backend::window_workspace`] names the workspace it
/// comes back to.
/// - A backend asked to show a workspace, or to put a window on one, that has no desktop yet makes
/// the desktops up to it first.
///
@@ -133,6 +144,8 @@ pub struct MonitorInfo {
/// # fn set_rect(&self, _: u32, _: &Rect) -> eyre::Result<()> { Ok(()) }
/// # fn focus(&self, _: u32, _: bool) -> eyre::Result<()> { Ok(()) }
/// # fn raise(&self, _: u32) -> eyre::Result<()> { Ok(()) }
/// # fn hide(&self, _: u32) -> eyre::Result<()> { Ok(()) }
/// # fn restore(&self, _: u32) -> eyre::Result<()> { Ok(()) }
/// # fn minimize(&self, _: u32) -> eyre::Result<()> { Ok(()) }
/// # fn unminimize(&self, _: u32) -> eyre::Result<()> { Ok(()) }
/// # fn close(&self, _: u32) -> eyre::Result<()> { Ok(()) }
@@ -192,6 +205,28 @@ pub trait Backend: Send + Sync + 'static {
/// When the window does not exist or is no longer alive.
fn raise(&self, id: u32) -> eyre::Result<()>;
/// Takes the window out of sight without closing or minimizing it, which is how the window
/// manager keeps the back of a stack out of the way. On KWin it goes to a virtual desktop that
/// nobody looks at.
///
/// The window stays on its workspace ([`Backend::window_workspace`]), and
/// [`Backend::set_window_workspace`] changes the workspace it comes back to, not where it is
/// hidden. A window that is hidden already is left as it is.
///
/// # Errors
///
/// When the window does not exist or is no longer alive, or the compositor cannot make the
/// place the window is hidden in.
fn hide(&self, id: u32) -> eyre::Result<()>;
/// Brings a hidden window back, to the workspace it is on. A window that is not hidden is left
/// as it is.
///
/// # Errors
///
/// When the window does not exist or is no longer alive.
fn restore(&self, id: u32) -> eyre::Result<()>;
/// Minimizes the window.
///
/// # Errors
+133
View File
@@ -4,6 +4,10 @@
//! the container is put on that tile. A new window gets a container of its own
//! ([`Workspace::new_container_for_window`](crate::workspace::Workspace::new_container_for_window)).
//!
//! A container with more than one window is a stack: the focused window is the one in front, and
//! the others are hidden ([`Window::hide`]) until they are given the tile
//! ([`Container::load_focused_window`]).
//!
//! A container can be locked ([`Lockable`]): a locked container keeps its index in the workspace
//! while others are inserted, removed or swapped around it.
@@ -100,10 +104,22 @@ impl Container {
self.remove_window_by_idx(focused_idx)
}
/// Puts a window at the back of the container and gives it the front, hiding every other
/// window of the container ([`Window::hide`])
///
/// It never fails; the result is there so that callers can use `?`.
pub fn add_window(&mut self, window: &Window) -> eyre::Result<()> {
self.windows_mut().push_back(*window);
self.focus_window(self.windows().len().saturating_sub(1));
let focused_window_idx = self.focused_window_idx();
for (i, window) in self.windows_mut().iter_mut().enumerate() {
if i != focused_window_idx {
window.hide();
}
}
Ok(())
}
@@ -113,17 +129,73 @@ impl Container {
self.windows.focus(idx);
}
/// Hides the unfocused windows of the container and restores the focused one. This function
/// is used to make sure we update the window that should be shown on a stack. If the container
/// isn't a stack this function won't change anything.
///
/// It never fails; the result is there so that callers can use `?`.
pub fn load_focused_window(&mut self) -> eyre::Result<()> {
let focused_idx = self.focused_window_idx();
for (i, window) in self.windows_mut().iter_mut().enumerate() {
if i == focused_idx {
window.restore();
} else {
window.hide();
}
}
Ok(())
}
pub fn remove_window_by_idx(&mut self, idx: usize) -> Option<Window> {
let window = self.windows_mut().remove(idx);
self.focus_window(idx.saturating_sub(1));
window
}
/// Hides every window of the container but `omit`, or every window when it is `None`
///
/// It never fails; the result is there so that callers can use `?`.
pub fn hide(&mut self, omit: Option<u32>) -> eyre::Result<()> {
for window in self.windows_mut().iter_mut().rev() {
let mut should_hide = omit.is_none();
if !should_hide
&& let Some(omit) = omit
&& omit != window.id
{
should_hide = true
}
if should_hide {
window.hide();
}
}
Ok(())
}
/// Restores the focused window of the container, which is the one that is in front when the
/// container is a stack
///
/// It never fails; the result is there so that callers can use `?`.
pub fn restore(&mut self) -> eyre::Result<()> {
if let Some(window) = self.focused_window_mut() {
window.restore();
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::backend::fake::FakeBackend;
use crate::backend::with_backend;
use serde_json;
use std::sync::Arc;
#[test]
fn test_contains_window() {
@@ -243,4 +315,65 @@ mod tests {
assert!(deserialized.locked);
assert_eq!(deserialized.id, container.id);
}
/// A container of the windows 701.. on a fake desktop, with the window at `focus` in front
fn stack_of(
fake: &Arc<FakeBackend>,
ids: std::ops::RangeInclusive<u32>,
focus: usize,
) -> Container {
let mut container = Container::default();
for id in ids {
fake.open_window(id, "foot", "foot", &format!("window {id}"));
container.add_window(&Window::from(id)).unwrap();
}
container.focus_window(focus);
container
}
#[test]
fn a_window_added_to_a_container_is_in_front_and_the_others_are_hidden() {
let fake = Arc::new(FakeBackend::with_one_monitor());
with_backend(fake.clone(), || {
let container = stack_of(&fake, 701..=703, 2);
assert_eq!(container.focused_window().map(|w| w.id), Some(703));
assert!(fake.is_hidden(701) && fake.is_hidden(702));
assert!(!fake.is_hidden(703));
});
}
#[test]
fn loading_the_focused_window_shows_it_and_hides_the_rest() {
let fake = Arc::new(FakeBackend::with_one_monitor());
with_backend(fake.clone(), || {
let mut container = stack_of(&fake, 704..=706, 0);
container.load_focused_window().unwrap();
assert!(!fake.is_hidden(704));
assert!(fake.is_hidden(705) && fake.is_hidden(706));
});
}
#[test]
fn hiding_a_container_leaves_out_the_window_it_is_told_to_and_restoring_shows_the_focused_one()
{
let fake = Arc::new(FakeBackend::with_one_monitor());
with_backend(fake.clone(), || {
let mut container = stack_of(&fake, 707..=709, 1);
container.hide(Some(709)).unwrap();
assert!(fake.is_hidden(707) && fake.is_hidden(708) && !fake.is_hidden(709));
container.hide(None).unwrap();
assert!(fake.is_hidden(709));
container.restore().unwrap();
assert!(fake.is_hidden(707) && !fake.is_hidden(708) && fake.is_hidden(709));
});
}
}
+9
View File
@@ -347,6 +347,10 @@ pub enum SocketMessage {
CancelPreselect,
CycleFocusWindow(CycleDirection),
CycleMoveWindow(CycleDirection),
StackWindow(OperationDirection),
UnstackWindow,
StackAll,
UnstackAll,
ResizeWindowEdge(OperationDirection, Sizing),
ResizeWindowAxis(Axis, Sizing),
MoveContainerToLastWorkspace,
@@ -378,6 +382,8 @@ pub enum SocketMessage {
UnlockMonitorWorkspaceContainer(usize, usize, usize),
ToggleLock,
ToggleFloat,
ToggleWindowContainerBehaviour,
ToggleFloatOverride,
ToggleCrossMonitorMoveBehaviour,
CrossMonitorMoveBehaviour(MoveBehaviour),
UnmanagedWindowOperationBehaviour(OperationBehaviour),
@@ -392,6 +398,8 @@ pub enum SocketMessage {
LayoutRatios(Option<Vec<f32>>, Option<Vec<f32>>),
// ChangeLayoutCustom(#[serde_as(as = "ResolvedPathBuf")] PathBuf),
FlipLayout(Axis),
ToggleWorkspaceWindowContainerBehaviour,
ToggleWorkspaceFloatOverride,
// Monitor and Workspace Commands
// MonitorIndexPreference(usize, i32, i32, i32, i32),
DisplayIndexPreference(usize, String),
@@ -400,6 +408,7 @@ pub enum SocketMessage {
NewWorkspace,
ToggleTiling,
Stop,
StopIgnoreRestore,
TogglePause,
Retile,
RetileWithResizeDimensions,
+181 -3
View File
@@ -42,6 +42,13 @@
//! When something other than komorebi does either, the script reports it, and the table turns it
//! into a [`WorkspaceChange`] or a [`WorkspaceMove`] for the window manager to follow.
//!
//! Hiding a window ([`Backend::hide`]) moves it to one more desktop, `komorebi-park`, that nobody
//! looks at and that is not a workspace; [`Backend::restore`] moves it back to the desktop of its
//! workspace. KWin saves its desktops in `kwinrc` as soon as one is made, so a desktop that
//! komorebi made and did not remove would be there for every later session: komorebi removes it
//! when it stops, and one that an earlier run left (it was killed, or the session was torn down
//! under it) is found in the first snapshot, its windows are sent home and it is removed.
//!
//! [`WorkspaceChange`]: crate::window_manager_event::WindowManagerEvent::WorkspaceChange
//! [`WorkspaceMove`]: crate::window_manager_event::WindowManagerEvent::WorkspaceMove
//!
@@ -67,7 +74,9 @@ use parking_lot::Mutex;
use serde_json::Value;
use serde_json::json;
use state::NeedsDesktops;
use state::NeedsPark;
use state::Output;
use state::PARK_DESKTOP_NAME;
use state::Table;
use std::collections::HashMap;
use std::collections::VecDeque;
@@ -142,6 +151,7 @@ impl Shared {
for output in outputs {
match output {
Output::Event(event) => window_manager_event_listener::send_notification(event),
Output::Command(command) => self.push(command),
Output::Cursor { token, x, y } => {
if let Some(waiter) = self.cursor_waiters.lock().remove(&token) {
let _ = waiter.send((x, y));
@@ -188,6 +198,9 @@ impl Events {
if is_snapshot {
self.shared.mark_ready();
// a parking desktop in a snapshot is one nobody is using: from an earlier run, or one
// that KWin kept in its configuration when it restarted under this one
sweep_stale_park(&self.shared);
}
}
}
@@ -526,6 +539,23 @@ async fn supervise(shared: Arc<Shared>) {
}
}
/// Removes the parking desktop an earlier run left behind, once its windows have moved home: the
/// snapshot that found it sent them, and they take a moment to get there
fn sweep_stale_park(shared: &Arc<Shared>) {
let Some(stale) = shared.table.lock().stale_park().map(String::from) else {
return;
};
let shared = shared.clone();
shared.handle.clone().spawn(async move {
tokio::time::sleep(Duration::from_millis(500)).await;
if let Err(error) = remove_desktop(&shared, &stale).await {
tracing::warn!("could not remove the stale parking desktop: {error}");
}
shared.table.lock().clear_stale_park();
});
}
async fn desktop_manager(shared: &Shared) -> eyre::Result<Proxy<'static>> {
let connection = shared.connection().await?;
// uncached: a property read right after createDesktop must not return the list from before it
@@ -543,6 +573,33 @@ async fn desktops(manager: &Proxy<'static>) -> eyre::Result<Vec<(u32, String, St
Ok(manager.get_property("desktops").await?)
}
/// The id of the desktop windows are hidden on, which is made when there is none: not the one an
/// earlier run left, which is about to go and would take the windows with it
async fn create_park_desktop(shared: &Shared) -> eyre::Result<String> {
let manager = desktop_manager(shared).await?;
let stale = shared.table.lock().stale_park().map(String::from);
let ours = |(_, id, name): &(u32, String, String)| {
name == PARK_DESKTOP_NAME && Some(id.as_str()) != stale.as_deref()
};
if let Some((_, id, _)) = desktops(&manager).await?.into_iter().find(ours) {
return Ok(id);
}
let count: u32 = manager.get_property("count").await?;
manager
.call_method("createDesktop", &(count, PARK_DESKTOP_NAME))
.await?;
desktops(&manager)
.await?
.into_iter()
.find(ours)
.map(|(_, id, _)| id)
.ok_or_eyre("KWin did not create the parking desktop")
}
/// "Desktop 2" is what KWin calls a desktop nobody named, and "Workspace 2" what komorebi calls one
/// it made for a workspace that has no name: neither is anyone's choice.
fn is_placeholder(name: &str) -> bool {
@@ -557,16 +614,23 @@ fn is_placeholder(name: &str) -> bool {
async fn create_workspace_desktops(shared: &Shared, names: &[String]) -> eyre::Result<()> {
let manager = desktop_manager(shared).await?;
let existing = desktops(&manager).await?;
let have = existing.len();
let have = existing
.iter()
.filter(|(_, _, name)| name != PARK_DESKTOP_NAME)
.count();
for (position, name) in names.iter().enumerate().skip(have) {
// by position, so that the parking desktop stays last
manager
.call_method("createDesktop", &(position as u32, name.as_str()))
.await?;
}
// the ones nobody named take the workspaces' names; the ones somebody did keep theirs
for ((_, id, name), wanted) in existing.iter().zip(names) {
let nameable = existing
.iter()
.filter(|(_, _, name)| name != PARK_DESKTOP_NAME);
for ((_, id, name), wanted) in nameable.zip(names) {
if is_placeholder(name) && !is_placeholder(wanted) {
manager
.call_method("setDesktopName", &(id.as_str(), wanted.as_str()))
@@ -582,6 +646,12 @@ async fn create_workspace_desktops(shared: &Shared, names: &[String]) -> eyre::R
Ok(())
}
async fn remove_desktop(shared: &Shared, id: &str) -> eyre::Result<()> {
let manager = desktop_manager(shared).await?;
manager.call_method("removeDesktop", &(id,)).await?;
Ok(())
}
/// KWin's own "Move Mouse to Focus" action: the scripting API cannot move the pointer
async fn move_mouse_to_focus(shared: &Shared) -> eyre::Result<()> {
let connection = shared.connection().await?;
@@ -690,6 +760,47 @@ impl Backend for KWinBackend {
self.command(id, |uuid| json!({ "op": "raise", "id": uuid }))
}
fn hide(&self, id: u32) -> eyre::Result<()> {
self.shared
.table
.lock()
.uuid(id)
.ok_or_eyre("there is no such window")?;
let commands = loop {
let attempt = self.shared.table.lock().hide_commands(id);
match attempt {
Ok(commands) => break commands,
Err(NeedsPark) => {
let shared = self.shared.clone();
let park = self
.shared
.block_on(async move { create_park_desktop(&shared).await })??;
self.shared.table.lock().set_park(park);
}
}
};
for command in commands {
self.shared.push(command);
}
Ok(())
}
fn restore(&self, id: u32) -> eyre::Result<()> {
self.shared
.table
.lock()
.uuid(id)
.ok_or_eyre("there is no such window")?;
let commands = self.shared.table.lock().restore_commands(id);
for command in commands {
self.shared.push(command);
}
Ok(())
}
fn ensure_workspaces(&self, names: &[String]) -> eyre::Result<()> {
let shared = self.shared.clone();
let names = names.to_vec();
@@ -760,10 +871,28 @@ impl Backend for KWinBackend {
}
fn shutdown(&self) {
// the script goes with komorebi: KWin would otherwise keep running it, reporting to nobody
// the window manager has already restored every window it hid. What is left is the parking
// desktop, which KWin would otherwise keep in the user's configuration, and the script,
// which KWin would otherwise keep running, reporting to nobody
let park = self.shared.table.lock().park_desktop().map(String::from);
let shared = self.shared.clone();
let told_kwin = self.shared.block_on(async move {
// let the restoring commands reach the script before the desktop goes
for _ in 0..40 {
if shared.queue.lock().is_empty() {
break;
}
tokio::time::sleep(Duration::from_millis(25)).await;
}
tokio::time::sleep(Duration::from_millis(300)).await;
if let Some(park) = park
&& let Err(error) = remove_desktop(&shared, &park).await
{
tracing::warn!("could not remove the parking desktop: {error}");
}
// every setting of KWin's that komorebi changed
if let Ok(connection) = shared.connection().await
&& let Some(kwinrc) = &shared.kwinrc
@@ -902,6 +1031,55 @@ mod tests {
let (runtime, backend) = offline();
assert!(backend.focus(7, false).is_err());
assert!(backend.hide(7).is_err());
assert!(backend.restore(7).is_err());
assert_eq!(next_poll(&runtime, &backend), json!([]));
}
#[test]
fn hiding_a_window_sends_it_to_the_parking_desktop_and_restoring_it_sends_it_home() {
let (runtime, backend) = offline();
{
let mut table = backend.shared.table.lock();
table.handle(
&json!({
"type": "snapshot",
"windows": [{
"id": "{a}", "pid": 0, "class": "foot", "caption": "a terminal",
"normal": true, "minimized": false, "desktops": ["d1"],
"geo": { "x": 0, "y": 0, "w": 800, "h": 600 },
}],
"screens": [],
"desktops": [
{ "id": "d1", "name": "Desktop 1" },
{ "id": "p1", "name": PARK_DESKTOP_NAME },
],
"current_desktops": [],
"active": null,
"cursor": { "x": 0, "y": 0 },
}),
Instant::now(),
);
// a snapshot that has the parking desktop has one left from an earlier run; this
// run's is the one it makes itself
table.clear_stale_park();
table.set_park(String::from("p1"));
}
backend.hide(1).unwrap();
assert_eq!(
next_poll(&runtime, &backend),
json!([{ "batch": 1, "cmds": [{ "op": "desktop", "id": "{a}", "v": "p1" }] }])
);
backend.restore(1).unwrap();
assert_eq!(
next_poll(&runtime, &backend),
json!([{ "batch": 2, "cmds": [{ "op": "desktop", "id": "{a}", "v": "d1" }] }])
);
// a window that is not hidden is not sent anywhere
backend.restore(1).unwrap();
assert_eq!(next_poll(&runtime, &backend), json!([]));
}
+485 -18
View File
@@ -13,6 +13,13 @@
//! ([`Table::switch_commands`], [`Table::window_workspace_commands`]), so that the table knows what
//! komorebi asked for and does not report it back as somebody else's doing.
//!
//! A window komorebi hides, the back of a stack, goes to one more desktop, the parking desktop
//! ([`PARK_DESKTOP_NAME`]), which is not a workspace and which nobody looks at
//! ([`Table::hide_commands`], [`Table::restore_commands`]). The table keeps the desktop the window
//! came from, so that [`Table::window_workspace`] still names its workspace, and does not report
//! the move to the parking desktop as somebody else's doing. A parking desktop that an earlier run
//! left behind is found in the first snapshot, its windows are sent home, and it is removed.
//!
//! # Example
//!
//! The script's first report is a snapshot of the desktop. A window that opens after it is an
@@ -71,6 +78,9 @@ use std::collections::HashMap;
use std::time::Duration;
use std::time::Instant;
/// The name of the virtual desktop komorebi hides windows on
pub const PARK_DESKTOP_NAME: &str = "komorebi-park";
/// How long a closed window can still be asked about, so that the `Destroy` event that names it
/// can be logged and serialized
const TOMBSTONE: Duration = Duration::from_secs(60);
@@ -81,6 +91,10 @@ struct Entry {
/// What KWin says: a normal window, as opposed to a dialog, splash, panel, popup...
kwin_normal: bool,
desktops: Vec<String>,
/// komorebi put it on the parking desktop
parked: bool,
/// The desktop the window was on when it was parked
home: Option<String>,
closed_at: Option<Instant>,
}
@@ -89,6 +103,8 @@ struct Entry {
pub enum Output {
/// A window event for the window manager.
Event(WindowManagerEvent),
/// A command for the script, to be queued with the others.
Command(Value),
/// The answer to a cursor query.
Cursor {
/// The query this answers, as the daemon numbered it.
@@ -121,6 +137,13 @@ pub struct Table {
/// KWin's per-output virtual desktops), which is what lets every monitor have a workspace of
/// its own in front.
current: HashMap<String, String>,
/// The workspace desktop an output showed before the parking desktop, so that it can be sent
/// back
previous: HashMap<String, String>,
/// The desktop this run hides windows on, once it has made one
park_desktop: Option<String>,
/// A parking desktop left behind by an earlier run, to be removed once it is empty
stale_park: Option<String>,
}
fn rect(v: &Value) -> Rect {
@@ -232,6 +255,23 @@ impl Table {
self.windows.get(&id).map(|e| e.uuid.clone())
}
/// Returns the desktop this run hides windows on, if it has made one. It is not in step with
/// the desktops KWin lists: [`Table::hide_commands`] checks that it is still there.
pub fn park_desktop(&self) -> Option<&str> {
self.park_desktop.as_deref()
}
/// Returns the parking desktop an earlier run left behind, until it has been removed. It is
/// never the parking desktop of this run: it goes as soon as the windows on it have moved home.
pub fn stale_park(&self) -> Option<&str> {
self.stale_park.as_deref()
}
/// Records that the stale parking desktop is gone.
pub fn clear_stale_park(&mut self) {
self.stale_park = None;
}
/// Whether komorebi should have anything to do with this window: a normal window, as opposed
/// to a dialog, a panel, a popup. Every desktop is a workspace of komorebi's.
fn manageable(&self, entry: &Entry) -> bool {
@@ -240,9 +280,13 @@ impl Table {
// ---- workspaces ------------------------------------------------------------------------
/// The ids of the desktops that are workspaces, in order: all of them
/// The ids of the desktops that are workspaces, in order: all of them but the parking desktop
fn workspace_desktops(&self) -> Vec<&str> {
self.desktops.iter().map(|(id, _)| id.as_str()).collect()
self.desktops
.iter()
.filter(|(_, name)| name != PARK_DESKTOP_NAME)
.map(|(id, _)| id.as_str())
.collect()
}
/// Which workspace a desktop is
@@ -250,11 +294,21 @@ impl Table {
self.workspace_desktops().iter().position(|d| *d == desktop)
}
/// Returns the workspace a window is on: the first of its desktops. A window on every desktop
/// (KWin gives it no desktop) is on none.
/// Where windows go when nothing says otherwise: the first desktop
fn default_desktop(&self) -> Option<String> {
self.workspace_desktops().first().map(|d| d.to_string())
}
/// Returns the workspace a window is on: the first of its desktops. A window komorebi has
/// hidden is on the workspace it will come back to, and one on every desktop (KWin gives it no
/// desktop) is on none.
pub fn window_workspace(&self, id: u32) -> Option<usize> {
let entry = self.windows.get(&id)?;
let desktop = entry.desktops.first()?;
let desktop = if entry.parked {
entry.home.as_ref()
} else {
entry.desktops.first()
}?;
self.workspace_index(desktop)
}
@@ -311,7 +365,8 @@ impl Table {
/// Returns the commands that put a window on workspace `idx`, and records the window there,
/// so that the next query sees it at once and KWin's report of the move raises nothing. A
/// window the table does not know gets no command.
/// window the table does not know gets no command, and a window komorebi has hidden stays
/// hidden and comes back to the workspace.
///
/// # Errors
///
@@ -331,16 +386,128 @@ impl Table {
return Ok(vec![]);
};
if entry.parked {
entry.home = Some(desktop);
return Ok(vec![]);
}
entry.desktops = vec![desktop.clone()];
Ok(vec![
json!({ "op": "desktop", "id": entry.uuid, "v": desktop }),
])
}
// ---- hiding ----------------------------------------------------------------------------
/// Returns the commands that hide a window: onto the parking desktop, which is where KDE puts
/// what should be out of the way. The window remembers the desktop it came from. A window the
/// table does not know, or that is hidden already, gets no command.
///
/// # Errors
///
/// [`NeedsPark`] when this run has no parking desktop, or KWin no longer lists the one it made
/// (somebody removed it, in System Settings, say, and windows sent to it would have nowhere to
/// go): make one, tell the table with [`Table::set_park`], then ask again.
///
/// # Example
///
/// ```rust
/// use std::time::Instant;
///
/// use komorebi::kwin::state::{NeedsPark, PARK_DESKTOP_NAME, Table};
/// use serde_json::json;
///
/// let mut table = Table::new();
/// let now = Instant::now();
/// table.handle(
/// &json!({
/// "type": "snapshot",
/// "windows": [{
/// "id": "{a}", "pid": 0, "class": "foot", "caption": "a terminal",
/// "normal": true, "minimized": false, "desktops": ["d1"],
/// "geo": { "x": 0, "y": 0, "w": 800, "h": 600 },
/// }],
/// "screens": [],
/// "desktops": [{ "id": "d1", "name": "Desktop 1" }],
/// "current_desktops": [],
/// "active": null,
/// "cursor": { "x": 0, "y": 0 },
/// }),
/// now,
/// );
///
/// // there is no parking desktop yet: the backend makes one, and says which it is
/// assert!(matches!(table.hide_commands(1), Err(NeedsPark)));
/// table.handle(
/// &json!({ "type": "desktop_list", "desktops": [
/// { "id": "d1", "name": "Desktop 1" },
/// { "id": "p1", "name": PARK_DESKTOP_NAME },
/// ] }),
/// now,
/// );
/// table.set_park(String::from("p1"));
///
/// assert_eq!(
/// table.hide_commands(1).unwrap(),
/// [json!({ "op": "desktop", "id": "{a}", "v": "p1" })]
/// );
/// // it is still on its workspace, which is where it goes back to
/// assert_eq!(table.window_workspace(1), Some(0));
/// assert_eq!(
/// table.restore_commands(1),
/// [json!({ "op": "desktop", "id": "{a}", "v": "d1" })]
/// );
/// ```
pub fn hide_commands(&mut self, id: u32) -> Result<Vec<Value>, NeedsPark> {
// the one this run made, if it is still there: whoever removed it (the user, in System
// Settings, say) leaves windows sent to it with nowhere to go, and nothing says so
let park = self
.park_desktop
.clone()
.filter(|park| self.desktops.iter().any(|(id, _)| id == park));
let current = self.default_desktop();
let Some(entry) = self.windows.get_mut(&id) else {
return Ok(vec![]);
};
if entry.parked {
return Ok(vec![]);
}
let park = park.ok_or(NeedsPark)?;
// remember where it came from; a window on every desktop goes back to the current one
if entry.home.is_none() {
entry.home = entry.desktops.first().cloned().or(current);
}
entry.parked = true;
Ok(vec![
json!({ "op": "desktop", "id": entry.uuid, "v": park }),
])
}
/// Returns the commands that undo [`Table::hide_commands`]: the window goes back to the desktop
/// it came from, or to the first desktop when that is not known. A window that is not hidden
/// gets no command.
pub fn restore_commands(&mut self, id: u32) -> Vec<Value> {
let fallback = self.default_desktop();
let Some(entry) = self.windows.get_mut(&id) else {
return vec![];
};
if !std::mem::take(&mut entry.parked) {
return vec![];
}
let home = entry.home.take().or(fallback);
home.map(|home| vec![json!({ "op": "desktop", "id": entry.uuid, "v": home })])
.unwrap_or_default()
}
/// KWin went away. Its windows go with it, and nothing will report them closing.
///
/// Returns a [`WindowManagerEvent::Destroy`] for every window the window manager may manage,
/// as if each had been closed, and forgets which window has the focus. The windows stay in
/// as if each had been closed, and forgets which window has the focus and the parking desktop
/// (a new KWin may have kept it, and then finds it as a stale one). The windows stay in
/// the table as closed ones, so their ids are not given out again. A KWin that comes back
/// reports its desktop in a new snapshot.
pub fn compositor_lost(&mut self, now: Instant) -> Vec<Output> {
@@ -358,9 +525,20 @@ impl Table {
}
self.foreground = None;
self.park_desktop = None;
out
}
/// Records the desktop this run hides windows on, which the backend made
pub fn set_park(&mut self, id: String) {
self.park_desktop = Some(id);
}
/// Forgets the parking desktop, so that the next [`Table::hide_commands`] asks for one again
pub fn forget_park(&mut self) {
self.park_desktop = None;
}
/// Records the frame komorebi has just asked KWin to give a window, so that the window manager
/// sees it at once. The `geometry` event that says what the client did replaces it.
pub fn note_requested_rect(&mut self, id: u32, rect: Rect) {
@@ -406,6 +584,8 @@ impl Table {
info,
kwin_normal: w["normal"].as_bool().unwrap_or(false),
desktops: strings(&w["desktops"]),
parked: false,
home: None,
closed_at: None,
};
@@ -448,7 +628,8 @@ impl Table {
/// - `snapshot`: everything on the desktop (`windows`, `screens`, `desktops`,
/// `current_desktops`, `active`, `cursor`), sent once, when the script starts. It fills the
/// table and raises no event: the window manager reads the desktop from the table when it
/// starts.
/// starts. A parking desktop in it is one an earlier run left, and the windows on it are sent
/// home with [`Output::Command`]s.
/// - `added`, `removed`: a window opened or closed. For a window komorebi may manage, they are
/// a [`WindowManagerEvent::Show`] and a [`WindowManagerEvent::Destroy`].
/// - `activated`: KWin gave a window the focus ([`WindowManagerEvent::FocusChange`]), or,
@@ -459,10 +640,13 @@ impl Table {
/// - `geometry`: a window's frame changed. It raises no event.
/// - `desktops`: a window is on other desktops. When it is now on another workspace than the
/// table had it on, this is a [`WindowManagerEvent::WorkspaceMove`]; komorebi's own move
/// ([`Table::window_workspace_commands`]) is on it already, and raises nothing.
/// ([`Table::window_workspace_commands`]) is on it already, and raises nothing, and neither
/// does a window on the parking desktop.
/// - `current_desktops`: the desktop each output shows. An output that shows another desktop
/// than the table had it showing is a [`WindowManagerEvent::WorkspaceChange`]; komorebi's own
/// switch ([`Table::switch_commands`]) raises nothing.
/// switch ([`Table::switch_commands`]) raises nothing. An output that shows the parking
/// desktop (KWin followed an activation of a hidden window there) is sent back to the
/// desktop it showed before, with an [`Output::Command`].
/// - `desktop_list`: the virtual desktops, in order. It raises no event.
/// - `cursor`: the answer to a cursor query ([`Output::Cursor`]).
/// - `failed`: commands the script could not carry out. They are logged.
@@ -525,9 +709,22 @@ impl Table {
}
fn on_snapshot(&mut self, event: &Value) -> Vec<Output> {
let mut out = vec![];
// desktops first: which workspace a window is on depends on them
self.desktops = desktop_list(&event["desktops"]);
self.current = current_map(&event["current_desktops"]);
self.previous = self.current.clone();
// a parking desktop at startup is left over from a run that did not clean up. It is not this
// run's: it is about to be removed, and anything parked on it would go with it. This run
// makes its own the first time it needs one.
self.park_desktop = None;
self.stale_park = self
.desktops
.iter()
.find(|(_, name)| name == PARK_DESKTOP_NAME)
.map(|(id, _)| id.clone());
// rebuild the windows, keeping the ids of those we already knew
let old = std::mem::take(&mut self.windows);
@@ -543,6 +740,17 @@ impl Table {
}
}
// windows an earlier run parked: put them back where the user will see them
if let (Some(park), Some(home)) = (self.stale_park.clone(), self.default_desktop()) {
for entry in self.windows.values() {
if entry.desktops == [park.clone()] {
out.push(Output::Command(
json!({ "op": "desktop", "id": entry.uuid, "v": home }),
));
}
}
}
self.foreground = event["active"]
.as_str()
.and_then(|u| self.by_uuid.get(u))
@@ -553,7 +761,7 @@ impl Table {
}
self.set_monitors(&event["screens"]);
vec![]
out
}
fn set_monitors(&mut self, screens: &Value) {
@@ -594,6 +802,7 @@ impl Table {
entry.info.alive = false;
entry.info.normal = false;
entry.closed_at = Some(now);
entry.parked = false;
}
if self.foreground == Some(id) {
@@ -686,13 +895,20 @@ impl Table {
let before = self.window_workspace(id);
let desktops = strings(&event["desktops"]);
// (or on the one an earlier run left, which they are being sent home from)
let parked_by_us = self
.park_desktop
.iter()
.chain(self.stale_park.iter())
.any(|park| desktops.contains(park));
if let Some(entry) = self.windows.get_mut(&id) {
entry.desktops = desktops;
}
// A window that is on another workspace's desktop than it was: komorebi's own doing coming
// back (the window manager already has it there) or somebody else's, which it will adopt.
// A window komorebi parked is where it put it. Otherwise this is a window that is on
// another workspace's desktop than it was: komorebi's own doing coming back (the window
// manager already has it there) or somebody else's, which it will adopt.
let after = self
.windows
.get(&id)
@@ -701,7 +917,7 @@ impl Table {
.and_then(|d| self.workspace_index(d));
match after {
Some(idx) if before != Some(idx) => {
Some(idx) if !parked_by_us && before != Some(idx) => {
vec![Output::Event(WindowManagerEvent::WorkspaceMove(
kwin(KWinNotification::WindowMovedToDesktop),
Window::from(id),
@@ -726,7 +942,22 @@ impl Table {
changes.sort();
for (output, desktop) in changes {
self.current.insert(output.clone(), desktop.clone());
let before = self.current.insert(output.clone(), desktop.clone());
// Activating a window komorebi has hidden (a taskbar click, an app raising itself) makes
// KWin follow it to the parking desktop, which has nothing on it but hidden windows. Go
// straight back; the window's own activation then tells komorebi to bring it forward.
if self.park_desktop.as_deref() == Some(desktop.as_str()) {
if let Some(back) = self.previous.get(&output).cloned().or(before) {
self.current.insert(output.clone(), back.clone());
out.push(Output::Command(
json!({ "op": "output_desktop", "output": output, "v": back }),
));
}
continue;
}
self.previous.insert(output.clone(), desktop.clone());
let (Some(idx), Some(monitor)) = (
self.workspace_index(&desktop),
@@ -776,6 +1007,14 @@ fn current_map(v: &Value) -> HashMap<String, String> {
.unwrap_or_default()
}
/// The error of a request to hide a window when there is no parking desktop to hide it on: it has
/// to be made first.
///
/// [`Table::hide_commands`] returns it; the KWin backend makes the desktop, records it with
/// [`Table::set_park`] and asks again.
#[derive(Debug)]
pub struct NeedsPark;
/// The error of a request for a workspace that has no desktop yet: at least this many desktops
/// are needed.
///
@@ -841,6 +1080,22 @@ mod tests {
t
}
/// The parking desktop as it is when it has been made: listed by the compositor, and the one
/// windows are hidden on
fn with_park(t: &mut Table) {
let mut desktops: Vec<Value> = t
.desktops
.iter()
.map(|(id, name)| json!({ "id": id, "name": name }))
.collect();
desktops.push(json!({ "id": "park", "name": PARK_DESKTOP_NAME }));
t.handle(
&json!({ "type": "desktop_list", "desktops": desktops }),
Instant::now(),
);
t.set_park("park".to_string());
}
fn events(out: &[Output]) -> Vec<String> {
out.iter()
.filter_map(|o| match o {
@@ -872,6 +1127,7 @@ mod tests {
format!("WorkspaceChange to {idx}")
}
Output::Event(e) => format!("{e} {}", e.window_id().unwrap_or(0)),
Output::Command(command) => format!("Command {command}"),
Output::Cursor { token, x, y } => format!("Cursor {token} at {x},{y}"),
})
.collect();
@@ -1189,6 +1445,20 @@ mod tests {
assert_eq!(t.workspace_count(), 2);
}
#[test]
fn the_parking_desktop_is_not_a_workspace() {
let mut t = Table::new();
let mut s = snapshot(vec![win("a", &["d1"])]);
s["desktops"] = json!([
{ "id": "d1", "name": "Desktop 1" },
{ "id": "d2", "name": "Desktop 2" },
{ "id": "park", "name": PARK_DESKTOP_NAME },
]);
t.handle(&s, Instant::now());
assert_eq!(t.workspace_count(), 2);
}
#[test]
fn moving_a_window_to_another_desktop_is_reported_once_as_a_workspace_move() {
let mut t = table(vec![win("a", &["d1"])]);
@@ -1217,17 +1487,38 @@ mod tests {
}
#[test]
fn komorebis_own_move_coming_back_from_kwin_raises_nothing() {
fn komorebis_own_move_and_its_park_and_restore_raise_nothing_new() {
let mut t = table(vec![win("a", &["d1"])]);
let now = Instant::now();
// komorebi put it on workspace 1; kwin says so
t.window_workspace_commands(1, 1).unwrap();
let out = t.handle(
&json!({ "type": "desktops", "id": "a", "desktops": ["d2"] }),
Instant::now(),
now,
);
assert!(out.is_empty(), "{out:?}");
// komorebi parked it; kwin says so, and then that it is back
with_park(&mut t);
t.hide_commands(1).unwrap();
let out = t.handle(
&json!({ "type": "desktops", "id": "a", "desktops": ["park"] }),
now,
);
assert!(out.is_empty(), "{out:?}");
t.restore_commands(1);
let out = t.handle(
&json!({ "type": "desktops", "id": "a", "desktops": ["d2"] }),
now,
);
assert!(
matches!(
&out[..],
[Output::Event(WindowManagerEvent::WorkspaceMove(_, _, 1))]
),
"restoring reports the workspace it came back to; the window manager already has it there: {out:?}"
);
}
#[test]
@@ -1243,6 +1534,16 @@ mod tests {
Some(1),
"visible to the next query at once"
);
// a window komorebi has hidden stays hidden, and comes back to the new workspace
with_park(&mut t);
t.hide_commands(1).unwrap();
assert!(t.window_workspace_commands(1, 0).unwrap().is_empty());
assert_eq!(t.window_workspace(1), Some(0));
assert_eq!(
t.restore_commands(1),
vec![json!({ "op": "desktop", "id": "a", "v": "d1" })]
);
}
#[test]
@@ -1272,6 +1573,170 @@ mod tests {
));
}
#[test]
fn parking_a_window_hides_it_without_unmanaging_it() {
let mut t = table(vec![win("a", &["d1"])]);
let now = Instant::now();
assert!(
t.hide_commands(1).is_err(),
"there is no parking desktop yet"
);
with_park(&mut t);
let cmds = t.hide_commands(1).unwrap();
assert_eq!(
cmds,
vec![json!({ "op": "desktop", "id": "a", "v": "park" })]
);
// kwin reports the window now being on the parking desktop: still ours
let out = t.handle(
&json!({ "type": "desktops", "id": "a", "desktops": ["park"] }),
now,
);
assert!(events(&out).is_empty());
assert!(t.window(1).unwrap().normal);
// and restoring sends it home again, not to wherever the user is now
let cmds = t.restore_commands(1);
assert_eq!(cmds, vec![json!({ "op": "desktop", "id": "a", "v": "d1" })]);
assert!(
t.restore_commands(1).is_empty(),
"restoring twice is a no-op"
);
}
#[test]
fn a_window_on_every_desktop_is_parked_and_returned_to_the_home_desktop() {
let mut t = table(vec![win("a", &[])]);
with_park(&mut t);
t.hide_commands(1).unwrap();
assert_eq!(
t.restore_commands(1),
vec![json!({ "op": "desktop", "id": "a", "v": "d1" })]
);
}
#[test]
fn a_parking_desktop_left_by_a_crashed_run_is_swept() {
let mut t = Table::new();
let mut s = snapshot(vec![win("stuck", &["park"]), win("fine", &["d1"])]);
s["desktops"] = json!([
{ "id": "d1", "name": "Desktop 1" },
{ "id": "park", "name": PARK_DESKTOP_NAME },
]);
let out = t.handle(&s, Instant::now());
let commands: Vec<&Value> = out
.iter()
.filter_map(|o| {
if let Output::Command(c) = o {
Some(c)
} else {
None
}
})
.collect();
assert_eq!(
commands,
vec![&json!({ "op": "desktop", "id": "stuck", "v": "d1" })]
);
assert_eq!(t.stale_park(), Some("park"));
t.clear_stale_park();
assert!(t.stale_park().is_none());
}
#[test]
fn a_stale_parking_desktop_is_not_the_one_windows_are_hidden_on() {
let mut t = Table::new();
let mut s = snapshot(vec![win("a", &["d1"])]);
s["desktops"] = json!([
{ "id": "d1", "name": "Desktop 1" },
{ "id": "stale", "name": PARK_DESKTOP_NAME },
]);
t.handle(&s, Instant::now());
// the stale one goes; hiding now needs a parking desktop of its own, and is not sent to it
assert!(t.hide_commands(1).is_err());
assert_eq!(t.park_desktop(), None);
}
#[test]
fn a_parking_desktop_that_has_gone_is_made_again_not_sent_windows() {
let mut t = table(vec![win("a", &["d1"])]);
t.set_park("park".to_string());
// nothing lists it: somebody removed it
assert!(
t.hide_commands(1).is_err(),
"a parking desktop that is not there is not one"
);
// once it is there, it is used
t.handle(
&json!({ "type": "desktop_list", "desktops": [
{ "id": "d1", "name": "Desktop 1" },
{ "id": "park", "name": PARK_DESKTOP_NAME },
] }),
Instant::now(),
);
t.set_park("park".to_string());
assert_eq!(
t.hide_commands(1).unwrap(),
vec![json!({ "op": "desktop", "id": "a", "v": "park" })]
);
}
#[test]
fn forgetting_the_parking_desktop_makes_hiding_ask_for_one_again() {
let mut t = table(vec![win("a", &["d1"])]);
with_park(&mut t);
assert_eq!(t.park_desktop(), Some("park"));
t.forget_park();
assert_eq!(t.park_desktop(), None);
assert!(t.hide_commands(1).is_err());
}
#[test]
fn a_window_the_table_does_not_know_is_neither_hidden_nor_restored() {
let mut t = table(vec![]);
with_park(&mut t);
assert!(t.hide_commands(9).unwrap().is_empty());
assert!(t.restore_commands(9).is_empty());
}
#[test]
fn a_window_that_closes_while_hidden_is_not_hidden_when_it_is_asked_about_again() {
let mut t = table(vec![win("a", &["d1"])]);
with_park(&mut t);
t.hide_commands(1).unwrap();
t.handle(&json!({ "type": "removed", "id": "a" }), Instant::now());
assert!(t.restore_commands(1).is_empty());
}
#[test]
fn following_a_hidden_window_to_the_parking_desktop_sends_that_output_back() {
let mut t = table(vec![win("a", &["d1"])]);
with_park(&mut t);
let out = t.handle(
&json!({ "type": "current_desktops", "current": [{ "output": "DP-1", "id": "park" }] }),
Instant::now(),
);
assert!(
matches!(&out[..], [Output::Command(c)]
if *c == json!({ "op": "output_desktop", "output": "DP-1", "v": "d1" })),
"{out:?}"
);
}
#[test]
fn another_party_switching_a_monitor_is_a_workspace_change() {
let mut t = table(vec![]);
@@ -1374,12 +1839,14 @@ mod tests {
#[test]
fn when_kwin_goes_away_every_window_it_had_is_destroyed() {
let mut t = table(vec![win("a", &["d1"]), win("b", &["d1"])]);
with_park(&mut t);
t.handle(&json!({ "type": "activated", "id": "a" }), Instant::now());
let mut destroyed = events(&t.compositor_lost(Instant::now()));
destroyed.sort();
assert_eq!(destroyed, vec!["Destroy 1", "Destroy 2"]);
assert_eq!(t.foreground(), None);
assert_eq!(t.park_desktop(), None);
assert!(t.windows().is_empty());
assert!(
t.compositor_lost(Instant::now()).is_empty(),
+6 -2
View File
@@ -39,6 +39,7 @@ use regex::Regex;
use serde::Deserialize;
use serde::Serialize;
use std::collections::HashMap;
use std::collections::HashSet;
use std::io::Write;
use std::os::unix::net::UnixStream;
use std::path::PathBuf;
@@ -134,6 +135,9 @@ lazy_static! {
/// The windows `UnmanageFocusedWindow` took out of the layout: komorebi leaves them alone
/// until `ManageFocusedWindow` takes them back, or until they close
static ref UNMANAGED_WINDOW_IDS: Arc<Mutex<Vec<u32>>> = Arc::new(Mutex::new(vec![]));
/// The windows komorebi took out of sight (the back of a stack, on the parking desktop), so
/// that what the compositor reports about them is not mistaken for something the user did
pub static ref HIDDEN_WINDOWS: Arc<Mutex<HashSet<u32>>> = Arc::new(Mutex::new(HashSet::new()));
}
/// The padding, in pixels, between the edge of a monitor's work area and the tiles of its
@@ -170,7 +174,7 @@ pub enum NotificationEvent {
/// use komorebi::core::SocketMessage;
/// use komorebi::window_manager_event::WindowManagerEvent;
///
/// let state = r#"{"monitors":{"elements":[],"focused":0},"monitor_usr_idx_map":{},"is_paused":false,"resize_delta":50,"cross_monitor_move_behaviour":"Swap","unmanaged_window_operation_behaviour":"Op","work_area_offset":null,"mouse_follows_focus":true}"#;
/// let state = r#"{"monitors":{"elements":[],"focused":0},"monitor_usr_idx_map":{},"is_paused":false,"resize_delta":50,"new_window_behaviour":"Create","float_override":false,"cross_monitor_move_behaviour":"Swap","unmanaged_window_operation_behaviour":"Op","work_area_offset":null,"mouse_follows_focus":true}"#;
///
/// let shown = format!(
/// r#"{{"event":{{"type":"Show","content":[{{"type":"KWin","content":"WindowAdded"}},{{"id":7}}]}},"state":{state}}}"#
@@ -245,7 +249,7 @@ pub struct Notification {
/// ]);
///
/// let state: State = serde_json::from_str(
/// r#"{"monitors":{"elements":[],"focused":0},"monitor_usr_idx_map":{},"is_paused":false,"resize_delta":50,"cross_monitor_move_behaviour":"Swap","unmanaged_window_operation_behaviour":"Op","work_area_offset":null,"mouse_follows_focus":true}"#,
/// r#"{"monitors":{"elements":[],"focused":0},"monitor_usr_idx_map":{},"is_paused":false,"resize_delta":50,"new_window_behaviour":"Create","float_override":false,"cross_monitor_move_behaviour":"Swap","unmanaged_window_operation_behaviour":"Op","work_area_offset":null,"mouse_follows_focus":true}"#,
/// )?;
/// let event = NotificationEvent::Socket(SocketMessage::Retile);
/// notify_subscribers(Notification { event, state }, false)?;
+8 -2
View File
@@ -14,8 +14,10 @@
//! It logs to standard output and to a file a day in [`struct@LOG_DIR`], which `komorebic log`
//! follows.
//!
//! When it stops, it connects to the socket of each subscriber and closes the connection without
//! writing anything, so a subscriber sees the daemon stop as a connection with nothing on it.
//! When it stops, it brings back the windows it hid (a stack's windows that were not in front,
//! except after a `StopIgnoreRestore` message), then connects to the socket of each subscriber
//! and closes the connection without writing anything, so a subscriber sees the daemon stop as a
//! connection with nothing on it.
use clap::Parser;
use clap::ValueEnum;
@@ -194,6 +196,10 @@ fn main() -> eyre::Result<()> {
let _ = quit_receiver.recv();
tracing::info!("stop signal received");
{
let mut wm = wm.lock();
wm.restore_all_windows(false)?;
}
backend::backend().shutdown();
let sockets = komorebi::SUBSCRIPTION_SOCKETS.lock();
+82 -3
View File
@@ -28,6 +28,18 @@
//! the previous one, and tile the workspace again
//! ([`WindowManager::move_container_in_direction`],
//! [`WindowManager::move_container_in_cycle_direction`]).
//! - **StackWindow** puts the focused window and the window in the container on one side of it in
//! one container, a stack that shows the window that moved and hides the other, and
//! **UnstackWindow** takes the focused window out of its stack again
//! ([`WindowManager::add_window_to_container`],
//! [`WindowManager::remove_window_from_container`]). **StackAll** puts every window of the
//! workspace in one stack, and **UnstackAll** takes every window out of the focused one
//! ([`WindowManager::stack_all`], [`WindowManager::unstack_all`]).
//! - **ToggleWindowContainerBehaviour** and **ToggleWorkspaceWindowContainerBehaviour** set whether
//! a window that opens gets a container of its own or joins the focused container, for every
//! workspace or for the focused one, and **ToggleFloatOverride** and
//! **ToggleWorkspaceFloatOverride** whether it floats
//! ([`WindowManager::window_management_behaviour`]).
//! - **Promote** moves the focused container to the largest tile, **PromoteSwap** swaps it with
//! the container there (and back), **PromoteFocus** gives that container the focus, and
//! **PromoteWindow** promotes the container on one side of the focused one
@@ -118,7 +130,8 @@
//! adjustments, and **RetileWithResizeDimensions** with them.
//! - **AddSubscriberSocket** and **AddSubscriberSocketWithOptions** add a subscriber by the name
//! of its socket in the data directory, and **RemoveSubscriberSocket** removes one.
//! - **Stop** stops the daemon ([`WindowManager::stop`]).
//! - **Stop** stops the daemon, after it has brought back the windows it hid, and
//! **StopIgnoreRestore** stops it without ([`WindowManager::stop`]).
//!
//! Once a message has been handled, every subscriber is sent a notification of it
//! ([`notify_subscribers`]).
@@ -144,6 +157,7 @@ use crate::core::Rect;
use crate::core::ScrollingLayoutOptions;
use crate::core::SocketMessage;
use crate::core::StateQuery;
use crate::core::WindowContainerBehaviour;
use crate::core::config_generation::IdWithIdentifier;
use crate::core::config_generation::MatchingRule;
use crate::core::config_generation::MatchingStrategy;
@@ -239,6 +253,11 @@ impl WindowManager {
/// `UnlockMonitorWorkspaceContainer` is not there (a container that is not there is ignored).
/// - The focused window cannot be floated or put back, for one of the reasons
/// [`WindowManager::toggle_float`] gives.
/// - The focused window cannot be stacked or unstacked, for one of the reasons
/// [`WindowManager::add_window_to_container`], [`WindowManager::remove_window_from_container`],
/// [`WindowManager::stack_all`] and [`WindowManager::unstack_all`] give, or the focused
/// workspace is not there for a behavior to be set on (`ToggleWorkspaceWindowContainerBehaviour`,
/// `ToggleWorkspaceFloatOverride`).
/// - The monitor a monitor command names is not there, or the compositor reports no window
/// with the focus to take to it ([`WindowManager::move_container_to_monitor`]).
/// - The monitor or the workspace a message names by its index is not there
@@ -260,7 +279,7 @@ impl WindowManager {
/// - The window manager fails to retile, for one of the reasons
/// [`WindowManager::retile_all`] gives.
/// - The answer cannot be written to `reply`.
/// - `Stop` fails, for the reason [`WindowManager::stop`] gives.
/// - `Stop` or `StopIgnoreRestore` fails, for the reason [`WindowManager::stop`] gives.
/// - The notification cannot be sent, for one of the reasons [`notify_subscribers`] gives.
#[tracing::instrument(skip(self, reply, message))]
pub fn process_command(
@@ -383,6 +402,18 @@ impl WindowManager {
SocketMessage::CycleMoveWindow(direction) => {
self.move_container_in_cycle_direction(direction)?;
}
SocketMessage::StackWindow(direction) => {
self.add_window_to_container(direction)?;
}
SocketMessage::UnstackWindow => {
self.remove_window_from_container()?;
}
SocketMessage::StackAll => {
self.stack_all()?;
}
SocketMessage::UnstackAll => {
self.unstack_all(true)?;
}
SocketMessage::CycleFocusMonitor(direction) => {
let monitor_idx = direction.next_idx(
self.focused_monitor_idx(),
@@ -900,7 +931,52 @@ impl WindowManager {
}
SocketMessage::Retile => self.retile_all(false)?,
SocketMessage::RetileWithResizeDimensions => self.retile_all(true)?,
SocketMessage::ToggleWorkspaceWindowContainerBehaviour => {
let current_global_behaviour = self.window_management_behaviour.current_behaviour;
if let Some(behaviour) =
&mut self.focused_workspace_mut()?.window_container_behaviour
{
match behaviour {
WindowContainerBehaviour::Create => {
*behaviour = WindowContainerBehaviour::Append
}
WindowContainerBehaviour::Append => {
*behaviour = WindowContainerBehaviour::Create
}
}
} else {
self.focused_workspace_mut()?.window_container_behaviour =
Some(match current_global_behaviour {
WindowContainerBehaviour::Create => WindowContainerBehaviour::Append,
WindowContainerBehaviour::Append => WindowContainerBehaviour::Create,
});
};
}
SocketMessage::ToggleWorkspaceFloatOverride => {
let current_global_override = self.window_management_behaviour.float_override;
if let Some(float_override) = &mut self.focused_workspace_mut()?.float_override {
*float_override = !*float_override;
} else {
self.focused_workspace_mut()?.float_override = Some(!current_global_override);
};
}
SocketMessage::ToggleLock => self.toggle_lock()?,
SocketMessage::ToggleWindowContainerBehaviour => {
match self.window_management_behaviour.current_behaviour {
WindowContainerBehaviour::Create => {
self.window_management_behaviour.current_behaviour =
WindowContainerBehaviour::Append;
}
WindowContainerBehaviour::Append => {
self.window_management_behaviour.current_behaviour =
WindowContainerBehaviour::Create;
}
}
}
SocketMessage::ToggleFloatOverride => {
self.window_management_behaviour.float_override =
!self.window_management_behaviour.float_override;
}
SocketMessage::ToggleWindowBasedWorkAreaOffset => {
let workspace = self.focused_workspace_mut()?;
workspace.apply_window_based_work_area_offset =
@@ -1279,7 +1355,10 @@ impl WindowManager {
sockets.remove(socket);
}
SocketMessage::Stop => {
self.stop()?;
self.stop(false)?;
}
SocketMessage::StopIgnoreRestore => {
self.stop(true)?;
}
SocketMessage::QuickSave => {
let workspace = self.focused_workspace()?;
+43 -10
View File
@@ -6,18 +6,23 @@
//! `UnmanageFocusedWindow`, changes nothing either. Otherwise:
//!
//! - **Show**, and **Manage** (`ManageFocusedWindow`): the window gets a container of its own after
//! the focused one, and the workspace is tiled again. The first window on an empty workspace is
//! given the focus. A window a float rule matches goes into the workspace's floating windows
//! the focused one, or joins the focused container when the window container behavior is
//! `Append` ([`WindowManager::window_management_behaviour`]), and the workspace is tiled again.
//! The first window on an empty workspace is given the focus. With the float override on, the
//! window floats instead. A window that another workspace has already is hidden and left to
//! that workspace. A window a float rule matches goes into the workspace's floating windows
//! instead, on a Show (a Manage tiles it whatever the rules say).
//! - **Destroy**, and **Unmanage** (`UnmanageFocusedWindow`): the window is taken out of whichever
//! workspace has it, and if that is the one in front it is tiled again. A window that is
//! workspace has it, and if that is the one in front it is tiled again. The window that was
//! behind it in a stack comes to the front. A window that is
//! unmanaged stays open, centered in the work area so that it is not left behind the tiles, and
//! komorebi leaves it alone until it is managed again.
//! - **FocusChange**: the workspace is tiled again and the container of the window that has the
//! focus becomes the focused container. In the scrolling layout the workspace is tiled after
//! that instead, so that the strip scrolls to the window that has the focus.
//! - **Minimize**: a window the user minimized leaves its workspace and the rest are tiled
//! again; **Restore** brings it back in a container of its own.
//! 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.
//! - **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.
//! - **WorkspaceChange**: a monitor shows another workspace, because something other than komorebi
@@ -42,6 +47,7 @@
//! [`Monitor::assign_windows_to_workspaces`]: crate::monitor::Monitor::assign_windows_to_workspaces
use crate::FLOATING_APPLICATIONS;
use crate::HIDDEN_WINDOWS;
use crate::Notification;
use crate::NotificationEvent;
use crate::REGEX_IDENTIFIERS;
@@ -49,6 +55,7 @@ use crate::UNMANAGED_WINDOW_IDS;
use crate::backend::backend;
use crate::core::DefaultLayout;
use crate::core::Layout;
use crate::core::WindowContainerBehaviour;
use crate::notify_subscribers;
use crate::state::State;
use crate::window::RuleDebug;
@@ -59,6 +66,7 @@ use crate::window_manager_event::SystemNotification;
use crate::window_manager_event::WindowManagerEvent;
use crate::window_manager_event_listener;
use color_eyre::eyre;
use color_eyre::eyre::OptionExt;
use parking_lot::Mutex;
use std::sync::Arc;
use tracing::instrument;
@@ -234,6 +242,10 @@ impl WindowManager {
}
}
WindowManagerEvent::Show(_, _) | WindowManagerEvent::Manage(_) => {
let focused_monitor_idx = self.focused_monitor_idx();
let focused_workspace_idx =
self.focused_workspace_idx_for_monitor_idx(focused_monitor_idx)?;
let mut create = true;
if self.focused_workspace()?.contains_window(window_id) {
@@ -251,11 +263,13 @@ impl WindowManager {
"ignoring show event for window already associated with another workspace"
);
window.hide();
create = false;
}
if create {
let behaviour = self.window_management_behaviour;
let behaviour = self
.window_management_behaviour(focused_monitor_idx, focused_workspace_idx);
let workspace = self.focused_workspace_mut()?;
let floating_applications = FLOATING_APPLICATIONS.lock();
@@ -306,8 +320,19 @@ impl WindowManager {
self.update_focused_workspace(false, false)?;
} else {
workspace.new_container_for_window(&window)?;
self.update_focused_workspace(false, false)?;
match behaviour.current_behaviour {
WindowContainerBehaviour::Create => {
workspace.new_container_for_window(&window)?;
self.update_focused_workspace(false, false)?;
}
WindowContainerBehaviour::Append => {
workspace
.focused_container_mut()
.ok_or_eyre("there is no focused container")?
.add_window(&window)?;
self.update_focused_workspace(true, false)?;
}
}
if self.focused_workspace()?.containers().len() == 1 {
// If after adding this window the workspace only contains 1 window, it
@@ -324,7 +349,7 @@ impl WindowManager {
let location = self.known_window_ids.get(&window_id).cloned();
if let Some((m_idx, w_idx)) = location {
let behaviour = self.window_management_behaviour;
let behaviour = self.window_management_behaviour(m_idx, w_idx);
let focused = m_idx == self.focused_monitor_idx()
&& Some(w_idx) == self.focused_workspace_idx().ok();
@@ -362,6 +387,7 @@ impl WindowManager {
if destroyed {
self.minimized_windows.remove(&window_id);
HIDDEN_WINDOWS.lock().remove(&window_id);
UNMANAGED_WINDOW_IDS.lock().retain(|id| *id != window_id);
} else {
// we only want to add the window ID after the window has been removed
@@ -369,8 +395,15 @@ impl WindowManager {
}
}
WindowManagerEvent::Minimize(_, _) => {
self.extract_minimized_window(window_id)?;
self.update_focused_workspace(false, false)?;
// A window komorebi took out of sight is not one the user minimized, whatever the
// compositor reports about it: it stays in its container, and only the user's own
// minimizes are acted on
if HIDDEN_WINDOWS.lock().contains(&window_id) {
tracing::trace!("ignoring minimize of window {window_id}, hidden by komorebi");
} else {
self.extract_minimized_window(window_id)?;
self.update_focused_workspace(false, false)?;
}
}
WindowManagerEvent::Restore(_, _) => match self.minimized_windows.remove(&window_id) {
None => {}
+18 -2
View File
@@ -17,6 +17,7 @@ use crate::MANAGE_IDENTIFIERS;
use crate::core::MoveBehaviour;
use crate::core::OperationBehaviour;
use crate::core::Rect;
use crate::core::WindowContainerBehaviour;
use crate::core::config_generation::MatchingRule;
use crate::monitor::Monitor;
use crate::ring::Ring;
@@ -124,6 +125,8 @@ pub struct State {
pub monitor_usr_idx_map: HashMap<usize, usize>,
pub is_paused: bool,
pub resize_delta: i32,
pub new_window_behaviour: WindowContainerBehaviour,
pub float_override: bool,
pub cross_monitor_move_behaviour: MoveBehaviour,
pub unmanaged_window_operation_behaviour: OperationBehaviour,
pub work_area_offset: Option<Rect>,
@@ -167,6 +170,8 @@ impl From<&WindowManager> for State {
work_area_offset: workspace.work_area_offset,
apply_window_based_work_area_offset: workspace
.apply_window_based_work_area_offset,
window_container_behaviour: workspace.window_container_behaviour,
float_override: workspace.float_override,
globals: workspace.globals,
preselected_container_idx: None,
promotion_swap_container_idx: None,
@@ -189,6 +194,8 @@ impl From<&WindowManager> for State {
is_paused: wm.is_paused,
work_area_offset: wm.work_area_offset,
resize_delta: wm.resize_delta,
new_window_behaviour: wm.window_management_behaviour.current_behaviour,
float_override: wm.window_management_behaviour.float_override,
cross_monitor_move_behaviour: wm.cross_monitor_move_behaviour,
mouse_follows_focus: wm.mouse_follows_focus,
unmanaged_window_operation_behaviour: wm.unmanaged_window_operation_behaviour,
@@ -198,8 +205,9 @@ impl From<&WindowManager> for State {
impl State {
/// Returns true if and only if the window manager's monitors (with their workspaces,
/// containers and windows), whether it is paused, its unmanaged window operation behavior, its
/// work area offset or its mouse follows focus setting differ from this state's
/// containers and windows), whether it is paused, its new window behavior, its float override,
/// its unmanaged window operation behavior, its work area offset or its mouse follows focus
/// setting differ from this state's
///
/// A window is compared by its id only, so a window that moved or was renamed is not a
/// change.
@@ -214,6 +222,14 @@ impl State {
return true;
}
if self.new_window_behaviour != new.new_window_behaviour {
return true;
}
if self.float_override != new.float_override {
return true;
}
if self.cross_monitor_move_behaviour != new.cross_monitor_move_behaviour {
return true;
}
+66
View File
@@ -9,9 +9,14 @@
//! [`Window::should_manage`] decides whether komorebi manages a window: it has to be a normal
//! application window that is alive, and then the ignore and manage rules decide
//! ([`should_act`], [`should_act_individual`]), writing what they found to a [`RuleDebug`].
//!
//! [`Window::hide`] takes a window out of sight, which is what a stack does with every window but
//! the one in front, and records it in [`struct@HIDDEN_WINDOWS`] so that the window manager does
//! not mistake what the compositor reports about it for the user's doing.
use crate::FLOATING_APPLICATIONS;
use crate::FLOATING_WINDOW_TOGGLE_ASPECT_RATIO;
use crate::HIDDEN_WINDOWS;
use crate::IGNORE_IDENTIFIERS;
use crate::MANAGE_IDENTIFIERS;
use crate::PERMAIGNORE_CLASSES;
@@ -202,6 +207,8 @@ impl Window {
backend().close(self.id)
}
/// Minimizes the window, as the user asking for it would. [`Window::hide`] is what komorebi
/// does to keep the back of a stack out of the way.
pub fn minimize(self) -> eyre::Result<()> {
backend().minimize(self.id)
}
@@ -210,6 +217,29 @@ impl Window {
backend().unminimize(self.id)
}
/// Takes the window out of sight ([`Backend::hide`](crate::backend::Backend::hide)): the back
/// of a stack, which on KDE goes to a virtual desktop nobody looks at
///
/// The id is recorded in [`struct@HIDDEN_WINDOWS`] first, so that what the compositor reports
/// about the window because of this (a move to another desktop) is not mistaken for something
/// the user did. A backend that cannot hide the window is logged and not returned: the window
/// stays where it is, and stays recorded as hidden until [`Window::restore`].
pub fn hide(self) {
HIDDEN_WINDOWS.lock().insert(self.id);
if let Err(error) = backend().hide(self.id) {
tracing::warn!("failed to hide window {}: {error}", self.id);
}
}
/// Brings a window [hidden](Window::hide) back, and takes it out of
/// [`struct@HIDDEN_WINDOWS`]. A failure is logged, as for [`Window::hide`].
pub fn restore(self) {
HIDDEN_WINDOWS.lock().remove(&self.id);
if let Err(error) = backend().restore(self.id) {
tracing::warn!("failed to restore window {}: {error}", self.id);
}
}
/// Moves the window to the middle of `work_area`, keeping its size, or with `resize` making it
/// half as high as the work area and as wide as the aspect ratio of floating windows says
///
@@ -879,6 +909,8 @@ mod tests {
window.raise()?;
window.minimize()?;
window.unminimize()?;
window.hide();
window.restore();
window.close()
})?;
@@ -890,12 +922,46 @@ mod tests {
Command::Raise(203),
Command::Minimize(203),
Command::Unminimize(203),
Command::Hide(203),
Command::Restore(203),
Command::Close(203),
]
);
Ok(())
}
#[test]
fn a_window_komorebi_hid_is_recorded_until_it_is_restored() {
let fake = fake_with(209);
with_backend(fake.clone(), || {
let window = Window::from(209);
window.hide();
assert!(HIDDEN_WINDOWS.lock().contains(&209));
assert!(fake.is_hidden(209));
window.restore();
assert!(!HIDDEN_WINDOWS.lock().contains(&209));
assert!(!fake.is_hidden(209));
});
}
#[test]
fn a_window_the_backend_cannot_hide_is_recorded_all_the_same() {
let fake = Arc::new(FakeBackend::with_one_monitor());
with_backend(fake.clone(), || {
Window::from(210).hide();
assert!(HIDDEN_WINDOWS.lock().contains(&210));
assert!(!fake.is_hidden(210));
Window::from(210).restore();
assert!(!HIDDEN_WINDOWS.lock().contains(&210));
});
}
#[test]
fn only_a_normal_window_that_is_alive_is_managed() {
let fake = Arc::new(FakeBackend::with_one_monitor());
+418 -6
View File
@@ -22,6 +22,16 @@
//! ([`WindowManager::set_workspace_name`]) and found by its name on any monitor
//! ([`WindowManager::monitor_workspace_index_by_name`]).
//!
//! A container with more than one window is a stack. The window in front is the container's focused
//! window, and the others are hidden ([`Window::hide`]), on KDE on a virtual desktop nobody looks
//! at. Windows are stacked and unstacked one at a time
//! ([`WindowManager::add_window_to_container`], [`WindowManager::remove_window_from_container`])
//! or all of a workspace together ([`WindowManager::stack_all`], [`WindowManager::unstack_all`]),
//! and a window that opens joins the focused container instead of getting one of its own when the
//! window container behavior says so ([`WindowManager::window_management_behaviour`]).
//! [`WindowManager::stop`] brings back every window the window manager hid
//! ([`WindowManager::restore_all_windows`]).
//!
//! With more than one monitor, the focus and a move at the edge of a monitor cross to the monitor
//! in that direction ([`WindowManager::monitor_idx_in_direction`]), and a container or a workspace
//! can be taken to another monitor ([`WindowManager::move_container_to_monitor`],
@@ -30,6 +40,7 @@
//! [`listen_for_commands`]: crate::process_command::listen_for_commands
use crate::DATA_DIR;
use crate::HIDDEN_WINDOWS;
use crate::LibraryError;
use crate::SUBSCRIPTION_SOCKETS;
use crate::UNMANAGED_WINDOW_IDS;
@@ -46,6 +57,7 @@ use crate::core::OperationBehaviour;
use crate::core::OperationDirection;
use crate::core::Rect;
use crate::core::Sizing;
use crate::core::WindowContainerBehaviour;
use crate::core::WindowManagementBehaviour;
use crate::desktop;
use crate::lockable_sequence::Lockable;
@@ -60,6 +72,7 @@ use color_eyre::eyre::OptionExt;
use color_eyre::eyre::bail;
use crossbeam_channel::Receiver;
use std::collections::HashMap;
use std::collections::VecDeque;
use std::io::ErrorKind;
use std::net::Shutdown;
use std::num::NonZeroUsize;
@@ -611,6 +624,19 @@ impl WindowManager {
.ok_or_eyre("there is no workspace")
}
/// Returns the index of the workspace the monitor at `idx` shows
///
/// # Errors
///
/// There is no monitor at the index.
pub fn focused_workspace_idx_for_monitor_idx(&self, idx: usize) -> eyre::Result<usize> {
Ok(self
.monitors()
.get(idx)
.ok_or_eyre("there is no monitor at this index")?
.focused_workspace_idx())
}
pub fn focused_workspace_for_monitor_idx(&self, idx: usize) -> eyre::Result<&Workspace> {
self.monitors()
.get(idx)
@@ -708,16 +734,124 @@ impl WindowManager {
self.update_focused_workspace(false, false)
}
/// Stops the daemon: connects to every subscriber and closes the connection without writing
/// anything, removes the command socket, lets the backend give up what it set up in the
/// compositor, and exits the process with status 0
/// Stacks the focused window with the window in the container next to it in `direction`: the
/// two end up in one container, which shows the window that moved and hides the other.
/// Nothing happens when the layout has no container in that direction. A container that is
/// left with no window is removed.
///
/// # Errors
///
/// - There is no focused workspace, or it has no container.
/// - The windows cannot be moved into one container, or the one in front cannot be focused.
/// - The workspace cannot be tiled again.
#[tracing::instrument(skip(self))]
pub fn add_window_to_container(&mut self, direction: OperationDirection) -> eyre::Result<()> {
tracing::info!("adding window to container");
let mouse_follows_focus = self.mouse_follows_focus;
let workspace = self.focused_workspace_mut()?;
let len = NonZeroUsize::new(workspace.containers_mut().len())
.ok_or_eyre("there must be at least one container")?;
let current_container_idx = workspace.focused_container_idx();
let is_valid = direction
.destination(
workspace.layout.as_boxed_direction().as_ref(),
workspace.layout_flip,
workspace.focused_container_idx(),
len,
workspace.layout_options,
)
.is_some();
if is_valid {
let new_idx = workspace
.new_idx_for_direction(direction)
.ok_or_eyre("this is not a valid direction from the current position")?;
let mut changed_focus = false;
let adjusted_new_index = if new_idx > current_container_idx
&& !matches!(
workspace.layout,
Layout::Default(DefaultLayout::Grid)
| Layout::Default(DefaultLayout::UltrawideVerticalStack)
) {
workspace.focus_container(new_idx);
changed_focus = true;
new_idx.saturating_sub(1)
} else {
new_idx
};
let mut target_container_is_stack = false;
if let Some(container) = workspace.containers().get(adjusted_new_index)
&& container.windows().len() > 1
{
target_container_is_stack = true;
}
if let Some(current) = workspace.focused_container() {
if current.windows().len() > 1 && !target_container_is_stack {
workspace.focus_container(adjusted_new_index);
changed_focus = true;
workspace.move_window_to_container(current_container_idx)?;
} else {
workspace.move_window_to_container(adjusted_new_index)?;
}
}
if changed_focus && let Some(container) = workspace.focused_container_mut() {
container.load_focused_window()?;
if let Some(window) = container.focused_window() {
window.focus(mouse_follows_focus)?;
}
}
self.update_focused_workspace(mouse_follows_focus, false)?;
}
Ok(())
}
/// Takes the focused window out of its stack into a container of its own, next to the stack,
/// and shows the stack's next window in its place
///
/// # Errors
///
/// - The focused container has only one window.
/// - There is no focused workspace, container or window.
/// - The workspace cannot be tiled again.
#[tracing::instrument(skip(self))]
pub fn remove_window_from_container(&mut self) -> eyre::Result<()> {
tracing::info!("removing window");
if self.focused_container()?.windows().len() == 1 {
bail!("a container must have at least one window");
}
let workspace = self.focused_workspace_mut()?;
workspace.new_container_for_focused_window()?;
self.update_focused_workspace(self.mouse_follows_focus, false)
}
/// Stops the daemon: brings back the windows it has hidden, unless `ignore_restore` is set
/// ([`WindowManager::restore_all_windows`]), connects to every subscriber and closes the
/// connection without writing anything, removes the command socket, lets the backend give up
/// what it set up in the compositor (the desktop hidden windows are parked on), and exits the
/// process with status 0
///
/// # Errors
///
/// A connection to a subscriber cannot be shut down. The daemon does not stop.
#[tracing::instrument(skip(self))]
pub fn stop(&mut self) -> eyre::Result<()> {
tracing::info!("received stop command, terminating process");
pub fn stop(&mut self, ignore_restore: bool) -> eyre::Result<()> {
tracing::info!(
"received stop command, restoring all hidden windows and terminating process"
);
self.restore_all_windows(ignore_restore)?;
let sockets = SUBSCRIPTION_SOCKETS.lock();
for path in (*sockets).values() {
@@ -734,6 +868,25 @@ impl WindowManager {
std::process::exit(0)
}
/// Brings back every window komorebi has hidden, wherever it is (in a stack, or on a workspace
/// that is not in front): they are exactly the ones it recorded when it hid them
/// ([`struct@HIDDEN_WINDOWS`]). With `ignore_restore` it brings back none.
///
/// It never fails; the result is there so that callers can use `?`.
#[tracing::instrument(skip(self))]
pub fn restore_all_windows(&mut self, ignore_restore: bool) -> eyre::Result<()> {
tracing::info!("restoring all hidden windows");
if !ignore_restore {
let hidden: Vec<u32> = HIDDEN_WINDOWS.lock().iter().copied().collect();
for id in hidden {
Window::from(id).restore();
}
}
Ok(())
}
/// Shows workspace `idx` on the focused monitor, creating it (and the ones before it) if it
/// does not exist yet.
///
@@ -1666,7 +1819,14 @@ impl WindowManager {
self.update_focused_workspace(self.mouse_follows_focus, true)
}
/// Gives the focus to the window at `idx` in the focused container
/// Gives the focus to the window at `idx` in the focused container, and brings it to the front
/// when the container is a stack
///
/// # Errors
///
/// - The focused container has only one window and `idx` is not 0.
/// - The focused container has no window at `idx`.
/// - There is no focused container, or the workspace cannot be tiled again.
#[tracing::instrument(skip(self))]
pub fn focus_container_window(&mut self, idx: usize) -> eyre::Result<()> {
tracing::info!("focusing container window at index {idx}");
@@ -1687,6 +1847,7 @@ impl WindowManager {
}
container.focus_window(idx);
container.load_focused_window()?;
if let Some(window) = container.focused_window() {
window.focus(mouse_follows_focus)?;
@@ -1695,6 +1856,93 @@ impl WindowManager {
self.update_focused_workspace(mouse_follows_focus, true)
}
/// Puts every window of the focused workspace in one container, in the order they had, with the
/// window that had the focus in front and the others hidden
///
/// # Errors
///
/// There is no focused workspace, or it cannot be tiled again.
#[tracing::instrument(skip(self))]
pub fn stack_all(&mut self) -> eyre::Result<()> {
tracing::info!("stacking all windows on workspace");
let workspace = self.focused_workspace_mut()?;
let mut focused_hwnd = None;
if let Some(container) = workspace.focused_container()
&& let Some(window) = container.focused_window()
{
focused_hwnd = Some(window.id);
}
let workspace_hwnds =
workspace
.containers()
.iter()
.fold(VecDeque::new(), |mut hwnds, c| {
hwnds.extend(c.windows().clone());
hwnds
});
let mut container = Container::default();
*container.windows_mut() = workspace_hwnds;
*workspace.containers_mut() = VecDeque::from([container]);
workspace.focus_container(0);
if let Some(hwnd) = focused_hwnd
&& let Some(c) = workspace.focused_container_mut()
&& let Some(w_idx_to_focus) = c.idx_for_window(hwnd)
{
c.focus_window(w_idx_to_focus);
c.load_focused_window()?;
}
self.update_focused_workspace(self.mouse_follows_focus, true)
}
/// Takes every window out of the focused container, each into a container of its own, and
/// gives the focus back to the window that had it. With `update_workspace` the workspace is
/// tiled again.
///
/// # Errors
///
/// There is no focused workspace, or, with `update_workspace`, it cannot be tiled again.
#[tracing::instrument(skip(self))]
pub fn unstack_all(&mut self, update_workspace: bool) -> eyre::Result<()> {
tracing::info!("unstacking all windows in container");
let workspace = self.focused_workspace_mut()?;
let mut focused_window_id = None;
if let Some(container) = workspace.focused_container()
&& let Some(window) = container.focused_window()
{
focused_window_id = Some(window.id);
}
let initial_focused_container_index = workspace.focused_container_idx();
let mut focused_container = workspace.focused_container().cloned();
while let Some(focused) = &focused_container {
if focused.windows().len() > 1 {
workspace.new_container_for_focused_window()?;
workspace.focus_container(initial_focused_container_index);
focused_container = workspace.focused_container().cloned();
} else {
focused_container = None;
}
}
if let Some(window_id) = focused_window_id {
workspace.focus_container_by_window(window_id)?;
}
if update_workspace {
self.update_focused_workspace(self.mouse_follows_focus, true)?;
}
Ok(())
}
/// With [`OperationBehaviour::NoOp`], refuses a message while the window that has the focus
/// in the compositor is not in a container of the focused workspace: a window komorebi does
/// not manage, one the user unmanaged, or a floating window
@@ -1799,6 +2047,72 @@ impl WindowManager {
}
}
/// Returns the [`WindowManagementBehaviour`] that applies to a window that opens on the
/// workspace at `workspace_idx` of the monitor at `monitor_idx`: the workspace's own
/// `window_container_behaviour` and `float_override` where it sets them, and the window
/// manager's where it does not
///
/// An empty workspace has no container to append to, so `Append` is `Create` for it. A
/// workspace or a monitor that does not exist gets `Create`.
pub fn window_management_behaviour(
&self,
monitor_idx: usize,
workspace_idx: usize,
) -> WindowManagementBehaviour {
if let Some(monitor) = self.monitors().get(monitor_idx)
&& let Some(workspace) = monitor.workspaces().get(workspace_idx)
{
let current_behaviour = if let Some(behaviour) = workspace.window_container_behaviour {
if workspace.containers().is_empty()
&& matches!(behaviour, WindowContainerBehaviour::Append)
{
// You can't append to an empty workspace
WindowContainerBehaviour::Create
} else {
behaviour
}
} else if workspace.containers().is_empty()
&& matches!(
self.window_management_behaviour.current_behaviour,
WindowContainerBehaviour::Append
)
{
// You can't append to an empty workspace
WindowContainerBehaviour::Create
} else {
self.window_management_behaviour.current_behaviour
};
let float_override = if let Some(float_override) = workspace.float_override {
float_override
} else {
self.window_management_behaviour.float_override
};
return WindowManagementBehaviour {
current_behaviour,
float_override,
floating_layer_override: self.window_management_behaviour.floating_layer_override,
floating_layer_behaviour: self.window_management_behaviour.floating_layer_behaviour,
toggle_float_placement: self.window_management_behaviour.toggle_float_placement,
floating_layer_placement: self.window_management_behaviour.floating_layer_placement,
float_override_placement: self.window_management_behaviour.float_override_placement,
float_rule_placement: self.window_management_behaviour.float_rule_placement,
};
}
WindowManagementBehaviour {
current_behaviour: WindowContainerBehaviour::Create,
float_override: self.window_management_behaviour.float_override,
floating_layer_override: self.window_management_behaviour.floating_layer_override,
floating_layer_behaviour: self.window_management_behaviour.floating_layer_behaviour,
toggle_float_placement: self.window_management_behaviour.toggle_float_placement,
floating_layer_placement: self.window_management_behaviour.floating_layer_placement,
float_override_placement: self.window_management_behaviour.float_override_placement,
float_rule_placement: self.window_management_behaviour.float_rule_placement,
}
}
/// Gives the workspace at `workspace_idx` on the monitor at `monitor_idx` a workspace padding
/// of `size` pixels, around its tiles, and tiles the focused workspace again
///
@@ -2889,6 +3203,104 @@ mod tests {
}
}
#[test]
fn test_remove_window_from_container() {
let (mut wm, _context) = setup_window_manager();
{
// Create a first monitor
let mut m = monitor::new(
0,
Rect::default(),
Rect::default(),
"TestMonitor1".to_string(),
"TestDeviceID1".to_string(),
);
// Create a container
let mut container = Container::default();
// Add three windows to the container
for i in 0..3 {
container.windows_mut().push_back(Window::from(i));
}
// Should have 3 windows in the container
assert_eq!(container.windows().len(), 3);
// Focus last window
container.focus_window(2);
// Should be focused on the 2nd window
assert_eq!(container.focused_window_idx(), 2);
// Add the container to a workspace
let workspace = m.focused_workspace_mut().unwrap();
workspace.add_container_to_back(container);
// Add monitor to the window manager
wm.monitors_mut().push_back(m);
}
// Remove the focused window from the container
wm.remove_window_from_container().ok();
{
// Should have 2 containers in the workspace
let workspace = wm.focused_workspace_mut().unwrap();
assert_eq!(workspace.containers().len(), 2);
// Should contain 1 window in the new container
let container = workspace.focused_container_mut().unwrap();
assert_eq!(container.windows().len(), 1);
}
{
// Switch to the old container
let workspace = wm.focused_workspace_mut().unwrap();
workspace.focus_container(0);
// Should contain 2 windows in the old container
let container = workspace.focused_container_mut().unwrap();
assert_eq!(container.windows().len(), 2);
}
}
#[test]
fn test_remove_nonexistent_window_from_container() {
let (mut wm, _context) = setup_window_manager();
{
// Create a first monitor
let mut m = monitor::new(
0,
Rect::default(),
Rect::default(),
"TestMonitor1".to_string(),
"TestDeviceID1".to_string(),
);
// Create a container
let container = Container::default();
// Should have 3 windows in the container
assert_eq!(container.windows().len(), 0);
// Add the container to a workspace
let workspace = m.focused_workspace_mut().unwrap();
workspace.add_container_to_back(container);
// Add monitor to the window manager
wm.monitors_mut().push_back(m);
}
// Should receive an error when trying to remove a window from an empty container
let result = wm.remove_window_from_container();
assert!(
result.is_err(),
"Expected an error when trying to remove a window from an empty container"
);
}
#[test]
fn test_swap_containers() {
let (mut wm, _context) = setup_window_manager();
+363 -3
View File
@@ -14,6 +14,7 @@ use crate::core::Layout;
use crate::core::LayoutOptions;
use crate::core::OperationDirection;
use crate::core::Rect;
use crate::core::WindowContainerBehaviour;
use crate::lockable_sequence::LockableSequence;
use crate::ring::Ring;
use crate::window::Window;
@@ -42,6 +43,12 @@ pub struct Workspace {
pub work_area_offset: Option<Rect>,
/// Whether this workspace takes its monitor's window-based offset (true by default)
pub apply_window_based_work_area_offset: bool,
/// What a window that opens on this workspace gets, when it is not the window manager's
/// default: a container of its own, or a place in the focused container
pub window_container_behaviour: Option<WindowContainerBehaviour>,
/// Whether a window that opens on this workspace floats, when it is not the window manager's
/// default
pub float_override: Option<bool>,
#[serde(skip)]
pub globals: WorkspaceGlobals,
#[serde(skip_serializing_if = "Option::is_none")]
@@ -69,7 +76,9 @@ impl Default for Workspace {
globals: Default::default(),
tile: true,
apply_window_based_work_area_offset: true,
window_container_behaviour: None,
floating_windows: Default::default(),
float_override: None,
preselected_container_idx: None,
promotion_swap_container_idx: None,
}
@@ -181,6 +190,12 @@ impl Workspace {
idx
}
/// Focuses the container the window is in, and the window in it. When the window is in a stack
/// and was not the one in front, it is brought to the front ([`Container::load_focused_window`]).
///
/// # Errors
///
/// No container of the workspace has the window.
pub fn focus_container_by_window(&mut self, window_id: u32) -> eyre::Result<()> {
let container_idx = self
.container_idx_for_window(window_id)
@@ -195,8 +210,18 @@ impl Workspace {
.idx_for_window(window_id)
.ok_or_eyre("there is no window")?;
let mut should_load = false;
if container.focused_window_idx() != window_idx {
should_load = true
}
container.focus_window(window_idx);
if should_load {
container.load_focused_window()?;
}
self.focus_container(container_idx);
Ok(())
@@ -320,6 +345,14 @@ impl Workspace {
Ok(invalid_window_ids.len() + invalid_floating_window_ids.len())
}
/// Takes the window out of its container, and returns it. A container that is left with no
/// window is removed. One that is left with windows shows the one in front of them now and
/// gives it the focus in the compositor, so that closing the window in front of a stack brings
/// the next one up.
///
/// # Errors
///
/// No container of the workspace has the window.
pub fn remove_window(&mut self, window_id: u32) -> eyre::Result<Window> {
let container_idx = self
.container_idx_for_window(window_id)
@@ -343,6 +376,11 @@ impl Workspace {
if container.windows().is_empty() {
self.remove_container_by_idx(container_idx);
self.focus_previous_container();
} else {
container.load_focused_window()?;
if let Some(window) = container.focused_window() {
window.focus(false)?;
}
}
Ok(window)
@@ -420,11 +458,139 @@ impl Workspace {
false
}
/// Gives the focus to the window of this workspace that had it: the focused window of the
/// Moves the focused window of the focused container into the container at
/// `target_container_idx`, which is how a window is stacked. The window is put in front of
/// the target's, and the container it left is removed when it has no window left, or shows its
/// next window.
///
/// # Errors
///
/// There is no focused container or window, or no container at the target's index (counted
/// after the container the window left has been removed, if it goes).
pub fn move_window_to_container(&mut self, target_container_idx: usize) -> eyre::Result<()> {
let focused_idx = self.focused_container_idx();
let container = self
.focused_container_mut()
.ok_or_eyre("there is no container")?;
let window = container
.remove_focused_window()
.ok_or_eyre("there is no window")?;
// This is a little messy
let adjusted_target_container_index = if container.windows().is_empty() {
self.remove_container_by_idx(focused_idx);
if focused_idx < target_container_idx {
target_container_idx.saturating_sub(1)
} else {
target_container_idx
}
} else {
container.load_focused_window()?;
target_container_idx
};
let target_container = self
.containers_mut()
.get_mut(adjusted_target_container_index)
.ok_or_eyre("there is no container")?;
target_container.add_window(&window)?;
self.focus_container(adjusted_target_container_index);
self.focused_container_mut()
.ok_or_eyre("there is no container")?
.load_focused_window()?;
Ok(())
}
/// Takes the focused window out of its container, which is how a window is unstacked, and puts
/// it in a container of its own after the focused one. The container it left is removed when
/// it has no window left, or shows its next window.
///
/// # Errors
///
/// There is no focused container or window.
pub fn new_container_for_focused_window(&mut self) -> eyre::Result<()> {
let focused_container_idx = self.focused_container_idx();
let container = self
.focused_container_mut()
.ok_or_eyre("there is no container")?;
let window = container
.remove_focused_window()
.ok_or_eyre("there is no window")?;
if container.windows().is_empty() {
self.remove_container_by_idx(focused_container_idx);
} else {
container.load_focused_window()?;
}
self.new_container_for_window(&window)?;
let mut container = Container::default();
container.add_window(&window)?;
Ok(())
}
/// Hides every window of the workspace, or every one but `omit`: the floating windows and the
/// windows of every container. A scrolling workspace is tiled again first without its resize
/// adjustments, which are put back after, so that the windows are hidden where the layout
/// has them and not where they were dragged.
///
/// # Errors
///
/// Never: the result is there so that callers can use `?`.
pub fn hide(&mut self, omit: Option<u32>) -> eyre::Result<()> {
for window in self.floating_windows_mut().iter_mut().rev() {
let mut should_hide = omit.is_none();
if !should_hide
&& let Some(omit) = omit
&& omit != window.id
{
should_hide = true
}
if should_hide {
window.hide();
}
}
let mut resize_dimensions = None;
if matches!(self.layout, Layout::Default(DefaultLayout::Scrolling))
&& self.resize_dimensions.iter().any(|r| r.is_some())
{
resize_dimensions = Some(self.resize_dimensions.clone());
self.resize_dimensions = Vec::new();
if let Err(error) = self.update() {
tracing::error!("{error}");
}
}
for container in self.containers_mut() {
container.hide(omit)?;
}
if let Some(resize_dimensions) = resize_dimensions {
self.resize_dimensions = resize_dimensions;
}
Ok(())
}
/// Restores the window of every container that is in front, and the floating windows, and
/// gives the focus to the window of this workspace that had it: the focused window of the
/// focused container, or the focused floating window when there is no container.
///
/// The compositor shows a workspace's windows by itself when the workspace's desktop is shown;
/// this is what komorebi does after it has asked for that.
/// this is what komorebi does after it has asked for that, and it brings back what komorebi
/// itself has hidden (the back of a stack stays hidden).
pub fn restore(&mut self, mouse_follows_focus: bool) -> eyre::Result<()> {
let idx = self.focused_container_idx();
let mut to_focus = None;
@@ -437,10 +603,18 @@ impl Workspace {
}
}
for container in self.containers_mut() {
container.restore()?;
}
if let Some(container) = self.focused_container_mut() {
container.focus_window(container.focused_window_idx());
}
for window in self.floating_windows_mut() {
window.restore();
}
if let Some(window) = to_focus {
window.focus(mouse_follows_focus)?;
} else if let Some(floating_window) = self.focused_floating_window() {
@@ -509,7 +683,8 @@ impl Workspace {
}
/// Takes the focused window out of its container, and out of the layout, into the floating
/// windows of the workspace; a container that is left with no window is removed
/// windows of the workspace; a container that is left with no window is removed, and one that
/// is left with windows shows the one in front now
///
/// # Errors
///
@@ -532,6 +707,8 @@ impl Workspace {
if focused_idx == self.containers().len() {
self.focus_container(focused_idx.saturating_sub(1));
}
} else {
container.load_focused_window()?;
}
window
@@ -1167,6 +1344,43 @@ mod tests {
}
}
#[test]
fn test_locked_containers_stack() {
let mut ws = Workspace::default();
// add 6 containers
for i in 0..6 {
let mut container = Container::default();
container.windows_mut().push_back(Window::from(i));
if i == 4 {
container.locked = true;
}
ws.add_container_to_back(container);
}
assert_eq!(ws.containers().len(), 6);
// set index 3 focused
ws.focus_container(3);
// stack index 3 on top of index 2
ws.move_window_to_container(2).unwrap();
assert_eq!(ws.containers()[0].focused_window().unwrap().id, 0);
assert_eq!(ws.containers()[1].focused_window().unwrap().id, 1);
assert_eq!(ws.containers()[2].windows().len(), 2);
assert_eq!(ws.containers()[3].focused_window().unwrap().id, 5);
// index 4 should still be the same
assert_eq!(ws.containers()[4].focused_window().unwrap().id, 4);
// unstack
ws.new_container_for_focused_window().unwrap();
// all indexes should be at their original position
for i in 0..6 {
assert_eq!(ws.containers()[i].focused_window().unwrap().id, i as u32)
}
}
#[test]
fn test_contains_window() {
// Create default workspace
@@ -1574,6 +1788,55 @@ mod tests {
assert!(workspace.contains_window(2));
}
#[test]
fn test_move_window_to_container() {
let mut workspace = Workspace::default();
{
// Container with 0 windows
let container = Container::default();
workspace.add_container_to_back(container);
}
{
// Container with 3 windows
let mut container = Container::default();
for i in 0..3 {
container.windows_mut().push_back(Window::from(i));
}
workspace.add_container_to_back(container);
}
// Move A Window from container 1 to container 0
workspace.move_window_to_container(0).unwrap();
// Focus on container 0
workspace.focus_container(0);
// Container 0 should have 1 window
let container = workspace.focused_container_mut().unwrap();
assert_eq!(container.windows().len(), 1);
}
#[test]
fn test_move_window_to_non_existent_container() {
let mut workspace = Workspace::default();
// Add a container with one window
let mut container = Container::default();
container.windows_mut().push_back(Window::from(1));
workspace.add_container_to_back(container);
// Try to move window to a non-existent container
let result = workspace.move_window_to_container(8);
// Should return an error
assert!(
result.is_err(),
"Expected an error when moving a window to a non-existent container"
);
}
#[test]
fn test_remove_window() {
let mut workspace = Workspace::default();
@@ -1598,6 +1861,34 @@ mod tests {
assert!(!workspace.contains_window(1));
}
#[test]
fn test_new_container_for_focused_window() {
let mut workspace = Workspace::default();
{
// Container with 1 window
let mut container = Container::default();
for i in 0..3 {
container.windows_mut().push_back(Window::from(i));
}
workspace.add_container_to_back(container);
}
// Add focused window to new container
workspace.new_container_for_focused_window().ok();
// Should have 2 containers
assert_eq!(workspace.containers().len(), 2);
{
// Inspect new container. Should contain 1 window. Window name should be 0
workspace.focus_container(1);
let container = workspace.focused_container_mut().unwrap();
assert_eq!(container.windows().len(), 1);
assert!(workspace.contains_window(0));
}
}
#[test]
fn test_focus_container_by_window() {
let mut workspace = Workspace::default();
@@ -1860,6 +2151,75 @@ mod tests {
Ok(())
}
/// A workspace with the windows `ids` in containers of their own, and the last two of them
/// stacked: the last is in front, and the one before it hidden
fn workspace_with_a_stack(ids: &[u32]) -> (Arc<FakeBackend>, Workspace) {
let (fake, mut workspace) = workspace_with(ids);
let last = ids.len() - 1;
with_backend(fake.clone(), || {
workspace.focus_container(last);
workspace.move_window_to_container(last - 1).unwrap();
});
(fake, workspace)
}
#[test]
fn stacking_a_window_puts_it_in_front_and_hides_the_one_it_was_put_on() {
let (fake, workspace) = workspace_with_a_stack(&[431, 432, 433]);
assert_eq!(workspace.containers().len(), 2);
let stack = workspace.focused_container().unwrap();
assert_eq!(stack.focused_window().map(|w| w.id), Some(433));
assert!(fake.is_hidden(432) && !fake.is_hidden(433) && !fake.is_hidden(431));
}
#[test]
fn a_window_that_leaves_a_stack_shows_the_next_one() -> eyre::Result<()> {
let (fake, mut workspace) = workspace_with_a_stack(&[441, 442, 443]);
with_backend(fake.clone(), || workspace.remove_window(443))?;
assert!(!fake.is_hidden(442));
assert_eq!(workspace.containers().len(), 2);
assert_eq!(workspace.focused_container().unwrap().windows().len(), 1);
Ok(())
}
#[test]
fn focusing_a_hidden_window_of_a_stack_brings_it_to_the_front() -> eyre::Result<()> {
let (fake, mut workspace) = workspace_with_a_stack(&[451, 452, 453]);
assert!(fake.is_hidden(452));
with_backend(fake.clone(), || workspace.focus_container_by_window(452))?;
assert!(!fake.is_hidden(452) && fake.is_hidden(453));
Ok(())
}
#[test]
fn showing_the_workspace_again_restores_the_front_of_each_stack_and_no_other()
-> eyre::Result<()> {
let (fake, mut workspace) = workspace_with_a_stack(&[461, 462, 463]);
with_backend(fake.clone(), || workspace.restore(false))?;
assert!(fake.is_hidden(462), "the back of the stack stays hidden");
assert!(!fake.is_hidden(463) && !fake.is_hidden(461));
Ok(())
}
#[test]
fn hiding_a_workspace_hides_every_window_but_the_one_it_is_told_to_leave() -> eyre::Result<()> {
let (fake, mut workspace) = workspace_with_a_stack(&[471, 472, 473]);
with_backend(fake.clone(), || workspace.hide(Some(471)))?;
assert!(!fake.is_hidden(471) && fake.is_hidden(472) && fake.is_hidden(473));
with_backend(fake.clone(), || workspace.hide(None))?;
assert!(fake.is_hidden(471));
Ok(())
}
#[test]
fn update_drops_a_container_that_has_no_windows_left() -> eyre::Result<()> {
let (fake, mut workspace) = workspace_with(&[421]);
+481
View File
@@ -0,0 +1,481 @@
//! Stacking windows in one container, and taking the windows a stack does not show out of sight,
//! against an in-memory desktop.
//!
//! A container tiles one window, so the other windows of a stack are hidden: the backend is asked
//! to take them out of sight, and the window manager records them as hidden so that what the
//! compositor reports about them is not mistaken for the user's doing. The messages go in through
//! [`WindowManager::process_command`], and what comes out is which windows the containers hold and
//! which of them the fake desktop has hidden.
//!
//! Window ids are in the 33_000s; the hidden-window table is process-wide.
use komorebi::backend::Backend;
use komorebi::backend::fake::FakeBackend;
use komorebi::backend::with_backend;
use komorebi::core::OperationDirection;
use komorebi::core::SocketMessage;
use komorebi::core::WindowContainerBehaviour;
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 removed(id: u32) -> WindowManagerEvent {
WindowManagerEvent::Destroy(
SystemNotification::KWin(KWinNotification::WindowRemoved),
Window::from(id),
)
}
fn minimized(id: u32) -> WindowManagerEvent {
WindowManagerEvent::Minimize(
SystemNotification::KWin(KWinNotification::WindowMinimized),
Window::from(id),
)
}
/// 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. The last one has the focus.
fn desktop_with(ids: &[u32]) -> (Arc<FakeBackend>, WindowManager) {
let fake = Arc::new(FakeBackend::with_one_monitor());
let (_sender, receiver) = crossbeam_channel::bounded(1);
// unix socket paths are limited to ~104 bytes on macOS, which the temp dir alone can exceed
static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
let socket = std::path::PathBuf::from(format!(
"/tmp/kms-{}-{}.sock",
std::process::id(),
NEXT.fetch_add(1, std::sync::atomic::Ordering::SeqCst)
));
let mut wm = with_backend(fake.clone(), || {
let mut wm = WindowManager::new(receiver, Some(socket)).unwrap();
wm.init().unwrap();
wm
});
for &id in ids {
open(&fake, &mut wm, id);
}
(fake, wm)
}
/// Opens a window, which KWin gives the focus, as it does a new window
fn open(fake: &Arc<FakeBackend>, wm: &mut WindowManager, id: u32) {
fake.open_window(id, "foot", "foot", &format!("terminal {id}"));
with_backend(fake.clone(), || wm.process_event(added(id))).unwrap();
fake.set_foreground(Some(id));
with_backend(fake.clone(), || wm.process_event(activated(id))).unwrap();
}
fn send(
fake: &Arc<FakeBackend>,
wm: &mut WindowManager,
message: SocketMessage,
) -> color_eyre::Result<()> {
with_backend(fake.clone(), || wm.process_command(message, Vec::new()))
}
fn process(
fake: &Arc<FakeBackend>,
wm: &mut WindowManager,
event: WindowManagerEvent,
) -> color_eyre::Result<()> {
with_backend(fake.clone(), || wm.process_event(event))
}
/// The ids of the windows of each container of the focused workspace, in order, the one in front
/// first
fn containers(wm: &WindowManager) -> Vec<Vec<u32>> {
wm.focused_workspace()
.unwrap()
.containers()
.iter()
.map(|container| {
let front = container.focused_window().unwrap().id;
let mut ids = vec![front];
ids.extend(
container
.windows()
.iter()
.map(|window| window.id)
.filter(|id| *id != front),
);
ids
})
.collect()
}
/// The windows among `ids` that the fake desktop has hidden
fn hidden(fake: &FakeBackend, ids: &[u32]) -> Vec<u32> {
ids.iter()
.copied()
.filter(|id| fake.is_hidden(*id))
.collect()
}
#[test]
fn a_minimize_komorebi_asked_for_is_not_mistaken_for_the_user() {
let (fake, mut wm) = desktop_with(&[33_001]);
// komorebi hides it (as it does the back of a stack), and the compositor reports a minimize
with_backend(fake.clone(), || Window::from(33_001).hide());
process(&fake, &mut wm, minimized(33_001)).unwrap();
assert!(wm.focused_workspace().unwrap().contains_window(33_001));
assert!(!wm.minimized_windows.contains_key(&33_001));
}
#[test]
fn a_minimize_the_user_asked_for_takes_the_window_out_of_the_layout() {
let (fake, mut wm) = desktop_with(&[33_011, 33_012]);
process(&fake, &mut wm, minimized(33_011)).unwrap();
assert!(!wm.focused_workspace().unwrap().contains_window(33_011));
assert!(wm.minimized_windows.contains_key(&33_011));
}
#[test]
fn stacking_puts_two_windows_in_one_container_and_hides_the_one_behind() {
let (fake, mut wm) = desktop_with(&[33_021, 33_022, 33_023]);
let ids = [33_021, 33_022, 33_023];
assert!(hidden(&fake, &ids).is_empty());
send(
&fake,
&mut wm,
SocketMessage::StackWindow(OperationDirection::Up),
)
.unwrap();
// 33_023 is the bottom right tile and had the focus: it goes onto 33_022, above it
assert_eq!(containers(&wm), [vec![33_021], vec![33_023, 33_022]]);
assert_eq!(hidden(&fake, &ids), [33_022]);
assert_eq!(fake.foreground_window(), Some(33_023));
}
#[test]
fn stacking_where_the_layout_has_nothing_changes_nothing() {
let (fake, mut wm) = desktop_with(&[33_031, 33_032]);
// the focused container is the last one, and BSP has nothing after it
send(
&fake,
&mut wm,
SocketMessage::StackWindow(OperationDirection::Right),
)
.unwrap();
assert_eq!(containers(&wm), [vec![33_031], vec![33_032]]);
assert!(hidden(&fake, &[33_031, 33_032]).is_empty());
}
#[test]
fn unstacking_gives_the_window_in_front_a_container_of_its_own_and_shows_the_next() {
let (fake, mut wm) = desktop_with(&[33_041, 33_042, 33_043]);
let ids = [33_041, 33_042, 33_043];
send(
&fake,
&mut wm,
SocketMessage::StackWindow(OperationDirection::Up),
)
.unwrap();
assert_eq!(hidden(&fake, &ids), [33_042]);
send(&fake, &mut wm, SocketMessage::UnstackWindow).unwrap();
assert_eq!(
containers(&wm),
[vec![33_041], vec![33_042], vec![33_043]],
"the window that was in front gets a container after the stack"
);
assert!(hidden(&fake, &ids).is_empty());
}
#[test]
fn a_window_alone_in_its_container_cannot_be_unstacked() {
let (fake, mut wm) = desktop_with(&[33_051, 33_052]);
let error = send(&fake, &mut wm, SocketMessage::UnstackWindow).unwrap_err();
assert_eq!(
error.to_string(),
"a container must have at least one window"
);
assert_eq!(containers(&wm), [vec![33_051], vec![33_052]]);
}
#[test]
fn stack_all_puts_every_window_in_one_container_and_unstack_all_gives_them_each_one_back() {
let (fake, mut wm) = desktop_with(&[33_061, 33_062, 33_063]);
let ids = [33_061, 33_062, 33_063];
send(&fake, &mut wm, SocketMessage::StackAll).unwrap();
assert_eq!(containers(&wm), [vec![33_063, 33_061, 33_062]]);
assert_eq!(hidden(&fake, &ids), [33_061, 33_062]);
send(&fake, &mut wm, SocketMessage::UnstackAll).unwrap();
let containers = containers(&wm);
assert_eq!(containers.len(), 3);
assert!(containers.iter().all(|windows| windows.len() == 1));
assert!(hidden(&fake, &ids).is_empty());
assert_eq!(
wm.focused_window().unwrap().id,
33_063,
"the window that had the focus keeps it"
);
}
#[test]
fn closing_the_window_in_front_of_a_stack_brings_the_next_one_forward() {
let (fake, mut wm) = desktop_with(&[33_071, 33_072]);
let ids = [33_071, 33_072];
send(&fake, &mut wm, SocketMessage::StackAll).unwrap();
assert_eq!(containers(&wm), [vec![33_072, 33_071]]);
assert_eq!(hidden(&fake, &ids), [33_071]);
fake.close_window_now(33_072);
process(&fake, &mut wm, removed(33_072)).unwrap();
assert_eq!(containers(&wm), [vec![33_071]]);
assert!(hidden(&fake, &ids).is_empty());
assert_eq!(fake.foreground_window(), Some(33_071));
}
#[test]
fn a_window_closed_while_it_is_hidden_leaves_the_stack_alone() {
let (fake, mut wm) = desktop_with(&[33_081, 33_082]);
send(&fake, &mut wm, SocketMessage::StackAll).unwrap();
fake.close_window_now(33_081);
process(&fake, &mut wm, removed(33_081)).unwrap();
assert_eq!(containers(&wm), [vec![33_082]]);
assert!(!fake.is_hidden(33_082));
}
#[test]
fn the_back_of_a_stack_stays_hidden_across_a_workspace_round_trip() {
let (fake, mut wm) = desktop_with(&[33_091, 33_092]);
let ids = [33_091, 33_092];
send(&fake, &mut wm, SocketMessage::StackAll).unwrap();
assert_eq!(hidden(&fake, &ids), [33_091]);
send(&fake, &mut wm, SocketMessage::FocusWorkspaceNumber(1)).unwrap();
send(&fake, &mut wm, SocketMessage::FocusWorkspaceNumber(0)).unwrap();
assert_eq!(containers(&wm), [vec![33_092, 33_091]]);
assert_eq!(hidden(&fake, &ids), [33_091]);
}
#[test]
fn a_stack_goes_to_another_workspace_whole_and_the_back_of_it_stays_hidden() {
let (fake, mut wm) = desktop_with(&[33_101, 33_102]);
let ids = [33_101, 33_102];
send(&fake, &mut wm, SocketMessage::StackAll).unwrap();
send(
&fake,
&mut wm,
SocketMessage::SendContainerToWorkspaceNumber(1),
)
.unwrap();
send(&fake, &mut wm, SocketMessage::FocusWorkspaceNumber(1)).unwrap();
assert_eq!(
wm.focused_workspace()
.unwrap()
.containers()
.iter()
.map(|container| container.windows().len())
.collect::<Vec<_>>(),
[2]
);
assert_eq!(fake.workspace_of(33_101), Some(1));
assert_eq!(fake.workspace_of(33_102), Some(1));
assert_eq!(hidden(&fake, &ids), [33_101]);
}
#[test]
fn with_append_a_window_that_opens_joins_the_focused_container() {
let (fake, mut wm) = desktop_with(&[33_111]);
let ids = [33_111, 33_112, 33_113];
send(
&fake,
&mut wm,
SocketMessage::ToggleWindowContainerBehaviour,
)
.unwrap();
assert_eq!(
wm.window_management_behaviour(0, 0).current_behaviour,
WindowContainerBehaviour::Append
);
open(&fake, &mut wm, 33_112);
open(&fake, &mut wm, 33_113);
assert_eq!(containers(&wm), [vec![33_113, 33_111, 33_112]]);
assert_eq!(hidden(&fake, &ids), [33_111, 33_112]);
send(
&fake,
&mut wm,
SocketMessage::ToggleWindowContainerBehaviour,
)
.unwrap();
assert_eq!(
wm.window_management_behaviour(0, 0).current_behaviour,
WindowContainerBehaviour::Create
);
}
#[test]
fn an_empty_workspace_has_nothing_to_append_to() {
let (fake, mut wm) = desktop_with(&[]);
send(
&fake,
&mut wm,
SocketMessage::ToggleWindowContainerBehaviour,
)
.unwrap();
open(&fake, &mut wm, 33_121);
open(&fake, &mut wm, 33_122);
assert_eq!(
containers(&wm),
[vec![33_122, 33_121]],
"the second window joins the first, which got a container of its own"
);
}
#[test]
fn the_behavior_of_one_workspace_does_not_change_the_others() {
let (fake, mut wm) = desktop_with(&[33_131]);
send(&fake, &mut wm, SocketMessage::EnsureWorkspaces(0, 2)).unwrap();
send(
&fake,
&mut wm,
SocketMessage::ToggleWorkspaceWindowContainerBehaviour,
)
.unwrap();
assert_eq!(
wm.window_management_behaviour(0, 0).current_behaviour,
WindowContainerBehaviour::Append
);
assert_eq!(
wm.window_management_behaviour(0, 1).current_behaviour,
WindowContainerBehaviour::Create,
"an empty workspace that is not set to append creates"
);
assert_eq!(
wm.window_management_behaviour.current_behaviour,
WindowContainerBehaviour::Create,
"the window manager's own is unchanged"
);
send(
&fake,
&mut wm,
SocketMessage::ToggleWorkspaceWindowContainerBehaviour,
)
.unwrap();
assert_eq!(
wm.window_management_behaviour(0, 0).current_behaviour,
WindowContainerBehaviour::Create
);
}
#[test]
fn with_the_float_override_a_window_that_opens_floats() {
let (fake, mut wm) = desktop_with(&[33_141]);
send(&fake, &mut wm, SocketMessage::ToggleFloatOverride).unwrap();
fake.open_window(33_142, "foot", "foot", "terminal 33142");
process(&fake, &mut wm, added(33_142)).unwrap();
let workspace = wm.focused_workspace().unwrap();
assert_eq!(containers(&wm), [vec![33_141]]);
assert!(workspace.floating_windows().iter().any(|w| w.id == 33_142));
send(&fake, &mut wm, SocketMessage::ToggleFloatOverride).unwrap();
open(&fake, &mut wm, 33_143);
assert_eq!(containers(&wm), [vec![33_141], vec![33_143]]);
}
#[test]
fn the_float_override_of_a_workspace_takes_the_opposite_of_the_global_one_the_first_time() {
let (fake, mut wm) = desktop_with(&[33_151]);
send(&fake, &mut wm, SocketMessage::ToggleFloatOverride).unwrap();
assert!(wm.window_management_behaviour(0, 0).float_override);
send(&fake, &mut wm, SocketMessage::ToggleWorkspaceFloatOverride).unwrap();
assert!(
!wm.window_management_behaviour(0, 0).float_override,
"the workspace's own override is the opposite of the global one that was on"
);
assert!(wm.window_management_behaviour.float_override);
send(&fake, &mut wm, SocketMessage::ToggleWorkspaceFloatOverride).unwrap();
assert!(wm.window_management_behaviour(0, 0).float_override);
}
#[test]
fn restoring_every_window_brings_back_the_hidden_ones_unless_it_is_told_to_ignore_that() {
let (fake, mut wm) = desktop_with(&[33_161, 33_162, 33_163]);
let ids = [33_161, 33_162, 33_163];
send(&fake, &mut wm, SocketMessage::StackAll).unwrap();
assert_eq!(hidden(&fake, &ids).len(), 2);
with_backend(fake.clone(), || wm.restore_all_windows(true)).unwrap();
assert_eq!(
hidden(&fake, &ids).len(),
2,
"with ignore_restore they stay hidden"
);
with_backend(fake.clone(), || wm.restore_all_windows(false)).unwrap();
assert!(hidden(&fake, &ids).is_empty());
}
#[test]
fn the_state_has_the_new_window_behavior_and_the_float_override() {
let (fake, mut wm) = desktop_with(&[33_171]);
let mut state = Vec::new();
send(
&fake,
&mut wm,
SocketMessage::ToggleWindowContainerBehaviour,
)
.unwrap();
send(&fake, &mut wm, SocketMessage::ToggleFloatOverride).unwrap();
with_backend(fake.clone(), || {
wm.process_command(SocketMessage::State, &mut state)
})
.unwrap();
let state: serde_json::Value = serde_json::from_slice(&state).unwrap();
assert_eq!(state["new_window_behaviour"], "Append");
assert_eq!(state["float_override"], true);
}
+11 -2
View File
@@ -4,7 +4,8 @@
//! show a workspace and to put a window on one. It follows a switch or a move that something else
//! made without undoing it, and does nothing when the compositor reports what komorebi did itself.
//!
//! Window ids are in the 10_000s and unique per test.
//! Window ids are in the 10_000s and unique per test, because the "hidden window" table is
//! process-wide.
use komorebi::backend::fake::Command;
use komorebi::backend::fake::FakeBackend;
@@ -132,6 +133,14 @@ fn switching_workspace_asks_the_compositor_to_show_the_other_desktop() {
!fake.on_screen(10_061),
"the window on workspace 0 is still shown"
);
assert!(
!fake
.commands()
.iter()
.any(|c| matches!(c, Command::Hide(_))),
"komorebi hid a window for a workspace switch: {:?}",
fake.commands()
);
}
#[test]
@@ -291,7 +300,7 @@ fn focus_going_to_a_window_on_the_workspace_in_front_changes_nothing() {
.unwrap();
assert_eq!(wm.focused_workspace_idx().unwrap(), 0);
assert!(fake.on_screen(10_411) && fake.on_screen(10_412));
assert!(!fake.is_hidden(10_411) && !fake.is_hidden(10_412));
}
fn moved_to_desktop(id: u32, idx: usize) -> WindowManagerEvent {
+63 -3
View File
@@ -14,6 +14,12 @@
//! workspace, `scrolling-layout-columns` and `layout-ratios` tune it, `toggle-tiling` turns its
//! tiling off and on, and `preselect-direction` and `cancel-preselect` reserve the place of the
//! next window and give it up.
//! - `stack` puts the focused window in one container with the window on one side of it, so that
//! they share a tile and only one is in sight, `unstack` takes it out again, and `stack-all` and
//! `unstack-all` do it for the whole workspace and for the focused stack.
//! `toggle-window-container-behaviour` and `toggle-workspace-window-container-behaviour` make a
//! window that opens join the focused container instead of getting a tile, and
//! `toggle-float-override` and `toggle-workspace-float-override` make it float.
//! - `promote`, `promote-swap`, `promote-focus` and `promote-window` bring a window to the largest
//! tile, or the focus to it.
//! - `toggle-float` takes the focused window out of the layout, or puts it back, and
@@ -141,6 +147,7 @@ gen_enum_subcommand_args! {
CycleWorkspace: CycleDirection,
CycleEmptyWorkspace: CycleDirection,
CycleMoveWorkspaceToMonitor: CycleDirection,
Stack: OperationDirection,
FlipLayout: Axis,
ChangeLayout: DefaultLayout,
CycleLayout: CycleDirection,
@@ -497,7 +504,11 @@ struct Start {
}
#[derive(Parser)]
struct Stop {}
struct Stop {
/// Do not restore windows after stopping komorebi
#[clap(long, hide = true)]
ignore_restore: bool,
}
#[derive(Parser)]
struct SaveResize {
@@ -635,6 +646,15 @@ enum SubCommand {
/// Focus the first managed window matching the given executable
#[clap(arg_required_else_help = true)]
EagerFocus(EagerFocus),
/// Stack the focused window in the specified direction
#[clap(arg_required_else_help = true)]
Stack(Stack),
/// Unstack the focused window
Unstack,
/// Stack all windows on the focused workspace
StackAll,
/// Unstack all windows in the focused container
UnstackAll,
/// Resize the focused window in the specified direction
#[clap(arg_required_else_help = true)]
#[clap(alias = "resize")]
@@ -827,6 +847,18 @@ enum SubCommand {
/// Set the workspace name for the specified workspace
#[clap(arg_required_else_help = true)]
WorkspaceName(WorkspaceName),
/// Toggle the behavior for new windows (stacking or dynamic tiling)
ToggleWindowContainerBehaviour,
/// Enable or disable float override, which makes it so every new window opens in floating mode
ToggleFloatOverride,
/// Toggle the behavior for new windows (stacking or dynamic tiling) for currently focused
/// workspace. If there was no behavior set for the workspace previously it takes the opposite
/// of the global value.
ToggleWorkspaceWindowContainerBehaviour,
/// Enable or disable float override, which makes it so every new window opens in floating
/// mode, for the currently focused workspace. If there was no override value set for the
/// workspace previously it takes the opposite of the global value.
ToggleWorkspaceFloatOverride,
/// Toggle the paused state for all window tiling
TogglePause,
/// Toggle window tiling on the focused workspace
@@ -963,8 +995,12 @@ fn main() -> eyre::Result<()> {
}
}
}
SubCommand::Stop(_) => {
send_message(&SocketMessage::Stop)?;
SubCommand::Stop(args) => {
if args.ignore_restore {
send_message(&SocketMessage::StopIgnoreRestore)?;
} else {
send_message(&SocketMessage::Stop)?;
}
}
SubCommand::DataDirectory => {
let dir = &*komorebi_client::DATA_DIR;
@@ -1012,6 +1048,18 @@ fn main() -> eyre::Result<()> {
SubCommand::FlipLayout(args) => {
send_message(&SocketMessage::FlipLayout(args.axis))?;
}
SubCommand::Stack(args) => {
send_message(&SocketMessage::StackWindow(args.operation_direction))?;
}
SubCommand::StackAll => {
send_message(&SocketMessage::StackAll)?;
}
SubCommand::Unstack => {
send_message(&SocketMessage::UnstackWindow)?;
}
SubCommand::UnstackAll => {
send_message(&SocketMessage::UnstackAll)?;
}
SubCommand::FocusWorkspace(args) => {
send_message(&SocketMessage::FocusWorkspaceNumber(args.target))?;
}
@@ -1163,6 +1211,18 @@ fn main() -> eyre::Result<()> {
SubCommand::ToggleWindowBasedWorkAreaOffset => {
send_message(&SocketMessage::ToggleWindowBasedWorkAreaOffset)?;
}
SubCommand::ToggleWindowContainerBehaviour => {
send_message(&SocketMessage::ToggleWindowContainerBehaviour)?;
}
SubCommand::ToggleFloatOverride => {
send_message(&SocketMessage::ToggleFloatOverride)?;
}
SubCommand::ToggleWorkspaceWindowContainerBehaviour => {
send_message(&SocketMessage::ToggleWorkspaceWindowContainerBehaviour)?;
}
SubCommand::ToggleWorkspaceFloatOverride => {
send_message(&SocketMessage::ToggleWorkspaceFloatOverride)?;
}
SubCommand::ToggleTiling => {
send_message(&SocketMessage::ToggleTiling)?;
}
+55
View File
@@ -121,6 +121,18 @@ fn stop_and_retile_send_their_message_and_print_nothing() {
}
}
#[test]
fn stop_with_ignore_restore_sends_the_message_that_leaves_the_hidden_windows_hidden() {
let runtime = Runtime::new();
let daemon = runtime.serve("");
let output = runtime.komorebic(&["stop", "--ignore-restore"]);
assert!(output.status.success(), "{output:?}");
assert_eq!(daemon.join().unwrap(), r#"{"type":"StopIgnoreRestore"}"#);
assert_eq!(stdout(&output), "");
}
#[test]
fn subscribe_socket_and_unsubscribe_socket_send_the_name_they_are_given() {
for (subcommand, message) in [
@@ -218,6 +230,41 @@ fn the_layout_subcommands_send_the_layout_axis_or_direction_they_are_given() {
sends(&["cancel-preselect"], r#"{"type":"CancelPreselect"}"#);
}
#[test]
fn the_stack_subcommands_send_the_direction_they_are_given() {
sends(
&["stack", "left"],
r#"{"type":"StackWindow","content":"Left"}"#,
);
sends(
&["stack", "down"],
r#"{"type":"StackWindow","content":"Down"}"#,
);
sends(&["unstack"], r#"{"type":"UnstackWindow"}"#);
sends(&["stack-all"], r#"{"type":"StackAll"}"#);
sends(&["unstack-all"], r#"{"type":"UnstackAll"}"#);
}
#[test]
fn the_subcommands_for_new_windows_send_their_message() {
sends(
&["toggle-window-container-behaviour"],
r#"{"type":"ToggleWindowContainerBehaviour"}"#,
);
sends(
&["toggle-workspace-window-container-behaviour"],
r#"{"type":"ToggleWorkspaceWindowContainerBehaviour"}"#,
);
sends(
&["toggle-float-override"],
r#"{"type":"ToggleFloatOverride"}"#,
);
sends(
&["toggle-workspace-float-override"],
r#"{"type":"ToggleWorkspaceFloatOverride"}"#,
);
}
#[test]
fn scrolling_layout_columns_and_layout_ratios_send_what_they_are_given() {
sends(
@@ -723,20 +770,28 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() {
"send-to-workspace.md",
"session-float-rule.md",
"session-float-rules.md",
"stack-all.md",
"stack.md",
"start.md",
"state.md",
"stop.md",
"subscribe-socket.md",
"swap-workspaces-with-monitor.md",
"toggle-cross-monitor-move-behaviour.md",
"toggle-float-override.md",
"toggle-float.md",
"toggle-lock.md",
"toggle-mouse-follows-focus.md",
"toggle-pause.md",
"toggle-tiling.md",
"toggle-window-based-work-area-offset.md",
"toggle-window-container-behaviour.md",
"toggle-workspace-float-override.md",
"toggle-workspace-window-container-behaviour.md",
"unmanage.md",
"unmanaged-window-operation-behaviour.md",
"unstack-all.md",
"unstack.md",
"unsubscribe-socket.md",
"workspace-layout.md",
"workspace-name.md",
+36
View File
@@ -227,6 +227,16 @@ class Kde:
self.as_user(f"echo KOMOREBI_ARGS={words} > {self.runtime}/komorebi-{self.name}.env")
self.systemctl("start", f"komorebi@{self.name}.service")
def kill_komorebi(self) -> None:
"""Kills the daemon with `SIGKILL`, as a crash does, and waits for it to be gone.
Nothing of what the daemon had set up is put back: the user's `kwinrc`, the desktops it
made and the windows it hid are as it left them.
"""
self.systemctl("kill", "--signal=KILL", f"komorebi@{self.name}.service")
if not self.wait_for(lambda: not self.komorebi_running()):
raise AssertionError("the daemon is still running after SIGKILL")
def stop_komorebi(self) -> None:
"""Stops the daemon with `SIGTERM`, as a logout does, and waits for it to exit."""
self.systemctl("stop", f"komorebi@{self.name}.service")
@@ -283,6 +293,18 @@ class Kde:
windows = containers["elements"][containers["focused"]]["windows"]
return windows["elements"][windows["focused"]]["details"]["title"]
def containers(self, workspace: int = 0) -> list[list[str]]:
"""The titles of the windows of each container of a workspace of the first monitor.
The containers are in the order of the layout, and the windows of a stack in the order of
the stack. A workspace with no container gives an empty list.
"""
elements = self._workspace(workspace)["containers"]["elements"]
return [
[window["details"]["title"] for window in container["windows"]["elements"]]
for container in elements
]
def managed(self, workspace: int = 0) -> int:
"""The number of windows the daemon has on a workspace of the first monitor."""
containers = self._workspace(workspace)["containers"]["elements"]
@@ -422,6 +444,20 @@ class Kde:
)[1].split()
return int(out[-1]) if out and out[-1].isdigit() else 0
def desktop_names(self) -> list[str]:
"""The names of the virtual desktops KWin has, in order.
The desktop at index `i` is the one `kdotool` calls `i + 1`.
"""
out = self.run(
"busctl --user get-property org.kde.KWin /VirtualDesktopManager"
" org.kde.KWin.VirtualDesktopManager desktops"
)[1]
# `a(uss) 2 0 "id" "Desktop 1" 1 "id" "Desktop 2"`: the signature, how many, then a
# position, an id and a name for each
words = shlex.split(out)
return words[4::3]
def kwinrc(self, group: str, key: str) -> str | None:
"""The value of `key` in `[group]` of the user's `kwinrc`, or None when it is not set."""
status, text = self.machine.execute(f"cat /home/{self.user}/.config/kwinrc")
+51
View File
@@ -157,6 +157,23 @@ def test_the_log_is_the_file_of_the_session_and_empty_before_a_start(
assert Kde(machine, "main").komorebi_log() == ""
def test_kill_komorebi_sends_sigkill_and_waits_for_the_unit_to_be_inactive(
machine: FakeMachine,
) -> None:
machine.reply("is-active --quiet komorebi@main.service", status=3)
Kde(machine, "main").kill_komorebi()
commands = [inner(command) for command in machine.commands if " sh -c " in command]
assert "systemctl --user kill --signal=KILL komorebi@main.service" in commands
def test_kill_komorebi_fails_the_test_when_the_daemon_survives(machine: FakeMachine) -> None:
kde = Kde(machine, "main", scale=0.01)
with pytest.raises(AssertionError, match="still running"):
kde.kill_komorebi()
def test_komorebi_running_asks_the_user_manager(machine: FakeMachine) -> None:
machine.reply("is-active --quiet komorebi@main.service", status=3)
assert not Kde(machine, "main").komorebi_running()
@@ -373,6 +390,25 @@ def test_the_state_is_what_komorebic_state_prints(machine: FakeMachine) -> None:
assert [inner(command) for command in machine.commands] == ["komorebic state"]
def test_containers_are_the_titles_of_each_container_in_order(machine: FakeMachine) -> None:
machine.reply(
"komorebic state",
output=a_state(
workspace(container("a"), container("b", "c", focused=1)), workspace(container("d"))
),
)
kde = Kde(machine, "main")
assert kde.containers() == [["a"], ["b", "c"]]
assert kde.containers(1) == [["d"]]
def test_a_workspace_without_containers_has_no_titles(machine: FakeMachine) -> None:
machine.reply("komorebic state", output=a_state(workspace()))
assert Kde(machine, "main").containers() == []
def test_managed_counts_the_windows_of_every_container_of_the_workspace(
machine: FakeMachine,
) -> None:
@@ -451,6 +487,21 @@ def test_shown_and_desktops_ask_kwin(machine: FakeMachine) -> None:
assert kde.desktops() == 4
def test_desktop_names_are_the_third_of_each_triple_kwin_prints(machine: FakeMachine) -> None:
machine.reply(
"VirtualDesktopManager desktops",
output='a(uss) 3 0 "a1" "Desktop 1" 1 "b2" "Mail and chat" 2 "c3" "komorebi-park"\n',
)
assert Kde(machine, "main").desktop_names() == ["Desktop 1", "Mail and chat", "komorebi-park"]
def test_there_are_no_desktop_names_when_kwin_does_not_answer(machine: FakeMachine) -> None:
machine.reply("VirtualDesktopManager desktops", status=1, output="")
assert Kde(machine, "main").desktop_names() == []
def test_kwinrc_reads_a_key_of_its_own_group(machine: FakeMachine) -> None:
machine.reply(
"cat /home/komorebi/.config/kwinrc",
+12
View File
@@ -159,6 +159,10 @@ cycle-focus next
cycle-focus previous
cycle-move next
cycle-move previous
stack left
unstack
stack-all
unstack-all
resize-edge left increase
resize-edge right decrease
resize-edge up increase
@@ -192,6 +196,14 @@ toggle-tiling
toggle-tiling
toggle-pause
toggle-pause
toggle-window-container-behaviour
toggle-window-container-behaviour
toggle-float-override
toggle-float-override
toggle-workspace-window-container-behaviour
toggle-workspace-window-container-behaviour
toggle-workspace-float-override
toggle-workspace-float-override
ensure-named-workspaces 0 one two three
workspace-name 0 0 one
ensure-workspaces 0 3
+5
View File
@@ -0,0 +1,5 @@
{
tier = "fast";
kind = "headless";
timeoutMinutes = 10;
}
+182
View File
@@ -0,0 +1,182 @@
# Stacking on a real KWin: what komorebi believes (`komorebic state`) against what KWin actually
# has (`kdotool`). A stack shows one window, and the rest of it is out of sight on the parking
# desktop, a virtual desktop nobody looks at; the window that is shown is the one that has the
# focus. KWin keeps its virtual desktops in `kwinrc` as soon as one is made, so what only a real
# KWin can tell is that the parking desktop is made when it is needed, that it is removed when
# komorebi stops, and that one a crashed komorebi left behind is swept by the next. The windows a
# stack hides are on a desktop of their own, not minimized: their events are not the user's.
# `komorebi/tests/stacks.rs` checks which windows a stack holds against the fake.
from komorebi_vm import Checks, Kde, Rect
W, H = 1920, 1080
PARK = "komorebi-park"
TITLES = ["win1", "win2", "win3"]
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 sizes() -> list[int]:
"""How many windows each container of the first workspace has, in order."""
return [len(container) for container in kde.containers()]
def park_desktop() -> int:
"""The number of the parking desktop, counted from 1 as kdotool counts, or 0 for none."""
names = kde.desktop_names()
return names.index(PARK) + 1 if PARK in names else 0
def parked() -> list[str]:
"""The titles of the windows that are on the parking desktop."""
park = park_desktop()
if park == 0:
return []
found = [t for t in TITLES if kde.wid(t) != "" and kde.desk(kde.wid(t)) == park]
return sorted(found)
def active_title() -> str:
active = kde.active()
return kde.title(active) if active else ""
def agree() -> bool:
"""KWin and komorebi have the same window focused."""
return active_title() != "" and active_title() == kde.focused_title()
def inside(r: Rect) -> bool:
return r.x >= 0 and r.y >= 0 and r.x + r.w <= W and r.y + r.h <= H
def on_a_workspace_desktop() -> bool:
"""Every window that is left is on a desktop that is a workspace, not on the parking one."""
return all(kde.desk(kde.wid(t)) in (1, 2) for t in TITLES if kde.wid(t) != "")
print("== 1. three windows")
kde.start_komorebi()
kde.wait_for(lambda: kde.run("komorebic monitor-information")[0] == 0, timeout=30)
for title in TITLES:
kde.spawn(f"foot -T {title} sleep 3000")
kde.wait_for(lambda title=title: kde.wid(title) != "", timeout=30)
checks.check("komorebi manages the three", kde.wait_for(lambda: kde.managed() == 3, timeout=20))
checks.check("there are three tiles", sizes() == [1, 1, 1])
checks.check("nothing is out of sight, and there is no parking desktop yet", park_desktop() == 0)
print("== 2. stack the focused window onto its neighbour")
kde.komorebic("stack", "left")
checks.check(
"two containers, one of them a stack of two",
kde.wait_for(lambda: sorted(sizes()) == [1, 2]),
)
print(f" containers: {kde.containers()}, out of sight: {parked()}")
checks.check(
"there is a parking desktop, and exactly one window is on it",
kde.wait_for(lambda: park_desktop() != 0 and len(parked()) == 1),
)
checks.check("the window in view is the one with the focus", kde.wait_for(agree))
shown = active_title()
checks.check("and the one out of sight is not it", parked() != [shown])
checks.check(
"the parking desktop is the last, so it is not a workspace",
park_desktop() == kde.desktops(),
)
checks.check(
"komorebi still has all three windows on workspace 0, the hidden one among them",
kde.managed(0) == 3,
)
rect_shown = kde.rect(kde.wid(shown))
checks.check("the one in view is inside the screen", inside(rect_shown))
print("== 3. a stack is still a stack after a workspace round trip")
before = parked()
kde.komorebic("focus-workspace", "1")
checks.check("workspace 1 is showing", kde.wait_for(lambda: kde.shown() == 2))
kde.komorebic("focus-workspace", "0")
checks.check("workspace 0 is showing again", kde.wait_for(lambda: kde.shown() == 1))
checks.check(
f"the same window is out of sight ({before})",
kde.wait_for(lambda: parked() == before),
)
checks.check("and the focus agrees", kde.wait_for(agree))
print("== 4. unstack")
kde.komorebic("unstack")
checks.check("three tiles again", kde.wait_for(lambda: sizes() == [1, 1, 1]))
checks.check("nothing is out of sight", kde.wait_for(lambda: parked() == []))
rects = [kde.rect(kde.wid(t)) for t in TITLES]
checks.check("they are inside the screen", all(inside(r) for r in rects))
checks.check(
"and they tile, not on each other",
not any(a.overlaps(b) for i, a in enumerate(rects) for b in rects[i + 1 :]),
)
print("== 5. closing the window in view brings the next one")
kde.komorebic("stack", "left")
checks.check("stacked again", kde.wait_for(lambda: len(parked()) == 1))
hidden_one = parked()[0]
kde.komorebic("close")
checks.check(
"the one that was out of sight is in view and has the focus",
kde.wait_for(lambda: parked() == [] and active_title() == hidden_one and agree()),
)
checks.check("two tiles are left", kde.wait_for(lambda: sizes() == [1, 1]))
print("== 6. stack all, and unstack all")
kde.komorebic("stack-all")
checks.check(
"every window is in one stack, with one in view",
kde.wait_for(lambda: sizes() == [2] and len(parked()) == 1),
)
checks.check("the window in view has the focus", kde.wait_for(agree))
kde.komorebic("unstack-all")
checks.check(
"they have a tile each again, and none is out of sight",
kde.wait_for(lambda: sizes() == [1, 1] and parked() == []),
)
print("== 7. a crash leaves a parking desktop, which the next start sweeps")
kde.komorebic("stack-all")
checks.check("a window is parked", kde.wait_for(lambda: len(parked()) == 1))
names_before = kde.desktop_names()
kde.kill_komorebi()
checks.check(
"the daemon is dead and the parking desktop is still there, with a window on it",
PARK in kde.desktop_names() and len(parked()) == 1,
)
kde.start_komorebi()
checks.check(
"the next start removed the stale parking desktop",
kde.wait_for(lambda: kde.run("komorebic monitor-information")[0] == 0 and park_desktop() == 0),
)
checks.check("and brought the parked window back", kde.wait_for(on_a_workspace_desktop))
checks.check(
"the workspaces' desktops are left alone",
kde.desktop_names() == [n for n in names_before if n != PARK],
)
checks.check("komorebi manages the two windows again", kde.wait_for(lambda: kde.managed() == 2))
kde.komorebic("stack-all")
checks.check(
"this run makes a parking desktop of its own and hides the back of the stack on it",
kde.wait_for(lambda: park_desktop() != 0 and len(parked()) == 1),
)
print("== 8. a clean stop puts every window back")
still_open = [t for t in TITLES if kde.wid(t) != ""]
kde.komorebic("stop")
checks.check("komorebi exited", kde.wait_for(lambda: not kde.komorebi_running()))
checks.check("the parking desktop is gone", kde.wait_for(lambda: park_desktop() == 0))
checks.check(
"and every window is on a workspace's desktop",
kde.wait_for(on_a_workspace_desktop),
)
checks.check("the windows are still open", all(kde.wid(t) != "" for t in still_open))
kde.stop()
checks.finish()