From efcc90d279567d50f948b8cffa4bf9c03a931c39 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 19:48:45 -0700 Subject: [PATCH] feat(wm): workspace rules A workspace rule sends the windows of an application to a workspace: an initial rule once, when komorebi first sees the window, and a permanent rule every time, so that a window the user takes away goes back. A rule is a rule on the window's executable, class, title or path, with a monitor and a workspace index, or the name of a workspace. It comes from komorebi.json (workspace_rules and initial_workspace_rules of a workspace, made again from the file each time it is read) or from komorebic (workspace-rule, initial-workspace-rule, their named forms, and the commands that clear and enforce them). The window manager looks at the rules before it handles each event about a window it manages, and again when the configuration is loaded, so the windows that were open when the daemon started are sent too. A window that leaves the workspace in front is taken out of the layout and hidden, as the back of a stack is, and it is put on the desktop of its new workspace, which is what it comes back to and is tiled on when that workspace is shown. A window that moves between workspaces that are not in front is put on the desktop of its new workspace as well. A floating window that goes to another monitor is moved onto it, and a workspace that does not exist yet is made. --- README.md | 5 +- docs/cli/clear-all-workspace-rules.md | 10 + docs/cli/clear-named-workspace-rules.md | 14 + docs/cli/clear-workspace-rules.md | 17 + docs/cli/enforce-workspace-rules.md | 10 + docs/cli/initial-named-workspace-rule.md | 24 + docs/cli/initial-workspace-rule.md | 27 ++ docs/cli/named-workspace-rule.md | 24 + docs/cli/workspace-rule.md | 27 ++ docs/dev/ARCHITECTURE.md | 30 +- docs/example-configurations.md | 9 +- docs/index.md | 4 +- docs/komorebi.example.json | 9 +- docs/usage/configuration.md | 9 +- docs/usage/workspace-rules.md | 83 ++++ komorebi/src/core/mod.rs | 8 + komorebi/src/lib.rs | 5 + komorebi/src/process_command.rs | 114 +++++ komorebi/src/process_event.rs | 6 + komorebi/src/state.rs | 9 +- komorebi/src/static_config.rs | 86 +++- komorebi/src/window_manager.rs | 334 ++++++++++++++ komorebi/src/workspace.rs | 33 +- komorebi/tests/workspace_rules.rs | 431 ++++++++++++++++++ komorebic/src/main.rs | 131 +++++- komorebic/tests/cli.rs | 8 + nix/komorebi-options.nix | 12 +- nix/tests/default.nix | 5 +- nix/tests/komorebi-example.nix | 1 + nix/tests/vm/suites/commands/test.py | 8 + .../vm/suites/workspace-rules/default.nix | 5 + nix/tests/vm/suites/workspace-rules/test.py | 190 ++++++++ schema.json | 20 + 33 files changed, 1694 insertions(+), 14 deletions(-) create mode 100644 docs/cli/clear-all-workspace-rules.md create mode 100644 docs/cli/clear-named-workspace-rules.md create mode 100644 docs/cli/clear-workspace-rules.md create mode 100644 docs/cli/enforce-workspace-rules.md create mode 100644 docs/cli/initial-named-workspace-rule.md create mode 100644 docs/cli/initial-workspace-rule.md create mode 100644 docs/cli/named-workspace-rule.md create mode 100644 docs/cli/workspace-rule.md create mode 100644 docs/usage/workspace-rules.md create mode 100644 komorebi/tests/workspace_rules.rs create mode 100644 nix/tests/vm/suites/workspace-rules/default.nix create mode 100644 nix/tests/vm/suites/workspace-rules/test.py diff --git a/README.md b/README.md index bda25691..e5f4ef4a 100644 --- a/README.md +++ b/README.md @@ -177,7 +177,10 @@ on events and orders until it is resumed. The padding commands set the gaps arou 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. +`session-float-rule` floats the focused window and the windows like it, and a +workspace rule (`workspace-rule`, `initial-workspace-rule`, their named forms, +or `workspace_rules` in `komorebi.json`) sends the windows of an application to a +workspace, once or whenever the window manager looks, which it does at every event. `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; their `cycle-` and `-last-workspace` forms go to the next, diff --git a/docs/cli/clear-all-workspace-rules.md b/docs/cli/clear-all-workspace-rules.md new file mode 100644 index 00000000..7cb5c896 --- /dev/null +++ b/docs/cli/clear-all-workspace-rules.md @@ -0,0 +1,10 @@ +```text +Remove all application association rules for all workspaces + +Usage: clear-all-workspace-rules + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/clear-named-workspace-rules.md b/docs/cli/clear-named-workspace-rules.md new file mode 100644 index 00000000..6beac719 --- /dev/null +++ b/docs/cli/clear-named-workspace-rules.md @@ -0,0 +1,14 @@ +```text +Remove all application association rules for a named workspace + +Usage: clear-named-workspace-rules + +Arguments: + + Name of a workspace + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/clear-workspace-rules.md b/docs/cli/clear-workspace-rules.md new file mode 100644 index 00000000..37eca2b3 --- /dev/null +++ b/docs/cli/clear-workspace-rules.md @@ -0,0 +1,17 @@ +```text +Remove all application association rules for a workspace by monitor and workspace index + +Usage: clear-workspace-rules + +Arguments: + + Monitor index (zero-indexed) + + + Workspace index on the specified monitor (zero-indexed) + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/enforce-workspace-rules.md b/docs/cli/enforce-workspace-rules.md new file mode 100644 index 00000000..9d9e3991 --- /dev/null +++ b/docs/cli/enforce-workspace-rules.md @@ -0,0 +1,10 @@ +```text +Enforce all workspace rules, including initial workspace rules that have already been applied + +Usage: enforce-workspace-rules + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/initial-named-workspace-rule.md b/docs/cli/initial-named-workspace-rule.md new file mode 100644 index 00000000..80781087 --- /dev/null +++ b/docs/cli/initial-named-workspace-rule.md @@ -0,0 +1,24 @@ +```text +Add a rule to associate an application with a named workspace on first show + +Usage: initial-named-workspace-rule + +Arguments: + + Possible values: + - exe: Executable name + - class: Role or subrole + - title: Window title + - path: Executable path + + + Identifier as a string + + + Name of a workspace + +Options: + -h, --help + Print help (see a summary with '-h') + +``` diff --git a/docs/cli/initial-workspace-rule.md b/docs/cli/initial-workspace-rule.md new file mode 100644 index 00000000..45490712 --- /dev/null +++ b/docs/cli/initial-workspace-rule.md @@ -0,0 +1,27 @@ +```text +Add a rule to associate an application with a workspace on first show + +Usage: initial-workspace-rule + +Arguments: + + Possible values: + - exe: Executable name + - class: Role or subrole + - title: Window title + - path: Executable path + + + Identifier as a string + + + Monitor index (zero-indexed) + + + Workspace index on the specified monitor (zero-indexed) + +Options: + -h, --help + Print help (see a summary with '-h') + +``` diff --git a/docs/cli/named-workspace-rule.md b/docs/cli/named-workspace-rule.md new file mode 100644 index 00000000..10a2935f --- /dev/null +++ b/docs/cli/named-workspace-rule.md @@ -0,0 +1,24 @@ +```text +Add a rule to associate an application with a named workspace + +Usage: named-workspace-rule + +Arguments: + + Possible values: + - exe: Executable name + - class: Role or subrole + - title: Window title + - path: Executable path + + + Identifier as a string + + + Name of a workspace + +Options: + -h, --help + Print help (see a summary with '-h') + +``` diff --git a/docs/cli/workspace-rule.md b/docs/cli/workspace-rule.md new file mode 100644 index 00000000..21e54393 --- /dev/null +++ b/docs/cli/workspace-rule.md @@ -0,0 +1,27 @@ +```text +Add a rule to associate an application with a workspace + +Usage: workspace-rule + +Arguments: + + Possible values: + - exe: Executable name + - class: Role or subrole + - title: Window title + - path: Executable path + + + Identifier as a string + + + Monitor index (zero-indexed) + + + Workspace index on the specified monitor (zero-indexed) + +Options: + -h, --help + Print help (see a summary with '-h') + +``` diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index 5cf83348..6a7ee5b8 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -683,6 +683,21 @@ defaults. A **rule** is an entry of one of the process-wide lists. A workspace's `layout_rules`, `work_area_offset_rules` and `window_container_behaviour_rules` are fields of the [`Workspace`], which [`Workspace::update`] reads each time it tiles. +A workspace's `workspace_rules` and `initial_workspace_rules` are not fields of the window manager +but entries of [`WORKSPACE_MATCHING_RULES`], which [`StaticConfig::postload`] and +[`StaticConfig::reload`] empty and fill from the file, and the messages `WorkspaceRule`, +`InitialWorkspaceRule` and their named forms add to. [`WindowManager::enforce_workspace_rules`] reads +them: for each window in view (the top of each container, and the floating windows) that a rule +matches, on a workspace other than the rule's, it makes an operation, takes the window out of its +workspace (and hides it when that is the focused one), puts it in the target (making the workspace +if it is not there, and taking a floating window to the target's monitor), tiles the focused +workspace again if the window left it, and has each target monitor put its windows on the desktops +of their workspaces +([`Monitor::assign_windows_to_workspaces`]). `handle_event` calls it before every event about a +window it manages, and `postload`, `reload` and `EnforceWorkspaceRules` call it too. An `initial_only` +rule moves a window once: the window id goes into [`WindowManager::already_moved_window_handles`], +which `EnforceWorkspaceRules` empties and a destroy removes the id from. + `ReplaceConfiguration` is the third way in: [`WindowManager::process_command`] checks that the file reads as a [`StaticConfig`], pauses the old window manager and brings back the windows it hid ([`WindowManager::restore_all_windows`]), makes a new window manager from the file @@ -721,6 +736,10 @@ goes the other way, for `GenerateStaticConfig`. | `schema.json` and `schema.asc.json` are what the Rust types print | Nix check `schema-fresh`, and a test that compares them with `komorebic`'s output | `schema-fresh`, `the_schema_files_of_the_repository_are_what_the_subcommands_print` | `just jsonschema` | | The options the module is typed with are made from the committed schema | the hash of `schema.json` in the first line of `nix/komorebi-options.nix`, compared by `schema-fresh` | `schema-fresh` | `just nixgen` | | The example, in Nix and in JSON, follows the schema, and says the same in both | Nix check `nix-options-validation`: the options evaluated against the Nix example, both examples checked with `check-jsonschema`, and one contained in the other | `nix-options-validation` | none | +| A window a workspace rule names ends on its workspace, and on that workspace's desktop once the workspace is shown | framework path: [`WindowManager::enforce_workspace_rules`] moves it in the model, and has the target monitor put it on the desktop | `a_rule_sends_the_window_of_an_application_to_its_workspace`, `a_window_a_rule_moves_between_workspaces_that_are_out_of_view_is_put_on_the_new_desktop`, `vm-workspace-rules` | none | +| A window a workspace rule takes off the workspace in front is out of sight until its workspace is shown | framework path: [`WindowManager::enforce_workspace_rules`] hides it, and showing the workspace restores it | `a_rule_sends_the_window_of_an_application_to_its_workspace`, `vm-workspace-rules` | none | +| An initial rule sends a window once, a permanent one every time | framework path: the window ids an initial rule has sent are in [`WindowManager::already_moved_window_handles`] until the window closes | `an_initial_rule_moves_a_window_once_and_a_permanent_one_every_time`, `vm-workspace-rules` | `komorebic enforce-workspace-rules` forgets them | +| The rules of the configuration are the file's, and the windows that are open follow them | framework path: [`StaticConfig::postload`] and [`StaticConfig::reload`] empty the list, fill it from the file and enforce it | `the_rules_of_komorebi_json_send_the_windows_that_are_open_and_come_out_in_the_generated_file`, `vm-workspace-rules` | none | | Replacing the configuration with a file that does not read leaves the window manager as it was | framework path: the arm reads the file as a [`StaticConfig`] before it makes anything | `replacing_the_configuration_makes_the_window_manager_again_from_the_new_file` | none | | Replacing the configuration leaves no window hidden | framework path: the arm brings back the windows the old window manager hid ([`WindowManager::restore_all_windows`]) before the new one reads the desktop | `replacing_the_configuration_makes_the_window_manager_again_from_the_new_file` | none | | `quickstart` never writes over a file without being told to | framework path: every file goes through `write_file_with_prompt`, which keeps the file unless the answer is `y` or `yes` | `quickstart_writes_the_example_files_and_asks_before_it_overwrites_one` | none | @@ -1037,7 +1056,9 @@ A window is shown, and ends up on a tile: [`komorebi/tests/config_parity.rs`](../../komorebi/tests/config_parity.rs) the files of other platforms and the example, which load; [`komorebi/tests/replace_configuration.rs`](../../komorebi/tests/replace_configuration.rs) - the `ReplaceConfiguration` message; [`komorebi/tests/schemas.rs`](../../komorebi/tests/schemas.rs) the schemas the daemon answers + the `ReplaceConfiguration` message; + [`komorebi/tests/workspace_rules.rs`](../../komorebi/tests/workspace_rules.rs) the workspace + rules; [`komorebi/tests/schemas.rs`](../../komorebi/tests/schemas.rs) the schemas the daemon answers with; [`schema.json`](../../schema.json), [`schema.asc.json`](../../schema.asc.json) and [`nix/komorebi-options.nix`](../../nix/komorebi-options.nix), which are generated; [`nix/tests/default.nix`](../../nix/tests/default.nix) and @@ -1111,6 +1132,9 @@ A window is shown, and ends up on a tile: a stack hides, the behavior of new windows and the float override, against the fake; [`nix/tests/vm/suites/stacks`](../../nix/tests/vm/suites/stacks/test.py), the same in a real KWin, with the parking desktop, a crash and a stop. +- [`nix/tests/vm/suites/workspace-rules`](../../nix/tests/vm/suites/workspace-rules/test.py): + workspace rules sending windows to other workspaces of a real KWin, out of sight on the parking + desktop until the workspace is shown. - [`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 @@ -1128,6 +1152,10 @@ A window is shown, and ends up on a tile: [`StaticConfig::reload`]: ../../komorebi/src/static_config.rs [`Workspace::load_static_config`]: ../../komorebi/src/workspace.rs [`HOME_DIR`]: ../../komorebi/src/lib.rs +[`WORKSPACE_MATCHING_RULES`]: ../../komorebi/src/lib.rs +[`WindowManager::enforce_workspace_rules`]: ../../komorebi/src/window_manager.rs +[`WindowManager::already_moved_window_handles`]: ../../komorebi/src/window_manager.rs +[`Monitor::assign_windows_to_workspaces`]: ../../komorebi/src/monitor.rs [`LAYOUT_DEFAULTS`]: ../../komorebi/src/lib.rs [`IGNORE_IDENTIFIERS`]: ../../komorebi/src/lib.rs [`MANAGE_IDENTIFIERS`]: ../../komorebi/src/lib.rs diff --git a/docs/example-configurations.md b/docs/example-configurations.md index 15303d33..9ba5ac25 100644 --- a/docs/example-configurations.md +++ b/docs/example-configurations.md @@ -27,7 +27,14 @@ different layout. This page has the file as it is: "workspaces": [ { "name": "I", - "layout": "BSP" + "layout": "BSP", + "initial_workspace_rules": [ +// { +// "kind": "Exe", +// "id": "firefox", +// "matching_strategy": "Equals" +// } + ] }, { "name": "II", diff --git a/docs/index.md b/docs/index.md index 6a7e1ed1..7a9b0fad 100644 --- a/docs/index.md +++ b/docs/index.md @@ -49,7 +49,9 @@ 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. +are KWin's virtual desktops, and how to show another or move a window to one, and +[Workspace rules](usage/workspace-rules.md) how to have the windows of an application go to a +workspace by themselves. [Configuration](usage/configuration.md) explains `komorebi.json`, where komorebi looks for it and how it is reloaded when it changes, [Example configurations](example-configurations.md) has one to start from, and [Application specific configuration](usage/application-specific-configuration.md) diff --git a/docs/komorebi.example.json b/docs/komorebi.example.json index a3f08b3a..7ab0d827 100644 --- a/docs/komorebi.example.json +++ b/docs/komorebi.example.json @@ -14,7 +14,14 @@ "workspaces": [ { "name": "I", - "layout": "BSP" + "layout": "BSP", + "initial_workspace_rules": [ +// { +// "kind": "Exe", +// "id": "firefox", +// "matching_strategy": "Equals" +// } + ] }, { "name": "II", diff --git a/docs/usage/configuration.md b/docs/usage/configuration.md index 71652323..0c284c3c 100644 --- a/docs/usage/configuration.md +++ b/docs/usage/configuration.md @@ -45,7 +45,9 @@ it is. [`komorebic generate-static-config`](../cli/generate-static-config.md) prints the settings the daemon has now as a `komorebi.json`: a way to start a file from a setup arrived at with commands. -The rules (`ignore_rules`, `manage_rules` and `floating_applications`) are not in what it prints. +The rules (`ignore_rules`, `manage_rules` and `floating_applications`) are not in what it prints; +the `workspace_rules` and `initial_workspace_rules` of the workspaces that were loaded from a file +are. ## One file for every platform @@ -103,7 +105,8 @@ Each is a list of rules, which [Rules](rules.md) explains. A rule is an object w `Contains`, `Regex`, or one of the four that negate them: `DoesNotEqual`, `DoesNotStartWith`, `DoesNotEndWith` and `DoesNotContain`), or a list of such objects, all of which have to match. Rules in the file add to the ones the daemon has: a rule that is taken out of the file stays -until the daemon restarts. +until the daemon restarts. The exception is a workspace's `workspace_rules` and +`initial_workspace_rules`, which the file gives again each time it is read. ### Monitors and workspaces @@ -130,6 +133,8 @@ named for it. A workspace has these keys: | `tile` | see below | Whether the workspace tiles its windows | | `layout_flip` | none | The axis the layout is mirrored on: `Horizontal`, `Vertical` or `HorizontalAndVertical` | | `layout_options` | none | Options of the layout, such as `column_ratios` and `scrolling` | +| `workspace_rules` | none | Rules for the windows that always go to this workspace ([Workspace rules](workspace-rules.md)) | +| `initial_workspace_rules` | none | Rules for the windows that go to this workspace when komorebi first sees them | | `layout_rules` | none | `{ "3": "Columns" }`: the layout the workspace has once it has 3 containers or more | | `layout_options_rules` | none | The same, for the layout options | | `container_padding`, `workspace_padding` | the default | The padding of this workspace | diff --git a/docs/usage/workspace-rules.md b/docs/usage/workspace-rules.md new file mode 100644 index 00000000..89a7116e --- /dev/null +++ b/docs/usage/workspace-rules.md @@ -0,0 +1,83 @@ +# Workspace rules + +A workspace rule sends the windows of an application to a workspace. It is a [rule](rules.md) +(`exe`, `class`, `title` or `path`) with a place: the index of a monitor and of a workspace, or +the name of a workspace. There are two kinds: + +- an **initial** rule sends a window once, when komorebi first sees it: after that the window + stays wherever you put it; +- a **permanent** rule sends the windows of the application there every time, so that a window + you take away from that workspace goes back. + +The windows are sent when a window opens or is focused, when the configuration is loaded, and when +you ask for it: komorebi looks at the rules at each event about a window it manages, before it +handles it. A window that +opens is in a workspace only after its own event has been handled, so it is sent by the next +event, which is the activation KWin reports a moment later. + +Only the windows in view are looked at: the one on top of each container, and the floating +windows. A window that is on its workspace already is left alone. A workspace that does not +exist yet is made, with the ones before it. When the window is on the workspace in front, it +leaves it and is hidden (it is put on the parking desktop, as the back of a stack is), and the +workspace is tiled again without it; either way, it goes to the virtual desktop of its new +workspace, so it is out of view until that workspace is shown, which brings it back and tiles it. +A floating window that goes to another monitor is moved onto that monitor. + +## In komorebi.json + +A workspace has `workspace_rules` and `initial_workspace_rules`, each a list of +[rules](configuration.md#rules) like the ones in `ignore_rules`: + +```json +{ + "monitors": [ + { + "workspaces": [ + { "name": "web", "layout": "BSP" }, + { + "name": "code", + "layout": "BSP", + "initial_workspace_rules": [ + { "kind": "Exe", "id": "kate", "matching_strategy": "Equals" } + ], + "workspace_rules": [ + { "kind": "Class", "id": "org.kde.konsole", "matching_strategy": "Equals" } + ] + } + ] + } + ] +} +``` + +The rules are made again from the file each time it is read, so a rule taken out of the file is +gone, and so are the ones `komorebic` added. The windows that are open are sent where the file +says when it has been read. + +## With komorebic + +[`initial-workspace-rule`](../cli/initial-workspace-rule.md) and +[`workspace-rule`](../cli/workspace-rule.md) take what the rule names (`exe`, `class`, `title` or +`path`), its text, and the index of the monitor and of the workspace; +[`initial-named-workspace-rule`](../cli/initial-named-workspace-rule.md) and +[`named-workspace-rule`](../cli/named-workspace-rule.md) take the name of the workspace instead, +and add no rule when no workspace has the name. A rule given this way matches a title or a class +that starts or ends with what it names, and an executable or a path that is exactly what it names. +A rule that is there already is not added again. + +```sh +komorebic initial-workspace-rule exe kate 0 1 +komorebic workspace-rule class org.kde.konsole 0 1 +komorebic named-workspace-rule exe thunderbird mail +``` + +[`enforce-workspace-rules`](../cli/enforce-workspace-rules.md) forgets which windows the initial +rules have sent and looks at the rules again, so that every window of an application goes to the +workspace its initial rule gives. The three clear commands take rules away: +[`clear-workspace-rules`](../cli/clear-workspace-rules.md) by monitor and workspace index, +[`clear-named-workspace-rules`](../cli/clear-named-workspace-rules.md) by name, and +[`clear-all-workspace-rules`](../cli/clear-all-workspace-rules.md) all of them. The first two +also take away the rules of every other workspace of the monitor they are given, and of every +other monitor's workspace with the same index, because of how they pick the rules to keep. Which +rules the daemon has is in the `workspace_rules` of +[`komorebic global-state`](../cli/global-state.md). diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index 1c234313..62a8862e 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -474,6 +474,14 @@ pub enum SocketMessage { WorkspaceWorkAreaOffset(usize, usize, Rect), ToggleWindowBasedWorkAreaOffset, ResizeDelta(i32), + InitialWorkspaceRule(ApplicationIdentifier, String, usize, usize), + InitialNamedWorkspaceRule(ApplicationIdentifier, String, String), + WorkspaceRule(ApplicationIdentifier, String, usize, usize), + NamedWorkspaceRule(ApplicationIdentifier, String, String), + ClearWorkspaceRules(usize, usize), + ClearNamedWorkspaceRules(String), + ClearAllWorkspaceRules, + EnforceWorkspaceRules, SessionFloatRule, SessionFloatRules, ClearSessionFloatRules, diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs index a8381b3e..be23ffb4 100644 --- a/komorebi/src/lib.rs +++ b/komorebi/src/lib.rs @@ -29,6 +29,7 @@ use crate::core::SubscribeOptions; use crate::core::config_generation::IdWithIdentifier; use crate::core::config_generation::MatchingRule; use crate::core::config_generation::MatchingStrategy; +use crate::core::config_generation::WorkspaceMatchingRule; use crate::state::State; use crate::window::AspectRatio; use crate::window::PredefinedAspectRatio; @@ -136,6 +137,10 @@ lazy_static! { /// ([`SocketMessage::DisplayIndexPreference`]): the window manager orders its monitors by it static ref DISPLAY_INDEX_PREFERENCES: Arc>> = Arc::new(RwLock::new(HashMap::new())); + /// The rules that send the windows of an application to a workspace: when they open + /// (`initial_only`) or whenever the window manager looks at them + static ref WORKSPACE_MATCHING_RULES: Arc>> = + Arc::new(Mutex::new(Vec::new())); /// The compiled regular expression of each rule whose matching strategy is `Regex`, by the /// rule's id static ref REGEX_IDENTIFIERS: Arc>> = diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index a82ebe42..4e93cd18 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -67,6 +67,12 @@ //! - **ScrollingLayoutColumns** sets how many columns the scrolling layout shows on the focused //! workspace, and **LayoutRatios** the share of the work area its first columns and rows take, //! and both tile the workspace again. +//! - **InitialWorkspaceRule**, **InitialNamedWorkspaceRule**, **WorkspaceRule** and +//! **NamedWorkspaceRule** add a rule that sends the windows of an application to a workspace, +//! given by its indices or by its name: when they open for the first time, or always; +//! **ClearWorkspaceRules**, **ClearNamedWorkspaceRules** and **ClearAllWorkspaceRules** take +//! rules away, and **EnforceWorkspaceRules** applies all of them to the windows that are open +//! ([`WindowManager::enforce_workspace_rules`]). //! - **WorkspaceLayoutRule** and **NamedWorkspaceLayoutRule** make a workspace change to a layout //! once it has so many containers, and **ClearWorkspaceLayoutRules** and //! **ClearNamedWorkspaceLayoutRules** take its rules away @@ -188,6 +194,7 @@ use crate::NotificationEvent; use crate::SESSION_FLOATING_APPLICATIONS; use crate::SUBSCRIPTION_SOCKET_OPTIONS; use crate::SUBSCRIPTION_SOCKETS; +use crate::WORKSPACE_MATCHING_RULES; use crate::backend::backend; use crate::core::ApplicationIdentifier; use crate::core::Axis; @@ -204,6 +211,7 @@ use crate::core::WindowContainerBehaviour; use crate::core::config_generation::IdWithIdentifier; use crate::core::config_generation::MatchingRule; use crate::core::config_generation::MatchingStrategy; +use crate::core::config_generation::WorkspaceMatchingRule; use crate::monitor::MonitorInformation; use crate::notify_subscribers; use crate::state::GlobalState; @@ -930,6 +938,8 @@ impl WindowManager { SocketMessage::ReplaceConfiguration(ref config) => { // Check that this is a valid static config file first if StaticConfig::read(config).is_ok() { + // Clear workspace rules; these will need to be replaced + WORKSPACE_MATCHING_RULES.lock().clear(); // Pause so that restored windows come to the foreground from all workspaces self.is_paused = true; // Bring all windows to the foreground @@ -1427,6 +1437,110 @@ impl WindowManager { floating_applications.retain(|r| !session_floating_applications.contains(r)); session_floating_applications.clear() } + SocketMessage::InitialWorkspaceRule(identifier, ref id, monitor_idx, workspace_idx) => { + let mut workspace_rules = WORKSPACE_MATCHING_RULES.lock(); + let workspace_matching_rule = WorkspaceMatchingRule { + monitor_index: monitor_idx, + workspace_index: workspace_idx, + matching_rule: MatchingRule::Simple(IdWithIdentifier { + kind: identifier, + id: id.to_string(), + matching_strategy: Some(MatchingStrategy::Legacy), + }), + initial_only: true, + }; + + if !workspace_rules.contains(&workspace_matching_rule) { + workspace_rules.push(workspace_matching_rule); + } + } + SocketMessage::InitialNamedWorkspaceRule(identifier, ref id, ref workspace) => { + if let Some((monitor_idx, workspace_idx)) = + self.monitor_workspace_index_by_name(workspace) + { + let mut workspace_rules = WORKSPACE_MATCHING_RULES.lock(); + let workspace_matching_rule = WorkspaceMatchingRule { + monitor_index: monitor_idx, + workspace_index: workspace_idx, + matching_rule: MatchingRule::Simple(IdWithIdentifier { + kind: identifier, + id: id.to_string(), + matching_strategy: Some(MatchingStrategy::Legacy), + }), + initial_only: true, + }; + + if !workspace_rules.contains(&workspace_matching_rule) { + workspace_rules.push(workspace_matching_rule); + } + } + } + SocketMessage::WorkspaceRule(identifier, ref id, monitor_idx, workspace_idx) => { + let mut workspace_rules = WORKSPACE_MATCHING_RULES.lock(); + let workspace_matching_rule = WorkspaceMatchingRule { + monitor_index: monitor_idx, + workspace_index: workspace_idx, + matching_rule: MatchingRule::Simple(IdWithIdentifier { + kind: identifier, + id: id.to_string(), + matching_strategy: Some(MatchingStrategy::Legacy), + }), + initial_only: false, + }; + + if !workspace_rules.contains(&workspace_matching_rule) { + workspace_rules.push(workspace_matching_rule); + } + } + SocketMessage::NamedWorkspaceRule(identifier, ref id, ref workspace) => { + if let Some((monitor_idx, workspace_idx)) = + self.monitor_workspace_index_by_name(workspace) + { + let mut workspace_rules = WORKSPACE_MATCHING_RULES.lock(); + let workspace_matching_rule = WorkspaceMatchingRule { + monitor_index: monitor_idx, + workspace_index: workspace_idx, + matching_rule: MatchingRule::Simple(IdWithIdentifier { + kind: identifier, + id: id.to_string(), + matching_strategy: Some(MatchingStrategy::Legacy), + }), + initial_only: false, + }; + + if !workspace_rules.contains(&workspace_matching_rule) { + workspace_rules.push(workspace_matching_rule); + } + } + } + SocketMessage::ClearWorkspaceRules(monitor_idx, workspace_idx) => { + let mut workspace_rules = WORKSPACE_MATCHING_RULES.lock(); + + workspace_rules.retain(|r| { + r.monitor_index != monitor_idx && r.workspace_index != workspace_idx + }); + } + SocketMessage::ClearNamedWorkspaceRules(ref workspace) => { + if let Some((monitor_idx, workspace_idx)) = + self.monitor_workspace_index_by_name(workspace) + { + let mut workspace_rules = WORKSPACE_MATCHING_RULES.lock(); + workspace_rules.retain(|r| { + r.monitor_index != monitor_idx && r.workspace_index != workspace_idx + }); + } + } + SocketMessage::ClearAllWorkspaceRules => { + let mut workspace_rules = WORKSPACE_MATCHING_RULES.lock(); + workspace_rules.clear(); + } + SocketMessage::EnforceWorkspaceRules => { + { + let mut already_moved = self.already_moved_window_handles.lock(); + already_moved.clear(); + } + self.enforce_workspace_rules()?; + } SocketMessage::IgnoreRule(identifier, ref id) => { let mut ignore_identifiers = IGNORE_IDENTIFIERS.lock(); diff --git a/komorebi/src/process_event.rs b/komorebi/src/process_event.rs index b9abaab1..98828607 100644 --- a/komorebi/src/process_event.rs +++ b/komorebi/src/process_event.rs @@ -5,6 +5,9 @@ //! covers and no manage rule rescues), or about one the user took out of the layout with //! `UnmanageFocusedWindow`, changes nothing either. Otherwise: //! +//! - Whatever the event, the windows of the workspaces are looked at first for workspace rules +//! ([`WindowManager::enforce_workspace_rules`]): a window a rule names is sent to its +//! workspace. //! - **Show**, and **Manage** (`ManageFocusedWindow`): the window gets a container of its own after //! the focused one, or joins the focused container when the window container behavior is //! `Append` ([`WindowManager::window_management_behaviour`]), and the workspace is tiled again @@ -182,6 +185,8 @@ impl WindowManager { self.focus_monitor(monitor_idx)?; } + self.enforce_workspace_rules()?; + match event { WindowManagerEvent::FocusChange(_, _) => { let is_known = self.known_window_ids.get(&window_id).cloned(); @@ -439,6 +444,7 @@ impl WindowManager { if destroyed { self.minimized_windows.remove(&window_id); + self.already_moved_window_handles.lock().remove(&window_id); HIDDEN_WINDOWS.lock().remove(&window_id); UNMANAGED_WINDOW_IDS.lock().retain(|id| *id != window_id); } else { diff --git a/komorebi/src/state.rs b/komorebi/src/state.rs index ae6d0504..0752382a 100644 --- a/komorebi/src/state.rs +++ b/komorebi/src/state.rs @@ -16,12 +16,14 @@ use crate::DISPLAY_INDEX_PREFERENCES; use crate::HOME_DIR; use crate::IGNORE_IDENTIFIERS; use crate::MANAGE_IDENTIFIERS; +use crate::WORKSPACE_MATCHING_RULES; use crate::core::MonocleFocusBehaviour; use crate::core::MoveBehaviour; use crate::core::OperationBehaviour; use crate::core::Rect; use crate::core::WindowContainerBehaviour; use crate::core::config_generation::MatchingRule; +use crate::core::config_generation::WorkspaceMatchingRule; use crate::monitor::Monitor; use crate::ring::Ring; use crate::window_manager::WindowManager; @@ -34,7 +36,8 @@ use std::path::PathBuf; /// What the daemon has that is not part of the window manager, as it answers /// [`SocketMessage::GlobalState`](crate::core::SocketMessage::GlobalState): the ignore and the manage -/// rules, the indices the user gave the monitors, and the configuration and the data directories +/// rules, the indices the user gave the monitors, the workspace rules, and the configuration and +/// the data directories /// /// # Example /// @@ -47,6 +50,7 @@ use std::path::PathBuf; /// assert!(json.contains(r#""id":"org.kde.plasmashell""#), "{json}"); /// assert!(state.manage_identifiers.is_empty()); /// assert!(state.display_index_preferences.is_empty()); +/// assert!(state.workspace_rules.is_empty()); /// assert_eq!(state.configuration_dir, *komorebi::HOME_DIR); /// assert_eq!(state.data_dir, *komorebi::DATA_DIR); /// @@ -77,6 +81,7 @@ pub struct GlobalState { // pub monitor_index_preferences: HashMap, pub display_index_preferences: HashMap, // pub ignored_duplicate_monitor_serial_ids: Vec, + pub workspace_rules: Vec, // pub window_hiding_behaviour: HidingBehaviour, pub configuration_dir: PathBuf, pub data_dir: PathBuf, @@ -89,6 +94,7 @@ impl Default for GlobalState { ignore_identifiers: IGNORE_IDENTIFIERS.lock().clone(), manage_identifiers: MANAGE_IDENTIFIERS.lock().clone(), display_index_preferences: DISPLAY_INDEX_PREFERENCES.read().clone(), + workspace_rules: WORKSPACE_MATCHING_RULES.lock().clone(), configuration_dir: HOME_DIR.clone(), data_dir: DATA_DIR.clone(), } @@ -196,6 +202,7 @@ impl From<&WindowManager> for State { layer: workspace.layer, floating_layer_behaviour: workspace.floating_layer_behaviour, globals: workspace.globals, + workspace_config: None, preselected_container_idx: None, promotion_swap_container_idx: None, }) diff --git a/komorebi/src/static_config.rs b/komorebi/src/static_config.rs index 33610d81..1f3a2ed3 100644 --- a/komorebi/src/static_config.rs +++ b/komorebi/src/static_config.rs @@ -13,6 +13,9 @@ //! nothing on KDE Plasma is accepted and ignored, and a key that is not known at all is ignored //! too, as serde does. //! +//! A workspace's `workspace_rules` and `initial_workspace_rules` become the rules that send windows +//! to it (`WORKSPACE_MATCHING_RULES`), which are made again from the file each time it is read. +//! //! The rules for particular applications are kept in files of their own, which the configuration //! names with `app_specific_configuration_path` ([`ApplicationSpecificConfiguration`]); their //! rules are added to the ones the configuration itself has. @@ -33,6 +36,7 @@ use crate::IGNORE_IDENTIFIERS; use crate::LAYOUT_DEFAULTS; use crate::MANAGE_IDENTIFIERS; use crate::REGEX_IDENTIFIERS; +use crate::WORKSPACE_MATCHING_RULES; use crate::core::Axis; use crate::core::CrossBoundaryBehaviour; use crate::core::DefaultLayout; @@ -53,6 +57,7 @@ use crate::core::asc::ApplicationSpecificConfiguration; use crate::core::asc::AscApplicationRulesOrSchema; use crate::core::config_generation::MatchingRule; use crate::core::config_generation::MatchingStrategy; +use crate::core::config_generation::WorkspaceMatchingRule; use crate::core::pathext::ResolvedPathBuf; use crate::monitor::Monitor; use crate::ring::Ring; @@ -112,6 +117,12 @@ pub struct WorkspaceConfig { /// Workspace padding (default: global) #[serde(skip_serializing_if = "Option::is_none")] pub workspace_padding: Option, + /// Initial workspace application rules + #[serde(skip_serializing_if = "Option::is_none")] + pub initial_workspace_rules: Option>, + /// Permanent workspace application rules + #[serde(skip_serializing_if = "Option::is_none")] + pub workspace_rules: Option>, /// Work area offset rules in the format of threshold => Rect (default: None) #[serde(skip_serializing_if = "Option::is_none")] pub work_area_offset_rules: Option>, @@ -221,6 +232,14 @@ impl From<&Workspace> for WorkspaceConfig { layout_rules, container_padding, workspace_padding, + initial_workspace_rules: value + .workspace_config + .as_ref() + .and_then(|c| c.initial_workspace_rules.clone()), + workspace_rules: value + .workspace_config + .as_ref() + .and_then(|c| c.workspace_rules.clone()), work_area_offset_rules, work_area_offset: value.work_area_offset, apply_window_based_work_area_offset: Some(value.apply_window_based_work_area_offset), @@ -890,6 +909,7 @@ impl StaticConfig { .unwrap_or(DEFAULT_MOUSE_FOLLOWS_FOCUS), hotwatch: Hotwatch::new()?, minimized_windows: HashMap::new(), + already_moved_window_handles: Default::default(), known_window_ids: HashMap::new(), }; @@ -931,8 +951,12 @@ impl StaticConfig { DISPLAY_INDEX_PREFERENCES.read().keys().copied().collect(); let mut configs_used = Vec::new(); + let mut workspace_matching_rules = WORKSPACE_MATCHING_RULES.lock(); + workspace_matching_rules.clear(); + drop(workspace_matching_rules); + let offset = wm.work_area_offset; - for monitor in wm.monitors_mut().iter_mut() { + for (i, monitor) in wm.monitors_mut().iter_mut().enumerate() { let preferred_config_idx = { let display_index_preferences = DISPLAY_INDEX_PREFERENCES.read(); @@ -985,9 +1009,36 @@ impl StaticConfig { ws.load_static_config(workspace_config, value.layout_defaults.as_ref())?; } } + + let mut workspace_matching_rules = WORKSPACE_MATCHING_RULES.lock(); + for (j, ws) in monitor_config.workspaces.iter().enumerate() { + if let Some(rules) = &ws.workspace_rules { + for r in rules { + workspace_matching_rules.push(WorkspaceMatchingRule { + monitor_index: i, + workspace_index: j, + matching_rule: r.clone(), + initial_only: false, + }); + } + } + + if let Some(rules) = &ws.initial_workspace_rules { + for r in rules { + workspace_matching_rules.push(WorkspaceMatchingRule { + monitor_index: i, + workspace_index: j, + matching_rule: r.clone(), + initial_only: true, + }); + } + } + } } } + wm.enforce_workspace_rules()?; + Ok(()) } @@ -1012,8 +1063,12 @@ impl StaticConfig { DISPLAY_INDEX_PREFERENCES.read().keys().copied().collect(); let mut configs_used = Vec::new(); + let mut workspace_matching_rules = WORKSPACE_MATCHING_RULES.lock(); + workspace_matching_rules.clear(); + drop(workspace_matching_rules); + let offset = wm.work_area_offset; - for monitor in wm.monitors_mut().iter_mut() { + for (i, monitor) in wm.monitors_mut().iter_mut().enumerate() { let preferred_config_idx = { let display_index_preferences = DISPLAY_INDEX_PREFERENCES.read(); @@ -1068,9 +1123,36 @@ impl StaticConfig { ws.load_static_config(workspace_config, value.layout_defaults.as_ref())?; } } + + let mut workspace_matching_rules = WORKSPACE_MATCHING_RULES.lock(); + for (j, ws) in monitor_config.workspaces.iter().enumerate() { + if let Some(rules) = &ws.workspace_rules { + for r in rules { + workspace_matching_rules.push(WorkspaceMatchingRule { + monitor_index: i, + workspace_index: j, + matching_rule: r.clone(), + initial_only: false, + }); + } + } + + if let Some(rules) = &ws.initial_workspace_rules { + for r in rules { + workspace_matching_rules.push(WorkspaceMatchingRule { + monitor_index: i, + workspace_index: j, + matching_rule: r.clone(), + initial_only: true, + }); + } + } + } } } + wm.enforce_workspace_rules()?; + wm.window_management_behaviour.current_behaviour = value.window_container_behaviour.unwrap_or_default(); wm.window_management_behaviour.float_override = value.float_override.unwrap_or_default(); diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index fa1230b8..639594b4 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -51,8 +51,10 @@ use crate::DATA_DIR; use crate::HIDDEN_WINDOWS; use crate::LibraryError; +use crate::REGEX_IDENTIFIERS; use crate::SUBSCRIPTION_SOCKETS; use crate::UNMANAGED_WINDOW_IDS; +use crate::WORKSPACE_MATCHING_RULES; use crate::backend::backend; use crate::container::Container; use crate::core::Arrangement; @@ -69,12 +71,14 @@ use crate::core::Rect; use crate::core::Sizing; use crate::core::WindowContainerBehaviour; use crate::core::WindowManagementBehaviour; +use crate::core::config_generation::MatchingRule; use crate::desktop; use crate::lockable_sequence::Lockable; use crate::monitor::Monitor; use crate::ring::Ring; use crate::static_config::StaticConfig; use crate::window::Window; +use crate::window::should_act_individual; use crate::window_manager_event::WindowManagerEvent; use crate::window_manager_event_listener; use crate::workspace::Workspace; @@ -84,7 +88,9 @@ use color_eyre::eyre::OptionExt; use color_eyre::eyre::bail; use crossbeam_channel::Receiver; use hotwatch::Hotwatch; +use parking_lot::Mutex; use std::collections::HashMap; +use std::collections::HashSet; use std::collections::VecDeque; use std::io::ErrorKind; use std::net::Shutdown; @@ -92,6 +98,7 @@ use std::num::NonZeroUsize; use std::os::unix::net::UnixListener; use std::os::unix::net::UnixStream; use std::path::PathBuf; +use std::sync::Arc; /// A tile cannot be resized to less than this fraction of the work area (or less than it already is) const MINIMUM_TILE_FRACTION: i32 = 10; @@ -135,12 +142,41 @@ pub struct WindowManager { /// [`crate::window_manager_event_listener`] pub incoming_events: Receiver, pub minimized_windows: HashMap, + /// The windows an `initial_only` workspace rule has moved already, so that it moves each of + /// them once, until it closes + pub already_moved_window_handles: Arc>>, /// Maps each known window id to the (monitor, workspace) index pair managing it pub known_window_ids: HashMap, } impl_ring_elements!(WindowManager, Monitor); +/// A window that a workspace rule sends from the workspace it is on to the one the rule names +#[derive(Debug, Clone, Copy)] +struct EnforceWorkspaceRuleOp { + window_id: u32, + origin_monitor_idx: usize, + origin_workspace_idx: usize, + target_monitor_idx: usize, + target_workspace_idx: usize, + floating: bool, +} + +impl EnforceWorkspaceRuleOp { + const fn is_origin(&self, monitor_idx: usize, workspace_idx: usize) -> bool { + self.origin_monitor_idx == monitor_idx && self.origin_workspace_idx == workspace_idx + } + + const fn is_target(&self, monitor_idx: usize, workspace_idx: usize) -> bool { + self.target_monitor_idx == monitor_idx && self.target_workspace_idx == workspace_idx + } + + const fn is_enforced(&self) -> bool { + (self.origin_monitor_idx == self.target_monitor_idx) + && (self.origin_workspace_idx == self.target_workspace_idx) + } +} + impl AsRef for WindowManager { fn as_ref(&self) -> &Self { self @@ -194,6 +230,7 @@ impl WindowManager { work_area_offset: None, incoming_events: incoming, minimized_windows: HashMap::new(), + already_moved_window_handles: Default::default(), known_window_ids: Default::default(), }) } @@ -2813,6 +2850,264 @@ impl WindowManager { Ok(()) } + /// Sends each window that a workspace rule names to the workspace the rule gives, and tiles the + /// focused workspace again if a window left it + /// + /// The rules are in `WORKSPACE_MATCHING_RULES`; only the window at the top of each container + /// and the floating windows are looked at, and a window that is on its workspace already is + /// left alone. A rule that is `initial_only` moves a window once: the window is remembered in + /// [`WindowManager::already_moved_window_handles`] until it closes. A floating window is + /// taken to the monitor of its workspace. A workspace that does not exist yet is made. A window + /// that leaves the focused workspace is hidden, so it stays out of sight until its new + /// workspace is shown. The windows that moved are put on the desktops of their workspaces, + /// which is also how a window that leaves a workspace that is out of view comes to the desktop + /// of its new one. + /// + /// # Errors + /// + /// There is no focused monitor, a rule names a monitor that is not there, a window cannot be + /// read, or the focused workspace cannot be tiled again. + #[tracing::instrument(skip(self), level = "debug")] + pub fn enforce_workspace_rules(&mut self) -> eyre::Result<()> { + let mut to_move = vec![]; + + let focused_monitor_idx = self.focused_monitor_idx(); + let focused_workspace_idx = self + .monitors() + .get(focused_monitor_idx) + .ok_or_eyre("there is no monitor with that index")? + .focused_workspace_idx(); + + // scope mutex locks to avoid deadlock if should_update_focused_workspace evaluates to true + // at the end of this function + { + let workspace_matching_rules = WORKSPACE_MATCHING_RULES.lock(); + let regex_identifiers = REGEX_IDENTIFIERS.lock(); + // Go through all the monitors and workspaces + for (i, monitor) in self.monitors().iter().enumerate() { + for (j, workspace) in monitor.workspaces().iter().enumerate() { + // And all the visible windows (at the top of a container) + for window in workspace.visible_windows().into_iter().flatten() { + if let (Some(exe_name), Some(title), Some(class), Some(path)) = + (window.exe(), window.title(), window.class(), window.path()) + { + for rule in &*workspace_matching_rules { + let matched = match &rule.matching_rule { + MatchingRule::Simple(r) => should_act_individual( + &title, + &exe_name, + &[&class], + &path.to_string_lossy(), + r, + ®ex_identifiers, + ), + MatchingRule::Composite(r) => { + let mut composite_results = vec![]; + for identifier in r { + composite_results.push(should_act_individual( + &title, + &exe_name, + &[&class], + &path.to_string_lossy(), + identifier, + ®ex_identifiers, + )); + } + + composite_results.iter().all(|&x| x) + } + }; + + if matched { + let floating = workspace.floating_windows().contains(window); + + let mut already_moved_window_handles = + self.already_moved_window_handles.lock(); + + if rule.initial_only { + if !already_moved_window_handles.contains(&window.id) { + already_moved_window_handles.insert(window.id); + + self.add_window_handle_to_move_based_on_workspace_rule( + &window + .title() + .ok_or_eyre("could not read window title")?, + window.id, + i, + j, + rule.monitor_index, + rule.workspace_index, + floating, + &mut to_move, + ); + } + } else { + self.add_window_handle_to_move_based_on_workspace_rule( + &window + .title() + .ok_or_eyre("could not read window title")?, + window.id, + i, + j, + rule.monitor_index, + rule.workspace_index, + floating, + &mut to_move, + ); + } + } + } + } + } + } + } + } + + // Only retain operations where the target is not the current workspace + to_move.retain(|op| !op.is_target(focused_monitor_idx, focused_workspace_idx)); + // Only retain operations where the rule has not already been enforced + to_move.retain(|op| !op.is_enforced()); + + let mut should_update_focused_workspace = false; + let mut removed_windows = HashMap::new(); + + // Parse the operation and remove any windows that are not placed according to their rules + for op in &to_move { + let target_area = self + .monitors_mut() + .get_mut(op.target_monitor_idx) + .ok_or_eyre("there is no monitor with that index")? + .work_area_size; + + let origin_monitor = self + .monitors_mut() + .get_mut(op.origin_monitor_idx) + .ok_or_eyre("there is no monitor with that index")?; + + let origin_area = origin_monitor.work_area_size; + + let origin_workspace = origin_monitor + .workspaces_mut() + .get_mut(op.origin_workspace_idx) + .ok_or_eyre("there is no workspace with that index")?; + + let window = origin_workspace.remove_window(op.window_id)?; + + // If it is a floating window move it to the target area + if op.floating { + window.move_to_area(&origin_area, &target_area)?; + } + + // Hide the window we are about to remove if it is on the currently focused workspace + if op.is_origin(focused_monitor_idx, focused_workspace_idx) { + window.hide(); + should_update_focused_workspace = true; + } + + removed_windows.insert(window.id, window); + } + + // Parse the operation again and associate those removed windows with the workspace that + // their rules have defined for them + for op in &to_move { + let window = removed_windows + .get_mut(&op.window_id) + .ok_or_eyre("there is no window")?; + + let target_monitor = self + .monitors_mut() + .get_mut(op.target_monitor_idx) + .ok_or_eyre("there is no monitor with that index")?; + + // The very first time this fn is called, the workspace might not even exist yet + if target_monitor + .workspaces() + .get(op.target_workspace_idx) + .is_none() + { + // If it doesn't, let's make sure it does for the next step + target_monitor.ensure_workspace_count(op.target_workspace_idx + 1); + } + + let target_workspace = target_monitor + .workspaces_mut() + .get_mut(op.target_workspace_idx) + .ok_or_eyre("there is no workspace with that index")?; + + if op.floating { + target_workspace + .floating_windows_mut() + // TODO: not sure about this clone + .push_back(*window); + } else { + //TODO(alex-ds13): should this take into account the target workspace + //`window_container_behaviour`? + //In the case above a floating window should always be moved as floating, + //because it was set as so either manually by the user or by a + //`floating_applications` rule so it should stay that way. But a tiled window + //when moving to another workspace by a `workspace_rule` should honor that + //workspace `window_container_behaviour` in my opinion! Maybe this should be done + //on the `new_container_for_window` function instead. + // TODO: not sure about this clone + target_workspace.new_container_for_window(window)?; + } + } + + // The compositor learns where the windows that moved belong: each is put on the desktop of + // the workspace it is on now (a hidden window only has the desktop it comes back to + // changed), which also takes a window that was not hidden out of view when that workspace + // is not the one in front + let mut assigned = vec![]; + for op in &to_move { + if !assigned.contains(&op.target_monitor_idx) + && let Some(monitor) = self.monitors().get(op.target_monitor_idx) + { + monitor.assign_windows_to_workspaces(); + assigned.push(op.target_monitor_idx); + } + } + + // Only re-tile the focused workspace if we need to + if should_update_focused_workspace { + self.update_focused_workspace(false, false)?; + } + + Ok(()) + } + + /// Adds to `to_move` the operation that takes the window from where it is to the workspace a + /// rule gives it + #[allow(clippy::too_many_arguments)] + #[tracing::instrument(skip(self), level = "debug")] + fn add_window_handle_to_move_based_on_workspace_rule( + &self, + window_title: &String, + window_id: u32, + origin_monitor_idx: usize, + origin_workspace_idx: usize, + target_monitor_idx: usize, + target_workspace_idx: usize, + floating: bool, + to_move: &mut Vec, + ) { + tracing::trace!( + "{} should be on monitor {}, workspace {}", + window_title, + target_monitor_idx, + target_workspace_idx + ); + + // Create an operation outline and save it for later in the fn + to_move.push(EnforceWorkspaceRuleOp { + window_id, + origin_monitor_idx, + origin_workspace_idx, + target_monitor_idx, + target_workspace_idx, + floating, + }); + } + /// Applies the `komorebi.json` at `pathbuf` to the window manager and tiles it again /// ([`StaticConfig::reload`]) /// @@ -5641,4 +5936,43 @@ mod tests { } } } + + #[test] + fn test_add_window_handle_to_move_based_on_workspace_rule() { + let (wm, _context) = setup_window_manager(); + + // Mock Data representing a window and its workspace/movement details + let window_title = String::from("TestWindow"); + let window_id = 12345; + let origin_monitor_idx = 0; + let origin_workspace_idx = 0; + let target_monitor_idx = 2; + let target_workspace_idx = 3; + let floating = false; + + // Empty vector to hold workspace rule enforcement operations + let mut to_move: Vec = Vec::new(); + + // Call the function to add a window movement operation based on workspace rules + wm.add_window_handle_to_move_based_on_workspace_rule( + &window_title, + window_id, + origin_monitor_idx, + origin_workspace_idx, + target_monitor_idx, + target_workspace_idx, + floating, + &mut to_move, + ); + + // Verify that the vector contains the expected operation with the correct values + assert_eq!(to_move.len(), 1); + let op = &to_move[0]; + assert_eq!(op.window_id, window_id); // 12345 + assert_eq!(op.origin_monitor_idx, origin_monitor_idx); // 0 + assert_eq!(op.origin_workspace_idx, origin_workspace_idx); // 0 + assert_eq!(op.target_monitor_idx, target_monitor_idx); // 2 + assert_eq!(op.target_workspace_idx, target_workspace_idx); // 3 + assert_eq!(op.floating, floating); // false + } } diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index 52682fea..937ec7de 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -100,6 +100,10 @@ pub struct Workspace { /// Whether a window that opens while this workspace is on its floating layer floats, when it /// is not the monitor's or the window manager's default pub floating_layer_behaviour: Option, + /// The entry of `komorebi.json` this workspace was loaded from, which keeps the rules that + /// send windows to it + #[serde(skip_serializing_if = "Option::is_none")] + pub workspace_config: Option, #[serde(skip_serializing_if = "Option::is_none")] pub preselected_container_idx: Option, #[serde(skip_serializing_if = "Option::is_none")] @@ -160,6 +164,7 @@ impl Default for Workspace { window_container_behaviour_rules: None, floating_windows: Default::default(), float_override: None, + workspace_config: None, preselected_container_idx: None, promotion_swap_container_idx: None, } @@ -253,7 +258,8 @@ impl Workspace { /// Takes the settings of `config`, which `komorebi.json` has for this workspace: its name, its /// layout and the rules that change it with the number of containers, its padding and offsets, /// what a new window gets and whether it floats, whether it tiles, how its layout is flipped - /// and what a new window does on its floating layer + /// and what a new window does on its floating layer, and keeps `config` itself + /// ([`Workspace::workspace_config`]) /// /// `layout_defaults` is what `komorebi.json` says every layout has, for the layout options the /// workspace sets none of: it is copied here, sorted, so that [`Workspace::update`] has it at @@ -362,6 +368,8 @@ impl Workspace { HashMap::new() }; + self.workspace_config = Some(config.clone()); + Ok(()) } @@ -1681,6 +1689,29 @@ impl Workspace { self.containers() .get(self.container_idx_for_window(window_id)?) } + + /// The windows that are in view on this workspace: the maximized window (an entry that is + /// `None` when there is none), the one at the top of the monocle container, the one at the top + /// of each container, and every floating window + pub fn visible_windows(&self) -> Vec> { + let mut vec = vec![]; + + vec.push(self.maximized_window.as_ref()); + + if let Some(monocle) = &self.monocle_container { + vec.push(monocle.focused_window()); + } + + for container in self.containers() { + vec.push(container.focused_window()); + } + + for window in self.floating_windows() { + vec.push(Some(window)); + } + + vec + } } impl Workspace { diff --git a/komorebi/tests/workspace_rules.rs b/komorebi/tests/workspace_rules.rs new file mode 100644 index 00000000..9b960ad0 --- /dev/null +++ b/komorebi/tests/workspace_rules.rs @@ -0,0 +1,431 @@ +//! Workspace rules against an in-memory desktop: the messages that add, clear and enforce them, +//! the rules a `komorebi.json` gives, and what happens to the window a rule names. +//! +//! A rule is looked at on every event, before the event is handled, and a window is in a container +//! only once its `Show` has been handled: so a window opens with the `Show` of its event and is +//! sent to its workspace at the next, the activation KWin reports after it. The rules are +//! process-wide, so the tests of this file take turns and each clears them first, and they name +//! the applications of their own. +//! +//! Window ids are in the 42_000s. + +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::core::ApplicationIdentifier; +use komorebi::core::Rect; +use komorebi::core::SocketMessage; +use komorebi::static_config::StaticConfig; +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 parking_lot::Mutex; +use std::os::unix::net::UnixListener; +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::MutexGuard; +use std::sync::atomic::AtomicU32; +use std::sync::atomic::Ordering; + +/// What the tests of this file take turns with +static TURN: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +/// A window manager over a fake desktop, which holds its turn for as long as the test does +struct Desktop { + fake: Arc, + wm: WindowManager, + _turn: MutexGuard<'static, ()>, +} + +fn short_path(suffix: &str) -> PathBuf { + static NEXT: AtomicU32 = AtomicU32::new(0); + PathBuf::from(format!( + "/tmp/kmw-{}-{}.{suffix}", + std::process::id(), + NEXT.fetch_add(1, Ordering::SeqCst) + )) +} + +fn event(kind: KWinNotification, id: u32) -> WindowManagerEvent { + match kind { + KWinNotification::WindowActivated => { + WindowManagerEvent::FocusChange(SystemNotification::KWin(kind), Window::from(id)) + } + _ => WindowManagerEvent::Show(SystemNotification::KWin(kind), Window::from(id)), + } +} + +impl Desktop { + /// A desktop with one monitor, whose first monitor has the workspaces `web`, `code` and + /// `chat` + fn new() -> Self { + let turn = TURN.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let fake = Arc::new(FakeBackend::with_one_monitor()); + let mut desktop = Self::on(fake, turn); + desktop.send(SocketMessage::ClearAllWorkspaceRules); + desktop.send(SocketMessage::EnsureNamedWorkspaces( + 0, + vec!["web".into(), "code".into(), "chat".into()], + )); + desktop + } + + fn on(fake: Arc, turn: MutexGuard<'static, ()>) -> Self { + let (_sender, receiver) = crossbeam_channel::bounded(1); + let wm = with_backend(fake.clone(), || { + let mut wm = WindowManager::new(receiver, Some(short_path("sock"))).unwrap(); + wm.init().unwrap(); + wm + }); + Self { + fake, + wm, + _turn: turn, + } + } + + fn send(&mut self, message: SocketMessage) { + with_backend(self.fake.clone(), || { + self.wm.process_command(message, Vec::new()) + }) + .unwrap(); + } + + fn handle(&mut self, event: WindowManagerEvent) { + with_backend(self.fake.clone(), || self.wm.process_event(event)).unwrap(); + } + + /// Opens a window of an application and has it activated, as KWin reports a new window + fn open(&mut self, id: u32, exe: &str) { + self.fake.open_window(id, exe, exe, &format!("window {id}")); + self.handle(event(KWinNotification::WindowAdded, id)); + self.handle(event(KWinNotification::WindowActivated, id)); + } + + /// Which workspace of the first monitor has the window in a container, if one does + fn workspace_of(&self, id: u32) -> Option { + self.wm.monitors()[0] + .workspaces() + .iter() + .position(|workspace| workspace.contains_window(id)) + } + + fn shown(&self) -> usize { + self.wm.monitors()[0].focused_workspace_idx() + } +} + +#[test] +fn a_rule_sends_the_window_of_an_application_to_its_workspace() { + let mut desktop = Desktop::new(); + desktop.send(SocketMessage::WorkspaceRule( + ApplicationIdentifier::Exe, + String::from("rule-sends"), + 0, + 1, + )); + + desktop.open(42_001, "rule-sends"); + desktop.open(42_002, "foot"); + + // the window of the application is on the workspace the rule names, and on its desktop, + // hidden, since it left the workspace in front; the other stays, and the workspace in front is + // the one it was + assert_eq!(desktop.workspace_of(42_001), Some(1)); + assert_eq!(desktop.fake.workspace_of(42_001), Some(1)); + assert!(desktop.fake.is_hidden(42_001)); + assert_eq!(desktop.workspace_of(42_002), Some(0)); + assert!(!desktop.fake.is_hidden(42_002)); + assert_eq!(desktop.shown(), 0); + assert!(!desktop.fake.on_screen(42_001)); + + // when the workspace is shown, the window is brought back and tiled in it + desktop.send(SocketMessage::FocusWorkspaceNumber(1)); + assert!(!desktop.fake.is_hidden(42_001)); + assert!(desktop.fake.on_screen(42_001)); + assert_eq!( + desktop.fake.rect_of(42_001), + Some(Rect { + left: 10, + top: 10, + right: 1900, + bottom: 1030 + }) + ); +} + +#[test] +fn a_window_a_rule_moves_between_workspaces_that_are_out_of_view_is_put_on_the_new_desktop() { + let mut desktop = Desktop::new(); + desktop.send(SocketMessage::WorkspaceRule( + ApplicationIdentifier::Exe, + String::from("rule-between"), + 0, + 1, + )); + desktop.open(42_021, "rule-between"); + assert_eq!(desktop.workspace_of(42_021), Some(1)); + assert_eq!(desktop.fake.workspace_of(42_021), Some(1)); + + // the rule now names another workspace, and the window moves between two that are out of view: + // nothing hides it, so what takes it to the desktop of its new workspace is the assignment + desktop.send(SocketMessage::ClearAllWorkspaceRules); + desktop.send(SocketMessage::WorkspaceRule( + ApplicationIdentifier::Exe, + String::from("rule-between"), + 0, + 2, + )); + desktop.send(SocketMessage::EnforceWorkspaceRules); + + assert_eq!(desktop.workspace_of(42_021), Some(2)); + assert_eq!(desktop.fake.workspace_of(42_021), Some(2)); + assert_eq!(desktop.shown(), 0); +} + +#[test] +fn an_initial_rule_moves_a_window_once_and_a_permanent_one_every_time() { + let mut desktop = Desktop::new(); + desktop.send(SocketMessage::InitialWorkspaceRule( + ApplicationIdentifier::Exe, + String::from("rule-once"), + 0, + 1, + )); + desktop.send(SocketMessage::WorkspaceRule( + ApplicationIdentifier::Exe, + String::from("rule-always"), + 0, + 2, + )); + desktop.open(42_011, "rule-once"); + desktop.open(42_012, "rule-always"); + assert_eq!(desktop.workspace_of(42_011), Some(1)); + assert_eq!(desktop.workspace_of(42_012), Some(2)); + + // the user takes each of them to the first workspace + for (id, from) in [(42_011, 1), (42_012, 2)] { + desktop.send(SocketMessage::FocusWorkspaceNumber(from)); + desktop.send(SocketMessage::MoveContainerToWorkspaceNumber(0)); + assert_eq!(desktop.workspace_of(id), Some(0)); + } + // the next event is about a window of the user's: it looks at the rules again + desktop.open(42_013, "foot"); + + assert_eq!( + desktop.workspace_of(42_011), + Some(0), + "an initial rule is applied once" + ); + assert_eq!( + desktop.workspace_of(42_012), + Some(2), + "a permanent rule is applied again" + ); + + // `EnforceWorkspaceRules` forgets what the initial rules did + desktop.send(SocketMessage::EnforceWorkspaceRules); + assert_eq!(desktop.workspace_of(42_011), Some(1)); +} + +#[test] +fn a_rule_can_name_its_workspace_and_a_workspace_that_is_not_there_is_made() { + let mut desktop = Desktop::new(); + desktop.send(SocketMessage::NamedWorkspaceRule( + ApplicationIdentifier::Exe, + String::from("rule-named"), + String::from("chat"), + )); + desktop.send(SocketMessage::InitialNamedWorkspaceRule( + ApplicationIdentifier::Exe, + String::from("rule-named-once"), + String::from("code"), + )); + // a name no workspace has: the rule is not made + desktop.send(SocketMessage::NamedWorkspaceRule( + ApplicationIdentifier::Exe, + String::from("rule-nameless"), + String::from("nowhere"), + )); + desktop.send(SocketMessage::WorkspaceRule( + ApplicationIdentifier::Exe, + String::from("rule-far"), + 0, + 5, + )); + + desktop.open(42_021, "rule-named"); + desktop.open(42_022, "rule-named-once"); + desktop.open(42_023, "rule-nameless"); + desktop.open(42_024, "rule-far"); + + assert_eq!(desktop.workspace_of(42_021), Some(2)); + assert_eq!(desktop.workspace_of(42_022), Some(1)); + assert_eq!(desktop.workspace_of(42_023), Some(0)); + assert_eq!(desktop.workspace_of(42_024), Some(5)); + assert_eq!(desktop.wm.monitors()[0].workspaces().len(), 6); +} + +#[test] +fn rules_are_cleared_by_workspace_by_name_and_all_at_once() { + let mut desktop = Desktop::new(); + let add = |desktop: &mut Desktop, exe: &str, workspace: usize| { + desktop.send(SocketMessage::WorkspaceRule( + ApplicationIdentifier::Exe, + exe.to_string(), + 0, + workspace, + )); + }; + let listed = |desktop: &mut Desktop| -> Vec { + let mut reply = Vec::new(); + with_backend(desktop.fake.clone(), || { + desktop + .wm + .process_command(SocketMessage::GlobalState, &mut reply) + }) + .unwrap(); + let state: serde_json::Value = serde_json::from_slice(&reply).unwrap(); + state["workspace_rules"] + .as_array() + .unwrap() + .iter() + .map(|rule| rule["matching_rule"]["id"].as_str().unwrap().to_string()) + .collect() + }; + + add(&mut desktop, "clear-a", 1); + add(&mut desktop, "clear-a", 1); + assert_eq!(listed(&mut desktop), ["clear-a"], "a rule is added once"); + + desktop.send(SocketMessage::ClearWorkspaceRules(0, 1)); + assert!(listed(&mut desktop).is_empty()); + + add(&mut desktop, "clear-b", 2); + desktop.send(SocketMessage::ClearNamedWorkspaceRules(String::from( + "chat", + ))); + assert!(listed(&mut desktop).is_empty()); + + add(&mut desktop, "clear-c", 1); + add(&mut desktop, "clear-d", 2); + assert_eq!(listed(&mut desktop).len(), 2); + desktop.send(SocketMessage::ClearAllWorkspaceRules); + assert!(listed(&mut desktop).is_empty()); +} + +#[test] +fn a_window_goes_to_a_workspace_of_another_monitor_and_is_tiled_there() { + let turn = TURN.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let fake = Arc::new(FakeBackend::with_one_monitor()); + fake.add_monitor( + 2, + "Virtual-1", + Rect { + left: 1920, + top: 0, + right: 1920, + bottom: 1080, + }, + Rect { + left: 1920, + top: 0, + right: 1920, + bottom: 1080, + }, + ); + let mut desktop = Desktop::on(fake, turn); + desktop.send(SocketMessage::ClearAllWorkspaceRules); + desktop.send(SocketMessage::WorkspaceRule( + ApplicationIdentifier::Exe, + String::from("rule-monitor"), + 1, + 0, + )); + + desktop.open(42_041, "rule-monitor"); + desktop.send(SocketMessage::Retile); + + assert!(desktop.wm.monitors()[1].workspaces()[0].contains_window(42_041)); + assert!(!desktop.wm.monitors()[0].workspaces()[0].contains_window(42_041)); + let rect = desktop.fake.rect_of(42_041).unwrap(); + assert!( + rect.left >= 1920, + "the window is on the second monitor: {rect:?}" + ); +} + +/// Loads a `komorebi.json` over a desktop that has a window of `exe` open already +fn load( + json: &str, + exe: &str, + id: u32, +) -> ( + Arc, + Arc>, + MutexGuard<'static, ()>, +) { + let turn = TURN.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let fake = Arc::new(FakeBackend::with_one_monitor()); + fake.open_window(id, exe, exe, "an application that was open"); + let path = short_path("json"); + std::fs::write(&path, json).unwrap(); + let socket = short_path("sock"); + let (_sender, receiver) = crossbeam_channel::bounded(1); + + let wm = with_backend(fake.clone(), || { + let mut wm = + StaticConfig::preload(&path, receiver, Some(UnixListener::bind(&socket).unwrap())) + .unwrap(); + wm.init().unwrap(); + wm + }); + let wm = Arc::new(Mutex::new(wm)); + with_backend(fake.clone(), || StaticConfig::postload(&path, &wm)).unwrap(); + let _ = std::fs::remove_file(&socket); + let _ = std::fs::remove_file(&path); + (fake, wm, turn) +} + +#[test] +fn the_rules_of_komorebi_json_send_the_windows_that_are_open_and_come_out_in_the_generated_file() { + let (_fake, wm, _turn) = load( + r#"{ + "monitors": [ + { + "workspaces": [ + { "name": "web", "layout": "BSP" }, + { + "name": "code", + "layout": "BSP", + "workspace_rules": [ + { "kind": "Exe", "id": "config-rule", "matching_strategy": "Equals" } + ], + "initial_workspace_rules": [ + { "kind": "Class", "id": "config-initial", "matching_strategy": "Equals" } + ] + } + ] + } + ] + }"#, + "config-rule", + 42_051, + ); + + // the window that was open when the daemon started is where the file says it goes + { + let wm = wm.lock(); + let workspaces = wm.monitors()[0].workspaces(); + assert!(workspaces[1].contains_window(42_051)); + assert!(!workspaces[0].contains_window(42_051)); + } + + // the rules are the window manager's, with the workspace they send to, and the file the + // window manager generates has them again + let generated = StaticConfig::from(&*wm.lock()); + let code = &generated.monitors.unwrap()[0].workspaces[1]; + assert_eq!(code.workspace_rules.as_ref().map(Vec::len), Some(1)); + assert_eq!(code.initial_workspace_rules.as_ref().map(Vec::len), Some(1)); +} diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs index ae2794f0..469fa5cc 100644 --- a/komorebic/src/main.rs +++ b/komorebic/src/main.rs @@ -70,7 +70,11 @@ //! `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 //! daemon stops, `session-float-rules` shows those rules and `clear-session-float-rules` removes -//! them, and `global-state` shows the rules the daemon has. +//! them, and `global-state` shows the rules the daemon has. `initial-workspace-rule`, +//! `initial-named-workspace-rule`, `workspace-rule` and `named-workspace-rule` send the windows of +//! an application to a workspace, when they open or always, `clear-workspace-rules`, +//! `clear-named-workspace-rules` and `clear-all-workspace-rules` take those rules away, and +//! `enforce-workspace-rules` applies them to the windows that are open. //! //! `workspace-layout-rule` and `named-workspace-layout-rule` make a workspace change layout once //! it has so many windows, and `clear-workspace-layout-rules` and @@ -436,6 +440,64 @@ pub struct ClearWorkspaceLayoutRules { workspace: usize, } +#[derive(Parser)] +struct InitialWorkspaceRule { + #[clap(value_enum)] + identifier: ApplicationIdentifier, + /// Identifier as a string + id: String, + /// Monitor index (zero-indexed) + monitor: usize, + /// Workspace index on the specified monitor (zero-indexed) + workspace: usize, +} + +#[derive(Parser)] +struct InitialNamedWorkspaceRule { + #[clap(value_enum)] + identifier: ApplicationIdentifier, + /// Identifier as a string + id: String, + /// Name of a workspace + workspace: String, +} + +#[derive(Parser)] +struct WorkspaceRule { + #[clap(value_enum)] + identifier: ApplicationIdentifier, + /// Identifier as a string + id: String, + /// Monitor index (zero-indexed) + monitor: usize, + /// Workspace index on the specified monitor (zero-indexed) + workspace: usize, +} + +#[derive(Parser)] +struct NamedWorkspaceRule { + #[clap(value_enum)] + identifier: ApplicationIdentifier, + /// Identifier as a string + id: String, + /// Name of a workspace + workspace: String, +} + +#[derive(Parser)] +struct ClearWorkspaceRules { + /// Monitor index (zero-indexed) + monitor: usize, + /// Workspace index on the specified monitor (zero-indexed) + workspace: usize, +} + +#[derive(Parser)] +struct ClearNamedWorkspaceRules { + /// Name of a workspace + workspace: String, +} + #[derive(Parser)] struct Resize { #[clap(value_enum)] @@ -1048,6 +1110,28 @@ enum SubCommand { /// Add a rule to always manage the specified application #[clap(arg_required_else_help = true)] ManageRule(ManageRule), + /// Add a rule to associate an application with a workspace on first show + #[clap(arg_required_else_help = true)] + InitialWorkspaceRule(InitialWorkspaceRule), + /// Add a rule to associate an application with a named workspace on first show + #[clap(arg_required_else_help = true)] + InitialNamedWorkspaceRule(InitialNamedWorkspaceRule), + /// Add a rule to associate an application with a workspace + #[clap(arg_required_else_help = true)] + WorkspaceRule(WorkspaceRule), + /// Add a rule to associate an application with a named workspace + #[clap(arg_required_else_help = true)] + NamedWorkspaceRule(NamedWorkspaceRule), + /// Remove all application association rules for a workspace by monitor and workspace index + #[clap(arg_required_else_help = true)] + ClearWorkspaceRules(ClearWorkspaceRules), + /// Remove all application association rules for a named workspace + #[clap(arg_required_else_help = true)] + ClearNamedWorkspaceRules(ClearNamedWorkspaceRules), + /// Remove all application association rules for all workspaces + ClearAllWorkspaceRules, + /// Enforce all workspace rules, including initial workspace rules that have already been applied + EnforceWorkspaceRules, /// Enable or disable mouse follows focus on all workspaces #[clap(arg_required_else_help = true)] MouseFollowsFocus(MouseFollowsFocus), @@ -1557,6 +1641,51 @@ fn main() -> eyre::Result<()> { SubCommand::ManageRule(args) => { send_message(&SocketMessage::ManageRule(args.identifier, args.id))?; } + SubCommand::InitialWorkspaceRule(args) => { + send_message(&SocketMessage::InitialWorkspaceRule( + args.identifier, + args.id, + args.monitor, + args.workspace, + ))?; + } + SubCommand::InitialNamedWorkspaceRule(args) => { + send_message(&SocketMessage::InitialNamedWorkspaceRule( + args.identifier, + args.id, + args.workspace, + ))?; + } + SubCommand::WorkspaceRule(args) => { + send_message(&SocketMessage::WorkspaceRule( + args.identifier, + args.id, + args.monitor, + args.workspace, + ))?; + } + SubCommand::NamedWorkspaceRule(args) => { + send_message(&SocketMessage::NamedWorkspaceRule( + args.identifier, + args.id, + args.workspace, + ))?; + } + SubCommand::ClearWorkspaceRules(args) => { + send_message(&SocketMessage::ClearWorkspaceRules( + args.monitor, + args.workspace, + ))?; + } + SubCommand::ClearNamedWorkspaceRules(args) => { + send_message(&SocketMessage::ClearNamedWorkspaceRules(args.workspace))?; + } + SubCommand::ClearAllWorkspaceRules => { + send_message(&SocketMessage::ClearAllWorkspaceRules)?; + } + SubCommand::EnforceWorkspaceRules => { + send_message(&SocketMessage::EnforceWorkspaceRules)?; + } SubCommand::EagerFocus(args) => { send_message(&SocketMessage::EagerFocus(args.exe))?; } diff --git a/komorebic/tests/cli.rs b/komorebic/tests/cli.rs index e04eb624..2c4b823f 100644 --- a/komorebic/tests/cli.rs +++ b/komorebic/tests/cli.rs @@ -984,9 +984,12 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "application-specific-configuration-schema.md", "cancel-preselect.md", "change-layout.md", + "clear-all-workspace-rules.md", "clear-named-workspace-layout-rules.md", + "clear-named-workspace-rules.md", "clear-session-float-rules.md", "clear-workspace-layout-rules.md", + "clear-workspace-rules.md", "close-workspace.md", "close.md", "completions.md", @@ -1011,6 +1014,7 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "display-index-preference.md", "eager-focus.md", "enable-autostart.md", + "enforce-workspace-rules.md", "ensure-named-workspaces.md", "ensure-workspaces.md", "flip-layout.md", @@ -1029,6 +1033,8 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "global-state.md", "global-work-area-offset.md", "ignore-rule.md", + "initial-named-workspace-rule.md", + "initial-workspace-rule.md", "layout-ratios.md", "load-resize.md", "log.md", @@ -1050,6 +1056,7 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "named-workspace-layout-rule.md", "named-workspace-layout.md", "named-workspace-padding.md", + "named-workspace-rule.md", "named-workspace-tiling.md", "new-workspace.md", "notification-schema.md", @@ -1109,6 +1116,7 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "workspace-layout.md", "workspace-name.md", "workspace-padding.md", + "workspace-rule.md", "workspace-tiling.md", "workspace-work-area-offset.md", ] diff --git a/nix/komorebi-options.nix b/nix/komorebi-options.nix index 05c85793..e2f71bba 100644 --- a/nix/komorebi-options.nix +++ b/nix/komorebi-options.nix @@ -1,4 +1,4 @@ -# schema-sha256: 2bb6a47d645d5027d15ea70545473ac3dd417e8a2d7ac932d3c593d71a539dbd +# schema-sha256: ca218a3bc93a1cc9466eca3ca51409ffb233df8af2cb56de31ee7b86133c8a0c { lib, ... }: let defaultLayout = ( @@ -371,6 +371,11 @@ in default = "Tile"; description = "Determine what happens to a new window when the Floating workspace layer is active"; }; + initial_workspace_rules = lib.mkOption { + type = (lib.types.nullOr (lib.types.listOf matchingRule)); + default = null; + description = "Initial workspace application rules"; + }; layout = lib.mkOption { type = (lib.types.nullOr defaultLayout); default = "BSP"; @@ -438,6 +443,11 @@ in default = null; description = "Workspace padding (default: global)"; }; + workspace_rules = lib.mkOption { + type = (lib.types.nullOr (lib.types.listOf matchingRule)); + default = null; + description = "Permanent workspace application rules"; + }; }; } ) diff --git a/nix/tests/default.nix b/nix/tests/default.nix index 696979af..807d38ef 100644 --- a/nix/tests/default.nix +++ b/nix/tests/default.nix @@ -32,7 +32,10 @@ let builtins.toJSON (filterNulls evaluated) ); - exampleJson = ../../docs/komorebi.example.json; + # the file has comment lines (komorebi reads them), which the schema checker does not + exampleJson = pkgs.runCommand "komorebi.example.json" { } '' + grep -v '^\s*//' ${../../docs/komorebi.example.json} > $out + ''; schema = ../../schema.json; in pkgs.runCommand "nix-options-validation" diff --git a/nix/tests/komorebi-example.nix b/nix/tests/komorebi-example.nix index 039ab08b..4946b043 100644 --- a/nix/tests/komorebi-example.nix +++ b/nix/tests/komorebi-example.nix @@ -19,6 +19,7 @@ { name = "I"; layout = "BSP"; + initial_workspace_rules = [ ]; } { name = "II"; diff --git a/nix/tests/vm/suites/commands/test.py b/nix/tests/vm/suites/commands/test.py index ced4ee2a..01cafca9 100644 --- a/nix/tests/vm/suites/commands/test.py +++ b/nix/tests/vm/suites/commands/test.py @@ -331,6 +331,14 @@ clear-session-float-rules toggle-float ignore-rule exe nonexistent manage-rule exe nonexistent +initial-workspace-rule exe nonexistent 0 1 +workspace-rule exe nonexistent 0 1 +initial-named-workspace-rule exe nonexistent two +named-workspace-rule exe nonexistent two +enforce-workspace-rules +clear-workspace-rules 0 1 +clear-named-workspace-rules two +clear-all-workspace-rules manage close retile diff --git a/nix/tests/vm/suites/workspace-rules/default.nix b/nix/tests/vm/suites/workspace-rules/default.nix new file mode 100644 index 00000000..bb57ac90 --- /dev/null +++ b/nix/tests/vm/suites/workspace-rules/default.nix @@ -0,0 +1,5 @@ +{ + tier = "fast"; + kind = "headless"; + timeoutMinutes = 10; +} diff --git a/nix/tests/vm/suites/workspace-rules/test.py b/nix/tests/vm/suites/workspace-rules/test.py new file mode 100644 index 00000000..5d53a911 --- /dev/null +++ b/nix/tests/vm/suites/workspace-rules/test.py @@ -0,0 +1,190 @@ +# Workspace rules in a real KWin: a rule sends the windows of an application to a workspace, which +# is a virtual desktop, so that a window that opens on the desktop in front leaves the workspace +# in front and is hidden, on the parking desktop, until its workspace is shown. What only a real +# KWin can tell: that the window is out of sight on the parking desktop while the desktop in front +# stays showing, that it is on the desktop of the workspace the rule names and tiled when that +# workspace is shown, that an initial rule sends a window once and a permanent rule sends it back, +# and that the rules a `komorebi.json` gives apply to a window that was open before the daemon +# started. `komorebi/tests/workspace_rules.rs` checks the same against the fake. +import json +import shlex + +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) +# foot sizes itself to whole cells of its font, so its frame can be short of the one asked for +CELL = 24 + + +def open_window(title: str) -> str: + kde.spawn(f"foot -T {shlex.quote(title)} sleep 3000") + kde.wait_for(lambda: kde.wid(title) != "", timeout=30) + return kde.wid(title) + + +def workspace_of(title: str) -> int | None: + """The workspace of the first monitor that has a window with the title in a container.""" + elements = kde.state()["monitors"]["elements"][0]["workspaces"]["elements"] + for index, workspace in enumerate(elements): + for container in workspace["containers"]["elements"]: + if any(w["details"]["title"] == title for w in container["windows"]["elements"]): + return index + return None + + +def shown_workspace() -> int: + return kde.state()["monitors"]["elements"][0]["workspaces"]["focused"] + + +def park_desktop() -> int: + """The number of the parking desktop, counted from 1 as kdotool counts, or 0 for none.""" + names = kde.desktop_names() + return names.index("komorebi-park") + 1 if "komorebi-park" in names else 0 + + +def parked(wid: str) -> bool: + """Whether the window is on the parking desktop, out of sight.""" + return park_desktop() != 0 and kde.desk(wid) == park_desktop() + + +print("== 1. a rule that was made while the daemon runs") +kde.start_komorebi() +checks.check( + "the daemon answers komorebic", + kde.wait_for(lambda: kde.run("komorebic state")[0] == 0, timeout=30), +) +kde.komorebic("ensure-named-workspaces", "0", "web", "code", "chat") +kde.komorebic("initial-workspace-rule", "title", "sent-once", "0", "1") +kde.komorebic("named-workspace-rule", "title", "sent-always", "chat") + +stay = open_window("stays here") +once = open_window("sent-once one") +checks.check( + "the window the rule names is on workspace 1, whichever way it got there", + kde.wait_for(lambda: workspace_of("sent-once one") == 1, timeout=30), +) +checks.check( + "... and it is out of sight on the parking desktop, while desktop 1 is still showing", + kde.wait_for(lambda: parked(once) and kde.shown() == 1 and shown_workspace() == 0), +) +checks.check( + "the other window is where it opened", + workspace_of("stays here") == 0 and kde.desk(stay) == 1, +) + +kde.komorebic("focus-workspace", "1") +checks.check("workspace 1 is shown", kde.wait_for(lambda: kde.shown() == 2)) +checks.check( + "and the window is back, on KWin's desktop 2, the desktop of its workspace", + kde.wait_for(lambda: kde.desk(once) == 2 and not parked(once)), +) + + +def tiled(title: str) -> bool: + want, wid = daemon.asked(kde.komorebi_log(), title), kde.wid(title) + if want is None or wid == "": + return False + have = kde.rect(wid) + return (have.x, have.y) == (want.x, want.y) and 0 <= want.w - have.w < CELL + + +checks.check( + "the window is tiled where komorebi asked", + kde.wait_for(lambda: tiled("sent-once one")), +) + +print("== 2. an initial rule sends a window once, a permanent rule every time") +kde.komorebic("move-to-workspace", "0") +checks.check( + "the user takes the window back to workspace 0", + kde.wait_for(lambda: workspace_of("sent-once one") == 0 and kde.desk(once) == 1), +) +always = open_window("sent-always one") +checks.check( + "a window the permanent rule names goes to the workspace named chat (2), out of sight", + kde.wait_for(lambda: workspace_of("sent-always one") == 2 and parked(always)), +) +checks.check( + "the window the initial rule sent is where the user put it", + workspace_of("sent-once one") == 0, +) +kde.komorebic("focus-workspace", "2") +checks.check( + "showing chat brings the window back to KWin's desktop 3", + kde.wait_for(lambda: kde.desk(always) == 3 and not parked(always)), +) +kde.komorebic("move-to-workspace", "0") +# a new window is an event, and every event looks at the rules first +open_window("poke one") +checks.check( + "the permanent rule sends the window back at the next event", + kde.wait_for(lambda: workspace_of("sent-always one") == 2, timeout=30), +) +kde.komorebic("enforce-workspace-rules") +checks.check( + "enforce-workspace-rules sends the initial rule's window again", + kde.wait_for(lambda: workspace_of("sent-once one") == 1, timeout=30), +) + +print("== 3. the rules can all be taken away") +kde.komorebic("clear-all-workspace-rules") +state_rules = json.loads(kde.komorebic("global-state"))["workspace_rules"] +checks.check("no rule is left", state_rules == []) +later = open_window("sent-once two") +checks.check( + "a window that opens now stays on the workspace in front", + kde.wait_for(lambda: workspace_of("sent-once two") == shown_workspace(), timeout=30) + and kde.desk(later) == kde.shown(), +) + +print("== 4. the rules of komorebi.json, with a window that was open before the daemon") +kde.komorebic("stop") +kde.wait_for(lambda: not kde.komorebi_running(), timeout=30) +CONFIG = "/tmp/rules-config.json" +kde.sh( + "printf %s " + + shlex.quote( + json.dumps( + { + "monitors": [ + { + "workspaces": [ + {"name": "web", "layout": "BSP"}, + { + "name": "code", + "layout": "BSP", + "workspace_rules": [ + { + "kind": "Title", + "id": "stays here", + "matching_strategy": "StartsWith", + } + ], + }, + ] + } + ] + } + ) + ) + + f" > {CONFIG}" +) +kde.start_komorebi("--config", CONFIG) +checks.check( + "the daemon answers komorebic again", + kde.wait_for(lambda: kde.run("komorebic state")[0] == 0, timeout=30), +) +checks.check( + "the window that was open when it started is on the workspace the file names, out of sight", + kde.wait_for(lambda: workspace_of("stays here") == 1 and parked(stay), timeout=30), +) + +kde.komorebic("stop") +checks.check("a clean stop", kde.wait_for(lambda: not kde.komorebi_running())) +kde.stop() +checks.finish() diff --git a/schema.json b/schema.json index c0e9cd65..0977a436 100644 --- a/schema.json +++ b/schema.json @@ -962,6 +962,16 @@ ], "default": "Tile" }, + "initial_workspace_rules": { + "description": "Initial workspace application rules", + "type": [ + "array", + "null" + ], + "items": { + "$ref": "#/$defs/MatchingRule" + } + }, "layout": { "description": "Layout", "anyOf": [ @@ -1090,6 +1100,16 @@ "null" ], "format": "int32" + }, + "workspace_rules": { + "description": "Permanent workspace application rules", + "type": [ + "array", + "null" + ], + "items": { + "$ref": "#/$defs/MatchingRule" + } } }, "required": [