diff --git a/Cargo.lock b/Cargo.lock index 62a711e1..1b779bf9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3347,6 +3347,7 @@ dependencies = [ "ed25519-dalek", "hotwatch", "komorebi-collections", + "komorebi-config", "komorebi-layouts", "komorebi-protocol", "komorebi-scrolling", @@ -3449,6 +3450,22 @@ dependencies = [ "serde_json_lenient", ] +[[package]] +name = "komorebi-config" +version = "0.1.42" +dependencies = [ + "clap", + "color-eyre", + "komorebi-layouts", + "komorebi-protocol", + "komorebi-themes", + "schemars 1.2.3", + "serde", + "serde_json_lenient", + "serde_with", + "strum", +] + [[package]] name = "komorebi-e2e-agent" version = "0.1.0" @@ -3563,6 +3580,7 @@ dependencies = [ "dunce", "fs-tail", "komorebi-client", + "komorebi-config", "komorebic-core", "lazy_static", "miette", diff --git a/Cargo.toml b/Cargo.toml index 37d30b9e..c4cd9097 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,6 +6,7 @@ members = [ "komorebi-client", "komorebi-gui", "crates/komorebi-collections", + "crates/komorebi-config", "komorebi-layouts", "komorebi-scrolling", "komorebic", diff --git a/crates/komorebi-config/Cargo.toml b/crates/komorebi-config/Cargo.toml new file mode 100644 index 00000000..432a1c74 --- /dev/null +++ b/crates/komorebi-config/Cargo.toml @@ -0,0 +1,32 @@ +[package] +name = "komorebi-config" +version = "0.1.42" +edition = "2024" +description = "The komorebi.json data types (StaticConfig and the types it is made of) and the generation of its JSON Schema" + +[dependencies] +komorebi-layouts = { path = "../../komorebi-layouts" } +komorebi-protocol = { path = "../komorebi-protocol", default-features = false } +komorebi-themes = { path = "../../komorebi-themes" } + +clap = { workspace = true } +color-eyre = { workspace = true } +serde = { workspace = true } +serde_with = { version = "3.12", features = ["schemars_1"] } +serde_json = { workspace = true, features = ["preserve_order"] } +strum = { workspace = true } + +# Optional dependencies +schemars = { workspace = true, optional = true } + +[dev-dependencies] +schemars = { workspace = true } + +[features] +default = ["schemars"] +schemars = [ + "dep:schemars", + "komorebi-layouts/schemars", + "komorebi-protocol/schemars", + "komorebi-themes/schemars", +] diff --git a/crates/komorebi-config/src/animation.rs b/crates/komorebi-config/src/animation.rs new file mode 100644 index 00000000..c593619f --- /dev/null +++ b/crates/komorebi-config/src/animation.rs @@ -0,0 +1,40 @@ +//! How the animation settings of `komorebi.json` are scoped. + +use std::collections::HashMap; + +use komorebi_protocol::animation::prefix::AnimationPrefix; +use serde::Deserialize; +use serde::Serialize; + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[serde(untagged)] +/// Animation configuration +/// +/// This can be either global: +/// ```json +/// { +/// "enabled": true, +/// "style": "EaseInSine", +/// "fps": 60, +/// "duration": 250 +/// } +/// ``` +/// +/// Or scoped by an animation kind prefix: +/// ```json +/// { +/// "movement": { +/// "enabled": true, +/// "style": "EaseInSine", +/// "fps": 60, +/// "duration": 250 +/// } +/// } +/// ``` +pub enum PerAnimationPrefixConfig { + /// Animation configuration prefixed for a specific animation kind + Prefix(HashMap), + /// Animation configuration for all animation kinds + Global(T), +} diff --git a/crates/komorebi-config/src/application_configuration.rs b/crates/komorebi-config/src/application_configuration.rs new file mode 100644 index 00000000..b54ffd77 --- /dev/null +++ b/crates/komorebi-config/src/application_configuration.rs @@ -0,0 +1,84 @@ +//! The entries that the Windows `fetch-app-specific-configuration` +//! generator reads, and the options that turn into rules. +//! +//! The generator itself (it reads YAML) stays in the Windows daemon; the data types are here so +//! that the conversion into `ApplicationSpecificConfiguration` can be a `From` impl next to it. + +use clap::ValueEnum; +use komorebi_protocol::types::ApplicationIdentifier; +use serde::Deserialize; +use serde::Serialize; +use strum::Display; +use strum::EnumString; + +use crate::matching::IdWithIdentifier; +use crate::matching::MatchingRule; +use crate::matching::MatchingStrategy; + +#[derive(Clone, Copy, Debug, Serialize, Deserialize, Display, EnumString, ValueEnum)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[strum(serialize_all = "snake_case")] +#[serde(rename_all = "snake_case")] +pub enum ApplicationOptions { + ObjectNameChange, + Layered, + TrayAndMultiWindow, + Force, + BorderOverflow, +} + +impl ApplicationOptions { + #[must_use] + pub fn raw_cfgen(&self, kind: &ApplicationIdentifier, id: &str) -> String { + match self { + ApplicationOptions::ObjectNameChange => { + format!("komorebic.exe identify-object-name-change-application {kind} \"{id}\"",) + } + ApplicationOptions::Layered => { + format!("komorebic.exe identify-layered-application {kind} \"{id}\"",) + } + ApplicationOptions::TrayAndMultiWindow => { + format!("komorebic.exe identify-tray-application {kind} \"{id}\"",) + } + ApplicationOptions::Force => { + format!("komorebic.exe manage-rule {kind} \"{id}\"") + } + ApplicationOptions::BorderOverflow => { + unreachable!("deprecated"); + } + } + } + + #[must_use] + pub fn cfgen(&self, kind: &ApplicationIdentifier, id: &str) -> String { + format!( + "RunWait('{}', , \"Hide\")", + ApplicationOptions::raw_cfgen(self, kind, id) + ) + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct ApplicationConfiguration { + pub name: String, + pub identifier: IdWithIdentifier, + #[serde(skip_serializing_if = "Option::is_none")] + pub options: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + #[serde(alias = "float_identifiers")] + pub ignore_identifiers: Option>, +} + +impl ApplicationConfiguration { + pub fn populate_default_matching_strategies(&mut self) { + if self.identifier.matching_strategy.is_none() { + match self.identifier.kind { + ApplicationIdentifier::Exe | ApplicationIdentifier::Path => { + self.identifier.matching_strategy = Option::from(MatchingStrategy::Equals); + } + ApplicationIdentifier::Class | ApplicationIdentifier::Title => {} + } + } + } +} diff --git a/crates/komorebi-config/src/asc.rs b/crates/komorebi-config/src/asc.rs new file mode 100644 index 00000000..a2bedac6 --- /dev/null +++ b/crates/komorebi-config/src/asc.rs @@ -0,0 +1,139 @@ +//! The application specific configuration file (`app_specific_configuration_path`): rules, by +//! application, for the windows komorebi ignores, manages or floats. + +use std::collections::BTreeMap; +use std::ops::Deref; +use std::ops::DerefMut; +use std::path::PathBuf; + +use color_eyre::Result; +use serde::Deserialize; +use serde::Serialize; + +use crate::application_configuration::ApplicationConfiguration; +use crate::application_configuration::ApplicationOptions; +use crate::matching::MatchingRule; + +#[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))] +#[allow(clippy::large_enum_variant)] // the rules are the common case; the enum is a map value +#[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, Default, 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 ignore specific windows from the transparency feature + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("x-komorebi-platforms" = ["windows"])))] + pub transparency_ignore: Option>, + /// Rules to identify applications which minimize to the tray or have multiple windows + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("x-komorebi-platforms" = ["windows"])))] + pub tray_and_multi_window: Option>, + /// Rules to identify applications which have the `WS_EX_LAYERED` Extended Window Style + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("x-komorebi-platforms" = ["windows"])))] + pub layered: Option>, + /// Rules to identify applications which send the `EVENT_OBJECT_NAMECHANGE` event on launch + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("x-komorebi-platforms" = ["windows"])))] + pub object_name_change: Option>, + /// Rules to identify applications which are slow to send initial event notifications + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("x-komorebi-platforms" = ["windows"])))] + pub slow_application: Option>, + /// Rules to identify applications which are title-less - only accepts Simple Exe rules + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("x-komorebi-platforms" = ["kde", "macos"])))] + pub titleless: Option>, + /// Rules to identify applications which are title-less - only accepts Simple Exe rules + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("x-komorebi-platforms" = ["kde", "macos"])))] + pub tabbed: Option>, +} + +impl From> for ApplicationSpecificConfiguration { + fn from(value: Vec) -> Self { + let mut map = BTreeMap::new(); + + for entry in &value { + let key = entry.name.clone(); + let mut rules = AscApplicationRules { + ignore: entry.ignore_identifiers.clone(), + ..AscApplicationRules::default() + }; + + if let Some(options) = &entry.options { + for opt in options { + let rule = Some(vec![MatchingRule::Simple(entry.identifier.clone())]); + match opt { + ApplicationOptions::ObjectNameChange => rules.object_name_change = rule, + ApplicationOptions::Layered => rules.layered = rule, + ApplicationOptions::TrayAndMultiWindow => { + rules.tray_and_multi_window = rule + } + ApplicationOptions::Force => rules.manage = rule, + ApplicationOptions::BorderOverflow => {} + } + } + } + + if rules.ignore.is_some() + || rules.manage.is_some() + || rules.floating.is_some() + || rules.transparency_ignore.is_some() + || rules.tray_and_multi_window.is_some() + || rules.layered.is_some() + || rules.object_name_change.is_some() + || rules.slow_application.is_some() + { + map.insert(key, AscApplicationRulesOrSchema::AscApplicationRules(rules)); + } + } + + Self(map) + } +} diff --git a/crates/komorebi-config/src/aspect_ratio.rs b/crates/komorebi-config/src/aspect_ratio.rs new file mode 100644 index 00000000..4b5c1768 --- /dev/null +++ b/crates/komorebi-config/src/aspect_ratio.rs @@ -0,0 +1,51 @@ +//! The aspect ratio a temporarily floating window is resized to. + +use serde::Deserialize; +use serde::Serialize; +use strum::Display; +use strum::EnumString; + +#[derive(Copy, Clone, Debug, Display, EnumString, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[serde(untagged)] +/// Aspect ratio for temporarily floating windows +pub enum AspectRatio { + /// Predefined aspect ratio + #[cfg_attr(feature = "schemars", schemars(title = "Predefined"))] + Predefined(PredefinedAspectRatio), + /// Custom W:H aspect ratio + #[cfg_attr(feature = "schemars", schemars(title = "Custom"))] + Custom(i32, i32), +} + +impl Default for AspectRatio { + fn default() -> Self { + AspectRatio::Predefined(PredefinedAspectRatio::default()) + } +} + +impl AspectRatio { + pub fn width_and_height(self) -> (i32, i32) { + match self { + AspectRatio::Predefined(predefined) => match predefined { + PredefinedAspectRatio::Ultrawide => (21, 9), + PredefinedAspectRatio::Widescreen => (16, 9), + PredefinedAspectRatio::Standard => (4, 3), + }, + AspectRatio::Custom(w, h) => (w, h), + } + } +} + +#[derive(Copy, Clone, Debug, Default, Display, EnumString, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Predefined aspect ratio +pub enum PredefinedAspectRatio { + /// 21:9 + Ultrawide, + /// 16:9 + Widescreen, + /// 4:3 + #[default] + Standard, +} diff --git a/crates/komorebi-config/src/behaviour.rs b/crates/komorebi-config/src/behaviour.rs new file mode 100644 index 00000000..92a71fce --- /dev/null +++ b/crates/komorebi-config/src/behaviour.rs @@ -0,0 +1,152 @@ +//! The small enums that `komorebi.json` uses to choose how a window or a container behaves. +//! +//! Some belong to one platform only (`WindowHidingPosition` to KDE and macOS, +//! `WindowHandlingBehaviour` and `ZOrder` to Windows): they are defined here all the same, +//! and a daemon that does not read the key says so when it loads the file. + +use clap::ValueEnum; +use serde::Deserialize; +use serde::Serialize; +use strum::Display; +use strum::EnumString; + +#[derive( + Clone, Copy, Debug, Default, Serialize, Deserialize, Display, EnumString, ValueEnum, PartialEq, +)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Window container behaviour when a new window is opened +pub enum WindowContainerBehaviour { + /// Create a new container for each new window + #[default] + Create, + /// Append new windows to the focused window container + Append, +} + +#[derive( + Clone, Copy, Debug, Default, Serialize, Deserialize, Display, EnumString, ValueEnum, PartialEq, +)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Floating layer behaviour when a new window is opened +pub enum FloatingLayerBehaviour { + /// Tile new windows (unless they match a float rule or float override is active) + #[default] + Tile, + /// Float new windows + Float, +} + +impl FloatingLayerBehaviour { + pub fn should_float(&self) -> bool { + match self { + FloatingLayerBehaviour::Tile => false, + FloatingLayerBehaviour::Float => true, + } + } +} + +#[derive( + Clone, Copy, Debug, Default, Serialize, Deserialize, Display, EnumString, ValueEnum, PartialEq, +)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Window hiding position +pub enum WindowHidingPosition { + /// Hide windows in the bottom left corner of the screen + #[default] + BottomLeft, + /// Hide windows in the bottom right corner of the screen + BottomRight, +} + +#[derive( + Clone, Copy, Debug, Default, Serialize, Deserialize, Display, EnumString, ValueEnum, PartialEq, +)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Placement behaviour for floating windows +pub enum Placement { + /// Does not change the size or position of the window + #[default] + None, + /// Center the window without changing the size + Center, + /// Center the window and resize it according to the `AspectRatio` + CenterAndResize, +} + +impl Placement { + pub fn should_center(&self) -> bool { + match self { + Placement::None => false, + Placement::Center | Placement::CenterAndResize => true, + } + } + + pub fn should_resize(&self) -> bool { + match self { + Placement::None | Placement::Center => false, + Placement::CenterAndResize => true, + } + } +} + +#[derive( + Clone, Copy, Debug, Default, Serialize, Deserialize, Display, EnumString, ValueEnum, PartialEq, +)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Behaviour when an action would cross a monitor boundary +pub enum CrossBoundaryBehaviour { + /// Attempt to perform actions across a workspace boundary + Workspace, + /// Attempt to perform actions across a monitor boundary + #[default] + Monitor, +} + +#[derive( + Clone, Copy, Debug, Default, Serialize, Deserialize, Display, EnumString, ValueEnum, PartialEq, +)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Window handling behaviour +pub enum WindowHandlingBehaviour { + #[default] + /// Synchronous + Sync, + /// Asynchronous + Async, +} + +#[derive(Debug, Copy, Clone, Display, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Z Order (https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setwindowpos) +pub enum ZOrder { + /// HWND_TOP + /// + /// Places the window at the top of the Z order. + Top, + /// HWND_NOTOPMOST + /// + /// Places the window above all non-topmost windows (that is, behind all topmost windows). + /// This flag has no effect if the window is already a non-topmost window. + NoTopMost, + /// HWND_BOTTOM + /// + /// Places the window at the bottom of the Z order. If the hWnd parameter identifies a topmost window, + /// the window loses its topmost status and is placed at the bottom of all other windows. + Bottom, + /// HWND_TOPMOST + /// + /// Places the window above all non-topmost windows. + /// The window maintains its topmost position even when it is deactivated. + TopMost, +} + +impl From for isize { + fn from(val: ZOrder) -> Self { + match val { + ZOrder::Top => 0, + ZOrder::NoTopMost => -2, + ZOrder::Bottom => 1, + ZOrder::TopMost => -1, + } + } +} diff --git a/crates/komorebi-config/src/changes.rs b/crates/komorebi-config/src/changes.rs new file mode 100644 index 00000000..4bb1c06f --- /dev/null +++ b/crates/komorebi-config/src/changes.rs @@ -0,0 +1,325 @@ +//! What each platform's schema says differently from the union, as data. +//! +//! The union is written once (Windows' text, Windows' defaults); a view applies the changes of +//! its platform after pruning. They are of three kinds: descriptions that read differently on +//! a platform (spelling, or a sentence about that platform), default values that are a platform +//! fact (paddings, border width and offset), and properties the platform's file never had. Each +//! entry is a candidate for convergence: removing one is a description or default change of one +//! checked-in schema, which the test of the schemas shows. +//! +//! Generated from the difference between the union's view and the checked-in schema.json of +//! each tree (the helper is `tools/schema-changes` in the work notes); the test `tests/schemas.rs` +//! proves that view and file are byte-identical. + +use komorebi_protocol::platforms::Platform; + +/// One change of a view +#[derive(Clone, Copy, Debug)] +pub enum Change { + /// Replace the value at the JSON pointer with this JSON text + Set(&'static str), + /// Remove the key at the JSON pointer + Remove, +} + +/// The changes a platform's view applies, in order +#[must_use] +pub const fn for_platform(platform: Platform) -> &'static [(&'static str, Change)] { + match platform { + Platform::Windows => WINDOWS, + Platform::Kde => KDE, + Platform::MacOs => MACOS, + } +} + +const WINDOWS: &[(&str, Change)] = &[( + "/$defs/PlacementTarget", + Change::Set( + r####"{"description":"A target position for window placement, used as a key in `InitialWindowPlacementRules::Rules`.\n\nCan be either a `WindowPlacement` variant name (e.g. `\"Primary\"`, `\"Last\"`)\nor a 1-based container index (e.g. `\"1\"`, `\"3\"`, or the integer `3`).\n\nNOTE: Integer indices are 1-based in the config for user-friendliness.","anyOf":[{"$ref":"#/$defs/WindowPlacement"},{"description":"A 1-based container index as a string","type":"string","pattern":"^[0-9]+$"},{"description":"A 1-based container index","type":"integer","minimum":0}]}"####, + ), +)]; + +const KDE: &[(&str, Change)] = &[ + ( + "/$defs/AnimationsConfig/description", + Change::Set(r####""Animation configuration""####), + ), + ( + "/$defs/AppSpecificConfigurationPath/anyOf/0/description", + Change::Set(r####""A single applications.json file""####), + ), + ( + "/$defs/AppSpecificConfigurationPath/anyOf/1/description", + Change::Set(r####""Multiple applications.json files""####), + ), + ( + "/$defs/BorderColours/description", + Change::Set( + r####""Border colours for different container states\n\nThese options will have no effect if a `theme` is set""####, + ), + ), + ( + "/$defs/MonitorConfig/properties/container_padding/description", + Change::Set(r####""Container padding""####), + ), + ( + "/$defs/MonitorConfig/properties/window_hiding_position/description", + Change::Set( + r####""Accepted so that a configuration written for another platform loads, and ignored: there is\nno hiding position on KDE Plasma""####, + ), + ), + ( + "/$defs/ThemeOptions/properties/floating_border/description", + Change::Set(r####""Border color when the window is floating""####), + ), + ( + "/$defs/ThemeOptions/properties/monocle_border/description", + Change::Set(r####""Border color when the container is in monocle mode""####), + ), + ( + "/$defs/ThemeOptions/properties/single_border/description", + Change::Set(r####""Border color when the container contains a single window""####), + ), + ( + "/$defs/ThemeOptions/properties/stack_border/description", + Change::Set(r####""Border color when the container contains multiple windows""####), + ), + ( + "/$defs/ThemeOptions/properties/unfocused_border/description", + Change::Set(r####""Border color when the container is unfocused""####), + ), + ( + "/$defs/ThemeOptions/properties/unfocused_locked_border/description", + Change::Set(r####""Border color when the container is unfocused and locked""####), + ), + ( + "/$defs/Wallpaper/properties/theme_options/description", + Change::Set(r####""Specify theme options""####), + ), + ( + "/$defs/WorkspaceConfig/properties/window_container_behaviour_rules/description", + Change::Set( + r####""Window container behavior rules in the format of threshold => behavior""####, + ), + ), + ( + "/description", + Change::Set( + r####""The `komorebi.json` static configuration file reference for komorebi for KDE Plasma""####, + ), + ), + ( + "/properties/app_specific_configuration_path/description", + Change::Set( + r####""Path to an applications.json, or a list of them, with rules for the applications that\nneed them: which windows to ignore, to manage and to float""####, + ), + ), + ( + "/properties/border_colours/description", + Change::Set( + r####""Window border colours for different container types (has no effect if a theme is defined)""####, + ), + ), + ( + "/properties/border_offset/default", + Change::Set(r####"0"####), + ), + ( + "/properties/border_width/default", + Change::Set(r####"10"####), + ), + ( + "/properties/default_container_padding/default", + Change::Set(r####"5"####), + ), + ( + "/properties/default_workspace_padding/default", + Change::Set(r####"5"####), + ), + ( + "/properties/float_rule_placement/description", + Change::Set( + r####""Determines the `Placement` to be used when spawning a window that matches a\n'floating_applications' rule""####, + ), + ), + ( + "/properties/focus_follows_mouse/description", + Change::Set( + r####""Focus the window under the pointer. On KDE this is KWin's own focus policy, whichever\nimplementation is named""####, + ), + ), + ( + "/properties/tabbed_applications/description", + Change::Set( + r####""Accepted so that a configuration written for another platform loads, and ignored: a KWin\nwindow has no native tabs""####, + ), + ), + ( + "/properties/titleless_applications/description", + Change::Set( + r####""Accepted so that a configuration written for another platform loads, and ignored: a KWin\nwindow is always a window""####, + ), + ), + ( + "/properties/transparency/description", + Change::Set(r####""Add transparency to unfocused windows (default: false)""####), + ), + ( + "/properties/transparency_alpha/description", + Change::Set( + r####""Alpha value for unfocused window transparency [[0-255]] (default: 200)""####, + ), + ), + ( + "/$defs/KomorebiThemeBase16/properties/stackbar_background", + Change::Remove, + ), + ( + "/$defs/KomorebiThemeBase16/properties/stackbar_focused_text", + Change::Remove, + ), + ( + "/$defs/KomorebiThemeBase16/properties/stackbar_unfocused_text", + Change::Remove, + ), + ( + "/$defs/KomorebiThemeCatppuccin/properties/stackbar_background", + Change::Remove, + ), + ( + "/$defs/KomorebiThemeCatppuccin/properties/stackbar_focused_text", + Change::Remove, + ), + ( + "/$defs/KomorebiThemeCatppuccin/properties/stackbar_unfocused_text", + Change::Remove, + ), + ( + "/$defs/KomorebiThemeCustom/properties/stackbar_background", + Change::Remove, + ), + ( + "/$defs/KomorebiThemeCustom/properties/stackbar_focused_text", + Change::Remove, + ), + ( + "/$defs/KomorebiThemeCustom/properties/stackbar_unfocused_text", + Change::Remove, + ), + ( + "/$defs/Wallpaper/properties/theme_options/default", + Change::Remove, + ), + ("/properties/focus_follows_mouse/deprecated", Change::Remove), + ("/properties/transparency/default", Change::Remove), + ("/properties/transparency_alpha/default", Change::Remove), +]; + +const MACOS: &[(&str, Change)] = &[ + ( + "/$defs/AnimationsConfig/description", + Change::Set(r####""Animation configuration""####), + ), + ( + "/$defs/AppSpecificConfigurationPath/anyOf/0/description", + Change::Set(r####""A single applications.json file""####), + ), + ( + "/$defs/AppSpecificConfigurationPath/anyOf/1/description", + Change::Set(r####""Multiple applications.json files""####), + ), + ( + "/$defs/BorderColours/description", + Change::Set( + r####""Border colours for different container states\n\nThese options will have no effect if a `theme` is set""####, + ), + ), + ( + "/$defs/MonitorConfig/properties/container_padding/description", + Change::Set(r####""Container padding""####), + ), + ( + "/$defs/Wallpaper/properties/theme_options/description", + Change::Set(r####""Specify theme options""####), + ), + ( + "/description", + Change::Set( + r####""The `komorebi.json` static configuration file reference for komorebi for Mac `v0.1.0`\n\n`\"$schema\": \"https://komorebi-for-mac.lgug2z.com/komorebi.0.1.0.schema.json\"`""####, + ), + ), + ( + "/properties/border_colours/description", + Change::Set( + r####""Window border colours for different container types (has no effect if a theme is defined)""####, + ), + ), + ( + "/properties/border_offset/default", + Change::Set(r####"0"####), + ), + ( + "/properties/border_width/default", + Change::Set(r####"10"####), + ), + ( + "/properties/default_container_padding/default", + Change::Set(r####"5"####), + ), + ( + "/properties/default_workspace_padding/default", + Change::Set(r####"5"####), + ), + ( + "/properties/float_rule_placement/description", + Change::Set( + r####""Determines the `Placement` to be used when spawning a window that matches a\n'floating_applications' rule""####, + ), + ), + ( + "/properties/floating_window_aspect_ratio/description", + Change::Set( + r####""Identify applications which are slow to send initial event notifications\nAspect ratio to resize with when toggling floating mode for a window""####, + ), + ), + ( + "/$defs/KomorebiThemeBase16/properties/stackbar_background", + Change::Remove, + ), + ( + "/$defs/KomorebiThemeBase16/properties/stackbar_focused_text", + Change::Remove, + ), + ( + "/$defs/KomorebiThemeBase16/properties/stackbar_unfocused_text", + Change::Remove, + ), + ( + "/$defs/KomorebiThemeCatppuccin/properties/stackbar_background", + Change::Remove, + ), + ( + "/$defs/KomorebiThemeCatppuccin/properties/stackbar_focused_text", + Change::Remove, + ), + ( + "/$defs/KomorebiThemeCatppuccin/properties/stackbar_unfocused_text", + Change::Remove, + ), + ( + "/$defs/KomorebiThemeCustom/properties/stackbar_background", + Change::Remove, + ), + ( + "/$defs/KomorebiThemeCustom/properties/stackbar_focused_text", + Change::Remove, + ), + ( + "/$defs/KomorebiThemeCustom/properties/stackbar_unfocused_text", + Change::Remove, + ), + ( + "/$defs/Wallpaper/properties/theme_options/default", + Change::Remove, + ), +]; diff --git a/crates/komorebi-config/src/defaults.rs b/crates/komorebi-config/src/defaults.rs new file mode 100644 index 00000000..b0b38f52 --- /dev/null +++ b/crates/komorebi-config/src/defaults.rs @@ -0,0 +1,18 @@ +//! The values the schema says a key has when the file leaves it out. +//! +//! These are the Windows values. Each daemon keeps its own run-time default for the few that +//! differ (the paddings, the border width and offset), and the schema view of a platform says +//! that platform's value (see `schema::platform_changes`). + +pub const DEFAULT_RESIZE_DELTA: i32 = 50; +pub const DEFAULT_MOUSE_FOLLOWS_FOCUS: bool = true; +pub const DEFAULT_WORKSPACE_PADDING: i32 = 10; +pub const DEFAULT_CONTAINER_PADDING: i32 = 10; +pub const SLOW_APPLICATION_COMPENSATION_TIME: u64 = 20; +pub const ANIMATION_FPS: u64 = 60; +pub const BORDER_WIDTH: i32 = 8; +pub const BORDER_OFFSET: i32 = -1; +pub const BORDER_ENABLED: bool = true; +pub const BORDER_RADIUS: i32 = 10; +pub const TRANSPARENCY_ENABLED: bool = false; +pub const TRANSPARENCY_ALPHA: u8 = 200; diff --git a/crates/komorebi-config/src/lib.rs b/crates/komorebi-config/src/lib.rs new file mode 100644 index 00000000..a40e456b --- /dev/null +++ b/crates/komorebi-config/src/lib.rs @@ -0,0 +1,24 @@ +//! The `komorebi.json` data types and the generation of their JSON Schema. +//! +//! The crate holds no window manager code: it knows what a configuration file may say, not +//! how a daemon applies it. The types are moved here from the three daemons one family at a +//! time; the schema of each tree is checked in (`schema.json`, `schema.asc.json`) and +//! `tests/schemas.rs` compares what this crate generates with those files. +#![warn(clippy::all)] +#![allow(clippy::missing_errors_doc, clippy::use_self, clippy::doc_markdown)] + +#[cfg(feature = "schemars")] +pub mod schema; + +pub mod animation; +pub mod application_configuration; +pub mod asc; +pub mod aspect_ratio; +pub mod behaviour; +pub mod changes; +pub mod defaults; +pub mod matching; +pub mod placement; +#[cfg(feature = "schemars")] +pub mod platforms; +pub mod static_config; diff --git a/crates/komorebi-config/src/matching.rs b/crates/komorebi-config/src/matching.rs new file mode 100644 index 00000000..899124fa --- /dev/null +++ b/crates/komorebi-config/src/matching.rs @@ -0,0 +1,161 @@ +//! Rules that match an application by how it identifies itself. +//! +//! A [`MatchingRule`] is the form every list of rules in the configuration takes: a single +//! [`IdWithIdentifier`], or a list of them that must all match. + +use serde::Deserialize; +use serde::Serialize; +use strum::Display; + +use komorebi_protocol::types::ApplicationIdentifier; + +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[serde(untagged)] +/// Rule for matching applications +pub enum MatchingRule { + /// Simple matching rule which must evaluate to true + Simple(IdWithIdentifier), + /// Composite matching rule where all conditions must evaluate to true + Composite(Vec), +} + +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Rule for assigning applications to a workspace +pub struct WorkspaceMatchingRule { + /// Target monitor index + pub monitor_index: usize, + /// Target workspace index + pub workspace_index: usize, + /// Matching rule for the application + pub matching_rule: MatchingRule, + /// Whether to apply the rule only when the application is initially launched + pub initial_only: bool, +} + +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Rule for matching applications +pub struct IdWithIdentifier { + /// Kind of identifier to target + pub kind: ApplicationIdentifier, + /// Target identifier + pub id: String, + #[serde(skip_serializing_if = "Option::is_none")] + /// Matching strategy to use + pub matching_strategy: Option, +} + +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Display)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Strategy for matching identifiers +pub enum MatchingStrategy { + /// Should not be used, only kept for backward compatibility + Legacy, + /// Equals + Equals, + /// Starts With + StartsWith, + /// Ends With + EndsWith, + /// Contains + Contains, + /// Regex + Regex, + /// Does not end with + DoesNotEndWith, + /// Does not start with + DoesNotStartWith, + /// Does not equal + DoesNotEqual, + /// Does not contain + DoesNotContain, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct IdWithIdentifierAndComment { + pub kind: ApplicationIdentifier, + pub id: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub comment: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub matching_strategy: Option, +} + +impl From for IdWithIdentifier { + fn from(value: IdWithIdentifierAndComment) -> Self { + Self { + kind: value.kind, + id: value.id.clone(), + matching_strategy: value.matching_strategy, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_rule_that_is_an_object_is_simple() { + let rule: MatchingRule = serde_json::from_str( + r#"{ "kind": "Exe", "id": "foot", "matching_strategy": "Equals" }"#, + ) + .expect("parses"); + + assert_eq!( + rule, + MatchingRule::Simple(IdWithIdentifier { + kind: ApplicationIdentifier::Exe, + id: "foot".to_string(), + matching_strategy: Some(MatchingStrategy::Equals), + }) + ); + } + + #[test] + fn a_rule_that_is_a_list_is_composite() { + let rule: MatchingRule = serde_json::from_str( + r#"[{ "kind": "Exe", "id": "foot" }, { "kind": "Title", "id": "scratch", "matching_strategy": "StartsWith" }]"#, + ) + .expect("parses"); + + let MatchingRule::Composite(parts) = rule else { + panic!("a list of objects is a composite rule"); + }; + assert_eq!(parts.len(), 2); + assert_eq!( + parts[1].matching_strategy, + Some(MatchingStrategy::StartsWith) + ); + } + + #[test] + fn the_matching_strategy_is_left_out_when_there_is_none() { + let rule = IdWithIdentifier { + kind: ApplicationIdentifier::Class, + id: "firefox".to_string(), + matching_strategy: None, + }; + + let json = serde_json::to_string(&rule).expect("serializes"); + + assert_eq!(json, r#"{"kind":"Class","id":"firefox"}"#); + } + + #[test] + fn a_commented_rule_becomes_a_plain_one() { + let commented: IdWithIdentifierAndComment = serde_json::from_str( + r#"{ "kind": "Path", "id": "/usr/bin/kcalc", "comment": "a calculator" }"#, + ) + .expect("parses"); + + let plain = IdWithIdentifier::from(commented); + + assert_eq!(plain.kind, ApplicationIdentifier::Path); + assert_eq!(plain.id, "/usr/bin/kcalc"); + assert_eq!(plain.matching_strategy, None); + } +} diff --git a/crates/komorebi-config/src/placement.rs b/crates/komorebi-config/src/placement.rs new file mode 100644 index 00000000..94b8f772 --- /dev/null +++ b/crates/komorebi-config/src/placement.rs @@ -0,0 +1,219 @@ +//! Where a new window goes in a workspace: the placement strategies, the targets that name a +//! place and the rules that pick one. + +use clap::ValueEnum; +use serde::Deserialize; +use serde::Serialize; +use strum::Display; +use strum::EnumString; + +use crate::matching; + +#[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 behaviour) + #[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]+$" + } + ] + }) + } +} + +/// 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(matching::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), +} + +/// 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), +} diff --git a/crates/komorebi-config/src/platforms.rs b/crates/komorebi-config/src/platforms.rs new file mode 100644 index 00000000..f56e0acb --- /dev/null +++ b/crates/komorebi-config/src/platforms.rs @@ -0,0 +1,48 @@ +//! Which platform reads which key of `komorebi.json`. +//! +//! The table is not written a second time: it is read from the `x-komorebi-platforms` markers +//! of the one `StaticConfig`, so a key cannot be added without saying who reads it. + +use komorebi_protocol::platforms::Platform; +use serde_json::Value; + +use crate::schema::PLATFORMS; +use crate::schema::platform_name; +use crate::schema::union; +use crate::static_config::StaticConfig; + +/// Whether `platform` reads the top-level `key` of a configuration. A key the type does not +/// know is read by nobody (it is ignored everywhere). +#[must_use] +pub fn reads(platform: Platform, key: &str) -> bool { + let schema = union::(); + match schema["properties"].get(key) { + None => false, + Some(property) => match property.get(PLATFORMS) { + Some(Value::Array(platforms)) => platforms + .iter() + .any(|p| p.as_str() == Some(platform_name(platform))), + _ => true, + }, + } +} + +/// The top-level keys of the configuration text `raw` that are keys of `komorebi.json` but that +/// `platform` does not read, in file order: what a daemon says at load time instead of silently +/// dropping them. Keys that are not known at all are not reported. +/// +/// # Errors +/// +/// The text is not JSON. +pub fn unsupported_keys(raw: &str, platform: Platform) -> color_eyre::Result> { + let value: Value = serde_json::from_str(raw)?; + let schema = union::(); + let known = schema["properties"].as_object(); + Ok(value + .as_object() + .into_iter() + .flat_map(|object| object.keys()) + .filter(|key| known.is_some_and(|k| k.contains_key(*key)) && !reads(platform, key)) + .cloned() + .collect()) +} diff --git a/crates/komorebi-config/src/schema.rs b/crates/komorebi-config/src/schema.rs new file mode 100644 index 00000000..3330f1a7 --- /dev/null +++ b/crates/komorebi-config/src/schema.rs @@ -0,0 +1,201 @@ +//! Generation of the JSON Schema files that are checked in next to the sources. +//! +//! The data types describe every key of `komorebi.json` that any platform reads. A key (or a +//! field of a nested type) that only some platforms read carries `x-komorebi-platforms`, a list +//! of platform names, in its schema. The schema a platform checks in is a *view* of that union: +//! [`view`] drops what the platform does not read, strips the `x-komorebi-` markers and +//! removes the definitions nothing refers to any more. + +use crate::changes; +use crate::changes::Change; +pub use komorebi_protocol::platforms::Platform; +use schemars::JsonSchema; +use serde_json::Map; +use serde_json::Value; + +/// The key that lists the platforms that read a property. +pub const PLATFORMS: &str = "x-komorebi-platforms"; + +/// The name a platform has in `x-komorebi-platforms`. +#[must_use] +pub const fn platform_name(platform: Platform) -> &'static str { + match platform { + Platform::Windows => "windows", + Platform::MacOs => "macos", + Platform::Kde => "kde", + } +} + +/// The text `komorebic` prints for the schema of `T`: pretty JSON followed by a newline. This is +/// the union over all platforms. +#[must_use] +pub fn pretty() -> String { + to_text(&union::()) +} + +/// The schema of `T` as one JSON value, the union over all platforms. +#[must_use] +pub fn union() -> Value { + let schema = schemars::schema_for!(T); + serde_json::to_value(schema).expect("a schema is JSON") +} + +/// The schema text that is checked in for `platform`: the view of the union of `T`. +#[must_use] +pub fn view(platform: Platform) -> String { + to_text(&view_of(union::(), platform)) +} + +fn to_text(schema: &Value) -> String { + let mut text = serde_json::to_string_pretty(schema).expect("a schema is JSON"); + text.push('\n'); + text +} + +/// Prune `schema` to what `platform` reads. +#[must_use] +pub fn view_of(mut schema: Value, platform: Platform) -> Value { + let name = platform_name(platform); + prune(&mut schema, name); + for (def, pointer, text) in platform_text(platform) { + if let Some(target) = schema.pointer_mut(&format!("/$defs/{def}{pointer}")) { + *target = Value::String((*text).to_string()); + } + } + for (pointer, change) in changes::for_platform(platform) { + apply(&mut schema, pointer, *change); + } + let mut reachable = Vec::new(); + collect_refs(&schema, &mut reachable); + if let Some(defs) = schema.get("$defs").and_then(Value::as_object).cloned() { + // a definition can refer to others: follow until nothing new is found + let mut next = 0; + while next < reachable.len() { + if let Some(def) = defs.get(&reachable[next]) { + let mut found = Vec::new(); + collect_refs(def, &mut found); + for name in found { + if !reachable.contains(&name) { + reachable.push(name); + } + } + } + next += 1; + } + let kept: Map = defs + .into_iter() + .filter(|(n, _)| reachable.contains(n)) + .collect(); + schema["$defs"] = Value::Object(kept); + } + schema +} + +/// Remove the properties `platform` does not read, everywhere, and the markers of the rest. +fn prune(value: &mut Value, platform: &str) { + match value { + Value::Object(map) => { + if let Some(Value::Object(properties)) = map.get_mut("properties") { + let gone: Vec = properties + .iter() + .filter(|(_, property)| !reads(property, platform)) + .map(|(key, _)| key.clone()) + .collect(); + properties.retain(|key, _| !gone.contains(key)); + if let Some(Value::Array(required)) = map.get_mut("required") { + required.retain(|key| !gone.iter().any(|g| key.as_str() == Some(g))); + } + } + map.remove(PLATFORMS); + for child in map.values_mut() { + prune(child, platform); + } + } + Value::Array(items) => items.iter_mut().for_each(|item| prune(item, platform)), + _ => {} + } +} + +/// A property without the marker is read by every platform. +fn reads(property: &Value, platform: &str) -> bool { + match property.get(PLATFORMS) { + Some(Value::Array(platforms)) => platforms.iter().any(|p| p.as_str() == Some(platform)), + _ => true, + } +} + +fn collect_refs(value: &Value, found: &mut Vec) { + match value { + Value::Object(map) => { + if let Some(Value::String(target)) = map.get("$ref") + && let Some(name) = target.strip_prefix("#/$defs/") + && !found.iter().any(|n| n == name) + { + found.push(name.to_string()); + } + for (key, child) in map { + if key != "$defs" { + collect_refs(child, found); + } + } + } + Value::Array(items) => items.iter().for_each(|item| collect_refs(item, found)), + _ => {} + } +} + +const WINDOWS_PATH: &str = "A file system path. Environment variables like %VAR%, $Env:VAR, or $VAR are automatically resolved."; +const UNIX_PATH: &str = + "A file system path. Environment variables like $VAR are automatically resolved."; +const FFM_KDE: &str = "Focus follows mouse implementation\n\nThe two exist on Windows. On KDE the compositor does it, so both ask KWin for its\n\"focus follows mouse\" focus policy."; + +/// Descriptions of definitions that live in `komorebi-protocol` and read differently on each +/// platform: (definition, JSON pointer inside it, text). The protocol crate picks the text by +/// the platform it is compiled for; a view is the same on every host, so it says them here. +fn platform_text(platform: Platform) -> &'static [(&'static str, &'static str, &'static str)] { + match platform { + Platform::Windows => &[ + ("PathBuf", "/description", WINDOWS_PATH), + ("ApplicationIdentifier", "/oneOf/1/description", "Class"), + ( + "FocusFollowsMouseImplementation", + "/description", + "Focus follows mouse implementation", + ), + ], + Platform::Kde => &[ + ("PathBuf", "/description", UNIX_PATH), + ( + "ApplicationIdentifier", + "/oneOf/1/description", + "Role or subrole", + ), + ("FocusFollowsMouseImplementation", "/description", FFM_KDE), + ], + Platform::MacOs => &[ + ("PathBuf", "/description", UNIX_PATH), + ( + "ApplicationIdentifier", + "/oneOf/1/description", + "Role or subrole", + ), + ], + } +} + +fn apply(schema: &mut Value, pointer: &str, change: Change) { + match change { + Change::Set(json) => { + if let Some(target) = schema.pointer_mut(pointer) { + *target = serde_json::from_str(json).expect("a change is JSON"); + } + } + Change::Remove => { + if let Some((parent, key)) = pointer.rsplit_once('/') + && let Some(Value::Object(map)) = schema.pointer_mut(parent) + { + map.retain(|k, _| k != key); + } + } + } +} diff --git a/crates/komorebi-config/src/static_config.rs b/crates/komorebi-config/src/static_config.rs new file mode 100644 index 00000000..b08e339f --- /dev/null +++ b/crates/komorebi-config/src/static_config.rs @@ -0,0 +1,709 @@ +//! The `komorebi.json` static configuration file: one `StaticConfig` with every key any +//! platform reads. A key that only some platforms read says so in its schema +//! (`x-komorebi-platforms`); a daemon reports the keys it does not read when it loads a file. + +use std::collections::HashMap; +use std::path::PathBuf; + +use komorebi_layouts::Axis; +use komorebi_layouts::DefaultLayout; +use komorebi_layouts::LayoutDefaultEntry; +use komorebi_layouts::LayoutOptions; +use komorebi_layouts::Rect; +use komorebi_protocol::animation::AnimationStyle; +use komorebi_protocol::pathext::ResolvedPathBuf; +use komorebi_protocol::pathext::resolve_option_hashmap_usize_path; +use komorebi_protocol::types::BorderImplementation; +use komorebi_protocol::types::BorderStyle; +use komorebi_protocol::types::FocusFollowsMouseImplementation; +use komorebi_protocol::types::HidingBehaviour; +use komorebi_protocol::types::MonocleFocusBehaviour; +use komorebi_protocol::types::MoveBehaviour; +use komorebi_protocol::types::OperationBehaviour; +use komorebi_protocol::types::StackbarLabel; +use komorebi_protocol::types::StackbarMode; +use komorebi_themes::KomorebiTheme; +use komorebi_themes::colour::Colour; +use serde::Deserialize; +use serde::Serialize; + +use crate::animation::PerAnimationPrefixConfig; +use crate::aspect_ratio::AspectRatio; +use crate::behaviour::CrossBoundaryBehaviour; +use crate::behaviour::FloatingLayerBehaviour; +use crate::behaviour::Placement; +use crate::behaviour::WindowContainerBehaviour; +use crate::behaviour::WindowHandlingBehaviour; +use crate::behaviour::WindowHidingPosition; +use crate::behaviour::ZOrder; +use crate::defaults; +use crate::matching::MatchingRule; +use crate::placement::InitialWindowPlacementRules; + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Border colours for different container states +pub struct BorderColours { + /// Border colour when the container contains a single window + #[serde(skip_serializing_if = "Option::is_none")] + pub single: Option, + /// Border colour when the container contains multiple windows + #[serde(skip_serializing_if = "Option::is_none")] + pub stack: Option, + /// Border colour when the container is in monocle mode + #[serde(skip_serializing_if = "Option::is_none")] + pub monocle: Option, + /// Border colour when the container is in floating mode + #[serde(skip_serializing_if = "Option::is_none")] + pub floating: Option, + /// Border colour when the container is unfocused + #[serde(skip_serializing_if = "Option::is_none")] + pub unfocused: Option, + /// Border colour when the container is unfocused and locked + #[serde(skip_serializing_if = "Option::is_none")] + pub unfocused_locked: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Theme options +pub struct ThemeOptions { + /// Specify Light or Dark variant for theme generation + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::ThemeVariant::Dark)))] + pub theme_variant: Option, + /// Border colour when the container contains a single window + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::Base16Value::Base0D)))] + pub single_border: Option, + /// Border colour when the container contains multiple windows + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::Base16Value::Base0B)))] + pub stack_border: Option, + /// Border colour when the container is in monocle mode + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::Base16Value::Base0F)))] + pub monocle_border: Option, + /// Border colour when the window is floating + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::Base16Value::Base09)))] + pub floating_border: Option, + /// Border colour when the container is unfocused + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::Base16Value::Base01)))] + pub unfocused_border: Option, + /// Border colour when the container is unfocused and locked + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::Base16Value::Base08)))] + pub unfocused_locked_border: Option, + /// Stackbar focused tab text colour + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::Base16Value::Base0B)))] + #[cfg_attr(feature = "schemars", schemars(extend("x-komorebi-platforms" = ["windows"])))] + pub stackbar_focused_text: Option, + /// Stackbar unfocused tab text colour + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::Base16Value::Base05)))] + #[cfg_attr(feature = "schemars", schemars(extend("x-komorebi-platforms" = ["windows"])))] + pub stackbar_unfocused_text: Option, + /// Stackbar tab background colour + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::Base16Value::Base01)))] + #[cfg_attr(feature = "schemars", schemars(extend("x-komorebi-platforms" = ["windows"])))] + pub stackbar_background: Option, + /// Komorebi status bar accent + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::Base16Value::Base0D)))] + pub bar_accent: Option, +} + +#[serde_with::serde_as] +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Wallpaper configuration +pub struct Wallpaper { + /// Path to the wallpaper image file + #[serde_as(as = "ResolvedPathBuf")] + pub path: PathBuf, + /// Generate and apply Base16 theme for this wallpaper + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = true)))] + pub generate_theme: Option, + /// Specify Light or Dark variant for theme generation + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::ThemeVariant::Dark)))] + pub theme_options: Option, +} + +#[serde_with::serde_as] +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Workspace configuration +pub struct WorkspaceConfig { + /// Name + pub name: String, + /// Layout + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = DefaultLayout::BSP)))] + pub layout: Option, + /// Layout-specific options + #[serde(skip_serializing_if = "Option::is_none")] + pub layout_options: Option, + /// Threshold-based layout options rules in the format of threshold => options. + /// When container count >= threshold, the highest matching threshold's options + /// fully replace the base `layout_options`. + /// This follows the same threshold logic as `layout_rules`. + #[serde(skip_serializing_if = "Option::is_none")] + pub layout_options_rules: Option>, + /// END OF LIFE FEATURE: Custom Layout + #[cfg_attr(feature = "schemars", schemars(extend("deprecated" = true)))] + #[serde(skip_serializing_if = "Option::is_none")] + #[serde_as(as = "Option")] + #[cfg_attr(feature = "schemars", schemars(extend("x-komorebi-platforms" = ["windows"])))] + pub custom_layout: Option, + /// Layout rules in the format of threshold => layout + #[serde(skip_serializing_if = "Option::is_none")] + pub layout_rules: Option>, + /// Work area offset rules in the format of threshold => Rect (default: None) + #[serde(skip_serializing_if = "Option::is_none")] + pub work_area_offset_rules: Option>, + /// END OF LIFE FEATURE: Custom layout rules + #[cfg_attr(feature = "schemars", schemars(extend("deprecated" = true)))] + #[serde(skip_serializing_if = "Option::is_none")] + #[serde(deserialize_with = "resolve_option_hashmap_usize_path", default)] + #[cfg_attr(feature = "schemars", schemars(extend("x-komorebi-platforms" = ["windows"])))] + pub custom_layout_rules: Option>, + /// Container padding (default: global) + #[serde(skip_serializing_if = "Option::is_none")] + pub container_padding: Option, + /// Workspace padding (default: global) + #[serde(skip_serializing_if = "Option::is_none")] + pub workspace_padding: Option, + /// Initial workspace application rules + #[serde(skip_serializing_if = "Option::is_none")] + pub initial_workspace_rules: Option>, + /// Permanent workspace application rules + #[serde(skip_serializing_if = "Option::is_none")] + pub workspace_rules: Option>, + /// Workspace specific work area offset + #[serde(skip_serializing_if = "Option::is_none")] + pub work_area_offset: Option, + /// Apply this monitor's window-based work area offset + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = true)))] + pub apply_window_based_work_area_offset: Option, + /// Determine what happens when a new window is opened + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = WindowContainerBehaviour::Create)))] + pub window_container_behaviour: Option, + /// Window container behaviour rules in the format of threshold => behaviour + #[serde(skip_serializing_if = "Option::is_none")] + pub window_container_behaviour_rules: Option>, + /// Enable or disable float override, which makes it so every new window opens in floating mode + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = false)))] + pub float_override: Option, + /// Enable or disable tiling for the workspace + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = true)))] + pub tile: Option, + /// Specify an axis on which to flip the selected layout + #[serde(skip_serializing_if = "Option::is_none")] + pub layout_flip: Option, + /// Determine what happens to a new window when the Floating workspace layer is active + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = FloatingLayerBehaviour::Tile)))] + pub floating_layer_behaviour: Option, + /// 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")] + #[cfg_attr(feature = "schemars", schemars(extend("x-komorebi-platforms" = ["windows", "kde"])))] + pub initial_window_placement_rules: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Monitor configuration +pub struct MonitorConfig { + /// Workspace configurations + pub workspaces: Vec, + /// Monitor-specific work area offset + #[serde(skip_serializing_if = "Option::is_none")] + pub work_area_offset: Option, + /// Window based work area offset + #[serde(skip_serializing_if = "Option::is_none")] + pub window_based_work_area_offset: Option, + /// Open window limit after which the window based work area offset will no longer be applied + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = 1)))] + pub window_based_work_area_offset_limit: Option, + /// Container padding (default: global) + #[serde(skip_serializing_if = "Option::is_none")] + pub container_padding: Option, + /// Workspace padding (default: global) + #[serde(skip_serializing_if = "Option::is_none")] + pub workspace_padding: Option, + /// Specify a wallpaper for this monitor + #[serde(skip_serializing_if = "Option::is_none")] + pub wallpaper: Option, + /// Determine what happens to a new window when the Floating workspace layer is active + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = FloatingLayerBehaviour::Tile)))] + pub floating_layer_behaviour: Option, + /// Determine which position windows should be hidden at on this monitor + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("x-komorebi-platforms" = ["kde", "macos"])))] + pub window_hiding_position: Option, +} + +#[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))] +/// The `komorebi.json` static configuration file reference for `v0.1.42` +pub struct StaticConfig { + /// DEPRECATED from v0.1.22: no longer required + #[cfg_attr(feature = "schemars", schemars(extend("deprecated" = true)))] + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("x-komorebi-platforms" = ["windows"])))] + pub invisible_borders: Option, + /// DISCOURAGED: Minimum width for a window to be eligible for tiling + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("x-komorebi-platforms" = ["windows"])))] + pub minimum_window_width: Option, + /// DISCOURAGED: Minimum height for a window to be eligible for tiling + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("x-komorebi-platforms" = ["windows"])))] + pub minimum_window_height: Option, + /// Delta to resize windows by + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = defaults::DEFAULT_RESIZE_DELTA)))] + pub resize_delta: Option, + /// Determine what happens when a new window is opened + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = WindowContainerBehaviour::Create)))] + pub window_container_behaviour: Option, + /// Enable or disable float override, which makes it so every new window opens in floating mode + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = false)))] + pub float_override: Option, + /// Determines what happens on a new window when on the `FloatingLayer` + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = FloatingLayerBehaviour::Tile)))] + pub floating_layer_behaviour: Option, + /// Determines the placement of a new window when toggling to float + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = Placement::CenterAndResize)))] + pub toggle_float_placement: Option, + /// Determines the `Placement` to be used when spawning a window on the floating layer with the + /// `FloatingLayerBehaviour` set to `FloatingLayerBehaviour::Float` + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = Placement::Center)))] + pub floating_layer_placement: Option, + /// Determines the `Placement` to be used when spawning a window with float override active + #[serde(skip_serializing_if = "Option::is_none")] + pub float_override_placement: Option, + /// Determines the `Placement` to be used when spawning a window that matches a + /// `floating_applications` rule + #[serde(skip_serializing_if = "Option::is_none")] + pub float_rule_placement: Option, + /// Determine what happens when a window is moved across a monitor boundary + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = MoveBehaviour::Swap)))] + pub cross_monitor_move_behaviour: Option, + /// Determine what happens when an action is called on a window at a monitor boundary + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = CrossBoundaryBehaviour::Monitor)))] + pub cross_boundary_behaviour: Option, + /// Determine what happens when focusing in a direction while a monocle container is active + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = MonocleFocusBehaviour::NoOp)))] + pub monocle_focus_behaviour: Option, + /// Determine what happens when commands are sent while an unmanaged window is in the foreground + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = OperationBehaviour::Op)))] + pub unmanaged_window_operation_behaviour: Option, + /// END OF LIFE FEATURE: Use https://github.com/LGUG2Z/masir instead + #[cfg_attr(feature = "schemars", schemars(extend("deprecated" = true)))] + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("x-komorebi-platforms" = ["windows", "kde"])))] + pub focus_follows_mouse: Option, + /// Enable or disable mouse follows focus + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = defaults::DEFAULT_MOUSE_FOLLOWS_FOCUS)))] + pub mouse_follows_focus: Option, + /// Path to applications.json from komorebi-application-specific-configurations + #[serde(skip_serializing_if = "Option::is_none")] + pub app_specific_configuration_path: Option, + /// Width of window borders + #[serde(skip_serializing_if = "Option::is_none")] + #[serde(alias = "active_window_border_width")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = defaults::BORDER_WIDTH)))] + pub border_width: Option, + /// Offset of window borders + #[serde(skip_serializing_if = "Option::is_none")] + #[serde(alias = "active_window_border_offset")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = defaults::BORDER_OFFSET)))] + pub border_offset: Option, + /// Radius of window borders + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = defaults::BORDER_RADIUS)))] + #[cfg_attr(feature = "schemars", schemars(extend("x-komorebi-platforms" = ["kde", "macos"])))] + pub border_radius: Option, + /// Display window borders + #[serde(skip_serializing_if = "Option::is_none")] + #[serde(alias = "active_window_border")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = defaults::BORDER_ENABLED)))] + pub border: Option, + /// Window border colours for different container types (has no effect if [`theme`] is defined) + #[serde(skip_serializing_if = "Option::is_none")] + #[serde(alias = "active_window_border_colours")] + pub border_colours: Option, + /// Window border style + #[serde(skip_serializing_if = "Option::is_none")] + #[serde(alias = "active_window_border_style")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = BorderStyle::System)))] + #[cfg_attr(feature = "schemars", schemars(extend("x-komorebi-platforms" = ["windows"])))] + pub border_style: Option, + /// DEPRECATED from v0.1.31: no longer required + #[cfg_attr(feature = "schemars", schemars(extend("deprecated" = true)))] + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("x-komorebi-platforms" = ["windows"])))] + pub border_z_order: Option, + /// Window border implementation + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = BorderImplementation::Komorebi)))] + #[cfg_attr(feature = "schemars", schemars(extend("x-komorebi-platforms" = ["windows"])))] + pub border_implementation: Option, + /// Add transparency to unfocused windows + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = defaults::TRANSPARENCY_ENABLED)))] + #[cfg_attr(feature = "schemars", schemars(extend("x-komorebi-platforms" = ["windows", "kde"])))] + pub transparency: Option, + /// Alpha value for unfocused window transparency [[0-255]] + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = defaults::TRANSPARENCY_ALPHA)))] + #[cfg_attr(feature = "schemars", schemars(extend("x-komorebi-platforms" = ["windows", "kde"])))] + pub transparency_alpha: Option, + /// Individual window transparency ignore rules + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("x-komorebi-platforms" = ["windows", "kde"])))] + pub transparency_ignore_rules: Option>, + /// Global default workspace padding + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = defaults::DEFAULT_WORKSPACE_PADDING)))] + pub default_workspace_padding: Option, + /// Global default container padding + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = defaults::DEFAULT_CONTAINER_PADDING)))] + pub default_container_padding: Option, + /// Per-layout default options and rules, keyed by layout name. + /// Applied as fallback when a workspace does not define its own layout_options or layout_options_rules. + /// If a workspace defines either setting, all global defaults for that layout are completely replaced. + #[serde(skip_serializing_if = "Option::is_none")] + pub layout_defaults: Option>, + /// Monitor and workspace configurations + #[serde(skip_serializing_if = "Option::is_none")] + pub monitors: Option>, + /// Which Windows signal to use when hiding windows + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = HidingBehaviour::Cloak)))] + #[cfg_attr(feature = "schemars", schemars(extend("x-komorebi-platforms" = ["windows"])))] + pub window_hiding_behaviour: Option, + /// Global work area (space used for tiling) offset + #[serde(skip_serializing_if = "Option::is_none")] + pub global_work_area_offset: Option, + /// Individual window floating rules + #[serde(skip_serializing_if = "Option::is_none")] + #[serde(alias = "float_rules")] + pub ignore_rules: Option>, + /// Individual window force-manage rules + #[serde(skip_serializing_if = "Option::is_none")] + pub manage_rules: Option>, + /// Identify applications which should be managed as floating windows + #[serde(skip_serializing_if = "Option::is_none")] + pub floating_applications: Option>, + /// Identify applications which should be managed despite not reporting titles to the system + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("x-komorebi-platforms" = ["kde", "macos"])))] + pub titleless_applications: Option>, + /// Identify applications which use native tabs for special handling + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("x-komorebi-platforms" = ["kde", "macos"])))] + pub tabbed_applications: Option>, + /// Identify border overflow applications + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("x-komorebi-platforms" = ["windows"])))] + pub border_overflow_applications: Option>, + /// Identify tray and multi-window applications + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("x-komorebi-platforms" = ["windows"])))] + pub tray_and_multi_window_applications: Option>, + /// Identify applications that have the `WS_EX_LAYERED` extended window style + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("x-komorebi-platforms" = ["windows"])))] + pub layered_applications: Option>, + /// Identify applications that send `EVENT_OBJECT_NAMECHANGE` on launch (very rare) + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("x-komorebi-platforms" = ["windows"])))] + pub object_name_change_applications: Option>, + /// Do not process `EVENT_OBJECT_NAMECHANGE` events as Show events for identified applications matching these title regexes + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("x-komorebi-platforms" = ["windows"])))] + pub object_name_change_title_ignore_list: Option>, + /// Set monitor index preferences + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("x-komorebi-platforms" = ["windows"])))] + pub monitor_index_preferences: Option>, + /// Set display index preferences + #[serde(skip_serializing_if = "Option::is_none")] + pub display_index_preferences: Option>, + /// Stackbar configuration options + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("x-komorebi-platforms" = ["windows"])))] + pub stackbar: Option, + /// Animations configuration options + #[serde(skip_serializing_if = "Option::is_none")] + pub animation: Option, + /// Theme configuration options + /// + /// If a theme is specified, `border_colours` will have no effect + #[serde(skip_serializing_if = "Option::is_none")] + pub theme: Option, + /// Identify applications which are slow to send initial event notifications + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("x-komorebi-platforms" = ["windows"])))] + pub slow_application_identifiers: Option>, + /// How long to wait when compensating for slow applications, in milliseconds + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = defaults::SLOW_APPLICATION_COMPENSATION_TIME)))] + #[cfg_attr(feature = "schemars", schemars(extend("x-komorebi-platforms" = ["windows"])))] + pub slow_application_compensation_time: Option, + /// Komorebi status bar configuration files for multiple instances on different monitors + // this option is a little special because it is only consumed by komorebic + #[serde(skip_serializing_if = "Option::is_none")] + #[serde_as(as = "Option>")] + #[cfg_attr(feature = "schemars", schemars(extend("x-komorebi-platforms" = ["windows"])))] + pub bar_configurations: Option>, + /// HEAVILY DISCOURAGED: Identify applications for which komorebi should forcibly remove title bars + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("x-komorebi-platforms" = ["windows"])))] + pub remove_titlebar_applications: Option>, + /// Aspect ratio to resize with when toggling floating mode for a window + #[serde(skip_serializing_if = "Option::is_none")] + pub floating_window_aspect_ratio: Option, + /// Which Windows API behaviour to use when manipulating windows + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = WindowHandlingBehaviour::Sync)))] + #[cfg_attr(feature = "schemars", schemars(extend("x-komorebi-platforms" = ["windows"])))] + pub window_handling_behaviour: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Animations configuration options +pub struct AnimationsConfig { + /// Enable or disable animations + #[cfg_attr(feature = "schemars", schemars(extend("default" = PerAnimationPrefixConfig::Global(false))))] + pub enabled: PerAnimationPrefixConfig, + /// Set the animation duration in ms + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = PerAnimationPrefixConfig::Global(250))))] + pub duration: Option>, + /// Set the animation style + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = PerAnimationPrefixConfig::Global(AnimationStyle::Linear))))] + pub style: Option>, + /// Set the animation FPS + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = defaults::ANIMATION_FPS)))] + pub fps: Option, + /// Render movement animations on a GPU-composited ghost surface (recommended). + /// When false, falls back to the legacy per-frame MoveWindow path. + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = false)))] + #[cfg_attr(feature = "schemars", schemars(extend("x-komorebi-platforms" = ["windows"])))] + pub ghost_movement: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Stackbar tabs configuration +pub struct TabsConfig { + /// Width of a stackbar tab + #[serde(skip_serializing_if = "Option::is_none")] + pub width: Option, + /// Focused tab text colour + #[serde(skip_serializing_if = "Option::is_none")] + pub focused_text: Option, + /// Unfocused tab text colour + #[serde(skip_serializing_if = "Option::is_none")] + pub unfocused_text: Option, + /// Tab background colour + #[serde(skip_serializing_if = "Option::is_none")] + pub background: Option, + /// Font family + #[serde(skip_serializing_if = "Option::is_none")] + pub font_family: Option, + /// Font size + #[serde(skip_serializing_if = "Option::is_none")] + pub font_size: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Stackbar configuration +pub struct StackbarConfig { + /// Stackbar height + #[serde(skip_serializing_if = "Option::is_none")] + pub height: Option, + /// Stackbar label + #[serde(skip_serializing_if = "Option::is_none")] + pub label: Option, + /// Stackbar mode + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = StackbarMode::Never)))] + pub mode: Option, + /// Stackbar tab configuration options + #[serde(skip_serializing_if = "Option::is_none")] + pub tabs: Option, +} + +impl StaticConfig { + /// Reads a configuration from text, as `komorebi.json` is read: comments and trailing commas + /// are accepted, and a key that is not known is ignored. + /// + /// ```rust + /// use komorebi_config::static_config::StaticConfig; + /// + /// let config = StaticConfig::read_raw( + /// r#"{ + /// // a comment, and a trailing comma + /// "resize_delta": 100, + /// "a_key_that_is_not_known": true, + /// }"#, + /// )?; + /// assert_eq!(config.resize_delta, Some(100)); + /// + /// assert!(StaticConfig::read_raw(r#"{ "resize_delta": "wide" }"#).is_err()); + /// + /// # Ok::<(), Box>(()) + /// ``` + /// + /// # Errors + /// + /// The text is not a configuration. + pub fn read_raw(raw: &str) -> color_eyre::Result { + Ok(serde_json::from_str(raw)?) + } + + /// Reads the file at `path`, as [`StaticConfig::read_raw`] reads text + /// + /// # Errors + /// + /// The file cannot be read, or it is not a configuration. + pub fn read(path: &PathBuf) -> color_eyre::Result { + let content = std::fs::read_to_string(path)?; + serde_json::from_str(&content).map_err(Into::into) + } + /// Prints the features of `raw` that are end-of-life + pub fn end_of_life(raw: &str) { + let features = vec![ + "focus_follows_mouse", + "custom_layout", + "custom_layout_rules", + ]; + + let mut display = false; + + for feature in features { + if raw.contains(feature) { + if !display { + display = true; + println!("\n\"{feature}\" is now end-of-life"); + } else { + println!(r#""{feature}" is now end-of-life"#); + } + } + } + + if display { + println!( + "\nEnd-of-life features will not receive any further bug fixes or updates; they should not be used\n" + ) + } + } + + /// Prints the keys of `raw` that have been renamed + pub fn aliases(raw: &str) { + let mut map = HashMap::new(); + map.insert("border", ["active_window_border"]); + map.insert("border_width", ["active_window_border_width"]); + map.insert("border_offset", ["active_window_border_offset"]); + map.insert("border_colours", ["active_window_border_colours"]); + map.insert("border_style", ["active_window_border_style"]); + map.insert("applications.json", ["applications.yaml"]); + map.insert("ignore_rules", ["float_rules"]); + + let mut display = false; + + for aliases in map.values() { + for a in aliases { + if raw.contains(a) { + display = true; + } + } + } + + if display { + println!( + "\nYour configuration file contains some options that have been renamed or deprecated:\n" + ); + for (canonical, aliases) in map { + for alias in aliases { + if raw.contains(alias) { + println!(r#""{alias}" is now "{canonical}""#); + } + } + } + } + } + + /// Prints the keys and values of `raw` that are deprecated + pub fn deprecated(raw: &str) { + let deprecated_options = ["invisible_borders", "border_z_order"]; + let deprecated_variants = vec![ + ("Hide", "window_hiding_behaviour", "Cloak"), + ("Minimize", "window_hiding_behaviour", "Cloak"), + ]; + + for option in deprecated_options { + if raw.contains(option) { + println!(r#""{option}" is deprecated and can be removed"#); + } + } + + for (variant, option, recommended) in deprecated_variants { + if raw.contains(option) && raw.contains(variant) { + println!( + r#"The "{variant}" option for "{option}" is deprecated and can be removed or replaced with "{recommended}""# + ); + } + } + } +} diff --git a/crates/komorebi-config/tests/schemas.rs b/crates/komorebi-config/tests/schemas.rs new file mode 100644 index 00000000..1d4ac3a6 --- /dev/null +++ b/crates/komorebi-config/tests/schemas.rs @@ -0,0 +1,305 @@ +//! The oracle of the crate: the schemas that are checked in next to the three daemons. +//! +//! `schema.json` and `schema.asc.json` of the Windows tree (the repository root), of +//! `komorebi-for-kde` and of `komorebi-for-mac` are what users, the docs and the nix options +//! are generated from, so they must not change by accident while the data types move into this +//! crate. The files are read by their path relative to the repository. +//! +//! What is checked at this stage: +//! - every checked-in file is in the canonical form the generator prints (pretty JSON, one +//! trailing newline), so a regenerated schema can be compared with `==` on the text; +//! - the files keep the keys they have today (53/37/33 properties, 60/52/47 definitions and +//! the six definitions of the applications schema): a step that drops or adds a key of +//! `komorebi.json` for one platform fails here. + +use std::path::PathBuf; + +use serde_json::Value; + +struct Tree { + name: &'static str, + dir: &'static str, + properties: usize, + defs: usize, +} + +const TREES: [Tree; 3] = [ + Tree { + name: "windows", + dir: "", + properties: 53, + defs: 60, + }, + Tree { + name: "kde", + dir: "komorebi-for-kde", + properties: 37, + defs: 52, + }, + Tree { + name: "macos", + dir: "komorebi-for-mac", + properties: 33, + defs: 47, + }, +]; + +fn checked_in(tree: &Tree, file: &str) -> String { + let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../..") + .join(tree.dir) + .join(file); + std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display())) +} + +#[test] +fn the_checked_in_schemas_are_in_the_form_the_generator_prints() { + for tree in &TREES { + for file in ["schema.json", "schema.asc.json"] { + let text = checked_in(tree, file); + let value: Value = serde_json::from_str(&text).expect("a schema is JSON"); + let mut again = serde_json::to_string_pretty(&value).expect("JSON"); + again.push('\n'); + assert!( + text == again, + "{} {file} is not in canonical form", + tree.name + ); + } + } +} + +#[test] +fn the_checked_in_schemas_have_the_keys_of_each_platform() { + for tree in &TREES { + let schema: Value = serde_json::from_str(&checked_in(tree, "schema.json")).unwrap(); + assert_eq!(schema["title"], "StaticConfig", "{}", tree.name); + assert_eq!( + schema["properties"].as_object().unwrap().len(), + tree.properties, + "{} properties", + tree.name + ); + assert_eq!( + schema["$defs"].as_object().unwrap().len(), + tree.defs, + "{} definitions", + tree.name + ); + + let asc: Value = serde_json::from_str(&checked_in(tree, "schema.asc.json")).unwrap(); + let defs: Vec<&str> = asc["$defs"] + .as_object() + .unwrap() + .keys() + .map(String::as_str) + .collect(); + assert_eq!( + defs, + [ + "ApplicationIdentifier", + "AscApplicationRules", + "AscApplicationRulesOrSchema", + "IdWithIdentifier", + "MatchingRule", + "MatchingStrategy" + ], + "{} applications schema", + tree.name + ); + } +} + +/// The definitions schemars generates for `T` and for everything `T` refers to, by name. +fn generated() -> serde_json::Map { + let mut generator = schemars::generate::SchemaSettings::draft2020_12().into_generator(); + let _ = generator.subschema_for::(); + let defs = generator.take_definitions(true); + match serde_json::to_value(&defs).expect("definitions are JSON") { + Value::Object(map) => map, + other => panic!("definitions are an object, not {other}"), + } +} + +/// The definitions `owned` by this crate (the others come with `T` but live in the layouts, +/// themes or protocol crates and have their own checks) must be in each of the `trees`' +/// `schema.json` and equal to what is generated for `T`. +fn assert_same_definitions(trees: &[&Tree], owned: &[&str]) { + let generated = generated::(); + for tree in trees { + let schema: Value = serde_json::from_str(&checked_in(tree, "schema.json")).unwrap(); + let defs = schema["$defs"].as_object().unwrap(); + for name in owned { + assert!( + defs.contains_key(*name), + "{} schema.json has no {name}", + tree.name + ); + assert!(generated.contains_key(*name), "{name} was not generated"); + } + for name in owned { + let def = &generated[*name]; + if let Some(checked) = defs.get(*name) { + assert!( + checked == def, + "{} schema.json: the definition of {name} differs from the generated one:\n{}\n---\n{}", + tree.name, + serde_json::to_string_pretty(checked).unwrap(), + serde_json::to_string_pretty(def).unwrap(), + ); + } + } + } +} + +fn all() -> Vec<&'static Tree> { + TREES.iter().collect() +} + +#[test] +fn the_matching_types_are_the_definitions_of_every_tree() { + use komorebi_config::matching::MatchingRule; + use komorebi_config::matching::WorkspaceMatchingRule; + + assert_same_definitions::( + &all(), + &["MatchingRule", "IdWithIdentifier", "MatchingStrategy"], + ); + // The workspace rules are an input of the daemons only: no schema carries them. + let _ = generated::(); +} + +#[test] +fn the_behaviour_enums_are_the_definitions_of_the_trees_that_have_them() { + use komorebi_config::behaviour::CrossBoundaryBehaviour; + use komorebi_config::behaviour::FloatingLayerBehaviour; + use komorebi_config::behaviour::Placement; + use komorebi_config::behaviour::WindowContainerBehaviour; + use komorebi_config::behaviour::WindowHandlingBehaviour; + use komorebi_config::behaviour::WindowHidingPosition; + use komorebi_config::behaviour::ZOrder; + + let [windows, kde, macos] = &TREES; + assert_same_definitions::(&all(), &["WindowContainerBehaviour"]); + assert_same_definitions::(&all(), &["FloatingLayerBehaviour"]); + assert_same_definitions::(&all(), &["Placement"]); + assert_same_definitions::(&all(), &["CrossBoundaryBehaviour"]); + assert_same_definitions::(&[kde, macos], &["WindowHidingPosition"]); + assert_same_definitions::(&[windows], &["WindowHandlingBehaviour"]); + assert_same_definitions::(&[windows], &["ZOrder"]); +} + +#[test] +fn the_aspect_ratio_is_the_definition_of_every_tree() { + use komorebi_config::aspect_ratio::AspectRatio; + + assert_same_definitions::(&all(), &["AspectRatio", "PredefinedAspectRatio"]); +} + +/// The platform views of the union schema of the applications file are byte-identical to the +/// three checked-in `schema.asc.json`. +#[test] +fn the_applications_schema_is_a_view_of_one_union() { + use komorebi_config::asc::ApplicationSpecificConfiguration; + use komorebi_protocol::platforms::Platform; + + for (tree, platform) in [ + (&TREES[0], Platform::Windows), + (&TREES[1], Platform::Kde), + (&TREES[2], Platform::MacOs), + ] { + let view = komorebi_config::schema::view::(platform); + assert!( + view == checked_in(tree, "schema.asc.json"), + "{}: the view of the applications schema differs from schema.asc.json", + tree.name + ); + } +} + +#[test] +fn the_placement_types_are_the_definitions_of_windows_and_kde() { + use komorebi_config::placement::InitialWindowPlacementRules; + + let [windows, kde, _] = &TREES; + // PlacementTarget is not compared: its schema is written by hand and reads differently on + // Windows (it is carried as a per-platform difference of the view). + assert_same_definitions::( + &[windows, kde], + &[ + "InitialWindowPlacementRules", + "PlacementMatchingRules", + "WindowPlacement", + ], + ); + assert_same_definitions::(&[kde], &["PlacementTarget"]); +} + +/// The platform views of the one `StaticConfig` are byte-identical to the checked-in +/// `schema.json` of each tree. +#[test] +fn the_schema_of_each_platform_is_a_view_of_the_one_static_config() { + use komorebi_config::static_config::StaticConfig; + use komorebi_protocol::platforms::Platform; + + for (tree, platform) in [(&TREES[1], Platform::Kde), (&TREES[2], Platform::MacOs)] { + let view = komorebi_config::schema::view::(platform); + assert!( + view == checked_in(tree, "schema.json"), + "{}: the view of the schema of StaticConfig differs from schema.json", + tree.name + ); + } +} + +#[test] +fn the_platform_table_comes_from_the_markers() { + use komorebi_config::platforms::reads; + use komorebi_config::platforms::unsupported_keys; + use komorebi_protocol::platforms::Platform; + + let windows_only = ["stackbar", "border_style", "slow_application_identifiers"]; + let kde_macos_only = [ + "border_radius", + "titleless_applications", + "tabbed_applications", + ]; + let windows_kde = ["transparency", "focus_follows_mouse"]; + + for key in windows_only { + assert!(reads(Platform::Windows, key)); + assert!( + !reads(Platform::Kde, key) && !reads(Platform::MacOs, key), + "{key}" + ); + } + for key in kde_macos_only { + assert!(!reads(Platform::Windows, key), "{key}"); + assert!(reads(Platform::Kde, key) && reads(Platform::MacOs, key)); + } + for key in windows_kde { + assert!(reads(Platform::Windows, key) && reads(Platform::Kde, key)); + assert!(!reads(Platform::MacOs, key), "{key}"); + } + assert!(reads(Platform::MacOs, "monitors") && !reads(Platform::MacOs, "no_such_key")); + + // the keys each tree's schema.json holds are the keys that platform reads + for (tree, platform) in [ + (&TREES[0], Platform::Windows), + (&TREES[1], Platform::Kde), + (&TREES[2], Platform::MacOs), + ] { + let schema: Value = serde_json::from_str(&checked_in(tree, "schema.json")).unwrap(); + for key in schema["properties"].as_object().unwrap().keys() { + assert!(reads(platform, key), "{} reads {key}", tree.name); + } + } + + let raw = r#"{ "stackbar": {}, "border": true, "a_key_nobody_knows": 1, "border_radius": 5 }"#; + assert_eq!(unsupported_keys(raw, Platform::Kde).unwrap(), ["stackbar"]); + assert_eq!( + unsupported_keys(raw, Platform::Windows).unwrap(), + ["border_radius"] + ); + assert!(unsupported_keys("{ ", Platform::Kde).is_err()); +} diff --git a/komorebi-for-kde/Cargo.lock b/komorebi-for-kde/Cargo.lock index 5c3ceebf..43935ed9 100644 --- a/komorebi-for-kde/Cargo.lock +++ b/komorebi-for-kde/Cargo.lock @@ -2502,6 +2502,7 @@ dependencies = [ "futures-util", "hotwatch", "komorebi-collections", + "komorebi-config", "komorebi-hotkeys", "komorebi-layouts", "komorebi-protocol", @@ -2546,6 +2547,22 @@ dependencies = [ "serde", ] +[[package]] +name = "komorebi-config" +version = "0.1.42" +dependencies = [ + "clap", + "color-eyre", + "komorebi-layouts", + "komorebi-protocol", + "komorebi-themes", + "schemars 1.2.3", + "serde", + "serde_json_lenient", + "serde_with", + "strum", +] + [[package]] name = "komorebi-hotkeys" version = "0.1.0" @@ -2625,6 +2642,7 @@ dependencies = [ "fs-tail", "komorebi", "komorebi-client", + "komorebi-config", "komorebi-hotkeys", "komorebic-core", "lazy_static", diff --git a/komorebi-for-kde/Cargo.toml b/komorebi-for-kde/Cargo.toml index 7a8be711..073b9b65 100644 --- a/komorebi-for-kde/Cargo.toml +++ b/komorebi-for-kde/Cargo.toml @@ -24,6 +24,7 @@ komorebi-layouts = { path = "../komorebi-layouts", features = [ # revision, whose layouts re-export it as `komorebi_layouts::scrolling::model` komorebi-scrolling = { path = "../komorebi-scrolling" } # the wire types shared with the other komorebi daemons +komorebi-config = { path = "../crates/komorebi-config", default-features = false, features = ["schemars"] } komorebi-protocol = { path = "../crates/komorebi-protocol", default-features = false, features = ["schemars"] } komorebi-transport = { path = "../crates/komorebi-transport" } # the themes (and the palettes made from pictures), from the same upstream revision diff --git a/komorebi-for-kde/komorebi-client/tests/subscribe.rs b/komorebi-for-kde/komorebi-client/tests/subscribe.rs index 7c97376b..070055f2 100644 --- a/komorebi-for-kde/komorebi-client/tests/subscribe.rs +++ b/komorebi-for-kde/komorebi-client/tests/subscribe.rs @@ -277,6 +277,9 @@ fn a_subscriber_that_filters_state_changes_is_sent_a_theme() floating_border: None, unfocused_border: None, unfocused_locked_border: None, + stackbar_focused_text: None, + stackbar_unfocused_text: None, + stackbar_background: None, }); send_query(&SocketMessage::Theme(Box::new(theme)))?; diff --git a/komorebi-for-kde/komorebi/Cargo.toml b/komorebi-for-kde/komorebi/Cargo.toml index a614d10b..bdcd5c64 100644 --- a/komorebi-for-kde/komorebi/Cargo.toml +++ b/komorebi-for-kde/komorebi/Cargo.toml @@ -10,6 +10,7 @@ komorebi-themes = { workspace = true } komorebi-collections = { workspace = true } komorebi-layouts = { workspace = true } komorebi-scrolling = { workspace = true } +komorebi-config = { workspace = true } komorebi-protocol = { workspace = true } komorebi-transport = { workspace = true } version = { path = "../version" } diff --git a/komorebi-for-kde/komorebi/src/animation/mod.rs b/komorebi-for-kde/komorebi/src/animation/mod.rs index af2efa44..3946ec98 100644 --- a/komorebi-for-kde/komorebi/src/animation/mod.rs +++ b/komorebi-for-kde/komorebi/src/animation/mod.rs @@ -12,6 +12,7 @@ use crate::core::animation::AnimationStyle; use parking_lot::Mutex; pub use prefix::AnimationPrefix; +pub use komorebi_config::animation::PerAnimationPrefixConfig; use std::collections::HashMap; use std::sync::Arc; use std::sync::LazyLock; @@ -20,41 +21,6 @@ use std::sync::atomic::AtomicU64; pub mod prefix; -use serde::Deserialize; -use serde::Serialize; - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -#[serde(untagged)] -/// Animation configuration -/// -/// This can be either global: -/// ```json -/// { -/// "enabled": true, -/// "style": "EaseInSine", -/// "fps": 60, -/// "duration": 250 -/// } -/// ``` -/// -/// Or scoped by an animation kind prefix: -/// ```json -/// { -/// "movement": { -/// "enabled": true, -/// "style": "EaseInSine", -/// "fps": 60, -/// "duration": 250 -/// } -/// } -/// ``` -pub enum PerAnimationPrefixConfig { - /// Animation configuration prefixed for a specific animation kind - Prefix(HashMap), - /// Animation configuration for all animation kinds - Global(T), -} pub const DEFAULT_ANIMATION_ENABLED: bool = false; pub const DEFAULT_ANIMATION_STYLE: AnimationStyle = AnimationStyle::Linear; diff --git a/komorebi-for-kde/komorebi/src/check.rs b/komorebi-for-kde/komorebi/src/check.rs index 46230f05..1437a149 100644 --- a/komorebi-for-kde/komorebi/src/check.rs +++ b/komorebi-for-kde/komorebi/src/check.rs @@ -477,7 +477,11 @@ mod schema { /// Returns the keys of each level, or `None` when the schema has no `monitors` or no /// `workspaces` to find them in. pub fn known_keys() -> Option { - let root = serde_json::to_value(schemars::schema_for!(StaticConfig)).ok()?; + let root: serde_json::Value = + serde_json::from_str(&komorebi_config::schema::view::( + komorebi_config::schema::Platform::CURRENT, + )) + .ok()?; let monitors = child(&root, &root, "monitors")?; let workspaces = child(&root, monitors, "workspaces"); diff --git a/komorebi-for-kde/komorebi/src/core/asc.rs b/komorebi-for-kde/komorebi/src/core/asc.rs index d27396ed..022dbccf 100644 --- a/komorebi-for-kde/komorebi/src/core/asc.rs +++ b/komorebi-for-kde/komorebi/src/core/asc.rs @@ -1,69 +1,8 @@ //! The application specific configuration file (`app_specific_configuration_path`): rules, by //! application, for the windows komorebi ignores, manages or floats. +//! +//! The types are defined in `komorebi-config`. -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>, -} +pub use komorebi_config::asc::ApplicationSpecificConfiguration; +pub use komorebi_config::asc::AscApplicationRules; +pub use komorebi_config::asc::AscApplicationRulesOrSchema; diff --git a/komorebi-for-kde/komorebi/src/core/config_generation.rs b/komorebi-for-kde/komorebi/src/core/config_generation.rs index 273eee18..03abb7ce 100644 --- a/komorebi-for-kde/komorebi/src/core/config_generation.rs +++ b/komorebi-for-kde/komorebi/src/core/config_generation.rs @@ -1,161 +1,9 @@ //! Rules that match an application by how it identifies itself. //! -//! A [`MatchingRule`] is the form every list of rules in the configuration takes: a single -//! [`IdWithIdentifier`], or a list of them that must all match. +//! The types are defined in `komorebi-config`, which `komorebi.json` is read with. -use serde::Deserialize; -use serde::Serialize; -use strum::Display; - -use super::ApplicationIdentifier; - -#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -#[serde(untagged)] -/// Rule for matching applications -pub enum MatchingRule { - /// Simple matching rule which must evaluate to true - Simple(IdWithIdentifier), - /// Composite matching rule where all conditions must evaluate to true - Composite(Vec), -} - -#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Rule for assigning applications to a workspace -pub struct WorkspaceMatchingRule { - /// Target monitor index - pub monitor_index: usize, - /// Target workspace index - pub workspace_index: usize, - /// Matching rule for the application - pub matching_rule: MatchingRule, - /// Whether to apply the rule only when the application is initially launched - pub initial_only: bool, -} - -#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Rule for matching applications -pub struct IdWithIdentifier { - /// Kind of identifier to target - pub kind: ApplicationIdentifier, - /// Target identifier - pub id: String, - #[serde(skip_serializing_if = "Option::is_none")] - /// Matching strategy to use - pub matching_strategy: Option, -} - -#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Display)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Strategy for matching identifiers -pub enum MatchingStrategy { - /// Should not be used, only kept for backward compatibility - Legacy, - /// Equals - Equals, - /// Starts With - StartsWith, - /// Ends With - EndsWith, - /// Contains - Contains, - /// Regex - Regex, - /// Does not end with - DoesNotEndWith, - /// Does not start with - DoesNotStartWith, - /// Does not equal - DoesNotEqual, - /// Does not contain - DoesNotContain, -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -pub struct IdWithIdentifierAndComment { - pub kind: ApplicationIdentifier, - pub id: String, - #[serde(skip_serializing_if = "Option::is_none")] - pub comment: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub matching_strategy: Option, -} - -impl From for IdWithIdentifier { - fn from(value: IdWithIdentifierAndComment) -> Self { - Self { - kind: value.kind, - id: value.id.clone(), - matching_strategy: value.matching_strategy, - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn a_rule_that_is_an_object_is_simple() { - let rule: MatchingRule = serde_json::from_str( - r#"{ "kind": "Exe", "id": "foot", "matching_strategy": "Equals" }"#, - ) - .expect("parses"); - - assert_eq!( - rule, - MatchingRule::Simple(IdWithIdentifier { - kind: ApplicationIdentifier::Exe, - id: "foot".to_string(), - matching_strategy: Some(MatchingStrategy::Equals), - }) - ); - } - - #[test] - fn a_rule_that_is_a_list_is_composite() { - let rule: MatchingRule = serde_json::from_str( - r#"[{ "kind": "Exe", "id": "foot" }, { "kind": "Title", "id": "scratch", "matching_strategy": "StartsWith" }]"#, - ) - .expect("parses"); - - let MatchingRule::Composite(parts) = rule else { - panic!("a list of objects is a composite rule"); - }; - assert_eq!(parts.len(), 2); - assert_eq!( - parts[1].matching_strategy, - Some(MatchingStrategy::StartsWith) - ); - } - - #[test] - fn the_matching_strategy_is_left_out_when_there_is_none() { - let rule = IdWithIdentifier { - kind: ApplicationIdentifier::Class, - id: "firefox".to_string(), - matching_strategy: None, - }; - - let json = serde_json::to_string(&rule).expect("serializes"); - - assert_eq!(json, r#"{"kind":"Class","id":"firefox"}"#); - } - - #[test] - fn a_commented_rule_becomes_a_plain_one() { - let commented: IdWithIdentifierAndComment = serde_json::from_str( - r#"{ "kind": "Path", "id": "/usr/bin/kcalc", "comment": "a calculator" }"#, - ) - .expect("parses"); - - let plain = IdWithIdentifier::from(commented); - - assert_eq!(plain.kind, ApplicationIdentifier::Path); - assert_eq!(plain.id, "/usr/bin/kcalc"); - assert_eq!(plain.matching_strategy, None); - } -} +pub use komorebi_config::matching::IdWithIdentifier; +pub use komorebi_config::matching::IdWithIdentifierAndComment; +pub use komorebi_config::matching::MatchingRule; +pub use komorebi_config::matching::MatchingStrategy; +pub use komorebi_config::matching::WorkspaceMatchingRule; diff --git a/komorebi-for-kde/komorebi/src/core/mod.rs b/komorebi-for-kde/komorebi/src/core/mod.rs index c561f36c..f805c546 100644 --- a/komorebi-for-kde/komorebi/src/core/mod.rs +++ b/komorebi-for-kde/komorebi/src/core/mod.rs @@ -12,11 +12,8 @@ //! [`OperationDirection`] is a side of the focused tile, and a [`CycleDirection`] the next or the //! previous container in the order of the workspace. -use clap::ValueEnum; use serde::Deserialize; use serde::Serialize; -use strum::Display; -use strum::EnumString; // Re-export types from komorebi-layouts pub use komorebi_layouts::Arrangement; @@ -45,6 +42,15 @@ pub use komorebi_layouts::validate_ratios; pub mod animation; pub mod asc; pub mod config_generation; +pub use komorebi_config::behaviour::CrossBoundaryBehaviour; +pub use komorebi_config::behaviour::FloatingLayerBehaviour; +pub use komorebi_config::behaviour::Placement; +pub use komorebi_config::behaviour::WindowContainerBehaviour; +pub use komorebi_config::behaviour::WindowHidingPosition; +pub use komorebi_config::placement::InitialWindowPlacementRules; +pub use komorebi_config::placement::PlacementMatchingRules; +pub use komorebi_config::placement::PlacementTarget; +pub use komorebi_config::placement::WindowPlacement; pub use komorebi_protocol::pathext; pub use komorebi_protocol::types::ApplicationIdentifier; pub use komorebi_protocol::types::FocusFollowsMouseImplementation; @@ -80,307 +86,6 @@ pub struct WindowManagementBehaviour { pub float_rule_placement: Placement, } -#[derive( - Clone, Copy, Debug, Default, Serialize, Deserialize, Display, EnumString, ValueEnum, PartialEq, -)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Window container behavior when a new window is opened -pub enum WindowContainerBehaviour { - /// Create a new container for each new window - #[default] - Create, - /// Append new windows to the focused window container - Append, -} - -#[derive( - Clone, Copy, Debug, Default, Serialize, Deserialize, Display, EnumString, ValueEnum, PartialEq, -)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Floating layer behavior when a new window is opened -pub enum FloatingLayerBehaviour { - /// Tile new windows (unless they match a float rule or float override is active) - #[default] - Tile, - /// Float new windows - Float, -} - -#[derive( - Clone, Copy, Debug, Default, Serialize, Deserialize, Display, EnumString, ValueEnum, PartialEq, -)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Window hiding position -pub enum WindowHidingPosition { - /// Hide windows in the bottom left corner of the screen - #[default] - BottomLeft, - /// Hide windows in the bottom right corner of the screen - BottomRight, -} - -#[derive( - Clone, Copy, Debug, Default, Serialize, Deserialize, Display, EnumString, ValueEnum, PartialEq, -)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Placement behavior for floating windows -pub enum Placement { - /// Does not change the size or position of the window - #[default] - None, - /// Center the window without changing the size - Center, - /// Center the window and resize it according to the `AspectRatio` - CenterAndResize, -} - -impl FloatingLayerBehaviour { - pub fn should_float(&self) -> bool { - match self { - FloatingLayerBehaviour::Tile => false, - FloatingLayerBehaviour::Float => true, - } - } -} - -impl Placement { - pub fn should_center(&self) -> bool { - match self { - Placement::None => false, - Placement::Center | Placement::CenterAndResize => true, - } - } - - pub fn should_resize(&self) -> bool { - match self { - Placement::None | Placement::Center => false, - Placement::CenterAndResize => true, - } - } -} - -#[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, Serialize, Deserialize, Display, EnumString, ValueEnum, PartialEq, -)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Behavior when an action would cross a monitor boundary -pub enum CrossBoundaryBehaviour { - /// Attempt to perform actions across a workspace boundary - Workspace, - /// Attempt to perform actions across a monitor boundary - #[default] - Monitor, -} - pub use komorebi_protocol::message::SocketMessage; #[cfg(test)] diff --git a/komorebi-for-kde/komorebi/src/main.rs b/komorebi-for-kde/komorebi/src/main.rs index 4546f748..95db7759 100644 --- a/komorebi-for-kde/komorebi/src/main.rs +++ b/komorebi-for-kde/komorebi/src/main.rs @@ -48,6 +48,7 @@ use komorebi::monitor_reconciliator; use komorebi::process_command::listen_for_commands; use komorebi::process_event::listen_for_events; use komorebi::static_config::StaticConfig; +use komorebi::static_config::StaticConfigExt; use komorebi::window_manager::WindowManager; use komorebi::window_manager_event_listener; use komorebi_hotkeys::Format; diff --git a/komorebi-for-kde/komorebi/src/process_command.rs b/komorebi-for-kde/komorebi/src/process_command.rs index f0e6092f..6ab7abce 100644 --- a/komorebi-for-kde/komorebi/src/process_command.rs +++ b/komorebi-for-kde/komorebi/src/process_command.rs @@ -260,6 +260,7 @@ use crate::notify_subscribers; use crate::state::GlobalState; use crate::state::State; use crate::static_config::StaticConfig; +use crate::static_config::StaticConfigExt; use crate::theme_manager; use crate::transparency_manager; use crate::window::RuleDebug; @@ -1852,10 +1853,10 @@ impl WindowManager { SocketMessage::ApplicationSpecificConfigurationSchema => { #[cfg(feature = "schemars")] { - let asc = schemars::schema_for!( - Vec - ); - let schema = serde_json::to_string_pretty(&asc)?; + let schema = komorebi_config::schema::view::< + Vec, + >(komorebi_config::schema::Platform::CURRENT); + let schema = schema.trim_end(); reply.write_all(schema.as_bytes())?; } @@ -1881,8 +1882,10 @@ impl WindowManager { SocketMessage::StaticConfigSchema => { #[cfg(feature = "schemars")] { - let static_config = schemars::schema_for!(StaticConfig); - let schema = serde_json::to_string_pretty(&static_config)?; + let schema = komorebi_config::schema::view::< + komorebi_config::static_config::StaticConfig, + >(komorebi_config::schema::Platform::CURRENT); + let schema = schema.trim_end(); reply.write_all(schema.as_bytes())?; } diff --git a/komorebi-for-kde/komorebi/src/static_config.rs b/komorebi-for-kde/komorebi/src/static_config.rs index 3dab9fb3..92658913 100644 --- a/komorebi-for-kde/komorebi/src/static_config.rs +++ b/komorebi-for-kde/komorebi/src/static_config.rs @@ -49,31 +49,20 @@ use crate::animation::DEFAULT_ANIMATION_FPS; use crate::animation::PerAnimationPrefixConfig; use crate::backend::backend; use crate::border_manager; -use crate::core::Axis; 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; -use crate::core::MonocleFocusBehaviour; use crate::core::MoveBehaviour; use crate::core::OperationBehaviour; use crate::core::Placement; use crate::core::Rect; use crate::core::SocketMessage; use crate::core::WindowContainerBehaviour; -use crate::core::WindowHidingPosition; use crate::core::WindowManagementBehaviour; -use crate::core::animation::AnimationStyle; use crate::core::asc::ApplicationSpecificConfiguration; use crate::core::asc::AscApplicationRulesOrSchema; use crate::core::config_generation::MatchingRule; use crate::core::config_generation::MatchingStrategy; use crate::core::config_generation::WorkspaceMatchingRule; -use crate::core::pathext::ResolvedPathBuf; use crate::monitor; use crate::monitor::Monitor; use crate::monitor_reconciliator; @@ -89,12 +78,9 @@ use color_eyre::eyre; use crossbeam_channel::Receiver; use hotwatch::EventKind; use hotwatch::Hotwatch; -use komorebi_themes::KomorebiTheme; use komorebi_themes::colour::Colour; use parking_lot::Mutex; use regex::Regex; -use serde::Deserialize; -use serde::Serialize; use std::collections::HashMap; use std::io::ErrorKind; use std::io::Write; @@ -104,177 +90,15 @@ use std::path::PathBuf; use std::sync::Arc; use std::sync::atomic::Ordering; -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Border colours for different container states -/// -/// These options will have no effect if a `theme` is set -pub struct BorderColours { - /// Border colour when the container contains a single window - #[serde(skip_serializing_if = "Option::is_none")] - pub single: Option, - /// Border colour when the container contains multiple windows - #[serde(skip_serializing_if = "Option::is_none")] - pub stack: Option, - /// Border colour when the container is in monocle mode - #[serde(skip_serializing_if = "Option::is_none")] - pub monocle: Option, - /// Border colour when the container is in floating mode - #[serde(skip_serializing_if = "Option::is_none")] - pub floating: Option, - /// Border colour when the container is unfocused - #[serde(skip_serializing_if = "Option::is_none")] - pub unfocused: Option, - /// Border colour when the container is unfocused and locked - #[serde(skip_serializing_if = "Option::is_none")] - pub unfocused_locked: Option, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Theme options -pub struct ThemeOptions { - /// Specify Light or Dark variant for theme generation - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::ThemeVariant::Dark)))] - pub theme_variant: Option, - /// Border color when the container contains a single window - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::Base16Value::Base0D)))] - pub single_border: Option, - /// Border color when the container contains multiple windows - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::Base16Value::Base0B)))] - pub stack_border: Option, - /// Border color when the container is in monocle mode - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::Base16Value::Base0F)))] - pub monocle_border: Option, - /// Border color when the window is floating - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::Base16Value::Base09)))] - pub floating_border: Option, - /// Border color when the container is unfocused - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::Base16Value::Base01)))] - pub unfocused_border: Option, - /// Border color when the container is unfocused and locked - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::Base16Value::Base08)))] - pub unfocused_locked_border: Option, - // /// Stackbar focused tab text colour (default: Base0B) - // #[serde(skip_serializing_if = "Option::is_none")] - // pub stackbar_focused_text: Option, - // /// Stackbar unfocused tab text colour (default: Base05) - // #[serde(skip_serializing_if = "Option::is_none")] - // pub stackbar_unfocused_text: Option, - // /// Stackbar tab background colour (default: Base01) - // #[serde(skip_serializing_if = "Option::is_none")] - // pub stackbar_background: Option, - /// Komorebi status bar accent - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::Base16Value::Base0D)))] - pub bar_accent: Option, -} - -#[serde_with::serde_as] -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Wallpaper configuration -pub struct Wallpaper { - /// Path to the wallpaper image file - #[serde_as(as = "ResolvedPathBuf")] - pub path: PathBuf, - /// Generate and apply Base16 theme for this wallpaper - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = true)))] - pub generate_theme: Option, - /// Specify theme options - #[serde(skip_serializing_if = "Option::is_none")] - pub theme_options: Option, -} - // serde_as must be before derive -#[serde_with::serde_as] -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Workspace configuration -pub struct WorkspaceConfig { - /// Name - pub name: String, - /// Layout - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = DefaultLayout::BSP)))] - pub layout: Option, - /// Layout-specific options - #[serde(skip_serializing_if = "Option::is_none")] - pub layout_options: Option, - /// Threshold-based layout options rules in the format of threshold => options. - /// When container count >= threshold, the highest matching threshold's options - /// fully replace the base `layout_options`. - /// This follows the same threshold logic as `layout_rules`. - #[serde(skip_serializing_if = "Option::is_none")] - pub layout_options_rules: Option>, - // /// END OF LIFE FEATURE: Custom Layout (default: None) - // #[serde(skip_serializing_if = "Option::is_none")] - // #[serde_as(as = "Option")] - // pub custom_layout: Option, - /// Layout rules in the format of threshold => layout - #[serde(skip_serializing_if = "Option::is_none")] - pub layout_rules: Option>, - /// Container padding (default: global) - #[serde(skip_serializing_if = "Option::is_none")] - pub container_padding: Option, - /// Workspace padding (default: global) - #[serde(skip_serializing_if = "Option::is_none")] - pub workspace_padding: Option, - /// Initial workspace application rules - #[serde(skip_serializing_if = "Option::is_none")] - pub initial_workspace_rules: Option>, - /// Permanent workspace application rules - #[serde(skip_serializing_if = "Option::is_none")] - pub workspace_rules: Option>, - /// Work area offset rules in the format of threshold => Rect (default: None) - #[serde(skip_serializing_if = "Option::is_none")] - pub work_area_offset_rules: Option>, - /// Workspace specific work area offset - #[serde(skip_serializing_if = "Option::is_none")] - pub work_area_offset: Option, - /// Apply this monitor's window-based work area offset - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = true)))] - pub apply_window_based_work_area_offset: Option, - /// Determine what happens when a new window is opened - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = WindowContainerBehaviour::Create)))] - pub window_container_behaviour: Option, - /// Window container behavior rules in the format of threshold => behavior - #[serde(skip_serializing_if = "Option::is_none")] - pub window_container_behaviour_rules: Option>, - /// Enable or disable float override, which makes it so every new window opens in floating mode - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = false)))] - pub float_override: Option, - /// Enable or disable tiling for the workspace - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = true)))] - pub tile: Option, - /// Specify an axis on which to flip the selected layout - #[serde(skip_serializing_if = "Option::is_none")] - pub layout_flip: Option, - /// Determine what happens to a new window when the Floating workspace layer is active - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = FloatingLayerBehaviour::Tile)))] - pub floating_layer_behaviour: Option, - /// 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, -} +pub use komorebi_config::static_config::AnimationsConfig; +pub use komorebi_config::static_config::AppSpecificConfigurationPath; +pub use komorebi_config::static_config::BorderColours; +pub use komorebi_config::static_config::MonitorConfig; +pub use komorebi_config::static_config::StaticConfig; +pub use komorebi_config::static_config::ThemeOptions; +pub use komorebi_config::static_config::Wallpaper; +pub use komorebi_config::static_config::WorkspaceConfig; impl From<&Workspace> for WorkspaceConfig { fn from(value: &Workspace) -> Self { @@ -374,45 +198,12 @@ impl From<&Workspace> for WorkspaceConfig { floating_layer_behaviour: value.floating_layer_behaviour, wallpaper: None, initial_window_placement_rules: value.initial_window_placement_rules.clone(), + custom_layout: None, + custom_layout_rules: None, } } } -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Monitor configuration -pub struct MonitorConfig { - /// Workspace configurations - pub workspaces: Vec, - /// Monitor-specific work area offset - #[serde(skip_serializing_if = "Option::is_none")] - pub work_area_offset: Option, - /// Window based work area offset - #[serde(skip_serializing_if = "Option::is_none")] - pub window_based_work_area_offset: Option, - /// Open window limit after which the window based work area offset will no longer be applied - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = 1)))] - pub window_based_work_area_offset_limit: Option, - /// Container padding - #[serde(skip_serializing_if = "Option::is_none")] - pub container_padding: Option, - /// Workspace padding (default: global) - #[serde(skip_serializing_if = "Option::is_none")] - pub workspace_padding: Option, - /// Specify a wallpaper for this monitor - #[serde(skip_serializing_if = "Option::is_none")] - pub wallpaper: Option, - /// Determine what happens to a new window when the Floating workspace layer is active - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = FloatingLayerBehaviour::Tile)))] - pub floating_layer_behaviour: Option, - /// Accepted so that a configuration written for another platform loads, and ignored: there is - /// no hiding position on KDE Plasma - #[serde(skip_serializing_if = "Option::is_none")] - pub window_hiding_position: Option, -} - impl From<&Monitor> for MonitorConfig { fn from(value: &Monitor) -> Self { let mut workspaces = vec![]; @@ -453,229 +244,6 @@ 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))] -/// The `komorebi.json` static configuration file reference for komorebi for KDE Plasma -pub struct StaticConfig { - // /// DISCOURAGED: Minimum width for a window to be eligible for tiling - // #[serde(skip_serializing_if = "Option::is_none")] - // pub minimum_window_width: Option, - // /// DISCOURAGED: Minimum height for a window to be eligible for tiling - // #[serde(skip_serializing_if = "Option::is_none")] - // pub minimum_window_height: Option, - /// Delta to resize windows by - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = DEFAULT_RESIZE_DELTA)))] - pub resize_delta: Option, - /// Determine what happens when a new window is opened - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = WindowContainerBehaviour::Create)))] - pub window_container_behaviour: Option, - /// Enable or disable float override, which makes it so every new window opens in floating mode - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = false)))] - pub float_override: Option, - /// Determines what happens on a new window when on the `FloatingLayer` - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = FloatingLayerBehaviour::Tile)))] - pub floating_layer_behaviour: Option, - /// Determines the placement of a new window when toggling to float - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = Placement::CenterAndResize)))] - pub toggle_float_placement: Option, - /// Determines the `Placement` to be used when spawning a window on the floating layer with the - /// `FloatingLayerBehaviour` set to `FloatingLayerBehaviour::Float` - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = Placement::Center)))] - pub floating_layer_placement: Option, - /// Determines the `Placement` to be used when spawning a window with float override active - #[serde(skip_serializing_if = "Option::is_none")] - pub float_override_placement: Option, - /// Determines the `Placement` to be used when spawning a window that matches a - /// 'floating_applications' rule - #[serde(skip_serializing_if = "Option::is_none")] - pub float_rule_placement: Option, - /// Determine what happens when a window is moved across a monitor boundary - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = MoveBehaviour::Swap)))] - pub cross_monitor_move_behaviour: Option, - /// Determine what happens when an action is called on a window at a monitor boundary - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = CrossBoundaryBehaviour::Monitor)))] - pub cross_boundary_behaviour: Option, - /// Determine what happens when focusing in a direction while a monocle container is active - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = MonocleFocusBehaviour::NoOp)))] - pub monocle_focus_behaviour: Option, - /// Determine what happens when commands are sent while an unmanaged window is in the foreground - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = OperationBehaviour::Op)))] - pub unmanaged_window_operation_behaviour: Option, - /// Focus the window under the pointer. On KDE this is KWin's own focus policy, whichever - /// implementation is named - #[serde(skip_serializing_if = "Option::is_none")] - pub focus_follows_mouse: Option, - /// Enable or disable mouse follows focus - #[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, - /// Width of window borders - #[serde(skip_serializing_if = "Option::is_none")] - #[serde(alias = "active_window_border_width")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = border_manager::BORDER_WIDTH)))] - pub border_width: Option, - /// Offset of window borders - #[serde(skip_serializing_if = "Option::is_none")] - #[serde(alias = "active_window_border_offset")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = border_manager::BORDER_OFFSET)))] - pub border_offset: Option, - /// Radius of window borders - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = border_manager::BORDER_RADIUS)))] - pub border_radius: Option, - /// Display window borders - #[serde(skip_serializing_if = "Option::is_none")] - #[serde(alias = "active_window_border")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = border_manager::BORDER_ENABLED)))] - pub border: Option, - /// Window border colours for different container types (has no effect if a theme is defined) - #[serde(skip_serializing_if = "Option::is_none")] - #[serde(alias = "active_window_border_colours")] - pub border_colours: Option, - // /// Active window border style (default: System) - // #[serde(skip_serializing_if = "Option::is_none")] - // #[serde(alias = "active_window_border_style")] - // pub border_style: Option, - // /// Active window border implementation (default: Komorebi) - // #[serde(skip_serializing_if = "Option::is_none")] - // pub border_implementation: Option, - /// Add transparency to unfocused windows (default: false) - #[serde(skip_serializing_if = "Option::is_none")] - pub transparency: Option, - /// Alpha value for unfocused window transparency [[0-255]] (default: 200) - #[serde(skip_serializing_if = "Option::is_none")] - pub transparency_alpha: Option, - /// Individual window transparency ignore rules - #[serde(skip_serializing_if = "Option::is_none")] - pub transparency_ignore_rules: Option>, - /// Global default workspace padding - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = DEFAULT_WORKSPACE_PADDING)))] - pub default_workspace_padding: Option, - /// Global default container padding - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = DEFAULT_CONTAINER_PADDING)))] - pub default_container_padding: Option, - /// Per-layout default options and rules, keyed by layout name. - /// Applied as fallback when a workspace does not define its own layout_options or layout_options_rules. - /// If a workspace defines either setting, all global defaults for that layout are completely replaced. - #[serde(skip_serializing_if = "Option::is_none")] - pub layout_defaults: Option>, - /// Monitor and workspace configurations - #[serde(skip_serializing_if = "Option::is_none")] - pub monitors: Option>, - // /// Which Windows signal to use when hiding windows (default: Cloak) - // #[serde(skip_serializing_if = "Option::is_none")] - // pub window_hiding_behaviour: Option, - /// Global work area (space used for tiling) offset - #[serde(skip_serializing_if = "Option::is_none")] - pub global_work_area_offset: Option, - /// Individual window floating rules - #[serde(skip_serializing_if = "Option::is_none")] - #[serde(alias = "float_rules")] - pub ignore_rules: Option>, - /// Individual window force-manage rules - #[serde(skip_serializing_if = "Option::is_none")] - pub manage_rules: Option>, - /// Identify applications which should be managed as floating windows - #[serde(skip_serializing_if = "Option::is_none")] - pub floating_applications: Option>, - /// Accepted so that a configuration written for another platform loads, and ignored: a KWin - /// window is always a window - #[serde(skip_serializing_if = "Option::is_none")] - pub titleless_applications: Option>, - /// Accepted so that a configuration written for another platform loads, and ignored: a KWin - /// window has no native tabs - #[serde(skip_serializing_if = "Option::is_none")] - pub tabbed_applications: Option>, - // /// Identify border overflow applications - // #[serde(skip_serializing_if = "Option::is_none")] - // pub border_overflow_applications: Option>, - // /// Identify tray and multi-window applications - // #[serde(skip_serializing_if = "Option::is_none")] - // pub tray_and_multi_window_applications: Option>, - // /// Identify applications that have the WS_EX_LAYERED extended window style - // #[serde(skip_serializing_if = "Option::is_none")] - // pub layered_applications: Option>, - // /// Identify applications that send EVENT_OBJECT_NAMECHANGE on launch (very rare) - // #[serde(skip_serializing_if = "Option::is_none")] - // pub object_name_change_applications: Option>, - // /// Do not process EVENT_OBJECT_NAMECHANGE events as Show events for identified applications matching these title regexes - // #[serde(skip_serializing_if = "Option::is_none")] - // pub object_name_change_title_ignore_list: Option>, - // /// Set monitor index preferences - // #[serde(skip_serializing_if = "Option::is_none")] - // pub monitor_index_preferences: Option>, - /// Set display index preferences - #[serde(skip_serializing_if = "Option::is_none")] - pub display_index_preferences: Option>, - // /// Stackbar configuration options - // #[serde(skip_serializing_if = "Option::is_none")] - // pub stackbar: Option, - /// Animations configuration options - #[serde(skip_serializing_if = "Option::is_none")] - pub animation: Option, - /// Theme configuration options - /// - /// If a theme is specified, `border_colours` will have no effect - #[serde(skip_serializing_if = "Option::is_none")] - pub theme: Option, - /// Aspect ratio to resize with when toggling floating mode for a window - #[serde(skip_serializing_if = "Option::is_none")] - pub floating_window_aspect_ratio: Option, - // /// Which Windows API behaviour to use when manipulating windows (default: Sync) - // #[serde(skip_serializing_if = "Option::is_none")] - // pub window_handling_behaviour: Option, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Animation configuration -pub struct AnimationsConfig { - /// Enable or disable animations - #[cfg_attr(feature = "schemars", schemars(extend("default" = PerAnimationPrefixConfig::Global(false))))] - pub enabled: PerAnimationPrefixConfig, - /// Set the animation duration in ms - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = PerAnimationPrefixConfig::Global(250))))] - pub duration: Option>, - /// Set the animation style - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = PerAnimationPrefixConfig::Global(AnimationStyle::Linear))))] - pub style: Option>, - /// Set the animation FPS - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = DEFAULT_ANIMATION_FPS)))] - pub fps: Option, -} - // #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] // #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] // pub struct TabsConfig { @@ -831,11 +399,17 @@ impl From<&WindowManager> for StaticConfig { floating_window_aspect_ratio: Option::from(*FLOATING_WINDOW_TOGGLE_ASPECT_RATIO.lock()), // window_handling_behaviour: Option::from(WINDOW_HANDLING_BEHAVIOUR.load()), tabbed_applications: None, + ..Default::default() } } } -impl StaticConfig { +/// Applies the settings of a configuration that are not the window manager's own +trait ApplyGlobals { + fn apply_globals(&mut self) -> eyre::Result<()>; +} + +impl ApplyGlobals for StaticConfig { #[allow(clippy::cognitive_complexity, clippy::too_many_lines)] fn apply_globals(&mut self) -> eyre::Result<()> { *FLOATING_WINDOW_TOGGLE_ASPECT_RATIO.lock() = self @@ -1142,47 +716,26 @@ impl StaticConfig { Ok(()) } +} - /// Parses the text of a `komorebi.json` - /// - /// Comments and trailing commas are allowed, and keys that are not known are ignored. - /// - /// # Errors - /// - /// The text is not JSON, or a value is not what its key takes. - /// - /// # Example - /// - /// ```rust - /// use komorebi::static_config::StaticConfig; - /// - /// let config = StaticConfig::read_raw( - /// r#"{ - /// // a comment, and a trailing comma - /// "resize_delta": 100, - /// "a_key_that_is_not_known": true, - /// }"#, - /// )?; - /// assert_eq!(config.resize_delta, Some(100)); - /// - /// assert!(StaticConfig::read_raw(r#"{ "resize_delta": "wide" }"#).is_err()); - /// - /// # Ok::<(), Box>(()) - /// ``` - pub fn read_raw(raw: &str) -> eyre::Result { - Ok(serde_json::from_str(raw)?) - } +/// What loading a configuration needs from the window manager: the part of `StaticConfig` +/// that cannot be an inherent impl now that the type lives in `komorebi-config`. +pub trait StaticConfigExt: Sized { + /// Makes the window manager from the file at `path`, and starts watching the file + fn preload( + path: &PathBuf, + incoming: Receiver, + unix_listener: Option, + ) -> eyre::Result; - /// Reads the file at `path`, as [`StaticConfig::read_raw`] reads text - /// - /// # Errors - /// - /// The file cannot be read, or it is not a configuration. - pub fn read(path: &PathBuf) -> eyre::Result { - let content = std::fs::read_to_string(path)?; - serde_json::from_str(&content).map_err(Into::into) - } + /// Gives the monitors of the window manager what the file says about them + fn postload(path: &PathBuf, wm: &Arc>) -> eyre::Result<()>; + /// Replaces the configuration of the window manager with the file at `path` + fn reload(path: &PathBuf, wm: &mut WindowManager) -> eyre::Result<()>; +} + +impl StaticConfigExt for StaticConfig { /// Makes the window manager from the file at `path`, and starts watching the file /// /// The settings that are not the window manager's own (the default padding, the rules and the @@ -1201,7 +754,7 @@ impl StaticConfig { /// - The socket file that is left over cannot be removed, or the socket cannot be bound. /// - The file cannot be watched. #[allow(clippy::too_many_lines)] - pub fn preload( + fn preload( path: &PathBuf, incoming: Receiver, unix_listener: Option, @@ -1307,7 +860,7 @@ impl StaticConfig { /// # Errors /// /// The file cannot be read or is not a configuration ([`StaticConfig::read`]). - pub fn postload(path: &PathBuf, wm: &Arc>) -> eyre::Result<()> { + fn postload(path: &PathBuf, wm: &Arc>) -> eyre::Result<()> { let mut value = Self::read(path)?; let mut wm = wm.lock(); @@ -1483,7 +1036,7 @@ impl StaticConfig { /// - The file cannot be read or is not a configuration ([`StaticConfig::read`]); nothing has /// changed then. /// - A rule has a regular expression that is not valid; the settings before it have changed. - pub fn reload(path: &PathBuf, wm: &mut WindowManager) -> eyre::Result<()> { + fn reload(path: &PathBuf, wm: &mut WindowManager) -> eyre::Result<()> { let mut value = Self::read(path)?; value.apply_globals()?; @@ -1784,6 +1337,7 @@ fn handle_asc_file( #[cfg(test)] mod tests { use super::*; + use crate::core::WindowHidingPosition; #[test] fn the_keys_that_do_nothing_on_kde_are_accepted_and_ignored() { diff --git a/komorebi-for-kde/komorebi/src/window.rs b/komorebi-for-kde/komorebi/src/window.rs index 0cfbe64f..90a55c83 100644 --- a/komorebi-for-kde/komorebi/src/window.rs +++ b/komorebi-for-kde/komorebi/src/window.rs @@ -27,6 +27,8 @@ use crate::REGEX_IDENTIFIERS; use crate::backend::backend; use crate::core::ApplicationIdentifier; use crate::core::Rect; +pub use komorebi_config::aspect_ratio::AspectRatio; +pub use komorebi_config::aspect_ratio::PredefinedAspectRatio; use crate::core::config_generation::IdWithIdentifier; use crate::core::config_generation::MatchingRule; use crate::core::config_generation::MatchingStrategy; @@ -43,8 +45,6 @@ use std::fmt::Display; use std::fmt::Formatter; use std::fmt::Write; use std::path::PathBuf; -use strum::Display; -use strum::EnumString; /// The windows the user is resizing by dragging an edge of: komorebi does not move them while they /// are (the other tiles follow the drag, and the window is put in its tile when they let go) @@ -431,51 +431,6 @@ impl Window { } } -#[derive(Copy, Clone, Debug, Display, EnumString, Serialize, Deserialize, PartialEq)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -#[serde(untagged)] -/// Aspect ratio for temporarily floating windows -pub enum AspectRatio { - /// A predefined aspect ratio - #[cfg_attr(feature = "schemars", schemars(title = "Predefined"))] - Predefined(PredefinedAspectRatio), - /// A custom W:H aspect ratio - #[cfg_attr(feature = "schemars", schemars(title = "Custom"))] - Custom(i32, i32), -} - -impl Default for AspectRatio { - fn default() -> Self { - AspectRatio::Predefined(PredefinedAspectRatio::default()) - } -} - -#[derive(Copy, Clone, Debug, Default, Display, EnumString, Serialize, Deserialize, PartialEq)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Predefined aspect ratio -pub enum PredefinedAspectRatio { - /// 21:9 - Ultrawide, - /// 16:9 - Widescreen, - /// 4:3 - #[default] - Standard, -} - -impl AspectRatio { - pub fn width_and_height(self) -> (i32, i32) { - match self { - AspectRatio::Predefined(predefined) => match predefined { - PredefinedAspectRatio::Ultrawide => (21, 9), - PredefinedAspectRatio::Widescreen => (16, 9), - PredefinedAspectRatio::Standard => (4, 3), - }, - AspectRatio::Custom(w, h) => (w, h), - } - } -} - /// Why [`Window::should_manage`] decided as it did: what it read of the window, and the rule of /// each kind that matched it #[derive(Debug, Default, Serialize, Deserialize)] diff --git a/komorebi-for-kde/komorebi/src/window_manager.rs b/komorebi-for-kde/komorebi/src/window_manager.rs index 3faaf05a..32a1beba 100644 --- a/komorebi-for-kde/komorebi/src/window_manager.rs +++ b/komorebi-for-kde/komorebi/src/window_manager.rs @@ -79,6 +79,7 @@ use crate::lockable_sequence::Lockable; use crate::monitor::Monitor; use crate::ring::Ring; use crate::static_config::StaticConfig; +use crate::static_config::StaticConfigExt; use crate::window::Window; use crate::window::should_act_individual; use crate::window_manager_event::WindowManagerEvent; diff --git a/komorebi-for-kde/komorebi/src/workspace.rs b/komorebi-for-kde/komorebi/src/workspace.rs index cb1dda4c..ca86b6e5 100644 --- a/komorebi-for-kde/komorebi/src/workspace.rs +++ b/komorebi-for-kde/komorebi/src/workspace.rs @@ -2155,6 +2155,9 @@ impl Workspace { unfocused_border: options.and_then(|o| o.unfocused_border), unfocused_locked_border: options.and_then(|o| o.unfocused_locked_border), bar_accent: options.and_then(|o| o.bar_accent), + stackbar_focused_text: None, + stackbar_unfocused_text: None, + stackbar_background: None, })); } } diff --git a/komorebi-for-kde/komorebi/tests/animation_config.rs b/komorebi-for-kde/komorebi/tests/animation_config.rs index ccd37f6a..37825de5 100644 --- a/komorebi-for-kde/komorebi/tests/animation_config.rs +++ b/komorebi-for-kde/komorebi/tests/animation_config.rs @@ -13,6 +13,7 @@ use komorebi::backend::fake::FakeBackend; use komorebi::backend::with_backend; use komorebi::core::animation::AnimationStyle; use komorebi::static_config::StaticConfig; +use komorebi::static_config::StaticConfigExt; use komorebi::window_manager::WindowManager; use parking_lot::Mutex; use std::os::unix::net::UnixListener; diff --git a/komorebi-for-kde/komorebi/tests/asc.rs b/komorebi-for-kde/komorebi/tests/asc.rs index e60fe88e..0ef4e187 100644 --- a/komorebi-for-kde/komorebi/tests/asc.rs +++ b/komorebi-for-kde/komorebi/tests/asc.rs @@ -11,6 +11,7 @@ use komorebi::backend::with_backend; use komorebi::core::asc::ApplicationSpecificConfiguration; use komorebi::core::asc::AscApplicationRulesOrSchema; use komorebi::static_config::StaticConfig; +use komorebi::static_config::StaticConfigExt; use komorebi::window::Window; use komorebi::window_manager::WindowManager; use komorebi::window_manager_event::KWinNotification; diff --git a/komorebi-for-kde/komorebi/tests/border_config.rs b/komorebi-for-kde/komorebi/tests/border_config.rs index 8c86617e..6718be53 100644 --- a/komorebi-for-kde/komorebi/tests/border_config.rs +++ b/komorebi-for-kde/komorebi/tests/border_config.rs @@ -10,6 +10,7 @@ use komorebi::backend::fake::FakeBackend; use komorebi::backend::with_backend; use komorebi::border_manager; use komorebi::static_config::StaticConfig; +use komorebi::static_config::StaticConfigExt; use komorebi::window_manager::WindowManager; use parking_lot::Mutex; use std::os::unix::net::UnixListener; diff --git a/komorebi-for-kde/komorebi/tests/config.rs b/komorebi-for-kde/komorebi/tests/config.rs index 6ebf1672..a031f876 100644 --- a/komorebi-for-kde/komorebi/tests/config.rs +++ b/komorebi-for-kde/komorebi/tests/config.rs @@ -29,6 +29,7 @@ use komorebi::core::Rect; use komorebi::core::SocketMessage; use komorebi::core::WindowContainerBehaviour; use komorebi::static_config::StaticConfig; +use komorebi::static_config::StaticConfigExt; use komorebi::window::Window; use komorebi::window_manager::WindowManager; use komorebi::window_manager_event::KWinNotification; diff --git a/komorebi-for-kde/komorebi/tests/config_displays.rs b/komorebi-for-kde/komorebi/tests/config_displays.rs index 0e058dba..69498218 100644 --- a/komorebi-for-kde/komorebi/tests/config_displays.rs +++ b/komorebi-for-kde/komorebi/tests/config_displays.rs @@ -10,6 +10,7 @@ use komorebi::backend::with_backend; use komorebi::core::Rect; use komorebi::monitor::Monitor; use komorebi::static_config::StaticConfig; +use komorebi::static_config::StaticConfigExt; use parking_lot::Mutex; use std::os::unix::net::UnixListener; use std::path::PathBuf; diff --git a/komorebi-for-kde/komorebi/tests/config_parity.rs b/komorebi-for-kde/komorebi/tests/config_parity.rs index 59c5a10a..dbc7616a 100644 --- a/komorebi-for-kde/komorebi/tests/config_parity.rs +++ b/komorebi-for-kde/komorebi/tests/config_parity.rs @@ -155,7 +155,11 @@ fn fixtures_load_round_trip_and_only_lose_windows_only_keys() { /// The top-level keys `StaticConfig` reads, from its schema fn keys_that_are_read() -> BTreeSet { - let schema = serde_json::to_value(schemars::schema_for!(StaticConfig)).unwrap(); + // the keys of the schema of this platform: the one `StaticConfig` carries every platform's + let schema: Value = serde_json::from_str(&komorebi_config::schema::view::( + komorebi_config::schema::Platform::CURRENT, + )) + .unwrap(); schema["properties"] .as_object() .unwrap() diff --git a/komorebi-for-kde/komorebi/tests/focus_follows_mouse.rs b/komorebi-for-kde/komorebi/tests/focus_follows_mouse.rs index 4e581d74..b448e880 100644 --- a/komorebi-for-kde/komorebi/tests/focus_follows_mouse.rs +++ b/komorebi-for-kde/komorebi/tests/focus_follows_mouse.rs @@ -13,6 +13,7 @@ use komorebi::core::FocusFollowsMouseImplementation; use komorebi::core::SocketMessage; use komorebi::state::State; use komorebi::static_config::StaticConfig; +use komorebi::static_config::StaticConfigExt; use komorebi::window_manager::WindowManager; use parking_lot::Mutex; use std::os::unix::net::UnixListener; diff --git a/komorebi-for-kde/komorebi/tests/replace_configuration.rs b/komorebi-for-kde/komorebi/tests/replace_configuration.rs index 240c4981..a6f34d3f 100644 --- a/komorebi-for-kde/komorebi/tests/replace_configuration.rs +++ b/komorebi-for-kde/komorebi/tests/replace_configuration.rs @@ -10,6 +10,7 @@ use komorebi::core::OperationDirection; use komorebi::core::Rect; use komorebi::core::SocketMessage; use komorebi::static_config::StaticConfig; +use komorebi::static_config::StaticConfigExt; use komorebi::window::Window; use komorebi::window_manager::WindowManager; use komorebi::window_manager_event::KWinNotification; diff --git a/komorebi-for-kde/komorebi/tests/theme_config.rs b/komorebi-for-kde/komorebi/tests/theme_config.rs index c5722710..a7a2c762 100644 --- a/komorebi-for-kde/komorebi/tests/theme_config.rs +++ b/komorebi-for-kde/komorebi/tests/theme_config.rs @@ -11,6 +11,7 @@ use komorebi::backend::fake::FakeBackend; use komorebi::backend::with_backend; use komorebi::border_manager; use komorebi::static_config::StaticConfig; +use komorebi::static_config::StaticConfigExt; use komorebi::window_manager::WindowManager; use komorebi_themes::colour::Colour; use komorebi_themes::colour::Rgb; diff --git a/komorebi-for-kde/komorebi/tests/themes.rs b/komorebi-for-kde/komorebi/tests/themes.rs index bb31dafc..f05c3e4c 100644 --- a/komorebi-for-kde/komorebi/tests/themes.rs +++ b/komorebi-for-kde/komorebi/tests/themes.rs @@ -71,6 +71,9 @@ fn a_named_theme_colours_every_kind_of_border() { floating_border: None, unfocused_border: None, unfocused_locked_border: None, + stackbar_focused_text: None, + stackbar_unfocused_text: None, + stackbar_background: None, }, ))), ); diff --git a/komorebi-for-kde/komorebi/tests/transparency_config.rs b/komorebi-for-kde/komorebi/tests/transparency_config.rs index a45e0092..8d138ee4 100644 --- a/komorebi-for-kde/komorebi/tests/transparency_config.rs +++ b/komorebi-for-kde/komorebi/tests/transparency_config.rs @@ -11,6 +11,7 @@ use komorebi::backend::fake::FakeBackend; use komorebi::backend::with_backend; use komorebi::core::SocketMessage; use komorebi::static_config::StaticConfig; +use komorebi::static_config::StaticConfigExt; use komorebi::transparency_manager; use komorebi::window::Window; use komorebi::window_manager::WindowManager; diff --git a/komorebi-for-kde/komorebi/tests/wallpaper.rs b/komorebi-for-kde/komorebi/tests/wallpaper.rs index fcf915b0..37151fde 100644 --- a/komorebi-for-kde/komorebi/tests/wallpaper.rs +++ b/komorebi-for-kde/komorebi/tests/wallpaper.rs @@ -12,6 +12,7 @@ use komorebi::backend::with_backend; use komorebi::border_manager; use komorebi::core::SocketMessage; use komorebi::static_config::StaticConfig; +use komorebi::static_config::StaticConfigExt; use komorebi::static_config::ThemeOptions; use komorebi::static_config::Wallpaper; use komorebi::theme_manager; @@ -355,6 +356,9 @@ fn theme_options_choose_the_variant_and_the_colour_each_border_takes() { unfocused_border: None, unfocused_locked_border: None, bar_accent: None, + stackbar_focused_text: None, + stackbar_unfocused_text: None, + stackbar_background: None, }; let by_default = focused_with(None); diff --git a/komorebi-for-kde/komorebi/tests/workspace_rules.rs b/komorebi-for-kde/komorebi/tests/workspace_rules.rs index 9b960ad0..5a021db6 100644 --- a/komorebi-for-kde/komorebi/tests/workspace_rules.rs +++ b/komorebi-for-kde/komorebi/tests/workspace_rules.rs @@ -15,6 +15,7 @@ use komorebi::core::ApplicationIdentifier; use komorebi::core::Rect; use komorebi::core::SocketMessage; use komorebi::static_config::StaticConfig; +use komorebi::static_config::StaticConfigExt; use komorebi::window::Window; use komorebi::window_manager::WindowManager; use komorebi::window_manager_event::KWinNotification; diff --git a/komorebi-for-kde/komorebic/Cargo.toml b/komorebi-for-kde/komorebic/Cargo.toml index 42e7789b..11f30bd2 100644 --- a/komorebi-for-kde/komorebic/Cargo.toml +++ b/komorebi-for-kde/komorebic/Cargo.toml @@ -5,6 +5,7 @@ description = "The command-line interface for Komorebi, a tiling window manager edition = "2024" [dependencies] +komorebi-config = { workspace = true } komorebi = { path = "../komorebi", default-features = false } komorebi-client = { path = "../komorebi-client", default-features = false } komorebi-hotkeys = { path = "../komorebi-hotkeys" } diff --git a/komorebi-for-kde/komorebic/src/main.rs b/komorebi-for-kde/komorebic/src/main.rs index 45a2a6a9..6707afbf 100644 --- a/komorebi-for-kde/komorebic/src/main.rs +++ b/komorebi-for-kde/komorebic/src/main.rs @@ -730,10 +730,10 @@ fn main() -> eyre::Result<()> { KdeCommands::ApplicationSpecificConfigurationSchema => { #[cfg(feature = "schemars")] { - let asc = - schemars::schema_for!(komorebi_client::ApplicationSpecificConfiguration); - let schema = serde_json::to_string_pretty(&asc)?; - println!("{schema}"); + let schema = komorebi_config::schema::view::< + komorebi_client::ApplicationSpecificConfiguration, + >(komorebi_config::schema::Platform::CURRENT); + print!("{schema}"); } } KdeCommands::NotificationSchema => { @@ -755,9 +755,10 @@ fn main() -> eyre::Result<()> { KdeCommands::StaticConfigSchema => { #[cfg(feature = "schemars")] { - let socket_message = schemars::schema_for!(komorebi_client::StaticConfig); - let schema = serde_json::to_string_pretty(&socket_message)?; - println!("{schema}"); + let schema = komorebi_config::schema::view::< + komorebi_config::static_config::StaticConfig, + >(komorebi_config::schema::Platform::CURRENT); + print!("{schema}"); } } KdeCommands::GenerateStaticConfig => { diff --git a/komorebi-for-kde/schema.json b/komorebi-for-kde/schema.json index 3c576349..c229f087 100644 --- a/komorebi-for-kde/schema.json +++ b/komorebi-for-kde/schema.json @@ -677,12 +677,12 @@ "anyOf": [ { "title": "Predefined", - "description": "A predefined aspect ratio", + "description": "Predefined aspect ratio", "$ref": "#/$defs/PredefinedAspectRatio" }, { "title": "Custom", - "description": "A custom W:H aspect ratio", + "description": "Custom W:H aspect ratio", "type": "array", "maxItems": 2, "minItems": 2, @@ -2488,7 +2488,7 @@ ] }, "CrossBoundaryBehaviour": { - "description": "Behavior when an action would cross a monitor boundary", + "description": "Behaviour when an action would cross a monitor boundary", "oneOf": [ { "description": "Attempt to perform actions across a workspace boundary", @@ -2553,7 +2553,7 @@ ] }, "FloatingLayerBehaviour": { - "description": "Floating layer behavior when a new window is opened", + "description": "Floating layer behaviour when a new window is opened", "oneOf": [ { "description": "Tile new windows (unless they match a float rule or float override is active)", @@ -3363,7 +3363,7 @@ ] }, "Placement": { - "description": "Placement behavior for floating windows", + "description": "Placement behaviour for floating windows", "oneOf": [ { "description": "Does not change the size or position of the window", @@ -3698,7 +3698,7 @@ ] }, "WindowContainerBehaviour": { - "description": "Window container behavior when a new window is opened", + "description": "Window container behaviour when a new window is opened", "oneOf": [ { "description": "Create a new container for each new window", @@ -3746,7 +3746,7 @@ "const": "BeforeFocused" }, { - "description": "Place the new window after the currently focused container (default behavior)", + "description": "Place the new window after the currently focused container (default behaviour)", "type": "string", "const": "AfterFocused" }, diff --git a/komorebi-for-mac/Cargo.lock b/komorebi-for-mac/Cargo.lock index c4854fe5..9e3aaf02 100644 --- a/komorebi-for-mac/Cargo.lock +++ b/komorebi-for-mac/Cargo.lock @@ -3166,6 +3166,7 @@ dependencies = [ "ed25519-dalek", "hotwatch", "komorebi-collections", + "komorebi-config", "komorebi-layouts", "komorebi-protocol", "komorebi-themes", @@ -3256,6 +3257,22 @@ dependencies = [ "serde", ] +[[package]] +name = "komorebi-config" +version = "0.1.42" +dependencies = [ + "clap", + "color-eyre", + "komorebi-layouts", + "komorebi-protocol", + "komorebi-themes", + "schemars 1.2.3", + "serde", + "serde_json_lenient", + "serde_with", + "strum", +] + [[package]] name = "komorebi-layouts" version = "0.1.42" @@ -3328,6 +3345,7 @@ dependencies = [ "dirs 6.0.0", "fs-tail", "komorebi-client", + "komorebi-config", "komorebic-core", "lazy_static", "reqwest", diff --git a/komorebi-for-mac/Cargo.toml b/komorebi-for-mac/Cargo.toml index d2b727fa..2951bd0d 100644 --- a/komorebi-for-mac/Cargo.toml +++ b/komorebi-for-mac/Cargo.toml @@ -15,6 +15,7 @@ version = "0.1.0" [workspace.dependencies] komorebi-themes = { path = "../komorebi-themes" } komorebi-collections = { path = "../crates/komorebi-collections" } +komorebi-config = { path = "../crates/komorebi-config", default-features = false, features = ["schemars"] } komorebi-protocol = { path = "../crates/komorebi-protocol", default-features = false, features = ["schemars"] } komorebi-transport = { path = "../crates/komorebi-transport" } komorebi-layouts = { path = "../komorebi-layouts", features = [ diff --git a/komorebi-for-mac/komorebi/Cargo.toml b/komorebi-for-mac/komorebi/Cargo.toml index a45a718b..04c7badc 100644 --- a/komorebi-for-mac/komorebi/Cargo.toml +++ b/komorebi-for-mac/komorebi/Cargo.toml @@ -8,6 +8,7 @@ edition = "2024" komorebi-themes = { workspace = true } komorebi-collections = { workspace = true } komorebi-layouts = { workspace = true } +komorebi-config = { workspace = true } komorebi-protocol = { workspace = true } komorebi-transport = { workspace = true } quickxml_to_serde = { git = "https://github.com/LGUG2Z/quickxml_to_serde.git", version = "0.6.1" } diff --git a/komorebi-for-mac/komorebi/src/animation/mod.rs b/komorebi-for-mac/komorebi/src/animation/mod.rs index 74f0b0b4..1213a6d6 100644 --- a/komorebi-for-mac/komorebi/src/animation/mod.rs +++ b/komorebi-for-mac/komorebi/src/animation/mod.rs @@ -2,6 +2,7 @@ use crate::core::animation::AnimationStyle; use parking_lot::Mutex; pub use prefix::AnimationPrefix; +pub use komorebi_config::animation::PerAnimationPrefixConfig; use std::collections::HashMap; use std::sync::Arc; use std::sync::LazyLock; @@ -25,41 +26,6 @@ pub mod tracks; pub mod transition; pub mod workspace_transition; -use serde::Deserialize; -use serde::Serialize; - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -#[serde(untagged)] -/// Animation configuration -/// -/// This can be either global: -/// ```json -/// { -/// "enabled": true, -/// "style": "EaseInSine", -/// "fps": 60, -/// "duration": 250 -/// } -/// ``` -/// -/// Or scoped by an animation kind prefix: -/// ```json -/// { -/// "movement": { -/// "enabled": true, -/// "style": "EaseInSine", -/// "fps": 60, -/// "duration": 250 -/// } -/// } -/// ``` -pub enum PerAnimationPrefixConfig { - /// Animation configuration prefixed for a specific animation kind - Prefix(HashMap), - /// Animation configuration for all animation kinds - Global(T), -} pub const DEFAULT_ANIMATION_ENABLED: bool = false; pub const DEFAULT_ANIMATION_STYLE: AnimationStyle = AnimationStyle::Linear; diff --git a/komorebi-for-mac/komorebi/src/core/asc.rs b/komorebi-for-mac/komorebi/src/core/asc.rs index 2141685d..f11db2f6 100644 --- a/komorebi-for-mac/komorebi/src/core/asc.rs +++ b/komorebi-for-mac/komorebi/src/core/asc.rs @@ -1,66 +1,7 @@ -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; +//! The application specific configuration file (`app_specific_configuration_path`). +//! +//! The types are defined in `komorebi-config`. -#[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>, -} +pub use komorebi_config::asc::ApplicationSpecificConfiguration; +pub use komorebi_config::asc::AscApplicationRules; +pub use komorebi_config::asc::AscApplicationRulesOrSchema; diff --git a/komorebi-for-mac/komorebi/src/core/config_generation.rs b/komorebi-for-mac/komorebi/src/core/config_generation.rs index 1cf9b43b..03abb7ce 100644 --- a/komorebi-for-mac/komorebi/src/core/config_generation.rs +++ b/komorebi-for-mac/komorebi/src/core/config_generation.rs @@ -1,90 +1,9 @@ -use serde::Deserialize; -use serde::Serialize; -use strum::Display; +//! Rules that match an application by how it identifies itself. +//! +//! The types are defined in `komorebi-config`, which `komorebi.json` is read with. -use super::ApplicationIdentifier; - -#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -#[serde(untagged)] -/// Rule for matching applications -pub enum MatchingRule { - /// Simple matching rule which must evaluate to true - Simple(IdWithIdentifier), - /// Composite matching rule where all conditions must evaluate to true - Composite(Vec), -} - -#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Rule for assigning applications to a workspace -pub struct WorkspaceMatchingRule { - /// Target monitor index - pub monitor_index: usize, - /// Target workspace index - pub workspace_index: usize, - /// Matching rule for the application - pub matching_rule: MatchingRule, - /// Whether to apply the rule only when the application is initially launched - pub initial_only: bool, -} - -#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Rule for matching applications -pub struct IdWithIdentifier { - /// Kind of identifier to target - pub kind: ApplicationIdentifier, - /// Target identifier - pub id: String, - #[serde(skip_serializing_if = "Option::is_none")] - /// Matching strategy to use - pub matching_strategy: Option, -} - -#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Display)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Strategy for matching identifiers -pub enum MatchingStrategy { - /// Should not be used, only kept for backward compatibility - Legacy, - /// Equals - Equals, - /// Starts With - StartsWith, - /// Ends With - EndsWith, - /// Contains - Contains, - /// Regex - Regex, - /// Does not end with - DoesNotEndWith, - /// Does not start with - DoesNotStartWith, - /// Does not equal - DoesNotEqual, - /// Does not contain - DoesNotContain, -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -pub struct IdWithIdentifierAndComment { - pub kind: ApplicationIdentifier, - pub id: String, - #[serde(skip_serializing_if = "Option::is_none")] - pub comment: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub matching_strategy: Option, -} - -impl From for IdWithIdentifier { - fn from(value: IdWithIdentifierAndComment) -> Self { - Self { - kind: value.kind, - id: value.id.clone(), - matching_strategy: value.matching_strategy, - } - } -} +pub use komorebi_config::matching::IdWithIdentifier; +pub use komorebi_config::matching::IdWithIdentifierAndComment; +pub use komorebi_config::matching::MatchingRule; +pub use komorebi_config::matching::MatchingStrategy; +pub use komorebi_config::matching::WorkspaceMatchingRule; diff --git a/komorebi-for-mac/komorebi/src/core/mod.rs b/komorebi-for-mac/komorebi/src/core/mod.rs index b97aeb17..2e51b8bd 100644 --- a/komorebi-for-mac/komorebi/src/core/mod.rs +++ b/komorebi-for-mac/komorebi/src/core/mod.rs @@ -1,8 +1,5 @@ -use clap::ValueEnum; use serde::Deserialize; use serde::Serialize; -use strum::Display; -use strum::EnumString; // Re-export types from komorebi-layouts pub use komorebi_layouts::Arrangement; @@ -32,6 +29,11 @@ pub use komorebi_layouts::validate_ratios; pub mod animation; pub mod asc; pub mod config_generation; +pub use komorebi_config::behaviour::CrossBoundaryBehaviour; +pub use komorebi_config::behaviour::FloatingLayerBehaviour; +pub use komorebi_config::behaviour::Placement; +pub use komorebi_config::behaviour::WindowContainerBehaviour; +pub use komorebi_config::behaviour::WindowHidingPosition; pub use komorebi_protocol::pathext; pub use komorebi_protocol::types::ApplicationIdentifier; pub use komorebi_protocol::types::MonocleFocusBehaviour; @@ -67,98 +69,6 @@ pub struct WindowManagementBehaviour { pub float_rule_placement: Placement, } -#[derive( - Clone, Copy, Debug, Default, Serialize, Deserialize, Display, EnumString, ValueEnum, PartialEq, -)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Window container behaviour when a new window is opened -pub enum WindowContainerBehaviour { - /// Create a new container for each new window - #[default] - Create, - /// Append new windows to the focused window container - Append, -} - -#[derive( - Clone, Copy, Debug, Default, Serialize, Deserialize, Display, EnumString, ValueEnum, PartialEq, -)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Floating layer behaviour when a new window is opened -pub enum FloatingLayerBehaviour { - /// Tile new windows (unless they match a float rule or float override is active) - #[default] - Tile, - /// Float new windows - Float, -} - -#[derive( - Clone, Copy, Debug, Default, Serialize, Deserialize, Display, EnumString, ValueEnum, PartialEq, -)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Window hiding position -pub enum WindowHidingPosition { - /// Hide windows in the bottom left corner of the screen - #[default] - BottomLeft, - /// Hide windows in the bottom right corner of the screen - BottomRight, -} - -#[derive( - Clone, Copy, Debug, Default, Serialize, Deserialize, Display, EnumString, ValueEnum, PartialEq, -)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Placement behaviour for floating windows -pub enum Placement { - /// Does not change the size or position of the window - #[default] - None, - /// Center the window without changing the size - Center, - /// Center the window and resize it according to the `AspectRatio` - CenterAndResize, -} - -impl FloatingLayerBehaviour { - pub fn should_float(&self) -> bool { - match self { - FloatingLayerBehaviour::Tile => false, - FloatingLayerBehaviour::Float => true, - } - } -} - -impl Placement { - pub fn should_center(&self) -> bool { - match self { - Placement::None => false, - Placement::Center | Placement::CenterAndResize => true, - } - } - - pub fn should_resize(&self) -> bool { - match self { - Placement::None | Placement::Center => false, - Placement::CenterAndResize => true, - } - } -} - -#[derive( - Clone, Copy, Debug, Default, Serialize, Deserialize, Display, EnumString, ValueEnum, PartialEq, -)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Behaviour when an action would cross a monitor boundary -pub enum CrossBoundaryBehaviour { - /// Attempt to perform actions across a workspace boundary - Workspace, - /// Attempt to perform actions across a monitor boundary - #[default] - Monitor, -} - pub use komorebi_protocol::message::SocketMessage; #[cfg(test)] diff --git a/komorebi-for-mac/komorebi/src/main.rs b/komorebi-for-mac/komorebi/src/main.rs index a967e2e1..85137d52 100644 --- a/komorebi-for-mac/komorebi/src/main.rs +++ b/komorebi-for-mac/komorebi/src/main.rs @@ -19,6 +19,7 @@ use komorebi::process_event::listen_for_events; use komorebi::reaper; use komorebi::settle; use komorebi::static_config::StaticConfig; +use komorebi::static_config::StaticConfigExt; use komorebi::theme_manager; use komorebi::window_manager::WindowManager; use komorebi::window_manager_event_listener; diff --git a/komorebi-for-mac/komorebi/src/process_command.rs b/komorebi-for-mac/komorebi/src/process_command.rs index cbb03fb3..276d9ada 100644 --- a/komorebi-for-mac/komorebi/src/process_command.rs +++ b/komorebi-for-mac/komorebi/src/process_command.rs @@ -46,6 +46,7 @@ use crate::notify_subscribers; use crate::state::GlobalState; use crate::state::State; use crate::static_config::StaticConfig; +use crate::static_config::StaticConfigExt; use crate::theme_manager; use crate::window::AdhocWindow; use crate::window::RuleDebug; @@ -1593,10 +1594,10 @@ impl WindowManager { SocketMessage::ApplicationSpecificConfigurationSchema => { #[cfg(feature = "schemars")] { - let asc = schemars::schema_for!( - Vec - ); - let schema = serde_json::to_string_pretty(&asc)?; + let schema = komorebi_config::schema::view::< + Vec, + >(komorebi_config::schema::Platform::CURRENT); + let schema = schema.trim_end(); reply.write_all(schema.as_bytes())?; } @@ -1622,8 +1623,10 @@ impl WindowManager { SocketMessage::StaticConfigSchema => { #[cfg(feature = "schemars")] { - let static_config = schemars::schema_for!(StaticConfig); - let schema = serde_json::to_string_pretty(&static_config)?; + let schema = komorebi_config::schema::view::< + komorebi_config::static_config::StaticConfig, + >(komorebi_config::schema::Platform::CURRENT); + let schema = schema.trim_end(); reply.write_all(schema.as_bytes())?; } diff --git a/komorebi-for-mac/komorebi/src/static_config.rs b/komorebi-for-mac/komorebi/src/static_config.rs index 206145d1..5fe68137 100644 --- a/komorebi-for-mac/komorebi/src/static_config.rs +++ b/komorebi-for-mac/komorebi/src/static_config.rs @@ -25,29 +25,20 @@ use crate::animation::DEFAULT_ANIMATION_FPS; use crate::animation::PerAnimationPrefixConfig; use crate::border_manager; use crate::core::ApplicationIdentifier; -use crate::core::Axis; use crate::core::CrossBoundaryBehaviour; -use crate::core::DefaultLayout; -use crate::core::FloatingLayerBehaviour; use crate::core::Layout; -use crate::core::LayoutDefaultEntry; -use crate::core::LayoutOptions; -use crate::core::MonocleFocusBehaviour; use crate::core::MoveBehaviour; use crate::core::OperationBehaviour; use crate::core::Placement; use crate::core::Rect; use crate::core::SocketMessage; use crate::core::WindowContainerBehaviour; -use crate::core::WindowHidingPosition; use crate::core::WindowManagementBehaviour; -use crate::core::animation::AnimationStyle; use crate::core::asc::ApplicationSpecificConfiguration; use crate::core::asc::AscApplicationRulesOrSchema; use crate::core::config_generation::MatchingRule; use crate::core::config_generation::MatchingStrategy; use crate::core::config_generation::WorkspaceMatchingRule; -use crate::core::pathext::ResolvedPathBuf; use crate::current_space_id; use crate::monitor; use crate::monitor::Monitor; @@ -63,14 +54,11 @@ use color_eyre::eyre; use crossbeam_channel::Receiver; use hotwatch::EventKind; use hotwatch::Hotwatch; -use komorebi_themes::KomorebiTheme; use komorebi_themes::colour::Colour; use objc2_core_foundation::CFRetained; use objc2_core_foundation::CFRunLoop; use parking_lot::Mutex; use regex::Regex; -use serde::Deserialize; -use serde::Serialize; use std::collections::HashMap; use std::io::ErrorKind; use std::io::Write; @@ -80,172 +68,15 @@ use std::path::PathBuf; use std::sync::Arc; use std::sync::atomic::Ordering; -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Border colours for different container states -/// -/// These options will have no effect if a `theme` is set -pub struct BorderColours { - /// Border colour when the container contains a single window - #[serde(skip_serializing_if = "Option::is_none")] - pub single: Option, - /// Border colour when the container contains multiple windows - #[serde(skip_serializing_if = "Option::is_none")] - pub stack: Option, - /// Border colour when the container is in monocle mode - #[serde(skip_serializing_if = "Option::is_none")] - pub monocle: Option, - /// Border colour when the container is in floating mode - #[serde(skip_serializing_if = "Option::is_none")] - pub floating: Option, - /// Border colour when the container is unfocused - #[serde(skip_serializing_if = "Option::is_none")] - pub unfocused: Option, - /// Border colour when the container is unfocused and locked - #[serde(skip_serializing_if = "Option::is_none")] - pub unfocused_locked: Option, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Theme options -pub struct ThemeOptions { - /// Specify Light or Dark variant for theme generation - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::ThemeVariant::Dark)))] - pub theme_variant: Option, - /// Border colour when the container contains a single window - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::Base16Value::Base0D)))] - pub single_border: Option, - /// Border colour when the container contains multiple windows - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::Base16Value::Base0B)))] - pub stack_border: Option, - /// Border colour when the container is in monocle mode - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::Base16Value::Base0F)))] - pub monocle_border: Option, - /// Border colour when the window is floating - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::Base16Value::Base09)))] - pub floating_border: Option, - /// Border colour when the container is unfocused - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::Base16Value::Base01)))] - pub unfocused_border: Option, - /// Border colour when the container is unfocused and locked - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::Base16Value::Base08)))] - pub unfocused_locked_border: Option, - // /// Stackbar focused tab text colour (default: Base0B) - // #[serde(skip_serializing_if = "Option::is_none")] - // pub stackbar_focused_text: Option, - // /// Stackbar unfocused tab text colour (default: Base05) - // #[serde(skip_serializing_if = "Option::is_none")] - // pub stackbar_unfocused_text: Option, - // /// Stackbar tab background colour (default: Base01) - // #[serde(skip_serializing_if = "Option::is_none")] - // pub stackbar_background: Option, - /// Komorebi status bar accent - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::Base16Value::Base0D)))] - pub bar_accent: Option, -} - -#[serde_with::serde_as] -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Wallpaper configuration -pub struct Wallpaper { - /// Path to the wallpaper image file - #[serde_as(as = "ResolvedPathBuf")] - pub path: PathBuf, - /// Generate and apply Base16 theme for this wallpaper - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = true)))] - pub generate_theme: Option, - /// Specify theme options - #[serde(skip_serializing_if = "Option::is_none")] - pub theme_options: Option, -} - // serde_as must be before derive -#[serde_with::serde_as] -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Workspace configuration -pub struct WorkspaceConfig { - /// Name - pub name: String, - /// Layout - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = DefaultLayout::BSP)))] - pub layout: Option, - /// Layout-specific options - #[serde(skip_serializing_if = "Option::is_none")] - pub layout_options: Option, - /// Threshold-based layout options rules in the format of threshold => options. - /// When container count >= threshold, the highest matching threshold's options - /// fully replace the base `layout_options`. - /// This follows the same threshold logic as `layout_rules`. - #[serde(skip_serializing_if = "Option::is_none")] - pub layout_options_rules: Option>, - // /// END OF LIFE FEATURE: Custom Layout (default: None) - // #[serde(skip_serializing_if = "Option::is_none")] - // #[serde_as(as = "Option")] - // pub custom_layout: Option, - /// Layout rules in the format of threshold => layout - #[serde(skip_serializing_if = "Option::is_none")] - pub layout_rules: Option>, - /// Container padding (default: global) - #[serde(skip_serializing_if = "Option::is_none")] - pub container_padding: Option, - /// Workspace padding (default: global) - #[serde(skip_serializing_if = "Option::is_none")] - pub workspace_padding: Option, - /// Initial workspace application rules - #[serde(skip_serializing_if = "Option::is_none")] - pub initial_workspace_rules: Option>, - /// Permanent workspace application rules - #[serde(skip_serializing_if = "Option::is_none")] - pub workspace_rules: Option>, - /// Work area offset rules in the format of threshold => Rect (default: None) - #[serde(skip_serializing_if = "Option::is_none")] - pub work_area_offset_rules: Option>, - /// Workspace specific work area offset - #[serde(skip_serializing_if = "Option::is_none")] - pub work_area_offset: Option, - /// Apply this monitor's window-based work area offset - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = true)))] - pub apply_window_based_work_area_offset: Option, - /// Determine what happens when a new window is opened - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = WindowContainerBehaviour::Create)))] - pub window_container_behaviour: Option, - /// Window container behaviour rules in the format of threshold => behaviour - #[serde(skip_serializing_if = "Option::is_none")] - pub window_container_behaviour_rules: Option>, - /// Enable or disable float override, which makes it so every new window opens in floating mode - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = false)))] - pub float_override: Option, - /// Enable or disable tiling for the workspace - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = true)))] - pub tile: Option, - /// Specify an axis on which to flip the selected layout - #[serde(skip_serializing_if = "Option::is_none")] - pub layout_flip: Option, - /// Determine what happens to a new window when the Floating workspace layer is active - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = FloatingLayerBehaviour::Tile)))] - pub floating_layer_behaviour: Option, - /// Specify a wallpaper for this workspace - #[serde(skip_serializing_if = "Option::is_none")] - pub wallpaper: Option, -} +pub use komorebi_config::static_config::AnimationsConfig; +pub use komorebi_config::static_config::AppSpecificConfigurationPath; +pub use komorebi_config::static_config::BorderColours; +pub use komorebi_config::static_config::MonitorConfig; +pub use komorebi_config::static_config::StaticConfig; +pub use komorebi_config::static_config::ThemeOptions; +pub use komorebi_config::static_config::Wallpaper; +pub use komorebi_config::static_config::WorkspaceConfig; impl From<&Workspace> for WorkspaceConfig { fn from(value: &Workspace) -> Self { @@ -344,44 +175,13 @@ impl From<&Workspace> for WorkspaceConfig { layout_flip: value.layout_flip, floating_layer_behaviour: value.floating_layer_behaviour, wallpaper: None, + custom_layout: None, + custom_layout_rules: None, + initial_window_placement_rules: None, } } } -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Monitor configuration -pub struct MonitorConfig { - /// Workspace configurations - pub workspaces: Vec, - /// Monitor-specific work area offset - #[serde(skip_serializing_if = "Option::is_none")] - pub work_area_offset: Option, - /// Window based work area offset - #[serde(skip_serializing_if = "Option::is_none")] - pub window_based_work_area_offset: Option, - /// Open window limit after which the window based work area offset will no longer be applied - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = 1)))] - pub window_based_work_area_offset_limit: Option, - /// Container padding - #[serde(skip_serializing_if = "Option::is_none")] - pub container_padding: Option, - /// Workspace padding (default: global) - #[serde(skip_serializing_if = "Option::is_none")] - pub workspace_padding: Option, - /// Specify a wallpaper for this monitor - #[serde(skip_serializing_if = "Option::is_none")] - pub wallpaper: Option, - /// Determine what happens to a new window when the Floating workspace layer is active - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = FloatingLayerBehaviour::Tile)))] - pub floating_layer_behaviour: Option, - /// Determine which position windows should be hidden at on this monitor - #[serde(skip_serializing_if = "Option::is_none")] - pub window_hiding_position: Option, -} - impl From<&Monitor> for MonitorConfig { fn from(value: &Monitor) -> Self { let mut workspaces = vec![]; @@ -422,238 +222,6 @@ 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))] -/// The `komorebi.json` static configuration file reference for komorebi for Mac `v0.1.0` -/// -/// `"$schema": "https://komorebi-for-mac.lgug2z.com/komorebi.0.1.0.schema.json"` -pub struct StaticConfig { - // /// DISCOURAGED: Minimum width for a window to be eligible for tiling - // #[serde(skip_serializing_if = "Option::is_none")] - // pub minimum_window_width: Option, - // /// DISCOURAGED: Minimum height for a window to be eligible for tiling - // #[serde(skip_serializing_if = "Option::is_none")] - // pub minimum_window_height: Option, - /// Delta to resize windows by - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = DEFAULT_RESIZE_DELTA)))] - pub resize_delta: Option, - /// Determine what happens when a new window is opened - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = WindowContainerBehaviour::Create)))] - pub window_container_behaviour: Option, - /// Enable or disable float override, which makes it so every new window opens in floating mode - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = false)))] - pub float_override: Option, - /// Determines what happens on a new window when on the `FloatingLayer` - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = FloatingLayerBehaviour::Tile)))] - pub floating_layer_behaviour: Option, - /// Determines the placement of a new window when toggling to float - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = Placement::CenterAndResize)))] - pub toggle_float_placement: Option, - /// Determines the `Placement` to be used when spawning a window on the floating layer with the - /// `FloatingLayerBehaviour` set to `FloatingLayerBehaviour::Float` - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = Placement::Center)))] - pub floating_layer_placement: Option, - /// Determines the `Placement` to be used when spawning a window with float override active - #[serde(skip_serializing_if = "Option::is_none")] - pub float_override_placement: Option, - /// Determines the `Placement` to be used when spawning a window that matches a - /// 'floating_applications' rule - #[serde(skip_serializing_if = "Option::is_none")] - pub float_rule_placement: Option, - /// Determine what happens when a window is moved across a monitor boundary - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = MoveBehaviour::Swap)))] - pub cross_monitor_move_behaviour: Option, - /// Determine what happens when an action is called on a window at a monitor boundary - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = CrossBoundaryBehaviour::Monitor)))] - pub cross_boundary_behaviour: Option, - /// Determine what happens when focusing in a direction while a monocle container is active - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = MonocleFocusBehaviour::NoOp)))] - pub monocle_focus_behaviour: Option, - /// Determine what happens when commands are sent while an unmanaged window is in the foreground - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = OperationBehaviour::Op)))] - pub unmanaged_window_operation_behaviour: Option, - /// Enable or disable mouse follows focus - #[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 applications.json from komorebi-application-specific-configurations - #[serde(skip_serializing_if = "Option::is_none")] - pub app_specific_configuration_path: Option, - /// Width of window borders - #[serde(skip_serializing_if = "Option::is_none")] - #[serde(alias = "active_window_border_width")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = border_manager::BORDER_WIDTH)))] - pub border_width: Option, - /// Offset of window borders - #[serde(skip_serializing_if = "Option::is_none")] - #[serde(alias = "active_window_border_offset")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = border_manager::BORDER_OFFSET)))] - pub border_offset: Option, - /// Radius of window borders - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = border_manager::BORDER_RADIUS)))] - pub border_radius: Option, - /// Display window borders - #[serde(skip_serializing_if = "Option::is_none")] - #[serde(alias = "active_window_border")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = border_manager::BORDER_ENABLED)))] - pub border: Option, - /// Window border colours for different container types (has no effect if a theme is defined) - #[serde(skip_serializing_if = "Option::is_none")] - #[serde(alias = "active_window_border_colours")] - pub border_colours: Option, - // /// Active window border style (default: System) - // #[serde(skip_serializing_if = "Option::is_none")] - // #[serde(alias = "active_window_border_style")] - // pub border_style: Option, - // /// Active window border implementation (default: Komorebi) - // #[serde(skip_serializing_if = "Option::is_none")] - // pub border_implementation: Option, - // /// Add transparency to unfocused windows (default: false) - // #[serde(skip_serializing_if = "Option::is_none")] - // pub transparency: Option, - // /// Alpha value for unfocused window transparency [[0-255]] (default: 200) - // #[serde(skip_serializing_if = "Option::is_none")] - // pub transparency_alpha: Option, - // /// Individual window transparency ignore rules - // #[serde(skip_serializing_if = "Option::is_none")] - // pub transparency_ignore_rules: Option>, - /// Global default workspace padding - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = DEFAULT_WORKSPACE_PADDING)))] - pub default_workspace_padding: Option, - /// Global default container padding - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = DEFAULT_CONTAINER_PADDING)))] - pub default_container_padding: Option, - /// Per-layout default options and rules, keyed by layout name. - /// Applied as fallback when a workspace does not define its own layout_options or layout_options_rules. - /// If a workspace defines either setting, all global defaults for that layout are completely replaced. - #[serde(skip_serializing_if = "Option::is_none")] - pub layout_defaults: Option>, - /// Monitor and workspace configurations - #[serde(skip_serializing_if = "Option::is_none")] - pub monitors: Option>, - // /// Which Windows signal to use when hiding windows (default: Cloak) - // #[serde(skip_serializing_if = "Option::is_none")] - // pub window_hiding_behaviour: Option, - /// Global work area (space used for tiling) offset - #[serde(skip_serializing_if = "Option::is_none")] - pub global_work_area_offset: Option, - /// Individual window floating rules - #[serde(skip_serializing_if = "Option::is_none")] - #[serde(alias = "float_rules")] - pub ignore_rules: Option>, - /// Individual window force-manage rules - #[serde(skip_serializing_if = "Option::is_none")] - pub manage_rules: Option>, - /// Identify applications which should be managed as floating windows - #[serde(skip_serializing_if = "Option::is_none")] - pub floating_applications: Option>, - /// Identify applications which should be managed despite not reporting titles to the system - #[serde(skip_serializing_if = "Option::is_none")] - pub titleless_applications: Option>, - /// Identify applications which use native tabs for special handling - #[serde(skip_serializing_if = "Option::is_none")] - pub tabbed_applications: Option>, - // /// Identify border overflow applications - // #[serde(skip_serializing_if = "Option::is_none")] - // pub border_overflow_applications: Option>, - // /// Identify tray and multi-window applications - // #[serde(skip_serializing_if = "Option::is_none")] - // pub tray_and_multi_window_applications: Option>, - // /// Identify applications that have the WS_EX_LAYERED extended window style - // #[serde(skip_serializing_if = "Option::is_none")] - // pub layered_applications: Option>, - // /// Identify applications that send EVENT_OBJECT_NAMECHANGE on launch (very rare) - // #[serde(skip_serializing_if = "Option::is_none")] - // pub object_name_change_applications: Option>, - // /// Do not process EVENT_OBJECT_NAMECHANGE events as Show events for identified applications matching these title regexes - // #[serde(skip_serializing_if = "Option::is_none")] - // pub object_name_change_title_ignore_list: Option>, - // /// Set monitor index preferences - // #[serde(skip_serializing_if = "Option::is_none")] - // pub monitor_index_preferences: Option>, - /// Set display index preferences - #[serde(skip_serializing_if = "Option::is_none")] - pub display_index_preferences: Option>, - // /// Stackbar configuration options - // #[serde(skip_serializing_if = "Option::is_none")] - // pub stackbar: Option, - /// Animations configuration options - #[serde(skip_serializing_if = "Option::is_none")] - pub animation: Option, - /// Theme configuration options - /// - /// If a theme is specified, `border_colours` will have no effect - #[serde(skip_serializing_if = "Option::is_none")] - pub theme: Option, - /// Identify applications which are slow to send initial event notifications - // #[serde(skip_serializing_if = "Option::is_none")] - // pub slow_application_identifiers: Option>, - // /// How long to wait when compensating for slow applications, in milliseconds (default: 20) - // #[serde(skip_serializing_if = "Option::is_none")] - // pub slow_application_compensation_time: Option, - // /// Komorebi status bar configuration files for multiple instances on different monitors - // // this option is a little special because it is only consumed by komorebic - // #[serde(skip_serializing_if = "Option::is_none")] - // #[serde_as(as = "Option>")] - // pub bar_configurations: Option>, - // /// HEAVILY DISCOURAGED: Identify applications for which komorebi should forcibly remove title bars - // #[serde(skip_serializing_if = "Option::is_none")] - // pub remove_titlebar_applications: Option>, - /// Aspect ratio to resize with when toggling floating mode for a window - #[serde(skip_serializing_if = "Option::is_none")] - pub floating_window_aspect_ratio: Option, - // /// Which Windows API behaviour to use when manipulating windows (default: Sync) - // #[serde(skip_serializing_if = "Option::is_none")] - // pub window_handling_behaviour: Option, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Animation configuration -pub struct AnimationsConfig { - /// Enable or disable animations - #[cfg_attr(feature = "schemars", schemars(extend("default" = PerAnimationPrefixConfig::Global(false))))] - pub enabled: PerAnimationPrefixConfig, - /// Set the animation duration in ms - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = PerAnimationPrefixConfig::Global(250))))] - pub duration: Option>, - /// Set the animation style - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = PerAnimationPrefixConfig::Global(AnimationStyle::Linear))))] - pub style: Option>, - /// Set the animation FPS - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = DEFAULT_ANIMATION_FPS)))] - pub fps: Option, -} - // #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] // #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] // pub struct TabsConfig { @@ -809,11 +377,17 @@ impl From<&WindowManager> for StaticConfig { floating_window_aspect_ratio: Option::from(*FLOATING_WINDOW_TOGGLE_ASPECT_RATIO.lock()), // window_handling_behaviour: Option::from(WINDOW_HANDLING_BEHAVIOUR.load()), tabbed_applications: None, + ..Default::default() } } } -impl StaticConfig { +/// Applies the settings of a configuration that are not the window manager's own +trait ApplyGlobals { + fn apply_globals(&mut self) -> eyre::Result<()>; +} + +impl ApplyGlobals for StaticConfig { #[allow(clippy::cognitive_complexity, clippy::too_many_lines)] fn apply_globals(&mut self) -> eyre::Result<()> { *FLOATING_WINDOW_TOGGLE_ASPECT_RATIO.lock() = self @@ -1133,18 +707,29 @@ impl StaticConfig { Ok(()) } +} - pub fn read_raw(raw: &str) -> eyre::Result { - Ok(serde_json::from_str(raw)?) - } +/// What loading a configuration needs from the window manager: the part of `StaticConfig` +/// that cannot be an inherent impl now that the type lives in `komorebi-config`. +pub trait StaticConfigExt: Sized { + /// Makes the window manager from the file at `path`, and starts watching the file + fn preload( + path: &PathBuf, + incoming: Receiver, + unix_listener: Option, + run_loop: &CFRetained, + ) -> eyre::Result; - pub fn read(path: &PathBuf) -> eyre::Result { - let content = std::fs::read_to_string(path)?; - serde_json::from_str(&content).map_err(Into::into) - } + /// Gives the monitors of the window manager what the file says about them + fn postload(path: &PathBuf, wm: &Arc>) -> eyre::Result<()>; + /// Replaces the configuration of the window manager with the file at `path` + fn reload(path: &PathBuf, wm: &mut WindowManager) -> eyre::Result<()>; +} + +impl StaticConfigExt for StaticConfig { #[allow(clippy::too_many_lines)] - pub fn preload( + fn preload( path: &PathBuf, incoming: Receiver, unix_listener: Option, @@ -1243,7 +828,7 @@ impl StaticConfig { Ok(wm) } - pub fn postload(path: &PathBuf, wm: &Arc>) -> eyre::Result<()> { + fn postload(path: &PathBuf, wm: &Arc>) -> eyre::Result<()> { let mut value = Self::read(path)?; let mut wm = wm.lock(); @@ -1405,7 +990,7 @@ impl StaticConfig { Ok(()) } - pub fn reload(path: &PathBuf, wm: &mut WindowManager) -> eyre::Result<()> { + fn reload(path: &PathBuf, wm: &mut WindowManager) -> eyre::Result<()> { let mut value = Self::read(path)?; value.apply_globals()?; diff --git a/komorebi-for-mac/komorebi/src/window.rs b/komorebi-for-mac/komorebi/src/window.rs index 008f6006..90e80ad2 100644 --- a/komorebi-for-mac/komorebi/src/window.rs +++ b/komorebi-for-mac/komorebi/src/window.rs @@ -42,6 +42,8 @@ use crate::arrival; use crate::cf_dictionary_value; use crate::core::ApplicationIdentifier; use crate::core::Rect; +pub use komorebi_config::aspect_ratio::AspectRatio; +pub use komorebi_config::aspect_ratio::PredefinedAspectRatio; use crate::core::WindowHidingPosition; use crate::core::config_generation::IdWithIdentifier; use crate::core::config_generation::MatchingRule; @@ -98,8 +100,6 @@ use std::ptr::NonNull; use std::str::FromStr; use std::sync::atomic::AtomicU32; use std::sync::atomic::Ordering; -use strum::Display; -use strum::EnumString; use tracing::instrument; /// Where a window that has scrolled out of view was parked @@ -1592,51 +1592,6 @@ impl From<&CFDictionary> for WindowBounds { } } -#[derive(Copy, Clone, Debug, Display, EnumString, Serialize, Deserialize, PartialEq)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -#[serde(untagged)] -/// Aspect ratio for temporarily floating windows -pub enum AspectRatio { - /// A predefined aspect ratio - #[cfg_attr(feature = "schemars", schemars(title = "Predefined"))] - Predefined(PredefinedAspectRatio), - /// A custom W:H aspect ratio - #[cfg_attr(feature = "schemars", schemars(title = "Custom"))] - Custom(i32, i32), -} - -impl Default for AspectRatio { - fn default() -> Self { - AspectRatio::Predefined(PredefinedAspectRatio::default()) - } -} - -#[derive(Copy, Clone, Debug, Default, Display, EnumString, Serialize, Deserialize, PartialEq)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Predefined aspect ratio -pub enum PredefinedAspectRatio { - /// 21:9 - Ultrawide, - /// 16:9 - Widescreen, - /// 4:3 - #[default] - Standard, -} - -impl AspectRatio { - pub fn width_and_height(self) -> (i32, i32) { - match self { - AspectRatio::Predefined(predefined) => match predefined { - PredefinedAspectRatio::Ultrawide => (21, 9), - PredefinedAspectRatio::Widescreen => (16, 9), - PredefinedAspectRatio::Standard => (4, 3), - }, - AspectRatio::Custom(w, h) => (w, h), - } - } -} - #[derive(Debug, Default, Serialize, Deserialize)] pub struct RuleDebug { pub should_manage: bool, diff --git a/komorebi-for-mac/komorebi/src/window_manager.rs b/komorebi-for-mac/komorebi/src/window_manager.rs index b4442bab..3bd9cd3a 100644 --- a/komorebi-for-mac/komorebi/src/window_manager.rs +++ b/komorebi-for-mac/komorebi/src/window_manager.rs @@ -44,6 +44,7 @@ use crate::ring::Ring; use crate::settle; use crate::skylight::BatchedUpdates; use crate::static_config::StaticConfig; +use crate::static_config::StaticConfigExt; use crate::window::AdhocWindow; use crate::window::Snapping; use crate::window::Window; diff --git a/komorebi-for-mac/komorebi/src/workspace.rs b/komorebi-for-mac/komorebi/src/workspace.rs index 55dab6cf..042eb7b9 100644 --- a/komorebi-for-mac/komorebi/src/workspace.rs +++ b/komorebi-for-mac/komorebi/src/workspace.rs @@ -1647,6 +1647,9 @@ impl Workspace { .as_ref() .and_then(|o| o.unfocused_locked_border), bar_accent: wallpaper.theme_options.as_ref().and_then(|o| o.bar_accent), + stackbar_focused_text: None, + stackbar_unfocused_text: None, + stackbar_background: None, }); let bytes = SocketMessage::Theme(Box::new(komorebi_theme)).as_bytes()?; diff --git a/komorebi-for-mac/komorebic/Cargo.toml b/komorebi-for-mac/komorebic/Cargo.toml index bfd934bc..20043ba4 100644 --- a/komorebi-for-mac/komorebic/Cargo.toml +++ b/komorebi-for-mac/komorebic/Cargo.toml @@ -5,6 +5,7 @@ description = "The command-line interface for Komorebi, a tiling window manager edition = "2024" [dependencies] +komorebi-config = { workspace = true } komorebi-client = { path = "../komorebi-client", default-features = false } komorebic-core = { path = "../../crates/komorebic-core" } version = { path = "../version" } diff --git a/komorebi-for-mac/komorebic/src/main.rs b/komorebi-for-mac/komorebic/src/main.rs index ac9ee063..9be53800 100644 --- a/komorebi-for-mac/komorebic/src/main.rs +++ b/komorebi-for-mac/komorebic/src/main.rs @@ -766,10 +766,10 @@ exit 1 MacosCommands::ApplicationSpecificConfigurationSchema => { #[cfg(feature = "schemars")] { - let asc = - schemars::schema_for!(komorebi_client::ApplicationSpecificConfiguration); - let schema = serde_json::to_string_pretty(&asc)?; - println!("{schema}"); + let schema = komorebi_config::schema::view::< + komorebi_client::ApplicationSpecificConfiguration, + >(komorebi_config::schema::Platform::CURRENT); + print!("{schema}"); } } MacosCommands::NotificationSchema => { @@ -791,9 +791,10 @@ exit 1 MacosCommands::StaticConfigSchema => { #[cfg(feature = "schemars")] { - let socket_message = schemars::schema_for!(komorebi_client::StaticConfig); - let schema = serde_json::to_string_pretty(&socket_message)?; - println!("{schema}"); + let schema = komorebi_config::schema::view::< + komorebi_config::static_config::StaticConfig, + >(komorebi_config::schema::Platform::CURRENT); + print!("{schema}"); } } MacosCommands::GenerateStaticConfig => { diff --git a/komorebi-for-mac/schema.json b/komorebi-for-mac/schema.json index 2f8ecfca..e86315f9 100644 --- a/komorebi-for-mac/schema.json +++ b/komorebi-for-mac/schema.json @@ -639,12 +639,12 @@ "anyOf": [ { "title": "Predefined", - "description": "A predefined aspect ratio", + "description": "Predefined aspect ratio", "$ref": "#/$defs/PredefinedAspectRatio" }, { "title": "Custom", - "description": "A custom W:H aspect ratio", + "description": "Custom W:H aspect ratio", "type": "array", "maxItems": 2, "minItems": 2, diff --git a/komorebi-themes/src/lib.rs b/komorebi-themes/src/lib.rs index ce3c278a..a0e509d9 100644 --- a/komorebi-themes/src/lib.rs +++ b/komorebi-themes/src/lib.rs @@ -460,17 +460,14 @@ pub struct KomorebiThemeCatppuccin { #[serde(skip_serializing_if = "Option::is_none")] #[cfg_attr(feature = "schemars", schemars(extend("default" = CatppuccinValue::Red)))] pub unfocused_locked_border: Option, - #[cfg(target_os = "windows")] /// Stackbar focused text colour #[serde(skip_serializing_if = "Option::is_none")] #[cfg_attr(feature = "schemars", schemars(extend("default" = CatppuccinValue::Green)))] pub stackbar_focused_text: Option, - #[cfg(target_os = "windows")] /// Stackbar unfocused text colour #[serde(skip_serializing_if = "Option::is_none")] #[cfg_attr(feature = "schemars", schemars(extend("default" = CatppuccinValue::Text)))] pub stackbar_unfocused_text: Option, - #[cfg(target_os = "windows")] /// Stackbar background colour #[serde(skip_serializing_if = "Option::is_none")] #[cfg_attr(feature = "schemars", schemars(extend("default" = CatppuccinValue::Base)))] @@ -511,17 +508,14 @@ pub struct KomorebiThemeBase16 { #[serde(skip_serializing_if = "Option::is_none")] #[cfg_attr(feature = "schemars", schemars(extend("default" = Base16Value::Base08)))] pub unfocused_locked_border: Option, - #[cfg(target_os = "windows")] /// Stackbar focused text colour #[serde(skip_serializing_if = "Option::is_none")] #[cfg_attr(feature = "schemars", schemars(extend("default" = Base16Value::Base0B)))] pub stackbar_focused_text: Option, - #[cfg(target_os = "windows")] /// Stackbar unfocused text colour #[serde(skip_serializing_if = "Option::is_none")] #[cfg_attr(feature = "schemars", schemars(extend("default" = Base16Value::Base05)))] pub stackbar_unfocused_text: Option, - #[cfg(target_os = "windows")] /// Stackbar background colour #[serde(skip_serializing_if = "Option::is_none")] #[cfg_attr(feature = "schemars", schemars(extend("default" = Base16Value::Base01)))] @@ -562,17 +556,14 @@ pub struct KomorebiThemeCustom { #[serde(skip_serializing_if = "Option::is_none")] #[cfg_attr(feature = "schemars", schemars(extend("default" = Base16Value::Base08)))] pub unfocused_locked_border: Option, - #[cfg(target_os = "windows")] /// Stackbar focused text colour #[serde(skip_serializing_if = "Option::is_none")] #[cfg_attr(feature = "schemars", schemars(extend("default" = Base16Value::Base0B)))] pub stackbar_focused_text: Option, - #[cfg(target_os = "windows")] /// Stackbar unfocused text colour #[serde(skip_serializing_if = "Option::is_none")] #[cfg_attr(feature = "schemars", schemars(extend("default" = Base16Value::Base05)))] pub stackbar_unfocused_text: Option, - #[cfg(target_os = "windows")] /// Stackbar background colour #[serde(skip_serializing_if = "Option::is_none")] #[cfg_attr(feature = "schemars", schemars(extend("default" = Base16Value::Base01)))] diff --git a/komorebi/Cargo.toml b/komorebi/Cargo.toml index 90d806c5..88cd21d7 100644 --- a/komorebi/Cargo.toml +++ b/komorebi/Cargo.toml @@ -9,6 +9,7 @@ edition = "2024" [dependencies] komorebi-collections = { path = "../crates/komorebi-collections" } +komorebi-config = { path = "../crates/komorebi-config", default-features = false } komorebi-layouts = { path = "../komorebi-layouts", features = ["win32"] } komorebi-scrolling = { path = "../komorebi-scrolling" } komorebi-themes = { path = "../komorebi-themes" } @@ -71,6 +72,7 @@ deadlock_detection = ["parking_lot/deadlock_detection"] schemars = [ "dep:schemars", "komorebi-collections/schemars", + "komorebi-config/schemars", "komorebi-layouts/schemars", "komorebi-protocol/schemars", ] diff --git a/komorebi/src/animation/mod.rs b/komorebi/src/animation/mod.rs index 86578fac..abd27466 100644 --- a/komorebi/src/animation/mod.rs +++ b/komorebi/src/animation/mod.rs @@ -13,6 +13,7 @@ use std::time::Duration; use parking_lot::Mutex; pub use engine::AnimationEngine; +pub use komorebi_config::animation::PerAnimationPrefixConfig; pub mod animation_manager; pub mod engine; pub mod ghost; @@ -25,42 +26,6 @@ pub use render_dispatcher::RenderDispatcher; pub mod style; pub mod transition; -use serde::Deserialize; -use serde::Serialize; - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -#[serde(untagged)] -/// Animation configuration -/// -/// This can be either global: -/// ```json -/// { -/// "enabled": true, -/// "style": "EaseInSine", -/// "fps": 60, -/// "duration": 250 -/// } -/// ``` -/// -/// Or scoped by an animation kind prefix: -/// ```json -/// { -/// "movement": { -/// "enabled": true, -/// "style": "EaseInSine", -/// "fps": 60, -/// "duration": 250 -/// } -/// } -/// ``` -pub enum PerAnimationPrefixConfig { - /// Animation configuration prefixed for a specific animation kind - Prefix(HashMap), - /// Animation configuration for all animation kinds - Global(T), -} - pub const DEFAULT_ANIMATION_ENABLED: bool = false; pub const DEFAULT_ANIMATION_STYLE: AnimationStyle = AnimationStyle::Linear; pub const DEFAULT_ANIMATION_DURATION: u64 = 250; diff --git a/komorebi/src/border_manager/mod.rs b/komorebi/src/border_manager/mod.rs index f4a7c528..eba053d3 100644 --- a/komorebi/src/border_manager/mod.rs +++ b/komorebi/src/border_manager/mod.rs @@ -16,12 +16,11 @@ use crossbeam_channel::Receiver; use crossbeam_channel::Sender; use crossbeam_utils::atomic::AtomicCell; use crossbeam_utils::atomic::AtomicConsume; +pub use komorebi_config::behaviour::ZOrder; use komorebi_themes::colour::Colour; use komorebi_themes::colour::Rgb; use lazy_static::lazy_static; use parking_lot::Mutex; -use serde::Deserialize; -use serde::Serialize; use std::collections::HashMap; use std::collections::HashSet; use std::collections::hash_map::Entry; @@ -32,7 +31,6 @@ use std::sync::atomic::AtomicBool; use std::sync::atomic::AtomicI32; use std::sync::atomic::AtomicU32; use std::sync::atomic::Ordering; -use strum::Display; use windows::Win32::Foundation::HWND; use windows::Win32::Graphics::Direct2D::ID2D1HwndRenderTarget; @@ -1102,42 +1100,6 @@ pub fn hide_border(tracking_hwnd: isize) { }); } -#[derive(Debug, Copy, Clone, Display, Serialize, Deserialize, PartialEq)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Z Order (https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setwindowpos) -pub enum ZOrder { - /// HWND_TOP - /// - /// Places the window at the top of the Z order. - Top, - /// HWND_NOTOPMOST - /// - /// Places the window above all non-topmost windows (that is, behind all topmost windows). - /// This flag has no effect if the window is already a non-topmost window. - NoTopMost, - /// HWND_BOTTOM - /// - /// Places the window at the bottom of the Z order. If the hWnd parameter identifies a topmost window, - /// the window loses its topmost status and is placed at the bottom of all other windows. - Bottom, - /// HWND_TOPMOST - /// - /// Places the window above all non-topmost windows. - /// The window maintains its topmost position even when it is deactivated. - TopMost, -} - -impl From for isize { - fn from(val: ZOrder) -> Self { - match val { - ZOrder::Top => 0, - ZOrder::NoTopMost => -2, - ZOrder::Bottom => 1, - ZOrder::TopMost => -1, - } - } -} - #[cfg(test)] mod tests { use super::*; diff --git a/komorebi/src/core/asc.rs b/komorebi/src/core/asc.rs index 45d9fb59..e9547be0 100644 --- a/komorebi/src/core/asc.rs +++ b/komorebi/src/core/asc.rs @@ -1,137 +1,3 @@ -use crate::config_generation::ApplicationConfiguration; -use crate::config_generation::ApplicationOptions; -use crate::config_generation::MatchingRule; -use color_eyre::eyre; -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) -> eyre::Result { - let content = std::fs::read_to_string(pathbuf)?; - Ok(serde_json::from_str(&content)?) - } - - pub fn format(pathbuf: &PathBuf) -> eyre::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 ignore specific windows from the transparency feature - #[serde(skip_serializing_if = "Option::is_none")] - pub transparency_ignore: Option>, - /// Rules to identify applications which minimize to the tray or have multiple windows - #[serde(skip_serializing_if = "Option::is_none")] - pub tray_and_multi_window: Option>, - /// Rules to identify applications which have the `WS_EX_LAYERED` Extended Window Style - #[serde(skip_serializing_if = "Option::is_none")] - pub layered: Option>, - /// Rules to identify applications which send the `EVENT_OBJECT_NAMECHANGE` event on launch - #[serde(skip_serializing_if = "Option::is_none")] - pub object_name_change: Option>, - /// Rules to identify applications which are slow to send initial event notifications - #[serde(skip_serializing_if = "Option::is_none")] - pub slow_application: Option>, -} - -impl From> for ApplicationSpecificConfiguration { - fn from(value: Vec) -> Self { - let mut map = BTreeMap::new(); - - for entry in &value { - let key = entry.name.clone(); - let mut rules = AscApplicationRules { - ignore: None, - manage: None, - floating: None, - transparency_ignore: None, - tray_and_multi_window: None, - layered: None, - object_name_change: None, - slow_application: None, - }; - - rules.ignore = entry.ignore_identifiers.clone(); - - if let Some(options) = &entry.options { - for opt in options { - match opt { - ApplicationOptions::ObjectNameChange => { - rules.object_name_change = - Some(vec![MatchingRule::Simple(entry.identifier.clone())]); - } - ApplicationOptions::Layered => { - rules.layered = - Some(vec![MatchingRule::Simple(entry.identifier.clone())]); - } - ApplicationOptions::TrayAndMultiWindow => { - rules.tray_and_multi_window = - Some(vec![MatchingRule::Simple(entry.identifier.clone())]); - } - ApplicationOptions::Force => { - rules.manage = - Some(vec![MatchingRule::Simple(entry.identifier.clone())]); - } - ApplicationOptions::BorderOverflow => {} - } - } - } - - if rules.ignore.is_some() - || rules.manage.is_some() - || rules.floating.is_some() - || rules.transparency_ignore.is_some() - || rules.tray_and_multi_window.is_some() - || rules.layered.is_some() - || rules.object_name_change.is_some() - || rules.slow_application.is_some() - { - map.insert(key, AscApplicationRulesOrSchema::AscApplicationRules(rules)); - } - } - - Self(map) - } -} +pub use komorebi_config::asc::ApplicationSpecificConfiguration; +pub use komorebi_config::asc::AscApplicationRules; +pub use komorebi_config::asc::AscApplicationRulesOrSchema; diff --git a/komorebi/src/core/config_generation.rs b/komorebi/src/core/config_generation.rs index a189a0da..73251aed 100644 --- a/komorebi/src/core/config_generation.rs +++ b/komorebi/src/core/config_generation.rs @@ -1,164 +1,14 @@ -use clap::ValueEnum; use color_eyre::eyre; use serde::Deserialize; use serde::Serialize; -use strum::Display; -use strum::EnumString; -use super::ApplicationIdentifier; - -#[derive(Clone, Copy, Debug, Serialize, Deserialize, Display, EnumString, ValueEnum)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -#[strum(serialize_all = "snake_case")] -#[serde(rename_all = "snake_case")] -pub enum ApplicationOptions { - ObjectNameChange, - Layered, - TrayAndMultiWindow, - Force, - BorderOverflow, -} - -impl ApplicationOptions { - #[must_use] - pub fn raw_cfgen(&self, kind: &ApplicationIdentifier, id: &str) -> String { - match self { - ApplicationOptions::ObjectNameChange => { - format!("komorebic.exe identify-object-name-change-application {kind} \"{id}\"",) - } - ApplicationOptions::Layered => { - format!("komorebic.exe identify-layered-application {kind} \"{id}\"",) - } - ApplicationOptions::TrayAndMultiWindow => { - format!("komorebic.exe identify-tray-application {kind} \"{id}\"",) - } - ApplicationOptions::Force => { - format!("komorebic.exe manage-rule {kind} \"{id}\"") - } - ApplicationOptions::BorderOverflow => { - unreachable!("deprecated"); - } - } - } - - #[must_use] - pub fn cfgen(&self, kind: &ApplicationIdentifier, id: &str) -> String { - format!( - "RunWait('{}', , \"Hide\")", - ApplicationOptions::raw_cfgen(self, kind, id) - ) - } -} - -#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -#[serde(untagged)] -/// Rule for matching applications -pub enum MatchingRule { - /// Simple matching rule which must evaluate to true - Simple(IdWithIdentifier), - /// Composite matching rule where all conditions must evaluate to true - Composite(Vec), -} - -#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Rule for assigning applications to a workspace -pub struct WorkspaceMatchingRule { - /// Target monitor index - pub monitor_index: usize, - /// Target workspace index - pub workspace_index: usize, - /// Matching rule for the application - pub matching_rule: MatchingRule, - /// Whether to apply the rule only when the application is initially launched - pub initial_only: bool, -} - -#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Rule for matching applications -pub struct IdWithIdentifier { - /// Kind of identifier to target - pub kind: ApplicationIdentifier, - /// Target identifier - pub id: String, - #[serde(skip_serializing_if = "Option::is_none")] - /// Matching strategy to use - pub matching_strategy: Option, -} - -#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Display)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Strategy for matching identifiers -pub enum MatchingStrategy { - /// Should not be used, only kept for backward compatibility - Legacy, - /// Equals - Equals, - /// Starts With - StartsWith, - /// Ends With - EndsWith, - /// Contains - Contains, - /// Regex - Regex, - /// Does not end with - DoesNotEndWith, - /// Does not start with - DoesNotStartWith, - /// Does not equal - DoesNotEqual, - /// Does not contain - DoesNotContain, -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -pub struct IdWithIdentifierAndComment { - pub kind: ApplicationIdentifier, - pub id: String, - #[serde(skip_serializing_if = "Option::is_none")] - pub comment: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub matching_strategy: Option, -} - -impl From for IdWithIdentifier { - fn from(value: IdWithIdentifierAndComment) -> Self { - Self { - kind: value.kind, - id: value.id.clone(), - matching_strategy: value.matching_strategy, - } - } -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -pub struct ApplicationConfiguration { - pub name: String, - pub identifier: IdWithIdentifier, - #[serde(skip_serializing_if = "Option::is_none")] - pub options: Option>, - #[serde(skip_serializing_if = "Option::is_none")] - #[serde(alias = "float_identifiers")] - pub ignore_identifiers: Option>, -} - -impl ApplicationConfiguration { - pub fn populate_default_matching_strategies(&mut self) { - if self.identifier.matching_strategy.is_none() { - match self.identifier.kind { - ApplicationIdentifier::Exe | ApplicationIdentifier::Path => { - self.identifier.matching_strategy = Option::from(MatchingStrategy::Equals); - } - ApplicationIdentifier::Class | ApplicationIdentifier::Title => {} - } - } - } -} +pub use komorebi_config::application_configuration::ApplicationConfiguration; +pub use komorebi_config::application_configuration::ApplicationOptions; +pub use komorebi_config::matching::IdWithIdentifier; +pub use komorebi_config::matching::IdWithIdentifierAndComment; +pub use komorebi_config::matching::MatchingRule; +pub use komorebi_config::matching::MatchingStrategy; +pub use komorebi_config::matching::WorkspaceMatchingRule; #[derive(Clone, Debug, Serialize, Deserialize)] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index c02029ce..020796f3 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -2,13 +2,8 @@ #![allow(clippy::missing_errors_doc, clippy::use_self, clippy::doc_markdown)] #![allow(deprecated)] // allow deprecated variants like HidingBehaviour::Hide to be used in derive macros - -use clap::ValueEnum; use serde::Deserialize; use serde::Serialize; -use strum::Display; -use strum::EnumString; - // Re-export everything from komorebi-layouts pub use komorebi_layouts::Arrangement; @@ -41,6 +36,15 @@ pub use komorebi_layouts::validate_ratios; // Local modules and exports pub use animation::AnimationStyle; +pub use komorebi_config::behaviour::CrossBoundaryBehaviour; +pub use komorebi_config::behaviour::FloatingLayerBehaviour; +pub use komorebi_config::behaviour::Placement; +pub use komorebi_config::behaviour::WindowContainerBehaviour; +pub use komorebi_config::behaviour::WindowHandlingBehaviour; +pub use komorebi_config::placement::InitialWindowPlacementRules; +pub use komorebi_config::placement::PlacementMatchingRules; +pub use komorebi_config::placement::PlacementTarget; +pub use komorebi_config::placement::WindowPlacement; pub use komorebi_protocol::types::ApplicationIdentifier; pub use komorebi_protocol::types::BorderImplementation; pub use komorebi_protocol::types::BorderStyle; @@ -93,324 +97,8 @@ pub struct WindowManagementBehaviour { pub float_rule_placement: Placement, } -#[derive( - Clone, Copy, Debug, Default, Serialize, Deserialize, Display, EnumString, ValueEnum, PartialEq, -)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Window container behaviour when a new window is opened -pub enum WindowContainerBehaviour { - /// Create a new container for each new window - #[default] - Create, - /// Append new windows to the focused window container - Append, -} - -#[derive( - Clone, Copy, Debug, Default, Serialize, Deserialize, Display, EnumString, ValueEnum, PartialEq, -)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Floating layer behaviour when a new window is opened -pub enum FloatingLayerBehaviour { - /// Tile new windows (unless they match a float rule or float override is active) - #[default] - Tile, - /// Float new windows - Float, -} - -#[derive( - Clone, Copy, Debug, Default, Serialize, Deserialize, Display, EnumString, ValueEnum, PartialEq, -)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Placement behaviour for floating windows -pub enum Placement { - /// Does not change the size or position of the window - #[default] - None, - /// Center the window without changing the size - Center, - /// Center the window and resize it according to the `AspectRatio` - CenterAndResize, -} - -impl FloatingLayerBehaviour { - pub fn should_float(&self) -> bool { - match self { - FloatingLayerBehaviour::Tile => false, - FloatingLayerBehaviour::Float => true, - } - } -} - -impl Placement { - pub fn should_center(&self) -> bool { - match self { - Placement::None => false, - Placement::Center | Placement::CenterAndResize => true, - } - } - - pub fn should_resize(&self) -> bool { - match self { - Placement::None | Placement::Center => false, - Placement::CenterAndResize => true, - } - } -} - -#[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 behaviour) - #[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)) - } -} - // Written by hand because the (de)serialization is: a `WindowPlacement` name or a container index, // as a string or as an integer, never the externally tagged object a derive would describe -#[cfg(feature = "schemars")] -impl schemars::JsonSchema for PlacementTarget { - fn schema_name() -> std::borrow::Cow<'static, str> { - "PlacementTarget".into() - } - - fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema { - schemars::json_schema!({ - "description": "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\"`, or the integer `3`). - -NOTE: Integer indices are 1-based in the config for user-friendliness.", - "anyOf": [ - generator.subschema_for::(), - { - "description": "A 1-based container index as a string", - "type": "string", - "pattern": "^[0-9]+$" - }, - { - "description": "A 1-based container index", - "type": "integer", - "minimum": 0 - } - ] - }) - } -} - -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 { - fn deserialize>(deserializer: D) -> Result { - struct PlacementTargetVisitor; - - impl serde::de::Visitor<'_> for PlacementTargetVisitor { - type Value = PlacementTarget; - - fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - f.write_str("a WindowPlacement name or a non-negative container index") - } - - fn visit_str(self, s: &str) -> Result { - s.parse().map_err(E::custom) - } - - fn visit_u64(self, n: u64) -> Result { - usize::try_from(n) - .map(PlacementTarget::Index) - .map_err(E::custom) - } - - fn visit_i64(self, n: i64) -> Result { - usize::try_from(n) - .map(PlacementTarget::Index) - .map_err(E::custom) - } - } - - deserializer.deserialize_any(PlacementTargetVisitor) - } -} - -/// 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, Serialize, Deserialize, Display, EnumString, ValueEnum, PartialEq, -)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Behaviour when an action would cross a monitor boundary -pub enum CrossBoundaryBehaviour { - /// Attempt to perform actions across a workspace boundary - Workspace, - /// Attempt to perform actions across a monitor boundary - #[default] - Monitor, -} - -#[derive( - Clone, Copy, Debug, Default, Serialize, Deserialize, Display, EnumString, ValueEnum, PartialEq, -)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Window handling behaviour -pub enum WindowHandlingBehaviour { - #[default] - /// Synchronous - Sync, - /// Asynchronous - Async, -} - #[cfg(test)] mod tests { use super::*; diff --git a/komorebi/src/main.rs b/komorebi/src/main.rs index a023de69..9b4f12d3 100644 --- a/komorebi/src/main.rs +++ b/komorebi/src/main.rs @@ -52,6 +52,7 @@ use komorebi::reaper; use komorebi::stackbar_manager; use komorebi::state::State; use komorebi::static_config::StaticConfig; +use komorebi::static_config::StaticConfigExt; use komorebi::theme_manager; use komorebi::transparency_manager; use komorebi::window_manager::WindowManager; diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index 5b5fa3ae..7362499b 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -86,6 +86,7 @@ use crate::state; use crate::state::GlobalState; use crate::state::State; use crate::static_config::StaticConfig; +use crate::static_config::StaticConfigExt; use crate::theme_manager; use crate::transparency_manager; use crate::window::RuleDebug; diff --git a/komorebi/src/static_config.rs b/komorebi/src/static_config.rs index c66c2fa7..c84b98e9 100644 --- a/komorebi/src/static_config.rs +++ b/komorebi/src/static_config.rs @@ -1,5 +1,4 @@ use crate::AspectRatio; -use crate::Axis; use crate::CrossBoundaryBehaviour; use crate::DATA_DIR; use crate::DEFAULT_CONTAINER_PADDING; @@ -22,7 +21,6 @@ use crate::OBJECT_NAME_CHANGE_TITLE_IGNORE_LIST; use crate::Placement; use crate::PredefinedAspectRatio; use crate::REGEX_IDENTIFIERS; -use crate::ResolvedPathBuf; use crate::SLOW_APPLICATION_COMPENSATION_TIME; use crate::SLOW_APPLICATION_IDENTIFIERS; use crate::TRANSPARENCY_BLACKLIST; @@ -30,7 +28,6 @@ use crate::TRAY_AND_MULTI_WINDOW_IDENTIFIERS; use crate::WINDOW_HANDLING_BEHAVIOUR; use crate::WINDOWS_11; use crate::WORKSPACE_MATCHING_RULES; -use crate::WindowHandlingBehaviour; use crate::animation::ANIMATION_DURATION_GLOBAL; use crate::animation::ANIMATION_DURATION_PER_ANIMATION; use crate::animation::ANIMATION_ENABLED_GLOBAL; @@ -47,25 +44,14 @@ use crate::asc::AscApplicationRulesOrSchema; use crate::border_manager; use crate::border_manager::IMPLEMENTATION; use crate::border_manager::STYLE; -use crate::border_manager::ZOrder; use crate::config_generation::WorkspaceMatchingRule; -use crate::core::AnimationStyle; use crate::core::BorderImplementation; -use crate::core::BorderStyle; -use crate::core::DefaultLayout; use crate::core::FocusFollowsMouseImplementation; -use crate::core::HidingBehaviour; -use crate::core::InitialWindowPlacementRules; use crate::core::Layout; -use crate::core::LayoutDefaultEntry; -use crate::core::LayoutOptions; -use crate::core::MonocleFocusBehaviour; use crate::core::MoveBehaviour; use crate::core::OperationBehaviour; use crate::core::Rect; use crate::core::SocketMessage; -use crate::core::StackbarLabel; -use crate::core::StackbarMode; use crate::core::WindowContainerBehaviour; use crate::core::WindowManagementBehaviour; use crate::core::config_generation::ApplicationConfiguration; @@ -77,7 +63,6 @@ use crate::current_virtual_desktop; use crate::monitor; use crate::monitor::Monitor; use crate::monitor_reconciliator; -use crate::resolve_option_hashmap_usize_path; use crate::ring::Ring; use crate::stackbar_manager::STACKBAR_FOCUSED_TEXT_COLOUR; use crate::stackbar_manager::STACKBAR_FONT_FAMILY; @@ -102,8 +87,6 @@ use hotwatch::Hotwatch; use komorebi_themes::colour::Colour; use parking_lot::Mutex; use regex::Regex; -use serde::Deserialize; -use serde::Serialize; use std::collections::HashMap; use std::collections::HashSet; use std::io::ErrorKind; @@ -114,185 +97,17 @@ use std::sync::atomic::Ordering; use uds_windows::UnixListener; use uds_windows::UnixStream; -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Border colours for different container states -pub struct BorderColours { - /// Border colour when the container contains a single window - #[serde(skip_serializing_if = "Option::is_none")] - pub single: Option, - /// Border colour when the container contains multiple windows - #[serde(skip_serializing_if = "Option::is_none")] - pub stack: Option, - /// Border colour when the container is in monocle mode - #[serde(skip_serializing_if = "Option::is_none")] - pub monocle: Option, - /// Border colour when the container is in floating mode - #[serde(skip_serializing_if = "Option::is_none")] - pub floating: Option, - /// Border colour when the container is unfocused - #[serde(skip_serializing_if = "Option::is_none")] - pub unfocused: Option, - /// Border colour when the container is unfocused and locked - #[serde(skip_serializing_if = "Option::is_none")] - pub unfocused_locked: Option, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Theme options -pub struct ThemeOptions { - /// Specify Light or Dark variant for theme generation - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::ThemeVariant::Dark)))] - pub theme_variant: Option, - /// Border colour when the container contains a single window - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::Base16Value::Base0D)))] - pub single_border: Option, - /// Border colour when the container contains multiple windows - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::Base16Value::Base0B)))] - pub stack_border: Option, - /// Border colour when the container is in monocle mode - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::Base16Value::Base0F)))] - pub monocle_border: Option, - /// Border colour when the window is floating - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::Base16Value::Base09)))] - pub floating_border: Option, - /// Border colour when the container is unfocused - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::Base16Value::Base01)))] - pub unfocused_border: Option, - /// Border colour when the container is unfocused and locked - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::Base16Value::Base08)))] - pub unfocused_locked_border: Option, - /// Stackbar focused tab text colour - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::Base16Value::Base0B)))] - pub stackbar_focused_text: Option, - /// Stackbar unfocused tab text colour - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::Base16Value::Base05)))] - pub stackbar_unfocused_text: Option, - /// Stackbar tab background colour - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::Base16Value::Base01)))] - pub stackbar_background: Option, - /// Komorebi status bar accent - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::Base16Value::Base0D)))] - pub bar_accent: Option, -} - -#[serde_with::serde_as] -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Wallpaper configuration -pub struct Wallpaper { - /// Path to the wallpaper image file - #[serde_as(as = "ResolvedPathBuf")] - pub path: PathBuf, - /// Generate and apply Base16 theme for this wallpaper - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = true)))] - pub generate_theme: Option, - /// Specify Light or Dark variant for theme generation - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::ThemeVariant::Dark)))] - pub theme_options: Option, -} - // serde_as must be before derive -#[serde_with::serde_as] -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Workspace configuration -pub struct WorkspaceConfig { - /// Name - pub name: String, - /// Layout - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = DefaultLayout::BSP)))] - pub layout: Option, - /// Layout-specific options - #[serde(skip_serializing_if = "Option::is_none")] - pub layout_options: Option, - /// Threshold-based layout options rules in the format of threshold => options. - /// When container count >= threshold, the highest matching threshold's options - /// fully replace the base `layout_options`. - /// This follows the same threshold logic as `layout_rules`. - #[serde(skip_serializing_if = "Option::is_none")] - pub layout_options_rules: Option>, - /// END OF LIFE FEATURE: Custom Layout - #[deprecated(note = "End of life feature")] - #[serde(skip_serializing_if = "Option::is_none")] - #[serde_as(as = "Option")] - pub custom_layout: Option, - /// Layout rules in the format of threshold => layout - #[serde(skip_serializing_if = "Option::is_none")] - pub layout_rules: Option>, - /// Work area offset rules in the format of threshold => Rect (default: None) - #[serde(skip_serializing_if = "Option::is_none")] - pub work_area_offset_rules: Option>, - /// END OF LIFE FEATURE: Custom layout rules - #[deprecated(note = "End of life feature")] - #[serde(skip_serializing_if = "Option::is_none")] - #[serde(deserialize_with = "resolve_option_hashmap_usize_path", default)] - pub custom_layout_rules: Option>, - /// Container padding (default: global) - #[serde(skip_serializing_if = "Option::is_none")] - pub container_padding: Option, - /// Workspace padding (default: global) - #[serde(skip_serializing_if = "Option::is_none")] - pub workspace_padding: Option, - /// Initial workspace application rules - #[serde(skip_serializing_if = "Option::is_none")] - pub initial_workspace_rules: Option>, - /// Permanent workspace application rules - #[serde(skip_serializing_if = "Option::is_none")] - pub workspace_rules: Option>, - /// Workspace specific work area offset - #[serde(skip_serializing_if = "Option::is_none")] - pub work_area_offset: Option, - /// Apply this monitor's window-based work area offset - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = true)))] - pub apply_window_based_work_area_offset: Option, - /// Determine what happens when a new window is opened - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = WindowContainerBehaviour::Create)))] - pub window_container_behaviour: Option, - /// Window container behaviour rules in the format of threshold => behaviour - #[serde(skip_serializing_if = "Option::is_none")] - pub window_container_behaviour_rules: Option>, - /// Enable or disable float override, which makes it so every new window opens in floating mode - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = false)))] - pub float_override: Option, - /// Enable or disable tiling for the workspace - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = true)))] - pub tile: Option, - /// Specify an axis on which to flip the selected layout - #[serde(skip_serializing_if = "Option::is_none")] - pub layout_flip: Option, - /// Determine what happens to a new window when the Floating workspace layer is active - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = FloatingLayerBehaviour::Tile)))] - pub floating_layer_behaviour: Option, - /// 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, -} +pub use komorebi_config::static_config::AnimationsConfig; +pub use komorebi_config::static_config::AppSpecificConfigurationPath; +pub use komorebi_config::static_config::BorderColours; +pub use komorebi_config::static_config::MonitorConfig; +pub use komorebi_config::static_config::StackbarConfig; +pub use komorebi_config::static_config::StaticConfig; +pub use komorebi_config::static_config::TabsConfig; +pub use komorebi_config::static_config::ThemeOptions; +pub use komorebi_config::static_config::Wallpaper; +pub use komorebi_config::static_config::WorkspaceConfig; impl From<&Workspace> for WorkspaceConfig { fn from(value: &Workspace) -> Self { @@ -400,37 +215,6 @@ impl From<&Workspace> for WorkspaceConfig { } } -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Monitor configuration -pub struct MonitorConfig { - /// Workspace configurations - pub workspaces: Vec, - /// Monitor-specific work area offset - #[serde(skip_serializing_if = "Option::is_none")] - pub work_area_offset: Option, - /// Window based work area offset - #[serde(skip_serializing_if = "Option::is_none")] - pub window_based_work_area_offset: Option, - /// Open window limit after which the window based work area offset will no longer be applied - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = 1)))] - pub window_based_work_area_offset_limit: Option, - /// Container padding (default: global) - #[serde(skip_serializing_if = "Option::is_none")] - pub container_padding: Option, - /// Workspace padding (default: global) - #[serde(skip_serializing_if = "Option::is_none")] - pub workspace_padding: Option, - /// Specify a wallpaper for this monitor - #[serde(skip_serializing_if = "Option::is_none")] - pub wallpaper: Option, - /// Determine what happens to a new window when the Floating workspace layer is active - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = FloatingLayerBehaviour::Tile)))] - pub floating_layer_behaviour: Option, -} - impl From<&Monitor> for MonitorConfig { fn from(value: &Monitor) -> Self { let mut workspaces = vec![]; @@ -466,386 +250,13 @@ impl From<&Monitor> for MonitorConfig { workspace_padding, wallpaper: value.wallpaper.clone(), floating_layer_behaviour: value.floating_layer_behaviour, + window_hiding_position: None, } } } -#[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))] -/// The `komorebi.json` static configuration file reference for `v0.1.42` -pub struct StaticConfig { - /// DEPRECATED from v0.1.22: no longer required - #[deprecated(note = "No longer required")] - #[serde(skip_serializing_if = "Option::is_none")] - pub invisible_borders: Option, - /// DISCOURAGED: Minimum width for a window to be eligible for tiling - #[serde(skip_serializing_if = "Option::is_none")] - pub minimum_window_width: Option, - /// DISCOURAGED: Minimum height for a window to be eligible for tiling - #[serde(skip_serializing_if = "Option::is_none")] - pub minimum_window_height: Option, - /// Delta to resize windows by - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = DEFAULT_RESIZE_DELTA)))] - pub resize_delta: Option, - /// Determine what happens when a new window is opened - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = WindowContainerBehaviour::Create)))] - pub window_container_behaviour: Option, - /// Enable or disable float override, which makes it so every new window opens in floating mode - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = false)))] - pub float_override: Option, - /// Determines what happens on a new window when on the `FloatingLayer` - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = FloatingLayerBehaviour::Tile)))] - pub floating_layer_behaviour: Option, - /// Determines the placement of a new window when toggling to float - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = Placement::CenterAndResize)))] - pub toggle_float_placement: Option, - /// Determines the `Placement` to be used when spawning a window on the floating layer with the - /// `FloatingLayerBehaviour` set to `FloatingLayerBehaviour::Float` - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = Placement::Center)))] - pub floating_layer_placement: Option, - /// Determines the `Placement` to be used when spawning a window with float override active - #[serde(skip_serializing_if = "Option::is_none")] - pub float_override_placement: Option, - /// Determines the `Placement` to be used when spawning a window that matches a - /// `floating_applications` rule - #[serde(skip_serializing_if = "Option::is_none")] - pub float_rule_placement: Option, - /// Determine what happens when a window is moved across a monitor boundary - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = MoveBehaviour::Swap)))] - pub cross_monitor_move_behaviour: Option, - /// Determine what happens when an action is called on a window at a monitor boundary - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = CrossBoundaryBehaviour::Monitor)))] - pub cross_boundary_behaviour: Option, - /// Determine what happens when focusing in a direction while a monocle container is active - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = MonocleFocusBehaviour::NoOp)))] - pub monocle_focus_behaviour: Option, - /// Determine what happens when commands are sent while an unmanaged window is in the foreground - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = OperationBehaviour::Op)))] - pub unmanaged_window_operation_behaviour: Option, - /// END OF LIFE FEATURE: Use https://github.com/LGUG2Z/masir instead - #[deprecated( - note = "End of life feature, use [masir](https://github.com/LGUG2Z/masir) instead" - )] - #[serde(skip_serializing_if = "Option::is_none")] - pub focus_follows_mouse: Option, - /// Enable or disable mouse follows focus - #[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 applications.json from komorebi-application-specific-configurations - #[serde(skip_serializing_if = "Option::is_none")] - pub app_specific_configuration_path: Option, - /// Width of window borders - #[serde(skip_serializing_if = "Option::is_none")] - #[serde(alias = "active_window_border_width")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = border_manager::BORDER_WIDTH)))] - pub border_width: Option, - /// Offset of window borders - #[serde(skip_serializing_if = "Option::is_none")] - #[serde(alias = "active_window_border_offset")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = border_manager::BORDER_OFFSET)))] - pub border_offset: Option, - /// Display window borders - #[serde(skip_serializing_if = "Option::is_none")] - #[serde(alias = "active_window_border")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = border_manager::BORDER_ENABLED)))] - pub border: Option, - /// Window border colours for different container types (has no effect if [`theme`] is defined) - #[serde(skip_serializing_if = "Option::is_none")] - #[serde(alias = "active_window_border_colours")] - pub border_colours: Option, - /// Window border style - #[serde(skip_serializing_if = "Option::is_none")] - #[serde(alias = "active_window_border_style")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = BorderStyle::System)))] - pub border_style: Option, - /// DEPRECATED from v0.1.31: no longer required - #[deprecated(note = "No longer required")] - #[serde(skip_serializing_if = "Option::is_none")] - pub border_z_order: Option, - /// Window border implementation - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = BorderImplementation::Komorebi)))] - pub border_implementation: Option, - /// Add transparency to unfocused windows - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = transparency_manager::TRANSPARENCY_ENABLED)))] - pub transparency: Option, - /// Alpha value for unfocused window transparency [[0-255]] - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = transparency_manager::TRANSPARENCY_ALPHA)))] - pub transparency_alpha: Option, - /// Individual window transparency ignore rules - #[serde(skip_serializing_if = "Option::is_none")] - pub transparency_ignore_rules: Option>, - /// Global default workspace padding - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = DEFAULT_WORKSPACE_PADDING)))] - pub default_workspace_padding: Option, - /// Global default container padding - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = DEFAULT_CONTAINER_PADDING)))] - pub default_container_padding: Option, - /// Per-layout default options and rules, keyed by layout name. - /// Applied as fallback when a workspace does not define its own layout_options or layout_options_rules. - /// If a workspace defines either setting, all global defaults for that layout are completely replaced. - #[serde(skip_serializing_if = "Option::is_none")] - pub layout_defaults: Option>, - /// Monitor and workspace configurations - #[serde(skip_serializing_if = "Option::is_none")] - pub monitors: Option>, - /// Which Windows signal to use when hiding windows - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = HidingBehaviour::Cloak)))] - pub window_hiding_behaviour: Option, - /// Global work area (space used for tiling) offset - #[serde(skip_serializing_if = "Option::is_none")] - pub global_work_area_offset: Option, - /// Individual window floating rules - #[serde(skip_serializing_if = "Option::is_none")] - #[serde(alias = "float_rules")] - pub ignore_rules: Option>, - /// Individual window force-manage rules - #[serde(skip_serializing_if = "Option::is_none")] - pub manage_rules: Option>, - /// Identify applications which should be managed as floating windows - #[serde(skip_serializing_if = "Option::is_none")] - pub floating_applications: Option>, - /// Identify border overflow applications - #[serde(skip_serializing_if = "Option::is_none")] - pub border_overflow_applications: Option>, - /// Identify tray and multi-window applications - #[serde(skip_serializing_if = "Option::is_none")] - pub tray_and_multi_window_applications: Option>, - /// Identify applications that have the `WS_EX_LAYERED` extended window style - #[serde(skip_serializing_if = "Option::is_none")] - pub layered_applications: Option>, - /// Identify applications that send `EVENT_OBJECT_NAMECHANGE` on launch (very rare) - #[serde(skip_serializing_if = "Option::is_none")] - pub object_name_change_applications: Option>, - /// Do not process `EVENT_OBJECT_NAMECHANGE` events as Show events for identified applications matching these title regexes - #[serde(skip_serializing_if = "Option::is_none")] - pub object_name_change_title_ignore_list: Option>, - /// Set monitor index preferences - #[serde(skip_serializing_if = "Option::is_none")] - pub monitor_index_preferences: Option>, - /// Set display index preferences - #[serde(skip_serializing_if = "Option::is_none")] - pub display_index_preferences: Option>, - /// Stackbar configuration options - #[serde(skip_serializing_if = "Option::is_none")] - pub stackbar: Option, - /// Animations configuration options - #[serde(skip_serializing_if = "Option::is_none")] - pub animation: Option, - /// Theme configuration options - /// - /// If a theme is specified, `border_colours` will have no effect - #[serde(skip_serializing_if = "Option::is_none")] - pub theme: Option, - /// Identify applications which are slow to send initial event notifications - #[serde(skip_serializing_if = "Option::is_none")] - pub slow_application_identifiers: Option>, - /// How long to wait when compensating for slow applications, in milliseconds - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = SLOW_APPLICATION_COMPENSATION_TIME)))] - pub slow_application_compensation_time: Option, - /// Komorebi status bar configuration files for multiple instances on different monitors - // this option is a little special because it is only consumed by komorebic - #[serde(skip_serializing_if = "Option::is_none")] - #[serde_as(as = "Option>")] - pub bar_configurations: Option>, - /// HEAVILY DISCOURAGED: Identify applications for which komorebi should forcibly remove title bars - #[serde(skip_serializing_if = "Option::is_none")] - pub remove_titlebar_applications: Option>, - /// Aspect ratio to resize with when toggling floating mode for a window - #[serde(skip_serializing_if = "Option::is_none")] - pub floating_window_aspect_ratio: Option, - /// Which Windows API behaviour to use when manipulating windows - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = WindowHandlingBehaviour::Sync)))] - pub window_handling_behaviour: Option, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Animations configuration options -pub struct AnimationsConfig { - /// Enable or disable animations - #[cfg_attr(feature = "schemars", schemars(extend("default" = PerAnimationPrefixConfig::Global(false))))] - pub enabled: PerAnimationPrefixConfig, - /// Set the animation duration in ms - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = PerAnimationPrefixConfig::Global(250))))] - pub duration: Option>, - /// Set the animation style - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = PerAnimationPrefixConfig::Global(AnimationStyle::Linear))))] - pub style: Option>, - /// Set the animation FPS - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = ANIMATION_FPS)))] - pub fps: Option, - /// Render movement animations on a GPU-composited ghost surface (recommended). - /// When false, falls back to the legacy per-frame MoveWindow path. - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = false)))] - pub ghost_movement: Option, -} - pub use komorebi_themes::KomorebiTheme; -impl StaticConfig { - pub fn end_of_life(raw: &str) { - let features = vec![ - "focus_follows_mouse", - "custom_layout", - "custom_layout_rules", - ]; - - let mut display = false; - - for feature in features { - if raw.contains(feature) { - if !display { - display = true; - println!("\n\"{feature}\" is now end-of-life"); - } else { - println!(r#""{feature}" is now end-of-life"#); - } - } - } - - if display { - println!( - "\nEnd-of-life features will not receive any further bug fixes or updates; they should not be used\n" - ) - } - } - - pub fn aliases(raw: &str) { - let mut map = HashMap::new(); - map.insert("border", ["active_window_border"]); - map.insert("border_width", ["active_window_border_width"]); - map.insert("border_offset", ["active_window_border_offset"]); - map.insert("border_colours", ["active_window_border_colours"]); - map.insert("border_style", ["active_window_border_style"]); - map.insert("applications.json", ["applications.yaml"]); - map.insert("ignore_rules", ["float_rules"]); - - let mut display = false; - - for aliases in map.values() { - for a in aliases { - if raw.contains(a) { - display = true; - } - } - } - - if display { - println!( - "\nYour configuration file contains some options that have been renamed or deprecated:\n" - ); - for (canonical, aliases) in map { - for alias in aliases { - if raw.contains(alias) { - println!(r#""{alias}" is now "{canonical}""#); - } - } - } - } - } - - pub fn deprecated(raw: &str) { - let deprecated_options = ["invisible_borders", "border_z_order"]; - let deprecated_variants = vec![ - ("Hide", "window_hiding_behaviour", "Cloak"), - ("Minimize", "window_hiding_behaviour", "Cloak"), - ]; - - for option in deprecated_options { - if raw.contains(option) { - println!(r#""{option}" is deprecated and can be removed"#); - } - } - - for (variant, option, recommended) in deprecated_variants { - if raw.contains(option) && raw.contains(variant) { - println!( - r#"The "{variant}" option for "{option}" is deprecated and can be removed or replaced with "{recommended}""# - ); - } - } - } -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Stackbar tabs configuration -pub struct TabsConfig { - /// Width of a stackbar tab - #[serde(skip_serializing_if = "Option::is_none")] - pub width: Option, - /// Focused tab text colour - #[serde(skip_serializing_if = "Option::is_none")] - pub focused_text: Option, - /// Unfocused tab text colour - #[serde(skip_serializing_if = "Option::is_none")] - pub unfocused_text: Option, - /// Tab background colour - #[serde(skip_serializing_if = "Option::is_none")] - pub background: Option, - /// Font family - #[serde(skip_serializing_if = "Option::is_none")] - pub font_family: Option, - /// Font size - #[serde(skip_serializing_if = "Option::is_none")] - pub font_size: Option, -} - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Stackbar configuration -pub struct StackbarConfig { - /// Stackbar height - #[serde(skip_serializing_if = "Option::is_none")] - pub height: Option, - /// Stackbar label - #[serde(skip_serializing_if = "Option::is_none")] - pub label: Option, - /// Stackbar mode - #[serde(skip_serializing_if = "Option::is_none")] - #[cfg_attr(feature = "schemars", schemars(extend("default" = StackbarMode::Never)))] - pub mode: Option, - /// Stackbar tab configuration options - #[serde(skip_serializing_if = "Option::is_none")] - pub tabs: Option, -} - impl From<&WindowManager> for StaticConfig { #[allow(clippy::too_many_lines)] fn from(value: &WindowManager) -> Self { @@ -970,11 +381,17 @@ impl From<&WindowManager> for StaticConfig { remove_titlebar_applications: Option::from(NO_TITLEBAR.lock().clone()), floating_window_aspect_ratio: Option::from(*FLOATING_WINDOW_TOGGLE_ASPECT_RATIO.lock()), window_handling_behaviour: Option::from(WINDOW_HANDLING_BEHAVIOUR.load()), + ..Default::default() } } } -impl StaticConfig { +/// Applies the settings of a configuration that are not the window manager's own +trait ApplyGlobals { + fn apply_globals(&mut self) -> eyre::Result<()>; +} + +impl ApplyGlobals for StaticConfig { #[allow(clippy::cognitive_complexity, clippy::too_many_lines)] fn apply_globals(&mut self) -> eyre::Result<()> { *FLOATING_WINDOW_TOGGLE_ASPECT_RATIO.lock() = self @@ -1292,18 +709,29 @@ impl StaticConfig { Ok(()) } +} - pub fn read_raw(raw: &str) -> eyre::Result { - Ok(serde_json::from_str(raw)?) - } +/// What loading a configuration needs from the window manager: the part of `StaticConfig` +/// that cannot be an inherent impl now that the type lives in `komorebi-config`. +#[allow(clippy::ptr_arg)] // the signatures are the ones the inherent functions had +pub trait StaticConfigExt: Sized { + /// Makes the window manager from the file at `path`, and starts watching the file + fn preload( + path: &PathBuf, + incoming: Receiver, + unix_listener: Option, + ) -> eyre::Result; - pub fn read(path: &PathBuf) -> eyre::Result { - let content = std::fs::read_to_string(path)?; - serde_json::from_str(&content).map_err(Into::into) - } + /// Gives the monitors of the window manager what the file says about them + fn postload(path: &PathBuf, wm: &Arc>) -> eyre::Result<()>; + /// Replaces the configuration of the window manager with the file at `path` + fn reload(path: &PathBuf, wm: &mut WindowManager) -> eyre::Result<()>; +} + +impl StaticConfigExt for StaticConfig { #[allow(clippy::too_many_lines)] - pub fn preload( + fn preload( path: &PathBuf, incoming: Receiver, unix_listener: Option, @@ -1407,7 +835,7 @@ impl StaticConfig { Ok(wm) } - pub fn postload(path: &PathBuf, wm: &Arc>) -> eyre::Result<()> { + fn postload(path: &PathBuf, wm: &Arc>) -> eyre::Result<()> { let mut value = Self::read(path)?; let mut wm = wm.lock(); @@ -1571,7 +999,7 @@ impl StaticConfig { Ok(()) } - pub fn reload(path: &PathBuf, wm: &mut WindowManager) -> eyre::Result<()> { + fn reload(path: &PathBuf, wm: &mut WindowManager) -> eyre::Result<()> { let mut value = Self::read(path)?; value.apply_globals()?; diff --git a/komorebi/src/window.rs b/komorebi/src/window.rs index 2f9009a6..321b599c 100644 --- a/komorebi/src/window.rs +++ b/komorebi/src/window.rs @@ -44,6 +44,8 @@ use crate::windows_api; use crate::windows_api::WindowsApi; use color_eyre::eyre; use crossbeam_utils::atomic::AtomicConsume; +pub use komorebi_config::aspect_ratio::AspectRatio; +pub use komorebi_config::aspect_ratio::PredefinedAspectRatio; use regex::Regex; use serde::Deserialize; use serde::Serialize; @@ -58,8 +60,6 @@ use std::sync::atomic::AtomicI32; use std::sync::atomic::Ordering; use std::thread; use std::time::Duration; -use strum::Display; -use strum::EnumString; use windows::Win32::Foundation::HWND; pub static MINIMUM_WIDTH: AtomicI32 = AtomicI32::new(0); @@ -227,51 +227,6 @@ impl RenderDispatcher for TransparencyRenderDispatcher { } } -#[derive(Copy, Clone, Debug, Display, EnumString, Serialize, Deserialize, PartialEq)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -#[serde(untagged)] -/// Aspect ratio for temporarily floating windows -pub enum AspectRatio { - /// Predefined aspect ratio - #[cfg_attr(feature = "schemars", schemars(title = "Predefined"))] - Predefined(PredefinedAspectRatio), - /// Custom W:H aspect ratio - #[cfg_attr(feature = "schemars", schemars(title = "Custom"))] - Custom(i32, i32), -} - -impl Default for AspectRatio { - fn default() -> Self { - AspectRatio::Predefined(PredefinedAspectRatio::default()) - } -} - -#[derive(Copy, Clone, Debug, Default, Display, EnumString, Serialize, Deserialize, PartialEq)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -/// Predefined aspect ratio -pub enum PredefinedAspectRatio { - /// 21:9 - Ultrawide, - /// 16:9 - Widescreen, - /// 4:3 - #[default] - Standard, -} - -impl AspectRatio { - pub fn width_and_height(self) -> (i32, i32) { - match self { - AspectRatio::Predefined(predefined) => match predefined { - PredefinedAspectRatio::Ultrawide => (21, 9), - PredefinedAspectRatio::Widescreen => (16, 9), - PredefinedAspectRatio::Standard => (4, 3), - }, - AspectRatio::Custom(w, h) => (w, h), - } - } -} - impl Window { pub const fn hwnd(self) -> HWND { HWND(windows_api::as_ptr!(self.hwnd)) diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index 5e09998b..a4e6502c 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -68,6 +68,7 @@ use crate::should_act; use crate::should_act_individual; use crate::state::State; use crate::static_config::StaticConfig; +use crate::static_config::StaticConfigExt; use crate::transparency_manager; use crate::window::Window; use crate::window_manager_event::WindowManagerEvent; diff --git a/komorebic/Cargo.toml b/komorebic/Cargo.toml index bad8f176..a264aae8 100644 --- a/komorebic/Cargo.toml +++ b/komorebic/Cargo.toml @@ -8,6 +8,7 @@ edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +komorebi-config = { path = "../crates/komorebi-config", default-features = false } komorebi-client = { path = "../komorebi-client", default-features = false } komorebic-core = { path = "../crates/komorebic-core" } @@ -38,7 +39,7 @@ shadow-rs = { workspace = true } [features] default = ["schemars"] -schemars = ["dep:schemars", "komorebi-client/default"] +schemars = ["dep:schemars", "komorebi-client/default", "komorebi-config/schemars"] [lints.rust] unexpected_cfgs = { level = "warn", check-cfg = ['cfg(FALSE)'] } diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs index 82112c8e..2277d1ff 100644 --- a/komorebic/src/main.rs +++ b/komorebic/src/main.rs @@ -1402,9 +1402,10 @@ if (Get-Command Get-CimInstance -ErrorAction SilentlyContinue) { WindowsCommands::ApplicationSpecificConfigurationSchema => { #[cfg(feature = "schemars")] { - let asc = schemars::schema_for!(ApplicationSpecificConfiguration); - let schema = serde_json::to_string_pretty(&asc)?; - println!("{schema}"); + let schema = komorebi_config::schema::view::( + komorebi_config::schema::Platform::CURRENT, + ); + print!("{schema}"); } } WindowsCommands::NotificationSchema => { @@ -1426,9 +1427,10 @@ if (Get-Command Get-CimInstance -ErrorAction SilentlyContinue) { WindowsCommands::StaticConfigSchema => { #[cfg(feature = "schemars")] { - let static_config = schemars::schema_for!(StaticConfig); - let schema = serde_json::to_string_pretty(&static_config)?; - println!("{schema}"); + let schema = komorebi_config::schema::view::< + komorebi_config::static_config::StaticConfig, + >(komorebi_config::schema::Platform::CURRENT); + print!("{schema}"); } } WindowsCommands::GenerateStaticConfig => {