From 8467b03ac27018a2b4e79b412f8017b34afb7e67 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 17:43:36 -0700 Subject: [PATCH] feat(wm): named workspaces and the other workspace commands Workspace i is KWin's desktop i, and switching and moving by index came with the workspaces. What a user binds keys to besides is the rest of komorebi's workspace commands: going to the next or the previous workspace (or the next empty one), back to the last one, adding and closing workspaces, showing one index on every monitor, and setting the layout or the tiling of a workspace that need not be in front. They are made of the same two operations, showing a workspace and moving a container to one, so KWin keeps doing the showing and the hiding. A workspace gets a name, which focus-named-workspace, named-workspace-layout and named-workspace-tiling find it by on any monitor; focusing a named workspace focuses its monitor too, so focus_monitor comes with it. The name is komorebi's: naming a workspace does not rename KWin's desktop. The query focused-workspace-name answers with the name, or the index of a workspace that has none. The moves to a named workspace, and everything that addresses a monitor, are moves between monitors in the window manager and come with more than one monitor. --- README.md | 5 +- docs/cli/close-workspace.md | 10 + docs/cli/cycle-empty-workspace.md | 14 + docs/cli/cycle-move-to-workspace.md | 14 + docs/cli/cycle-send-to-workspace.md | 14 + docs/cli/cycle-workspace.md | 14 + docs/cli/ensure-named-workspaces.md | 17 ++ docs/cli/ensure-workspaces.md | 17 ++ docs/cli/focus-last-workspace.md | 10 + docs/cli/focus-named-workspace.md | 14 + docs/cli/focus-workspaces.md | 14 + docs/cli/move-to-last-workspace.md | 10 + docs/cli/named-workspace-layout.md | 26 ++ docs/cli/named-workspace-tiling.md | 17 ++ docs/cli/new-workspace.md | 10 + docs/cli/query.md | 3 +- docs/cli/send-to-last-workspace.md | 10 + docs/cli/workspace-layout.md | 29 ++ docs/cli/workspace-name.md | 20 ++ docs/cli/workspace-tiling.md | 20 ++ docs/dev/ARCHITECTURE.md | 30 +- docs/usage/workspaces.md | 68 +++++ komorebi/src/core/mod.rs | 21 ++ komorebi/src/monitor.rs | 14 + komorebi/src/process_command.rs | 226 +++++++++++++++ komorebi/src/state.rs | 3 + komorebi/src/window_manager.rs | 360 +++++++++++++++++++++++- komorebi/src/workspace.rs | 2 + komorebi/tests/workspace_commands.rs | 401 +++++++++++++++++++++++++++ komorebic/Cargo.toml | 3 + komorebic/src/main.rs | 251 +++++++++++++++++ komorebic/tests/cli.rs | 92 ++++++ nix/tests/vm/suites/commands/test.py | 32 +++ 33 files changed, 1782 insertions(+), 9 deletions(-) create mode 100644 docs/cli/close-workspace.md create mode 100644 docs/cli/cycle-empty-workspace.md create mode 100644 docs/cli/cycle-move-to-workspace.md create mode 100644 docs/cli/cycle-send-to-workspace.md create mode 100644 docs/cli/cycle-workspace.md create mode 100644 docs/cli/ensure-named-workspaces.md create mode 100644 docs/cli/ensure-workspaces.md create mode 100644 docs/cli/focus-last-workspace.md create mode 100644 docs/cli/focus-named-workspace.md create mode 100644 docs/cli/focus-workspaces.md create mode 100644 docs/cli/move-to-last-workspace.md create mode 100644 docs/cli/named-workspace-layout.md create mode 100644 docs/cli/named-workspace-tiling.md create mode 100644 docs/cli/new-workspace.md create mode 100644 docs/cli/send-to-last-workspace.md create mode 100644 docs/cli/workspace-layout.md create mode 100644 docs/cli/workspace-name.md create mode 100644 docs/cli/workspace-tiling.md create mode 100644 komorebi/tests/workspace_commands.rs diff --git a/README.md b/README.md index a746eaf8..8d1a7d0b 100644 --- a/README.md +++ b/README.md @@ -164,7 +164,10 @@ 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. +without showing it; their `cycle-` and `-last-workspace` forms go to the next, +the previous or the last workspace, `workspace-name` names a workspace for +`focus-named-workspace` and the other named commands, and `new-workspace` and +`close-workspace` add and remove one. 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 diff --git a/docs/cli/close-workspace.md b/docs/cli/close-workspace.md new file mode 100644 index 00000000..5ce04f43 --- /dev/null +++ b/docs/cli/close-workspace.md @@ -0,0 +1,10 @@ +```text +Close the focused workspace (must be empty and unnamed) + +Usage: close-workspace + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/cycle-empty-workspace.md b/docs/cli/cycle-empty-workspace.md new file mode 100644 index 00000000..ca6a6d58 --- /dev/null +++ b/docs/cli/cycle-empty-workspace.md @@ -0,0 +1,14 @@ +```text +Focus the next empty workspace in the given cycle direction (if one exists) + +Usage: cycle-empty-workspace + +Arguments: + + [possible values: previous, next] + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/cycle-move-to-workspace.md b/docs/cli/cycle-move-to-workspace.md new file mode 100644 index 00000000..b2b86bfb --- /dev/null +++ b/docs/cli/cycle-move-to-workspace.md @@ -0,0 +1,14 @@ +```text +Move the focused window to the workspace in the given cycle direction + +Usage: cycle-move-to-workspace + +Arguments: + + [possible values: previous, next] + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/cycle-send-to-workspace.md b/docs/cli/cycle-send-to-workspace.md new file mode 100644 index 00000000..a19499f3 --- /dev/null +++ b/docs/cli/cycle-send-to-workspace.md @@ -0,0 +1,14 @@ +```text +Send the focused window to the workspace in the given cycle direction + +Usage: cycle-send-to-workspace + +Arguments: + + [possible values: previous, next] + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/cycle-workspace.md b/docs/cli/cycle-workspace.md new file mode 100644 index 00000000..2146fc81 --- /dev/null +++ b/docs/cli/cycle-workspace.md @@ -0,0 +1,14 @@ +```text +Focus the workspace in the given cycle direction + +Usage: cycle-workspace + +Arguments: + + [possible values: previous, next] + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/ensure-named-workspaces.md b/docs/cli/ensure-named-workspaces.md new file mode 100644 index 00000000..8fa821f0 --- /dev/null +++ b/docs/cli/ensure-named-workspaces.md @@ -0,0 +1,17 @@ +```text +Create these many named workspaces for the specified monitor + +Usage: ensure-named-workspaces [NAMES]... + +Arguments: + + Monitor index (zero-indexed) + + [NAMES]... + Names of desired workspaces + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/ensure-workspaces.md b/docs/cli/ensure-workspaces.md new file mode 100644 index 00000000..a91e64a1 --- /dev/null +++ b/docs/cli/ensure-workspaces.md @@ -0,0 +1,17 @@ +```text +Create at least this many workspaces for the specified monitor + +Usage: ensure-workspaces + +Arguments: + + Monitor index (zero-indexed) + + + Number of desired workspaces + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/focus-last-workspace.md b/docs/cli/focus-last-workspace.md new file mode 100644 index 00000000..168226d5 --- /dev/null +++ b/docs/cli/focus-last-workspace.md @@ -0,0 +1,10 @@ +```text +Focus the last focused workspace on the focused monitor + +Usage: focus-last-workspace + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/focus-named-workspace.md b/docs/cli/focus-named-workspace.md new file mode 100644 index 00000000..e3d31cfc --- /dev/null +++ b/docs/cli/focus-named-workspace.md @@ -0,0 +1,14 @@ +```text +Focus the specified workspace + +Usage: focus-named-workspace + +Arguments: + + Target workspace name + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/focus-workspaces.md b/docs/cli/focus-workspaces.md new file mode 100644 index 00000000..e2bbc0c3 --- /dev/null +++ b/docs/cli/focus-workspaces.md @@ -0,0 +1,14 @@ +```text +Focus the specified workspace on all monitors + +Usage: focus-workspaces + +Arguments: + + Target index (zero-indexed) + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/move-to-last-workspace.md b/docs/cli/move-to-last-workspace.md new file mode 100644 index 00000000..83bf3e9a --- /dev/null +++ b/docs/cli/move-to-last-workspace.md @@ -0,0 +1,10 @@ +```text +Move the focused window to the last focused monitor workspace + +Usage: move-to-last-workspace + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/named-workspace-layout.md b/docs/cli/named-workspace-layout.md new file mode 100644 index 00000000..03eb3ea3 --- /dev/null +++ b/docs/cli/named-workspace-layout.md @@ -0,0 +1,26 @@ +```text +Set the layout for the specified workspace + +Usage: named-workspace-layout + +Arguments: + + Target workspace name + + + Possible values: + - bsp: BSP Layout + - columns: Columns Layout + - rows: Rows Layout + - vertical-stack: Vertical Stack Layout + - horizontal-stack: Horizontal Stack Layout + - ultrawide-vertical-stack: Ultrawide Vertical Stack Layout + - grid: Grid Layout + - right-main-vertical-stack: Right Main Vertical Stack Layout + - scrolling: Scrolling Layout + +Options: + -h, --help + Print help (see a summary with '-h') + +``` diff --git a/docs/cli/named-workspace-tiling.md b/docs/cli/named-workspace-tiling.md new file mode 100644 index 00000000..fb11fd49 --- /dev/null +++ b/docs/cli/named-workspace-tiling.md @@ -0,0 +1,17 @@ +```text +Enable or disable window tiling for the specified workspace + +Usage: named-workspace-tiling + +Arguments: + + Target workspace name + + + [possible values: enable, disable] + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/new-workspace.md b/docs/cli/new-workspace.md new file mode 100644 index 00000000..6fad0ed7 --- /dev/null +++ b/docs/cli/new-workspace.md @@ -0,0 +1,10 @@ +```text +Create and append a new workspace on the focused monitor + +Usage: new-workspace + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/query.md b/docs/cli/query.md index f2a6a955..1dfeae39 100644 --- a/docs/cli/query.md +++ b/docs/cli/query.md @@ -6,7 +6,8 @@ Usage: query Arguments: [possible values: focused-monitor-index, focused-workspace-index, focused-container-index, - focused-window-index, focused-workspace-layout, focused-container-kind, version] + focused-window-index, focused-workspace-name, focused-workspace-layout, + focused-container-kind, version] Options: -h, --help diff --git a/docs/cli/send-to-last-workspace.md b/docs/cli/send-to-last-workspace.md new file mode 100644 index 00000000..7b9ac014 --- /dev/null +++ b/docs/cli/send-to-last-workspace.md @@ -0,0 +1,10 @@ +```text +Send the focused window to the last focused monitor workspace + +Usage: send-to-last-workspace + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/workspace-layout.md b/docs/cli/workspace-layout.md new file mode 100644 index 00000000..21e8107b --- /dev/null +++ b/docs/cli/workspace-layout.md @@ -0,0 +1,29 @@ +```text +Set the layout for the specified workspace + +Usage: workspace-layout + +Arguments: + + Monitor index (zero-indexed) + + + Workspace index on the specified monitor (zero-indexed) + + + Possible values: + - bsp: BSP Layout + - columns: Columns Layout + - rows: Rows Layout + - vertical-stack: Vertical Stack Layout + - horizontal-stack: Horizontal Stack Layout + - ultrawide-vertical-stack: Ultrawide Vertical Stack Layout + - grid: Grid Layout + - right-main-vertical-stack: Right Main Vertical Stack Layout + - scrolling: Scrolling Layout + +Options: + -h, --help + Print help (see a summary with '-h') + +``` diff --git a/docs/cli/workspace-name.md b/docs/cli/workspace-name.md new file mode 100644 index 00000000..7110d1a5 --- /dev/null +++ b/docs/cli/workspace-name.md @@ -0,0 +1,20 @@ +```text +Set the workspace name for the specified workspace + +Usage: workspace-name + +Arguments: + + Monitor index (zero-indexed) + + + Workspace index on the specified monitor (zero-indexed) + + + Name of the workspace as a String + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/workspace-tiling.md b/docs/cli/workspace-tiling.md new file mode 100644 index 00000000..01157a40 --- /dev/null +++ b/docs/cli/workspace-tiling.md @@ -0,0 +1,20 @@ +```text +Enable or disable window tiling for the specified workspace + +Usage: workspace-tiling + +Arguments: + + Monitor index (zero-indexed) + + + Workspace index on the specified monitor (zero-indexed) + + + [possible values: enable, disable] + +Options: + -h, --help + Print help + +``` diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index d4c86da3..906490c4 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -20,7 +20,8 @@ each part of the daemon that is added has its place here. 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. Workspace `i` is the - compositor's desktop `i` on that monitor. + compositor's desktop `i` on that monitor. A workspace can have a name, which the named + commands find it by. - **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. @@ -421,6 +422,22 @@ of the monitor and shows that workspace, and `SendContainerToWorkspaceNumber` do 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. +The other workspace commands are made of the same two operations. `CycleFocusWorkspace`, +`CycleMoveContainerToWorkspace` and `CycleSendContainerToWorkspace` take the next or the previous +workspace, which wraps around, and `CycleFocusEmptyWorkspace` the next or the previous with no +window. A monitor remembers the workspace that was in front before ([`Monitor::focus_workspace`] +records it), which `FocusLastWorkspace`, `MoveContainerToLastWorkspace` and +`SendContainerToLastWorkspace` take. `FocusWorkspaceNumbers` shows a workspace on every monitor. +`WorkspaceName` names a workspace, `EnsureNamedWorkspaces` gives a monitor named workspaces, and +`FocusNamedWorkspace`, `NamedWorkspaceLayout` and `NamedWorkspaceTiling` look a workspace up by +its name on every monitor ([`WindowManager::monitor_workspace_index_by_name`]); a name no +workspace has changes nothing. `FocusNamedWorkspace` focuses the monitor that has the workspace +([`WindowManager::focus_monitor`]). `WorkspaceLayout` and `WorkspaceTiling` set the layout and the +tiling of a workspace by index. `NewWorkspace` adds a workspace and shows it, `EnsureWorkspaces` +gives a monitor workspaces up to a number, and `CloseWorkspace` removes the workspace in front +when it has no window and no name and is not the monitor's last. A name is komorebi's: the +compositor's desktops keep theirs. + `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 @@ -481,7 +498,8 @@ module's unit. window out, move the focus, move the focused container, change the layout, resize or promote the focused container, float a window, lock a container, set the padding of a workspace, manage and unmanage a window, show a workspace, move a container to another - workspace, follow a workspace switch made by something else). + workspace, follow a workspace switch made by something else, name a workspace and find + it by its name, set the layout of a workspace that is not in front). - [`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 @@ -583,6 +601,7 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | 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 | +| A workspace is closed only when it has no window and no name and is not the monitor's last | framework path: the `CloseWorkspace` arm of [`WindowManager::process_command`] checks all three | `new_workspace_adds_one_and_close_workspace_removes_it_when_it_is_empty_and_unnamed` | none | | 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 | @@ -714,7 +733,9 @@ A window is shown, and ends up on a tile: - [`nix/tests/vm/suites/commands`](../../nix/tests/vm/suites/commands/test.py): every layout, and every `komorebic` command, against a real KWin with two outputs. - [`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 + fake's desktops; + [`komorebi/tests/workspace_commands.rs`](../../komorebi/tests/workspace_commands.rs), naming, + cycling and the other workspace commands; [`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; @@ -809,6 +830,9 @@ A window is shown, and ends up on a tile: [`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 +[`WindowManager::monitor_workspace_index_by_name`]: ../../komorebi/src/window_manager.rs +[`WindowManager::focus_monitor`]: ../../komorebi/src/window_manager.rs +[`Monitor::focus_workspace`]: ../../komorebi/src/monitor.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 diff --git a/docs/usage/workspaces.md b/docs/usage/workspaces.md index c3713c31..d41986a2 100644 --- a/docs/usage/workspaces.md +++ b/docs/usage/workspaces.md @@ -36,6 +36,74 @@ komorebic move-to-workspace 1 komorebic send-to-workspace 2 ``` +## Going round the workspaces + +[`komorebic cycle-workspace`](../cli/cycle-workspace.md) shows the next or the previous workspace +of the focused monitor, and wraps around at both ends; +[`komorebic cycle-empty-workspace`](../cli/cycle-empty-workspace.md) shows the next or the previous +one that has no window, if there is one. +[`komorebic cycle-move-to-workspace`](../cli/cycle-move-to-workspace.md) and +[`komorebic cycle-send-to-workspace`](../cli/cycle-send-to-workspace.md) take the focused window to +the next or the previous workspace, with and without showing it. + +```sh +komorebic cycle-workspace next +komorebic cycle-empty-workspace previous +komorebic cycle-move-to-workspace next +``` + +## The last workspace + +Each monitor remembers which workspace was in front before the one in front now. +[`komorebic focus-last-workspace`](../cli/focus-last-workspace.md) shows it again, so two in a row +go back and forth between the two. +[`komorebic move-to-last-workspace`](../cli/move-to-last-workspace.md) and +[`komorebic send-to-last-workspace`](../cli/send-to-last-workspace.md) take the focused window +there, with and without showing it. + +## Names + +[`komorebic workspace-name`](../cli/workspace-name.md) names a workspace, given by the index of its +monitor and its own index, and +[`komorebic ensure-named-workspaces`](../cli/ensure-named-workspaces.md) gives a monitor a workspace +for each name it is given, in order. The name is komorebi's, for the commands that find a +workspace by its name: KWin's desktop keeps the name it has. +[`komorebic focus-named-workspace`](../cli/focus-named-workspace.md) shows the workspace with that +name, on whichever monitor has it, and focuses that monitor. A name no workspace has changes +nothing. `komorebic query focused-workspace-name` prints the name of the workspace in front, or its +index when it has none. + +```sh +komorebic ensure-named-workspaces 0 web code mail +komorebic focus-named-workspace mail +``` + +## Adding and removing workspaces + +[`komorebic new-workspace`](../cli/new-workspace.md) adds a workspace after the last one of the +focused monitor and shows it, and [`komorebic ensure-workspaces`](../cli/ensure-workspaces.md) +gives a monitor at least as many workspaces as it is told. +[`komorebic close-workspace`](../cli/close-workspace.md) removes the workspace in front and shows +the one before it, when the workspace has no window and no name and is not the monitor's last. + +[`komorebic focus-workspaces`](../cli/focus-workspaces.md) shows the workspace with the same index +on every monitor. + +## The layout of another workspace + +[`komorebic workspace-layout`](../cli/workspace-layout.md) and +[`komorebic workspace-tiling`](../cli/workspace-tiling.md) set the layout of a workspace, and turn +its tiling off or on, by the index of its monitor and its own index; +[`komorebic named-workspace-layout`](../cli/named-workspace-layout.md) and +[`komorebic named-workspace-tiling`](../cli/named-workspace-tiling.md) find it by its name. The +focused workspace is tiled again at once, and another workspace the next time it is tiled, when it +is shown at the latest. + +```sh +komorebic workspace-layout 0 1 columns +komorebic named-workspace-tiling mail disable +``` + ## Switching with KWin Anything that switches KWin's desktop switches komorebi's workspace: the pager, KWin's own diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index e51b7894..e8d78060 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -274,6 +274,7 @@ pub enum StateQuery { FocusedWorkspaceIndex, FocusedContainerIndex, FocusedWindowIndex, + FocusedWorkspaceName, FocusedWorkspaceLayout, FocusedContainerKind, Version, @@ -348,8 +349,12 @@ pub enum SocketMessage { CycleMoveWindow(CycleDirection), ResizeWindowEdge(OperationDirection, Sizing), ResizeWindowAxis(Axis, Sizing), + MoveContainerToLastWorkspace, + SendContainerToLastWorkspace, MoveContainerToWorkspaceNumber(usize), + CycleMoveContainerToWorkspace(CycleDirection), SendContainerToWorkspaceNumber(usize), + CycleSendContainerToWorkspace(CycleDirection), // ForceFocus, Close, Minimize, @@ -375,6 +380,9 @@ pub enum SocketMessage { FlipLayout(Axis), // Monitor and Workspace Commands // MonitorIndexPreference(usize, i32, i32, i32, i32), + EnsureWorkspaces(usize, usize), + EnsureNamedWorkspaces(usize, Vec), + NewWorkspace, ToggleTiling, Stop, TogglePause, @@ -384,11 +392,24 @@ pub enum SocketMessage { QuickLoad, Save(#[serde_as(as = "ResolvedPathBuf")] PathBuf), Load(#[serde_as(as = "ResolvedPathBuf")] PathBuf), + CycleFocusWorkspace(CycleDirection), + CycleFocusEmptyWorkspace(CycleDirection), + FocusLastWorkspace, + CloseWorkspace, FocusWorkspaceNumber(usize), + FocusWorkspaceNumbers(usize), + FocusNamedWorkspace(String), ContainerPadding(usize, usize, i32), FocusedWorkspaceContainerPadding(i32), WorkspacePadding(usize, usize, i32), FocusedWorkspacePadding(i32), + WorkspaceTiling(usize, usize, bool), + NamedWorkspaceTiling(String, bool), + WorkspaceName(usize, usize, String), + WorkspaceLayout(usize, usize, DefaultLayout), + NamedWorkspaceLayout(String, DefaultLayout), + // WorkspaceLayoutCustom(usize, usize, #[serde_as(as = "ResolvedPathBuf")] PathBuf), + // NamedWorkspaceLayoutCustom(String, #[serde_as(as = "ResolvedPathBuf")] PathBuf), WorkAreaOffset(Rect), MonitorWorkAreaOffset(usize, Rect), WorkspaceWorkAreaOffset(usize, usize, Rect), diff --git a/komorebi/src/monitor.rs b/komorebi/src/monitor.rs index 18160570..ea14c389 100644 --- a/komorebi/src/monitor.rs +++ b/komorebi/src/monitor.rs @@ -66,6 +66,10 @@ pub struct Monitor { pub window_based_work_area_offset_limit: isize, pub container_padding: Option, pub workspace_padding: Option, + /// The workspace that was in front before the one in front now, which `focus-last-workspace` + /// shows again + #[serde(skip_serializing_if = "Option::is_none")] + pub last_focused_workspace: Option, } /// Returns a monitor with one empty workspace, the way [`Monitor::new`] makes one, from owned @@ -90,6 +94,7 @@ pub fn new( window_based_work_area_offset: None, window_based_work_area_offset_limit: 1, workspaces, + last_focused_workspace: None, container_padding: None, workspace_padding: None, } @@ -119,6 +124,7 @@ impl Monitor { window_based_work_area_offset_limit: 1, container_padding: None, workspace_padding: None, + last_focused_workspace: None, } } @@ -176,6 +182,7 @@ impl Monitor { if workspaces.get(idx).is_none() { workspaces.resize(idx + 1, Workspace::default()); } + self.last_focused_workspace = Some(self.workspaces.focused_idx()); self.workspaces.focus(idx); } @@ -427,6 +434,13 @@ impl Monitor { } } + /// The name of the focused workspace, if it has one + pub fn focused_workspace_name(&self) -> Option { + self.focused_workspace() + .map(|w| w.name.clone()) + .unwrap_or(None) + } + /// The layout of the focused workspace, if the monitor has one and its tiling is on pub fn focused_workspace_layout(&self) -> Option { self.focused_workspace().and_then(|workspace| { diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index da0b26c0..88a4bb49 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -87,6 +87,19 @@ //! 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. +//! - **CycleFocusWorkspace**, **CycleMoveContainerToWorkspace** and +//! **CycleSendContainerToWorkspace** do the same for the next or the previous workspace, and +//! **FocusLastWorkspace**, **MoveContainerToLastWorkspace** and +//! **SendContainerToLastWorkspace** for the workspace that was in front before. +//! **CycleFocusEmptyWorkspace** shows the next or the previous workspace with no window, and +//! **FocusWorkspaceNumbers** shows a workspace on every monitor. +//! - **WorkspaceName** names a workspace and **EnsureNamedWorkspaces** gives a monitor named +//! workspaces; **FocusNamedWorkspace** shows the workspace with a name, on its monitor +//! ([`WindowManager::monitor_workspace_index_by_name`]), and **NamedWorkspaceLayout** and +//! **NamedWorkspaceTiling** set its layout and its tiling, which **WorkspaceLayout** and +//! **WorkspaceTiling** do by index. **EnsureWorkspaces** gives a monitor workspaces up to a +//! number, **NewWorkspace** adds one and shows it, and **CloseWorkspace** removes the workspace +//! in front when it has no window and no name and is not the monitor's last. //! - **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 @@ -133,6 +146,7 @@ use std::fs::File; use std::fs::OpenOptions; use std::io::BufRead; use std::io::BufReader; +use std::num::NonZeroUsize; use std::os::unix::net::UnixStream; use std::str::FromStr; use std::sync::Arc; @@ -208,6 +222,9 @@ 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 monitor or the workspace a message names by its index is not there + /// (`WorkspaceName`, `WorkspaceLayout`, `WorkspaceTiling`, `EnsureWorkspaces`, + /// `EnsureNamedWorkspaces`). A name no workspace has is ignored. /// - 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 @@ -282,11 +299,119 @@ impl WindowManager { SocketMessage::CycleMoveWindow(direction) => { self.move_container_in_cycle_direction(direction)?; } + SocketMessage::CycleFocusWorkspace(direction) => { + let focused_monitor = self.focused_monitor().ok_or_eyre("there is no monitor")?; + + let focused_workspace_idx = focused_monitor.focused_workspace_idx(); + let workspaces = focused_monitor.workspaces().len(); + + let workspace_idx = direction.next_idx( + focused_workspace_idx, + NonZeroUsize::new(workspaces) + .ok_or_eyre("there must be at least one workspace")?, + ); + + self.focus_workspace(workspace_idx)?; + } + SocketMessage::CycleFocusEmptyWorkspace(direction) => { + let focused_monitor = self.focused_monitor().ok_or_eyre("there is no monitor")?; + + let focused_workspace_idx = focused_monitor.focused_workspace_idx(); + let workspaces = focused_monitor.workspaces().len(); + + let mut empty_workspaces = vec![]; + + for (idx, w) in focused_monitor.workspaces().iter().enumerate() { + if w.is_empty() { + empty_workspaces.push(idx); + } + } + + if !empty_workspaces.is_empty() { + let mut workspace_idx = direction.next_idx( + focused_workspace_idx, + NonZeroUsize::new(workspaces) + .ok_or_eyre("there must be at least one workspace")?, + ); + + while !empty_workspaces.contains(&workspace_idx) { + workspace_idx = direction.next_idx( + workspace_idx, + NonZeroUsize::new(workspaces) + .ok_or_eyre("there must be at least one workspace")?, + ); + } + + self.focus_workspace(workspace_idx)?; + } + } + SocketMessage::FocusLastWorkspace => { + let idx = self + .focused_monitor() + .ok_or_eyre("there is no monitor")? + .focused_workspace_idx(); + + if let Some(monitor) = self.focused_monitor_mut() + && let Some(last_focused_workspace) = monitor.last_focused_workspace + { + self.focus_workspace(last_focused_workspace)?; + } + + self.focused_monitor_mut() + .ok_or_eyre("there is no monitor")? + .last_focused_workspace = Option::from(idx); + } SocketMessage::FocusWorkspaceNumber(workspace_idx) => { if self.focused_workspace_idx().unwrap_or_default() != workspace_idx { self.focus_workspace(workspace_idx)?; } } + SocketMessage::FocusWorkspaceNumbers(workspace_idx) => { + let focused_monitor_idx = self.focused_monitor_idx(); + + for (i, monitor) in self.monitors_mut().iter_mut().enumerate() { + if i != focused_monitor_idx { + monitor.focus_workspace(workspace_idx)?; + monitor.load_focused_workspace(false)?; + } + } + + self.focus_workspace(workspace_idx)?; + } + SocketMessage::FocusNamedWorkspace(ref name) => { + if let Some((monitor_idx, workspace_idx)) = + self.monitor_workspace_index_by_name(name) + { + self.focus_monitor(monitor_idx)?; + self.focus_workspace(workspace_idx)?; + } + } + SocketMessage::CloseWorkspace => { + let mut can_close = false; + + if let Some(monitor) = self.focused_monitor_mut() { + let focused_workspace_idx = monitor.focused_workspace_idx(); + let next_focused_workspace_idx = focused_workspace_idx.saturating_sub(1); + + if let Some(workspace) = monitor.focused_workspace() + && monitor.workspaces().len() > 1 + && workspace.containers().is_empty() + && workspace.floating_windows().is_empty() + && workspace.name.is_none() + { + can_close = true; + } + + if can_close + && monitor + .workspaces_mut() + .remove(focused_workspace_idx) + .is_some() + { + self.focus_workspace(next_focused_workspace_idx)?; + } + } + } SocketMessage::MoveContainerToWorkspaceNumber(workspace_idx) => { self.move_container_to_workspace(workspace_idx, true, None)?; @@ -294,6 +419,97 @@ impl WindowManager { SocketMessage::SendContainerToWorkspaceNumber(workspace_idx) => { self.move_container_to_workspace(workspace_idx, false, None)?; } + SocketMessage::MoveContainerToLastWorkspace => { + let idx = self + .focused_monitor() + .ok_or_eyre("there is no monitor")? + .focused_workspace_idx(); + + if let Some(monitor) = self.focused_monitor_mut() + && let Some(last_focused_workspace) = monitor.last_focused_workspace + { + self.move_container_to_workspace(last_focused_workspace, true, None)?; + } + + self.focused_monitor_mut() + .ok_or_eyre("there is no monitor")? + .last_focused_workspace = Option::from(idx); + } + SocketMessage::SendContainerToLastWorkspace => { + let idx = self + .focused_monitor() + .ok_or_eyre("there is no monitor")? + .focused_workspace_idx(); + + if let Some(monitor) = self.focused_monitor_mut() + && let Some(last_focused_workspace) = monitor.last_focused_workspace + { + self.move_container_to_workspace(last_focused_workspace, false, None)?; + } + self.focused_monitor_mut() + .ok_or_eyre("there is no monitor")? + .last_focused_workspace = Option::from(idx); + } + SocketMessage::CycleMoveContainerToWorkspace(direction) => { + let focused_monitor = self.focused_monitor().ok_or_eyre("there is no monitor")?; + + let focused_workspace_idx = focused_monitor.focused_workspace_idx(); + let workspaces = focused_monitor.workspaces().len(); + + let workspace_idx = direction.next_idx( + focused_workspace_idx, + NonZeroUsize::new(workspaces) + .ok_or_eyre("there must be at least one workspace")?, + ); + + self.move_container_to_workspace(workspace_idx, true, None)?; + } + SocketMessage::CycleSendContainerToWorkspace(direction) => { + let focused_monitor = self.focused_monitor().ok_or_eyre("there is no monitor")?; + + let focused_workspace_idx = focused_monitor.focused_workspace_idx(); + let workspaces = focused_monitor.workspaces().len(); + + let workspace_idx = direction.next_idx( + focused_workspace_idx, + NonZeroUsize::new(workspaces) + .ok_or_eyre("there must be at least one workspace")?, + ); + + self.move_container_to_workspace(workspace_idx, false, None)?; + } + SocketMessage::NewWorkspace => { + self.new_workspace()?; + } + SocketMessage::WorkspaceTiling(monitor_idx, workspace_idx, tile) => { + self.set_workspace_tiling(monitor_idx, workspace_idx, tile)?; + } + SocketMessage::WorkspaceLayout(monitor_idx, workspace_idx, layout) => { + self.set_workspace_layout_default(monitor_idx, workspace_idx, layout)?; + } + SocketMessage::NamedWorkspaceTiling(ref workspace, tile) => { + if let Some((monitor_idx, workspace_idx)) = + self.monitor_workspace_index_by_name(workspace) + { + self.set_workspace_tiling(monitor_idx, workspace_idx, tile)?; + } + } + SocketMessage::WorkspaceName(monitor_idx, workspace_idx, ref name) => { + self.set_workspace_name(monitor_idx, workspace_idx, name.to_string())?; + } + SocketMessage::NamedWorkspaceLayout(ref workspace, layout) => { + if let Some((monitor_idx, workspace_idx)) = + self.monitor_workspace_index_by_name(workspace) + { + self.set_workspace_layout_default(monitor_idx, workspace_idx, layout)?; + } + } + SocketMessage::EnsureWorkspaces(monitor_idx, workspace_count) => { + self.ensure_workspaces_for_monitor(monitor_idx, workspace_count)?; + } + SocketMessage::EnsureNamedWorkspaces(monitor_idx, ref names) => { + self.ensure_named_workspaces_for_monitor(monitor_idx, names)?; + } SocketMessage::ToggleFloat => self.toggle_float(false)?, SocketMessage::ResizeWindowEdge(direction, sizing) => { self.resize_window(direction, sizing, self.resize_delta, true)?; @@ -489,6 +705,14 @@ impl WindowManager { StateQuery::FocusedWindowIndex => { self.focused_container()?.focused_window_idx().to_string() } + StateQuery::FocusedWorkspaceName => { + let focused_monitor = + self.focused_monitor().ok_or_eyre("there is no monitor")?; + + focused_monitor + .focused_workspace_name() + .unwrap_or_else(|| focused_monitor.focused_workspace_idx().to_string()) + } StateQuery::Version => build::VERSION.to_string(), StateQuery::FocusedWorkspaceLayout => { let focused_monitor = @@ -1062,6 +1286,8 @@ mod tests { assert_eq!(query(StateQuery::FocusedWorkspaceIndex)?, "0"); assert_eq!(query(StateQuery::FocusedContainerIndex)?, "0"); assert_eq!(query(StateQuery::FocusedWindowIndex)?, "0"); + // a workspace with no name is named by its index + assert_eq!(query(StateQuery::FocusedWorkspaceName)?, "0"); assert_eq!(query(StateQuery::FocusedWorkspaceLayout)?, "BSP"); assert_eq!(query(StateQuery::FocusedContainerKind)?, "Single"); // the version is shadow-rs's description of the build, the package version first diff --git a/komorebi/src/state.rs b/komorebi/src/state.rs index 6aaf51aa..8f3ea9ad 100644 --- a/komorebi/src/state.rs +++ b/komorebi/src/state.rs @@ -149,6 +149,7 @@ impl From<&WindowManager> for State { .workspaces() .iter() .map(|workspace| Workspace { + name: workspace.name.clone(), containers: workspace.containers.clone(), floating_windows: workspace.floating_windows.clone(), layout: workspace.layout.clone(), @@ -170,6 +171,8 @@ impl From<&WindowManager> for State { ws.focus(monitor.workspaces.focused_idx()); ws }, + last_focused_workspace: monitor.last_focused_workspace, + // workspace_names: monitor.workspace_names.clone(), container_padding: monitor.container_padding, workspace_padding: monitor.workspace_padding, }) diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index cb549330..d39b54c8 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -18,7 +18,9 @@ //! ([`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`]). +//! something else made ([`WindowManager::adopt_workspace_change`]). A workspace can be named +//! ([`WindowManager::set_workspace_name`]) and found by its name on any monitor +//! ([`WindowManager::monitor_workspace_index_by_name`]). //! //! [`listen_for_commands`]: crate::process_command::listen_for_commands @@ -327,6 +329,40 @@ impl WindowManager { self.update_focused_workspace(self.mouse_follows_focus, false) } + #[tracing::instrument(skip(self))] + pub fn set_workspace_layout_default( + &mut self, + monitor_idx: usize, + workspace_idx: usize, + layout: DefaultLayout, + ) -> eyre::Result<()> { + tracing::info!("setting workspace layout"); + + let focused_monitor_idx = self.focused_monitor_idx(); + + let monitor = self + .monitors_mut() + .get_mut(monitor_idx) + .ok_or_eyre("there is no monitor")?; + + let focused_workspace_idx = monitor.focused_workspace_idx(); + + let workspace = monitor + .workspaces_mut() + .get_mut(workspace_idx) + .ok_or_eyre("there is no monitor")?; + + workspace.layout = Layout::Default(layout); + + // If this is the focused workspace on a non-focused screen, let's update it + if focused_monitor_idx != monitor_idx && focused_workspace_idx == workspace_idx { + workspace.update()?; + Ok(()) + } else { + Ok(self.update_focused_workspace(false, false)?) + } + } + pub fn focused_workspace_idx(&self) -> eyre::Result { Ok(self .focused_monitor() @@ -348,6 +384,21 @@ impl WindowManager { .ok_or_eyre("there is no workspace") } + #[tracing::instrument(skip(self))] + pub fn new_workspace(&mut self) -> eyre::Result<()> { + tracing::info!("adding new 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(monitor.new_workspace_idx())?; + monitor.load_focused_workspace(mouse_follows_focus)?; + + self.update_focused_workspace(self.mouse_follows_focus, false) + } + pub fn focused_container(&self) -> eyre::Result<&Container> { self.focused_workspace()? .focused_container() @@ -958,6 +1009,36 @@ impl WindowManager { self.update_focused_workspace(false, false) } + #[tracing::instrument(skip(self))] + pub fn focus_monitor(&mut self, idx: usize) -> eyre::Result<()> { + tracing::info!("focusing monitor"); + + if self.monitors().get(idx).is_some() { + self.monitors.focus(idx); + } else { + eyre::bail!("this is not a valid monitor index"); + } + + Ok(()) + } + + #[tracing::instrument(skip(self))] + pub fn monitor_workspace_index_by_name(&mut self, name: &str) -> Option<(usize, usize)> { + tracing::info!("looking up workspace by name"); + + for (monitor_idx, monitor) in self.monitors().iter().enumerate() { + for (workspace_idx, workspace) in monitor.workspaces().iter().enumerate() { + if let Some(workspace_name) = &workspace.name + && workspace_name == name + { + return Option::from((monitor_idx, workspace_idx)); + } + } + } + + None + } + /// Gives the focus to the window of the next (or the previous) container of the focused /// workspace, wrapping around at the ends, and the pointer follows it if /// [`WindowManager::mouse_follows_focus`] is set @@ -1047,8 +1128,9 @@ 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 + /// Make sure the compositor has a virtual desktop for every workspace any monitor has, with + /// the workspaces' names where it has to create them (and "Workspace 2" and so on for a + /// workspace without one) pub fn sync_workspace_desktops(&self) { let count = self .monitors() @@ -1058,7 +1140,15 @@ impl WindowManager { .unwrap_or(1) .max(1); - let names: Vec = (0..count).map(|i| format!("Workspace {}", i + 1)).collect(); + let names: Vec = (0..count) + .map(|i| { + self.monitors() + .iter() + .filter_map(|m| m.workspaces().get(i).and_then(|w| w.name.clone())) + .find(|name| !name.is_empty()) + .unwrap_or_else(|| 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}"); @@ -1143,6 +1233,31 @@ impl WindowManager { self.update_focused_workspace(false, false) } + #[tracing::instrument(skip(self))] + pub fn set_workspace_name( + &mut self, + monitor_idx: usize, + workspace_idx: usize, + name: String, + ) -> eyre::Result<()> { + tracing::info!("setting workspace name"); + + let monitor = self + .monitors_mut() + .get_mut(monitor_idx) + .ok_or_eyre("there is no monitor")?; + + let workspace = monitor + .workspaces_mut() + .get_mut(workspace_idx) + .ok_or_eyre("there is no monitor")?; + + workspace.name = Option::from(name.clone()); + // monitor.workspace_names.insert(workspace_idx, name); + + Ok(()) + } + /// Gives the workspace at `workspace_idx` on the monitor at `monitor_idx` a container padding /// of `size` pixels, around each tile, and tiles the focused workspace again /// @@ -1174,6 +1289,28 @@ impl WindowManager { self.update_focused_workspace(false, false) } + #[tracing::instrument(skip(self))] + pub fn set_workspace_tiling( + &mut self, + monitor_idx: usize, + workspace_idx: usize, + tile: bool, + ) -> eyre::Result<()> { + let monitor = self + .monitors_mut() + .get_mut(monitor_idx) + .ok_or_eyre("there is no monitor")?; + + let workspace = monitor + .workspaces_mut() + .get_mut(workspace_idx) + .ok_or_eyre("there is no monitor")?; + + workspace.tile = tile; + + self.update_focused_workspace(false, false) + } + /// Makes the workspace padding of the focused workspace `adjustment` pixels larger or smaller, /// and tiles it again /// @@ -1226,6 +1363,62 @@ impl WindowManager { self.update_focused_workspace(false, false) } + #[tracing::instrument(skip(self))] + pub fn ensure_workspaces_for_monitor( + &mut self, + monitor_idx: usize, + workspace_count: usize, + ) -> eyre::Result<()> { + tracing::info!("ensuring workspace count"); + + let monitor = self + .monitors_mut() + .get_mut(monitor_idx) + .ok_or_eyre("there is no monitor")?; + + monitor.ensure_workspace_count(workspace_count); + + Ok(()) + } + + #[tracing::instrument(skip(self))] + pub fn ensure_named_workspaces_for_monitor( + &mut self, + monitor_idx: usize, + names: &Vec, + ) -> eyre::Result<()> { + tracing::info!("ensuring workspace count"); + + let monitor = self + .monitors_mut() + .get_mut(monitor_idx) + .ok_or_eyre("there is no monitor")?; + + monitor.ensure_workspace_count(names.len()); + + for (workspace_idx, name) in names.iter().enumerate() { + if let Some(workspace) = monitor.workspaces_mut().get_mut(workspace_idx) { + workspace.name = Option::from(name.clone()); + } + } + + Ok(()) + } + + pub fn remove_focused_workspace(&mut self) -> Option { + let focused_monitor: &mut Monitor = self.focused_monitor_mut()?; + let focused_workspace_idx = focused_monitor.focused_workspace_idx(); + let workspace = focused_monitor.remove_workspace_by_idx(focused_workspace_idx); + if let Err(error) = focused_monitor.focus_workspace(focused_workspace_idx.saturating_sub(1)) + { + tracing::error!( + "Error focusing previous workspace while removing the focused workspace: {}", + error + ); + } + workspace + } + /// Asks the window manager to manage the window that has the focus in the compositor again /// after [`WindowManager::unmanage_focused_window`], by raising a /// [`WindowManagerEvent::Manage`] for it, which is handled like a window that opens @@ -1366,6 +1559,96 @@ mod tests { assert_eq!(wm.focused_workspace_idx().unwrap(), 0); } + #[test] + fn test_remove_focused_workspace() { + let (mut wm, _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); + + { + // focus a workspace which doesn't yet exist should create it + let monitor = wm.focused_monitor_mut().unwrap(); + monitor.focus_workspace(new_workspace_index + 1).unwrap(); + + // Monitor focused workspace should be 2 + assert_eq!(monitor.focused_workspace_idx(), 2); + + // Should have 3 Workspaces + assert_eq!(monitor.workspaces().len(), 3); + } + + // Remove the focused workspace + wm.remove_focused_workspace().unwrap(); + + { + let monitor = wm.focused_monitor_mut().unwrap(); + monitor.focus_workspace(new_workspace_index).unwrap(); + + // Should be focused on workspace 1 + assert_eq!(monitor.focused_workspace_idx(), 1); + + // Should have 2 Workspaces + assert_eq!(monitor.workspaces().len(), 2); + } + } + + #[test] + fn test_set_workspace_name() { + 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); + + // create a new 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); + + // set the name of the first workspace + wm.set_workspace_name(0, 0, "workspace1".to_string()) + .unwrap(); + + // monitor_workspace_index_by_name should return the index of the workspace with the name "workspace1" + let workspace_index = wm.monitor_workspace_index_by_name("workspace1").unwrap(); + + // workspace index 0 should now have the name "workspace1" + assert_eq!(workspace_index.1, 0); + } + #[test] fn test_focus_container_in_cycle_direction() { let (mut wm, _test_context) = setup_window_manager(); @@ -1728,4 +2011,73 @@ mod tests { "Expected an error when trying to float a non-existent window" ); } + + #[test] + fn test_ensure_named_workspace_for_monitor() { + let (mut wm, _context) = setup_window_manager(); + + { + // Create a monitor + let m = monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestMonitor".to_string(), + "TestDeviceID".to_string(), + ); + + // Add the monitor to the window manager + wm.monitors_mut().push_back(m); + } + + { + // Create a monitor + let m = monitor::new( + 1, + Rect::default(), + Rect::default(), + "TestMonitor1".to_string(), + "TestDeviceID1".to_string(), + ); + + // Add the monitor to the window manager + wm.monitors_mut().push_back(m); + } + + // Workspace names list + let mut workspace_names = vec!["Workspace".to_string(), "Workspace1".to_string()]; + + // Ensure workspaces for monitor 1 + wm.ensure_named_workspaces_for_monitor(1, &workspace_names) + .ok(); + + { + // Monitor 1 should have 2 workspaces with names "Workspace" and "Workspace1" + let monitor = wm.monitors().get(1).unwrap(); + let workspaces = monitor.workspaces(); + assert_eq!(workspaces.len(), workspace_names.len()); + for (i, workspace) in workspaces.iter().enumerate() { + assert_eq!(workspace.name, Some(workspace_names[i].clone())); + } + } + + // Add more workspaces to list + workspace_names.push("Workspace2".to_string()); + workspace_names.push("Workspace3".to_string()); + + // Ensure workspaces for monitor 0 + wm.ensure_named_workspaces_for_monitor(0, &workspace_names) + .ok(); + + { + // Monitor 0 should have 4 workspaces with names "Workspace", "Workspace1", + // "Workspace2" and "Workspace3" + let monitor = wm.monitors().front().unwrap(); + let workspaces = monitor.workspaces(); + assert_eq!(workspaces.len(), workspace_names.len()); + for (i, workspace) in workspaces.iter().enumerate() { + assert_eq!(workspace.name, Some(workspace_names[i].clone())); + } + } + } } diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index 4233e559..7ec1771b 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -27,6 +27,7 @@ use std::num::NonZeroUsize; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] pub struct Workspace { + pub name: Option, pub containers: Ring, pub floating_windows: Ring, pub layout: Layout, @@ -55,6 +56,7 @@ impl_ring_elements!(Workspace, Window, "floating_window"); impl Default for Workspace { fn default() -> Self { Self { + name: None, containers: Default::default(), workspace_padding: None, container_padding: None, diff --git a/komorebi/tests/workspace_commands.rs b/komorebi/tests/workspace_commands.rs new file mode 100644 index 00000000..c1f2638e --- /dev/null +++ b/komorebi/tests/workspace_commands.rs @@ -0,0 +1,401 @@ +//! The workspace commands beyond showing a workspace and moving a window to one by its index +//! (`workspaces.rs`), against an in-memory desktop: naming a workspace and finding it by its name, +//! cycling through the workspaces, going back to the last one, adding and closing workspaces, and +//! setting the layout and the tiling of a workspace that need not be in front. The messages go in +//! through [`WindowManager::process_command`]; what comes out is the workspaces of the window +//! manager and what the compositor was asked to show. +//! +//! Window ids are in the 31_000s. + +use komorebi::backend::fake::Command; +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::core::CycleDirection; +use komorebi::core::DefaultLayout; +use komorebi::core::Layout; +use komorebi::core::Rect; +use komorebi::core::SocketMessage; +use komorebi::core::StateQuery; +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; + +const MONITOR: u32 = 1; + +fn added(id: u32) -> WindowManagerEvent { + WindowManagerEvent::Show( + SystemNotification::KWin(KWinNotification::WindowAdded), + Window::from(id), + ) +} + +/// A window manager over `fake`, with a window for each of `ids`, opened in that order +fn desktop_on(fake: FakeBackend, ids: &[u32]) -> (Arc, WindowManager) { + let fake = Arc::new(fake); + let (_sender, receiver) = crossbeam_channel::bounded(1); + // unix socket paths are limited to ~104 bytes on macOS, which the temp dir alone can exceed + static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let socket = std::path::PathBuf::from(format!( + "/tmp/kmw-{}-{}.sock", + std::process::id(), + NEXT.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + )); + + let mut wm = with_backend(fake.clone(), || { + let mut wm = WindowManager::new(receiver, Some(socket)).unwrap(); + wm.init().unwrap(); + wm + }); + for &id in ids { + fake.open_window(id, "foot", "foot", &format!("terminal {id}")); + with_backend(fake.clone(), || wm.process_event(added(id))).unwrap(); + } + + (fake, wm) +} + +/// A window manager over a fake desktop with one 1920x1080 monitor +fn desktop(ids: &[u32]) -> (Arc, WindowManager) { + desktop_on(FakeBackend::with_one_monitor(), ids) +} + +fn send( + fake: &Arc, + wm: &mut WindowManager, + message: SocketMessage, +) -> color_eyre::Result<()> { + with_backend(fake.clone(), || wm.process_command(message, Vec::new())) +} + +fn query(fake: &Arc, wm: &mut WindowManager, query: StateQuery) -> String { + let mut answer = Vec::new(); + with_backend(fake.clone(), || { + wm.process_command(SocketMessage::Query(query), &mut answer) + }) + .unwrap(); + String::from_utf8(answer).unwrap() +} + +/// The ids of the windows of each workspace of the focused monitor +fn windows(wm: &WindowManager) -> Vec> { + wm.focused_monitor() + .unwrap() + .workspaces() + .iter() + .map(|workspace| { + workspace + .containers() + .iter() + .flat_map(|container| container.windows().iter().map(|window| window.id)) + .collect() + }) + .collect() +} + +fn names(wm: &WindowManager) -> Vec> { + wm.focused_monitor() + .unwrap() + .workspaces() + .iter() + .map(|workspace| workspace.name.clone()) + .collect() +} + +#[test] +fn a_named_workspace_is_found_by_its_name_and_shown() { + let (fake, mut wm) = desktop(&[31_001]); + + assert!( + send( + &fake, + &mut wm, + SocketMessage::WorkspaceName(0, 2, String::from("mail")), + ) + .is_err(), + "there is no workspace 2 to name yet" + ); + send(&fake, &mut wm, SocketMessage::EnsureWorkspaces(0, 3)).unwrap(); + send( + &fake, + &mut wm, + SocketMessage::WorkspaceName(0, 2, String::from("mail")), + ) + .unwrap(); + assert_eq!(query(&fake, &mut wm, StateQuery::FocusedWorkspaceName), "0"); + + fake.clear_commands(); + send( + &fake, + &mut wm, + SocketMessage::FocusNamedWorkspace(String::from("mail")), + ) + .unwrap(); + + assert_eq!(wm.focused_workspace_idx().unwrap(), 2); + assert_eq!(fake.shown_workspace(MONITOR), 2); + assert!( + fake.commands() + .contains(&Command::SwitchWorkspace(MONITOR, 2)), + "{:?}", + fake.commands() + ); + assert_eq!( + query(&fake, &mut wm, StateQuery::FocusedWorkspaceName), + "mail" + ); +} + +#[test] +fn a_name_no_workspace_has_changes_nothing() { + let (fake, mut wm) = desktop(&[31_011]); + send(&fake, &mut wm, SocketMessage::EnsureWorkspaces(0, 2)).unwrap(); + fake.clear_commands(); + + send( + &fake, + &mut wm, + SocketMessage::FocusNamedWorkspace(String::from("nowhere")), + ) + .unwrap(); + send( + &fake, + &mut wm, + SocketMessage::NamedWorkspaceTiling(String::from("nowhere"), false), + ) + .unwrap(); + + assert_eq!(wm.focused_workspace_idx().unwrap(), 0); + assert!(fake.commands().is_empty(), "{:?}", fake.commands()); +} + +#[test] +fn ensure_named_workspaces_gives_a_monitor_workspaces_with_those_names() { + let (fake, mut wm) = desktop(&[]); + + send( + &fake, + &mut wm, + SocketMessage::EnsureNamedWorkspaces(0, vec![String::from("web"), String::from("code")]), + ) + .unwrap(); + + assert_eq!( + names(&wm), + [Some(String::from("web")), Some(String::from("code"))] + ); +} + +#[test] +fn cycle_workspace_goes_round_the_workspaces_of_the_monitor() { + let (fake, mut wm) = desktop(&[31_021]); + send(&fake, &mut wm, SocketMessage::EnsureWorkspaces(0, 3)).unwrap(); + let mut shown = vec![]; + + for direction in [ + CycleDirection::Next, + CycleDirection::Next, + CycleDirection::Next, + CycleDirection::Previous, + ] { + send( + &fake, + &mut wm, + SocketMessage::CycleFocusWorkspace(direction), + ) + .unwrap(); + shown.push(( + wm.focused_workspace_idx().unwrap(), + fake.shown_workspace(MONITOR), + )); + } + + assert_eq!(shown, [(1, 1), (2, 2), (0, 0), (2, 2)]); +} + +#[test] +fn cycle_empty_workspace_goes_to_the_next_workspace_without_windows() { + let (fake, mut wm) = desktop(&[31_031, 31_032]); + send(&fake, &mut wm, SocketMessage::EnsureWorkspaces(0, 3)).unwrap(); + // the focused window (31_032) on workspace 1: workspace 2 is the only empty one + send( + &fake, + &mut wm, + SocketMessage::SendContainerToWorkspaceNumber(1), + ) + .unwrap(); + + send( + &fake, + &mut wm, + SocketMessage::CycleFocusEmptyWorkspace(CycleDirection::Next), + ) + .unwrap(); + + assert_eq!(wm.focused_workspace_idx().unwrap(), 2); + assert_eq!(windows(&wm), [vec![31_031], vec![31_032], vec![]]); +} + +#[test] +fn focus_last_workspace_goes_back_and_forth_between_the_last_two() { + let (fake, mut wm) = desktop(&[31_041]); + send(&fake, &mut wm, SocketMessage::FocusWorkspaceNumber(2)).unwrap(); + let mut shown = vec![]; + + for _ in 0..3 { + send(&fake, &mut wm, SocketMessage::FocusLastWorkspace).unwrap(); + shown.push(fake.shown_workspace(MONITOR)); + } + + assert_eq!(shown, [0, 2, 0]); +} + +#[test] +fn send_to_last_workspace_takes_the_window_to_the_one_in_front_before_and_stays() { + let (fake, mut wm) = desktop(&[31_051, 31_052]); + send(&fake, &mut wm, SocketMessage::FocusWorkspaceNumber(1)).unwrap(); + send(&fake, &mut wm, SocketMessage::FocusWorkspaceNumber(0)).unwrap(); + + send(&fake, &mut wm, SocketMessage::SendContainerToLastWorkspace).unwrap(); + + assert_eq!(wm.focused_workspace_idx().unwrap(), 0); + assert_eq!(windows(&wm), [vec![31_051], vec![31_052]]); + assert_eq!(fake.workspace_of(31_052), Some(1)); +} + +#[test] +fn move_to_last_workspace_takes_the_window_to_the_one_in_front_before_and_shows_it() { + let (fake, mut wm) = desktop(&[31_055, 31_056]); + send(&fake, &mut wm, SocketMessage::FocusWorkspaceNumber(1)).unwrap(); + send(&fake, &mut wm, SocketMessage::FocusWorkspaceNumber(0)).unwrap(); + + send(&fake, &mut wm, SocketMessage::MoveContainerToLastWorkspace).unwrap(); + + assert_eq!(wm.focused_workspace_idx().unwrap(), 1); + assert_eq!(fake.shown_workspace(MONITOR), 1); + assert_eq!(windows(&wm), [vec![31_055], vec![31_056]]); + assert!(fake.on_screen(31_056) && !fake.on_screen(31_055)); +} + +#[test] +fn cycle_send_and_cycle_move_take_the_window_to_the_next_workspace() { + let (fake, mut wm) = desktop(&[31_061, 31_062]); + send(&fake, &mut wm, SocketMessage::EnsureWorkspaces(0, 2)).unwrap(); + + send( + &fake, + &mut wm, + SocketMessage::CycleSendContainerToWorkspace(CycleDirection::Next), + ) + .unwrap(); + assert_eq!(wm.focused_workspace_idx().unwrap(), 0); + assert_eq!(windows(&wm), [vec![31_061], vec![31_062]]); + + // from workspace 0, the previous workspace is the last one, and the window goes with it + send( + &fake, + &mut wm, + SocketMessage::CycleMoveContainerToWorkspace(CycleDirection::Previous), + ) + .unwrap(); + assert_eq!(wm.focused_workspace_idx().unwrap(), 1); + assert_eq!(windows(&wm), [vec![], vec![31_062, 31_061]]); + assert_eq!(fake.shown_workspace(MONITOR), 1); +} + +#[test] +fn new_workspace_adds_one_and_close_workspace_removes_it_when_it_is_empty_and_unnamed() { + let (fake, mut wm) = desktop(&[31_071]); + + send(&fake, &mut wm, SocketMessage::NewWorkspace).unwrap(); + assert_eq!(windows(&wm).len(), 2); + assert_eq!(wm.focused_workspace_idx().unwrap(), 1); + assert_eq!(fake.shown_workspace(MONITOR), 1); + + send(&fake, &mut wm, SocketMessage::CloseWorkspace).unwrap(); + assert_eq!(windows(&wm).len(), 1); + assert_eq!(wm.focused_workspace_idx().unwrap(), 0); + assert_eq!(fake.shown_workspace(MONITOR), 0); + + // the last workspace, a workspace with a window, and a named workspace stay + send(&fake, &mut wm, SocketMessage::CloseWorkspace).unwrap(); + assert_eq!(windows(&wm), [vec![31_071]]); + send(&fake, &mut wm, SocketMessage::NewWorkspace).unwrap(); + send( + &fake, + &mut wm, + SocketMessage::WorkspaceName(0, 1, String::from("kept")), + ) + .unwrap(); + send(&fake, &mut wm, SocketMessage::CloseWorkspace).unwrap(); + assert_eq!(names(&wm), [None, Some(String::from("kept"))]); +} + +#[test] +fn focus_workspaces_shows_the_workspace_on_every_monitor() { + let fake = FakeBackend::with_one_monitor(); + let second = Rect { + left: 1920, + top: 0, + right: 1920, + bottom: 1080, + }; + fake.add_monitor(2, "Virtual-1", second, second); + let (fake, mut wm) = desktop_on(fake, &[]); + + send(&fake, &mut wm, SocketMessage::FocusWorkspaceNumbers(1)).unwrap(); + + assert_eq!((fake.shown_workspace(1), fake.shown_workspace(2)), (1, 1)); + assert!( + wm.monitors() + .iter() + .all(|monitor| monitor.focused_workspace_idx() == 1) + ); +} + +#[test] +fn the_layout_and_the_tiling_of_a_workspace_are_set_by_its_index_or_its_name() { + let (fake, mut wm) = desktop(&[31_081, 31_082]); + send( + &fake, + &mut wm, + SocketMessage::EnsureNamedWorkspaces(0, vec![String::from("main"), String::from("side")]), + ) + .unwrap(); + + send( + &fake, + &mut wm, + SocketMessage::WorkspaceLayout(0, 0, DefaultLayout::Rows), + ) + .unwrap(); + let workspace = wm.focused_workspace().unwrap(); + assert_eq!(workspace.layout, Layout::Default(DefaultLayout::Rows)); + // the workspace in front is tiled again: one row above the other + let (first, second) = (fake.rect_of(31_081).unwrap(), fake.rect_of(31_082).unwrap()); + assert_eq!(first.left, second.left); + assert_ne!(first.top, second.top); + + send( + &fake, + &mut wm, + SocketMessage::NamedWorkspaceLayout(String::from("side"), DefaultLayout::Columns), + ) + .unwrap(); + send( + &fake, + &mut wm, + SocketMessage::NamedWorkspaceTiling(String::from("main"), false), + ) + .unwrap(); + send(&fake, &mut wm, SocketMessage::WorkspaceTiling(0, 1, false)).unwrap(); + + let workspaces = wm.focused_monitor().unwrap().workspaces(); + assert_eq!( + workspaces[1].layout, + Layout::Default(DefaultLayout::Columns) + ); + assert!(!workspaces[0].tile && !workspaces[1].tile); +} diff --git a/komorebic/Cargo.toml b/komorebic/Cargo.toml index f4c5d1e7..881baeb7 100644 --- a/komorebic/Cargo.toml +++ b/komorebic/Cargo.toml @@ -19,3 +19,6 @@ sysinfo = { workspace = true } [features] default = ["schemars"] schemars = ["komorebi-client/default"] + +[lints.rust] +unexpected_cfgs = { level = "warn", check-cfg = ['cfg(FALSE)'] } diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs index e030edbc..54dac229 100644 --- a/komorebic/src/main.rs +++ b/komorebic/src/main.rs @@ -33,6 +33,15 @@ //! - `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. +//! `cycle-workspace`, `cycle-empty-workspace`, `cycle-move-to-workspace` and +//! `cycle-send-to-workspace` go to the next or the previous workspace, `focus-last-workspace`, +//! `move-to-last-workspace` and `send-to-last-workspace` to the one that was in front before, +//! `focus-workspaces` shows a workspace on every monitor, and `new-workspace` and +//! `close-workspace` add a workspace and remove an empty one. +//! - `workspace-name` names a workspace, which `focus-named-workspace`, `named-workspace-layout` +//! and `named-workspace-tiling` find by its name; `workspace-layout` and `workspace-tiling` set +//! the layout and the tiling of a workspace by its index, and `ensure-workspaces` and +//! `ensure-named-workspaces` give a monitor workspaces up to a number, or with names. //! //! `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 @@ -113,6 +122,10 @@ gen_enum_subcommand_args! { PreselectDirection: OperationDirection, CycleFocus: CycleDirection, CycleMove: CycleDirection, + CycleMoveToWorkspace: CycleDirection, + CycleSendToWorkspace: CycleDirection, + CycleWorkspace: CycleDirection, + CycleEmptyWorkspace: CycleDirection, FlipLayout: Axis, ChangeLayout: DefaultLayout, CycleLayout: CycleDirection, @@ -140,6 +153,86 @@ gen_target_subcommand_args! { MoveToWorkspace, SendToWorkspace, FocusWorkspace, + FocusWorkspaces, +} + +macro_rules! gen_named_target_subcommand_args { + // SubCommand Pattern + ( $( $name:ident ),+ $(,)? ) => { + $( + #[derive(clap::Parser)] + pub struct $name { + /// Target workspace name + workspace: String, + } + )+ + }; +} + +gen_named_target_subcommand_args! { + FocusNamedWorkspace, +} + +// Thanks to @danielhenrymantilla for showing me how to use cfg_attr with an optional argument like +// this on the Rust Programming Language Community Discord Server +macro_rules! gen_workspace_subcommand_args { + // Workspace Property: #[enum] Value Enum (if the value is an Enum) + // Workspace Property: Value Type (if the value is anything else) + ( $( $name:ident: $(#[enum] $(@$value_enum:tt)?)? $value:ty ),+ $(,)? ) => ( + pastey::paste! { + $( + #[derive(clap::Parser)] + pub struct [] { + /// Monitor index (zero-indexed) + monitor: usize, + + /// Workspace index on the specified monitor (zero-indexed) + workspace: usize, + + $(#[clap(value_enum)] $($value_enum)?)? + #[cfg_attr( + all($(FALSE $($value_enum)?)?), + doc = ""$name " of the workspace as a "$value "" + )] + value: $value, + } + )+ + } + ) +} + +gen_workspace_subcommand_args! { + Name: String, + Layout: #[enum] DefaultLayout, + Tiling: #[enum] BooleanState, +} + +macro_rules! gen_named_workspace_subcommand_args { + // Workspace Property: #[enum] Value Enum (if the value is an Enum) + // Workspace Property: Value Type (if the value is anything else) + ( $( $name:ident: $(#[enum] $(@$value_enum:tt)?)? $value:ty ),+ $(,)? ) => ( + pastey::paste! { + $( + #[derive(clap::Parser)] + pub struct [] { + /// Target workspace name + workspace: String, + + $(#[clap(value_enum)] $($value_enum)?)? + #[cfg_attr( + all($(FALSE $($value_enum)?)?), + doc = ""$name " of the workspace as a "$value "" + )] + value: $value, + } + )+ + } + ) +} + +gen_named_workspace_subcommand_args! { + Layout: #[enum] DefaultLayout, + Tiling: #[enum] BooleanState, } macro_rules! gen_focused_workspace_padding_subcommand_args { @@ -303,6 +396,22 @@ struct WorkspaceWorkAreaOffset { bottom: i32, } +#[derive(Parser)] +struct EnsureWorkspaces { + /// Monitor index (zero-indexed) + monitor: usize, + /// Number of desired workspaces + workspace_count: usize, +} + +#[derive(Parser)] +struct EnsureNamedWorkspaces { + /// Monitor index (zero-indexed) + monitor: usize, + /// Names of desired workspaces + names: Vec, +} + #[derive(Parser)] #[allow(clippy::struct_excessive_bools)] struct Start { @@ -451,12 +560,40 @@ enum SubCommand { /// Move the focused window to the specified workspace #[clap(arg_required_else_help = true)] MoveToWorkspace(MoveToWorkspace), + /// Move the focused window to the workspace in the given cycle direction + #[clap(arg_required_else_help = true)] + CycleMoveToWorkspace(CycleMoveToWorkspace), /// Send the focused window to the specified workspace #[clap(arg_required_else_help = true)] SendToWorkspace(SendToWorkspace), + /// Send the focused window to the workspace in the given cycle direction + #[clap(arg_required_else_help = true)] + CycleSendToWorkspace(CycleSendToWorkspace), + /// Send the focused window to the last focused monitor workspace + SendToLastWorkspace, + /// Move the focused window to the last focused monitor workspace + MoveToLastWorkspace, + /// Focus the last focused workspace on the focused monitor + FocusLastWorkspace, /// Focus the specified workspace on the focused monitor #[clap(arg_required_else_help = true)] FocusWorkspace(FocusWorkspace), + /// Focus the specified workspace on all monitors + #[clap(arg_required_else_help = true)] + FocusWorkspaces(FocusWorkspaces), + /// Focus the specified workspace + #[clap(arg_required_else_help = true)] + FocusNamedWorkspace(FocusNamedWorkspace), + /// Close the focused workspace (must be empty and unnamed) + CloseWorkspace, + /// Focus the workspace in the given cycle direction + #[clap(arg_required_else_help = true)] + CycleWorkspace(CycleWorkspace), + /// Focus the next empty workspace in the given cycle direction (if one exists) + #[clap(arg_required_else_help = true)] + CycleEmptyWorkspace(CycleWorkspace), + /// Create and append a new workspace on the focused monitor + NewWorkspace, /// Set the resize delta (used by resize-edge and resize-axis) #[clap(arg_required_else_help = true)] ResizeDelta(ResizeDelta), @@ -514,12 +651,41 @@ enum SubCommand { PromoteWindow(PromoteWindow), /// Force the retiling of all managed windows Retile, + /// Create at least this many workspaces for the specified monitor + #[clap(arg_required_else_help = true)] + EnsureWorkspaces(EnsureWorkspaces), + /// Create these many named workspaces for the specified monitor + #[clap(arg_required_else_help = true)] + EnsureNamedWorkspaces(EnsureNamedWorkspaces), /// Set the container padding for the specified workspace #[clap(arg_required_else_help = true)] ContainerPadding(ContainerPadding), /// Set the workspace padding for the specified workspace #[clap(arg_required_else_help = true)] WorkspacePadding(WorkspacePadding), + /// Set the layout for the specified workspace + #[clap(arg_required_else_help = true)] + WorkspaceLayout(WorkspaceLayout), + /// Set the layout for the specified workspace + #[clap(arg_required_else_help = true)] + NamedWorkspaceLayout(NamedWorkspaceLayout), + // /// Set a custom layout for the specified workspace + // #[clap(hide = true)] + // #[clap(arg_required_else_help = true)] + // WorkspaceCustomLayout(WorkspaceCustomLayout), + // /// Set a custom layout for the specified workspace + // #[clap(hide = true)] + // #[clap(arg_required_else_help = true)] + // NamedWorkspaceCustomLayout(NamedWorkspaceCustomLayout), + /// Enable or disable window tiling for the specified workspace + #[clap(arg_required_else_help = true)] + WorkspaceTiling(WorkspaceTiling), + /// Enable or disable window tiling for the specified workspace + #[clap(arg_required_else_help = true)] + NamedWorkspaceTiling(NamedWorkspaceTiling), + /// Set the workspace name for the specified workspace + #[clap(arg_required_else_help = true)] + WorkspaceName(WorkspaceName), /// Toggle the paused state for all window tiling TogglePause, /// Toggle window tiling on the focused workspace @@ -703,6 +869,26 @@ fn main() -> eyre::Result<()> { SubCommand::FocusWorkspace(args) => { send_message(&SocketMessage::FocusWorkspaceNumber(args.target))?; } + SubCommand::FocusLastWorkspace => { + send_message(&SocketMessage::FocusLastWorkspace)?; + } + SubCommand::FocusWorkspaces(args) => { + send_message(&SocketMessage::FocusWorkspaceNumbers(args.target))?; + } + SubCommand::FocusNamedWorkspace(args) => { + send_message(&SocketMessage::FocusNamedWorkspace(args.workspace))?; + } + SubCommand::CloseWorkspace => { + send_message(&SocketMessage::CloseWorkspace)?; + } + SubCommand::CycleWorkspace(args) => { + send_message(&SocketMessage::CycleFocusWorkspace(args.cycle_direction))?; + } + SubCommand::CycleEmptyWorkspace(args) => { + send_message(&SocketMessage::CycleFocusEmptyWorkspace( + args.cycle_direction, + ))?; + } SubCommand::ToggleFloat => { send_message(&SocketMessage::ToggleFloat)?; } @@ -715,9 +901,25 @@ fn main() -> eyre::Result<()> { SubCommand::MoveToWorkspace(args) => { send_message(&SocketMessage::MoveContainerToWorkspaceNumber(args.target))?; } + SubCommand::CycleMoveToWorkspace(args) => { + send_message(&SocketMessage::CycleMoveContainerToWorkspace( + args.cycle_direction, + ))?; + } SubCommand::SendToWorkspace(args) => { send_message(&SocketMessage::SendContainerToWorkspaceNumber(args.target))?; } + SubCommand::CycleSendToWorkspace(args) => { + send_message(&SocketMessage::CycleSendContainerToWorkspace( + args.cycle_direction, + ))?; + } + SubCommand::MoveToLastWorkspace => { + send_message(&SocketMessage::MoveContainerToLastWorkspace)?; + } + SubCommand::SendToLastWorkspace => { + send_message(&SocketMessage::SendContainerToLastWorkspace)?; + } SubCommand::Retile => { send_message(&SocketMessage::Retile)?; } @@ -781,6 +983,16 @@ fn main() -> eyre::Result<()> { SubCommand::ManageRule(args) => { send_message(&SocketMessage::ManageRule(args.identifier, args.id))?; } + SubCommand::NewWorkspace => { + send_message(&SocketMessage::NewWorkspace)?; + } + SubCommand::WorkspaceName(name) => { + send_message(&SocketMessage::WorkspaceName( + name.monitor, + name.workspace, + name.value, + ))?; + } SubCommand::ResizeDelta(args) => { send_message(&SocketMessage::ResizeDelta(args.pixels))?; } @@ -848,6 +1060,33 @@ fn main() -> eyre::Result<()> { args.adjustment, ))?; } + SubCommand::WorkspaceLayout(args) => { + send_message(&SocketMessage::WorkspaceLayout( + args.monitor, + args.workspace, + args.value, + ))?; + } + SubCommand::NamedWorkspaceLayout(args) => { + send_message(&SocketMessage::NamedWorkspaceLayout( + args.workspace, + args.value, + ))?; + } + + SubCommand::WorkspaceTiling(args) => { + send_message(&SocketMessage::WorkspaceTiling( + args.monitor, + args.workspace, + args.value.into(), + ))?; + } + SubCommand::NamedWorkspaceTiling(args) => { + send_message(&SocketMessage::NamedWorkspaceTiling( + args.workspace, + args.value.into(), + ))?; + } SubCommand::ScrollingLayoutColumns(args) => { send_message(&SocketMessage::ScrollingLayoutColumns(args.count))?; } @@ -860,6 +1099,18 @@ fn main() -> eyre::Result<()> { send_message(&SocketMessage::LayoutRatios(args.columns, args.rows))?; } } + SubCommand::EnsureWorkspaces(workspaces) => { + send_message(&SocketMessage::EnsureWorkspaces( + workspaces.monitor, + workspaces.workspace_count, + ))?; + } + SubCommand::EnsureNamedWorkspaces(args) => { + send_message(&SocketMessage::EnsureNamedWorkspaces( + args.monitor, + args.names, + ))?; + } SubCommand::UnmanagedWindowOperationBehaviour(args) => { send_message(&SocketMessage::UnmanagedWindowOperationBehaviour( args.operation_behaviour, diff --git a/komorebic/tests/cli.rs b/komorebic/tests/cli.rs index 414670d2..3b98916f 100644 --- a/komorebic/tests/cli.rs +++ b/komorebic/tests/cli.rs @@ -440,6 +440,80 @@ fn the_workspace_subcommands_send_the_index_they_are_given() { ); } +#[test] +fn the_other_workspace_subcommands_send_what_they_are_given() { + sends( + &["cycle-workspace", "next"], + r#"{"type":"CycleFocusWorkspace","content":"Next"}"#, + ); + sends( + &["cycle-empty-workspace", "previous"], + r#"{"type":"CycleFocusEmptyWorkspace","content":"Previous"}"#, + ); + sends( + &["cycle-move-to-workspace", "next"], + r#"{"type":"CycleMoveContainerToWorkspace","content":"Next"}"#, + ); + sends( + &["cycle-send-to-workspace", "previous"], + r#"{"type":"CycleSendContainerToWorkspace","content":"Previous"}"#, + ); + sends( + &["focus-last-workspace"], + r#"{"type":"FocusLastWorkspace"}"#, + ); + sends( + &["move-to-last-workspace"], + r#"{"type":"MoveContainerToLastWorkspace"}"#, + ); + sends( + &["send-to-last-workspace"], + r#"{"type":"SendContainerToLastWorkspace"}"#, + ); + sends( + &["focus-workspaces", "2"], + r#"{"type":"FocusWorkspaceNumbers","content":2}"#, + ); + sends(&["new-workspace"], r#"{"type":"NewWorkspace"}"#); + sends(&["close-workspace"], r#"{"type":"CloseWorkspace"}"#); +} + +#[test] +fn the_named_workspace_subcommands_send_the_names_they_are_given() { + sends( + &["workspace-name", "0", "1", "mail"], + r#"{"type":"WorkspaceName","content":[0,1,"mail"]}"#, + ); + sends( + &["focus-named-workspace", "mail"], + r#"{"type":"FocusNamedWorkspace","content":"mail"}"#, + ); + sends( + &["ensure-workspaces", "0", "3"], + r#"{"type":"EnsureWorkspaces","content":[0,3]}"#, + ); + sends( + &["ensure-named-workspaces", "0", "web", "code"], + r#"{"type":"EnsureNamedWorkspaces","content":[0,["web","code"]]}"#, + ); + sends( + &["workspace-layout", "0", "1", "columns"], + r#"{"type":"WorkspaceLayout","content":[0,1,"Columns"]}"#, + ); + sends( + &["named-workspace-layout", "mail", "rows"], + r#"{"type":"NamedWorkspaceLayout","content":["mail","Rows"]}"#, + ); + sends( + &["workspace-tiling", "0", "1", "disable"], + r#"{"type":"WorkspaceTiling","content":[0,1,false]}"#, + ); + sends( + &["named-workspace-tiling", "mail", "enable"], + r#"{"type":"NamedWorkspaceTiling","content":["mail",true]}"#, + ); +} + #[test] fn without_a_daemon_a_question_fails() { let runtime = Runtime::new(); @@ -484,15 +558,25 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "cancel-preselect.md", "change-layout.md", "clear-session-float-rules.md", + "close-workspace.md", "close.md", "completions.md", "container-padding.md", + "cycle-empty-workspace.md", "cycle-focus.md", "cycle-layout.md", + "cycle-move-to-workspace.md", "cycle-move.md", + "cycle-send-to-workspace.md", + "cycle-workspace.md", "data-directory.md", + "ensure-named-workspaces.md", + "ensure-workspaces.md", "flip-layout.md", + "focus-last-workspace.md", + "focus-named-workspace.md", "focus-workspace.md", + "focus-workspaces.md", "focus.md", "focused-workspace-container-padding.md", "focused-workspace-padding.md", @@ -508,8 +592,12 @@ 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-last-workspace.md", "move-to-workspace.md", "move.md", + "named-workspace-layout.md", + "named-workspace-tiling.md", + "new-workspace.md", "preselect-direction.md", "promote-focus.md", "promote-swap.md", @@ -524,6 +612,7 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "retile.md", "save-resize.md", "scrolling-layout-columns.md", + "send-to-last-workspace.md", "send-to-workspace.md", "session-float-rule.md", "session-float-rules.md", @@ -540,7 +629,10 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "unmanage.md", "unmanaged-window-operation-behaviour.md", "unsubscribe-socket.md", + "workspace-layout.md", + "workspace-name.md", "workspace-padding.md", + "workspace-tiling.md", "workspace-work-area-offset.md", ] ); diff --git a/nix/tests/vm/suites/commands/test.py b/nix/tests/vm/suites/commands/test.py index f13df547..e57dd17a 100644 --- a/nix/tests/vm/suites/commands/test.py +++ b/nix/tests/vm/suites/commands/test.py @@ -192,12 +192,43 @@ toggle-tiling toggle-tiling toggle-pause toggle-pause +ensure-named-workspaces 0 one two three +workspace-name 0 0 one +ensure-workspaces 0 3 +workspace-tiling 0 0 disable +workspace-tiling 0 0 enable +named-workspace-tiling one disable +named-workspace-tiling one enable focus-workspace 1 focus-workspace 0 +focus-last-workspace +focus-last-workspace +focus-workspaces 1 +focus-workspaces 0 +cycle-workspace next +cycle-workspace previous +cycle-empty-workspace next +focus-workspace 0 +focus-named-workspace two +focus-named-workspace one send-to-workspace 1 focus-workspace 1 move-to-workspace 0 focus-workspace 0 +cycle-send-to-workspace next +focus-workspace 1 +cycle-move-to-workspace previous +focus-workspace 0 +send-to-last-workspace +move-to-last-workspace +focus-workspace 0 +new-workspace +close-workspace +focus-workspace 0 +workspace-layout 0 0 columns +workspace-layout 0 0 bsp +named-workspace-layout one columns +named-workspace-layout one bsp 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 @@ -331,6 +362,7 @@ for query in [ "focused-workspace-index", "focused-container-index", "focused-window-index", + "focused-workspace-name", "focused-workspace-layout", "focused-container-kind", "version",