mirror of
https://github.com/LGUG2Z/komorebi.git
synced 2026-11-17 22:33:12 +01:00
feat(kwin): workspaces are KWin's own desktops
komorebi's workspaces exist on Windows and macOS because neither has a virtual desktop API: switching hides every window of the workspace being left. KWin has virtual desktops, per output since 6.8, so here workspace i is KWin's desktop i on every monitor, and each monitor shows one. KWin shows, hides and focuses the windows of a desktop; komorebi asks for a switch, puts a window on a desktop, and follows what anything else does. The Backend gets the workspace methods (ensure_workspaces, switch_workspace, set_window_workspace, window_workspace, current_workspaces), and the fake its desktops. The bridge reports the desktops, the desktop each output shows and a window's desktops, and carries out output_desktop and desktop commands, typed and tested with the fixtures like the rest. The table turns a switch or a move komorebi did not make into a WorkspaceChange or a WorkspaceMove, and records its own when it sends them, so that KWin's report of those raises nothing. The window manager follows a switch with no command in reply (adopt_workspace_change), puts windows on their desktops before a desktop is shown (focusing a window first would take the monitor back), and loads the windows open at startup onto the workspace of their desktop. Per-output desktops are a kwinrc setting that is off by default, and kwriteconfig6 was not on the PATH of the user service in a live session, so komorebi edits kwinrc itself (kwin::kwinrc) and puts the user's value back when it stops, also after a crash. focus-workspace, move-to-workspace and send-to-workspace come with this commit, since the tests of switching and moving, and vm-workspace-switch, need them; the named and cycling workspace commands follow. vm-workspace-switch runs the daemon against a real KWin; vm-kwin-contract checks what komorebi relies on from KWin's per-output desktops, on a headless KWin with two outputs and no komorebi.
This commit is contained in:
1 parent
1b10611022
commit
62e37e44cf
38 files changed
+3522
-77
No files matched your search
@@ -65,7 +65,8 @@ without a checkout of the toolchain.
|
||||
- [`komorebi`](komorebi): the daemon, and the library behind it. The library has
|
||||
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 (`kwin`),
|
||||
(`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 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
|
||||
@@ -119,6 +120,15 @@ a table of the windows and monitors from those reports, answers the window
|
||||
manager's questions from it, and turns each report into an event for the window
|
||||
manager. If KWin restarts, the daemon loads the bridge into the new one.
|
||||
|
||||
komorebi's workspaces are KWin's own virtual desktops: workspace `i` is desktop
|
||||
`i`, and each monitor shows a desktop of its own, which the daemon has KWin do by
|
||||
turning on its per-output virtual desktops (the setting is put back when the
|
||||
daemon stops). Showing a workspace is a request to KWin, which shows the
|
||||
windows of that desktop, hides the others, and gives the focus to one of them.
|
||||
When something else switches a monitor to another desktop (a pager, a shortcut,
|
||||
an application raising a window of another desktop), or puts a window on
|
||||
another desktop, the window manager follows.
|
||||
|
||||
The window manager models the desktop as monitors, each with a ring of
|
||||
workspaces, each with a ring of containers, each with a ring of windows. A
|
||||
workspace's layout gives each of its containers a tile of the monitor's work
|
||||
@@ -126,7 +136,8 @@ area, and every window of a container is moved onto its tile. At startup the
|
||||
window manager loads the monitors and the windows that are open from the
|
||||
backend and tiles them; after that it changes the model when the compositor
|
||||
reports that a window was shown, closed, focused, minimized or restored, and
|
||||
tiles the workspace in front again.
|
||||
tiles the workspace in front again. A window open at startup goes to the
|
||||
workspace whose desktop it is on.
|
||||
|
||||
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
|
||||
@@ -151,6 +162,9 @@ the work area offsets keep parts of a monitor free of tiles. Rules decide which
|
||||
windows are managed at all: `ignore-rule` keeps an application out of the
|
||||
layout, `manage-rule` tiles it whatever the ignore rules say, and
|
||||
`session-float-rule` floats the focused window and the windows like it.
|
||||
`focus-workspace` shows another workspace, and `move-to-workspace` and
|
||||
`send-to-workspace` put the focused window on another workspace, with and
|
||||
without showing it.
|
||||
|
||||
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
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
```text
|
||||
Focus the specified workspace on the focused monitor
|
||||
|
||||
Usage: focus-workspace <TARGET>
|
||||
|
||||
Arguments:
|
||||
<TARGET>
|
||||
Target index (zero-indexed)
|
||||
|
||||
Options:
|
||||
-h, --help
|
||||
Print help
|
||||
|
||||
```
|
||||
@@ -0,0 +1,14 @@
|
||||
```text
|
||||
Move the focused window to the specified workspace
|
||||
|
||||
Usage: move-to-workspace <TARGET>
|
||||
|
||||
Arguments:
|
||||
<TARGET>
|
||||
Target index (zero-indexed)
|
||||
|
||||
Options:
|
||||
-h, --help
|
||||
Print help
|
||||
|
||||
```
|
||||
@@ -0,0 +1,14 @@
|
||||
```text
|
||||
Send the focused window to the specified workspace
|
||||
|
||||
Usage: send-to-workspace <TARGET>
|
||||
|
||||
Arguments:
|
||||
<TARGET>
|
||||
Target index (zero-indexed)
|
||||
|
||||
Options:
|
||||
-h, --help
|
||||
Print help
|
||||
|
||||
```
|
||||
+96
-14
@@ -7,10 +7,10 @@ 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 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.
|
||||
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.
|
||||
|
||||
## Vocabulary
|
||||
|
||||
@@ -19,16 +19,22 @@ its place here.
|
||||
- **Monitor**: a connected output, with its bounds and its work area (its bounds minus
|
||||
the panels).
|
||||
- **Workspace**: the containers a monitor shows, in order, and the layout that tiles
|
||||
them. A monitor has a ring of workspaces and shows one of them.
|
||||
them. A monitor has a ring of workspaces and shows one of them. Workspace `i` is the
|
||||
compositor's desktop `i` on that monitor.
|
||||
- **Desktop**: one of KWin's virtual desktops. KWin shows the windows of one desktop on each
|
||||
output and hides the others; with its per-output virtual desktops on, each output shows a
|
||||
desktop of its own.
|
||||
- **Container**: what a layout places. It gets one tile, and every window in it is put on
|
||||
that tile.
|
||||
- **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
|
||||
the focus, minimized or restored ([`WindowManagerEvent`]). Two events come from komorebi
|
||||
itself: a command asks it to manage the focused window, or to stop managing it.
|
||||
the focus, minimized or restored, or put on another workspace's desktop; and that a monitor
|
||||
shows another workspace ([`WindowManagerEvent`]). Two events come from komorebi itself: a
|
||||
command asks it to manage the focused window, or to stop managing it.
|
||||
- **Message**: what a client sends the daemon on its socket, a [`SocketMessage`]: an order
|
||||
(focus a window, move it, change the layout, resize it, retile, stop) or a question (the state, the monitors, one [`StateQuery`]).
|
||||
(focus a window, move it, change the layout, resize it, show a workspace, retile, stop) or a
|
||||
question (the state, the monitors, one [`StateQuery`]).
|
||||
- **Rule**: a condition on a window's title, executable, class or path ([`MatchingRule`]), in
|
||||
one of the process-wide lists that decide whether a window is managed (the ignore and the
|
||||
manage rules) and whether it floats when it opens (the float rules).
|
||||
@@ -81,7 +87,9 @@ The desktop, as the window manager sees it, is two lists and a pointer:
|
||||
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, and put the pointer in the middle of a rectangle.
|
||||
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
|
||||
element focused, so that "the focused workspace" or "the focused container" means
|
||||
@@ -111,9 +119,10 @@ tile is clamped to the work area, so it cannot reach onto a neighboring monitor.
|
||||
The [`WindowManager`] keeps the monitors, the windows the user minimized (they are in no
|
||||
workspace until they are restored), and an index from each window it manages to the
|
||||
monitor and workspace that have it. It is loaded from the backend at startup: every
|
||||
monitor, and every open window that is normal, alive, not minimized and not ignored by a
|
||||
rule, on the focused workspace of the monitor its middle is on. After that it changes only
|
||||
when an event comes in, and each event ends with the workspace in front tiled again.
|
||||
monitor, focused on the workspace the compositor shows on it, and every open window that is
|
||||
normal, alive, not minimized and not ignored by a rule, on the workspace whose desktop it is
|
||||
on, of the monitor its middle is on. After that it changes only when an event comes in, and
|
||||
each event ends with the workspace in front tiled again.
|
||||
|
||||
## The KWin backend
|
||||
|
||||
@@ -179,6 +188,41 @@ and returns once the snapshot has arrived, so that the window manager reads a fu
|
||||
it starts. [PLATFORM.md](PLATFORM.md) has the D-Bus names, the files and the environment
|
||||
variables; [DESIGN.md](DESIGN.md#why-does-komorebi-run-a-script-inside-kwin) has the reasons.
|
||||
|
||||
## Workspaces
|
||||
|
||||
komorebi's workspaces are the compositor's virtual desktops: workspace `i` is desktop `i` on
|
||||
every monitor, and each monitor shows one at a time. The compositor shows the windows of the
|
||||
desktop in front, hides the others, and keeps which window of each desktop had the focus; the
|
||||
window manager hides no window to leave a workspace. The reasons are in
|
||||
[DESIGN.md](DESIGN.md#why-are-komorebis-workspaces-kwins-virtual-desktops).
|
||||
|
||||
Showing a workspace ([`Monitor::load_focused_workspace`]) is three steps. Every window of every
|
||||
workspace of the monitor is put on the desktop of its workspace, unless it is already there.
|
||||
The compositor is asked to show the workspace on the monitor ([`Backend::switch_workspace`]),
|
||||
which leaves the other monitors as they are. The workspace's focused window is given the focus.
|
||||
The order matters: a window that is focused while it is on another desktop takes the monitor
|
||||
back to that desktop.
|
||||
|
||||
Desktops are global in KWin: every monitor has as many as the monitor with the most
|
||||
workspaces, and each has one name. At startup, and when a workspace is asked for that has no
|
||||
desktop, the backend creates the missing ones over KWin's `org.kde.KWin.VirtualDesktopManager`
|
||||
interface, named "Workspace 1", "Workspace 2" and so on ([`WindowManager::sync_workspace_desktops`]).
|
||||
Without KWin's per-output virtual desktops every output would show the same desktop, so
|
||||
[`connect`] turns them on in the user's `kwinrc`, and [`Kwinrc`] keeps the user's value and
|
||||
puts it back when komorebi stops, also after a crash.
|
||||
|
||||
Something else can switch a monitor to another desktop: a pager, a KWin shortcut, an
|
||||
application that raises a window of another desktop, which KWin answers by showing that
|
||||
desktop. KWin has one signal for it, which does not say which output, so the bridge sends the
|
||||
desktop of every output after it, and once a second. The table compares it with what it had,
|
||||
and a monitor that shows another desktop is a `WorkspaceChange` event: the window manager
|
||||
focuses that workspace and tiles it ([`WindowManager::adopt_workspace_change`]), and asks the
|
||||
compositor for nothing, since KWin has already shown the windows and chosen which to focus. A
|
||||
window put on another desktop by something else (the window menu's "Move to Desktop") is a
|
||||
`WorkspaceMove`: the window manager moves the window to that workspace. komorebi's own switch
|
||||
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.
|
||||
|
||||
## The command socket
|
||||
|
||||
The daemon takes messages on a Unix socket, `komorebi.sock` in [`DATA_DIR`]
|
||||
@@ -370,6 +414,13 @@ would be smaller than a tenth of the work area, or than it is already. The adjus
|
||||
until a `Retile`, which drops them; `RetileWithResizeDimensions` tiles with them, and `Save`,
|
||||
`Load`, `QuickSave` and `QuickLoad` write them to a file as JSON and read them back.
|
||||
|
||||
`FocusWorkspaceNumber` shows another workspace of the focused monitor
|
||||
([`WindowManager::focus_workspace`]). `MoveContainerToWorkspaceNumber` takes the focused
|
||||
container (or the focused window, when it is a floating one) to the back of another workspace
|
||||
of the monitor and shows that workspace, and `SendContainerToWorkspaceNumber` does the same
|
||||
and leaves the workspace in front showing ([`WindowManager::move_container_to_workspace`]). A
|
||||
workspace that does not exist yet is created, with the ones before it, and gets a desktop.
|
||||
|
||||
`PreselectDirection` reserves the index on one side of the focused container for the next
|
||||
window ([`WindowManager::preselect_container_in_direction`]). The workspace inserts an empty
|
||||
container there ([`Container::preselect`]), which [`Workspace::update`] keeps and the layout
|
||||
@@ -429,7 +480,8 @@ 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).
|
||||
workspace, manage and unmanage a window, show a workspace, move a container to another
|
||||
workspace, follow a workspace switch made by something else).
|
||||
- [`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
|
||||
@@ -439,7 +491,9 @@ module's unit.
|
||||
channel that carries events from the backend to the window manager, and
|
||||
[`listen_for_events`], the thread that takes them off it.
|
||||
- [`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; and
|
||||
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
|
||||
[`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.
|
||||
@@ -480,6 +534,11 @@ the fake. The window manager is its only caller, through [`backend`]. The contra
|
||||
- A command about a window that does not exist, or is no longer alive, is an error. It
|
||||
never panics. The KWin backend knows a closed window for a minute after it closed, and
|
||||
sends its commands to the bridge, which reports that it could not carry them out.
|
||||
- Workspace `i` is the compositor's desktop `i`, and each monitor shows one
|
||||
(`switch_workspace`, `set_window_workspace`, `window_workspace`, `current_workspaces`). A
|
||||
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.
|
||||
- `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.
|
||||
@@ -518,6 +577,12 @@ the fake. The window manager is its only caller, through [`backend`]. The contra
|
||||
| A resize leaves no tile smaller than a tenth of the work area, or than it was | framework path: [`WindowManager::resize_window`] calculates the tiles for the adjustment, and cuts the adjustment down until they all fit | `a_resize_leaves_every_tile_about_a_tenth_of_the_work_area_wide_at_least` | the paddings are taken off afterwards, so a tile can end up a little smaller |
|
||||
| The offset of a workspace wins over its monitor's, which wins over the window manager's | framework path: [`Monitor::update_workspace_globals`] gives the workspace the monitor's offset or else the window manager's, and [`Workspace::update`] takes its own before that | `the_workspaces_offset_wins_over_the_monitors_which_wins_over_the_global_one` | none |
|
||||
| A workspace whose tiling is off moves no window | framework path: [`Workspace::update`] returns before the layout when [`Workspace::tile`] is false | `with_tiling_off_no_window_is_moved_until_it_is_back_on` | none |
|
||||
| komorebi hides no window to leave a workspace | framework path: showing a workspace is one request to the compositor ([`Backend::switch_workspace`]), which shows and hides the windows of its desktops | `switching_workspace_asks_the_compositor_to_show_the_other_desktop`, `vm-workspace-switch` ("KWin shows the desktop, komorebi hides nothing") | none |
|
||||
| Showing a workspace on one monitor leaves the other monitors as they are | KWin's per-output virtual desktops, which [`connect`] turns on | `showing_a_workspace_switches_that_output_only`, `vm-kwin-contract` ("the other keeps its own") | a `kwinrc` komorebi cannot write: every monitor switches |
|
||||
| A window is on its new workspace's desktop before the desktop is shown or the window focused | framework path: [`Monitor::load_focused_workspace`] puts every window on its desktop first | `moving_a_window_to_another_workspace_puts_it_on_the_desktop_before_showing_it` | none |
|
||||
| A workspace switch or a window move made by something else is followed, and answered with no command | framework path: the table reports what it did not send as a `WorkspaceChange` or a `WorkspaceMove`, and [`WindowManager::adopt_workspace_change`] asks the compositor for nothing | `a_workspace_switch_by_someone_else_is_followed_not_undone`, `a_window_moved_to_another_desktop_by_someone_else_changes_workspace`, `another_party_switching_a_monitor_is_a_workspace_change`, `vm-workspace-switch` ("nothing is flip-flopping") | none |
|
||||
| komorebi's own switch or move, reported back by KWin, changes nothing | framework path: the table records a switch and a move when it makes their commands | `the_compositor_reporting_komorebis_own_switch_changes_nothing`, `komorebis_own_move_coming_back_as_an_event_moves_nothing`, `komorebi_switching_a_monitor_comes_back_as_a_change_to_what_it_already_knows` | none |
|
||||
| The user's `kwinrc` gets back the value komorebi changed, also after a crash | framework path: [`Kwinrc`] records the first value of a key in a backup file, and the backend's `shutdown` puts it back | `what_komorebi_changed_is_put_back_exactly_and_what_it_added_is_removed`, `a_backup_left_by_a_crash_keeps_the_values_from_before_the_first_run`, `vm-workspace-switch` ("back as they were") | `SIGKILL`: the next run puts it back when it stops |
|
||||
| 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 |
|
||||
@@ -648,6 +713,14 @@ A window is shown, and ends up on a tile:
|
||||
strip in a real KWin, with its columns out of view off the screen.
|
||||
- [`nix/tests/vm/suites/commands`](../../nix/tests/vm/suites/commands/test.py): every layout,
|
||||
and every `komorebic` command, against a real KWin with two outputs.
|
||||
- [`komorebi/tests/workspaces.rs`](../../komorebi/tests/workspaces.rs): workspaces as the
|
||||
fake's desktops; [`komorebi/src/kwin/kwinrc.rs`](../../komorebi/src/kwin/kwinrc.rs), the
|
||||
`kwinrc` editor and its tests.
|
||||
- [`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
|
||||
behavior of KWin's per-output virtual desktops komorebi relies on, with two outputs and no
|
||||
komorebi.
|
||||
- [`nix/nixos-module.nix`](../../nix/nixos-module.nix): the NixOS module;
|
||||
[`nix/tests/nixos-module.nix`](../../nix/tests/nixos-module.nix), its scenarios, evaluated in
|
||||
real NixOS systems; and [`nix/tests/vm/suites/module`](../../nix/tests/vm/suites/module/test.py),
|
||||
@@ -727,6 +800,15 @@ A window is shown, and ends up on a tile:
|
||||
[`Table`]: ../../komorebi/src/kwin/state.rs
|
||||
[`Table::handle`]: ../../komorebi/src/kwin/state.rs
|
||||
[`Table::compositor_lost`]: ../../komorebi/src/kwin/state.rs
|
||||
[`Table::switch_commands`]: ../../komorebi/src/kwin/state.rs
|
||||
[`Table::window_workspace_commands`]: ../../komorebi/src/kwin/state.rs
|
||||
[`Kwinrc`]: ../../komorebi/src/kwin/kwinrc.rs
|
||||
[`Backend::switch_workspace`]: ../../komorebi/src/backend/mod.rs
|
||||
[`Monitor::load_focused_workspace`]: ../../komorebi/src/monitor.rs
|
||||
[`WindowManager::sync_workspace_desktops`]: ../../komorebi/src/window_manager.rs
|
||||
[`WindowManager::adopt_workspace_change`]: ../../komorebi/src/window_manager.rs
|
||||
[`WindowManager::focus_workspace`]: ../../komorebi/src/window_manager.rs
|
||||
[`WindowManager::move_container_to_workspace`]: ../../komorebi/src/window_manager.rs
|
||||
[`bridge.js`]: ../../komorebi/src/kwin/bridge.js
|
||||
[`kwin-api.d.ts`]: ../../komorebi/src/kwin/kwin-api.d.ts
|
||||
[`bridge.test.js`]: ../../komorebi/src/kwin/bridge.test.js
|
||||
|
||||
@@ -223,3 +223,39 @@ to put a window for a second, and sets the position again when the window's fram
|
||||
another one in that time ([PLATFORM.md](PLATFORM.md#how-clients-answer-a-frame)). Three tries
|
||||
at most keep it from chasing a window that cannot go where it was asked, such as a fullscreen
|
||||
one.
|
||||
|
||||
## Why are komorebi's workspaces KWin's virtual desktops?
|
||||
|
||||
Because KWin has virtual desktops, per output since KWin 6.8, and Windows and macOS have no API
|
||||
for them. komorebi's own workspaces exist there for that reason: switching workspace hides
|
||||
every window of the workspace being left and restores the windows of the one being entered. On
|
||||
KDE that is what KWin does with its desktops, and native behavior is preferred over a
|
||||
workaround (see [What is komorebi for KDE the port of?](#what-is-komorebi-for-kde-the-port-of)):
|
||||
workspace `i` is desktop `i` on every monitor, and each monitor shows one at a time.
|
||||
|
||||
The spikes measured what KWin does with per-output desktops on a headless KWin with two
|
||||
outputs: showing a desktop on one output left the other output's alone; KWin gave the focus to
|
||||
a window of the desktop it switched to, by itself; and activating a window on another desktop
|
||||
of its output (an application raising itself) made KWin switch that output to the window's
|
||||
desktop and focus the window, by itself. So komorebi asks for a switch and follows the ones it
|
||||
did not ask for, with no command in reply. A first attempt in which komorebi hid the windows
|
||||
itself switched between two workspaces about 280 times a second after an application raised a
|
||||
window of another workspace: KWin delivered focus events it had generated before it carried
|
||||
out komorebi's commands, and komorebi took each for a new request. With KWin's desktops there
|
||||
is nothing to debounce, since komorebi answers a switch with nothing.
|
||||
|
||||
The costs: desktops are global, so every monitor has as many as the monitor with the most
|
||||
workspaces, with one name each, and they show in the pager and the overview. A window komorebi
|
||||
does not manage (a dialog, say) belongs to the desktop it opened on and goes out of view with
|
||||
it. The desktops komorebi created stay when it stops: by then they are the user's desktops.
|
||||
|
||||
## Why does komorebi edit `kwinrc` itself?
|
||||
|
||||
Because per-output virtual desktops are off by default, they are a setting in the user's
|
||||
`kwinrc`, and the program that would set it cannot be counted on. KDE's `kwriteconfig6` was not
|
||||
on the PATH of komorebi's user service in the first live run in a Plasma session, and
|
||||
per-output desktops stayed off; `kreadconfig6` is not always installed either. The file is
|
||||
plain ini, which komorebi changes line by line, and asks KWin to reload its configuration.
|
||||
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.
|
||||
+70
-11
@@ -19,6 +19,8 @@ was measured with KWin 6.8.1, Plasma 6.8.1 and Qt 6.12.0 from nixpkgs `d3b13ad`
|
||||
- **Script**: a JavaScript program that KWin runs inside itself, through its scripting API.
|
||||
komorebi's is the **bridge**, [`bridge.js`](../../komorebi/src/kwin/bridge.js).
|
||||
- **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`.
|
||||
- **Headless KWin**: `kwin_wayland --virtual`, a KWin with virtual outputs and no display,
|
||||
which the VM tests run ([vm-tests.md](vm-tests.md)).
|
||||
|
||||
@@ -26,10 +28,35 @@ was measured with KWin 6.8.1, Plasma 6.8.1 and Qt 6.12.0 from nixpkgs `d3b13ad`
|
||||
|
||||
### KWin 6.8 or newer
|
||||
|
||||
KWin 6.8 is the oldest KWin komorebi supports. The bridge reads the work area of each output
|
||||
for the virtual desktop that output shows (`workspace.currentDesktopForScreen`), which is part
|
||||
of the per-output virtual desktops KWin 6.8 introduced. At time of writing (2026-10-27) KWin
|
||||
6.8.1 is the only version komorebi has been run against; 6.7 and older have not been tried.
|
||||
KWin 6.8 is the oldest KWin komorebi supports. komorebi's workspaces are KWin's virtual
|
||||
desktops, one shown on each output, which needs the per-output virtual desktops KWin 6.8
|
||||
introduced (`workspace.currentDesktopForScreen`, `workspace.setCurrentDesktopForScreen`, and
|
||||
the setting `[Windows] PerOutputVirtualDesktops` in `kwinrc`). At time of writing (2026-10-27)
|
||||
KWin 6.8.1 is the only version komorebi has been run against; 6.7 and older have not been
|
||||
tried.
|
||||
|
||||
### Per-output virtual desktops
|
||||
|
||||
What komorebi relies on KWin to do with them, on KWin 6.8.1 at time of writing (2026-10-27),
|
||||
measured in the spikes and checked by the VM test `vm-kwin-contract` on a headless KWin with two
|
||||
outputs:
|
||||
|
||||
- With `PerOutputVirtualDesktops=true` in the `[Windows]` group of `kwinrc`, a script that
|
||||
shows a desktop on one output (`workspace.setCurrentDesktopForScreen`) leaves the other
|
||||
output's desktop as it was. komorebi turns the setting on when it starts, has KWin reload its
|
||||
configuration (`org.kde.KWin.reconfigure`), and puts the user's value back when it stops.
|
||||
- KWin raises `workspace.currentDesktopChanged` when an output shows another desktop. The signal
|
||||
does not say which output, so the bridge reads the desktop of every output after it.
|
||||
- KWin gives the focus to a window of the desktop it switched an output to, by itself.
|
||||
- Activating a window that is on another desktop of its output switches that output to the
|
||||
window's desktop and gives the window the focus.
|
||||
- A window that a script moves so that its middle is on another output keeps its desktops;
|
||||
`window.output` follows the middle. KWin puts a window on the new output's desktop only during
|
||||
an interactive move.
|
||||
- Putting a window on another desktop from outside the script raises the window's
|
||||
`desktopsChanged`.
|
||||
- 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.
|
||||
|
||||
### Wayland
|
||||
|
||||
@@ -74,9 +101,16 @@ the windows and outputs it finds, and from then on every window that opens, clos
|
||||
focus, is minimized or brought back, moves or changes size. The daemon waits up to 10 seconds
|
||||
for the first report and does not start without it.
|
||||
|
||||
Before it loads the script, it turns on KWin's per-output virtual desktops in the user's
|
||||
`kwinrc` (`[Windows] PerOutputVirtualDesktops=true`), unless they are on, and asks KWin to
|
||||
reload its configuration. If a workspace has no desktop, it creates the missing desktops over
|
||||
`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) 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
|
||||
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,
|
||||
which puts the pointer in the middle of the window KWin has focused.
|
||||
|
||||
@@ -94,11 +128,15 @@ 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 asks KWin
|
||||
to unload the script, closes an empty connection to each subscriber, and removes the socket.
|
||||
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, and the socket file in
|
||||
the runtime directory, until the next start replaces both or the session ends.
|
||||
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
|
||||
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.
|
||||
|
||||
### A headless KWin
|
||||
|
||||
@@ -143,11 +181,19 @@ What komorebi calls:
|
||||
| `org.kde.KWin` | `/Scripting/Script<id>` | `org.kde.kwin.Script` | `run()` | after `loadScript` |
|
||||
| `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 |
|
||||
|
||||
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,
|
||||
since a read right after `createDesktop` has to see the new desktop.
|
||||
|
||||
## Files and directories
|
||||
|
||||
| Path | What | Lifetime |
|
||||
|---|---|---|
|
||||
| `$XDG_CONFIG_HOME/kwinrc` (`~/.config/kwinrc`) | KWin's configuration: komorebi sets `PerOutputVirtualDesktops=true` in `[Windows]`, changing that line or adding it and nothing else, and writes the file beside it first and renames it over it | put back as it was when the daemon stops |
|
||||
| `$XDG_RUNTIME_DIR/komorebi/kwinrc-backup.json` | the value each key of `kwinrc` had before komorebi first changed it | removed when the values are put back; one a crash left behind is used by the next run |
|
||||
| `$XDG_RUNTIME_DIR/komorebi/bridge.js` | the script KWin loads, with its configuration (the D-Bus names and the hold time of `Poll`) on its first line | written at every start; the directory is removed at logout |
|
||||
| `$XDG_RUNTIME_DIR/komorebi/komorebi.sock` | the command socket | bound once the daemon is connected to KWin, after a file left there is removed; removed when the daemon stops |
|
||||
| `$XDG_RUNTIME_DIR/komorebi/NAME` | the socket of a subscriber, which the subscriber binds and names in its subscription | removed by the daemon, with the subscriber, when it cannot connect to it |
|
||||
@@ -170,6 +216,19 @@ either. An address with no bus behind it is the first error under [No KWin](#no-
|
||||
The runtime directory of the user, normally `/run/user/<uid>`: komorebi writes the bridge to
|
||||
the `komorebi` directory in it, and binds its command socket there.
|
||||
|
||||
### `XDG_CONFIG_HOME`
|
||||
|
||||
Where the user's `kwinrc` is: `$XDG_CONFIG_HOME/kwinrc`, or `~/.config/kwinrc` when it is not
|
||||
set. Without either, komorebi leaves per-output virtual desktops as they are and logs that it
|
||||
found no configuration directory.
|
||||
|
||||
### `XDG_CONFIG_DIRS`
|
||||
|
||||
Where KConfig looks for the system's `kwinrc` when the user's has no value: komorebi reads
|
||||
`PerOutputVirtualDesktops` the same way, from the user's file and then from the first of these
|
||||
directories that has it (`/etc/xdg` when the variable is not set), and changes nothing when the
|
||||
setting is on already.
|
||||
|
||||
### `XDG_DATA_HOME`
|
||||
|
||||
The logs are written to `$XDG_DATA_HOME/komorebi` (`~/.local/share/komorebi` if
|
||||
|
||||
@@ -134,6 +134,14 @@ the run.
|
||||
in order, `daemon.window_ids(log)` maps a window's title to the daemon's id
|
||||
for it, and `daemon.requests(log)` returns the frame the daemon last asked KWin
|
||||
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`.
|
||||
- `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
|
||||
goes on reporting what its signal handlers see, and `kwin_reports(name)`
|
||||
reads every line it has reported so far from the journal.
|
||||
- `monitor_bridge(path)` records the bridge's traffic on the session bus with
|
||||
`dbus-monitor`, and `latency.rounds` times each batch of commands in it, from
|
||||
the daemon's answer to the last frame KWin reports for the windows it moved.
|
||||
|
||||
@@ -43,6 +43,8 @@ window and pause the daemon, and
|
||||
and keep parts of a monitor free of them.
|
||||
[Rules](usage/rules.md) explains how to keep an application out of the layout, always tile it, or
|
||||
float its windows.
|
||||
[Workspaces](usage/workspaces.md) explains how each monitor shows one of its workspaces, which
|
||||
are KWin's virtual desktops, and how to show another or move a window to one.
|
||||
[Subscribing to notifications](usage/subscribing-to-notifications.md) explains how a program
|
||||
such as a status bar follows what komorebi does. The [CLI reference](cli/start.md) has a page
|
||||
for every `komorebic` command, generated from its help.
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
# Workspaces
|
||||
|
||||
Each monitor has workspaces, and shows one of them at a time. A workspace has its own windows
|
||||
and its own layout. komorebi's workspaces are KWin's virtual desktops: workspace 0 is the first
|
||||
desktop, workspace 1 the second, and so on, which is why the pager, the overview and KWin's
|
||||
shortcuts show and switch them too.
|
||||
|
||||
komorebi turns on KWin's per-output virtual desktops when it starts, so that each monitor shows
|
||||
a desktop of its own: switching the workspace of one monitor leaves the others as they are. It
|
||||
puts the setting back as it was when it stops.
|
||||
|
||||
## Showing another workspace
|
||||
|
||||
[`komorebic focus-workspace`](../cli/focus-workspace.md) shows a workspace of the focused
|
||||
monitor, by its number, counted from 0. KWin shows the windows of that workspace and hides the
|
||||
others, and the window of that workspace that had the focus has it again.
|
||||
|
||||
```sh
|
||||
komorebic focus-workspace 1
|
||||
komorebic focus-workspace 0
|
||||
```
|
||||
|
||||
A workspace that does not exist yet is created, with the ones before it, and KWin gets a
|
||||
desktop for each, named "Workspace 2" and so on. A desktop that is there already keeps its
|
||||
name. The desktops komorebi creates stay when it stops.
|
||||
|
||||
## Moving a window to another workspace
|
||||
|
||||
[`komorebic move-to-workspace`](../cli/move-to-workspace.md) takes the focused window to another
|
||||
workspace, puts it after the windows there, and shows that workspace.
|
||||
[`komorebic send-to-workspace`](../cli/send-to-workspace.md) does the same and stays on the
|
||||
workspace in front, which is tiled again without the window.
|
||||
|
||||
```sh
|
||||
komorebic move-to-workspace 1
|
||||
komorebic send-to-workspace 2
|
||||
```
|
||||
|
||||
## Switching with KWin
|
||||
|
||||
Anything that switches KWin's desktop switches komorebi's workspace: the pager, KWin's own
|
||||
shortcuts, the overview, or an application that raises a window of another desktop (KWin then
|
||||
shows that desktop and focuses the window). komorebi follows, tiles the workspace that came
|
||||
into view, and asks KWin for nothing in reply. A window moved to another desktop with the
|
||||
window menu's "Move to Desktop" moves to that workspace.
|
||||
|
||||
## The windows that were open before
|
||||
|
||||
When komorebi starts, each window that is open goes to the workspace whose desktop it is on,
|
||||
and each monitor starts on the workspace KWin shows there. A window that is on every desktop
|
||||
goes to the workspace in front.
|
||||
@@ -52,6 +52,12 @@ pub enum Command {
|
||||
Close(u32),
|
||||
/// [`Backend::center_cursor_in`].
|
||||
CenterCursor(Rect),
|
||||
/// [`Backend::ensure_workspaces`]: how many workspaces were asked for.
|
||||
EnsureWorkspaces(usize),
|
||||
/// [`Backend::switch_workspace`]: the monitor, and the workspace it was asked to show.
|
||||
SwitchWorkspace(u32, usize),
|
||||
/// [`Backend::set_window_workspace`]: the window, and the workspace it was put on.
|
||||
SetWindowWorkspace(u32, usize),
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -65,6 +71,42 @@ struct State {
|
||||
foreground: Option<u32>,
|
||||
cursor: Option<(i32, i32)>,
|
||||
commands: Vec<Command>,
|
||||
/// how many virtual desktops there are
|
||||
desktops: usize,
|
||||
/// the desktop every window is on
|
||||
window_ws: HashMap<u32, usize>,
|
||||
/// the desktop each monitor (by id) shows
|
||||
shown: HashMap<u32, usize>,
|
||||
}
|
||||
|
||||
impl State {
|
||||
/// The monitor a window is on: the one that holds the middle of it, else the first
|
||||
fn monitor_of(&self, id: u32) -> Option<u32> {
|
||||
let w = self.windows.get(&id)?;
|
||||
let (x, y) = (
|
||||
w.rect.left + w.rect.right / 2,
|
||||
w.rect.top + w.rect.bottom / 2,
|
||||
);
|
||||
self.monitors
|
||||
.iter()
|
||||
.find(|m| {
|
||||
x >= m.size.left
|
||||
&& x < m.size.left + m.size.right
|
||||
&& y >= m.size.top
|
||||
&& y < m.size.top + m.size.bottom
|
||||
})
|
||||
.or_else(|| self.monitors.first())
|
||||
.map(|m| m.id)
|
||||
}
|
||||
|
||||
/// What a window opened now would be on, as in KWin: the desktop its monitor is showing
|
||||
fn desktop_for_new_window(&self) -> usize {
|
||||
self.monitors
|
||||
.first()
|
||||
.and_then(|m| self.shown.get(&m.id))
|
||||
.copied()
|
||||
.unwrap_or(0)
|
||||
}
|
||||
}
|
||||
|
||||
/// An in-memory [`Backend`].
|
||||
@@ -127,9 +169,12 @@ impl FakeBackend {
|
||||
}
|
||||
|
||||
/// Opens a window of an application. It starts at 800x600 at (100, 100), a normal window with
|
||||
/// no focus.
|
||||
/// no focus, on the workspace the first monitor shows.
|
||||
pub fn open_window(&self, id: u32, exe: &str, class: &str, title: &str) {
|
||||
self.state.lock().windows.insert(
|
||||
let mut state = self.state.lock();
|
||||
let desktop = state.desktop_for_new_window();
|
||||
state.window_ws.insert(id, desktop);
|
||||
state.windows.insert(
|
||||
id,
|
||||
WindowInfo {
|
||||
id,
|
||||
@@ -207,6 +252,45 @@ 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.
|
||||
pub fn on_screen(&self, id: u32) -> bool {
|
||||
let state = self.state.lock();
|
||||
let Some(window) = state.windows.get(&id) else {
|
||||
return false;
|
||||
};
|
||||
let monitor = state.monitor_of(id);
|
||||
let shown = monitor
|
||||
.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
|
||||
}
|
||||
|
||||
/// Returns the workspace a window is on, if it was ever opened.
|
||||
pub fn workspace_of(&self, id: u32) -> Option<usize> {
|
||||
self.state.lock().window_ws.get(&id).copied()
|
||||
}
|
||||
|
||||
/// Returns the workspace a monitor shows.
|
||||
pub fn shown_workspace(&self, monitor_id: u32) -> usize {
|
||||
self.state
|
||||
.lock()
|
||||
.shown
|
||||
.get(&monitor_id)
|
||||
.copied()
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Shows workspace `idx` on a monitor the way something other than komorebi does (a pager, a
|
||||
/// shortcut, a click on a window of another desktop): no command is recorded, and the
|
||||
/// compositor's event about it is the test's to send.
|
||||
pub fn show_workspace_by_user(&self, monitor_id: u32, idx: usize) {
|
||||
let mut state = self.state.lock();
|
||||
state.desktops = state.desktops.max(idx + 1);
|
||||
state.shown.insert(monitor_id, idx);
|
||||
}
|
||||
|
||||
/// Returns every command received so far, oldest first.
|
||||
pub fn commands(&self) -> Vec<Command> {
|
||||
self.state.lock().commands.clone()
|
||||
@@ -344,6 +428,47 @@ impl Backend for FakeBackend {
|
||||
state.cursor = Some((rect.left + rect.right / 2, rect.top + rect.bottom / 2));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn ensure_workspaces(&self, names: &[String]) -> eyre::Result<()> {
|
||||
let mut state = self.state.lock();
|
||||
state.commands.push(Command::EnsureWorkspaces(names.len()));
|
||||
state.desktops = state.desktops.max(names.len());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn switch_workspace(&self, monitor_id: u32, idx: usize) -> eyre::Result<()> {
|
||||
let mut state = self.state.lock();
|
||||
state
|
||||
.commands
|
||||
.push(Command::SwitchWorkspace(monitor_id, idx));
|
||||
state.desktops = state.desktops.max(idx + 1);
|
||||
state.shown.insert(monitor_id, idx);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_window_workspace(&self, id: u32, idx: usize) -> eyre::Result<()> {
|
||||
self.record(id, Command::SetWindowWorkspace(id, idx), |state| {
|
||||
state.desktops = state.desktops.max(idx + 1);
|
||||
state.window_ws.insert(id, idx);
|
||||
})
|
||||
}
|
||||
|
||||
fn window_workspace(&self, id: u32) -> Option<usize> {
|
||||
let mut state = self.state.lock();
|
||||
if state.permissive && !state.windows.contains_key(&id) {
|
||||
state.windows.insert(id, permissive_window(id));
|
||||
}
|
||||
state.window_ws.get(&id).copied()
|
||||
}
|
||||
|
||||
fn current_workspaces(&self) -> Vec<(u32, usize)> {
|
||||
let state = self.state.lock();
|
||||
state
|
||||
.monitors
|
||||
.iter()
|
||||
.map(|m| (m.id, state.shown.get(&m.id).copied().unwrap_or(0)))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -500,6 +625,69 @@ mod tests {
|
||||
assert_eq!(ids, [1, 3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_opens_on_the_workspace_the_first_monitor_shows() {
|
||||
let fake = FakeBackend::with_one_monitor();
|
||||
fake.show_workspace_by_user(1, 2);
|
||||
|
||||
fake.open_window(1, "foot", "foot", "window 1");
|
||||
|
||||
assert_eq!(fake.workspace_of(1), Some(2));
|
||||
assert_eq!(fake.window_workspace(1), Some(2));
|
||||
assert!(fake.on_screen(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_monitor_shows_the_windows_of_its_workspace_and_no_others() -> eyre::Result<()> {
|
||||
let fake = fake_with(&[1, 2]);
|
||||
fake.set_window_workspace(2, 1)?;
|
||||
|
||||
assert!(fake.on_screen(1) && !fake.on_screen(2));
|
||||
|
||||
fake.switch_workspace(1, 1)?;
|
||||
|
||||
assert!(!fake.on_screen(1) && fake.on_screen(2));
|
||||
assert_eq!(fake.shown_workspace(1), 1);
|
||||
assert_eq!(fake.current_workspaces(), [(1, 1)]);
|
||||
assert_eq!(
|
||||
fake.commands(),
|
||||
[
|
||||
Command::SetWindowWorkspace(2, 1),
|
||||
Command::SwitchWorkspace(1, 1)
|
||||
]
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_workspace_shown_by_the_user_is_not_a_command() {
|
||||
let fake = fake_with(&[1]);
|
||||
|
||||
fake.show_workspace_by_user(1, 3);
|
||||
|
||||
assert_eq!(fake.current_workspaces(), [(1, 3)]);
|
||||
assert!(fake.commands().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_minimized_window_or_one_that_closed_is_not_on_screen() -> eyre::Result<()> {
|
||||
let fake = fake_with(&[1, 2]);
|
||||
|
||||
fake.minimize(1)?;
|
||||
fake.close_window_now(2);
|
||||
|
||||
assert!(!fake.on_screen(1) && !fake.on_screen(2));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn putting_a_window_nobody_opened_on_a_workspace_is_an_error() {
|
||||
let fake = fake_with(&[1]);
|
||||
|
||||
assert!(fake.set_window_workspace(9, 1).is_err());
|
||||
assert_eq!(fake.workspace_of(9), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cursor_can_be_centered_in_a_rectangle() -> eyre::Result<()> {
|
||||
let fake = FakeBackend::new();
|
||||
|
||||
@@ -20,6 +20,14 @@
|
||||
//! short time, with [`WindowInfo::alive`] false, so that the event that mentions it can still be
|
||||
//! logged. Commands return once the compositor has accepted them, not once the client has acted on
|
||||
//! them, and an implementation may batch them.
|
||||
//!
|
||||
//! # Workspaces
|
||||
//!
|
||||
//! komorebi's workspaces are the compositor's virtual desktops, per monitor: the window manager
|
||||
//! asks for workspace `i` to be shown on a monitor ([`Backend::switch_workspace`]) and for a window
|
||||
//! 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.
|
||||
|
||||
#![deny(missing_docs)]
|
||||
|
||||
@@ -89,6 +97,12 @@ pub struct MonitorInfo {
|
||||
/// - A command about a window that does not exist, or is no longer alive, returns an error. It does
|
||||
/// not panic.
|
||||
/// - A backend is `Send + Sync`: the window manager calls it from several threads.
|
||||
/// - Workspace `i` is the compositor's virtual desktop `i` on every monitor, and each monitor shows
|
||||
/// 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 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.
|
||||
///
|
||||
/// The compiler enforces the first and last parts of the contract that it can see. A backend that
|
||||
/// leaves out a method does not compile:
|
||||
@@ -123,6 +137,11 @@ pub struct MonitorInfo {
|
||||
/// # fn unminimize(&self, _: u32) -> eyre::Result<()> { Ok(()) }
|
||||
/// # fn close(&self, _: u32) -> eyre::Result<()> { Ok(()) }
|
||||
/// # fn center_cursor_in(&self, _: &Rect) -> eyre::Result<()> { Ok(()) }
|
||||
/// # fn ensure_workspaces(&self, _: &[String]) -> eyre::Result<()> { Ok(()) }
|
||||
/// # fn switch_workspace(&self, _: u32, _: usize) -> eyre::Result<()> { Ok(()) }
|
||||
/// # fn set_window_workspace(&self, _: u32, _: usize) -> eyre::Result<()> { Ok(()) }
|
||||
/// # fn window_workspace(&self, _: u32) -> Option<usize> { None }
|
||||
/// # fn current_workspaces(&self) -> Vec<(u32, usize)> { vec![] }
|
||||
/// # }
|
||||
/// ```
|
||||
pub trait Backend: Send + Sync + 'static {
|
||||
@@ -201,6 +220,49 @@ pub trait Backend: Send + Sync + 'static {
|
||||
/// When the compositor refuses to move the pointer.
|
||||
fn center_cursor_in(&self, rect: &Rect) -> eyre::Result<()>;
|
||||
|
||||
// ---- workspaces ----------------------------------------------------------------------------
|
||||
//
|
||||
// komorebi's workspaces are the compositor's own virtual desktops: workspace `i` is desktop `i`
|
||||
// on every monitor, and each monitor shows one at a time. Showing, hiding and focusing the
|
||||
// windows of a workspace is then the compositor's business; komorebi tiles what is in front and
|
||||
// follows the compositor when something else (a pager, a shortcut, an app raising a window)
|
||||
// changes what a monitor shows.
|
||||
|
||||
/// Makes sure there are at least as many desktops as `names`, creating the missing ones with
|
||||
/// those names.
|
||||
///
|
||||
/// A desktop that is already there keeps its name, unless nobody chose it (the compositor's
|
||||
/// own "Desktop 2"), in which case it may take the name it is given.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// When the compositor refuses to create or rename a desktop.
|
||||
fn ensure_workspaces(&self, names: &[String]) -> eyre::Result<()>;
|
||||
|
||||
/// Shows workspace `idx` on the monitor `monitor_id`, leaving the other monitors as they are.
|
||||
///
|
||||
/// The compositor shows the windows on that workspace, hides the rest, and gives the focus to a
|
||||
/// window of that workspace by itself.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// When there is no desktop for `idx` and one cannot be made.
|
||||
fn switch_workspace(&self, monitor_id: u32, idx: usize) -> eyre::Result<()>;
|
||||
|
||||
/// Puts a window on workspace `idx`. It is visible at once to [`Backend::window_workspace`].
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// When the window does not exist, or there is no desktop for `idx` and one cannot be made.
|
||||
fn set_window_workspace(&self, id: u32, idx: usize) -> eyre::Result<()>;
|
||||
|
||||
/// Returns the workspace a window is on, or `None` for a window the compositor does not know or
|
||||
/// that is on every workspace.
|
||||
fn window_workspace(&self, id: u32) -> Option<usize>;
|
||||
|
||||
/// Returns the workspace each monitor shows, as `(monitor id, workspace index)`.
|
||||
fn current_workspaces(&self) -> Vec<(u32, usize)>;
|
||||
|
||||
// ---- provided ------------------------------------------------------------------------------
|
||||
|
||||
/// Called once as komorebi exits, after the window manager has put back what it moved, so that
|
||||
|
||||
@@ -348,6 +348,8 @@ pub enum SocketMessage {
|
||||
CycleMoveWindow(CycleDirection),
|
||||
ResizeWindowEdge(OperationDirection, Sizing),
|
||||
ResizeWindowAxis(Axis, Sizing),
|
||||
MoveContainerToWorkspaceNumber(usize),
|
||||
SendContainerToWorkspaceNumber(usize),
|
||||
// ForceFocus,
|
||||
Close,
|
||||
Minimize,
|
||||
@@ -382,6 +384,7 @@ pub enum SocketMessage {
|
||||
QuickLoad,
|
||||
Save(#[serde_as(as = "ResolvedPathBuf")] PathBuf),
|
||||
Load(#[serde_as(as = "ResolvedPathBuf")] PathBuf),
|
||||
FocusWorkspaceNumber(usize),
|
||||
ContainerPadding(usize, usize, i32),
|
||||
FocusedWorkspaceContainerPadding(i32),
|
||||
WorkspacePadding(usize, usize, i32),
|
||||
|
||||
+25
-7
@@ -141,13 +141,19 @@ pub fn load_monitor_information(wm: &mut WindowManager) -> eyre::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Puts the windows that are already open into containers on the focused workspace of the
|
||||
/// monitor they are on, so that starting komorebi tiles what is on screen.
|
||||
/// Puts the windows that are already open into containers on the workspace of the monitor they
|
||||
/// are on, so that starting komorebi tiles what is on screen.
|
||||
///
|
||||
/// A window is on the monitor whose bounds contain its middle. A window that is minimized, that
|
||||
/// komorebi does not manage ([`Window::should_manage`]: not a normal window, or one the rules
|
||||
/// ignore), or that is on no monitor is left alone.
|
||||
/// Nothing is moved: tiling is [`WindowManager::retile_all`]'s job.
|
||||
/// Each monitor is first focused on the workspace the compositor shows on it
|
||||
/// ([`Backend::current_workspaces`]). A window is on the monitor whose bounds contain its middle,
|
||||
/// and on the workspace whose desktop it is on ([`Backend::window_workspace`]), which need not be
|
||||
/// the one in front; a window on every desktop goes to the one in front. The monitor gets as many
|
||||
/// workspaces as that takes. A window that is minimized, that komorebi does not manage
|
||||
/// ([`Window::should_manage`]: not a normal window, or one the rules ignore), or that is on no
|
||||
/// monitor is left alone. Nothing is moved: tiling is [`WindowManager::retile_all`]'s job.
|
||||
///
|
||||
/// [`Backend::current_workspaces`]: crate::backend::Backend::current_workspaces
|
||||
/// [`Backend::window_workspace`]: crate::backend::Backend::window_workspace
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
@@ -181,6 +187,7 @@ pub fn load_monitor_information(wm: &mut WindowManager) -> eyre::Result<()> {
|
||||
/// let workspace = wm.focused_workspace()?;
|
||||
/// assert!(workspace.contains_window(1));
|
||||
/// assert!(!workspace.contains_window(2));
|
||||
/// assert_eq!(wm.focused_workspace_idx()?, 0);
|
||||
/// # std::fs::remove_file(socket)?;
|
||||
/// # Ok::<(), color_eyre::eyre::Report>(())
|
||||
/// ```
|
||||
@@ -188,6 +195,13 @@ pub fn load_monitor_information(wm: &mut WindowManager) -> eyre::Result<()> {
|
||||
pub fn load_workspace_information(wm: &mut WindowManager) -> eyre::Result<()> {
|
||||
let mut valid_window_count = 0;
|
||||
|
||||
// each monitor starts out showing the workspace the compositor is showing on it
|
||||
for (monitor_id, idx) in backend().current_workspaces() {
|
||||
if let Some(monitor) = wm.monitors_mut().iter_mut().find(|m| m.id == monitor_id) {
|
||||
monitor.focus_workspace(idx)?;
|
||||
}
|
||||
}
|
||||
|
||||
for info in backend().windows() {
|
||||
if info.minimized {
|
||||
continue;
|
||||
@@ -212,10 +226,14 @@ pub fn load_workspace_information(wm: &mut WindowManager) -> eyre::Result<()> {
|
||||
continue;
|
||||
};
|
||||
|
||||
// a window is on the workspace whose desktop it is on, not necessarily the one in front
|
||||
let Some(monitor) = wm.monitors_mut().get_mut(monitor_idx) else {
|
||||
continue;
|
||||
};
|
||||
let workspace_idx = monitor.focused_workspace_idx();
|
||||
let workspace_idx = backend()
|
||||
.window_workspace(info.id)
|
||||
.unwrap_or_else(|| monitor.focused_workspace_idx());
|
||||
monitor.ensure_workspace_count(workspace_idx + 1);
|
||||
|
||||
if let Some(workspace) = monitor.workspaces_mut().get_mut(workspace_idx) {
|
||||
let mut container = Container::default();
|
||||
|
||||
+120
-7
@@ -41,16 +41,25 @@
|
||||
* }} Screen
|
||||
*/
|
||||
|
||||
/**
|
||||
* A virtual desktop, by KWin's id for it and its name; and the desktop an output shows.
|
||||
*
|
||||
* @typedef {{ id: string, name: string }} Desktop
|
||||
* @typedef {{ output: string, id: string }} CurrentDesktop
|
||||
*/
|
||||
|
||||
/**
|
||||
* What the bridge sends, as the one argument of `Event`. `emit` adds `seq` to each, which counts
|
||||
* them from 1. `snapshot` is everything on the desktop, sent once, when the script starts; an
|
||||
* `activated` with no `id` means no window has the focus; `caption` is a window's new title;
|
||||
* `desktops` says which desktops a window is on now, `desktop_list` which desktops there are, and
|
||||
* `current_desktops` which desktop each output shows, each sent when it is not what was last sent;
|
||||
* `cursor` answers a cursor query, and `failed` gives back the commands of a batch that could not
|
||||
* be carried out.
|
||||
*
|
||||
* @typedef {{
|
||||
* type: "snapshot", windows: WindowInfo[], screens: Screen[], active: string | null,
|
||||
* cursor: Point
|
||||
* type: "snapshot", windows: WindowInfo[], screens: Screen[], desktops: Desktop[],
|
||||
* current_desktops: CurrentDesktop[], active: string | null, cursor: Point
|
||||
* }} Snapshot
|
||||
* @typedef {WindowInfo & { type: "added" }} Added
|
||||
* @typedef {{ type: "removed", id: string }} Removed
|
||||
@@ -58,25 +67,32 @@
|
||||
* @typedef {{ type: "minimized", id: string, v: boolean }} Minimized
|
||||
* @typedef {{ type: "geometry", id: string, geo: Rect }} Geometry
|
||||
* @typedef {{ type: "caption", id: string, caption: string }} Caption
|
||||
* @typedef {{ type: "desktops", id: string, desktops: string[] }} Desktops
|
||||
* @typedef {{ type: "desktop_list", desktops: Desktop[] }} DesktopList
|
||||
* @typedef {{ type: "current_desktops", current: CurrentDesktop[] }} CurrentDesktops
|
||||
* @typedef {{ type: "cursor", token: number, x: number, y: number }} CursorAnswer
|
||||
* @typedef {{ type: "failed", batch: number, cmds: Command[] }} Failed
|
||||
* @typedef {Snapshot | Added | Removed | Activated | Minimized | Geometry | Caption | CursorAnswer | Failed} BridgeEvent
|
||||
* @typedef {Snapshot | Added | Removed | Activated | Minimized | Geometry | Caption | Desktops
|
||||
* | DesktopList | CurrentDesktops | CursorAnswer | Failed} BridgeEvent
|
||||
*/
|
||||
|
||||
/**
|
||||
* What the daemon sends: the answer to `Poll` is a list of batches, each a list of commands. A
|
||||
* window command names the window by its `id`: `geo` sets its frame, `min` minimizes it (`v`) or
|
||||
* brings it back, and `activate`, `raise` and `close` do what they say. A cursor query is
|
||||
* numbered by `token` so that its answer can be matched.
|
||||
* brings it back, `desktop` puts it on the desktop `v` (and on no other), and `activate`, `raise`
|
||||
* and `close` do what they say. `output_desktop` shows the desktop `v` on one output, leaving the
|
||||
* others as they are. A cursor query is numbered by `token` so that its answer can be matched.
|
||||
*
|
||||
* @typedef {{ op: "cursor", token: number }} CursorQuery
|
||||
* @typedef {{ op: "output_desktop", output: string, v: string }} OutputDesktop
|
||||
* @typedef {{ op: "geo", id: string, x: number, y: number, w: number, h: number }} SetFrame
|
||||
* @typedef {{ op: "min", id: string, v: boolean }} SetMinimized
|
||||
* @typedef {{ op: "activate", id: string }} Activate
|
||||
* @typedef {{ op: "raise", id: string }} Raise
|
||||
* @typedef {{ op: "close", id: string }} Close
|
||||
* @typedef {SetFrame | SetMinimized | Activate | Raise | Close} WindowCommand
|
||||
* @typedef {CursorQuery | WindowCommand} Command
|
||||
* @typedef {{ op: "desktop", id: string, v: string }} SetDesktop
|
||||
* @typedef {SetFrame | SetMinimized | Activate | Raise | Close | SetDesktop} WindowCommand
|
||||
* @typedef {CursorQuery | OutputDesktop | WindowCommand} Command
|
||||
* @typedef {{ batch: number, cmds: Command[] }} Batch
|
||||
*/
|
||||
|
||||
@@ -207,6 +223,59 @@ function cursor() {
|
||||
return { x: Math.round(p.x), y: Math.round(p.y) };
|
||||
}
|
||||
|
||||
/** @returns {Desktop[]} */
|
||||
function desktops() {
|
||||
var ds = [];
|
||||
for (var i = 0; i < workspace.desktops.length; i++) {
|
||||
ds.push({ id: String(workspace.desktops[i].id), name: String(workspace.desktops[i].name) });
|
||||
}
|
||||
return ds;
|
||||
}
|
||||
|
||||
// The desktop each output shows. With per-output virtual desktops (which komorebi turns on) the
|
||||
// outputs are independent: that is what lets each monitor have its own workspace in front.
|
||||
/** @returns {CurrentDesktop[]} */
|
||||
function currentDesktops() {
|
||||
var out = [];
|
||||
for (var i = 0; i < workspace.screens.length; i++) {
|
||||
var s = workspace.screens[i];
|
||||
out.push({ output: String(s.name), id: String(workspace.currentDesktopForScreen(s).id) });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} name
|
||||
* @returns {Output | null}
|
||||
*/
|
||||
function screenByName(name) {
|
||||
for (var i = 0; i < workspace.screens.length; i++) {
|
||||
if (String(workspace.screens[i].name) === name) {
|
||||
return workspace.screens[i];
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// KWin has one signal for "an output changed desktop" and it does not say which, so the whole set is
|
||||
// compared with what was last announced, here and once a second.
|
||||
var lastCurrent = "";
|
||||
var lastDesktopList = "";
|
||||
|
||||
function announceDesktops() {
|
||||
var list = JSON.stringify(desktops());
|
||||
if (list !== lastDesktopList) {
|
||||
lastDesktopList = list;
|
||||
emit("desktop_list", { desktops: JSON.parse(list) });
|
||||
}
|
||||
|
||||
var now = JSON.stringify(currentDesktops());
|
||||
if (now !== lastCurrent) {
|
||||
lastCurrent = now;
|
||||
emit("current_desktops", { current: JSON.parse(now) });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} id
|
||||
* @returns {KWinWindow | null}
|
||||
@@ -224,6 +293,19 @@ function findWindow(id) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} id
|
||||
* @returns {VirtualDesktop | null}
|
||||
*/
|
||||
function findDesktop(id) {
|
||||
for (var i = 0; i < workspace.desktops.length; i++) {
|
||||
if (String(workspace.desktops[i].id) === id) {
|
||||
return workspace.desktops[i];
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// A window has moved or been resized; if it is not where komorebi asked, ask again for the
|
||||
// position alone (see `want`). A few tries at most, so a window that cannot go where it was asked
|
||||
// (a fullscreen one, say) is left alone rather than chased.
|
||||
@@ -272,6 +354,9 @@ function track(w, announce) {
|
||||
w.captionChanged.connect(function () {
|
||||
emit("caption", { id: id, caption: String(w.caption) });
|
||||
});
|
||||
w.desktopsChanged.connect(function () {
|
||||
emit("desktops", { id: id, desktops: desktopIds(w) });
|
||||
});
|
||||
}
|
||||
|
||||
workspace.windowAdded.connect(function (w) {
|
||||
@@ -298,6 +383,12 @@ function announceActive(w) {
|
||||
}
|
||||
|
||||
workspace.windowActivated.connect(announceActive);
|
||||
workspace.currentDesktopChanged.connect(function () {
|
||||
announceDesktops();
|
||||
});
|
||||
workspace.desktopsChanged.connect(function () {
|
||||
announceDesktops();
|
||||
});
|
||||
|
||||
var existing = workspace.windowList();
|
||||
for (var i = 0; i < existing.length; i++) {
|
||||
@@ -305,10 +396,14 @@ for (var i = 0; i < existing.length; i++) {
|
||||
}
|
||||
|
||||
lastActive = workspace.activeWindow ? wid(workspace.activeWindow) : null;
|
||||
lastCurrent = JSON.stringify(currentDesktops());
|
||||
lastDesktopList = JSON.stringify(desktops());
|
||||
|
||||
emit("snapshot", {
|
||||
windows: workspace.windowList().map(describe),
|
||||
screens: screens(),
|
||||
desktops: desktops(),
|
||||
current_desktops: currentDesktops(),
|
||||
active: workspace.activeWindow ? wid(workspace.activeWindow) : null,
|
||||
cursor: cursor()
|
||||
});
|
||||
@@ -326,6 +421,15 @@ function applyOne(c) {
|
||||
emit("cursor", { token: c.token, x: p.x, y: p.y });
|
||||
return true;
|
||||
}
|
||||
if (c.op === "output_desktop") {
|
||||
// show a desktop on one output, leaving the others as they are
|
||||
var target = findDesktop(c.v);
|
||||
var screen = screenByName(c.output);
|
||||
if (target && screen) {
|
||||
workspace.setCurrentDesktopForScreen(target, screen);
|
||||
}
|
||||
return !!(target && screen);
|
||||
}
|
||||
|
||||
var w = findWindow(c.id);
|
||||
if (!w) {
|
||||
@@ -349,6 +453,14 @@ function applyOne(c) {
|
||||
case "close":
|
||||
w.closeWindow();
|
||||
break;
|
||||
case "desktop": {
|
||||
var d = findDesktop(c.v);
|
||||
if (!d) {
|
||||
return false;
|
||||
}
|
||||
w.desktops = [d];
|
||||
break;
|
||||
}
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
@@ -408,5 +520,6 @@ watchdog.timeout.connect(function () {
|
||||
if (Date.now() - lastIssue > CFG.hold_ms + 3000) {
|
||||
pull();
|
||||
}
|
||||
announceDesktops();
|
||||
});
|
||||
watchdog.start();
|
||||
@@ -57,13 +57,14 @@ function geometry(x, y, width, height) {
|
||||
}
|
||||
|
||||
// A window. `id` becomes its `internalId`, which is a QUuid in KWin: an object, not a string.
|
||||
// Setting `minimized` or `frameGeometry` raises the signal KWin raises, and `closeWindow` closes it
|
||||
// once it is in a KWin. `place` is where KWin puts the window when it is asked for a frame: where
|
||||
// it was asked, unless a test says otherwise.
|
||||
// Setting `minimized`, `frameGeometry` or `desktops` raises the signal KWin raises, and
|
||||
// `closeWindow` closes it once it is in a KWin. `place` is where KWin puts the window when it is
|
||||
// asked for a frame: where it was asked, unless a test says otherwise.
|
||||
function window({
|
||||
id,
|
||||
minimized = false,
|
||||
frameGeometry = geometry(0, 0, 100, 100),
|
||||
desktops = [],
|
||||
place = (g) => g,
|
||||
...rest
|
||||
}) {
|
||||
@@ -83,15 +84,22 @@ function window({
|
||||
minSize: { width: 0, height: 0 },
|
||||
move: false,
|
||||
resize: false,
|
||||
desktops: [],
|
||||
frameGeometryChanged: new Signal(),
|
||||
minimizedChanged: new Signal(),
|
||||
captionChanged: new Signal(),
|
||||
desktopsChanged: new Signal(),
|
||||
closeWindow: () => assert.fail("a window that is in no KWin was closed"),
|
||||
...rest,
|
||||
};
|
||||
let state = { minimized, frameGeometry };
|
||||
let state = { minimized, frameGeometry, desktops };
|
||||
Object.defineProperties(w, {
|
||||
desktops: {
|
||||
get: () => state.desktops,
|
||||
set: (ds) => {
|
||||
state.desktops = ds;
|
||||
w.desktopsChanged.emit();
|
||||
},
|
||||
},
|
||||
minimized: {
|
||||
get: () => state.minimized,
|
||||
set: (v) => {
|
||||
@@ -123,8 +131,23 @@ const DP1 = {
|
||||
placementArea: geometry(0, 0, 1920, 1050),
|
||||
};
|
||||
|
||||
// the virtual desktops of a KWin that nobody has given any others
|
||||
function twoDesktops() {
|
||||
return [
|
||||
{ id: "desktop-1", name: "Desktop 1" },
|
||||
{ id: "desktop-2", name: "Desktop 2" },
|
||||
];
|
||||
}
|
||||
|
||||
// A KWin with `windows` open, `active` focused and the pointer at `cursor`, running the bridge.
|
||||
function kwin({ windows = [], screens = [DP1], active = null, cursor = { x: 0, y: 0 } } = {}) {
|
||||
// Every output shows the first of `desktops`.
|
||||
function kwin({
|
||||
windows = [],
|
||||
screens = [DP1],
|
||||
desktops = twoDesktops(),
|
||||
active = null,
|
||||
cursor = { x: 0, y: 0 },
|
||||
} = {}) {
|
||||
const calls = [];
|
||||
const printed = [];
|
||||
const raised = [];
|
||||
@@ -132,21 +155,30 @@ function kwin({ windows = [], screens = [DP1], active = null, cursor = { x: 0, y
|
||||
const clock = { now: 1000 };
|
||||
const open = [];
|
||||
let activeWindow = active;
|
||||
const current = Object.fromEntries(screens.map((s) => [s.name, desktops[0]]));
|
||||
|
||||
const workspace = {
|
||||
screens,
|
||||
desktops,
|
||||
cursorPos: cursor,
|
||||
windowList: () => open.slice(),
|
||||
clientArea: (option, output, desktop) => {
|
||||
assert.equal(option, 7, "the placement area");
|
||||
assert.equal(desktop.id, `desktop of ${output.name}`);
|
||||
assert.equal(desktop, current[output.name], "the desktop the output shows");
|
||||
return output.placementArea;
|
||||
},
|
||||
currentDesktopForScreen: (output) => ({ id: `desktop of ${output.name}` }),
|
||||
currentDesktopForScreen: (output) => current[output.name],
|
||||
// per-output virtual desktops: the other outputs keep theirs
|
||||
setCurrentDesktopForScreen: (desktop, output) => {
|
||||
current[output.name] = desktop;
|
||||
workspace.currentDesktopChanged.emit();
|
||||
},
|
||||
raiseWindow: (w) => raised.push(w),
|
||||
windowAdded: new Signal(),
|
||||
windowRemoved: new Signal(),
|
||||
windowActivated: new Signal(),
|
||||
currentDesktopChanged: new Signal(),
|
||||
desktopsChanged: new Signal(),
|
||||
};
|
||||
Object.defineProperty(workspace, "activeWindow", {
|
||||
get: () => activeWindow,
|
||||
@@ -219,6 +251,11 @@ function kwin({ windows = [], screens = [DP1], active = null, cursor = { x: 0, y
|
||||
},
|
||||
// the daemon answers the bridge's last `Poll` with these batches
|
||||
answer: (batches) => k.reply(JSON.stringify(batches)),
|
||||
// somebody makes another desktop (System Settings, the pager)
|
||||
createDesktop: (desktop) => {
|
||||
desktops.push(desktop);
|
||||
workspace.desktopsChanged.emit();
|
||||
},
|
||||
};
|
||||
return k;
|
||||
}
|
||||
@@ -267,7 +304,7 @@ test("what the bridge sends for a session is what the daemon's tests read", () =
|
||||
// the client took the frame it was given to whole cells of its font
|
||||
terminal.frameGeometry = geometry(480.4, 270, 956, 532);
|
||||
|
||||
const [cursorQuery, windowCommands] = commands;
|
||||
const [cursorQuery, windowCommands, workspaceCommands] = commands;
|
||||
assert.equal(k.events().at(-1).seq, cursorQuery.after_seq);
|
||||
k.workspace.cursorPos = { x: 1200, y: 700.5 };
|
||||
k.answer([cursorQuery.batch]);
|
||||
@@ -279,6 +316,19 @@ test("what the bridge sends for a session is what the daemon's tests read", () =
|
||||
assert.equal(k.events().at(-1).seq, windowCommands.after_seq);
|
||||
k.answer([windowCommands.batch]);
|
||||
|
||||
// the editor is sent to the second workspace, and the output is switched to it
|
||||
assert.equal(k.events().at(-1).seq, workspaceCommands.after_seq);
|
||||
k.answer([workspaceCommands.batch]);
|
||||
const [first, second] = k.workspace.desktops;
|
||||
// (an array the script made, whose prototype is not this file's)
|
||||
assert.deepStrictEqual([...editor.desktops], [second]);
|
||||
assert.equal(k.workspace.currentDesktopForScreen(DP1), second);
|
||||
|
||||
// then somebody else makes a desktop, moves the editor back to the first, and shows that
|
||||
k.createDesktop({ id: "desktop-3", name: "mail" });
|
||||
editor.desktops = [first];
|
||||
k.workspace.setCurrentDesktopForScreen(first, DP1);
|
||||
|
||||
assert.deepStrictEqual(k.events(), events);
|
||||
assert.deepStrictEqual(editor.frameGeometry, geometry(0, 0, 960, 1050));
|
||||
assert.equal(k.workspace.activeWindow, editor);
|
||||
@@ -287,6 +337,52 @@ test("what the bridge sends for a session is what the daemon's tests read", () =
|
||||
assert.deepStrictEqual(k.workspace.windowList(), [editor]);
|
||||
});
|
||||
|
||||
test("the desktop each output shows is sent when it changes, and once", () => {
|
||||
const k = kwin();
|
||||
const [first, second] = k.workspace.desktops;
|
||||
|
||||
k.workspace.setCurrentDesktopForScreen(second, DP1);
|
||||
k.timers[0].timeout.emit();
|
||||
k.workspace.setCurrentDesktopForScreen(first, DP1);
|
||||
|
||||
assert.deepStrictEqual(k.events().slice(1), [
|
||||
{ type: "current_desktops", current: [{ output: "DP-1", id: "desktop-2" }], seq: 2 },
|
||||
{ type: "current_desktops", current: [{ output: "DP-1", id: "desktop-1" }], seq: 3 },
|
||||
]);
|
||||
});
|
||||
|
||||
test("a desktop made while the bridge runs is sent as the new list of desktops", () => {
|
||||
const k = kwin();
|
||||
|
||||
k.createDesktop({ id: "desktop-3", name: "mail" });
|
||||
|
||||
assert.deepStrictEqual(k.events().at(-1), {
|
||||
type: "desktop_list",
|
||||
desktops: [
|
||||
{ id: "desktop-1", name: "Desktop 1" },
|
||||
{ id: "desktop-2", name: "Desktop 2" },
|
||||
{ id: "desktop-3", name: "mail" },
|
||||
],
|
||||
seq: 2,
|
||||
});
|
||||
});
|
||||
|
||||
test("a desktop a command names that KWin does not have is given back as failed", () => {
|
||||
const w = window({ id: "{w}", desktops: [{ id: "desktop-1" }] });
|
||||
const k = kwin({ windows: [w] });
|
||||
const commands = [
|
||||
{ op: "desktop", id: "{w}", v: "gone" },
|
||||
{ op: "output_desktop", output: "DP-1", v: "gone" },
|
||||
{ op: "output_desktop", output: "HDMI-9", v: "desktop-2" },
|
||||
];
|
||||
|
||||
k.answer([{ batch: 6, cmds: commands }]);
|
||||
|
||||
assert.deepStrictEqual(w.desktops, [{ id: "desktop-1" }]);
|
||||
assert.equal(k.workspace.currentDesktopForScreen(DP1).id, "desktop-1");
|
||||
assert.deepStrictEqual(k.events().at(-1), { type: "failed", batch: 6, cmds: commands, seq: 2 });
|
||||
});
|
||||
|
||||
test("a window KWin activates before announcing it is announced first, and once", () => {
|
||||
const k = kwin();
|
||||
const w = window({ id: "{w}" });
|
||||
|
||||
@@ -20,5 +20,15 @@
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"after_seq": 15,
|
||||
"batch": {
|
||||
"batch": 3,
|
||||
"cmds": [
|
||||
{"op": "desktop", "id": "{0e5a1c3b-0000-4000-8000-00000000000a}", "v": "desktop-2"},
|
||||
{"op": "output_desktop", "output": "DP-1", "v": "desktop-2"}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
@@ -18,6 +18,10 @@
|
||||
"area": {"x": 0, "y": 0, "w": 1920, "h": 1050}
|
||||
}
|
||||
],
|
||||
"desktops": [
|
||||
{"id": "desktop-1", "name": "Desktop 1"}, {"id": "desktop-2", "name": "Desktop 2"}
|
||||
],
|
||||
"current_desktops": [{"output": "DP-1", "id": "desktop-1"}],
|
||||
"active": "{0e5a1c3b-0000-4000-8000-00000000000a}", "cursor": {"x": 481, "y": 525}
|
||||
},
|
||||
{
|
||||
@@ -59,5 +63,22 @@
|
||||
"w": 960, "h": 1050
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "desktops", "seq": 16, "id": "{0e5a1c3b-0000-4000-8000-00000000000a}",
|
||||
"desktops": ["desktop-2"]
|
||||
},
|
||||
{"type": "current_desktops", "seq": 17, "current": [{"output": "DP-1", "id": "desktop-2"}]},
|
||||
{
|
||||
"type": "desktop_list", "seq": 18,
|
||||
"desktops": [
|
||||
{"id": "desktop-1", "name": "Desktop 1"}, {"id": "desktop-2", "name": "Desktop 2"},
|
||||
{"id": "desktop-3", "name": "mail"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "desktops", "seq": 19, "id": "{0e5a1c3b-0000-4000-8000-00000000000a}",
|
||||
"desktops": ["desktop-1"]
|
||||
},
|
||||
{"type": "current_desktops", "seq": 20, "current": [{"output": "DP-1", "id": "desktop-1"}]}
|
||||
]
|
||||
Vendored
+16
-1
@@ -45,8 +45,10 @@ interface QUuid {
|
||||
readonly __quuid: never;
|
||||
}
|
||||
|
||||
/** A virtual desktop (`KWin::VirtualDesktop`). `id` is a UUID, as a string. */
|
||||
interface VirtualDesktop {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
}
|
||||
|
||||
/** An output (`KWin::Output`). */
|
||||
@@ -82,10 +84,13 @@ interface KWinWindow {
|
||||
readonly move: boolean;
|
||||
/** True while the user resizes the window with the pointer. */
|
||||
readonly resize: boolean;
|
||||
readonly desktops: VirtualDesktop[];
|
||||
/** The desktops the window is on; empty when it is on all of them. Setting it moves the
|
||||
* window. */
|
||||
desktops: VirtualDesktop[];
|
||||
readonly frameGeometryChanged: Signal<[oldGeometry: QRectF]>;
|
||||
readonly minimizedChanged: Signal;
|
||||
readonly captionChanged: Signal;
|
||||
readonly desktopsChanged: Signal;
|
||||
closeWindow(): void;
|
||||
}
|
||||
|
||||
@@ -95,14 +100,24 @@ interface Workspace {
|
||||
/** Setting it activates the window. */
|
||||
activeWindow: KWinWindow | null;
|
||||
readonly cursorPos: QPointF;
|
||||
/** Every virtual desktop, in order. */
|
||||
readonly desktops: VirtualDesktop[];
|
||||
windowList(): KWinWindow[];
|
||||
clientArea(option: number, output: Output, desktop: VirtualDesktop): QRectF;
|
||||
/** The desktop an output shows. With per-output virtual desktops each output has its own. */
|
||||
currentDesktopForScreen(output: Output): VirtualDesktop;
|
||||
/** Shows a desktop on one output; with per-output virtual desktops the others keep theirs. */
|
||||
setCurrentDesktopForScreen(desktop: VirtualDesktop, output: Output): void;
|
||||
raiseWindow(window: KWinWindow): void;
|
||||
readonly windowAdded: Signal<[window: KWinWindow]>;
|
||||
readonly windowRemoved: Signal<[window: KWinWindow]>;
|
||||
/** `null` when no window has the focus. */
|
||||
readonly windowActivated: Signal<[window: KWinWindow | null]>;
|
||||
/** Some output shows another desktop. It does not say which, and the bridge does not need
|
||||
* what KWin passes with it: it reads the desktop of every output. */
|
||||
readonly currentDesktopChanged: Signal;
|
||||
/** A desktop was created or removed. */
|
||||
readonly desktopsChanged: Signal;
|
||||
}
|
||||
|
||||
declare const workspace: Workspace;
|
||||
|
||||
@@ -0,0 +1,425 @@
|
||||
//! KWin's configuration file, `kwinrc`, for the setting komorebi changes: per-output virtual
|
||||
//! desktops.
|
||||
//!
|
||||
//! These are the user's settings, changed on their behalf, so [`Kwinrc::set`] records the value of
|
||||
//! every key the first time komorebi changes it, in a backup file, and [`Kwinrc::restore`] puts the
|
||||
//! values back when komorebi exits. The backup outlives a crash: the next run finds it, keeps the
|
||||
//! values it recorded (not the ones the crashed run wrote), and restores them at the end of that
|
||||
//! run. The KWin backend keeps the backup in [`DATA_DIR`](struct@crate::DATA_DIR), which is under
|
||||
//! `$XDG_RUNTIME_DIR` when there is one: such a directory is emptied at logout, so a backup a crash
|
||||
//! left behind lasts until the session ends.
|
||||
//!
|
||||
//! KDE's tools (`kreadconfig6`, `kwriteconfig6`) are not used. The daemon runs as a user service
|
||||
//! whose PATH need not have them: in a live Plasma 6.8.1 session, at time of writing (2026-10-27),
|
||||
//! `kwriteconfig6` was not on that PATH, and per-output desktops stayed off. The file is plain ini,
|
||||
//! which KConfig reads back, and a setting that silently was not changed is worse than one changed
|
||||
//! by editing a file.
|
||||
//!
|
||||
//! # What is guaranteed, and by what
|
||||
//!
|
||||
//! | Rule | Enforced by | Proof |
|
||||
//! |---|---|---|
|
||||
//! | A key komorebi changed gets back the value it had before komorebi first changed it, and a key komorebi added is removed | [`Kwinrc::set`] records only the first value of a key; [`Kwinrc::restore`] | `kwin::kwinrc::tests::what_komorebi_changed_is_put_back_exactly_and_what_it_added_is_removed` |
|
||||
//! | A crash loses none of the recorded values | the backup file, read by the next run | `kwin::kwinrc::tests::a_backup_left_by_a_crash_keeps_the_values_from_before_the_first_run` |
|
||||
//! | Only the line of the key changes; the rest of the file is left as it was | [`ini_set`], [`ini_unset`] | `kwin::kwinrc::tests::a_key_is_set_in_place_added_to_its_group_or_given_a_group`, `kwin::kwinrc::tests::a_key_is_removed_from_its_own_group_only` |
|
||||
//! | KWin never reads a half-written file | [`Kwinrc`] writes a file beside `kwinrc` and renames it over it | no test |
|
||||
|
||||
#![deny(missing_docs)]
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use std::collections::BTreeMap;
|
||||
use std::io;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// The value of each key before komorebi changed it, by group and key: `None` for a key that was
|
||||
/// not in the user's file.
|
||||
type Originals = BTreeMap<String, BTreeMap<String, Option<String>>>;
|
||||
|
||||
/// A `kwinrc` file that komorebi changes, and the backup of the values it changed.
|
||||
pub struct Kwinrc {
|
||||
/// The `kwinrc` that is read and written.
|
||||
path: PathBuf,
|
||||
/// The JSON file the original values are kept in.
|
||||
backup: PathBuf,
|
||||
}
|
||||
|
||||
/// The contents of the backup file.
|
||||
#[derive(Serialize, Deserialize, Default)]
|
||||
struct Backup {
|
||||
/// The value of every key komorebi changed, before it first changed it.
|
||||
originals: Originals,
|
||||
}
|
||||
|
||||
impl Kwinrc {
|
||||
/// Returns a `kwinrc` at `path`, with its backup at `backup`. Neither file has to exist.
|
||||
pub fn new(path: PathBuf, backup: PathBuf) -> Self {
|
||||
Self { path, backup }
|
||||
}
|
||||
|
||||
/// Returns the user's `kwinrc`, with the backup as `kwinrc-backup.json` in `data_dir`.
|
||||
///
|
||||
/// The user's `kwinrc` is in `$XDG_CONFIG_HOME`, or in `~/.config` when that is not set.
|
||||
/// Returns `None` when neither can be found.
|
||||
pub fn user(data_dir: &std::path::Path) -> Option<Self> {
|
||||
let config = std::env::var_os("XDG_CONFIG_HOME")
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| dirs::home_dir().map(|home| home.join(".config")))?;
|
||||
|
||||
Some(Self::new(
|
||||
config.join("kwinrc"),
|
||||
data_dir.join("kwinrc-backup.json"),
|
||||
))
|
||||
}
|
||||
|
||||
/// Returns the value of `key` in `[group]`, read the way KConfig cascades: from the user's file
|
||||
/// if it has the key, else from the first `kwinrc` in `$XDG_CONFIG_DIRS` (`/etc/xdg` when that
|
||||
/// is not set) that has it.
|
||||
pub fn get(&self, group: &str, key: &str) -> Option<String> {
|
||||
let system = std::env::var("XDG_CONFIG_DIRS").unwrap_or_else(|_| "/etc/xdg".to_string());
|
||||
|
||||
std::iter::once(self.path.clone())
|
||||
.chain(
|
||||
system
|
||||
.split(':')
|
||||
.map(|dir| PathBuf::from(dir).join("kwinrc")),
|
||||
)
|
||||
.filter_map(|file| std::fs::read_to_string(file).ok())
|
||||
.find_map(|text| ini_value(&text, group, key))
|
||||
}
|
||||
|
||||
/// Returns true if and only if the setting is `true`, as [`Kwinrc::get`] reads it.
|
||||
pub fn is_on(&self, group: &str, key: &str) -> bool {
|
||||
self.get(group, key).as_deref() == Some("true")
|
||||
}
|
||||
|
||||
/// Sets keys in a group, recording the value of each in the backup the first time komorebi
|
||||
/// changes it.
|
||||
///
|
||||
/// A key set a second time keeps the value recorded the first time, in this run or in one that
|
||||
/// crashed, so [`Kwinrc::restore`] puts back what the user had.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if the backup or `kwinrc` cannot be written. The backup is written first:
|
||||
/// when it cannot be, `kwinrc` is left as it was.
|
||||
pub fn set(&self, group: &str, pairs: &[(&str, String)]) -> io::Result<()> {
|
||||
let text = std::fs::read_to_string(&self.path).unwrap_or_default();
|
||||
|
||||
let mut backup = self.read_backup();
|
||||
let mut changed = false;
|
||||
for (key, _) in pairs {
|
||||
let originals = backup.originals.entry(group.to_string()).or_default();
|
||||
if !originals.contains_key(*key) {
|
||||
originals.insert((*key).to_string(), ini_value(&text, group, key));
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
self.write_backup(&backup)?;
|
||||
}
|
||||
|
||||
let mut updated = text;
|
||||
for (key, value) in pairs {
|
||||
updated = ini_set(&updated, group, key, value);
|
||||
}
|
||||
self.write_file(&updated)
|
||||
}
|
||||
|
||||
/// Puts back everything [`Kwinrc::set`] changed, removes the backup, and returns true if and
|
||||
/// only if there was anything to put back.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if `kwinrc` cannot be written, or if the backup cannot be removed after
|
||||
/// `kwinrc` was written.
|
||||
pub fn restore(&self) -> io::Result<bool> {
|
||||
let backup = self.read_backup();
|
||||
if backup.originals.is_empty() {
|
||||
let _ = std::fs::remove_file(&self.backup);
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
let mut text = std::fs::read_to_string(&self.path).unwrap_or_default();
|
||||
for (group, keys) in &backup.originals {
|
||||
for (key, original) in keys {
|
||||
text = match original {
|
||||
Some(value) => ini_set(&text, group, key, value),
|
||||
None => ini_unset(&text, group, key),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
self.write_file(&text)?;
|
||||
std::fs::remove_file(&self.backup)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Returns the backup, or an empty one when there is no backup file or it cannot be read.
|
||||
fn read_backup(&self) -> Backup {
|
||||
std::fs::read_to_string(&self.backup)
|
||||
.ok()
|
||||
.and_then(|text| serde_json::from_str(&text).ok())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Writes the backup, creating its directory if needed.
|
||||
fn write_backup(&self, backup: &Backup) -> io::Result<()> {
|
||||
if let Some(dir) = self.backup.parent() {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
}
|
||||
std::fs::write(
|
||||
&self.backup,
|
||||
serde_json::to_string_pretty(backup).map_err(io::Error::other)?,
|
||||
)
|
||||
}
|
||||
|
||||
/// Writes `kwinrc`: the text goes into a file beside it, which is then renamed over it, so that
|
||||
/// KWin never reads half of it.
|
||||
fn write_file(&self, text: &str) -> io::Result<()> {
|
||||
let dir = self.path.parent().map(PathBuf::from).unwrap_or_default();
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
let temporary = dir.join(".kwinrc.komorebi");
|
||||
std::fs::write(&temporary, text)?;
|
||||
std::fs::rename(&temporary, &self.path)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the value of `key` in `[group]` of the ini text, trimmed, or `None` when the group does
|
||||
/// not have the key.
|
||||
///
|
||||
/// Covered by `kwin::kwinrc::tests::a_key_is_read_from_its_own_group_only`.
|
||||
pub fn ini_value(text: &str, group: &str, key: &str) -> Option<String> {
|
||||
let mut in_group = false;
|
||||
for line in text.lines().map(str::trim) {
|
||||
if let Some(name) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
|
||||
in_group = name == group;
|
||||
} else if in_group
|
||||
&& let Some((k, v)) = line.split_once('=')
|
||||
&& k.trim() == key
|
||||
{
|
||||
return Some(v.trim().to_string());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Returns the ini text with `key=value` in `[group]`: the line of the key is replaced if there is
|
||||
/// one, otherwise the line is added at the end of the group, and the group is added at the end of
|
||||
/// the text when there is none.
|
||||
///
|
||||
/// Every other line is left as it was, and the text returned ends with a newline. Covered by
|
||||
/// `kwin::kwinrc::tests::a_key_is_set_in_place_added_to_its_group_or_given_a_group`.
|
||||
pub fn ini_set(text: &str, group: &str, key: &str, value: &str) -> String {
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
let mut in_group = false;
|
||||
let mut done = false;
|
||||
|
||||
let flush = |out: &mut Vec<String>, done: &mut bool, in_group: bool| {
|
||||
// leaving the group without having found the key: it goes at the end of the group
|
||||
if in_group && !*done {
|
||||
let mut at = out.len();
|
||||
while at > 0 && out[at - 1].trim().is_empty() {
|
||||
at -= 1;
|
||||
}
|
||||
out.insert(at, format!("{key}={value}"));
|
||||
*done = true;
|
||||
}
|
||||
};
|
||||
|
||||
for line in text.lines() {
|
||||
let trimmed = line.trim();
|
||||
if let Some(name) = trimmed.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
|
||||
flush(&mut out, &mut done, in_group);
|
||||
in_group = name == group;
|
||||
out.push(line.to_string());
|
||||
} else if in_group
|
||||
&& !done
|
||||
&& let Some((k, _)) = trimmed.split_once('=')
|
||||
&& k.trim() == key
|
||||
{
|
||||
out.push(format!("{key}={value}"));
|
||||
done = true;
|
||||
} else {
|
||||
out.push(line.to_string());
|
||||
}
|
||||
}
|
||||
flush(&mut out, &mut done, in_group);
|
||||
|
||||
if !done {
|
||||
if out.last().is_some_and(|l| !l.trim().is_empty()) {
|
||||
out.push(String::new());
|
||||
}
|
||||
out.push(format!("[{group}]"));
|
||||
out.push(format!("{key}={value}"));
|
||||
}
|
||||
|
||||
let mut joined = out.join("\n");
|
||||
joined.push('\n');
|
||||
joined
|
||||
}
|
||||
|
||||
/// Returns the ini text without `key` in `[group]`.
|
||||
///
|
||||
/// A group left empty stays in place, which KConfig accepts. Every other line is left as it was.
|
||||
/// Covered by `kwin::kwinrc::tests::a_key_is_removed_from_its_own_group_only`.
|
||||
pub fn ini_unset(text: &str, group: &str, key: &str) -> String {
|
||||
let mut in_group = false;
|
||||
let mut out: Vec<&str> = Vec::new();
|
||||
|
||||
for line in text.lines() {
|
||||
let trimmed = line.trim();
|
||||
if let Some(name) = trimmed.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
|
||||
in_group = name == group;
|
||||
} else if in_group
|
||||
&& let Some((k, _)) = trimmed.split_once('=')
|
||||
&& k.trim() == key
|
||||
{
|
||||
continue;
|
||||
}
|
||||
out.push(line);
|
||||
}
|
||||
|
||||
let mut joined = out.join("\n");
|
||||
if text.ends_with('\n') || !joined.is_empty() {
|
||||
joined.push('\n');
|
||||
}
|
||||
joined
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn dir(name: &str) -> PathBuf {
|
||||
let dir = PathBuf::from(format!(
|
||||
"/tmp/komorebi-kwinrc-{}-{name}",
|
||||
std::process::id()
|
||||
));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_key_is_read_from_its_own_group_only() {
|
||||
let rc = "[General]\nK=true\n\n[Windows]\nFocusPolicy=1\nK = false \n\n[Other]\nK=true\n";
|
||||
assert_eq!(ini_value(rc, "Windows", "K").as_deref(), Some("false"));
|
||||
assert_eq!(ini_value(rc, "Windows", "Missing"), None);
|
||||
assert_eq!(ini_value(rc, "Nowhere", "FocusPolicy"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_key_is_set_in_place_added_to_its_group_or_given_a_group() {
|
||||
assert_eq!(
|
||||
ini_set(
|
||||
"[A]\nx=1\n\n[Windows]\nFocusPolicy=1\nK=old\n\n[B]\ny=2\n",
|
||||
"Windows",
|
||||
"K",
|
||||
"new"
|
||||
),
|
||||
"[A]\nx=1\n\n[Windows]\nFocusPolicy=1\nK=new\n\n[B]\ny=2\n"
|
||||
);
|
||||
assert_eq!(
|
||||
ini_set(
|
||||
"[Windows]\nFocusPolicy=1\n\n[B]\ny=2\n",
|
||||
"Windows",
|
||||
"K",
|
||||
"v"
|
||||
),
|
||||
"[Windows]\nFocusPolicy=1\nK=v\n\n[B]\ny=2\n"
|
||||
);
|
||||
assert_eq!(
|
||||
ini_set("[A]\nx=1\n\n[Windows]\nFocusPolicy=1", "Windows", "K", "v"),
|
||||
"[A]\nx=1\n\n[Windows]\nFocusPolicy=1\nK=v\n"
|
||||
);
|
||||
assert_eq!(
|
||||
ini_set("[A]\nx=1\n", "Windows", "K", "v"),
|
||||
"[A]\nx=1\n\n[Windows]\nK=v\n"
|
||||
);
|
||||
assert_eq!(ini_set("", "Windows", "K", "v"), "[Windows]\nK=v\n");
|
||||
assert_eq!(
|
||||
ini_set("[Other]\nK=1\n", "Windows", "K", "v"),
|
||||
"[Other]\nK=1\n\n[Windows]\nK=v\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_key_is_removed_from_its_own_group_only() {
|
||||
assert_eq!(
|
||||
ini_unset("[A]\nK=1\n[Windows]\nK=2\nJ=3\n", "Windows", "K"),
|
||||
"[A]\nK=1\n[Windows]\nJ=3\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_komorebi_changed_is_put_back_exactly_and_what_it_added_is_removed() {
|
||||
let d = dir("backup");
|
||||
let rc = Kwinrc::new(d.join("kwinrc"), d.join("backup.json"));
|
||||
let original = "[Windows]\nFocusPolicy=1\nShade=true\n\n[Round-Corners]\nSize=8\n";
|
||||
std::fs::write(d.join("kwinrc"), original).unwrap();
|
||||
|
||||
rc.set(
|
||||
"Round-Corners",
|
||||
&[
|
||||
("Size", "20".into()),
|
||||
("OuterOutlineThickness", "10".into()),
|
||||
],
|
||||
)
|
||||
.unwrap();
|
||||
rc.set("Windows", &[("PerOutputVirtualDesktops", "true".into())])
|
||||
.unwrap();
|
||||
// a second change to a key already changed must not overwrite what it was before komorebi
|
||||
rc.set("Round-Corners", &[("Size", "30".into())]).unwrap();
|
||||
|
||||
let changed = std::fs::read_to_string(d.join("kwinrc")).unwrap();
|
||||
assert_eq!(
|
||||
ini_value(&changed, "Round-Corners", "Size").as_deref(),
|
||||
Some("30")
|
||||
);
|
||||
assert!(rc.is_on("Windows", "PerOutputVirtualDesktops"));
|
||||
|
||||
assert!(rc.restore().unwrap());
|
||||
let back = std::fs::read_to_string(d.join("kwinrc")).unwrap();
|
||||
assert_eq!(
|
||||
ini_value(&back, "Round-Corners", "Size").as_deref(),
|
||||
Some("8")
|
||||
);
|
||||
assert_eq!(
|
||||
ini_value(&back, "Round-Corners", "OuterOutlineThickness"),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
ini_value(&back, "Windows", "PerOutputVirtualDesktops"),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
ini_value(&back, "Windows", "FocusPolicy").as_deref(),
|
||||
Some("1")
|
||||
);
|
||||
assert!(!d.join("backup.json").exists());
|
||||
|
||||
// nothing left to restore
|
||||
assert!(!rc.restore().unwrap());
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_backup_left_by_a_crash_keeps_the_values_from_before_the_first_run() {
|
||||
let d = dir("crash");
|
||||
let first = Kwinrc::new(d.join("kwinrc"), d.join("backup.json"));
|
||||
std::fs::write(d.join("kwinrc"), "[Windows]\nK=orig\n").unwrap();
|
||||
first.set("Windows", &[("K", "komorebi".into())]).unwrap();
|
||||
|
||||
// the daemon dies; the next one starts with the changed file and the backup
|
||||
let second = Kwinrc::new(d.join("kwinrc"), d.join("backup.json"));
|
||||
second
|
||||
.set("Windows", &[("K", "komorebi again".into())])
|
||||
.unwrap();
|
||||
second.restore().unwrap();
|
||||
|
||||
let back = std::fs::read_to_string(d.join("kwinrc")).unwrap();
|
||||
assert_eq!(ini_value(&back, "Windows", "K").as_deref(), Some("orig"));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
}
|
||||
+227
-2
@@ -34,11 +34,23 @@
|
||||
//! owner again, the daemon loads the script into the new KWin, which reports its desktop as it
|
||||
//! does at start.
|
||||
//!
|
||||
//! Workspaces are KWin's own virtual desktops, per output: workspace `i` is desktop `i`, and each
|
||||
//! output shows a desktop of its own, which KWin does once its per-output virtual desktops are
|
||||
//! turned on. [`connect`] turns them on in the user's `kwinrc` (the exit puts the user's setting
|
||||
//! back), desktops are created over KWin's `org.kde.KWin.VirtualDesktopManager` interface when a
|
||||
//! workspace has none, and the script switches an output's desktop and puts a window on a desktop.
|
||||
//! 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.
|
||||
//!
|
||||
//! [`WorkspaceChange`]: crate::window_manager_event::WindowManagerEvent::WorkspaceChange
|
||||
//! [`WorkspaceMove`]: crate::window_manager_event::WindowManagerEvent::WorkspaceMove
|
||||
//!
|
||||
//! `docs/dev/PLATFORM.md` has the D-Bus names, the files and the environment variables involved,
|
||||
//! and `docs/dev/DESIGN.md` the reasons for this design.
|
||||
|
||||
#![deny(missing_docs)]
|
||||
|
||||
mod kwinrc;
|
||||
pub mod state;
|
||||
|
||||
use crate::DATA_DIR;
|
||||
@@ -54,6 +66,7 @@ use parking_lot::Condvar;
|
||||
use parking_lot::Mutex;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
use state::NeedsDesktops;
|
||||
use state::Output;
|
||||
use state::Table;
|
||||
use std::collections::HashMap;
|
||||
@@ -68,6 +81,7 @@ use tokio::runtime::Handle;
|
||||
use tokio::sync::Notify;
|
||||
use zbus::Connection;
|
||||
use zbus::interface;
|
||||
use zbus::proxy::CacheProperties;
|
||||
use zbus::proxy::Proxy;
|
||||
|
||||
const SERVICE: &str = "org.komorebi.Bridge";
|
||||
@@ -104,6 +118,8 @@ struct Shared {
|
||||
/// runtime is then being shut down, and blocking on it panics
|
||||
alive: AtomicBool,
|
||||
connection: Mutex<Option<Connection>>,
|
||||
/// the user's `kwinrc`, for the settings komorebi changes and puts back
|
||||
kwinrc: Option<kwinrc::Kwinrc>,
|
||||
}
|
||||
|
||||
impl Shared {
|
||||
@@ -252,6 +268,12 @@ pub struct KWinBackend {
|
||||
/// daemon exits or the session bus goes away. The same thread watches KWin on the bus, and loads
|
||||
/// the script again into a KWin that has restarted.
|
||||
///
|
||||
/// Before it loads the script, it turns on KWin's per-output virtual desktops in the user's
|
||||
/// `kwinrc` (`[Windows] PerOutputVirtualDesktops`), unless they are on, and has KWin reload its
|
||||
/// configuration. [`Backend::shutdown`] puts the user's setting back. A `kwinrc` that cannot be
|
||||
/// written is logged, and komorebi runs on: with more than one monitor, a workspace switch then
|
||||
/// switches every monitor.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// - The session bus cannot be reached (`DBUS_SESSION_BUS_ADDRESS` is not set, or names a bus
|
||||
@@ -295,6 +317,7 @@ pub fn connect() -> eyre::Result<Arc<KWinBackend>> {
|
||||
handle: runtime.handle().clone(),
|
||||
alive: AtomicBool::new(true),
|
||||
connection: Mutex::new(None),
|
||||
kwinrc: kwinrc::Kwinrc::user(&DATA_DIR),
|
||||
});
|
||||
|
||||
let (started_tx, started_rx) = std::sync::mpsc::channel::<eyre::Result<()>>();
|
||||
@@ -366,9 +389,52 @@ async fn start(shared: Arc<Shared>) -> eyre::Result<()> {
|
||||
})?;
|
||||
|
||||
*shared.connection.lock() = Some(connection.clone());
|
||||
enable_per_output_desktops(&shared, &connection).await;
|
||||
load_script(&connection).await
|
||||
}
|
||||
|
||||
async fn kwin_reconfigure(connection: &Connection) {
|
||||
let result = async {
|
||||
let kwin = Proxy::new(connection, "org.kde.KWin", "/KWin", "org.kde.KWin").await?;
|
||||
kwin.call_method("reconfigure", &()).await?;
|
||||
eyre::Ok(())
|
||||
}
|
||||
.await;
|
||||
if let Err(error) = result {
|
||||
tracing::warn!("could not ask KWin to reload its configuration: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Turn on KWin's per-output virtual desktops, which is how every monitor gets a workspace of its
|
||||
/// own: without them, switching the desktop switches it on every output. The user's setting is put
|
||||
/// back when komorebi exits (see [`kwinrc::Kwinrc`]).
|
||||
async fn enable_per_output_desktops(shared: &Shared, connection: &Connection) {
|
||||
let Some(kwinrc) = &shared.kwinrc else {
|
||||
tracing::warn!("there is no configuration directory to find kwinrc in");
|
||||
return;
|
||||
};
|
||||
|
||||
if kwinrc.is_on("Windows", "PerOutputVirtualDesktops") {
|
||||
return;
|
||||
}
|
||||
|
||||
if let Err(error) = kwinrc.set(
|
||||
"Windows",
|
||||
&[("PerOutputVirtualDesktops", "true".to_string())],
|
||||
) {
|
||||
tracing::warn!(
|
||||
"could not turn on per-output virtual desktops ({error}): with more than one monitor, \
|
||||
switching workspace will switch them all"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
kwin_reconfigure(connection).await;
|
||||
// the setting is applied as KWin reloads; the script reads the desktops right after
|
||||
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||
tracing::info!("turned on KWin's per-output virtual desktops");
|
||||
}
|
||||
|
||||
/// Write the bridge to disk, where KWin can read it, and have KWin run it
|
||||
async fn load_script(connection: &Connection) -> eyre::Result<()> {
|
||||
let cfg = json!({
|
||||
@@ -460,6 +526,62 @@ async fn supervise(shared: Arc<Shared>) {
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
Ok(zbus::proxy::Builder::new(&connection)
|
||||
.destination("org.kde.KWin")?
|
||||
.path("/VirtualDesktopManager")?
|
||||
.interface("org.kde.KWin.VirtualDesktopManager")?
|
||||
.cache_properties(CacheProperties::No)
|
||||
.build()
|
||||
.await?)
|
||||
}
|
||||
|
||||
/// `(position, id, name)`; kwin's introspection says `a(iss)` but the value on the wire is `a(uss)`
|
||||
async fn desktops(manager: &Proxy<'static>) -> eyre::Result<Vec<(u32, String, String)>> {
|
||||
Ok(manager.get_property("desktops").await?)
|
||||
}
|
||||
|
||||
/// "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 {
|
||||
["Desktop ", "Workspace "].iter().any(|prefix| {
|
||||
name.strip_prefix(prefix)
|
||||
.is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
|
||||
})
|
||||
}
|
||||
|
||||
/// Make sure there are desktops for these workspaces, naming the ones that are created. Existing
|
||||
/// desktops keep their names, if they are somebody's: they may be the user's.
|
||||
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();
|
||||
|
||||
for (position, name) in names.iter().enumerate().skip(have) {
|
||||
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) {
|
||||
if is_placeholder(name) && !is_placeholder(wanted) {
|
||||
manager
|
||||
.call_method("setDesktopName", &(id.as_str(), wanted.as_str()))
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
|
||||
let after = desktops(&manager).await?;
|
||||
shared
|
||||
.table
|
||||
.lock()
|
||||
.set_desktops(after.into_iter().map(|(_, id, name)| (id, name)).collect());
|
||||
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?;
|
||||
@@ -481,6 +603,12 @@ fn command_rect(uuid: &str, rect: &Rect) -> Value {
|
||||
}
|
||||
|
||||
impl KWinBackend {
|
||||
/// A workspace was asked for that has no desktop: make desktops up to it
|
||||
fn make_desktops(&self, count: usize) -> eyre::Result<()> {
|
||||
let names: Vec<String> = (1..=count).map(|n| format!("Workspace {n}")).collect();
|
||||
self.ensure_workspaces(&names)
|
||||
}
|
||||
|
||||
fn command(&self, id: u32, build: impl FnOnce(&str) -> Value) -> eyre::Result<()> {
|
||||
let uuid = self
|
||||
.shared
|
||||
@@ -562,6 +690,51 @@ impl Backend for KWinBackend {
|
||||
self.command(id, |uuid| json!({ "op": "raise", "id": uuid }))
|
||||
}
|
||||
|
||||
fn ensure_workspaces(&self, names: &[String]) -> eyre::Result<()> {
|
||||
let shared = self.shared.clone();
|
||||
let names = names.to_vec();
|
||||
self.shared
|
||||
.block_on(async move { create_workspace_desktops(&shared, &names).await })?
|
||||
}
|
||||
|
||||
fn switch_workspace(&self, monitor_id: u32, idx: usize) -> eyre::Result<()> {
|
||||
let commands = loop {
|
||||
let attempt = self.shared.table.lock().switch_commands(monitor_id, idx);
|
||||
match attempt {
|
||||
Ok(commands) => break commands,
|
||||
Err(NeedsDesktops(count)) => self.make_desktops(count)?,
|
||||
}
|
||||
};
|
||||
|
||||
for command in commands {
|
||||
self.shared.push(command);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_window_workspace(&self, id: u32, idx: usize) -> eyre::Result<()> {
|
||||
let commands = loop {
|
||||
let attempt = self.shared.table.lock().window_workspace_commands(id, idx);
|
||||
match attempt {
|
||||
Ok(commands) => break commands,
|
||||
Err(NeedsDesktops(count)) => self.make_desktops(count)?,
|
||||
}
|
||||
};
|
||||
|
||||
for command in commands {
|
||||
self.shared.push(command);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn window_workspace(&self, id: u32) -> Option<usize> {
|
||||
self.shared.table.lock().window_workspace(id)
|
||||
}
|
||||
|
||||
fn current_workspaces(&self) -> Vec<(u32, usize)> {
|
||||
self.shared.table.lock().current_workspaces()
|
||||
}
|
||||
|
||||
fn minimize(&self, id: u32) -> eyre::Result<()> {
|
||||
self.command(id, |uuid| json!({ "op": "min", "id": uuid, "v": true }))
|
||||
}
|
||||
@@ -590,7 +763,18 @@ impl Backend for KWinBackend {
|
||||
// the script goes with komorebi: KWin would otherwise keep running it, reporting to nobody
|
||||
let shared = self.shared.clone();
|
||||
|
||||
let _ = self.shared.block_on(async move {
|
||||
let told_kwin = self.shared.block_on(async move {
|
||||
// every setting of KWin's that komorebi changed
|
||||
if let Ok(connection) = shared.connection().await
|
||||
&& let Some(kwinrc) = &shared.kwinrc
|
||||
{
|
||||
match kwinrc.restore() {
|
||||
Ok(true) => kwin_reconfigure(&connection).await,
|
||||
Ok(false) => {}
|
||||
Err(error) => tracing::warn!("could not put kwinrc back as it was: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
if let Ok(connection) = shared.connection().await
|
||||
&& let Ok(scripting) = Proxy::new(
|
||||
&connection,
|
||||
@@ -603,6 +787,16 @@ impl Backend for KWinBackend {
|
||||
let _: Result<bool, _> = scripting.call("unloadScript", &(SCRIPT_NAME,)).await;
|
||||
}
|
||||
});
|
||||
|
||||
// KWin is gone (the session is being torn down, so this is not the way it usually ends):
|
||||
// there is nobody to tell, but what komorebi changed in `kwinrc` is the user's, and a file
|
||||
// can be put back without KWin
|
||||
if told_kwin.is_err()
|
||||
&& let Some(kwinrc) = &self.shared.kwinrc
|
||||
&& let Err(error) = kwinrc.restore()
|
||||
{
|
||||
tracing::warn!("could not put kwinrc back as it was: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -630,6 +824,7 @@ mod tests {
|
||||
handle: runtime.handle().clone(),
|
||||
alive: AtomicBool::new(true),
|
||||
connection: Mutex::new(None),
|
||||
kwinrc: None,
|
||||
});
|
||||
|
||||
(runtime, KWinBackend { shared })
|
||||
@@ -655,7 +850,7 @@ mod tests {
|
||||
serde_json::from_str(include_str!("fixtures/commands.json")).unwrap();
|
||||
|
||||
// what the window manager asks of the backend, batch by batch
|
||||
let asks: [fn(&KWinBackend); 2] = [
|
||||
let asks: [fn(&KWinBackend); 3] = [
|
||||
|backend| {
|
||||
// nothing answers the query here, so the pointer is where the snapshot had it
|
||||
assert_eq!(backend.cursor_pos(), Some((481, 525)));
|
||||
@@ -677,6 +872,14 @@ mod tests {
|
||||
// the terminal has closed, and the table still knows it: the bridge gives it back
|
||||
backend.set_rect(2, &left(960)).unwrap();
|
||||
},
|
||||
|backend| {
|
||||
// the editor goes to the second workspace before the monitor is switched to it
|
||||
let monitor = backend.monitors().unwrap()[0].id;
|
||||
backend.set_window_workspace(1, 1).unwrap();
|
||||
backend.switch_workspace(monitor, 1).unwrap();
|
||||
assert_eq!(backend.window_workspace(1), Some(1));
|
||||
assert_eq!(backend.current_workspaces(), [(monitor, 1)]);
|
||||
},
|
||||
];
|
||||
assert_eq!(asks.len(), commands.len());
|
||||
|
||||
@@ -738,4 +941,26 @@ mod tests {
|
||||
|
||||
assert_eq!(next_poll(&runtime, &backend), json!([]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_desktop_nobody_named_is_a_placeholder() {
|
||||
assert!(is_placeholder("Desktop 1"));
|
||||
assert!(is_placeholder("Desktop 12"));
|
||||
assert!(is_placeholder("Workspace 3"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_somebody_chose_is_not() {
|
||||
for name in [
|
||||
"",
|
||||
"Desktop",
|
||||
"Desktop ",
|
||||
"Desktop 1b",
|
||||
"Mail",
|
||||
"My Desktop 1",
|
||||
"terminal",
|
||||
] {
|
||||
assert!(!is_placeholder(name), "{name:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
+447
-12
@@ -1,11 +1,18 @@
|
||||
//! The daemon's model of the compositor: the windows and monitors KWin reports, kept up to date by
|
||||
//! the events the script in KWin sends, and the window events the window manager gets from them.
|
||||
//! The daemon's model of the compositor: the windows, monitors and virtual desktops KWin reports,
|
||||
//! kept up to date by the events the script in KWin sends, and the window events the window manager
|
||||
//! gets from them.
|
||||
//!
|
||||
//! This is pure: JSON in, [`Output`]s out, no D-Bus and no threads, so everything the bridge
|
||||
//! decides can be tested without a compositor. The script (`bridge.js`) holds no logic: it reports
|
||||
//! what KWin tells it, and every decision about what a report means is made here. The events are
|
||||
//! JSON objects with a `type`, described on [`Table::handle`].
|
||||
//!
|
||||
//! Every virtual desktop is a workspace: workspace `i` is KWin's desktop `i`, and each output
|
||||
//! shows one desktop of its own, because komorebi turns on KWin's per-output virtual desktops. The
|
||||
//! commands that show a workspace and put a window on one are made here too
|
||||
//! ([`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.
|
||||
//!
|
||||
//! # Example
|
||||
//!
|
||||
//! The script's first report is a snapshot of the desktop. A window that opens after it is an
|
||||
@@ -73,6 +80,7 @@ struct Entry {
|
||||
info: WindowInfo,
|
||||
/// What KWin says: a normal window, as opposed to a dialog, splash, panel, popup...
|
||||
kwin_normal: bool,
|
||||
desktops: Vec<String>,
|
||||
closed_at: Option<Instant>,
|
||||
}
|
||||
|
||||
@@ -107,6 +115,12 @@ pub struct Table {
|
||||
monitors: Vec<MonitorInfo>,
|
||||
foreground: Option<u32>,
|
||||
cursor: Option<(i32, i32)>,
|
||||
/// `(id, name)` of every virtual desktop, in KWin's order
|
||||
desktops: Vec<(String, String)>,
|
||||
/// The desktop each output shows, by output name. They are independent (komorebi turns on
|
||||
/// KWin's per-output virtual desktops), which is what lets every monitor have a workspace of
|
||||
/// its own in front.
|
||||
current: HashMap<String, String>,
|
||||
}
|
||||
|
||||
fn rect(v: &Value) -> Rect {
|
||||
@@ -119,6 +133,16 @@ fn rect(v: &Value) -> Rect {
|
||||
}
|
||||
}
|
||||
|
||||
fn strings(v: &Value) -> Vec<String> {
|
||||
v.as_array()
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.filter_map(|s| s.as_str().map(String::from))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// FNV-1a: a monitor's id has to be the same on every run, so no `RandomState`
|
||||
fn stable_id(s: &str) -> u32 {
|
||||
let mut hash: u32 = 0x811c_9dc5;
|
||||
@@ -209,11 +233,110 @@ impl Table {
|
||||
}
|
||||
|
||||
/// Whether komorebi should have anything to do with this window: a normal window, as opposed
|
||||
/// to a dialog, a panel, a popup.
|
||||
/// to a dialog, a panel, a popup. Every desktop is a workspace of komorebi's.
|
||||
fn manageable(&self, entry: &Entry) -> bool {
|
||||
entry.kwin_normal
|
||||
}
|
||||
|
||||
// ---- workspaces ------------------------------------------------------------------------
|
||||
|
||||
/// The ids of the desktops that are workspaces, in order: all of them
|
||||
fn workspace_desktops(&self) -> Vec<&str> {
|
||||
self.desktops.iter().map(|(id, _)| id.as_str()).collect()
|
||||
}
|
||||
|
||||
/// Which workspace a desktop is
|
||||
fn workspace_index(&self, desktop: &str) -> Option<usize> {
|
||||
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.
|
||||
pub fn window_workspace(&self, id: u32) -> Option<usize> {
|
||||
let entry = self.windows.get(&id)?;
|
||||
let desktop = entry.desktops.first()?;
|
||||
self.workspace_index(desktop)
|
||||
}
|
||||
|
||||
/// Returns the workspace each monitor shows, as `(monitor id, workspace index)`
|
||||
pub fn current_workspaces(&self) -> Vec<(u32, usize)> {
|
||||
self.monitors
|
||||
.iter()
|
||||
.filter_map(|m| {
|
||||
let desktop = self.current.get(&m.name)?;
|
||||
Some((m.id, self.workspace_index(desktop)?))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Returns how many workspace desktops there are
|
||||
pub fn workspace_count(&self) -> usize {
|
||||
self.workspace_desktops().len()
|
||||
}
|
||||
|
||||
/// Replaces the list of desktops with what KWin says it is now, for after komorebi created
|
||||
/// some. The list is `(id, name)` pairs, in KWin's order.
|
||||
pub fn set_desktops(&mut self, desktops: Vec<(String, String)>) {
|
||||
self.desktops = desktops;
|
||||
}
|
||||
|
||||
/// Returns the commands that show workspace `idx` on a monitor, and records that the monitor
|
||||
/// shows it, so that KWin's report of the switch is not taken for somebody else's. A monitor
|
||||
/// the table does not know gets no command.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// [`NeedsDesktops`] when there are not that many desktops yet: make them, then ask again.
|
||||
pub fn switch_commands(
|
||||
&mut self,
|
||||
monitor_id: u32,
|
||||
idx: usize,
|
||||
) -> Result<Vec<Value>, NeedsDesktops> {
|
||||
let desktop = self
|
||||
.workspace_desktops()
|
||||
.get(idx)
|
||||
.map(|d| d.to_string())
|
||||
.ok_or(NeedsDesktops(idx + 1))?;
|
||||
|
||||
let Some(monitor) = self.monitors.iter().find(|m| m.id == monitor_id) else {
|
||||
return Ok(vec![]);
|
||||
};
|
||||
|
||||
let output = monitor.name.clone();
|
||||
self.current.insert(output.clone(), desktop.clone());
|
||||
Ok(vec![
|
||||
json!({ "op": "output_desktop", "output": output, "v": desktop }),
|
||||
])
|
||||
}
|
||||
|
||||
/// 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.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// [`NeedsDesktops`] when there are not that many desktops yet: make them, then ask again.
|
||||
pub fn window_workspace_commands(
|
||||
&mut self,
|
||||
id: u32,
|
||||
idx: usize,
|
||||
) -> Result<Vec<Value>, NeedsDesktops> {
|
||||
let desktop = self
|
||||
.workspace_desktops()
|
||||
.get(idx)
|
||||
.map(|d| d.to_string())
|
||||
.ok_or(NeedsDesktops(idx + 1))?;
|
||||
|
||||
let Some(entry) = self.windows.get_mut(&id) else {
|
||||
return Ok(vec![]);
|
||||
};
|
||||
|
||||
entry.desktops = vec![desktop.clone()];
|
||||
Ok(vec![
|
||||
json!({ "op": "desktop", "id": entry.uuid, "v": desktop }),
|
||||
])
|
||||
}
|
||||
|
||||
/// 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,
|
||||
@@ -282,6 +405,7 @@ impl Table {
|
||||
uuid,
|
||||
info,
|
||||
kwin_normal: w["normal"].as_bool().unwrap_or(false),
|
||||
desktops: strings(&w["desktops"]),
|
||||
closed_at: None,
|
||||
};
|
||||
|
||||
@@ -321,9 +445,10 @@ impl Table {
|
||||
///
|
||||
/// The event's `type` is one of:
|
||||
///
|
||||
/// - `snapshot`: everything on the desktop (`windows`, `screens`, `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.
|
||||
/// - `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.
|
||||
/// - `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,
|
||||
@@ -332,6 +457,13 @@ impl Table {
|
||||
/// [`WindowManagerEvent::Restore`]).
|
||||
/// - `caption`: a window's title changed ([`WindowManagerEvent::TitleUpdate`]).
|
||||
/// - `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.
|
||||
/// - `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.
|
||||
/// - `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.
|
||||
///
|
||||
@@ -353,6 +485,12 @@ impl Table {
|
||||
}
|
||||
vec![]
|
||||
}
|
||||
Some("desktops") => self.on_desktops(event),
|
||||
Some("current_desktops") => self.on_current_desktops(event),
|
||||
Some("desktop_list") => {
|
||||
self.desktops = desktop_list(&event["desktops"]);
|
||||
vec![]
|
||||
}
|
||||
Some("cursor") => {
|
||||
let (x, y) = (
|
||||
event["x"].as_i64().unwrap_or(0) as i32,
|
||||
@@ -387,6 +525,10 @@ impl Table {
|
||||
}
|
||||
|
||||
fn on_snapshot(&mut self, event: &Value) -> Vec<Output> {
|
||||
// desktops first: which workspace a window is on depends on them
|
||||
self.desktops = desktop_list(&event["desktops"]);
|
||||
self.current = current_map(&event["current_desktops"]);
|
||||
|
||||
// rebuild the windows, keeping the ids of those we already knew
|
||||
let old = std::mem::take(&mut self.windows);
|
||||
for w in event["windows"].as_array().cloned().unwrap_or_default() {
|
||||
@@ -536,8 +678,112 @@ impl Table {
|
||||
vec![]
|
||||
}
|
||||
}
|
||||
|
||||
fn on_desktops(&mut self, event: &Value) -> Vec<Output> {
|
||||
let Some(id) = self.id_of(event) else {
|
||||
return vec![];
|
||||
};
|
||||
|
||||
let before = self.window_workspace(id);
|
||||
let desktops = strings(&event["desktops"]);
|
||||
|
||||
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.
|
||||
let after = self
|
||||
.windows
|
||||
.get(&id)
|
||||
.filter(|e| e.info.normal && e.info.alive)
|
||||
.and_then(|e| e.desktops.first())
|
||||
.and_then(|d| self.workspace_index(d));
|
||||
|
||||
match after {
|
||||
Some(idx) if before != Some(idx) => {
|
||||
vec![Output::Event(WindowManagerEvent::WorkspaceMove(
|
||||
kwin(KWinNotification::WindowMovedToDesktop),
|
||||
Window::from(id),
|
||||
idx,
|
||||
))]
|
||||
}
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
/// Some output now shows another desktop: komorebi's request, or a pager, a shortcut, an app
|
||||
/// raising a window (KWin switches that output to the window's desktop)
|
||||
fn on_current_desktops(&mut self, event: &Value) -> Vec<Output> {
|
||||
let now = current_map(&event["current"]);
|
||||
let mut out = vec![];
|
||||
|
||||
let mut changes: Vec<(String, String)> = now
|
||||
.iter()
|
||||
.filter(|(output, desktop)| self.current.get(*output) != Some(*desktop))
|
||||
.map(|(o, d)| (o.clone(), d.clone()))
|
||||
.collect();
|
||||
changes.sort();
|
||||
|
||||
for (output, desktop) in changes {
|
||||
self.current.insert(output.clone(), desktop.clone());
|
||||
|
||||
let (Some(idx), Some(monitor)) = (
|
||||
self.workspace_index(&desktop),
|
||||
self.monitors.iter().find(|m| m.name == output),
|
||||
) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
out.push(Output::Event(WindowManagerEvent::WorkspaceChange(
|
||||
kwin(KWinNotification::WorkspaceChanged),
|
||||
monitor.id,
|
||||
idx,
|
||||
)));
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
fn desktop_list(v: &Value) -> Vec<(String, String)> {
|
||||
v.as_array()
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.filter_map(|d| {
|
||||
Some((
|
||||
d["id"].as_str()?.to_string(),
|
||||
d["name"].as_str()?.to_string(),
|
||||
))
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn current_map(v: &Value) -> HashMap<String, String> {
|
||||
v.as_array()
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.filter_map(|d| {
|
||||
Some((
|
||||
d["output"].as_str()?.to_string(),
|
||||
d["id"].as_str()?.to_string(),
|
||||
))
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The error of a request for a workspace that has no desktop yet: at least this many desktops
|
||||
/// are needed.
|
||||
///
|
||||
/// [`Table::switch_commands`] and [`Table::window_workspace_commands`] return it; the KWin backend
|
||||
/// makes the desktops and asks again.
|
||||
#[derive(Debug)]
|
||||
pub struct NeedsDesktops(pub usize);
|
||||
|
||||
/// The executable of a process, by name and by path.
|
||||
///
|
||||
/// Rules match on these (`Exe` is the basename, `Path` the full path), as they do on Windows.
|
||||
@@ -582,6 +828,8 @@ mod tests {
|
||||
"geo": { "x": 0, "y": 0, "w": 1920, "h": 1080 },
|
||||
"area": { "x": 0, "y": 0, "w": 1920, "h": 1050 },
|
||||
}],
|
||||
"desktops": [{ "id": "d1", "name": "Desktop 1" }, { "id": "d2", "name": "Desktop 2" }],
|
||||
"current_desktops": [{ "output": "DP-1", "id": "d1" }],
|
||||
"active": null,
|
||||
"cursor": { "x": 5, "y": 6 },
|
||||
})
|
||||
@@ -614,18 +862,33 @@ mod tests {
|
||||
let mut trace = vec![];
|
||||
for event in &session {
|
||||
let out = t.handle(event, now);
|
||||
let mut said = events(&out);
|
||||
for output in &out {
|
||||
if let Output::Cursor { token, x, y } = output {
|
||||
said.push(format!("Cursor {token} at {x},{y}"));
|
||||
}
|
||||
}
|
||||
let said: Vec<String> = out
|
||||
.iter()
|
||||
.map(|output| match output {
|
||||
Output::Event(WindowManagerEvent::WorkspaceMove(_, window, idx)) => {
|
||||
format!("WorkspaceMove {} to {idx}", window.id)
|
||||
}
|
||||
Output::Event(WindowManagerEvent::WorkspaceChange(_, _, idx)) => {
|
||||
format!("WorkspaceChange to {idx}")
|
||||
}
|
||||
Output::Event(e) => format!("{e} {}", e.window_id().unwrap_or(0)),
|
||||
Output::Cursor { token, x, y } => format!("Cursor {token} at {x},{y}"),
|
||||
})
|
||||
.collect();
|
||||
trace.push(format!(
|
||||
"{} -> {}",
|
||||
event["type"].as_str().unwrap(),
|
||||
said.join(", ")
|
||||
));
|
||||
|
||||
// what komorebi asks for next (fixtures/commands.json, batch 3): the editor on the
|
||||
// second workspace, and the output showing it
|
||||
if event["seq"] == 15 {
|
||||
let monitor = t.monitors()[0].id;
|
||||
t.window_workspace_commands(1, 1).unwrap();
|
||||
t.switch_commands(monitor, 1).unwrap();
|
||||
}
|
||||
|
||||
if event["type"] == "added" && event["caption"] == "a terminal" {
|
||||
let w = t.window(2).unwrap();
|
||||
assert_eq!(
|
||||
@@ -664,6 +927,13 @@ mod tests {
|
||||
"minimized -> Restore 1",
|
||||
"removed -> ",
|
||||
"failed -> ",
|
||||
// komorebi's own move and switch, coming back
|
||||
"desktops -> ",
|
||||
"current_desktops -> ",
|
||||
// somebody else's: a new desktop, the editor moved back, the first one shown
|
||||
"desktop_list -> ",
|
||||
"desktops -> WorkspaceMove 1 to 0",
|
||||
"current_desktops -> WorkspaceChange to 0",
|
||||
]
|
||||
);
|
||||
|
||||
@@ -676,6 +946,9 @@ mod tests {
|
||||
assert_eq!(t.window(2).unwrap().rect.bottom, 532, "the geometry event");
|
||||
assert_eq!(t.foreground(), Some(1));
|
||||
assert_eq!(t.cursor(), Some((1200, 701)));
|
||||
assert_eq!(t.workspace_count(), 3);
|
||||
assert_eq!(t.window_workspace(1), Some(0));
|
||||
assert_eq!(t.current_workspaces(), [(t.monitors()[0].id, 0)]);
|
||||
|
||||
let monitor = &t.monitors()[0];
|
||||
assert_eq!(
|
||||
@@ -714,6 +987,7 @@ mod tests {
|
||||
}
|
||||
);
|
||||
assert_eq!(t.cursor(), Some((5, 6)));
|
||||
assert_eq!(t.current_workspaces(), vec![(t.monitors()[0].id, 0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -892,6 +1166,167 @@ mod tests {
|
||||
assert_eq!(t.window(1).unwrap().title, "renamed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_desktop_is_a_workspace_and_a_window_is_on_the_one_it_is_on() {
|
||||
let t = table(vec![
|
||||
win("first", &["d1"]),
|
||||
win("second", &["d2"]),
|
||||
win("everywhere", &[]),
|
||||
]);
|
||||
|
||||
assert_eq!(
|
||||
t.windows().len(),
|
||||
3,
|
||||
"windows on any desktop are komorebi's"
|
||||
);
|
||||
assert_eq!(t.window_workspace(1), Some(0));
|
||||
assert_eq!(t.window_workspace(2), Some(1));
|
||||
assert_eq!(
|
||||
t.window_workspace(3),
|
||||
None,
|
||||
"a window on every desktop is on none"
|
||||
);
|
||||
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"])]);
|
||||
let now = Instant::now();
|
||||
|
||||
let out = t.handle(
|
||||
&json!({ "type": "desktops", "id": "a", "desktops": ["d2"] }),
|
||||
now,
|
||||
);
|
||||
assert!(
|
||||
matches!(
|
||||
&out[..],
|
||||
[Output::Event(WindowManagerEvent::WorkspaceMove(_, _, 1))]
|
||||
),
|
||||
"{out:?}"
|
||||
);
|
||||
assert_eq!(t.window_workspace(1), Some(1));
|
||||
assert!(t.window(1).unwrap().normal);
|
||||
|
||||
// the same again is nothing new
|
||||
let out = t.handle(
|
||||
&json!({ "type": "desktops", "id": "a", "desktops": ["d2"] }),
|
||||
now,
|
||||
);
|
||||
assert!(out.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn komorebis_own_move_coming_back_from_kwin_raises_nothing() {
|
||||
let mut t = table(vec![win("a", &["d1"])]);
|
||||
|
||||
// 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(),
|
||||
);
|
||||
|
||||
assert!(out.is_empty(), "{out:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_is_put_on_a_workspace_by_putting_it_on_its_desktop() {
|
||||
let mut t = table(vec![win("a", &["d1"])]);
|
||||
|
||||
assert_eq!(
|
||||
t.window_workspace_commands(1, 1).unwrap(),
|
||||
vec![json!({ "op": "desktop", "id": "a", "v": "d2" })]
|
||||
);
|
||||
assert_eq!(
|
||||
t.window_workspace(1),
|
||||
Some(1),
|
||||
"visible to the next query at once"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn showing_a_workspace_switches_that_output_only() {
|
||||
let mut t = table(vec![]);
|
||||
let monitor = t.monitors()[0].id;
|
||||
|
||||
assert_eq!(
|
||||
t.switch_commands(monitor, 1).unwrap(),
|
||||
vec![json!({ "op": "output_desktop", "output": "DP-1", "v": "d2" })]
|
||||
);
|
||||
assert_eq!(t.current_workspaces(), vec![(monitor, 1)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_workspace_without_a_desktop_asks_for_one() {
|
||||
let mut t = table(vec![win("a", &["d1"])]);
|
||||
let monitor = t.monitors()[0].id;
|
||||
|
||||
assert!(matches!(
|
||||
t.switch_commands(monitor, 4),
|
||||
Err(NeedsDesktops(5))
|
||||
));
|
||||
assert!(matches!(
|
||||
t.window_workspace_commands(1, 2),
|
||||
Err(NeedsDesktops(3))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_party_switching_a_monitor_is_a_workspace_change() {
|
||||
let mut t = table(vec![]);
|
||||
let monitor = t.monitors()[0].id;
|
||||
|
||||
let out = t.handle(
|
||||
&json!({ "type": "current_desktops", "current": [{ "output": "DP-1", "id": "d2" }] }),
|
||||
Instant::now(),
|
||||
);
|
||||
assert!(
|
||||
matches!(&out[..], [Output::Event(WindowManagerEvent::WorkspaceChange(_, m, 1))] if *m == monitor),
|
||||
"{out:?}"
|
||||
);
|
||||
|
||||
// the same again says nothing
|
||||
let out = t.handle(
|
||||
&json!({ "type": "current_desktops", "current": [{ "output": "DP-1", "id": "d2" }] }),
|
||||
Instant::now(),
|
||||
);
|
||||
assert!(out.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn komorebi_switching_a_monitor_comes_back_as_a_change_to_what_it_already_knows() {
|
||||
let mut t = table(vec![]);
|
||||
let monitor = t.monitors()[0].id;
|
||||
t.switch_commands(monitor, 1).unwrap();
|
||||
|
||||
// the table already believes it, so KWin's report of it raises nothing a second time
|
||||
let out = t.handle(
|
||||
&json!({ "type": "current_desktops", "current": [{ "output": "DP-1", "id": "d2" }] }),
|
||||
Instant::now(),
|
||||
);
|
||||
assert!(out.is_empty(), "{out:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_list_of_desktops_is_read_and_raises_nothing() {
|
||||
let mut t = table(vec![win("a", &["d3"])]);
|
||||
assert_eq!(t.window_workspace(1), None, "d3 is not a desktop yet");
|
||||
|
||||
let out = t.handle(
|
||||
&json!({ "type": "desktop_list", "desktops": [
|
||||
{ "id": "d1", "name": "Desktop 1" },
|
||||
{ "id": "d2", "name": "Desktop 2" },
|
||||
{ "id": "d3", "name": "mail" },
|
||||
] }),
|
||||
Instant::now(),
|
||||
);
|
||||
|
||||
assert!(out.is_empty(), "{out:?}");
|
||||
assert_eq!(t.workspace_count(), 3);
|
||||
assert_eq!(t.window_workspace(1), Some(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cursor_query_answer_is_passed_on_and_remembered() {
|
||||
let mut t = table(vec![]);
|
||||
|
||||
@@ -5,11 +5,19 @@
|
||||
//! one. Before the focused workspace is tiled it is given the monitor's work area, the monitor's
|
||||
//! padding (or [`DEFAULT_CONTAINER_PADDING`] and [`DEFAULT_WORKSPACE_PADDING`]) and the work area
|
||||
//! offset ([`WorkspaceGlobals`]).
|
||||
//!
|
||||
//! Workspace `i` of a monitor is the compositor's virtual desktop `i` on that monitor. Showing
|
||||
//! another workspace ([`Monitor::load_focused_workspace`]) puts every window on the desktop of the
|
||||
//! workspace it is in, asks the compositor to show the focused workspace's desktop, which shows its
|
||||
//! windows and hides the others, and gives the focus to the workspace's focused window.
|
||||
|
||||
use crate::DEFAULT_CONTAINER_PADDING;
|
||||
use crate::DEFAULT_WORKSPACE_PADDING;
|
||||
use crate::backend::backend;
|
||||
use crate::container::Container;
|
||||
use crate::core::DefaultLayout;
|
||||
use crate::core::Layout;
|
||||
use crate::core::OperationDirection;
|
||||
use crate::core::Rect;
|
||||
use crate::ring::Ring;
|
||||
use crate::workspace::Workspace;
|
||||
@@ -174,10 +182,207 @@ impl Monitor {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Make this monitor show its focused workspace.
|
||||
///
|
||||
/// The workspaces are the compositor's virtual desktops, so this is a request to switch the
|
||||
/// desktop this monitor shows, and the compositor shows the windows on it and hides the rest.
|
||||
/// What is left for komorebi is to tile the windows that came into view.
|
||||
pub fn load_focused_workspace(&mut self, mouse_follows_focus: bool) -> eyre::Result<()> {
|
||||
let focused_idx = self.focused_workspace_idx();
|
||||
let monitor_id = self.id;
|
||||
|
||||
// a window moved to this workspace has to be on its desktop before the desktop is shown
|
||||
// and a window of it focused, or focusing it would take the monitor back to the desktop it
|
||||
// was on
|
||||
self.assign_windows_to_workspaces();
|
||||
|
||||
if let Err(error) = backend().switch_workspace(monitor_id, focused_idx) {
|
||||
tracing::warn!("could not show workspace {focused_idx}: {error}");
|
||||
}
|
||||
|
||||
if let Some(workspace) = self.workspaces_mut().get_mut(focused_idx) {
|
||||
workspace.restore(mouse_follows_focus)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Put every window of every workspace of this monitor on that workspace's desktop, unless it
|
||||
/// already is. komorebi decides which workspace a window belongs to (a window sent to another
|
||||
/// workspace, a new window, a rule); this is how the compositor learns of it.
|
||||
pub fn assign_windows_to_workspaces(&self) {
|
||||
for (idx, workspace) in self.workspaces().iter().enumerate() {
|
||||
let windows = workspace
|
||||
.containers()
|
||||
.iter()
|
||||
.flat_map(|c| c.windows().iter())
|
||||
.chain(workspace.floating_windows().iter());
|
||||
|
||||
for window in windows {
|
||||
if backend().window_workspace(window.id) != Some(idx)
|
||||
&& let Err(error) = backend().set_window_workspace(window.id, idx)
|
||||
{
|
||||
tracing::debug!(
|
||||
"could not put window {} on workspace {idx}: {error}",
|
||||
window.id
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn new_workspace_idx(&self) -> usize {
|
||||
self.workspaces().len()
|
||||
}
|
||||
|
||||
/// Moves the focused container of the focused workspace, or the focused window when it is a
|
||||
/// floating one, to the back of workspace `target_workspace_idx`, creating the workspace (and
|
||||
/// the ones before it) if it does not exist, and focuses that workspace when `follow` is set.
|
||||
///
|
||||
/// With a `direction`, the container goes where a container moved across a boundary in that
|
||||
/// direction goes ([`Monitor::add_container_with_direction`]).
|
||||
#[tracing::instrument(skip(self))]
|
||||
pub fn move_container_to_workspace(
|
||||
&mut self,
|
||||
target_workspace_idx: usize,
|
||||
follow: bool,
|
||||
direction: Option<OperationDirection>,
|
||||
) -> eyre::Result<()> {
|
||||
let workspace = self
|
||||
.focused_workspace_mut()
|
||||
.ok_or_eyre("there is no workspace")?;
|
||||
|
||||
let foreground_hwnd = if !cfg!(test) {
|
||||
backend()
|
||||
.foreground_window()
|
||||
.ok_or_eyre("no foreground window")?
|
||||
} else {
|
||||
0
|
||||
};
|
||||
|
||||
let floating_window_index = workspace
|
||||
.floating_windows()
|
||||
.iter()
|
||||
.position(|w| w.id == foreground_hwnd);
|
||||
|
||||
if let Some(idx) = floating_window_index {
|
||||
if let Some(window) = workspace.floating_windows_mut().remove(idx) {
|
||||
let workspaces = self.workspaces_mut();
|
||||
#[allow(clippy::option_if_let_else)]
|
||||
let target_workspace = match workspaces.get_mut(target_workspace_idx) {
|
||||
None => {
|
||||
workspaces.resize(target_workspace_idx + 1, Workspace::default());
|
||||
workspaces.get_mut(target_workspace_idx).unwrap()
|
||||
}
|
||||
Some(workspace) => workspace,
|
||||
};
|
||||
|
||||
target_workspace.floating_windows_mut().push_back(window);
|
||||
}
|
||||
} else {
|
||||
let container = workspace
|
||||
.remove_focused_container()
|
||||
.ok_or_eyre("there is no container")?;
|
||||
|
||||
let workspaces = self.workspaces_mut();
|
||||
|
||||
#[allow(clippy::option_if_let_else)]
|
||||
let target_workspace = match workspaces.get_mut(target_workspace_idx) {
|
||||
None => {
|
||||
workspaces.resize(target_workspace_idx + 1, Workspace::default());
|
||||
workspaces.get_mut(target_workspace_idx).unwrap()
|
||||
}
|
||||
Some(workspace) => workspace,
|
||||
};
|
||||
|
||||
if let Some(direction) = direction {
|
||||
self.add_container_with_direction(
|
||||
container,
|
||||
Some(target_workspace_idx),
|
||||
direction,
|
||||
)?;
|
||||
} else {
|
||||
target_workspace.add_container_to_back(container);
|
||||
}
|
||||
}
|
||||
|
||||
if follow {
|
||||
self.focus_workspace(target_workspace_idx)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Adds a container to this `Monitor` using the move direction to calculate if the container
|
||||
/// should be added in front of all containers, in the back or in place of the focused
|
||||
/// container, moving the rest along. The move direction should be from the origin monitor
|
||||
/// towards the target monitor or from the origin workspace towards the target workspace.
|
||||
pub fn add_container_with_direction(
|
||||
&mut self,
|
||||
container: Container,
|
||||
workspace_idx: Option<usize>,
|
||||
direction: OperationDirection,
|
||||
) -> eyre::Result<()> {
|
||||
let workspace = if let Some(idx) = workspace_idx {
|
||||
self.workspaces_mut()
|
||||
.get_mut(idx)
|
||||
.ok_or_eyre(format!("there is no workspace at index {}", idx))?
|
||||
} else {
|
||||
self.focused_workspace_mut()
|
||||
.ok_or_eyre("there is no workspace")?
|
||||
};
|
||||
|
||||
match direction {
|
||||
OperationDirection::Left => {
|
||||
// insert the container into the workspace on the monitor at the back (or rightmost position)
|
||||
// if we are moving across a boundary to the left (back = right side of the target)
|
||||
match workspace.layout {
|
||||
Layout::Default(layout) => match layout {
|
||||
DefaultLayout::RightMainVerticalStack => {
|
||||
workspace.add_container_to_front(container);
|
||||
}
|
||||
DefaultLayout::UltrawideVerticalStack
|
||||
if workspace.containers().len() == 1 =>
|
||||
{
|
||||
workspace.insert_container_at_idx(0, container);
|
||||
}
|
||||
_ => {
|
||||
workspace.add_container_to_back(container);
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
OperationDirection::Right => {
|
||||
// insert the container into the workspace on the monitor at the front (or leftmost position)
|
||||
// if we are moving across a boundary to the right (front = left side of the target)
|
||||
match workspace.layout {
|
||||
Layout::Default(layout) => {
|
||||
let target_index = layout.leftmost_index(workspace.containers().len());
|
||||
|
||||
match layout {
|
||||
DefaultLayout::RightMainVerticalStack
|
||||
| DefaultLayout::UltrawideVerticalStack
|
||||
if workspace.containers().len() == 1 =>
|
||||
{
|
||||
workspace.add_container_to_back(container);
|
||||
}
|
||||
_ => {
|
||||
workspace.insert_container_at_idx(target_index, container);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
OperationDirection::Up | OperationDirection::Down => {
|
||||
// insert the container into the workspace on the monitor at the position
|
||||
// where the currently focused container on that workspace is
|
||||
workspace.insert_container_at_idx(workspace.focused_container_idx(), container);
|
||||
}
|
||||
};
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn remove_workspace_by_idx(&mut self, idx: usize) -> Option<Workspace> {
|
||||
if idx < self.workspaces().len() {
|
||||
return self.workspaces_mut().remove(idx);
|
||||
@@ -380,6 +585,106 @@ mod tests {
|
||||
assert_eq!(new_workspace_index, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_move_container_to_workspace() {
|
||||
let mut m = Monitor::new(
|
||||
0,
|
||||
Rect::default(),
|
||||
Rect::default(),
|
||||
"TestDevice",
|
||||
"TestDeviceId",
|
||||
);
|
||||
|
||||
let new_workspace_index = m.new_workspace_idx();
|
||||
assert_eq!(new_workspace_index, 1);
|
||||
|
||||
{
|
||||
// Create workspace 1 and add 3 containers
|
||||
let workspace = m.focused_workspace_mut().unwrap();
|
||||
for _ in 0..3 {
|
||||
let container = Container::default();
|
||||
workspace.add_container_to_back(container);
|
||||
}
|
||||
|
||||
// Should have 3 containers in workspace 1
|
||||
assert_eq!(m.focused_workspace().unwrap().containers().len(), 3);
|
||||
}
|
||||
|
||||
// Create and focus workspace 2
|
||||
m.focus_workspace(new_workspace_index).unwrap();
|
||||
|
||||
// Focus workspace 1
|
||||
m.focus_workspace(0).unwrap();
|
||||
|
||||
// Move container to workspace 2
|
||||
m.move_container_to_workspace(1, true, None).unwrap();
|
||||
|
||||
// Should be focused on workspace 2
|
||||
assert_eq!(m.focused_workspace_idx(), 1);
|
||||
|
||||
// Workspace 2 should have 1 container now
|
||||
assert_eq!(m.focused_workspace().unwrap().containers().len(), 1);
|
||||
|
||||
// Move to workspace 1
|
||||
m.focus_workspace(0).unwrap();
|
||||
|
||||
// Workspace 1 should have 2 containers
|
||||
assert_eq!(m.focused_workspace().unwrap().containers().len(), 2);
|
||||
|
||||
// Move a another container from workspace 1 to workspace 2 without following
|
||||
m.move_container_to_workspace(1, false, None).unwrap();
|
||||
|
||||
// Should have 1 container
|
||||
assert_eq!(m.focused_workspace().unwrap().containers().len(), 1);
|
||||
|
||||
// Should still be focused on workspace 1
|
||||
assert_eq!(m.focused_workspace_idx(), 0);
|
||||
|
||||
// Switch to workspace 2
|
||||
m.focus_workspace(1).unwrap();
|
||||
|
||||
// Workspace 2 should now have 2 containers
|
||||
assert_eq!(m.focused_workspace().unwrap().containers().len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_move_container_to_nonexistent_workspace() {
|
||||
let mut m = Monitor::new(
|
||||
0,
|
||||
Rect::default(),
|
||||
Rect::default(),
|
||||
"TestDevice",
|
||||
"TestDeviceId",
|
||||
);
|
||||
|
||||
{
|
||||
// Create workspace 1 and add 3 containers
|
||||
let workspace = m.focused_workspace_mut().unwrap();
|
||||
for _ in 0..3 {
|
||||
let container = Container::default();
|
||||
workspace.add_container_to_back(container);
|
||||
}
|
||||
|
||||
// Should have 3 containers in workspace 1
|
||||
assert_eq!(m.focused_workspace().unwrap().containers().len(), 3);
|
||||
}
|
||||
|
||||
// Should only have 1 workspace
|
||||
assert_eq!(m.workspaces().len(), 1);
|
||||
|
||||
// Try to move a container to a workspace that doesn't exist
|
||||
m.move_container_to_workspace(8, true, None).unwrap();
|
||||
|
||||
// Should have 9 workspaces now
|
||||
assert_eq!(m.workspaces().len(), 9);
|
||||
|
||||
// Should be focused on workspace 8
|
||||
assert_eq!(m.focused_workspace_idx(), 8);
|
||||
|
||||
// Should have 1 container in workspace 8
|
||||
assert_eq!(m.focused_workspace().unwrap().containers().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ensure_workspace_count_workspace_contains_two_workspaces() {
|
||||
let mut m = Monitor::new(
|
||||
|
||||
@@ -81,6 +81,12 @@
|
||||
//! [`WindowManager::resize_delta`] that **ResizeDelta** sets ([`WindowManager::resize_window`]),
|
||||
//! and **QuickSave**, **QuickLoad**, **Save** and **Load** write the resize adjustments of the
|
||||
//! focused workspace's containers to a file and read them back.
|
||||
//! - **FocusWorkspaceNumber** shows a workspace of the focused monitor, by its index
|
||||
//! ([`WindowManager::focus_workspace`]): the compositor is asked to show its desktop on that
|
||||
//! monitor. **MoveContainerToWorkspaceNumber** moves the focused container to a workspace and
|
||||
//! shows it, and **SendContainerToWorkspaceNumber** moves it there and stays
|
||||
//! ([`WindowManager::move_container_to_workspace`]). A workspace that does not exist yet is
|
||||
//! made, with the ones before it.
|
||||
//! - **Retile** tiles the focused workspace of every monitor again, without the resize
|
||||
//! adjustments, and **RetileWithResizeDimensions** with them.
|
||||
//! - **AddSubscriberSocket** and **AddSubscriberSocketWithOptions** add a subscriber by the name
|
||||
@@ -202,6 +208,10 @@ 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 monitor has no workspace or no container to move to another workspace, or
|
||||
/// the compositor reports no window with the focus (`MoveContainerToWorkspaceNumber`,
|
||||
/// `SendContainerToWorkspaceNumber`), or the focused window of the workspace that is shown
|
||||
/// cannot be focused.
|
||||
/// - The monitor or the workspace of `WorkspacePadding` or `ContainerPadding` is not there, or
|
||||
/// the focused workspace has no padding of its own for `AdjustWorkspacePadding` or
|
||||
/// `AdjustContainerPadding` to change.
|
||||
@@ -272,6 +282,18 @@ impl WindowManager {
|
||||
SocketMessage::CycleMoveWindow(direction) => {
|
||||
self.move_container_in_cycle_direction(direction)?;
|
||||
}
|
||||
SocketMessage::FocusWorkspaceNumber(workspace_idx) => {
|
||||
if self.focused_workspace_idx().unwrap_or_default() != workspace_idx {
|
||||
self.focus_workspace(workspace_idx)?;
|
||||
}
|
||||
}
|
||||
|
||||
SocketMessage::MoveContainerToWorkspaceNumber(workspace_idx) => {
|
||||
self.move_container_to_workspace(workspace_idx, true, None)?;
|
||||
}
|
||||
SocketMessage::SendContainerToWorkspaceNumber(workspace_idx) => {
|
||||
self.move_container_to_workspace(workspace_idx, false, None)?;
|
||||
}
|
||||
SocketMessage::ToggleFloat => self.toggle_float(false)?,
|
||||
SocketMessage::ResizeWindowEdge(direction, sizing) => {
|
||||
self.resize_window(direction, sizing, self.resize_delta, true)?;
|
||||
@@ -904,6 +926,11 @@ mod tests {
|
||||
use crate::backend::fake::FakeBackend;
|
||||
use crate::backend::with_backend;
|
||||
use crate::core::Rect;
|
||||
use crate::monitor;
|
||||
use crate::window_manager_event::WindowManagerEvent;
|
||||
use crossbeam_channel::Receiver;
|
||||
use crossbeam_channel::Sender;
|
||||
use crossbeam_channel::bounded;
|
||||
use std::io::Read;
|
||||
use std::io::Write;
|
||||
use std::net::Shutdown;
|
||||
@@ -1121,4 +1148,53 @@ mod tests {
|
||||
|
||||
assert!(reply.is_err());
|
||||
}
|
||||
|
||||
fn send_socket_message(socket: &PathBuf, message: SocketMessage) {
|
||||
let mut stream = UnixStream::connect(socket).unwrap();
|
||||
stream
|
||||
.set_write_timeout(Some(Duration::from_secs(1)))
|
||||
.unwrap();
|
||||
stream
|
||||
.write_all(serde_json::to_string(&message).unwrap().as_bytes())
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_receive_socket_message() {
|
||||
let (_sender, receiver): (Sender<WindowManagerEvent>, Receiver<WindowManagerEvent>) =
|
||||
bounded(1);
|
||||
// /tmp: short enough for a unix socket path on macOS, and writable wherever the tests run
|
||||
let socket_name = format!("/tmp/komorebi-test-{}.sock", Uuid::new_v4());
|
||||
let socket_path = PathBuf::from(&socket_name);
|
||||
let mut wm = WindowManager::new(receiver, Some(socket_path.clone())).unwrap();
|
||||
let m = monitor::new(
|
||||
0,
|
||||
Rect::default(),
|
||||
Rect::default(),
|
||||
"TestMonitor".to_string(),
|
||||
"TestDeviceID".to_string(),
|
||||
);
|
||||
|
||||
wm.monitors_mut().push_back(m);
|
||||
|
||||
// send a message
|
||||
send_socket_message(&socket_path, SocketMessage::FocusWorkspaceNumber(5));
|
||||
|
||||
let (stream, _) = wm.command_listener.accept().unwrap();
|
||||
let reader = BufReader::new(stream.try_clone().unwrap());
|
||||
let next = reader.lines().next();
|
||||
|
||||
// read and deserialize the message
|
||||
let message_string = next.unwrap().unwrap();
|
||||
let message = SocketMessage::from_str(&message_string).unwrap();
|
||||
assert!(matches!(message, SocketMessage::FocusWorkspaceNumber(5)));
|
||||
|
||||
// process the message
|
||||
wm.process_command(message, stream).unwrap();
|
||||
|
||||
// check the updated window manager state
|
||||
assert_eq!(wm.focused_workspace_idx().unwrap(), 5);
|
||||
|
||||
std::fs::remove_file(socket_path).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,17 @@
|
||||
//! again; **Restore** brings it back in a container of its own.
|
||||
//! - **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
|
||||
//! switched it (a pager, a shortcut, an app raising a window of another desktop). The window
|
||||
//! manager follows ([`WindowManager::adopt_workspace_change`]) and asks the compositor for
|
||||
//! nothing: it has already shown the windows and chosen which to focus. komorebi's own switch
|
||||
//! comes back as one too, and changes nothing.
|
||||
//! - **WorkspaceMove**: a window was put on the desktop of another workspace by something other
|
||||
//! than komorebi. It moves to that workspace, and whichever of the two is in front is tiled
|
||||
//! again.
|
||||
//!
|
||||
//! A window that is shown or managed is put on the desktop of the workspace it was managed into
|
||||
//! ([`Monitor::assign_windows_to_workspaces`]).
|
||||
//!
|
||||
//! The daemon hands events to the window manager on a thread of their own,
|
||||
//! [`listen_for_events`], one at a time and in the order the backend raised them.
|
||||
@@ -28,6 +39,7 @@
|
||||
//! of it ([`notify_subscribers`]).
|
||||
//!
|
||||
//! [`Window::should_manage`]: crate::window::Window::should_manage
|
||||
//! [`Monitor::assign_windows_to_workspaces`]: crate::monitor::Monitor::assign_windows_to_workspaces
|
||||
|
||||
use crate::FLOATING_APPLICATIONS;
|
||||
use crate::Notification;
|
||||
@@ -107,6 +119,11 @@ impl WindowManager {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// a monitor changed which workspace it shows; nothing to do with any window
|
||||
if let WindowManagerEvent::WorkspaceChange(_, monitor_id, idx) = event {
|
||||
return self.adopt_workspace_change(monitor_id, idx);
|
||||
}
|
||||
|
||||
let Some(window) = event.window() else {
|
||||
return Ok(());
|
||||
};
|
||||
@@ -144,6 +161,7 @@ impl WindowManager {
|
||||
|
||||
match event {
|
||||
WindowManagerEvent::FocusChange(_, _) => {
|
||||
let is_known = self.known_window_ids.get(&window_id).cloned();
|
||||
let mut is_on_current_workspace = false;
|
||||
|
||||
// don't want to trigger the full workspace updates when there are no managed
|
||||
@@ -172,6 +190,38 @@ impl WindowManager {
|
||||
{
|
||||
self.update_focused_workspace(self.mouse_follows_focus, false)?;
|
||||
}
|
||||
|
||||
// A window of another workspace being activated (an app raising itself) makes
|
||||
// KWin switch that monitor to the window's desktop, and tells us in a
|
||||
// `WorkspaceChange`: there is nothing to do about the window until that arrives
|
||||
let _ = (is_known, is_on_current_workspace);
|
||||
}
|
||||
// handled before the window is looked up
|
||||
WindowManagerEvent::WorkspaceChange(..) => {}
|
||||
WindowManagerEvent::WorkspaceMove(_, _, idx) => {
|
||||
// somebody put the window on another workspace's desktop: it belongs there now.
|
||||
// (komorebi's own moves come back here too, and find the window already there.)
|
||||
if let Some((m_idx, w_idx)) = self.known_window_ids.get(&window_id).cloned()
|
||||
&& w_idx != idx
|
||||
{
|
||||
tracing::info!("window {window_id} was moved to workspace {idx}");
|
||||
let offset = self.work_area_offset;
|
||||
|
||||
if let Some(monitor) = self.monitors_mut().get_mut(m_idx) {
|
||||
monitor.ensure_workspace_count(idx + 1);
|
||||
|
||||
if let Some(from) = monitor.workspaces_mut().get_mut(w_idx) {
|
||||
from.remove_window(window_id)?;
|
||||
}
|
||||
|
||||
if let Some(to) = monitor.workspaces_mut().get_mut(idx) {
|
||||
to.new_container_for_window(&window)?;
|
||||
}
|
||||
|
||||
// whichever of the two is showing needs its tiles redone
|
||||
monitor.update_focused_workspace(offset)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
WindowManagerEvent::Show(_, _) | WindowManagerEvent::Manage(_) => {
|
||||
let mut create = true;
|
||||
@@ -335,6 +385,17 @@ impl WindowManager {
|
||||
}
|
||||
}
|
||||
|
||||
// a window that was just managed is on the desktop the compositor opened it on, which is the
|
||||
// one in front where it opened; make sure that is the workspace it was managed into
|
||||
if matches!(
|
||||
event,
|
||||
WindowManagerEvent::Show(_, _) | WindowManagerEvent::Manage(_)
|
||||
) {
|
||||
for monitor in self.monitors() {
|
||||
monitor.assign_windows_to_workspaces();
|
||||
}
|
||||
}
|
||||
|
||||
self.update_known_window_ids();
|
||||
|
||||
notify_subscribers(
|
||||
|
||||
@@ -14,6 +14,12 @@
|
||||
//! [`WindowManager::move_container_in_cycle_direction`]), and stops the daemon when it is asked
|
||||
//! to ([`WindowManager::stop`]).
|
||||
//!
|
||||
//! A monitor's workspaces are the compositor's virtual desktops. The window manager shows one
|
||||
//! ([`WindowManager::focus_workspace`]), moves a container to one
|
||||
//! ([`WindowManager::move_container_to_workspace`]), makes sure the compositor has a desktop for
|
||||
//! each ([`WindowManager::sync_workspace_desktops`]), and follows a workspace switch that
|
||||
//! something else made ([`WindowManager::adopt_workspace_change`]).
|
||||
//!
|
||||
//! [`listen_for_commands`]: crate::process_command::listen_for_commands
|
||||
|
||||
use crate::DATA_DIR;
|
||||
@@ -136,11 +142,13 @@ impl WindowManager {
|
||||
}
|
||||
|
||||
/// Loads the monitors and the windows that are already open from the backend
|
||||
/// ([`desktop`])
|
||||
/// ([`desktop`]), and makes sure the compositor has a desktop for every workspace
|
||||
/// ([`WindowManager::sync_workspace_desktops`])
|
||||
#[tracing::instrument(skip(self))]
|
||||
pub fn init(&mut self) -> Result<(), LibraryError> {
|
||||
tracing::info!("initializing");
|
||||
desktop::load_monitor_information(self)?;
|
||||
self.sync_workspace_desktops();
|
||||
desktop::load_workspace_information(self)?;
|
||||
// the windows that were open already are in containers now; an event about one of them
|
||||
// (the first thing to happen may be that it closes) has to find it
|
||||
@@ -422,6 +430,55 @@ impl WindowManager {
|
||||
std::process::exit(0)
|
||||
}
|
||||
|
||||
/// Shows workspace `idx` on the focused monitor, creating it (and the ones before it) if it
|
||||
/// does not exist yet.
|
||||
///
|
||||
/// The compositor is asked to show the workspace's desktop on that monitor
|
||||
/// ([`Monitor::load_focused_workspace`]): it shows the windows on it and hides the others, and
|
||||
/// komorebi focuses the workspace's focused window and tiles it.
|
||||
#[tracing::instrument(skip(self))]
|
||||
pub fn focus_workspace(&mut self, idx: usize) -> eyre::Result<()> {
|
||||
tracing::info!("focusing workspace");
|
||||
|
||||
let mouse_follows_focus = self.mouse_follows_focus;
|
||||
let monitor = self
|
||||
.focused_monitor_mut()
|
||||
.ok_or_eyre("there is no workspace")?;
|
||||
|
||||
monitor.focus_workspace(idx)?;
|
||||
monitor.load_focused_workspace(mouse_follows_focus)?;
|
||||
|
||||
self.update_focused_workspace(false, true)
|
||||
}
|
||||
|
||||
/// Moves the focused container of the focused monitor to workspace `idx`, creating it if it
|
||||
/// does not exist yet, and shows that workspace when `follow` is set.
|
||||
///
|
||||
/// The container's windows are put on the workspace's desktop before the desktop is shown or
|
||||
/// one of them is focused ([`Monitor::load_focused_workspace`]): a window that is focused while
|
||||
/// it is still on the desktop it came from takes the monitor back to that desktop.
|
||||
#[tracing::instrument(skip(self))]
|
||||
pub fn move_container_to_workspace(
|
||||
&mut self,
|
||||
idx: usize,
|
||||
follow: bool,
|
||||
direction: Option<OperationDirection>,
|
||||
) -> eyre::Result<()> {
|
||||
tracing::info!("moving container");
|
||||
|
||||
let mouse_follows_focus = self.mouse_follows_focus;
|
||||
let monitor = self
|
||||
.focused_monitor_mut()
|
||||
.ok_or_eyre("there is no monitor")?;
|
||||
|
||||
monitor.move_container_to_workspace(idx, follow, direction)?;
|
||||
monitor.load_focused_workspace(mouse_follows_focus)?;
|
||||
|
||||
self.update_focused_workspace(mouse_follows_focus, true)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Takes the window that has the focus in the compositor out of the layout of the focused
|
||||
/// workspace, or puts it back when it is one of its floating windows and `force_float` is not
|
||||
/// set, and tiles the workspace again
|
||||
@@ -990,6 +1047,48 @@ impl WindowManager {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Make sure the compositor has a virtual desktop for every workspace any monitor has, named
|
||||
/// "Workspace 1", "Workspace 2" and so on where it has to create them
|
||||
pub fn sync_workspace_desktops(&self) {
|
||||
let count = self
|
||||
.monitors()
|
||||
.iter()
|
||||
.map(|m| m.workspaces().len())
|
||||
.max()
|
||||
.unwrap_or(1)
|
||||
.max(1);
|
||||
|
||||
let names: Vec<String> = (0..count).map(|i| format!("Workspace {}", i + 1)).collect();
|
||||
|
||||
if let Err(error) = backend().ensure_workspaces(&names) {
|
||||
tracing::warn!("could not make sure there are desktops for the workspaces: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A monitor now shows workspace `idx`, which komorebi did not ask for: a pager, a shortcut, an
|
||||
/// app raising a window of another desktop. The compositor has already shown the windows and
|
||||
/// chosen what to focus; komorebi follows, and tiles what came into view.
|
||||
pub fn adopt_workspace_change(&mut self, monitor_id: u32, idx: usize) -> eyre::Result<()> {
|
||||
let offset = self.work_area_offset;
|
||||
|
||||
let Some(monitor) = self.monitors_mut().iter_mut().find(|m| m.id == monitor_id) else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
if monitor.focused_workspace_idx() == idx {
|
||||
// komorebi's own switch, coming back
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
tracing::info!("the compositor now shows workspace {idx} on monitor {monitor_id}");
|
||||
monitor.focus_workspace(idx)?;
|
||||
monitor.update_focused_workspace(offset)?;
|
||||
|
||||
self.update_known_window_ids();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn update_known_window_ids(&mut self) {
|
||||
tracing::trace!("updating list of known window_ids");
|
||||
let mut known_window_ids = HashMap::new();
|
||||
@@ -1223,6 +1322,50 @@ mod tests {
|
||||
let (_wm, _test_context) = setup_window_manager();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_focus_workspace() {
|
||||
let (mut wm, _test_context) = setup_window_manager();
|
||||
|
||||
let m = monitor::new(
|
||||
0,
|
||||
Rect::default(),
|
||||
Rect::default(),
|
||||
"TestMonitor".to_string(),
|
||||
"TestDeviceID".to_string(),
|
||||
);
|
||||
|
||||
// a new monitor should have a single workspace
|
||||
assert_eq!(m.workspaces().len(), 1);
|
||||
|
||||
// the next index on the monitor should be the not-yet-created second workspace
|
||||
let new_workspace_index = m.new_workspace_idx();
|
||||
assert_eq!(new_workspace_index, 1);
|
||||
|
||||
// add the monitor to the window manager
|
||||
wm.monitors_mut().push_back(m);
|
||||
|
||||
{
|
||||
// focusing a workspace which doesn't yet exist should create it
|
||||
let monitor = wm.focused_monitor_mut().unwrap();
|
||||
monitor.focus_workspace(new_workspace_index).unwrap();
|
||||
assert_eq!(monitor.workspaces().len(), 2);
|
||||
}
|
||||
assert_eq!(wm.focused_workspace_idx().unwrap(), 1);
|
||||
|
||||
{
|
||||
// focusing a workspace many indices ahead should create all workspaces
|
||||
// required along the way
|
||||
let monitor = wm.focused_monitor_mut().unwrap();
|
||||
monitor.focus_workspace(new_workspace_index + 2).unwrap();
|
||||
assert_eq!(monitor.workspaces().len(), 4);
|
||||
}
|
||||
assert_eq!(wm.focused_workspace_idx().unwrap(), 3);
|
||||
|
||||
// we should be able to successfully focus an existing workspace too
|
||||
wm.focus_workspace(0).unwrap();
|
||||
assert_eq!(wm.focused_workspace_idx().unwrap(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_focus_container_in_cycle_direction() {
|
||||
let (mut wm, _test_context) = setup_window_manager();
|
||||
|
||||
@@ -2,11 +2,12 @@
|
||||
//! window manager handles it
|
||||
//! ([`WindowManager::process_event`](crate::window_manager::WindowManager::process_event)).
|
||||
//!
|
||||
//! An event is about one window and carries it, and the compositor signal it came from
|
||||
//! ([`SystemNotification`]), which is only for logging. Two events come from komorebi itself
|
||||
//! rather than from the compositor: [`WindowManagerEvent::Manage`] and
|
||||
//! [`WindowManagerEvent::Unmanage`], which the commands that manage and unmanage the focused window
|
||||
//! raise.
|
||||
//! An event carries the compositor signal it came from ([`SystemNotification`]), which is only for
|
||||
//! logging. Every event but one is about a window, and carries it: a
|
||||
//! [`WindowManagerEvent::WorkspaceChange`] is about a monitor that shows another workspace. Two
|
||||
//! events come from komorebi itself rather than from the compositor:
|
||||
//! [`WindowManagerEvent::Manage`] and [`WindowManagerEvent::Unmanage`], which the commands that
|
||||
//! manage and unmanage the focused window raise.
|
||||
|
||||
use crate::window::Window;
|
||||
use serde::Deserialize;
|
||||
@@ -32,6 +33,10 @@ pub enum KWinNotification {
|
||||
WindowRemoved,
|
||||
/// `workspace.windowActivated`
|
||||
WindowActivated,
|
||||
/// `workspace.currentDesktopChanged`: a monitor now shows another desktop
|
||||
WorkspaceChanged,
|
||||
/// `window.desktopsChanged`: a window is on another desktop
|
||||
WindowMovedToDesktop,
|
||||
/// `window.minimizedChanged` to true
|
||||
WindowMinimized,
|
||||
/// `window.minimizedChanged` to false
|
||||
@@ -48,7 +53,7 @@ pub enum ManualNotification {
|
||||
Unmanage,
|
||||
}
|
||||
|
||||
/// Window events: each carries the window it is about.
|
||||
/// Window events: each carries the window it is about, but for a workspace change.
|
||||
#[derive(Debug, Copy, Clone, Serialize, Deserialize, Display)]
|
||||
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
|
||||
#[serde(tag = "type", content = "content")]
|
||||
@@ -64,6 +69,12 @@ pub enum WindowManagerEvent {
|
||||
Manage(Window),
|
||||
/// The user asked komorebi to stop managing the window (`UnmanageFocusedWindow`)
|
||||
Unmanage(Window),
|
||||
/// A monitor (by id) now shows another workspace: komorebi did that itself, or a pager, a
|
||||
/// shortcut or an app raising a window did. Not about any one window.
|
||||
WorkspaceChange(SystemNotification, u32, usize),
|
||||
/// A window was put on another workspace's desktop by something other than komorebi (the
|
||||
/// window menu's "Move to Desktop", a drag in the pager)
|
||||
WorkspaceMove(SystemNotification, Window, usize),
|
||||
}
|
||||
|
||||
impl WindowManagerEvent {
|
||||
@@ -77,7 +88,9 @@ impl WindowManagerEvent {
|
||||
| WindowManagerEvent::Restore(_, window)
|
||||
| WindowManagerEvent::TitleUpdate(_, window)
|
||||
| WindowManagerEvent::Manage(window)
|
||||
| WindowManagerEvent::Unmanage(window) => *window,
|
||||
| WindowManagerEvent::Unmanage(window)
|
||||
| WindowManagerEvent::WorkspaceMove(_, window, _) => *window,
|
||||
WindowManagerEvent::WorkspaceChange(..) => return None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -97,7 +110,9 @@ impl WindowManagerEvent {
|
||||
| WindowManagerEvent::Destroy(n, _)
|
||||
| WindowManagerEvent::Minimize(n, _)
|
||||
| WindowManagerEvent::Restore(n, _)
|
||||
| WindowManagerEvent::TitleUpdate(n, _) => match n {
|
||||
| WindowManagerEvent::TitleUpdate(n, _)
|
||||
| WindowManagerEvent::WorkspaceChange(n, _, _)
|
||||
| WindowManagerEvent::WorkspaceMove(n, _, _) => match n {
|
||||
SystemNotification::KWin(k) => k.to_string(),
|
||||
SystemNotification::Manual(m) => m.to_string(),
|
||||
},
|
||||
@@ -125,4 +140,17 @@ mod tests {
|
||||
assert_eq!(event.notification(), "WindowMinimized");
|
||||
assert_eq!(event.to_string(), "Minimize");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_workspace_change_is_about_a_monitor_and_no_window() {
|
||||
let event = WindowManagerEvent::WorkspaceChange(
|
||||
SystemNotification::KWin(KWinNotification::WorkspaceChanged),
|
||||
7,
|
||||
2,
|
||||
);
|
||||
|
||||
assert_eq!(event.window(), None);
|
||||
assert_eq!(event.window_id(), None);
|
||||
assert_eq!(event.notification(), "WorkspaceChanged");
|
||||
}
|
||||
}
|
||||
@@ -388,6 +388,36 @@ impl Workspace {
|
||||
false
|
||||
}
|
||||
|
||||
/// 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.
|
||||
pub fn restore(&mut self, mouse_follows_focus: bool) -> eyre::Result<()> {
|
||||
let idx = self.focused_container_idx();
|
||||
let mut to_focus = None;
|
||||
|
||||
for (i, container) in self.containers().iter().enumerate() {
|
||||
if let Some(window) = container.focused_window()
|
||||
&& idx == i
|
||||
{
|
||||
to_focus = Option::from(*window);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(container) = self.focused_container_mut() {
|
||||
container.focus_window(container.focused_window_idx());
|
||||
}
|
||||
|
||||
if let Some(window) = to_focus {
|
||||
window.focus(mouse_follows_focus)?;
|
||||
} else if let Some(floating_window) = self.focused_floating_window() {
|
||||
floating_window.focus(mouse_follows_focus)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn remove_focused_container(&mut self) -> Option<Container> {
|
||||
let focused_idx = self.focused_container_idx();
|
||||
let container = self.remove_container_by_idx(focused_idx);
|
||||
|
||||
@@ -0,0 +1,361 @@
|
||||
//! Workspaces as the compositor's virtual desktops, against an in-memory desktop.
|
||||
//!
|
||||
//! Workspace `i` is the compositor's desktop `i` on each monitor. komorebi asks the compositor to
|
||||
//! 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.
|
||||
|
||||
use komorebi::backend::fake::Command;
|
||||
use komorebi::backend::fake::FakeBackend;
|
||||
use komorebi::backend::with_backend;
|
||||
use komorebi::core::SocketMessage;
|
||||
use komorebi::window::Window;
|
||||
use komorebi::window_manager::WindowManager;
|
||||
use komorebi::window_manager_event::KWinNotification;
|
||||
use komorebi::window_manager_event::SystemNotification;
|
||||
use komorebi::window_manager_event::WindowManagerEvent;
|
||||
use std::sync::Arc;
|
||||
|
||||
fn added(id: u32) -> WindowManagerEvent {
|
||||
WindowManagerEvent::Show(
|
||||
SystemNotification::KWin(KWinNotification::WindowAdded),
|
||||
Window::from(id),
|
||||
)
|
||||
}
|
||||
|
||||
fn removed(id: u32) -> WindowManagerEvent {
|
||||
WindowManagerEvent::Destroy(
|
||||
SystemNotification::KWin(KWinNotification::WindowRemoved),
|
||||
Window::from(id),
|
||||
)
|
||||
}
|
||||
|
||||
/// A window manager over a fake desktop with one 1920x1080 monitor (1920x1050 without the panel)
|
||||
fn desktop() -> (Arc<FakeBackend>, WindowManager) {
|
||||
desktop_on(FakeBackend::with_one_monitor())
|
||||
}
|
||||
|
||||
fn desktop_on(fake: FakeBackend) -> (Arc<FakeBackend>, WindowManager) {
|
||||
let fake = Arc::new(fake);
|
||||
let (_sender, receiver) = crossbeam_channel::bounded(1);
|
||||
// unix socket paths are limited to ~104 bytes on macOS, which the temp dir alone can exceed
|
||||
static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
|
||||
let socket = std::path::PathBuf::from(format!(
|
||||
"/tmp/kmb-{}-{}.sock",
|
||||
std::process::id(),
|
||||
NEXT.fetch_add(1, std::sync::atomic::Ordering::SeqCst)
|
||||
));
|
||||
|
||||
let wm = with_backend(fake.clone(), || {
|
||||
let mut wm = WindowManager::new(receiver, Some(socket)).unwrap();
|
||||
wm.init().unwrap();
|
||||
wm
|
||||
});
|
||||
|
||||
(fake, wm)
|
||||
}
|
||||
|
||||
fn open(fake: &FakeBackend, id: u32) {
|
||||
fake.open_window(id, "foot", "foot", &format!("terminal {id}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_destroyed_window_is_removed_from_a_workspace_that_is_not_in_front() {
|
||||
let (fake, mut wm) = desktop();
|
||||
open(&fake, 10_031);
|
||||
open(&fake, 10_032);
|
||||
|
||||
with_backend(fake.clone(), || {
|
||||
wm.process_event(added(10_031))?;
|
||||
wm.process_event(added(10_032))?;
|
||||
// send the focused window (10_032) to workspace 1 and stay on workspace 0
|
||||
wm.process_command(SocketMessage::SendContainerToWorkspaceNumber(1), Vec::new())?;
|
||||
assert!(wm.known_window_ids.contains_key(&10_032));
|
||||
|
||||
fake.close_window_now(10_032);
|
||||
wm.process_event(removed(10_032))
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
assert!(!wm.known_window_ids.contains_key(&10_032));
|
||||
assert!(wm.known_window_ids.contains_key(&10_031));
|
||||
}
|
||||
|
||||
fn activated(id: u32) -> WindowManagerEvent {
|
||||
WindowManagerEvent::FocusChange(
|
||||
SystemNotification::KWin(KWinNotification::WindowActivated),
|
||||
Window::from(id),
|
||||
)
|
||||
}
|
||||
|
||||
fn workspace_changed(monitor_id: u32, idx: usize) -> WindowManagerEvent {
|
||||
WindowManagerEvent::WorkspaceChange(
|
||||
SystemNotification::KWin(KWinNotification::WorkspaceChanged),
|
||||
monitor_id,
|
||||
idx,
|
||||
)
|
||||
}
|
||||
|
||||
const MONITOR: u32 = 1;
|
||||
|
||||
#[test]
|
||||
fn switching_workspace_asks_the_compositor_to_show_the_other_desktop() {
|
||||
let (fake, mut wm) = desktop();
|
||||
open(&fake, 10_061);
|
||||
open(&fake, 10_062);
|
||||
|
||||
with_backend(fake.clone(), || {
|
||||
wm.process_event(added(10_061))?;
|
||||
wm.process_event(added(10_062))?;
|
||||
wm.process_command(SocketMessage::SendContainerToWorkspaceNumber(1), Vec::new())?;
|
||||
fake.clear_commands();
|
||||
wm.process_command(SocketMessage::FocusWorkspaceNumber(1), Vec::new())
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(fake.shown_workspace(MONITOR), 1);
|
||||
assert!(
|
||||
fake.commands()
|
||||
.iter()
|
||||
.any(|c| matches!(c, Command::SwitchWorkspace(MONITOR, 1))),
|
||||
"{:?}",
|
||||
fake.commands()
|
||||
);
|
||||
// the compositor shows the windows of the workspace in front and not the others; komorebi
|
||||
// hides nothing
|
||||
assert!(
|
||||
fake.on_screen(10_062),
|
||||
"the window on workspace 1 is not shown"
|
||||
);
|
||||
assert!(
|
||||
!fake.on_screen(10_061),
|
||||
"the window on workspace 0 is still shown"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_sent_to_another_workspace_is_put_on_that_desktop() {
|
||||
let (fake, mut wm) = desktop();
|
||||
open(&fake, 10_071);
|
||||
open(&fake, 10_072);
|
||||
|
||||
with_backend(fake.clone(), || {
|
||||
wm.process_event(added(10_071))?;
|
||||
wm.process_event(added(10_072))?;
|
||||
wm.process_command(SocketMessage::SendContainerToWorkspaceNumber(1), Vec::new())
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(fake.workspace_of(10_071), Some(0));
|
||||
assert_eq!(fake.workspace_of(10_072), Some(1));
|
||||
assert_eq!(
|
||||
wm.focused_workspace_idx().unwrap(),
|
||||
0,
|
||||
"send does not follow"
|
||||
);
|
||||
assert!(!fake.on_screen(10_072));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_a_window_to_another_workspace_puts_it_on_the_desktop_before_showing_it() {
|
||||
// focusing a window that is not yet on the desktop being shown would take the monitor back
|
||||
let (fake, mut wm) = desktop();
|
||||
open(&fake, 10_081);
|
||||
open(&fake, 10_082);
|
||||
|
||||
with_backend(fake.clone(), || {
|
||||
wm.process_event(added(10_081))?;
|
||||
wm.process_event(added(10_082))?;
|
||||
fake.clear_commands();
|
||||
wm.process_command(SocketMessage::MoveContainerToWorkspaceNumber(1), Vec::new())
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let commands = fake.commands();
|
||||
let assigned = commands
|
||||
.iter()
|
||||
.position(|c| matches!(c, Command::SetWindowWorkspace(10_082, 1)))
|
||||
.expect("the window was never put on workspace 1's desktop");
|
||||
let switched = commands
|
||||
.iter()
|
||||
.position(|c| matches!(c, Command::SwitchWorkspace(MONITOR, 1)))
|
||||
.expect("the monitor was never switched");
|
||||
let focused = commands
|
||||
.iter()
|
||||
.position(|c| matches!(c, Command::Focus(10_082, _)))
|
||||
.expect("the moved window was never focused");
|
||||
|
||||
assert!(assigned < switched, "{commands:?}");
|
||||
assert!(assigned < focused, "{commands:?}");
|
||||
assert_eq!(wm.focused_workspace_idx().unwrap(), 1);
|
||||
assert!(fake.on_screen(10_082));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_workspace_switch_by_someone_else_is_followed_not_undone() {
|
||||
let (fake, mut wm) = desktop();
|
||||
open(&fake, 10_091);
|
||||
open(&fake, 10_092);
|
||||
|
||||
with_backend(fake.clone(), || {
|
||||
wm.process_event(added(10_091))?;
|
||||
wm.process_event(added(10_092))?;
|
||||
wm.process_command(SocketMessage::SendContainerToWorkspaceNumber(1), Vec::new())
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
// a pager, a shortcut, or an app raising a window of workspace 1: the compositor shows it
|
||||
fake.show_workspace_by_user(MONITOR, 1);
|
||||
fake.clear_commands();
|
||||
with_backend(fake.clone(), || {
|
||||
wm.process_event(workspace_changed(MONITOR, 1))
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
wm.focused_workspace_idx().unwrap(),
|
||||
1,
|
||||
"komorebi did not follow"
|
||||
);
|
||||
assert!(
|
||||
!fake
|
||||
.commands()
|
||||
.iter()
|
||||
.any(|c| matches!(c, Command::SwitchWorkspace(..))),
|
||||
"komorebi asked for a switch in reply to one: {:?}",
|
||||
fake.commands()
|
||||
);
|
||||
assert_eq!(fake.shown_workspace(MONITOR), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_compositor_reporting_komorebis_own_switch_changes_nothing() {
|
||||
let (fake, mut wm) = desktop();
|
||||
open(&fake, 10_101);
|
||||
|
||||
with_backend(fake.clone(), || {
|
||||
wm.process_event(added(10_101))?;
|
||||
wm.process_command(SocketMessage::FocusWorkspaceNumber(1), Vec::new())?;
|
||||
fake.clear_commands();
|
||||
wm.process_event(workspace_changed(MONITOR, 1))
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(wm.focused_workspace_idx().unwrap(), 1);
|
||||
assert!(fake.commands().is_empty(), "{:?}", fake.commands());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_open_on_a_desktop_at_startup_starts_on_that_workspace() {
|
||||
let fake = FakeBackend::with_one_monitor();
|
||||
fake.open_window(10_111, "foot", "foot", "terminal 10111");
|
||||
fake.open_window(10_112, "foot", "foot", "terminal 10112");
|
||||
// the user had put one on the second desktop, and was looking at the first
|
||||
fake.show_workspace_by_user(MONITOR, 0);
|
||||
{
|
||||
use komorebi::backend::Backend;
|
||||
fake.set_window_workspace(10_112, 1).unwrap();
|
||||
fake.clear_commands();
|
||||
}
|
||||
let (_fake, wm) = desktop_on(fake);
|
||||
|
||||
let workspaces = wm.focused_monitor().unwrap().workspaces();
|
||||
let ids = |idx: usize| -> Vec<u32> {
|
||||
workspaces
|
||||
.get(idx)
|
||||
.map(|w| {
|
||||
w.containers()
|
||||
.iter()
|
||||
.flat_map(|c| c.windows().iter().map(|w| w.id))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
};
|
||||
assert_eq!(ids(0), [10_111]);
|
||||
assert_eq!(ids(1), [10_112]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn focus_going_to_a_window_on_the_workspace_in_front_changes_nothing() {
|
||||
let (fake, mut wm) = desktop();
|
||||
open(&fake, 10_411);
|
||||
open(&fake, 10_412);
|
||||
|
||||
with_backend(fake.clone(), || {
|
||||
wm.process_event(added(10_411))?;
|
||||
wm.process_event(added(10_412))?;
|
||||
fake.clear_commands();
|
||||
wm.process_event(activated(10_411))
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(wm.focused_workspace_idx().unwrap(), 0);
|
||||
assert!(fake.on_screen(10_411) && fake.on_screen(10_412));
|
||||
}
|
||||
|
||||
fn moved_to_desktop(id: u32, idx: usize) -> WindowManagerEvent {
|
||||
WindowManagerEvent::WorkspaceMove(
|
||||
SystemNotification::KWin(KWinNotification::WindowMovedToDesktop),
|
||||
Window::from(id),
|
||||
idx,
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_moved_to_another_desktop_by_someone_else_changes_workspace() {
|
||||
let (fake, mut wm) = desktop();
|
||||
open(&fake, 10_501);
|
||||
open(&fake, 10_502);
|
||||
|
||||
with_backend(fake.clone(), || {
|
||||
wm.process_event(added(10_501))?;
|
||||
wm.process_event(added(10_502))?;
|
||||
// "Move to Desktop 2" in the window menu
|
||||
wm.process_event(moved_to_desktop(10_502, 1))
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let ids = |idx: usize| -> Vec<u32> {
|
||||
wm.focused_monitor()
|
||||
.unwrap()
|
||||
.workspaces()
|
||||
.get(idx)
|
||||
.map(|w| {
|
||||
w.containers()
|
||||
.iter()
|
||||
.flat_map(|c| c.windows().iter().map(|w| w.id))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
};
|
||||
assert_eq!(ids(0), [10_501]);
|
||||
assert_eq!(ids(1), [10_502]);
|
||||
|
||||
// the tile left behind was given to the other window
|
||||
let remaining = fake.rect_of(10_501).unwrap();
|
||||
assert!(remaining.right > 1500, "{remaining:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn komorebis_own_move_coming_back_as_an_event_moves_nothing() {
|
||||
let (fake, mut wm) = desktop();
|
||||
open(&fake, 10_511);
|
||||
open(&fake, 10_512);
|
||||
|
||||
with_backend(fake.clone(), || {
|
||||
wm.process_event(added(10_511))?;
|
||||
wm.process_event(added(10_512))?;
|
||||
wm.process_command(SocketMessage::SendContainerToWorkspaceNumber(1), Vec::new())?;
|
||||
fake.clear_commands();
|
||||
wm.process_event(moved_to_desktop(10_512, 1))
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
assert!(
|
||||
fake.commands().is_empty(),
|
||||
"an event about komorebi's own move caused commands: {:?}",
|
||||
fake.commands()
|
||||
);
|
||||
assert_eq!(wm.focused_workspace_idx().unwrap(), 0);
|
||||
}
|
||||
@@ -30,6 +30,9 @@
|
||||
//! - `resize-edge` and `resize-axis` resize the focused window by the `resize-delta`, and
|
||||
//! `quick-save-resize`, `quick-load-resize`, `save-resize` and `load-resize` save the sizes of
|
||||
//! the tiles of the focused workspace and load them back.
|
||||
//! - `focus-workspace` shows another workspace of the focused monitor, `move-to-workspace` moves
|
||||
//! the focused window to a workspace and shows it, and `send-to-workspace` moves it there and
|
||||
//! stays. A workspace is KWin's virtual desktop of the same number, counted from 0.
|
||||
//!
|
||||
//! `ignore-rule` and `manage-rule` add a rule that keeps an application out of the layout or
|
||||
//! always in it, `session-float-rule` floats the focused window and every window like it until the
|
||||
@@ -120,6 +123,25 @@ gen_enum_subcommand_args! {
|
||||
PromoteWindow: OperationDirection,
|
||||
}
|
||||
|
||||
macro_rules! gen_target_subcommand_args {
|
||||
// SubCommand Pattern
|
||||
( $( $name:ident ),+ $(,)? ) => {
|
||||
$(
|
||||
#[derive(clap::Parser)]
|
||||
pub struct $name {
|
||||
/// Target index (zero-indexed)
|
||||
target: usize,
|
||||
}
|
||||
)+
|
||||
};
|
||||
}
|
||||
|
||||
gen_target_subcommand_args! {
|
||||
MoveToWorkspace,
|
||||
SendToWorkspace,
|
||||
FocusWorkspace,
|
||||
}
|
||||
|
||||
macro_rules! gen_focused_workspace_padding_subcommand_args {
|
||||
// SubCommand Pattern
|
||||
( $( $name:ident ),+ $(,)? ) => {
|
||||
@@ -426,6 +448,15 @@ enum SubCommand {
|
||||
/// Resize the focused window or primary column along the specified axis
|
||||
#[clap(arg_required_else_help = true)]
|
||||
ResizeAxis(ResizeAxis),
|
||||
/// Move the focused window to the specified workspace
|
||||
#[clap(arg_required_else_help = true)]
|
||||
MoveToWorkspace(MoveToWorkspace),
|
||||
/// Send the focused window to the specified workspace
|
||||
#[clap(arg_required_else_help = true)]
|
||||
SendToWorkspace(SendToWorkspace),
|
||||
/// Focus the specified workspace on the focused monitor
|
||||
#[clap(arg_required_else_help = true)]
|
||||
FocusWorkspace(FocusWorkspace),
|
||||
/// Set the resize delta (used by resize-edge and resize-axis)
|
||||
#[clap(arg_required_else_help = true)]
|
||||
ResizeDelta(ResizeDelta),
|
||||
@@ -669,6 +700,9 @@ fn main() -> eyre::Result<()> {
|
||||
SubCommand::FlipLayout(args) => {
|
||||
send_message(&SocketMessage::FlipLayout(args.axis))?;
|
||||
}
|
||||
SubCommand::FocusWorkspace(args) => {
|
||||
send_message(&SocketMessage::FocusWorkspaceNumber(args.target))?;
|
||||
}
|
||||
SubCommand::ToggleFloat => {
|
||||
send_message(&SocketMessage::ToggleFloat)?;
|
||||
}
|
||||
@@ -678,6 +712,12 @@ fn main() -> eyre::Result<()> {
|
||||
SubCommand::ResizeAxis(args) => {
|
||||
send_message(&SocketMessage::ResizeWindowAxis(args.axis, args.sizing))?;
|
||||
}
|
||||
SubCommand::MoveToWorkspace(args) => {
|
||||
send_message(&SocketMessage::MoveContainerToWorkspaceNumber(args.target))?;
|
||||
}
|
||||
SubCommand::SendToWorkspace(args) => {
|
||||
send_message(&SocketMessage::SendContainerToWorkspaceNumber(args.target))?;
|
||||
}
|
||||
SubCommand::Retile => {
|
||||
send_message(&SocketMessage::Retile)?;
|
||||
}
|
||||
|
||||
@@ -424,6 +424,22 @@ fn mouse_follows_focus_is_set_with_enable_and_disable_or_toggled() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_workspace_subcommands_send_the_index_they_are_given() {
|
||||
sends(
|
||||
&["focus-workspace", "1"],
|
||||
r#"{"type":"FocusWorkspaceNumber","content":1}"#,
|
||||
);
|
||||
sends(
|
||||
&["move-to-workspace", "2"],
|
||||
r#"{"type":"MoveContainerToWorkspaceNumber","content":2}"#,
|
||||
);
|
||||
sends(
|
||||
&["send-to-workspace", "0"],
|
||||
r#"{"type":"SendContainerToWorkspaceNumber","content":0}"#,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_a_daemon_a_question_fails() {
|
||||
let runtime = Runtime::new();
|
||||
@@ -476,6 +492,7 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() {
|
||||
"cycle-move.md",
|
||||
"data-directory.md",
|
||||
"flip-layout.md",
|
||||
"focus-workspace.md",
|
||||
"focus.md",
|
||||
"focused-workspace-container-padding.md",
|
||||
"focused-workspace-padding.md",
|
||||
@@ -491,6 +508,7 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() {
|
||||
"monitor-information.md",
|
||||
"monitor-work-area-offset.md",
|
||||
"mouse-follows-focus.md",
|
||||
"move-to-workspace.md",
|
||||
"move.md",
|
||||
"preselect-direction.md",
|
||||
"promote-focus.md",
|
||||
@@ -506,6 +524,7 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() {
|
||||
"retile.md",
|
||||
"save-resize.md",
|
||||
"scrolling-layout-columns.md",
|
||||
"send-to-workspace.md",
|
||||
"session-float-rule.md",
|
||||
"session-float-rules.md",
|
||||
"start.md",
|
||||
|
||||
@@ -397,6 +397,83 @@ class Kde:
|
||||
self.machine.screenshot(name)
|
||||
return Image.open(self.machine.out_dir / f"{name}.png").convert("RGB")
|
||||
|
||||
def desk(self, wid: str) -> int:
|
||||
"""The number of the virtual desktop the window is on, counted from 1 as kdotool counts.
|
||||
|
||||
0 when kdotool cannot say (a window on every desktop, a window that is gone).
|
||||
"""
|
||||
lines = self.run(f"kdotool get_desktop_for_window {shlex.quote(wid)}")[1].split()
|
||||
return int(lines[-1]) if lines and lines[-1].isdigit() else 0
|
||||
|
||||
def shown(self) -> int:
|
||||
"""The number of the virtual desktop KWin shows, counted from 1.
|
||||
|
||||
With per-output virtual desktops, that is the desktop of the output KWin considers
|
||||
active; a suite with one output has no other.
|
||||
"""
|
||||
lines = self.run("kdotool get_desktop")[1].split()
|
||||
return int(lines[-1]) if lines and lines[-1].isdigit() else 0
|
||||
|
||||
def desktops(self) -> int:
|
||||
"""The number of virtual desktops KWin has."""
|
||||
out = self.run(
|
||||
"busctl --user get-property org.kde.KWin /VirtualDesktopManager"
|
||||
" org.kde.KWin.VirtualDesktopManager count"
|
||||
)[1].split()
|
||||
return int(out[-1]) if out and out[-1].isdigit() else 0
|
||||
|
||||
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")
|
||||
if status != 0:
|
||||
return None
|
||||
current = None
|
||||
for line in text.splitlines():
|
||||
line = line.strip()
|
||||
if line.startswith("[") and line.endswith("]"):
|
||||
current = line[1:-1]
|
||||
elif current == group and "=" in line:
|
||||
name, value = line.split("=", 1)
|
||||
if name.strip() == key:
|
||||
return value.strip()
|
||||
return None
|
||||
|
||||
def kwin_script(self, name: str, source: str, *, keep: bool = False) -> list[str]:
|
||||
"""Runs `source` as the KWin script `name` and returns the lines it reported.
|
||||
|
||||
The script reports with `report(...)`, which writes its arguments to KWin's log as one
|
||||
line marked with `name`, and ends with `report("done")`, which the lines are waited for.
|
||||
The script is unloaded afterwards, unless `keep` is set: a script that connects to a
|
||||
signal goes on reporting, and [`Kde.kwin_reports`][] reads what it reported since.
|
||||
"""
|
||||
path = f"/tmp/kwin-script-{name}.js"
|
||||
prelude = (
|
||||
"function report() { print("
|
||||
+ json.dumps(f"KS:{name} ")
|
||||
+ " + Array.prototype.slice.call(arguments).join(' ')); }\n"
|
||||
)
|
||||
self.as_user(f"printf %s {shlex.quote(prelude + source)} > {path}")
|
||||
reply = self.sh(
|
||||
"busctl --user call org.kde.KWin /Scripting org.kde.kwin.Scripting loadScript ss"
|
||||
f" {path} {shlex.quote(name)}"
|
||||
).split()
|
||||
script = f"/Scripting/Script{reply[-1]}"
|
||||
self.sh(f"busctl --user call org.kde.KWin {script} org.kde.kwin.Script run")
|
||||
if not self.wait_for(lambda: "done" in self.kwin_reports(name)):
|
||||
raise AssertionError(f"the KWin script {name} never reported it was done")
|
||||
if not keep:
|
||||
self.sh(
|
||||
"busctl --user call org.kde.KWin /Scripting org.kde.kwin.Scripting unloadScript s"
|
||||
f" {shlex.quote(name)}"
|
||||
)
|
||||
return [line for line in self.kwin_reports(name) if line != "done"]
|
||||
|
||||
def kwin_reports(self, name: str) -> list[str]:
|
||||
"""Every line the KWin script `name` has reported so far ([`Kde.kwin_script`][])."""
|
||||
log = self.machine.execute(f"journalctl _UID={self.uid} --no-pager -o cat")[1]
|
||||
mark = f"KS:{name} "
|
||||
return [line.split(mark, 1)[1] for line in log.splitlines() if mark in line]
|
||||
|
||||
def outputs(self) -> int:
|
||||
"""The number of outputs KWin has enabled."""
|
||||
return int(self.sh("kscreen-doctor -j | jq '[.outputs[] | select(.enabled)] | length'"))
|
||||
|
||||
@@ -431,3 +431,75 @@ def test_focused_title_is_empty_for_a_workspace_without_containers(machine: Fake
|
||||
machine.reply("komorebic state", output=a_state(workspace()))
|
||||
|
||||
assert Kde(machine, "main").focused_title() == ""
|
||||
|
||||
|
||||
def test_desk_is_the_desktop_number_kdotool_prints_or_zero(machine: FakeMachine) -> None:
|
||||
machine.reply("{a}", output="2\n")
|
||||
machine.reply("{b}", status=1, output="no such window")
|
||||
kde = Kde(machine, "main")
|
||||
|
||||
assert kde.desk("{a}") == 2
|
||||
assert kde.desk("{b}") == 0
|
||||
|
||||
|
||||
def test_shown_and_desktops_ask_kwin(machine: FakeMachine) -> None:
|
||||
machine.reply("kdotool get_desktop", output="3\n")
|
||||
machine.reply("VirtualDesktopManager count", output="u 4\n")
|
||||
kde = Kde(machine, "main")
|
||||
|
||||
assert kde.shown() == 3
|
||||
assert kde.desktops() == 4
|
||||
|
||||
|
||||
def test_kwinrc_reads_a_key_of_its_own_group(machine: FakeMachine) -> None:
|
||||
machine.reply(
|
||||
"cat /home/komorebi/.config/kwinrc",
|
||||
output=(
|
||||
"[Desktops]\nPerOutputVirtualDesktops=false\n"
|
||||
"[Windows]\nPerOutputVirtualDesktops = true\n"
|
||||
),
|
||||
)
|
||||
kde = Kde(machine, "main")
|
||||
|
||||
assert kde.kwinrc("Windows", "PerOutputVirtualDesktops") == "true"
|
||||
assert kde.kwinrc("Windows", "FocusPolicy") is None
|
||||
|
||||
|
||||
def test_kwinrc_is_none_without_a_file(machine: FakeMachine) -> None:
|
||||
machine.reply("cat /home/komorebi/.config/kwinrc", status=1)
|
||||
|
||||
assert Kde(machine, "main").kwinrc("Windows", "PerOutputVirtualDesktops") is None
|
||||
|
||||
|
||||
def test_a_kwin_script_is_loaded_run_and_unloaded_and_its_reports_returned(
|
||||
machine: FakeMachine,
|
||||
) -> None:
|
||||
machine.reply("loadScript", output="i 7\n")
|
||||
machine.reply("journalctl", output="other\nKS:probe 2 outputs\nkwin: KS:probe done\n")
|
||||
kde = Kde(machine, "main", scale=0.01)
|
||||
|
||||
lines = kde.kwin_script("probe", 'report(workspace.screens.length, "outputs"); report("done");')
|
||||
|
||||
assert lines == ["2 outputs"]
|
||||
scripts = [inner(command) for command in machine.commands if " sh -c " in command]
|
||||
assert any("/tmp/kwin-script-probe.js" in s and "function report()" in s for s in scripts)
|
||||
assert any("/Scripting/Script7 org.kde.kwin.Script run" in s for s in scripts)
|
||||
assert any("unloadScript s probe" in s for s in scripts)
|
||||
|
||||
|
||||
def test_a_kwin_script_that_is_kept_stays_loaded(machine: FakeMachine) -> None:
|
||||
machine.reply("loadScript", output="i 8\n")
|
||||
machine.reply("journalctl", output="KS:listen done\n")
|
||||
kde = Kde(machine, "main", scale=0.01)
|
||||
|
||||
kde.kwin_script("listen", 'report("done");', keep=True)
|
||||
|
||||
assert not any("unloadScript" in command for command in machine.commands)
|
||||
|
||||
|
||||
def test_a_kwin_script_that_never_reports_it_is_done_fails_the_test(machine: FakeMachine) -> None:
|
||||
machine.reply("loadScript", output="i 9\n")
|
||||
kde = Kde(machine, "main", scale=0.01)
|
||||
|
||||
with pytest.raises(AssertionError, match="never reported"):
|
||||
kde.kwin_script("silent", "")
|
||||
@@ -192,6 +192,12 @@ toggle-tiling
|
||||
toggle-tiling
|
||||
toggle-pause
|
||||
toggle-pause
|
||||
focus-workspace 1
|
||||
focus-workspace 0
|
||||
send-to-workspace 1
|
||||
focus-workspace 1
|
||||
move-to-workspace 0
|
||||
focus-workspace 0
|
||||
global-work-area-offset 10 10 20 20
|
||||
global-work-area-offset 0 0 0 0
|
||||
monitor-work-area-offset 0 10 10 20 20
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
tier = "fast";
|
||||
kind = "headless";
|
||||
timeoutMinutes = 10;
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
# The contract of KWin's per-output virtual desktops that komorebi's workspaces rely on, checked
|
||||
# against a headless KWin with two outputs and no komorebi: workspace `i` is desktop `i`, and each
|
||||
# output shows a desktop of its own. What has to hold, and what breaks if it does not:
|
||||
#
|
||||
# - with `[Windows] PerOutputVirtualDesktops=true` in kwinrc, a script can show a desktop on one
|
||||
# output and the other output keeps its own (otherwise a workspace switch switches every monitor);
|
||||
# - KWin says so with `workspace.currentDesktopChanged`, which the bridge listens to;
|
||||
# - KWin focuses a window of the desktop it switched an output to, by itself (komorebi asks for no
|
||||
# focus after a switch it did not make);
|
||||
# - activating a window on another desktop of its output (an app raising itself) makes KWin switch
|
||||
# that output to the window's desktop (which komorebi then follows);
|
||||
# - a window moved by a script so that its middle is on the other output keeps its desktops: KWin
|
||||
# moves a window to the new output's desktop only during an interactive move;
|
||||
# - a window put on another desktop from outside raises `desktopsChanged` on the window, which the
|
||||
# bridge listens to.
|
||||
#
|
||||
# docs/dev/PLATFORM.md records these as the facts of KWin that komorebi depends on.
|
||||
from itertools import count
|
||||
|
||||
from komorebi_vm import Checks, Kde
|
||||
|
||||
start_all()
|
||||
machine.wait_for_unit("multi-user.target")
|
||||
machine.wait_for_unit("user@1000.service")
|
||||
|
||||
checks = Checks()
|
||||
# per-output desktops are read when KWin starts, as komorebi's users have them after their first run
|
||||
machine.succeed(
|
||||
"runuser -u komorebi -- sh -c 'mkdir -p ~/.config"
|
||||
' && printf "[Windows]\\nPerOutputVirtualDesktops=true\\n" > ~/.config/kwinrc\''
|
||||
)
|
||||
kde = Kde.headless(machine, "main", size=(1920, 1080), outputs=2, scale=SCALE)
|
||||
|
||||
# what every script is given: the desktop each output shows, and a window by its title
|
||||
HELPERS = """
|
||||
function cur() {
|
||||
return workspace.screens.map(function (o) {
|
||||
return workspace.currentDesktopForScreen(o).name;
|
||||
}).join("/");
|
||||
}
|
||||
function win(title) {
|
||||
return workspace.windowList().filter(function (w) { return w.caption === title; })[0];
|
||||
}
|
||||
function names(ds) {
|
||||
return ds.map(function (d) { return d.name; }).join(",");
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def script(name: str, body: str, keep: bool = False) -> list[str]:
|
||||
return kde.kwin_script(name, HELPERS + body + '\nreport("done");\n', keep=keep)
|
||||
|
||||
|
||||
def shows() -> str:
|
||||
"""What each output shows, as `first/second`."""
|
||||
lines = script(f"shows-{next(counter)}", "report(cur());")
|
||||
return lines[0] if lines else ""
|
||||
|
||||
|
||||
counter = count(1)
|
||||
|
||||
print("== 1. two outputs, one desktop, and per-output desktops on")
|
||||
outputs = script(
|
||||
"outputs", 'report(workspace.screens.map(function (o) { return o.name; }).join(" "));'
|
||||
)
|
||||
print(f" outputs: {outputs}")
|
||||
names_of = outputs[0].split() if outputs else []
|
||||
checks.check("KWin has two outputs", len(names_of) == 2)
|
||||
checks.check("and one desktop", kde.desktops() == 1)
|
||||
checks.check(
|
||||
"kwinrc has per-output desktops on",
|
||||
kde.kwinrc("Windows", "PerOutputVirtualDesktops") == "true",
|
||||
)
|
||||
|
||||
print("== 2. a desktop created over D-Bus is a desktop of every output")
|
||||
kde.sh(
|
||||
"busctl --user call org.kde.KWin /VirtualDesktopManager"
|
||||
" org.kde.KWin.VirtualDesktopManager createDesktop us 1 two > /dev/null"
|
||||
)
|
||||
checks.check("KWin has two desktops", kde.wait_for(lambda: kde.desktops() == 2))
|
||||
desktops = script("desktops", "report(names(workspace.desktops));")
|
||||
checks.check(f"the script sees them in order: {desktops}", desktops[-1:] == ["Desktop 1,two"])
|
||||
checks.check("both outputs show the first", shows() == "Desktop 1/Desktop 1")
|
||||
|
||||
print("== 3. one output shows another desktop, and the other keeps its own")
|
||||
script(
|
||||
"listen",
|
||||
'workspace.currentDesktopChanged.connect(function () { report("changed", cur()); });',
|
||||
keep=True,
|
||||
)
|
||||
script(
|
||||
"switch", "workspace.setCurrentDesktopForScreen(workspace.desktops[1], workspace.screens[0]);"
|
||||
)
|
||||
checks.check(
|
||||
"the first output shows the second desktop, and the second output the first",
|
||||
kde.wait_for(lambda: shows() == "two/Desktop 1"),
|
||||
)
|
||||
checks.check(
|
||||
"KWin said so with currentDesktopChanged",
|
||||
kde.wait_for(lambda: "changed two/Desktop 1" in kde.kwin_reports("listen")),
|
||||
)
|
||||
script("back", "workspace.setCurrentDesktopForScreen(workspace.desktops[0], workspace.screens[0]);")
|
||||
checks.check("and back", kde.wait_for(lambda: shows() == "Desktop 1/Desktop 1"))
|
||||
|
||||
print("== 4. KWin focuses a window of the desktop it switched an output to")
|
||||
for title in ["w1", "w2"]:
|
||||
kde.spawn(f"foot -T {title} sleep 3000")
|
||||
kde.wait_for(lambda title=title: kde.wid(title) != "", timeout=30)
|
||||
script(
|
||||
"place",
|
||||
"""
|
||||
var d = workspace.desktops;
|
||||
var w1 = win("w1"), w2 = win("w2");
|
||||
w1.desktops = [d[0]];
|
||||
w1.frameGeometry = { x: 100, y: 100, width: 600, height: 400 };
|
||||
w2.desktops = [d[1]];
|
||||
w2.frameGeometry = { x: 800, y: 100, width: 600, height: 400 };
|
||||
workspace.activeWindow = w1;
|
||||
""",
|
||||
)
|
||||
checks.check(
|
||||
"w1 has the focus, on the first desktop",
|
||||
kde.wait_for(lambda: kde.title(kde.active()) == "w1"),
|
||||
)
|
||||
script(
|
||||
"to-two", "workspace.setCurrentDesktopForScreen(workspace.desktops[1], workspace.screens[0]);"
|
||||
)
|
||||
checks.check(
|
||||
"after the first output shows the second desktop, w2, which is on it, has the focus",
|
||||
kde.wait_for(lambda: kde.active() != "" and kde.title(kde.active()) == "w2"),
|
||||
)
|
||||
|
||||
print("== 5. activating a window on another desktop of its output switches that output to it")
|
||||
script("raise", 'workspace.activeWindow = win("w1");')
|
||||
checks.check(
|
||||
"the first output shows the first desktop again",
|
||||
kde.wait_for(lambda: shows() == "Desktop 1/Desktop 1"),
|
||||
)
|
||||
checks.check("and w1 has the focus", kde.wait_for(lambda: kde.title(kde.active()) == "w1"))
|
||||
|
||||
print("== 6. a window a script moves onto the other output keeps its desktops")
|
||||
script("cross", 'win("w1").frameGeometry = { x: 2300, y: 100, width: 600, height: 400 };')
|
||||
|
||||
|
||||
def where_w1() -> str:
|
||||
lines = script(
|
||||
f"where-{next(counter)}",
|
||||
'var w = win("w1"); report(w.output.name + " " + names(w.desktops));',
|
||||
)
|
||||
return lines[0] if lines else ""
|
||||
|
||||
|
||||
second = names_of[1] if len(names_of) == 2 else "?"
|
||||
checks.check(
|
||||
f"w1 is on {second} now, and still on the first desktop only",
|
||||
kde.wait_for(lambda: where_w1() == f"{second} Desktop 1"),
|
||||
)
|
||||
|
||||
print("== 7. a window put on another desktop from outside says so")
|
||||
script(
|
||||
"watch",
|
||||
'var w = win("w1"); w.desktopsChanged.connect(function () { report("moved", names(w.desktops)); });',
|
||||
keep=True,
|
||||
)
|
||||
kde.sh(f"kdotool set_desktop_for_window {kde.wid('w1')} 2")
|
||||
checks.check(
|
||||
"w1's desktopsChanged was raised, with the second desktop",
|
||||
kde.wait_for(lambda: "moved two" in kde.kwin_reports("watch")),
|
||||
)
|
||||
|
||||
kde.stop()
|
||||
checks.finish()
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
tier = "fast";
|
||||
kind = "headless";
|
||||
timeoutMinutes = 10;
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
# komorebi's workspaces are KWin's own virtual desktops, per output. What only a real KWin can
|
||||
# tell: that komorebi turns on KWin's per-output virtual desktops and puts the user's setting back
|
||||
# when it stops; that `komorebic send-to-workspace` puts a window on another desktop and leaves the
|
||||
# one in front showing; that `komorebic focus-workspace` has KWin show the other desktop, and KWin
|
||||
# focuses the window there, which komorebi agrees with, without komorebi hiding or parking any
|
||||
# window; that a switch by anything else (a shortcut, an app raising a window of another desktop)
|
||||
# is followed once, with KWin and komorebi agreeing on the focused window and nothing flip-flopping;
|
||||
# and that a window moved to another desktop by someone else (the window menu's "Move to Desktop")
|
||||
# moves to that workspace. `komorebi/tests/workspaces.rs` checks the same against the fake.
|
||||
import time
|
||||
|
||||
from komorebi_vm import Checks, Kde, daemon
|
||||
|
||||
start_all()
|
||||
machine.wait_for_unit("multi-user.target")
|
||||
machine.wait_for_unit("user@1000.service")
|
||||
|
||||
checks = Checks()
|
||||
kde = Kde.headless(machine, "main", size=(1920, 1080), scale=SCALE)
|
||||
|
||||
|
||||
def focus_changes() -> int:
|
||||
return sum(1 for e in daemon.events(kde.komorebi_log()) if e.kind == "FocusChange")
|
||||
|
||||
|
||||
def ws() -> int:
|
||||
"""The workspace komorebi has in front on the (only) monitor."""
|
||||
return kde.state()["monitors"]["elements"][0]["workspaces"]["focused"]
|
||||
|
||||
|
||||
def active_title() -> str:
|
||||
active = kde.active()
|
||||
return kde.title(active) if active else ""
|
||||
|
||||
|
||||
def per_output() -> bool:
|
||||
return kde.kwinrc("Windows", "PerOutputVirtualDesktops") == "true"
|
||||
|
||||
|
||||
print("== 1. start, and three windows")
|
||||
checks.check("per-output virtual desktops are off before komorebi starts", not per_output())
|
||||
kde.start_komorebi()
|
||||
checks.check(
|
||||
"the daemon answers komorebic",
|
||||
kde.wait_for(lambda: kde.run("komorebic state")[0] == 0, timeout=30),
|
||||
)
|
||||
for title in ["w1", "w2", "w3"]:
|
||||
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(0) == 3, timeout=20))
|
||||
|
||||
print("== 2. workspaces are desktops")
|
||||
checks.check("komorebi turned on per-output virtual desktops in kwinrc", per_output())
|
||||
checks.check(
|
||||
"all three windows are on desktop 1, which is showing",
|
||||
all(kde.desk(kde.wid(t)) == 1 for t in ["w1", "w2", "w3"]) and kde.shown() == 1,
|
||||
)
|
||||
|
||||
print("== 3. one window goes to workspace 1 and stays there")
|
||||
moved = active_title()
|
||||
mid = kde.wid(moved)
|
||||
kde.komorebic("send-to-workspace", "1")
|
||||
checks.check(
|
||||
f"{moved} is on desktop 2, and desktop 1 is still showing",
|
||||
kde.wait_for(lambda: kde.desk(mid) == 2 and kde.shown() == 1 and ws() == 0),
|
||||
)
|
||||
checks.check(
|
||||
"the other two are on workspace 0, and komorebi has the moved one on workspace 1",
|
||||
kde.wait_for(lambda: kde.managed(0) == 2 and kde.managed(1) == 1),
|
||||
)
|
||||
stayed = [t for t in ["w1", "w2", "w3"] if t != moved]
|
||||
|
||||
print("== 4. komorebic switches workspace: KWin shows the desktop, komorebi hides nothing")
|
||||
kde.komorebic("focus-workspace", "1")
|
||||
checks.check(
|
||||
"desktop 2 is showing and komorebi agrees",
|
||||
kde.wait_for(lambda: kde.shown() == 2 and ws() == 1),
|
||||
)
|
||||
checks.check(
|
||||
"KWin focused the window of that desktop and komorebi knows it",
|
||||
kde.wait_for(lambda: active_title() == moved and kde.focused_title(1) == moved),
|
||||
)
|
||||
checks.check(
|
||||
"the windows of desktop 1 never left it", all(kde.desk(kde.wid(t)) == 1 for t in stayed)
|
||||
)
|
||||
checks.check("komorebi made one desktop, for workspace 1, and no other", kde.desktops() == 2)
|
||||
kde.komorebic("focus-workspace", "0")
|
||||
checks.check("back on desktop 1", kde.wait_for(lambda: kde.shown() == 1 and ws() == 0))
|
||||
|
||||
print("== 5. something else switches: a pager or a shortcut")
|
||||
kde.sh("busctl --user call org.kde.KWin /KWin org.kde.KWin setCurrentDesktop i 2 > /dev/null")
|
||||
checks.check("komorebi followed to workspace 1", kde.wait_for(lambda: ws() == 1))
|
||||
checks.check(
|
||||
"and agrees with KWin on the focused window",
|
||||
kde.wait_for(lambda: active_title() != "" and active_title() == kde.focused_title(1)),
|
||||
)
|
||||
|
||||
print("== 6. an app raises a window of another desktop")
|
||||
kde.sh("busctl --user call org.kde.KWin /KWin org.kde.KWin setCurrentDesktop i 1 > /dev/null")
|
||||
kde.wait_for(lambda: ws() == 0)
|
||||
time.sleep(1 * SCALE)
|
||||
before = focus_changes()
|
||||
kde.activate(mid)
|
||||
checks.check(
|
||||
"KWin switched to the window's desktop and komorebi followed",
|
||||
kde.wait_for(lambda: kde.shown() == 2 and ws() == 1),
|
||||
)
|
||||
checks.check(
|
||||
f"KWin and komorebi agree on the focused window: {moved}",
|
||||
kde.wait_for(lambda: active_title() == moved and kde.focused_title(1) == moved),
|
||||
)
|
||||
time.sleep(3 * SCALE)
|
||||
after = focus_changes()
|
||||
print(f" focus changes komorebi handled meanwhile: {after - before}")
|
||||
checks.check(
|
||||
f"nothing is flip-flopping (at most 6 focus events, got {after - before})",
|
||||
after - before <= 6,
|
||||
)
|
||||
time.sleep(3 * SCALE)
|
||||
final = focus_changes()
|
||||
checks.check(f"and it stays quiet afterwards ({final - after} more)", final - after <= 1)
|
||||
|
||||
print("== 7. somebody moves a window to another desktop (the window menu's Move to Desktop)")
|
||||
other = kde.wid(stayed[0])
|
||||
kde.sh(f"kdotool set_desktop_for_window {other} 2")
|
||||
checks.check(
|
||||
"komorebi moved it to workspace 1: one window left on workspace 0, two on workspace 1",
|
||||
kde.wait_for(lambda: kde.managed(0) == 1 and kde.managed(1) == 2),
|
||||
)
|
||||
checks.check("and left it where KWin put it", kde.desk(other) == 2)
|
||||
checks.check("KWin carried out every command", "the bridge could not do" not in kde.komorebi_log())
|
||||
|
||||
print("== 8. a clean stop")
|
||||
kde.komorebic("stop")
|
||||
checks.check("the daemon exited", kde.wait_for(lambda: not kde.komorebi_running()))
|
||||
checks.check("per-output virtual desktops are back as they were (off)", not per_output())
|
||||
checks.check("the desktops komorebi made stay: they are the user's now", kde.desktops() == 2)
|
||||
|
||||
kde.stop()
|
||||
checks.finish()
|
||||
Reference in new issue
Block a user