From 21017b573f73e0b15c0cbeaff153751bc7c46921 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 19:59:53 -0700 Subject: [PATCH] feat(wm): initial window placement rules A window that opens goes after the focused container. A workspace can now say another place for its windows: the primary or the secondary tile, before or after the focused container, the end of the list, or a place by number, counting from 1. The place is for every window, or for the windows that match a rule on their program, app id, title or path; the rules are the conditions the ignore and manage rules are made of, and the first that matches in key order decides. A place that does not exist, such as the secondary tile of a workspace with one container, is the default place. A place is read from a name, a number or text that is a number. The documentation of the setting shows a number and a map's keys can only be text, and komorebi for Windows (83c4e11d) reads only text, so the form its own page shows is refused there. A place that was reserved with preselect-direction is used before the rules are asked, and a locked container keeps its index. A workspace whose window_container_behaviour is Append puts a window in the focused container, and the rules are not used. A workspace takes the rules from the key initial_window_placement_rules of its entry in komorebi.json. The key is in schema.json and so in the typed config option of the module, and the page docs/initial-window-placement-rules.md says how to write it. vm-placement opens windows in a headless KWin and checks where they go, by program, app id and title. The schema that schemars derives for a place is an object with a Placement or an Index key, which is not what is read or written, so a check against it refuses a file that the daemon reads. The schema of PlacementTarget is written by hand instead: a name, a number, or text that is a number. A file with a place of each form is checked against schema.json, and the module's config option takes them. --- README.md | 5 +- docs/dev/ARCHITECTURE.md | 53 ++++- docs/dev/DESIGN.md | 16 ++ docs/index.md | 2 + docs/initial-window-placement-rules.md | 267 ++++++++++++++++++++++ docs/usage/configuration.md | 1 + docs/usage/managing-windows.md | 3 +- docs/usage/maximizing-windows.md | 8 +- docs/usage/stacking-windows.md | 7 +- komorebi/src/core/mod.rs | 209 +++++++++++++++++ komorebi/src/state.rs | 3 + komorebi/src/static_config.rs | 7 + komorebi/src/workspace.rs | 144 +++++++++++- komorebi/tests/placement.rs | 251 ++++++++++++++++++++ komorebi/tests/placement_cases.rs | 152 ++++++++++++ komorebi/tests/schemas.rs | 67 +++++- nix/komorebi-options.nix | 30 ++- nix/tests/default.nix | 79 ++++++- nix/tests/nixos-module.nix | 50 ++++ nix/tests/vm/suites/placement/default.nix | 5 + nix/tests/vm/suites/placement/test.py | 131 +++++++++++ schema.json | 100 ++++++++ 22 files changed, 1567 insertions(+), 23 deletions(-) create mode 100644 docs/initial-window-placement-rules.md create mode 100644 komorebi/tests/placement.rs create mode 100644 komorebi/tests/placement_cases.rs create mode 100644 nix/tests/vm/suites/placement/default.nix create mode 100644 nix/tests/vm/suites/placement/test.py diff --git a/README.md b/README.md index 6661900a..f0115ce3 100644 --- a/README.md +++ b/README.md @@ -261,7 +261,10 @@ names, layouts, paddings and rules. It watches the file, and when it changes applies it again to the windows it has. It also sets what a window that opens gets (`window_container_behaviour`, `float_override`, `floating_layer_behaviour`, for a workspace or for all of them) and what focusing does in monocle -(`monocle_focus_behaviour`). A key that komorebi for KDE does not read +(`monocle_focus_behaviour`). Where a new window goes in the layout is the +workspace's `initial_window_placement_rules`: after the focused container unless +they say another place, which can depend on the window's program, app id or +title. A key that komorebi for KDE does not read is ignored, so one file serves every platform. Rules for particular applications can be in files of their own, which `app_specific_configuration_path` names. `workspace-layout-rule` makes a diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index f32f604f..1a0bd342 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -63,6 +63,10 @@ that is added has its place here. - **Rule**: a condition on a window's title, executable, class or path ([`MatchingRule`]), in one of the process-wide lists that decide whether a window is managed (the ignore and the manage rules) and whether it floats when it opens (the float rules). +- **Placement rule**: where in the list of containers the container of a new window goes: a place, + such as the first or the last, for every window, or a place for the windows that match a + condition ([`InitialWindowPlacementRules`]). A workspace has none unless it is given them, and a + window goes after the focused container. - **Direction**: where an order goes from the focused container: a side of its tile ([`OperationDirection`]), or the next or the previous container of the workspace ([`CycleDirection`]). @@ -138,7 +142,8 @@ the same thing at every level. - A **workspace** ([`Workspace`]) has a layout, its padding, an optional work area offset of its own, whether it takes the monitor's window-based offset, its containers, in order, its monocle container and its maximized window, if it has them, and its floating windows, which - are in no container and which the layout does not tile, and which layer it is on. + are in no container and which the layout does not tile, which layer it is on, and its placement + rules, if it has them. - A **container** ([`Container`]) has its windows. A new window gets a container of its own, unless the window container behavior says to put it in the focused one. With more than one window it is a stack: the focused window is in front and the others are hidden. A @@ -777,6 +782,22 @@ gives a tile, and [`Workspace::new_container_for_window`] puts the next window i `CancelPreselect` removes it. A workspace reserves one place at a time, and the grid layout none. +A new window's container goes after the focused container, unless the workspace has placement +rules ([`Workspace::initial_window_placement_rules`]), which the entry of the workspace in +`komorebi.json` gives it ([`Workspace::load_static_config`]). A rule is a place for every window, +or a map from places to conditions, which are the conditions of the ignore and manage rules and are +read by [`should_act`] and [`should_act_individual`]; the first place in key order whose condition +matches the window is the window's. A place is a strategy ([`WindowPlacement`]: the primary tile, +the secondary, before the focused container, after it, the last place) or a number counting from +1, and the primary and the secondary tile are indexes 0 and 1 of every layout +([`Workspace::new_container_for_window`]). A place that does not exist, such as the secondary tile +of a workspace with one container or a number past the end, is the default place. A reserved place +(`PreselectDirection`) is used before the rules are asked, and the container is inserted through +`LockableSequence`, so that a rule that asks for the index of a locked container gets the index +after it. The rules apply wherever a window gets a container of its own: a window that opens, one +that comes back from a minimize, one that `ManageFocusedWindow` takes in, one that comes out of a +stack, and one that a workspace rule or the compositor moves to the workspace. + ## Dragging The user can move a window with the pointer, and resize it by dragging an edge. KWin reports the @@ -884,7 +905,8 @@ defaults. The settings of the borders are statics too, which the file sets and [`border_manager::current_look`] and the layout read. A **rule** is an entry of one of the process-wide lists. A workspace's own `layout_rules`, `work_area_offset_rules` and `window_container_behaviour_rules` are fields of the [`Workspace`], which [`Workspace::update`] -reads each time it tiles. +reads each time it tiles, and so are its `initial_window_placement_rules`, which +[`Workspace::new_container_for_window`] reads when a window gets a container. 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 @@ -954,6 +976,8 @@ goes the other way, for `GenerateStaticConfig`. | A workspace's own layout options replace the defaults of its layout, whole | framework path: [`Workspace::update`] takes the workspace's options and rules when it has either, and else those of `layout_defaults` | `layout_options_of_a_workspace_replace_the_defaults_of_its_layout` | none | | The highest of the rules a count of containers reaches decides the layout, the offset and the container behavior | framework path: [`Workspace::update`] reads the rules, kept in the order of their thresholds | `layout_rules_change_the_layout_with_the_number_of_windows`, `work_area_offset_rules_change_the_offset_with_the_number_of_windows`, `window_container_behaviour_rules_change_the_behaviour_with_the_number_of_containers` | none | | A workspace's own container behavior and float override come before the one for every workspace, and its floating layer behavior before its monitor's, which comes before the one for every workspace | framework path: [`WindowManager::window_management_behaviour`] reads the workspace, then (for the floating layer) the monitor, then the window manager | `the_behaviour_of_a_workspace_comes_before_the_one_for_every_workspace`, `the_float_override_of_a_workspace_comes_before_the_one_for_every_workspace`, `the_floating_layer_behaviour_of_a_workspace_comes_before_a_monitors_and_that_before_the_default` | none | +| A workspace places the windows that open by the `initial_window_placement_rules` of its entry in `komorebi.json` | framework path: [`Workspace::load_static_config`] sets [`Workspace::initial_window_placement_rules`] from the entry, and [`Workspace::new_container_for_window`] reads it | `a_workspace_in_komorebi_json_has_them`, `the_rules_come_from_the_configuration_of_the_workspace`, `vm-placement` | none | +| The schema, and the module's typed `config`, take a place in each form the daemon reads: a name, a number, or text that is a number | test: the schema of [`PlacementTarget`] is written by hand, to say what its `Serialize` and `Deserialize` do, and a file with a place of each form is checked against `schema.json` | `a_place_is_described_as_a_name_a_number_or_text_that_is_a_number`, `nix-options-validation`, `nixos-module-eval` ("the place a workspace gives the windows that open is a typed option in each form it is read") | none | | The configuration the daemon generates loads and says the same | test | `a_configuration_comes_out_again_as_the_settings_of_the_window_manager` | none | | The daemon reads the file it is given or the one in the config home, not both | startup order: `main.rs` takes `--config` before the config home | `the_daemon_follows_the_file_it_is_given_when_the_file_changes`, `the_daemon_reads_komorebi_json_from_the_config_home` | none | @@ -1293,6 +1317,14 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | A window that leaves fullscreen is put in the tile the layout has for it | framework path: `handle_event` tiles the workspace in front again on a `FullscreenChange` back from fullscreen | `a_fullscreen_window_is_left_covering_the_monitor_and_goes_back_to_its_tile_afterwards` | none | | The bridge reports a fullscreen change with what the window is now | test: the bridge reads `fullScreen` when KWin raises `fullScreenChanged`, and the table keeps it | `bridge.test.js` ("a window that goes fullscreen or comes back from it is reported as it is now", and the session), `going_fullscreen_and_coming_back_are_events_and_are_remembered` | none | | In a real KWin, a fullscreen window covers the monitor, a window that opens does not take it out of fullscreen, and it goes back to a tile that overlaps no other | VM test | `vm-features` (section E) | none | +| Without placement rules a window goes after the focused container | framework path: `resolve_placement_index` returns that index when the workspace has no rules, or none matches | `without_rules_a_window_goes_after_the_focused_one` | none | +| A place that does not exist is the default place, never an error | framework path: `resolve_placement_index` falls back to the default for a number past the end and for the secondary tile of one container | `a_place_that_is_not_there_is_the_default` | none | +| The first rule in key order decides | framework path: the rules are a `BTreeMap` ordered by the text of the place | `the_first_rule_in_key_order_wins`, `a_place_for_the_windows_that_match_a_rule` | none | +| A rule of several conditions needs all of them | framework path: a composite [`MatchingRule`] is read by [`should_act`], which needs every part | `a_rule_of_several_conditions_needs_them_all` | none | +| A setting that is not a place is refused | type system: `PlacementTarget` reads a strategy name or a number, and nothing else; checked when the setting is read | `a_place_that_is_not_one_is_refused` | none | +| A reserved place wins over the rules | framework path: [`Workspace::new_container_for_window`] checks `preselected_container_idx` before it asks for a place | `a_place_that_was_preselected_wins_over_the_rules` | none | +| A locked container keeps its index when a rule asks for it | framework path: the container is inserted through `LockableSequence` | `a_rule_that_asks_for_the_place_of_a_locked_container_gets_the_place_after_it` | none | +| In a real KWin, windows go where the rules say, by program, app id and title | VM test | `vm-placement` | none | | A window stays maximized through a retile | framework path: [`Workspace::update`] asks the backend to maximize it again, and moves no container | `a_retile_while_a_window_is_maximized_asks_the_compositor_to_maximize_it_again` | none | | A maximized window that closes takes the maximize with it | framework path: [`Workspace::remove_window`] looks at the maximized window first, which the index of managed windows lists | `a_maximized_window_that_closes_leaves_the_layout_whole` | none | | In a real KWin, the maximized window fills the work area, is on top, and goes back to its tile | VM test | `vm-features` ("the focused window fills the work area", "and is the one on top", "toggled back, it is in its tile again") | none | @@ -1439,9 +1471,10 @@ A window is shown, and ends up on a tile: 3. The index of managed windows is rebuilt from the containers. If the workspace in front already has the window, or the index has it on another monitor or workspace, the event creates nothing. -4. [`Workspace::new_container_for_window`] puts the window in a new container after the - focused one, inserted through `LockableSequence` so that a locked container keeps its - index, and focuses the new container. +4. [`Workspace::new_container_for_window`] puts the window in a new container, inserted through + `LockableSequence` so that a locked container keeps its index, and focuses the new container. + It goes after the focused one, unless a place was preselected or the workspace's placement + rules give another. 5. [`WindowManager::update_focused_workspace`] asks the focused [`Monitor`] to give its focused workspace the work area, the padding and the offset ([`WorkspaceGlobals`]), and calls [`Workspace::update`]. @@ -1588,6 +1621,9 @@ A window is shown, and ends up on a tile: the user maximizes; [`komorebi/tests/fullscreen.rs`](../../komorebi/tests/fullscreen.rs), a window that goes fullscreen and comes back; + [`komorebi/tests/placement.rs`](../../komorebi/tests/placement.rs) and + [`komorebi/tests/placement_cases.rs`](../../komorebi/tests/placement_cases.rs), the placement + rules; [`komorebi/tests/manage.rs`](../../komorebi/tests/manage.rs), minimizing, closing, unmanaging and managing the focused window, and pausing; [`komorebi/tests/padding.rs`](../../komorebi/tests/padding.rs), the paddings and the work area @@ -1605,6 +1641,8 @@ A window is shown, and ends up on a tile: screen of a real compositing session, read from screenshots. - [`nix/tests/vm/suites/user-maximize`](../../nix/tests/vm/suites/user-maximize/test.py): a window the user maximizes, in a real KWin. +- [`nix/tests/vm/suites/placement`](../../nix/tests/vm/suites/placement/test.py): where the + windows of a real KWin go in the layout, by the placement rules of a `komorebi.json`. - [`nix/tests/vm/suites/commands`](../../nix/tests/vm/suites/commands/test.py): every layout, and every `komorebic` command, against a real KWin with two outputs. - [`nix/tests/vm/suites/drag-resize`](../../nix/tests/vm/suites/drag-resize/test.py): edges and @@ -1714,6 +1752,7 @@ A window is shown, and ends up on a tile: [`Window`]: ../../komorebi/src/window.rs [`Window::should_manage`]: ../../komorebi/src/window.rs [`should_act`]: ../../komorebi/src/window.rs +[`should_act_individual`]: ../../komorebi/src/window.rs [`RuleDebug`]: ../../komorebi/src/window.rs [`GlobalState`]: ../../komorebi/src/state.rs [`MatchingRule`]: ../../komorebi/src/core/config_generation.rs @@ -1787,6 +1826,10 @@ A window is shown, and ends up on a tile: [`WindowManager::adopt_maximize_change`]: ../../komorebi/src/window_manager.rs [`WindowInfo::maximized`]: ../../komorebi/src/backend/mod.rs [`WindowInfo::fullscreen`]: ../../komorebi/src/backend/mod.rs +[`InitialWindowPlacementRules`]: ../../komorebi/src/core/mod.rs +[`PlacementTarget`]: ../../komorebi/src/core/mod.rs +[`WindowPlacement`]: ../../komorebi/src/core/mod.rs +[`Workspace::initial_window_placement_rules`]: ../../komorebi/src/workspace.rs [`load_workspace_information`]: ../../komorebi/src/desktop.rs [`WindowManager::adjust_workspace_padding`]: ../../komorebi/src/window_manager.rs [`Workspace::apply_window_based_work_area_offset`]: ../../komorebi/src/workspace.rs diff --git a/docs/dev/DESIGN.md b/docs/dev/DESIGN.md index 7af4222c..b509879d 100644 --- a/docs/dev/DESIGN.md +++ b/docs/dev/DESIGN.md @@ -671,3 +671,19 @@ tile it has now" (the comment in `handle_event`), so the workspace is tiled agai second request for a position gives up after three tries for the same reason: so that a window that cannot go where it was asked, "a fullscreen one, say", is left alone rather than chased (the comment on `settle` in [`bridge.js`](../../komorebi/src/kwin/bridge.js)). + +## Why does `initial_window_placement_rules` take a number as well as text? + +Because the documentation of the setting shows a number (`"initial_window_placement_rules": 3`), +and a JSON object's keys can only be text: the doc comment on the `Deserialize` of +[`PlacementTarget`](../../komorebi/src/core/mod.rs) says both. The place is read from `"Primary"`, +`"3"` and `3`, so the form the page shows works as well as the form a map's keys force. In komorebi +for Windows, at its commit 83c4e11d, the deserializer reads only text, so the number its page shows +is refused. [The page of this repository](../initial-window-placement-rules.md#on-kde) says which +forms are read. + +The JSON schema of the type is written by hand, so that it says the same. The one `schemars` +derives for the enum is an object with a `Placement` or an `Index` key, which the comment on the +`JsonSchema` impl of [`PlacementTarget`](../../komorebi/src/core/mod.rs) calls "not what +`Serialize` and `Deserialize` read and write". The schema `schema.json` has says a name, a number, +or text that is a number, which is also what the module's typed `config` takes. diff --git a/docs/index.md b/docs/index.md index 1203a5cf..2ec15045 100644 --- a/docs/index.md +++ b/docs/index.md @@ -51,6 +51,8 @@ window and pause the daemon, and and keep parts of a monitor free of them. [Rules](usage/rules.md) explains how to keep an application out of the layout, always tile it, or float its windows. +[Initial window placement rules](initial-window-placement-rules.md) explains how to say where in the +layout a window goes when it opens. [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, and [Workspace rules](usage/workspace-rules.md) how to have the windows of an application go to a diff --git a/docs/initial-window-placement-rules.md b/docs/initial-window-placement-rules.md new file mode 100644 index 00000000..99a0aabf --- /dev/null +++ b/docs/initial-window-placement-rules.md @@ -0,0 +1,267 @@ +# Initial window placement rules + +By default, when a new window opens, komorebi puts it **after the focused container**. The +`initial_window_placement_rules` setting of a workspace, in its entry in +[`komorebi.json`](usage/configuration.md#monitors-and-workspaces), controls where new tiled windows +go in the list of containers. + +The setting only applies when the workspace's `window_container_behaviour` is `Create`, which is +the default. With `Append` (see [Stacking windows](usage/stacking-windows.md)), a new window goes +into the focused container whatever the rules say. + +## The two forms + +`initial_window_placement_rules` takes a place for every window, or a map from places to the +windows that go there. + +### A place for every window + +A placement strategy (a string) or a container index (a number, counting from 1): + +```json +{ + "monitors": [ + { + "workspaces": [ + { + "name": "main", + "initial_window_placement_rules": "Primary" + } + ] + } + ] +} +``` + +With a number, every new window goes to that place: + +```json +{ + "monitors": [ + { + "workspaces": [ + { + "name": "main", + "initial_window_placement_rules": 3 + } + ] + } + ] +} +``` + +This puts every new window third. If there is no such place, the window goes where it would +have gone without a rule, after the focused container. The place after the last container is +there: `4` is the end of a list of three. + +The strategies: + +| Strategy | Where the window goes | +|----------|-----------------------| +| `Primary` | The primary (largest) tile: index 0 in every built-in layout | +| `Secondary` | The secondary tile: index 1 in every built-in layout, and none when there is only one container | +| `BeforeFocused` | Before the focused container | +| `AfterFocused` | After the focused container (the default) | +| `Last` | At the end of the list | + +### A place for the windows that match + +A map from a strategy or a number to the rule that says which windows go there. The key is a +strategy or a place counted from 1, as text: + +```json +{ + "monitors": [ + { + "workspaces": [ + { + "name": "main", + "initial_window_placement_rules": { + "Primary": { + "kind": "Exe", + "id": "firefox", + "matching_strategy": "Equals" + }, + "Last": { + "kind": "Title", + "id": "Chat", + "matching_strategy": "Contains" + } + } + } + ] + } + ] +} +``` + +Here the windows of Firefox take the primary tile, a window with "Chat" in its title goes to the end +of the list, and every other window goes after the focused container. + +## What a rule matches + +A rule is the same condition the [ignore and manage rules](usage/rules.md) are made of: a `kind` +(`Exe`, `Class`, `Title` or `Path`), an `id`, and a `matching_strategy`. + +### One condition + +```json +{ + "kind": "Exe", + "id": "firefox", + "matching_strategy": "Equals" +} +``` + +### Several windows for one place (OR) + +An array is a list of conditions, and a window goes to the place when **any** of them matches it: + +```json +{ + "initial_window_placement_rules": { + "Primary": [ + { "kind": "Exe", "id": "firefox", "matching_strategy": "Equals" }, + { "kind": "Exe", "id": "chromium", "matching_strategy": "Equals" } + ] + } +} +``` + +This puts Firefox and Chromium in the primary tile. + +### A window that matches all of them (AND) + +An array inside the array is a condition that needs **all** of its parts: + +```json +{ + "initial_window_placement_rules": { + "Primary": [ + [ + { "kind": "Exe", "id": "code", "matching_strategy": "Equals" }, + { "kind": "Title", "id": "workspace", "matching_strategy": "Contains" } + ] + ] + } +} +``` + +This only matches windows of `code` with "workspace" in their title. + +### Both + +The two can be mixed in one list: + +```json +{ + "initial_window_placement_rules": { + "Primary": [ + { "kind": "Exe", "id": "firefox", "matching_strategy": "Equals" }, + [ + { "kind": "Exe", "id": "code", "matching_strategy": "Equals" }, + { "kind": "Title", "id": "workspace", "matching_strategy": "Contains" } + ] + ] + } +} +``` + +This puts every window of Firefox in the primary tile, and so every window of `code` that has +"workspace" in its title. + +## The primary and secondary tiles + +In every built-in layout the primary container is the one at index 0, the largest tile, and the +secondary is the one at index 1. Flipping a layout moves the tiles on the screen and not the +indexes of the containers. + +| Layout | Primary (index 0) | Secondary (index 1) | +|--------|-------------------|---------------------| +| **BSP** | The largest split | The second split | +| **VerticalStack** | The left column | The first row of the right stack | +| **RightMainVerticalStack** | The right column | The first row of the left stack | +| **HorizontalStack** | The top row | The first column of the bottom stack | +| **UltrawideVerticalStack** | The center column | The left column | +| **Columns** | The first column | The second column | +| **Rows** | The first row | The second row | +| **Grid** | The first cell | The second cell | +| **Scrolling** | The first column | The second column | + +Custom layouts are not supported on KDE yet. + +## The order rules are tried in + +The rules of the map form are tried in the order of their keys, and the first that matches +decides. A key is compared as text: a number sorts before a name, `10` before `2`, and the names +alphabetically. + +```json +{ + "initial_window_placement_rules": { + "1": { "kind": "Exe", "id": "firefox", "matching_strategy": "Equals" }, + "Primary": { "kind": "Exe", "id": "chromium", "matching_strategy": "Equals" }, + "Secondary": { "kind": "Title", "id": "Chat", "matching_strategy": "Contains" } + } +} +``` + +The keys are tried in this order: `"1"`, `"Primary"`, `"Secondary"`. A new window goes: + +- of `firefox`: to place 1, the first; +- of `chromium`: to the primary tile, which is also the first place, but is found from the layout; +- with "Chat" in its title: to the secondary tile; +- any other: after the focused container. + +A mix of numbers and names sorts like this: + +| Key | Position | +|-----|----------| +| `"1"` | 1st | +| `"10"` | 2nd | +| `"2"` | 3rd | +| `"AfterFocused"` | 4th | +| `"Last"` | 5th | +| `"Primary"` | 6th | +| `"Secondary"` | 7th | + +Most configurations have a few keys, and the order does not matter. When a window matches two +keys, the first of these decides. + +If a rule matches and its place does not exist (a rule for place 5 on a workspace of three +containers), that match is ignored and the window goes after the focused container. + +## Other things that decide + +- A place that was reserved with [`preselect-direction`](cli/preselect-direction.md) wins over the + rules, and the rules are back for the next window. +- `window_container_behaviour`: while a workspace has `Append`, because its entry says so, because + of its `window_container_behaviour_rules`, or because + [`toggle-workspace-window-container-behaviour`](cli/toggle-workspace-window-container-behaviour.md) + switched it, the rules are not used. +- The rules decide for every window that gets a container of its own, not only for one that opens: + one that comes back from being minimized, one that + [`manage`](cli/manage.md) puts back in the layout, one that + [`unstack`](cli/unstack.md) takes out of a stack, and one that a + [workspace rule](usage/workspace-rules.md) or KWin moves to the workspace. +- A locked container keeps its index: a window that a rule puts at the index of a locked container + goes just after it. +- The container a window opens in takes the focus, as it does without a rule. + +## On KDE + +This is the same setting as in komorebi for Windows, and it reads the same configuration. What +differs is how a window is named: + +- `Exe` is the name of the program (`firefox`, `foot`, `code`). A `.exe` in the `id` is ignored, so + a `komorebi.json` with `"chrome.exe"` in it works on every platform. +- `Class` is the Wayland `app_id` of the window (the X11 `WM_CLASS` of a window on XWayland), such + as `org.kde.konsole`. +- `Title` is the title of the window, and `Path` the full path of its executable. + +[`komorebic state`](cli/state.md) shows all four for every window. The matching strategies are +those of the [ignore and manage rules](usage/rules.md). + +A number is accepted as the whole value of the setting (`"initial_window_placement_rules": 3`), +as this page shows. komorebi for Windows shows the same in its documentation, and as of its commit +83c4e11d its deserializer only reads a number that is quoted: `"3"`. diff --git a/docs/usage/configuration.md b/docs/usage/configuration.md index 755ab493..d1ad18de 100644 --- a/docs/usage/configuration.md +++ b/docs/usage/configuration.md @@ -192,6 +192,7 @@ named for it. A workspace has these keys: | `float_override` | the default | Whether every window that opens on this workspace floats | | `floating_layer_behaviour` | the default | What a window that opens while this workspace is on its floating layer gets: `Tile` or `Float` | | `wallpaper` | none | The picture the monitor shows while this workspace is in front, instead of its monitor's: `{ "path": "~/Pictures/sea.png" }`, and `generate_theme` and `theme_options` for the borders' colors ([Wallpapers](wallpapers.md)) | +| `initial_window_placement_rules` | none | Where in the list of containers a window that opens on this workspace goes: a place, or a place for each kind of window ([Initial window placement rules](../initial-window-placement-rules.md)) | A workspace that names no `layout` and does not say `"tile": true` does not tile: its windows stay where they open. A workspace with `layout_rules` tiles. Otherwise a workspace tiles. diff --git a/docs/usage/managing-windows.md b/docs/usage/managing-windows.md index 80c3a086..b3eab2cd 100644 --- a/docs/usage/managing-windows.md +++ b/docs/usage/managing-windows.md @@ -27,7 +27,8 @@ container of its own, when it is restored. It stays open, in the middle of the work area with the size it had, and komorebi leaves it alone from then on: it does not tile it again, and it does not move it. [`komorebic manage`](../cli/manage.md), with that window focused, puts it back in the layout, -after the focused window. +after the focused window, or where the workspace's +[placement rules](../initial-window-placement-rules.md) say. ```sh komorebic unmanage diff --git a/docs/usage/maximizing-windows.md b/docs/usage/maximizing-windows.md index 5797587d..d593afd6 100644 --- a/docs/usage/maximizing-windows.md +++ b/docs/usage/maximizing-windows.md @@ -13,9 +13,11 @@ komorebic toggle-maximize A window that is the only one of its container takes the container with it, and the container is made again when the window comes back. The tiles that were left are not moved while the window is -maximized: it covers them. A window that opens meanwhile is added to the layout, after the focused -container, and has its tile when the maximized window is restored. A window that closes while it -is maximized takes the maximize with it, and the other windows are tiled again. +maximized: it covers them. A window that opens meanwhile is added to the layout, where a new +window goes (after the focused container, unless the workspace has +[placement rules](../initial-window-placement-rules.md)), and has its tile when the maximized +window is restored. A window that closes while it is maximized takes the maximize with it, and the +other windows are tiled again. A window in [monocle](monocle.md) that is maximized leaves the monocle. When the monitor of a maximized window is unplugged, the window goes to a monitor that is left and stays maximized: see diff --git a/docs/usage/stacking-windows.md b/docs/usage/stacking-windows.md index cc69716d..9d91b1d7 100644 --- a/docs/usage/stacking-windows.md +++ b/docs/usage/stacking-windows.md @@ -18,9 +18,10 @@ komorebic stack down ``` [`komorebic unstack`](../cli/unstack.md) takes the window in front out of its stack and puts it -in a tile of its own after the stack, and the next window of the stack is in front again. A -window that is alone on its tile cannot be unstacked, and the daemon logs "a container must have -at least one window". +in a tile of its own, and the next window of the stack is in front again. The tile is after the +stack, unless the workspace has [placement rules](../initial-window-placement-rules.md), which +say where a window goes that gets a tile of its own. A window that is alone on its tile cannot be +unstacked, and the daemon logs "a container must have at least one window". ```sh komorebic unstack diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index 6a9b2b88..bddcb02c 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -183,6 +183,215 @@ pub enum FocusFollowsMouseImplementation { Windows, } +#[derive( + Clone, + Copy, + Debug, + Default, + Serialize, + Deserialize, + Display, + EnumString, + ValueEnum, + PartialEq, + Eq, + Hash, +)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Placement strategy for new windows in a workspace +pub enum WindowPlacement { + /// Place the new window at the primary (largest) container position + Primary, + /// Place the new window at the secondary container position + Secondary, + /// Place the new window before the currently focused container + BeforeFocused, + /// Place the new window after the currently focused container (default behavior) + #[default] + AfterFocused, + /// Place the new window at the end of the container list + Last, +} + +/// A target position for window placement, used as a key in `InitialWindowPlacementRules::Rules`. +/// +/// Can be either a `WindowPlacement` variant name (e.g. `"Primary"`, `"Last"`) +/// or a 1-based container index (e.g. `"1"`, `"3"`). +/// +/// NOTE: Integer indices are 1-based in the config for user-friendliness. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum PlacementTarget { + /// A named placement strategy + Placement(WindowPlacement), + /// A 1-based container index + Index(usize), +} + +impl std::fmt::Display for PlacementTarget { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + PlacementTarget::Placement(p) => write!(f, "{p}"), + PlacementTarget::Index(i) => write!(f, "{i}"), + } + } +} + +impl std::str::FromStr for PlacementTarget { + type Err = String; + + fn from_str(s: &str) -> Result { + // Try parsing as a WindowPlacement variant first + if let Ok(placement) = ::from_str(s) { + return Ok(PlacementTarget::Placement(placement)); + } + // Then try parsing as a 1-based index + if let Ok(idx) = s.parse::() { + return Ok(PlacementTarget::Index(idx)); + } + Err(format!( + "'{s}' is not a valid WindowPlacement variant or integer" + )) + } +} + +impl PartialOrd for PlacementTarget { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for PlacementTarget { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.to_string().cmp(&other.to_string()) + } +} + +impl Serialize for PlacementTarget { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(&self.to_string()) + } +} + +impl<'de> Deserialize<'de> for PlacementTarget { + /// A name or a number: `"Primary"`, `"3"` and `3` (the documentation of the setting shows a + /// number, and a JSON object's keys can only be text) + fn deserialize>(deserializer: D) -> Result { + #[derive(Deserialize)] + #[serde(untagged)] + enum Raw { + Text(String), + Number(usize), + } + + match Raw::deserialize(deserializer)? { + Raw::Text(text) => text.parse().map_err(serde::de::Error::custom), + Raw::Number(index) => Ok(PlacementTarget::Index(index)), + } + } +} + +/// The schema is written by hand, since the one `schemars` derives for the enum (an object with a +/// `Placement` or an `Index` key) is not what [`Serialize`] and [`Deserialize`] read and write: a +/// name, a number, or text that is a number. +#[cfg(feature = "schemars")] +impl schemars::JsonSchema for PlacementTarget { + fn schema_name() -> std::borrow::Cow<'static, str> { + std::borrow::Cow::Borrowed("PlacementTarget") + } + + fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema { + schemars::json_schema!({ + "description": "A place in the list of containers: the name of a placement strategy, or a 1-based container index, as a number or as text (`3` and `\"3\"` are the same place; the keys of a JSON object can only be text).", + "anyOf": [ + generator.subschema_for::(), + { + "description": "A 1-based container index", + "type": "integer", + "format": "uint", + "minimum": 0 + }, + { + "description": "A 1-based container index, as text", + "type": "string", + "pattern": "^[0-9]+$" + } + ] + }) + } +} + +/// Configuration for initial window placement rules on a workspace. +/// +/// This can be specified in two forms in the JSON config: +/// - A placement target (string or integer) — applies the same placement to all windows. +/// Strings are `WindowPlacement` variant names (e.g. `"Primary"`, `"AfterFocused"`), +/// integers are 1-based container indices. +/// - A map of placement targets to matching rules — keys can be `WindowPlacement` variant names +/// (e.g. `"Primary"`, `"Secondary"`) or 1-based container indices (e.g. `"1"`, `"3"`). +/// Rules are evaluated in key order; the first matching rule determines placement. +/// +/// NOTE: Container indices in the config are 1-based for user-friendliness. +/// They are converted to 0-based internally during resolution. +/// +/// NOTE: This feature currently only applies when `WindowContainerBehaviour::Create` is active. +/// Future versions may support toggling this for `Append` mode as well. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[serde(untagged)] +pub enum InitialWindowPlacementRules { + /// A single placement target applied to all new windows (string or integer in config) + Target(PlacementTarget), + /// A map of placement targets to matching rules. + /// Keys can be `WindowPlacement` variant names (e.g. `"Primary"`) or 1-based container indices (e.g. `"1"`). + /// Values can be: + /// - A single `IdWithIdentifier` object (simple rule) + /// - An array containing objects and/or arrays: + /// - Each object in the array is an independent simple rule (OR logic between entries) + /// - Each inner array is a composite rule where all conditions must match (AND logic) + /// - The outer array entries are evaluated with OR logic + /// + /// Rules are evaluated in key order; the first matching rule determines placement. + Rules(std::collections::BTreeMap), +} + +/// Matching rules for a placement target. +/// +/// Can be specified in JSON as: +/// - A single `IdWithIdentifier` object — one simple rule +/// - An array of `MatchingRule`s — multiple rules with OR logic between them +/// (each element can be a simple rule object or a composite rule array with AND logic) +/// +/// Examples: +/// ```json +/// // Single rule +/// { "kind": "Exe", "id": "chrome.exe", "matching_strategy": "Equals" } +/// +/// // Multiple rules (OR): chrome OR teams +/// [ +/// { "kind": "Exe", "id": "chrome.exe", "matching_strategy": "Equals" }, +/// { "kind": "Title", "id": "Microsoft Teams", "matching_strategy": "Equals" } +/// ] +/// +/// // Mixed: chrome OR (code.exe AND title contains "workspace") +/// [ +/// { "kind": "Exe", "id": "chrome.exe", "matching_strategy": "Equals" }, +/// [ +/// { "kind": "Exe", "id": "code.exe", "matching_strategy": "Equals" }, +/// { "kind": "Title", "id": "workspace", "matching_strategy": "Contains" } +/// ] +/// ] +/// ``` +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[serde(untagged)] +pub enum PlacementMatchingRules { + /// A single simple matching rule + Single(config_generation::IdWithIdentifier), + /// Multiple matching rules evaluated with OR logic. + /// Each entry is a `MatchingRule`: either a simple rule (object) or composite rule (array, AND logic). + Many(Vec), +} + #[derive( Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize, Display, EnumString, ValueEnum, )] diff --git a/komorebi/src/state.rs b/komorebi/src/state.rs index fe19bff7..4fbbd3e2 100644 --- a/komorebi/src/state.rs +++ b/komorebi/src/state.rs @@ -222,6 +222,9 @@ impl From<&WindowManager> for State { wallpaper: workspace.wallpaper.clone(), workspace_config: None, preselected_container_idx: None, + initial_window_placement_rules: workspace + .initial_window_placement_rules + .clone(), promotion_swap_container_idx: None, }) .collect::>(); diff --git a/komorebi/src/static_config.rs b/komorebi/src/static_config.rs index 18f71709..e97890e2 100644 --- a/komorebi/src/static_config.rs +++ b/komorebi/src/static_config.rs @@ -54,6 +54,7 @@ use crate::core::CrossBoundaryBehaviour; use crate::core::DefaultLayout; use crate::core::FloatingLayerBehaviour; use crate::core::FocusFollowsMouseImplementation; +use crate::core::InitialWindowPlacementRules; use crate::core::Layout; use crate::core::LayoutDefaultEntry; use crate::core::LayoutOptions; @@ -268,6 +269,11 @@ pub struct WorkspaceConfig { /// Specify a wallpaper for this workspace #[serde(skip_serializing_if = "Option::is_none")] pub wallpaper: Option, + /// Initial window placement rules that determine where new tiled windows are placed + /// in the container list. Can be a placement target (a `WindowPlacement` string like + /// `"Primary"` or a 1-based container index), or a map of placement targets to matching rules. + #[serde(skip_serializing_if = "Option::is_none")] + pub initial_window_placement_rules: Option, } impl From<&Workspace> for WorkspaceConfig { @@ -367,6 +373,7 @@ impl From<&Workspace> for WorkspaceConfig { layout_flip: value.layout_flip, floating_layer_behaviour: value.floating_layer_behaviour, wallpaper: None, + initial_window_placement_rules: value.initial_window_placement_rules.clone(), } } } diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index 6944d0b0..cc4eb972 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -11,18 +11,23 @@ //! [`Workspace::work_area_offset_rules`]), and its layout options come from the workspace or from //! the defaults of its layout. +use crate::REGEX_IDENTIFIERS; use crate::backend::backend; use crate::container::Container; use crate::core::Axis; use crate::core::CycleDirection; use crate::core::DefaultLayout; use crate::core::FloatingLayerBehaviour; +use crate::core::InitialWindowPlacementRules; use crate::core::Layout; use crate::core::LayoutDefaultEntry; use crate::core::LayoutOptions; use crate::core::OperationDirection; +use crate::core::PlacementMatchingRules; +use crate::core::PlacementTarget; use crate::core::Rect; use crate::core::WindowContainerBehaviour; +use crate::core::WindowPlacement; use crate::lockable_sequence::LockableSequence; use crate::ring::Ring; use crate::static_config::Wallpaper; @@ -30,6 +35,8 @@ use crate::static_config::WorkspaceConfig; use crate::theme_manager; use crate::window::Window; use crate::window::WindowDetails; +use crate::window::should_act; +use crate::window::should_act_individual; use color_eyre::eyre; use color_eyre::eyre::OptionExt; use komorebi_themes::KomorebiTheme; @@ -115,6 +122,11 @@ pub struct Workspace { pub preselected_container_idx: Option, #[serde(skip_serializing_if = "Option::is_none")] pub promotion_swap_container_idx: Option, + /// Initial window placement rules that determine where new tiled windows are placed + /// ([`Workspace::new_container_for_window`]); with none, a window goes after the focused + /// container + #[serde(skip_serializing_if = "Option::is_none")] + pub initial_window_placement_rules: Option, } /// Which of a workspace's two kinds of windows the focus, move and resize commands act on: the @@ -174,6 +186,7 @@ impl Default for Workspace { wallpaper: None, workspace_config: None, preselected_container_idx: None, + initial_window_placement_rules: None, promotion_swap_container_idx: None, } } @@ -268,8 +281,9 @@ impl HorizontalBounds for Rect { 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 keeps `config` itself + /// what a new window gets and whether it floats, whether it tiles, how its layout is flipped, + /// what a new window does on its floating layer, and where in the layout a new window goes + /// ([`Workspace::initial_window_placement_rules`]), and keeps `config` itself /// ([`Workspace::workspace_config`]) /// /// `layout_defaults` is what `komorebi.json` says every layout has, for the layout options the @@ -348,6 +362,7 @@ impl Workspace { self.wallpaper = config.wallpaper.clone(); // Load layout options directly (LayoutOptions is used in both config and runtime) self.layout_options = config.layout_options; + self.initial_window_placement_rules = config.initial_window_placement_rules.clone(); // Load threshold-based layout options rules, sorted by threshold ascending self.layout_options_rules = @@ -516,8 +531,9 @@ impl Workspace { } /// Puts the window in a container of its own, and focuses that container: in the container a - /// preselection reserved, if there is one, and otherwise after the focused container (at the - /// start of an empty workspace) + /// preselection reserved, if there is one, and otherwise at the index the workspace's initial + /// window placement rules give it ([`Workspace::initial_window_placement_rules`]), which is + /// after the focused container unless they say otherwise (at the start of an empty workspace) pub fn new_container_for_window(&mut self, window: &Window) -> eyre::Result<()> { let next_idx = if let Some(idx) = self.preselected_container_idx { let next = idx; @@ -527,7 +543,7 @@ impl Workspace { } else if self.containers().is_empty() { 0 } else { - self.focused_container_idx() + 1 + self.resolve_placement_index(window) }; let mut container = Container::default(); @@ -538,6 +554,119 @@ impl Workspace { Ok(()) } + /// Resolves the container index at which a new window should be placed, + /// based on the `initial_window_placement_rules` configuration. + /// + /// Falls back to the default placement (`AfterFocused`, + /// i.e. `focused_container_idx() + 1`) when: + /// - No rules are configured + /// - A `Rules` map has no matching rule for the window + /// - A resolved index is out of bounds + fn resolve_placement_index(&self, window: &Window) -> usize { + let fallback_idx = self.focused_container_idx() + 1; + + let Some(rules) = &self.initial_window_placement_rules else { + return fallback_idx; + }; + + match rules { + InitialWindowPlacementRules::Target(target) => { + self.resolve_placement_target(target, fallback_idx) + } + InitialWindowPlacementRules::Rules(rules_map) => { + let (Some(title), Some(exe_name), Some(class), Some(path)) = + (window.title(), window.exe(), window.class(), window.path()) + else { + return fallback_idx; + }; + let path = path.to_string_lossy(); + + let regex_identifiers = REGEX_IDENTIFIERS.lock().clone(); + + // BTreeMap iterates in key order + for (target, placement_rules) in rules_map { + let matched = match placement_rules { + PlacementMatchingRules::Single(id) => should_act_individual( + &title, + &exe_name, + &[class.as_str()], + &path, + id, + ®ex_identifiers, + ), + PlacementMatchingRules::Many(rules) => { + // OR logic: any matching rule triggers placement at this target. + // Each MatchingRule handles its own Simple/Composite (AND) logic + // internally via should_act. + should_act( + &title, + &exe_name, + &[class.as_str()], + &path, + rules, + ®ex_identifiers, + ) + .is_some() + } + }; + + if matched { + return self.resolve_placement_target(target, fallback_idx); + } + } + + // No matching rule found + fallback_idx + } + } + } + + /// Resolves a `WindowPlacement` variant to a concrete container index. + fn resolve_window_placement(&self, placement: &WindowPlacement, fallback_idx: usize) -> usize { + match placement { + WindowPlacement::AfterFocused => self.focused_container_idx() + 1, + WindowPlacement::BeforeFocused => self.focused_container_idx(), + WindowPlacement::Primary => { + let idx = self.layout.primary_index(); + if idx <= self.containers().len() { + idx + } else { + fallback_idx + } + } + WindowPlacement::Secondary => { + if let Some(idx) = self.layout.secondary_index(self.containers().len()) { + if idx <= self.containers().len() { + idx + } else { + fallback_idx + } + } else { + fallback_idx + } + } + WindowPlacement::Last => self.containers().len(), + } + } + + /// Resolves a `PlacementTarget` (either a named placement or a 1-based index) to a concrete container index. + fn resolve_placement_target(&self, target: &PlacementTarget, fallback_idx: usize) -> usize { + match target { + PlacementTarget::Placement(placement) => { + self.resolve_window_placement(placement, fallback_idx) + } + PlacementTarget::Index(idx) => { + // Config indices are 1-based; convert to 0-based + let zero_based = idx.saturating_sub(1); + if zero_based <= self.containers().len() { + zero_based + } else { + fallback_idx + } + } + } + } + // this fn respects locked container indexes - we should use it for pretty much everything // except monocle and maximize toggles pub fn insert_container_at_idx(&mut self, idx: usize, container: Container) -> usize { @@ -908,8 +1037,9 @@ impl Workspace { } /// Takes the focused window out of its container, which is how a window is unstacked, and puts - /// it in a container of its own after the focused one. The container it left is removed when - /// it has no window left, or shows its next window. + /// it in a container of its own, where a new window goes ([`Workspace::new_container_for_window`]): + /// after the focused one, unless the workspace's initial window placement rules say otherwise. + /// The container it left is removed when it has no window left, or shows its next window. /// /// # Errors /// diff --git a/komorebi/tests/placement.rs b/komorebi/tests/placement.rs new file mode 100644 index 00000000..b6b2eff1 --- /dev/null +++ b/komorebi/tests/placement.rs @@ -0,0 +1,251 @@ +//! `initial_window_placement_rules`: where in the list of containers a window that opens is put. +//! +//! The default is after the focused container. A workspace can say another place for every window +//! (`"Primary"`, `"Last"`, `2`, ...), or a place for the windows that match a rule. + +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::core::InitialWindowPlacementRules; +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 std::sync::Arc; + +fn desktop(rules: Option<&str>) -> (Arc, WindowManager) { + let fake = Arc::new(FakeBackend::with_one_monitor()); + let (_sender, receiver) = crossbeam_channel::bounded(1); + static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let socket = std::path::PathBuf::from(format!( + "/tmp/kmp-{}-{}.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 + }); + + if let Some(rules) = rules { + let rules: InitialWindowPlacementRules = serde_json::from_str(rules).unwrap(); + wm.monitors_mut()[0].workspaces_mut()[0].initial_window_placement_rules = Some(rules); + } + + (fake, wm) +} + +fn open(fake: &Arc, wm: &mut WindowManager, id: u32, exe: &str, title: &str) { + fake.open_window(id, exe, exe, title); + with_backend(fake.clone(), || { + wm.process_event(WindowManagerEvent::Show( + SystemNotification::KWin(KWinNotification::WindowAdded), + Window::from(id), + )) + }) + .unwrap(); +} + +/// the titles of the containers, in order +fn order(fake: &Arc, wm: &WindowManager) -> Vec { + with_backend(fake.clone(), || { + wm.focused_workspace() + .unwrap() + .containers() + .iter() + .map(|c| c.focused_window().unwrap().title().unwrap()) + .collect() + }) +} + +/// open windows with these titles, one after another (the exe is the title's first word) +fn open_all(fake: &Arc, wm: &mut WindowManager, base: u32, titles: &[&str]) { + for (i, title) in titles.iter().enumerate() { + let exe = title.split_whitespace().next().unwrap(); + open(fake, wm, base + i as u32, exe, title); + } +} + +#[test] +fn without_rules_a_window_goes_after_the_focused_one() { + let (fake, mut wm) = desktop(None); + open_all(&fake, &mut wm, 61_000, &["a", "b", "c"]); + assert_eq!(order(&fake, &wm), ["a", "b", "c"]); +} + +#[test] +fn one_place_for_every_window() { + // the largest tile: each new window takes it, and the others move up + let (fake, mut wm) = desktop(Some(r#""Primary""#)); + open_all(&fake, &mut wm, 61_100, &["a", "b", "c"]); + assert_eq!(order(&fake, &wm), ["c", "b", "a"]); + + // the end of the list + let (fake, mut wm) = desktop(Some(r#""Last""#)); + open_all(&fake, &mut wm, 61_200, &["a", "b", "c"]); + assert_eq!(order(&fake, &wm), ["a", "b", "c"]); + + // the second tile + let (fake, mut wm) = desktop(Some(r#""Secondary""#)); + open_all(&fake, &mut wm, 61_300, &["a", "b", "c", "d"]); + assert_eq!(order(&fake, &wm), ["a", "d", "c", "b"]); + + // before the one in focus + let (fake, mut wm) = desktop(Some(r#""BeforeFocused""#)); + open_all(&fake, &mut wm, 61_400, &["a", "b"]); + assert_eq!(order(&fake, &wm), ["b", "a"]); + + // a place by number, from 1 + let (fake, mut wm) = desktop(Some("2")); + open_all(&fake, &mut wm, 61_500, &["a", "b", "c"]); + assert_eq!(order(&fake, &wm), ["a", "c", "b"]); +} + +#[test] +fn a_place_that_is_not_there_is_the_default() { + let (fake, mut wm) = desktop(Some("10")); + open_all(&fake, &mut wm, 61_600, &["a", "b", "c"]); + assert_eq!(order(&fake, &wm), ["a", "b", "c"]); + + // the second tile of a workspace that has one tile has no second tile + let (fake, mut wm) = desktop(Some(r#""Secondary""#)); + open_all(&fake, &mut wm, 61_700, &["a", "b"]); + assert_eq!(order(&fake, &wm), ["a", "b"]); +} + +#[test] +fn a_place_for_the_windows_that_match_a_rule() { + let rules = r#"{ + "Primary": { "kind": "Exe", "id": "firefox", "matching_strategy": "Equals" }, + "Last": [ + { "kind": "Exe", "id": "slack", "matching_strategy": "Equals" }, + { "kind": "Title", "id": "chat", "matching_strategy": "Contains" } + ] + }"#; + let (fake, mut wm) = desktop(Some(rules)); + + open_all( + &fake, + &mut wm, + 62_000, + &[ + "term one", + "term two", + "firefox page", + "slack x", + "term three", + "other chat room", + ], + ); + + // firefox took the first tile; slack went to the end, and "term three" after it, where the focus + // was; the window with "chat" in its title went to the end + assert_eq!( + order(&fake, &wm), + [ + "firefox page", + "term one", + "term two", + "slack x", + "term three", + "other chat room" + ] + ); +} + +#[test] +fn a_rule_of_several_conditions_needs_them_all() { + // code, and a title with "work" in it + let rules = r#"{ + "1": [[ + { "kind": "Exe", "id": "code", "matching_strategy": "Equals" }, + { "kind": "Title", "id": "work", "matching_strategy": "Contains" } + ]] + }"#; + let (fake, mut wm) = desktop(Some(rules)); + + open_all( + &fake, + &mut wm, + 63_000, + &["term a", "code scratch", "code work"], + ); + + // "code scratch" has the exe but not the title: default. "code work" has both: first. + assert_eq!(order(&fake, &wm), ["code work", "term a", "code scratch"]); +} + +#[test] +fn the_first_rule_in_key_order_wins() { + // a window that matches both: "1" is before "Primary" in key order + let rules = r#"{ + "Primary": { "kind": "Exe", "id": "x", "matching_strategy": "Equals" }, + "2": { "kind": "Exe", "id": "x", "matching_strategy": "Equals" } + }"#; + let (fake, mut wm) = desktop(Some(rules)); + open_all(&fake, &mut wm, 64_000, &["a", "b", "x one"]); + + // "2" sorts before "Primary" ('2' < 'P'): second place + assert_eq!(order(&fake, &wm), ["a", "x one", "b"]); +} + +#[test] +fn a_workspace_in_komorebi_json_has_them() { + let config: StaticConfig = serde_json::from_str( + r#"{ "monitors": [ { "workspaces": [ + { "name": "one", "layout": "BSP", "initial_window_placement_rules": "Last" }, + { "name": "two", "layout": "BSP", "initial_window_placement_rules": { + "Primary": { "kind": "Exe", "id": "firefox", "matching_strategy": "Equals" } } }, + { "name": "three", "layout": "BSP", "initial_window_placement_rules": 3 } + ] } ] }"#, + ) + .unwrap(); + + let workspaces = &config.monitors.unwrap()[0].workspaces; + assert!(matches!( + workspaces[0].initial_window_placement_rules, + Some(InitialWindowPlacementRules::Target(_)) + )); + assert!(matches!( + workspaces[1].initial_window_placement_rules, + Some(InitialWindowPlacementRules::Rules(_)) + )); + assert!(matches!( + workspaces[2].initial_window_placement_rules, + Some(InitialWindowPlacementRules::Target(_)) + )); + + // and it goes back out the way it came + let again = serde_json::to_string(&workspaces[1]).unwrap(); + assert!(again.contains("\"Primary\""), "{again}"); +} + +#[test] +fn a_place_that_is_not_one_is_refused() { + assert!(serde_json::from_str::(r#""Middle""#).is_err()); + assert!(serde_json::from_str::("true").is_err()); +} + +#[test] +fn the_rules_come_from_the_configuration_of_the_workspace() { + let config: StaticConfig = serde_json::from_str( + r#"{ "monitors": [ { "workspaces": [ + { "name": "one", "layout": "BSP", "initial_window_placement_rules": "Primary" } + ] } ] }"#, + ) + .unwrap(); + let workspace_config = config.monitors.unwrap().remove(0).workspaces.remove(0); + + let mut workspace = komorebi::workspace::Workspace::default(); + workspace + .load_static_config(&workspace_config, None) + .unwrap(); + + assert_eq!( + workspace.initial_window_placement_rules, + workspace_config.initial_window_placement_rules + ); +} diff --git a/komorebi/tests/placement_cases.rs b/komorebi/tests/placement_cases.rs new file mode 100644 index 00000000..daaea038 --- /dev/null +++ b/komorebi/tests/placement_cases.rs @@ -0,0 +1,152 @@ +//! What a placement rule does beside the other things that decide where a window goes: how a rule +//! names a program, an app id and a title, a place that was preselected, and a locked container. +//! +//! `placement.rs` has the forms of the setting and the places they name. Window ids are in the +//! 61_000s. + +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::core::InitialWindowPlacementRules; +use komorebi::core::OperationDirection; +use komorebi::core::SocketMessage; +use komorebi::window::Window; +use komorebi::window_manager::WindowManager; +use komorebi::window_manager_event::KWinNotification; +use komorebi::window_manager_event::SystemNotification; +use komorebi::window_manager_event::WindowManagerEvent; +use std::sync::Arc; + +fn desktop(rules: &str) -> (Arc, WindowManager) { + let fake = Arc::new(FakeBackend::with_one_monitor()); + let (_sender, receiver) = crossbeam_channel::bounded(1); + // unix socket paths are limited to ~104 bytes on macOS, which the temp dir alone can exceed + static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let socket = std::path::PathBuf::from(format!( + "/tmp/kmq-{}-{}.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 + }); + + let rules: InitialWindowPlacementRules = serde_json::from_str(rules).unwrap(); + wm.monitors_mut()[0].workspaces_mut()[0].initial_window_placement_rules = Some(rules); + + (fake, wm) +} + +fn open(fake: &Arc, wm: &mut WindowManager, id: u32, exe: &str, class: &str) { + fake.open_window(id, exe, class, &format!("{exe} {id}")); + with_backend(fake.clone(), || { + wm.process_event(WindowManagerEvent::Show( + SystemNotification::KWin(KWinNotification::WindowAdded), + Window::from(id), + )) + }) + .unwrap(); +} + +/// the ids of the windows of the containers, in order +fn order(fake: &Arc, wm: &WindowManager) -> Vec { + with_backend(fake.clone(), || { + wm.focused_workspace() + .unwrap() + .containers() + .iter() + .filter_map(|c| c.focused_window().map(|w| w.id)) + .collect() + }) +} + +fn send(fake: &Arc, wm: &mut WindowManager, message: SocketMessage) { + with_backend(fake.clone(), || wm.process_command(message, Vec::new())).unwrap(); +} + +fn focus(fake: &Arc, wm: &mut WindowManager, id: u32) { + fake.set_foreground(Some(id)); + with_backend(fake.clone(), || { + wm.process_event(WindowManagerEvent::FocusChange( + SystemNotification::KWin(KWinNotification::WindowActivated), + Window::from(id), + )) + }) + .unwrap(); +} + +#[test] +fn a_rule_may_name_the_program_the_way_windows_does() { + // `.exe` is ignored in the id, so a configuration written for Windows works here + let (fake, mut wm) = desktop( + r#"{ "Primary": { "kind": "Exe", "id": "firefox.exe", "matching_strategy": "Equals" } }"#, + ); + + open(&fake, &mut wm, 61_001, "foot", "foot"); + open(&fake, &mut wm, 61_002, "foot", "foot"); + open(&fake, &mut wm, 61_003, "firefox", "firefox"); + + assert_eq!(order(&fake, &wm), [61_003, 61_001, 61_002]); +} + +#[test] +fn a_rule_may_name_the_app_id_of_the_window() { + let (fake, mut wm) = desktop( + r#"{ "Last": { "kind": "Class", "id": "special", "matching_strategy": "Equals" } }"#, + ); + + open(&fake, &mut wm, 61_011, "foot", "special"); + open(&fake, &mut wm, 61_012, "foot", "foot"); + open(&fake, &mut wm, 61_013, "foot", "foot"); + + // a window that no rule matches goes after the focused container, which is the last to open + assert_eq!(order(&fake, &wm), [61_011, 61_012, 61_013]); + + open(&fake, &mut wm, 61_014, "foot", "special"); + focus(&fake, &mut wm, 61_011); + open(&fake, &mut wm, 61_015, "foot", "foot"); + open(&fake, &mut wm, 61_016, "foot", "special"); + + // 61_015 went after the focused 61_011; 61_016 matches and went to the end + assert_eq!( + order(&fake, &wm), + [61_011, 61_015, 61_012, 61_013, 61_014, 61_016] + ); +} + +#[test] +fn a_place_that_was_preselected_wins_over_the_rules() { + let (fake, mut wm) = desktop(r#""Last""#); + open(&fake, &mut wm, 61_021, "foot", "foot"); + open(&fake, &mut wm, 61_022, "foot", "foot"); + focus(&fake, &mut wm, 61_021); + + send( + &fake, + &mut wm, + SocketMessage::PreselectDirection(OperationDirection::Right), + ); + open(&fake, &mut wm, 61_023, "foot", "foot"); + + // the rule says the end of the list; the place that was reserved is the one in the middle + assert_eq!(order(&fake, &wm), [61_021, 61_023, 61_022]); + + // and the rule is back for the next window + open(&fake, &mut wm, 61_024, "foot", "foot"); + assert_eq!(order(&fake, &wm), [61_021, 61_023, 61_022, 61_024]); +} + +#[test] +fn a_rule_that_asks_for_the_place_of_a_locked_container_gets_the_place_after_it() { + let (fake, mut wm) = desktop(r#""Primary""#); + open(&fake, &mut wm, 61_031, "foot", "foot"); + send(&fake, &mut wm, SocketMessage::ToggleLock); + + open(&fake, &mut wm, 61_032, "foot", "foot"); + open(&fake, &mut wm, 61_033, "foot", "foot"); + + // the first place is the locked container's, so each window takes the one after it + assert_eq!(order(&fake, &wm), [61_031, 61_033, 61_032]); +} diff --git a/komorebi/tests/schemas.rs b/komorebi/tests/schemas.rs index 195ca0c8..06157045 100644 --- a/komorebi/tests/schemas.rs +++ b/komorebi/tests/schemas.rs @@ -1,12 +1,15 @@ //! The JSON Schemas the daemon answers with: `StaticConfigSchema`, //! `ApplicationSpecificConfigurationSchema`, `NotificationSchema` and `SocketSchema`, against an //! in-memory desktop. `komorebic` prints the same schemas without the daemon; the daemon answers -//! on its socket for a client that has none. +//! on its socket for a client that has none. The schema of a place for a new window, which is +//! written by hand, is checked here too. use komorebi::backend::fake::FakeBackend; use komorebi::backend::with_backend; +use komorebi::core::PlacementTarget; use komorebi::core::SocketMessage; use komorebi::window_manager::WindowManager; +use serde_json::json; use std::sync::Arc; fn answer(message: SocketMessage) -> serde_json::Value { @@ -48,3 +51,65 @@ fn the_daemon_answers_with_the_schemas_of_what_it_sends_and_of_what_it_takes() { assert!(answer(SocketMessage::NotificationSchema)["properties"]["state"].is_object()); assert!(answer(SocketMessage::SocketSchema)["oneOf"].is_array()); } + +#[test] +fn the_schema_of_komorebi_json_has_the_places_a_workspace_can_give_a_new_window() { + let schema = answer(SocketMessage::StaticConfigSchema); + + let key = &schema["$defs"]["WorkspaceConfig"]["properties"]["initial_window_placement_rules"]; + assert!(key.is_object(), "a workspace has the key in the schema"); + assert!(schema["$defs"]["InitialWindowPlacementRules"]["anyOf"].is_array()); + assert!(schema["$defs"]["PlacementTarget"].is_object()); +} + +/// The schema derived for the enum is an object with a `Placement` or an `Index` key, which is not +/// what is read: a name, a number, or text that is a number. +#[test] +fn a_place_is_described_as_a_name_a_number_or_text_that_is_a_number() { + let schema = serde_json::to_value(schemars::schema_for!(PlacementTarget)).unwrap(); + let forms = schema["anyOf"] + .as_array() + .expect("a place has several forms"); + assert_eq!(forms.len(), 3); + + // a name: every strategy of `WindowPlacement`, and each of them is read + assert_eq!(forms[0]["$ref"], "#/$defs/WindowPlacement"); + let names: Vec<&str> = schema["$defs"]["WindowPlacement"]["oneOf"] + .as_array() + .unwrap() + .iter() + .map(|name| name["const"].as_str().unwrap()) + .collect(); + assert_eq!(names.len(), 5); + for name in &names { + assert!( + matches!( + serde_json::from_value(json!(name)), + Ok(PlacementTarget::Placement(_)) + ), + "{name} is not read as a strategy" + ); + } + + // a number + assert_eq!(forms[1]["type"], "integer"); + assert_eq!( + serde_json::from_value::(json!(3)).unwrap(), + PlacementTarget::Index(3) + ); + + // text that is a number: what the pattern accepts is what is read as a number, and a name is + // not + assert_eq!(forms[2]["type"], "string"); + let pattern = regex::Regex::new(forms[2]["pattern"].as_str().unwrap()).unwrap(); + assert!(pattern.is_match("3")); + assert!(!pattern.is_match("Primary")); + assert_eq!( + serde_json::from_value::(json!("3")).unwrap(), + PlacementTarget::Index(3) + ); + + // and a place that is none of them is refused + assert!(serde_json::from_value::(json!("Nowhere")).is_err()); + assert!(!pattern.is_match("Nowhere")); +} diff --git a/nix/komorebi-options.nix b/nix/komorebi-options.nix index 8a161491..3979bda8 100644 --- a/nix/komorebi-options.nix +++ b/nix/komorebi-options.nix @@ -1,4 +1,4 @@ -# schema-sha256: be9289ac70f6f47d7d8aebee0d7c67a2fa0d54456d9306ce6c634ef6e7748ddf +# schema-sha256: 03b13ffd266a4432379c1dc2dc69b84b180484acd196ffda7dd436e511ad4170 { lib, ... }: let animationStyle = ( @@ -244,6 +244,12 @@ let "CenterAndResize" ] ); + placementMatchingRules = ( + lib.types.oneOf [ + idWithIdentifier + (lib.types.listOf matchingRule) + ] + ); rect = ( lib.types.submodule { options = { @@ -709,6 +715,28 @@ in default = "Tile"; description = "Determine what happens to a new window when the Floating workspace layer is active"; }; + initial_window_placement_rules = lib.mkOption { + type = ( + lib.types.nullOr ( + lib.types.oneOf [ + (lib.types.oneOf [ + (lib.types.enum [ + "Primary" + "Secondary" + "BeforeFocused" + "AfterFocused" + "Last" + ]) + lib.types.int + lib.types.str + ]) + (lib.types.attrsOf placementMatchingRules) + ] + ) + ); + default = null; + description = "Initial window placement rules that determine where new tiled windows are placed\nin the container list. Can be a placement target (a `WindowPlacement` string like\n`\"Primary\"` or a 1-based container index), or a map of placement targets to matching rules."; + }; initial_workspace_rules = lib.mkOption { type = (lib.types.nullOr (lib.types.listOf matchingRule)); default = null; diff --git a/nix/tests/default.nix b/nix/tests/default.nix index 807d38ef..501c701e 100644 --- a/nix/tests/default.nix +++ b/nix/tests/default.nix @@ -1,6 +1,7 @@ # `nix-options-validation`: the options `just nixgen` makes from `schema.json`, evaluated against # the example configuration, whose JSON is checked against the schema, and against the example -# file of the docs. Run with `nix build -f nix/tests/default.nix`, or as a check of the flake. +# file of the docs, and against the places a workspace can give the windows that open, in every +# form komorebi reads. Run with `nix build -f nix/tests/default.nix`, or as a check of the flake. { pkgs ? import { }, }: @@ -32,6 +33,72 @@ let builtins.toJSON (filterNulls evaluated) ); + # where a workspace puts the windows that open, in each form komorebi reads: a name, a number, + # text that is a number, and a map of places to rules (whose keys are text) + placements = + (lib.evalModules { + modules = [ + (import ../komorebi-options.nix) + { + komorebi.monitors = [ + { + workspaces = [ + { + name = "name"; + initial_window_placement_rules = "Primary"; + } + { + name = "number"; + initial_window_placement_rules = 3; + } + { + name = "text"; + initial_window_placement_rules = "3"; + } + { + name = "map"; + initial_window_placement_rules = { + Primary = { + kind = "Exe"; + id = "firefox"; + matching_strategy = "Equals"; + }; + "2" = [ + { + kind = "Title"; + id = "notes"; + matching_strategy = "StartsWith"; + } + ]; + }; + } + ]; + } + ]; + } + ]; + }).config.komorebi; + + placementsJson = pkgs.writeText "komorebi-placements.json" ( + builtins.toJSON (filterNulls placements) + ); + + # a place that is neither a name nor a number + nowhereJson = pkgs.writeText "komorebi-nowhere.json" ( + builtins.toJSON { + monitors = [ + { + workspaces = [ + { + name = "x"; + initial_window_placement_rules = "Nowhere"; + } + ]; + } + ]; + } + ); + # 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 @@ -55,6 +122,16 @@ pkgs.runCommand "nix-options-validation" echo "Checking that the two examples say the same..." jq -e --slurpfile example ${exampleJson} 'contains($example[0])' ${evaluatedJson} > /dev/null + echo "Validating the places a workspace can give a new window, in every form, against the schema..." + check-jsonschema --schemafile ${schema} ${placementsJson} + jq -e '[.monitors[0].workspaces[].initial_window_placement_rules | type] == ["string", "number", "string", "object"]' ${placementsJson} > /dev/null + + echo "Checking that the schema refuses a place that is neither a name nor a number..." + if check-jsonschema --schemafile ${schema} ${nowhereJson} > /dev/null 2>&1; then + echo "the schema accepts a place that komorebi cannot read" >&2 + exit 1 + fi + echo "All validations passed!" touch $out '' diff --git a/nix/tests/nixos-module.nix b/nix/tests/nixos-module.nix index 5cf019d6..ae3209db 100644 --- a/nix/tests/nixos-module.nix +++ b/nix/tests/nixos-module.nix @@ -118,6 +118,43 @@ let }; }; + # where a workspace puts the windows that open, in each form komorebi reads: a name, a number, + # text that is a number, and a map of places to rules + withPlacement = eval { + imports = [ plasma ]; + services.komorebi = { + enable = true; + config.monitors = [ + { + workspaces = [ + { + name = "name"; + initial_window_placement_rules = "Primary"; + } + { + name = "number"; + initial_window_placement_rules = 3; + } + { + name = "text"; + initial_window_placement_rules = "3"; + } + { + name = "map"; + initial_window_placement_rules = { + Primary = { + kind = "Exe"; + id = "firefox"; + matching_strategy = "Equals"; + }; + }; + } + ]; + } + ]; + }; + }; + # a layout komorebi does not have badLayout = eval { imports = [ plasma ]; @@ -467,6 +504,19 @@ let .window_container_behaviour_rules."2" == "Append"; got = withConfig.services.komorebi.internal.configAttrs; } + { + name = "the place a workspace gives the windows that open is a typed option in each form it is read"; + ok = + let + workspaces = (lib.head withPlacement.services.komorebi.internal.configAttrs.monitors).workspaces; + place = name: (lib.findFirst (w: w.name == name) null workspaces).initial_window_placement_rules; + in + place "name" == "Primary" + && place "number" == 3 + && place "text" == "3" + && (place "map").Primary.id == "firefox"; + got = withPlacement.services.komorebi.internal.configAttrs; + } { name = "config reaches execStart as a komorebi.json that was checked against the schema"; ok = diff --git a/nix/tests/vm/suites/placement/default.nix b/nix/tests/vm/suites/placement/default.nix new file mode 100644 index 00000000..bb57ac90 --- /dev/null +++ b/nix/tests/vm/suites/placement/default.nix @@ -0,0 +1,5 @@ +{ + tier = "fast"; + kind = "headless"; + timeoutMinutes = 10; +} diff --git a/nix/tests/vm/suites/placement/test.py b/nix/tests/vm/suites/placement/test.py new file mode 100644 index 00000000..6b3bb64b --- /dev/null +++ b/nix/tests/vm/suites/placement/test.py @@ -0,0 +1,131 @@ +# `initial_window_placement_rules` in a real (headless) KWin: where in the layout a window that +# opens goes. The daemon reads the rules from a `komorebi.json` it is started with, and the rules +# match a window by what it is called: its program (`Exe`), its Wayland app id (`Class`) and its +# title. `komorebi/tests/placement.rs` checks the same against the fake; this checks that the names +# the rules match are the ones a real window has, and that the places of a file are the places the +# windows get. +import json +import shlex +import time +from typing import Any + +from komorebi_vm import Checks, Kde + +CONFIG = "/tmp/placement.json" + +start_all() +machine.wait_for_unit("multi-user.target") +machine.wait_for_unit("user@1000.service") + +checks = Checks() +kde = Kde.headless(machine, "main", size=(1920, 1080), scale=SCALE) +opened: list[str] = [] + + +def order() -> list[str]: + """The title of the window of each container of the first workspace, in the layout's order.""" + return [titles[0] for titles in kde.containers()] + + +def open_window(title: str, app_id: str = "foot") -> None: + """Opens a window, and waits until the daemon has put it in a container.""" + kde.spawn(f"foot -a {shlex.quote(app_id)} -T {shlex.quote(title)} sleep 3000") + opened.append(title) + kde.wait_for(lambda: kde.wid(title) != "", timeout=30) + kde.wait_for(lambda: kde.managed() == len(opened), timeout=20) + # the window that has just opened has the focus once the daemon has told KWin so + kde.wait_for(lambda: kde.focused_title() == title, timeout=20) + time.sleep(0.5 * SCALE) + + +def fresh(rules: Any) -> None: + """Starts the daemon again, with `rules` as the placement rules of the workspace's windows. + + The windows of the run before are closed. `None` leaves the key out of the file. + """ + if kde.komorebi_running(): + kde.komorebic("stop") + kde.wait_for(lambda: not kde.komorebi_running(), timeout=30) + for title in opened: + wid = kde.wid(title) + if wid != "": + kde.close(wid) + kde.wait_for(lambda: all(kde.wid(title) == "" for title in opened), timeout=30) + opened.clear() + + workspace: dict[str, Any] = {"name": "a", "layout": "BSP"} + if rules is not None: + workspace["initial_window_placement_rules"] = rules + config = { + "default_workspace_padding": 10, + "default_container_padding": 10, + "monitors": [{"workspaces": [workspace]}], + } + kde.sh(f"printf %s {shlex.quote(json.dumps(config))} > {CONFIG}") + kde.start_komorebi("--config", CONFIG) + checks.check( + "the daemon answers komorebic", + kde.wait_for(lambda: kde.run("komorebic state")[0] == 0, timeout=30), + ) + + +print("== 1. no rules: after the one in focus") +fresh(None) +for title in ("a", "b", "c"): + open_window(title) +checks.check(f"a, b, c ({order()})", order() == ["a", "b", "c"]) + +print("== 2. every window to the primary tile") +fresh("Primary") +for title in ("a", "b", "c"): + open_window(title) +checks.check(f"c, b, a ({order()})", order() == ["c", "b", "a"]) + +print("== 3. by the number of the place, counted from 1, as a number and as text") +fresh(2) +for title in ("a", "b", "c"): + open_window(title) +checks.check(f"a, c, b ({order()})", order() == ["a", "c", "b"]) +fresh("2") +for title in ("a", "b", "c"): + open_window(title) +checks.check( + f"text that is a number is the same place: a, c, b ({order()})", order() == ["a", "c", "b"] +) + +print("== 4. by the app id and the title") +fresh( + { + "Primary": {"kind": "Class", "id": "special", "matching_strategy": "Equals"}, + "Last": [{"kind": "Title", "id": "chat", "matching_strategy": "Contains"}], + } +) +for title in ("one", "two"): + open_window(title) +open_window("three", "special") +checks.check( + f"the window with the app id special is first ({order()})", order() == ["three", "one", "two"] +) +open_window("a chat room") +checks.check( + f"the chat room is last ({order()})", order() == ["three", "one", "two", "a chat room"] +) +open_window("four") +checks.check( + f"a window no rule matches goes after the one in focus, the chat room ({order()})", + order() == ["three", "one", "two", "a chat room", "four"], +) + +print("== 5. by the program, with the name of a Windows executable") +fresh({"Primary": {"kind": "Exe", "id": "foot.exe", "matching_strategy": "Equals"}}) +for title in ("a", "b", "c"): + open_window(title) +checks.check( + f"foot.exe is foot, so every window is a primary one: c, b, a ({order()})", + order() == ["c", "b", "a"], +) + +kde.komorebic("stop") +checks.check("a clean stop", kde.wait_for(lambda: not kde.komorebi_running(), timeout=30)) +kde.stop() +checks.finish() diff --git a/schema.json b/schema.json index a75ef311..d492d3bb 100644 --- a/schema.json +++ b/schema.json @@ -2631,6 +2631,30 @@ "id" ] }, + "InitialWindowPlacementRules": { + "description": "Configuration for initial window placement rules on a workspace.\n\nThis can be specified in two forms in the JSON config:\n- A placement target (string or integer) — applies the same placement to all windows.\n Strings are `WindowPlacement` variant names (e.g. `\"Primary\"`, `\"AfterFocused\"`),\n integers are 1-based container indices.\n- A map of placement targets to matching rules — keys can be `WindowPlacement` variant names\n (e.g. `\"Primary\"`, `\"Secondary\"`) or 1-based container indices (e.g. `\"1\"`, `\"3\"`).\n Rules are evaluated in key order; the first matching rule determines placement.\n\nNOTE: Container indices in the config are 1-based for user-friendliness.\nThey are converted to 0-based internally during resolution.\n\nNOTE: This feature currently only applies when `WindowContainerBehaviour::Create` is active.\nFuture versions may support toggling this for `Append` mode as well.", + "anyOf": [ + { + "description": "A single placement target applied to all new windows (string or integer in config)", + "$ref": "#/$defs/PlacementTarget" + }, + { + "description": "A map of placement targets to matching rules.\nKeys can be `WindowPlacement` variant names (e.g. `\"Primary\"`) or 1-based container indices (e.g. `\"1\"`).\nValues can be:\n- A single `IdWithIdentifier` object (simple rule)\n- An array containing objects and/or arrays:\n - Each object in the array is an independent simple rule (OR logic between entries)\n - Each inner array is a composite rule where all conditions must match (AND logic)\n - The outer array entries are evaluated with OR logic\n\nRules are evaluated in key order; the first matching rule determines placement.", + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/PlacementMatchingRules" + }, + "patternProperties": { + "^[0-9]+$": { + "$ref": "#/$defs/PlacementMatchingRules" + }, + "^\\d+$": { + "$ref": "#/$defs/PlacementMatchingRules" + } + } + } + ] + }, "KomorebiTheme": { "description": "Komorebi theme", "oneOf": [ @@ -3367,6 +3391,41 @@ } ] }, + "PlacementMatchingRules": { + "description": "Matching rules for a placement target.\n\nCan be specified in JSON as:\n- A single `IdWithIdentifier` object — one simple rule\n- An array of `MatchingRule`s — multiple rules with OR logic between them\n (each element can be a simple rule object or a composite rule array with AND logic)\n\nExamples:\n```json\n// Single rule\n{ \"kind\": \"Exe\", \"id\": \"chrome.exe\", \"matching_strategy\": \"Equals\" }\n\n// Multiple rules (OR): chrome OR teams\n[\n { \"kind\": \"Exe\", \"id\": \"chrome.exe\", \"matching_strategy\": \"Equals\" },\n { \"kind\": \"Title\", \"id\": \"Microsoft Teams\", \"matching_strategy\": \"Equals\" }\n]\n\n// Mixed: chrome OR (code.exe AND title contains \"workspace\")\n[\n { \"kind\": \"Exe\", \"id\": \"chrome.exe\", \"matching_strategy\": \"Equals\" },\n [\n { \"kind\": \"Exe\", \"id\": \"code.exe\", \"matching_strategy\": \"Equals\" },\n { \"kind\": \"Title\", \"id\": \"workspace\", \"matching_strategy\": \"Contains\" }\n ]\n]\n```", + "anyOf": [ + { + "description": "A single simple matching rule", + "$ref": "#/$defs/IdWithIdentifier" + }, + { + "description": "Multiple matching rules evaluated with OR logic.\nEach entry is a `MatchingRule`: either a simple rule (object) or composite rule (array, AND logic).", + "type": "array", + "items": { + "$ref": "#/$defs/MatchingRule" + } + } + ] + }, + "PlacementTarget": { + "description": "A place in the list of containers: the name of a placement strategy, or a 1-based container index, as a number or as text (`3` and `\"3\"` are the same place; the keys of a JSON object can only be text).", + "anyOf": [ + { + "$ref": "#/$defs/WindowPlacement" + }, + { + "description": "A 1-based container index", + "type": "integer", + "format": "uint", + "minimum": 0 + }, + { + "description": "A 1-based container index, as text", + "type": "string", + "pattern": "^[0-9]+$" + } + ] + }, "PredefinedAspectRatio": { "description": "Predefined aspect ratio", "oneOf": [ @@ -3649,6 +3708,36 @@ } ] }, + "WindowPlacement": { + "description": "Placement strategy for new windows in a workspace", + "oneOf": [ + { + "description": "Place the new window at the primary (largest) container position", + "type": "string", + "const": "Primary" + }, + { + "description": "Place the new window at the secondary container position", + "type": "string", + "const": "Secondary" + }, + { + "description": "Place the new window before the currently focused container", + "type": "string", + "const": "BeforeFocused" + }, + { + "description": "Place the new window after the currently focused container (default behavior)", + "type": "string", + "const": "AfterFocused" + }, + { + "description": "Place the new window at the end of the container list", + "type": "string", + "const": "Last" + } + ] + }, "WorkspaceConfig": { "description": "Workspace configuration", "type": "object", @@ -3689,6 +3778,17 @@ ], "default": "Tile" }, + "initial_window_placement_rules": { + "description": "Initial window placement rules that determine where new tiled windows are placed\nin the container list. Can be a placement target (a `WindowPlacement` string like\n`\"Primary\"` or a 1-based container index), or a map of placement targets to matching rules.", + "anyOf": [ + { + "$ref": "#/$defs/InitialWindowPlacementRules" + }, + { + "type": "null" + } + ] + }, "initial_workspace_rules": { "description": "Initial workspace application rules", "type": [