From ed34286bca5557303293147d09169b9d9f67d6e1 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 19:25:38 -0700 Subject: [PATCH] feat(wm): application specific configuration Rules for particular applications can be kept in files of their own, applications.json, which komorebi.json names with app_specific_configuration_path: one path or a list. The ignore, manage and floating rules of every application in a file are added to the lists the configuration's own rules go in, so a file can be shared or kept apart from the settings. A path with no file behind it is skipped with a warning, since one komorebi.json is meant to work on every platform and may name a file that only another platform has; a file that is there and is not an applications.json is an error. The titleless and tabbed rules of other platforms are read and do nothing. komorebic/applications.json is a start for Plasma: it floats the calculators, the screenshot tool, the authentication dialog and System Settings. A test opens the windows it names. --- README.md | 4 +- docs/dev/ARCHITECTURE.md | 13 +- docs/dev/DESIGN.md | 7 + docs/example-configurations.md | 10 + docs/index.md | 5 +- docs/komorebi.example.json | 1 + .../application-specific-configuration.md | 73 ++++++ docs/usage/configuration.md | 1 + komorebi-client/src/lib.rs | 1 + komorebi/src/core/asc.rs | 69 ++++++ komorebi/src/core/mod.rs | 1 + komorebi/src/static_config.rs | 143 +++++++++++ komorebi/tests/asc.rs | 229 ++++++++++++++++++ komorebi/tests/config_parity.rs | 2 - komorebic/applications.json | 11 + 15 files changed, 564 insertions(+), 6 deletions(-) create mode 100644 docs/usage/application-specific-configuration.md create mode 100644 komorebi/src/core/asc.rs create mode 100644 komorebi/tests/asc.rs create mode 100644 komorebic/applications.json diff --git a/README.md b/README.md index d5761b0f..4b9b3233 100644 --- a/README.md +++ b/README.md @@ -199,7 +199,9 @@ 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 -is ignored, so one file serves every platform. `workspace-layout-rule` makes a +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 workspace change layout with the number of windows it has, as the file's `layout_rules` do, and `generate-static-config` prints the settings the daemon has as a `komorebi.json`. diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index 55b34cc9..2f1fa555 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -669,6 +669,13 @@ first and applies it only when it parsed, so a file that is half written changes for the window manager that is running what the three steps do for one that starts, and tiles every monitor again. +`app_specific_configuration_path` names files of rules for particular applications, which +[`StaticConfig`] reads after the rules of its own (`apply_globals`): the `ignore`, `manage` and +`floating` rules of each application in each file are appended to the same lists, once each (a +rule that is in the list already is not added again). A path with no file is skipped with a +warning, since one `komorebi.json` may name a file that only another platform has; a file that is +there and is not an applications.json is an error. + Three kinds of key reach the model. A **setting** of the window manager is a field of it ([`WindowManager::resize_delta`] and the others). A **default** is a process-wide static that a monitor or a workspace falls back to when it has no value of its own: the paddings, the layout @@ -686,6 +693,8 @@ goes the other way, for `GenerateStaticConfig`. | A key komorebi does not read does not stop a configuration from loading | serde: [`StaticConfig`] ignores unknown keys, and a key of another platform is a field nothing reads | `the_keys_that_do_nothing_on_kde_are_accepted_and_ignored`, `fixtures_load_round_trip_and_only_lose_windows_only_keys` | none | | The keys the parity test ignores are keys `StaticConfig` does not read | test: the ignore lists are compared with the schema of [`StaticConfig`] | `the_lists_name_no_key_that_is_read` | none | | The example in the docs is the example file, which loads | test | `the_example_in_the_docs_is_the_example_file`, `fixtures_load_round_trip_and_only_lose_windows_only_keys` | none | +| A path to an applications file that is not there is skipped, and one that is there and is broken is an error | framework path: `handle_asc_file` returns early when the path does not exist, and parses the file otherwise | `a_missing_application_specific_configuration_is_skipped_not_fatal`, `an_application_specific_configuration_that_exists_but_is_broken_is_still_an_error`, `a_file_that_is_not_there_is_skipped_and_one_that_is_broken_is_an_error` | none | +| The rules of an applications file and of the configuration add up | framework path: both are appended to the process-wide lists | `the_rules_of_the_configuration_and_of_the_file_add_up`, `every_file_of_a_list_is_read` | none | | A file that cannot be read changes nothing | framework path: [`StaticConfig::reload`] reads and parses the file before it applies anything | `a_configuration_that_cannot_be_read_changes_nothing`, `the_daemon_follows_the_file_it_is_given_when_the_file_changes` | none | | The daemon applies a change to its file, written in place or replaced by a rename | framework path: the watcher sends `ReloadStaticConfiguration` to the daemon's own socket | `the_daemon_follows_the_file_it_is_given_when_the_file_changes`, `vm-module` | none: the file has to be the one the daemon was started with | | A monitor takes the entry its display index preference gives it, else the first nobody has | framework path: [`StaticConfig::postload`] and [`StaticConfig::reload`] choose the entry by serial number id first | `a_monitor_takes_the_configuration_its_display_index_preference_gives_it` | none | @@ -987,7 +996,9 @@ A window is shown, and ends up on a tile: with several monitors, [`komorebi/tests/hot_reload.rs`](../../komorebi/tests/hot_reload.rs) the daemon following a file, and [`komorebi/tests/config_parity.rs`](../../komorebi/tests/config_parity.rs) the files of other - platforms and the example, which load. + platforms and the example, which load; [`komorebi/tests/asc.rs`](../../komorebi/tests/asc.rs) + the applications files; [`komorebi/src/core/asc.rs`](../../komorebi/src/core/asc.rs) their + format. - [`komorebi/src/process_event.rs`](../../komorebi/src/process_event.rs): what each event does, and the thread that handles them. - [`komorebi/src/process_command.rs`](../../komorebi/src/process_command.rs): the socket, what diff --git a/docs/dev/DESIGN.md b/docs/dev/DESIGN.md index 28cd6457..f35e41df 100644 --- a/docs/dev/DESIGN.md +++ b/docs/dev/DESIGN.md @@ -347,3 +347,10 @@ which do not exist here. The watcher is `hotwatch`, whose default is to wait two editor to settle. An editor either writes a file in place or replaces it with a new one, so the daemon reloads on a modification and on a removal, and the test that follows a real daemon through both of them is `the_daemon_follows_the_file_it_is_given_when_the_file_changes`. + +## Why is an applications file that is not there skipped, and one that is broken an error? + +Because one `komorebi.json` is meant to work on every platform, and the file it points to may be +one that another platform has: a configuration written for macOS names `applications.mac.json`, +which a KDE desktop does not have. The daemon warns and goes on. A file that exists and is not an +applications.json is a mistake in something the user wrote, and is an error. diff --git a/docs/example-configurations.md b/docs/example-configurations.md index f77a1e1a..8fe9f096 100644 --- a/docs/example-configurations.md +++ b/docs/example-configurations.md @@ -12,6 +12,7 @@ different layout. This page has the file as it is: ```json { + "app_specific_configuration_path": "$HOME/.config/komorebi/applications.json", "cross_monitor_move_behaviour": "Insert", "default_workspace_padding": 15, "default_container_padding": 15, @@ -67,6 +68,15 @@ with `komorebic start --config`. [Configuration](usage/configuration.md) explain where the daemon looks. The settings of a monitor with more than one entry in `monitors`, and of each workspace, are there too. +### Application specific configuration + +`app_specific_configuration_path` names a file of rules for the applications that need them, which +the repository has a start of in +[`komorebic/applications.json`](../komorebic/applications.json). Put a copy where the example +says, `~/.config/komorebi/applications.json`; a path with no file behind it is skipped. +[Application specific configuration](usage/application-specific-configuration.md) explains the +format. + ### Padding While you can set the workspace padding (the space between the outer edges of the windows and diff --git a/docs/index.md b/docs/index.md index fc1301e5..c6a3da2a 100644 --- a/docs/index.md +++ b/docs/index.md @@ -51,8 +51,9 @@ 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. [Configuration](usage/configuration.md) explains `komorebi.json`, where komorebi looks for it and -how it is reloaded when it changes, and [Example configurations](example-configurations.md) has -one to start from. +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) +explains the files of rules for particular applications it can name. [Subscribing to notifications](usage/subscribing-to-notifications.md) explains how a program such as a status bar follows what komorebi does. The [CLI reference](cli/start.md) has a page for every `komorebic` command, generated from its help. diff --git a/docs/komorebi.example.json b/docs/komorebi.example.json index aee89caf..a3f08b3a 100644 --- a/docs/komorebi.example.json +++ b/docs/komorebi.example.json @@ -1,4 +1,5 @@ { + "app_specific_configuration_path": "$HOME/.config/komorebi/applications.json", "cross_monitor_move_behaviour": "Insert", "default_workspace_padding": 15, "default_container_padding": 15, diff --git a/docs/usage/application-specific-configuration.md b/docs/usage/application-specific-configuration.md new file mode 100644 index 00000000..3701ea35 --- /dev/null +++ b/docs/usage/application-specific-configuration.md @@ -0,0 +1,73 @@ +# Application specific configuration + +Some applications need to be told how to behave under a tiling window manager: a calculator that +should float instead of taking a tile, a launcher that should never be tiled. The +[rules](rules.md) that say so can be put in `komorebi.json`, or in a file of their own, +`applications.json`, that the configuration names. The file can be shared, or kept apart from +the settings, and a list of files can be put together from several sources. + +## The file + +`applications.json` is an object with one entry for each application. The name of the entry is +only for the reader. Each entry has lists of [rules](rules.md), as `komorebi.json` has them: + +```json +{ + "KDE Plasma": { + "floating": [ + { "kind": "Class", "id": "org.kde.kcalc", "matching_strategy": "Equals" }, + { "kind": "Class", "id": "org.kde.spectacle", "matching_strategy": "Equals" } + ] + }, + "Steam": { + "ignore": [{ "kind": "Exe", "id": "steam", "matching_strategy": "Equals" }] + } +} +``` + +| List | What it does | In `komorebi.json` | +|---|---|---| +| `ignore` | komorebi leaves the windows alone | `ignore_rules` | +| `manage` | komorebi tiles the windows, whatever the ignore rules say | `manage_rules` | +| `floating` | the windows open floating | `floating_applications` | +| `titleless`, `tabbed` | nothing: they work around how another platform exposes windows, and a KWin window is always a window | `titleless_applications`, `tabbed_applications` | + +An entry named `$schema` has the address of a schema as its value, as an editor wants it, and +is ignored. + +## Naming the file + +`app_specific_configuration_path` in `komorebi.json` is the path of one file, or a list of paths: + +```json +{ + "app_specific_configuration_path": "$HOME/.config/komorebi/applications.json" +} +``` + +```json +{ + "app_specific_configuration_path": [ + "$HOME/.config/komorebi/applications.json", + "$HOME/.config/komorebi/mine.json" + ] +} +``` + +Environment variables in a path, such as `$HOME`, are replaced. The files are read when +`komorebi.json` is: when the daemon starts, and again when the configuration changes. Their rules +are added to the ones the daemon has, after the rules of `komorebi.json` itself, which +[Configuration](configuration.md#rules) explains. + +A path with no file behind it is skipped, and the daemon logs a warning: one `komorebi.json` can +serve every platform, even if it names a file that only another platform has. A file that is +there and is not an `applications.json`, or has a rule that is not valid, is an error: the daemon +does not start with it, and a reload with it fails and logs the error. Only a file with the +extension `.json` is read. + +## The file komorebi ships + +[`komorebic/applications.json`](../../komorebic/applications.json) in the repository has an +entry for KDE Plasma, which floats the calculators of KDE and GNOME, the screenshot tool, the +authentication dialog of Plasma and System Settings. A test loads it, and opens the windows it +names. diff --git a/docs/usage/configuration.md b/docs/usage/configuration.md index f1301cfd..5eb13be4 100644 --- a/docs/usage/configuration.md +++ b/docs/usage/configuration.md @@ -96,6 +96,7 @@ can have values of their own, which come before the default. | `ignore_rules` | Windows komorebi leaves alone (`float_rules` is the same key under its old name) | | `manage_rules` | Windows komorebi tiles whatever the ignore rules say | | `floating_applications` | Windows that open floating | +| `app_specific_configuration_path` | One `applications.json`, or a list of them, whose rules are added to these ([Application specific configuration](application-specific-configuration.md)) | Each is a list of rules, which [Rules](rules.md) explains. A rule is an object with `kind` (`Exe`, `Class`, `Title` or `Path`), `id` and `matching_strategy` (`Equals`, `StartsWith`, `EndsWith`, diff --git a/komorebi-client/src/lib.rs b/komorebi-client/src/lib.rs index 3f8e0a1b..4e0b4a26 100644 --- a/komorebi-client/src/lib.rs +++ b/komorebi-client/src/lib.rs @@ -74,6 +74,7 @@ pub use komorebi::core::SocketMessage; pub use komorebi::core::StateQuery; pub use komorebi::core::SubscribeOptions; pub use komorebi::core::WindowKind; +pub use komorebi::core::asc::ApplicationSpecificConfiguration; pub use komorebi::core::pathext::PathExt; pub use komorebi::core::pathext::replace_env_in_path; pub use komorebi::state::State; diff --git a/komorebi/src/core/asc.rs b/komorebi/src/core/asc.rs new file mode 100644 index 00000000..d27396ed --- /dev/null +++ b/komorebi/src/core/asc.rs @@ -0,0 +1,69 @@ +//! The application specific configuration file (`app_specific_configuration_path`): rules, by +//! application, for the windows komorebi ignores, manages or floats. + +use crate::core::config_generation::MatchingRule; +use color_eyre::Result; +use serde::Deserialize; +use serde::Serialize; +use std::collections::BTreeMap; +use std::ops::Deref; +use std::ops::DerefMut; +use std::path::PathBuf; + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct ApplicationSpecificConfiguration(pub BTreeMap); + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[serde(untagged)] +pub enum AscApplicationRulesOrSchema { + AscApplicationRules(AscApplicationRules), + Schema(String), +} + +impl Deref for ApplicationSpecificConfiguration { + type Target = BTreeMap; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DerefMut for ApplicationSpecificConfiguration { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +impl ApplicationSpecificConfiguration { + pub fn load(pathbuf: &PathBuf) -> Result { + let content = std::fs::read_to_string(pathbuf)?; + Ok(serde_json::from_str(&content)?) + } + + pub fn format(pathbuf: &PathBuf) -> Result { + Ok(serde_json::to_string_pretty(&Self::load(pathbuf)?)?) + } +} + +/// Rules that determine how an application is handled +#[derive(Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct AscApplicationRules { + /// Rules to ignore specific windows + #[serde(skip_serializing_if = "Option::is_none")] + pub ignore: Option>, + /// Rules to forcibly manage specific windows + #[serde(skip_serializing_if = "Option::is_none")] + pub manage: Option>, + /// Rules to manage specific windows as floating windows + #[serde(skip_serializing_if = "Option::is_none")] + pub floating: Option>, + /// Rules to identify applications which are title-less - only accepts Simple Exe rules + #[serde(skip_serializing_if = "Option::is_none")] + pub titleless: Option>, + /// Rules to identify applications which are title-less - only accepts Simple Exe rules + #[serde(skip_serializing_if = "Option::is_none")] + pub tabbed: Option>, +} diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index 4f6cc053..857fcf9f 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -45,6 +45,7 @@ pub use komorebi_layouts::Sizing; pub use komorebi_layouts::validate_ratios; // Keep local modules that aren't in komorebi-layouts +pub mod asc; pub mod config_generation; pub mod pathext; diff --git a/komorebi/src/static_config.rs b/komorebi/src/static_config.rs index e2c92dc8..33610d81 100644 --- a/komorebi/src/static_config.rs +++ b/komorebi/src/static_config.rs @@ -13,6 +13,10 @@ //! nothing on KDE Plasma is accepted and ignored, and a key that is not known at all is ignored //! too, as serde does. //! +//! 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. +//! //! Settings that have no key are left to their defaults ([`DEFAULT_RESIZE_DELTA`], //! [`DEFAULT_WORKSPACE_PADDING`] and the others in [`crate`]), and an optional key set to `null` //! is the same as one that is left out. @@ -45,8 +49,11 @@ use crate::core::SocketMessage; use crate::core::WindowContainerBehaviour; use crate::core::WindowHidingPosition; use crate::core::WindowManagementBehaviour; +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::pathext::ResolvedPathBuf; use crate::monitor::Monitor; use crate::ring::Ring; use crate::window::AspectRatio; @@ -302,6 +309,18 @@ impl From<&Monitor> for MonitorConfig { } } +#[serde_with::serde_as] +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[serde(untagged)] +/// Path(s) to application-specific configuration file(s) +pub enum AppSpecificConfigurationPath { + /// A single applications.json file + Single(#[serde_as(as = "ResolvedPathBuf")] PathBuf), + /// Multiple applications.json files + Multiple(#[serde_as(as = "Vec")] Vec), +} + #[serde_with::serde_as] #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] @@ -365,6 +384,10 @@ pub struct StaticConfig { #[serde(skip_serializing_if = "Option::is_none")] #[cfg_attr(feature = "schemars", schemars(extend("default" = DEFAULT_MOUSE_FOLLOWS_FOCUS)))] pub mouse_follows_focus: Option, + /// Path to an applications.json, or a list of them, with rules for the applications that + /// need them: which windows to ignore, to manage and to float + #[serde(skip_serializing_if = "Option::is_none")] + pub app_specific_configuration_path: Option, /// Global default workspace padding #[serde(skip_serializing_if = "Option::is_none")] #[cfg_attr(feature = "schemars", schemars(extend("default" = DEFAULT_WORKSPACE_PADDING)))] @@ -515,6 +538,7 @@ impl From<&WindowManager> for StaticConfig { // minimum_window_height: Some(window::MINIMUM_HEIGHT.load(Ordering::SeqCst)), // minimum_window_width: Some(window::MINIMUM_WIDTH.load(Ordering::SeqCst)), mouse_follows_focus: Option::from(value.mouse_follows_focus), + app_specific_configuration_path: None, default_workspace_padding: Option::from( DEFAULT_WORKSPACE_PADDING.load(Ordering::SeqCst), ), @@ -711,6 +735,29 @@ impl StaticConfig { // } // } // + if let Some(path) = &self.app_specific_configuration_path { + match path { + AppSpecificConfigurationPath::Single(path) => handle_asc_file( + path, + &mut ignore_identifiers, + &mut manage_identifiers, + &mut floating_applications, + &mut regex_identifiers, + )?, + AppSpecificConfigurationPath::Multiple(paths) => { + for path in paths { + handle_asc_file( + path, + &mut ignore_identifiers, + &mut manage_identifiers, + &mut floating_applications, + &mut regex_identifiers, + )? + } + } + } + } + // if let Some(behaviour) = self.window_handling_behaviour { // WINDOW_HANDLING_BEHAVIOUR.store(behaviour); // } @@ -1101,6 +1148,63 @@ fn populate_rules( Ok(()) } +/// Adds the rules of the applications.json at `path` to the lists the window manager decides by +/// +/// A file that is not there is skipped with a warning: one `komorebi.json` is meant to work on +/// every platform, and the file it points to may be one that another platform has +/// (`applications.mac.json` on a KDE desktop). A file that is there and is not an applications.json +/// is an error. Only a file with the extension `json` is read. The rules to ignore, to manage and +/// to float of every application in the file are added; the other kinds of rule that file can +/// have (`titleless` and `tabbed`) are about how another platform exposes windows, and are +/// ignored. +#[allow(clippy::too_many_arguments)] +fn handle_asc_file( + path: &PathBuf, + ignore_identifiers: &mut Vec, + manage_identifiers: &mut Vec, + floating_applications: &mut Vec, + regex_identifiers: &mut HashMap, +) -> eyre::Result<()> { + // One komorebi.json is meant to work on every platform, and the file it points to is one that + // another platform has (applications.mac.json on a KDE desktop): warn and carry on + if !path.exists() { + tracing::warn!( + "the application specific configuration {} does not exist, ignoring it", + path.display() + ); + return Ok(()); + } + + match path.extension() { + Some(ext) if ext.to_string_lossy().to_string().as_str() == "json" => { + tracing::info!("loading applications.json from: {}", path.display()); + let mut asc = ApplicationSpecificConfiguration::load(path)?; + + for entry in asc.values_mut() { + match entry { + AscApplicationRulesOrSchema::Schema(_) => {} + AscApplicationRulesOrSchema::AscApplicationRules(entry) => { + if let Some(rules) = &mut entry.ignore { + populate_rules(rules, ignore_identifiers, regex_identifiers)?; + } + + if let Some(rules) = &mut entry.manage { + populate_rules(rules, manage_identifiers, regex_identifiers)?; + } + + if let Some(rules) = &mut entry.floating { + populate_rules(rules, floating_applications, regex_identifiers)?; + } + } + } + } + } + _ => {} + } + + Ok(()) +} + #[cfg(test)] mod tests { use super::*; @@ -1159,4 +1263,43 @@ mod tests { assert!(StaticConfig::read(&path).is_err()); } + + #[test] + fn a_missing_application_specific_configuration_is_skipped_not_fatal() { + let (mut ignore, mut manage, mut floating) = (Vec::new(), Vec::new(), Vec::new()); + let mut regexes = HashMap::new(); + + handle_asc_file( + &PathBuf::from( + "/nonexistent/komorebi-application-specific-configuration/applications.mac.json", + ), + &mut ignore, + &mut manage, + &mut floating, + &mut regexes, + ) + .unwrap(); + + assert!(ignore.is_empty() && manage.is_empty() && floating.is_empty()); + } + + #[test] + fn an_application_specific_configuration_that_exists_but_is_broken_is_still_an_error() { + let path = PathBuf::from(format!( + "/tmp/komorebi-asc-test-{}.json", + std::process::id() + )); + std::fs::write(&path, "{ not json").unwrap(); + + let result = handle_asc_file( + &path, + &mut Vec::new(), + &mut Vec::new(), + &mut Vec::new(), + &mut HashMap::new(), + ); + let _ = std::fs::remove_file(&path); + + assert!(result.is_err()); + } } diff --git a/komorebi/tests/asc.rs b/komorebi/tests/asc.rs new file mode 100644 index 00000000..e60fe88e --- /dev/null +++ b/komorebi/tests/asc.rs @@ -0,0 +1,229 @@ +//! The application specific configuration against an in-memory desktop: the `applications.json` +//! files a `komorebi.json` names with `app_specific_configuration_path`, and what the rules in +//! them do to the windows that open. +//! +//! The rule lists are process-wide, so every test names the applications of its own, and each +//! loads its configuration the way the daemon does. Window ids are in the 39_000s. + +use color_eyre::eyre; +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::core::asc::ApplicationSpecificConfiguration; +use komorebi::core::asc::AscApplicationRulesOrSchema; +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::os::unix::net::UnixListener; +use std::path::Path; +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::AtomicU32; +use std::sync::atomic::Ordering; + +/// A path for a file or a socket of a test, short enough for a unix socket path on macOS +fn short_path(suffix: &str) -> PathBuf { + static NEXT: AtomicU32 = AtomicU32::new(0); + PathBuf::from(format!( + "/tmp/kma-{}-{}.{suffix}", + std::process::id(), + NEXT.fetch_add(1, Ordering::SeqCst) + )) +} + +fn write(suffix: &str, text: &str) -> PathBuf { + let path = short_path(suffix); + std::fs::write(&path, text).unwrap(); + path +} + +fn added(id: u32) -> WindowManagerEvent { + WindowManagerEvent::Show( + SystemNotification::KWin(KWinNotification::WindowAdded), + Window::from(id), + ) +} + +/// What the tests find out about a window the desktop opened +#[derive(Debug, PartialEq)] +enum Where { + Tiled, + Floating, + Unmanaged, +} + +struct Desktop { + fake: Arc, + wm: WindowManager, +} + +impl Desktop { + /// Loads a `komorebi.json` with `config` in it over a fake desktop, as the daemon does + fn load(config: &str) -> eyre::Result { + let fake = Arc::new(FakeBackend::with_one_monitor()); + let path = write("json", config); + let (_sender, receiver) = crossbeam_channel::bounded(1); + let socket = short_path("sock"); + + let wm = with_backend(fake.clone(), || -> eyre::Result { + let mut wm = + StaticConfig::preload(&path, receiver, Some(UnixListener::bind(&socket)?))?; + wm.init()?; + Ok(wm) + }); + let _ = std::fs::remove_file(&socket); + let _ = std::fs::remove_file(&path); + + Ok(Self { fake, wm: wm? }) + } + + /// Opens a window of an application, and says what became of it + fn open(&mut self, id: u32, exe: &str, class: &str) -> Where { + self.fake + .open_window(id, exe, class, &format!("window {id}")); + with_backend(self.fake.clone(), || self.wm.process_event(added(id))).unwrap(); + + let workspace = self.wm.focused_workspace().unwrap(); + if workspace.containers().iter().any(|c| c.contains_window(id)) { + Where::Tiled + } else if workspace.floating_windows().iter().any(|w| w.id == id) { + Where::Floating + } else { + Where::Unmanaged + } + } +} + +fn applications(path: &Path) -> String { + format!( + r#"{{ "app_specific_configuration_path": {:?} }}"#, + path.display().to_string() + ) +} + +#[test] +fn the_rules_of_an_applications_file_ignore_manage_and_float_windows() { + let file = write( + "json", + r#"{ + "asc one": { + "ignore": [{ "kind": "Exe", "id": "asc-ignored", "matching_strategy": "Equals" }], + "floating": [{ "kind": "Class", "id": "asc-floated", "matching_strategy": "Equals" }] + }, + "asc two": { + "manage": [{ "kind": "Exe", "id": "asc-managed", "matching_strategy": "Equals" }] + } + }"#, + ); + let mut desktop = Desktop::load(&applications(&file)).unwrap(); + + assert_eq!(desktop.open(39_001, "asc-ignored", "x"), Where::Unmanaged); + assert_eq!(desktop.open(39_002, "foot", "asc-floated"), Where::Floating); + assert_eq!(desktop.open(39_003, "asc-managed", "x"), Where::Tiled); + assert_eq!(desktop.open(39_004, "foot", "foot"), Where::Tiled); + let _ = std::fs::remove_file(file); +} + +#[test] +fn every_file_of_a_list_is_read() { + let first = write( + "json", + r#"{ "a": { "ignore": [{ "kind": "Exe", "id": "list-first", "matching_strategy": "Equals" }] } }"#, + ); + let second = write( + "json", + r#"{ "b": { "ignore": [{ "kind": "Exe", "id": "list-second", "matching_strategy": "Equals" }] } }"#, + ); + let mut desktop = Desktop::load(&format!( + r#"{{ "app_specific_configuration_path": [{:?}, {:?}] }}"#, + first.display().to_string(), + second.display().to_string() + )) + .unwrap(); + + assert_eq!(desktop.open(39_011, "list-first", "x"), Where::Unmanaged); + assert_eq!(desktop.open(39_012, "list-second", "x"), Where::Unmanaged); + assert_eq!(desktop.open(39_013, "foot", "foot"), Where::Tiled); + let _ = (std::fs::remove_file(first), std::fs::remove_file(second)); +} + +#[test] +fn the_rules_of_the_configuration_and_of_the_file_add_up() { + let file = write( + "json", + r#"{ "a": { "ignore": [{ "kind": "Exe", "id": "sum-file", "matching_strategy": "Equals" }] } }"#, + ); + let mut desktop = Desktop::load(&format!( + r#"{{ + "app_specific_configuration_path": {:?}, + "ignore_rules": [{{ "kind": "Exe", "id": "sum-config", "matching_strategy": "Equals" }}] + }}"#, + file.display().to_string() + )) + .unwrap(); + + assert_eq!(desktop.open(39_021, "sum-file", "x"), Where::Unmanaged); + assert_eq!(desktop.open(39_022, "sum-config", "x"), Where::Unmanaged); + let _ = std::fs::remove_file(file); +} + +#[test] +fn a_file_that_is_not_there_is_skipped_and_one_that_is_broken_is_an_error() { + let missing = short_path("json"); + let mut desktop = Desktop::load(&applications(&missing)).unwrap(); + assert_eq!(desktop.open(39_031, "foot", "foot"), Where::Tiled); + + let broken = write("json", "{ not json"); + let error = Desktop::load(&applications(&broken)) + .err() + .expect("a broken file is an error"); + assert!(!error.to_string().is_empty()); + let _ = std::fs::remove_file(broken); +} + +#[test] +fn the_kinds_of_rule_of_other_platforms_are_read_and_do_nothing() { + let file = write( + "json", + r#"{ + "$schema": "https://example.invalid/applications.schema.json", + "kde": { + "titleless": [{ "kind": "Exe", "id": "other-platform", "matching_strategy": "Equals" }], + "tabbed": [{ "kind": "Exe", "id": "other-platform", "matching_strategy": "Equals" }] + } + }"#, + ); + let mut desktop = Desktop::load(&applications(&file)).unwrap(); + + assert_eq!(desktop.open(39_041, "other-platform", "x"), Where::Tiled); + + // the `$schema` entry is the text of a schema's address, and the rest are applications + let loaded = ApplicationSpecificConfiguration::load(&file).unwrap(); + assert!(matches!( + loaded["$schema"], + AscApplicationRulesOrSchema::Schema(_) + )); + assert!(matches!( + loaded["kde"], + AscApplicationRulesOrSchema::AscApplicationRules(_) + )); + let _ = std::fs::remove_file(file); +} + +#[test] +fn the_applications_file_komorebic_ships_floats_the_programs_it_names() { + let shipped = Path::new(env!("CARGO_MANIFEST_DIR")).join("../komorebic/applications.json"); + let mut desktop = Desktop::load(&applications(&shipped)).unwrap(); + + assert_eq!( + desktop.open(39_051, "kcalc", "org.kde.kcalc"), + Where::Floating + ); + assert_eq!( + desktop.open(39_052, "systemsettings", "org.kde.systemsettings"), + Where::Floating + ); + assert_eq!(desktop.open(39_053, "kate", "org.kde.kate"), Where::Tiled); +} diff --git a/komorebi/tests/config_parity.rs b/komorebi/tests/config_parity.rs index f0405476..9d383ea2 100644 --- a/komorebi/tests/config_parity.rs +++ b/komorebi/tests/config_parity.rs @@ -43,8 +43,6 @@ const WINDOWS_ONLY: &[&str] = &[ /// ignored until then. Each comment says which commit of the plan brings the feature, and takes /// the key off this list. const NOT_YET: &[&str] = &[ - // application specific configuration (39) - "app_specific_configuration_path", // borders drawn by the compositor (43) "border", "border_colours", diff --git a/komorebic/applications.json b/komorebic/applications.json new file mode 100644 index 00000000..953f28db --- /dev/null +++ b/komorebic/applications.json @@ -0,0 +1,11 @@ +{ + "KDE Plasma": { + "floating": [ + { "kind": "Class", "id": "org.kde.kcalc", "matching_strategy": "Equals" }, + { "kind": "Class", "id": "org.gnome.Calculator", "matching_strategy": "Equals" }, + { "kind": "Class", "id": "org.kde.spectacle", "matching_strategy": "Equals" }, + { "kind": "Class", "id": "org.kde.polkit-kde-authentication-agent-1", "matching_strategy": "Equals" }, + { "kind": "Class", "id": "org.kde.systemsettings", "matching_strategy": "Equals" } + ] + } +}