From 507c51f0c0c79eaf365d145225b727266cb9bfc2 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 10:01:50 -0700 Subject: [PATCH] feat(core): the vocabulary the window manager is written in Configuration, commands and the layout code all speak in the same small types: how a new window is added to a workspace, what happens to a window that crosses a monitor boundary, which kind of window a border colour is for, how an application is matched by what it calls itself. They are defined once, in `core`, with the layout types re-exported next to them so that the rest of the crate imports from one place. The layouts themselves are `komorebi-layouts` from komorebi, a git dependency as in komorebi for Mac, at f08aa55 (the tip of master when this was written). That revision has the fix for resizing a tile by dragging its edge (LGUG2Z/komorebi#1765) and the placement helpers this port uses, so nothing is vendored. The crate pulls in serde_yaml, which has an advisory (RUSTSEC-2024-0449, unmaintained unsafe-libyaml) for reading the Windows-only custom layouts; nothing here calls it, and deny.toml says so where it ignores the advisory. The module also has what the rest is built from. `Ring` is a list with one focused element, which monitors, workspaces and containers each keep their children in; it has the unit tests and the example upstream's version never had. `lockable_sequence` keeps locked containers at their positions when others are inserted or removed around them. `core::pathext` resolves environment variables in configured paths, and `core::config_generation` has the rules that match an application, with tests for the two shapes a rule takes in JSON (an object, and a list that must all match). Types that belong to a feature come with the feature: the socket messages, the placement rules and the animation styles are not here. The `impl_ring_elements` macro waits for the first type that uses it. Every module has a `//!` summary, and the README says what the library has. --- Cargo.lock | 679 ++++++++++++++++++++++++- Cargo.toml | 11 + README.md | 9 +- deny.toml | 11 + komorebi/Cargo.toml | 12 + komorebi/src/core/config_generation.rs | 161 ++++++ komorebi/src/core/mod.rs | 254 +++++++++ komorebi/src/core/pathext.rs | 223 ++++++++ komorebi/src/lib.rs | 8 + komorebi/src/lockable_sequence.rs | 368 ++++++++++++++ komorebi/src/ring.rs | 138 +++++ 11 files changed, 1871 insertions(+), 3 deletions(-) create mode 100644 komorebi/src/core/config_generation.rs create mode 100644 komorebi/src/core/mod.rs create mode 100644 komorebi/src/core/pathext.rs create mode 100644 komorebi/src/lib.rs create mode 100644 komorebi/src/lockable_sequence.rs create mode 100644 komorebi/src/ring.rs diff --git a/Cargo.lock b/Cargo.lock index 72b77353..3e2d3efb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,21 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "addr2line" +version = "0.27.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e567177890eb1617b1f774005b66b26b2377afd138a2ca37aae7d8f0c81429d4" +dependencies = [ + "gimli", +] + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + [[package]] name = "android_system_properties" version = "0.1.6" @@ -61,12 +76,54 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "backtrace" +version = "0.3.77" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42f4220217f3288537b83684130f42fad43320b1c3b805f1910d683d52ded24f" +dependencies = [ + "addr2line", + "cfg-if", + "libc", + "miniz_oxide", + "object", + "rustc-demangle", + "windows-link", +] + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + [[package]] name = "bitflags" version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "bs58" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4" +dependencies = [ + "tinyvec", +] + [[package]] name = "bumpalo" version = "3.20.3" @@ -91,6 +148,18 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "num-traits", + "serde", + "windows-link", +] + [[package]] name = "clap" version = "4.6.7" @@ -132,6 +201,33 @@ version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" +[[package]] +name = "color-eyre" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5920befb47832a6d61ee3a3a846565cfa39b331331e68a3b1d1116630f2f26d" +dependencies = [ + "backtrace", + "color-spantrace", + "eyre", + "indenter", + "once_cell", + "owo-colors", + "tracing-error", +] + +[[package]] +name = "color-spantrace" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8b88ea9df13354b55bc7234ebcce36e6ef896aca2e42a15de9e10edce01b427" +dependencies = [ + "once_cell", + "owo-colors", + "tracing-core", + "tracing-error", +] + [[package]] name = "colorchoice" version = "1.0.5" @@ -165,11 +261,79 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "darling" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 3.0.9", +] + +[[package]] +name = "darling_macro" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" +dependencies = [ + "darling_core", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "defmt" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4a0795ac740cb54d7b3775c9c17345f6aaecf884c01733b39d6017738e0e3e1" +dependencies = [ + "bitflags 1.3.2", + "defmt-macros", +] + +[[package]] +name = "defmt-macros" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "840bb056bd99c495c9188198a258ab787c79f306d864db3e6e8451442d6d8366" +dependencies = [ + "defmt-parser", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "defmt-parser" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71958f69fb2de856c5dd51ac9377e986ca1aa5919f931bf5395a807277f889a0" +dependencies = [ + "thiserror", +] + [[package]] name = "deranged" version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" +dependencies = [ + "serde_core", +] [[package]] name = "displaydoc" @@ -182,6 +346,18 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + [[package]] name = "errno" version = "0.3.14" @@ -192,6 +368,17 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "eyre" +version = "0.6.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08309dbcc659c5549a24ddb9b27027640641b282ef5768267c7e675558986a3" +dependencies = [ + "autocfg", + "indenter", + "once_cell", +] + [[package]] name = "find-msvc-tools" version = "0.1.15" @@ -242,25 +429,49 @@ dependencies = [ "r-efi", ] +[[package]] +name = "gimli" +version = "0.34.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1033caf0b349c518623b5396bfb2cf0bddf44f0306d543a250e5743297aafd10" + [[package]] name = "git2" version = "0.20.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b88256088d75a56f8ecfa070513a775dd9107f6530ef14919dac831af9cfe2b" dependencies = [ - "bitflags", + "bitflags 2.13.2", "libc", "libgit2-sys", "log", "url", ] +[[package]] +name = "hashbrown" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + [[package]] name = "heck" version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + [[package]] name = "iana-time-zone" version = "0.1.65" @@ -368,6 +579,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + [[package]] name = "idna" version = "1.1.0" @@ -389,6 +606,35 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "indenter" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "964de6e86d545b246d84badc0fef527924ace5134f30641c203ef52ba83f58d5" + +[[package]] +name = "indexmap" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" +dependencies = [ + "autocfg", + "hashbrown 0.12.3", + "serde", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", + "serde", + "serde_core", +] + [[package]] name = "is_debug" version = "1.1.0" @@ -401,6 +647,66 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jiff" +version = "0.2.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2b005715dcbeb0089a3c0dab99f2ff1cc3b2525323552703d648585d342a383" +dependencies = [ + "defmt", + "jiff-core", + "jiff-static", + "jiff-tzdb-platform", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", + "windows-link", +] + +[[package]] +name = "jiff-core" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e52fe76043ccecc9005d2305ebaadf7d7fc0cc89ca6baa10a94d6bc68c7128c" +dependencies = [ + "defmt", + "log", +] + +[[package]] +name = "jiff-static" +version = "0.2.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cc9817253cf7c7ee4684451bd327e88d6f3658014e54a29198625590650695c" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jiff-tzdb" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa8377070c6bae868759445e5a77f66d84f0b72f3a054bfb00e6d038b8282da7" + +[[package]] +name = "jiff-tzdb-platform" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8" +dependencies = [ + "jiff-tzdb", +] + [[package]] name = "jobserver" version = "0.1.35" @@ -427,9 +733,30 @@ name = "komorebi" version = "0.1.0" dependencies = [ "clap", + "komorebi-layouts", + "schemars 1.2.3", + "serde", + "serde_json_lenient", + "serde_with", + "strum", "version", ] +[[package]] +name = "komorebi-layouts" +version = "0.1.42" +source = "git+https://github.com/LGUG2Z/komorebi?rev=f08aa55511d77ca56ab0e789efabeb0a237a463e#f08aa55511d77ca56ab0e789efabeb0a237a463e" +dependencies = [ + "clap", + "color-eyre", + "schemars 1.2.3", + "serde", + "serde_json_lenient", + "serde_yaml", + "strum", + "tracing", +] + [[package]] name = "konst" version = "0.2.20" @@ -445,6 +772,12 @@ version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a4933f3f57a8e9d9da04db23fb153356ecaf00cbd14aee46279c33dc80925c37" +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + [[package]] name = "libc" version = "0.2.191" @@ -493,12 +826,36 @@ version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", +] + [[package]] name = "num-conv" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + [[package]] name = "num_threads" version = "0.1.8" @@ -508,6 +865,15 @@ dependencies = [ "libc", ] +[[package]] +name = "object" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd229a0361b9d0d4396176e02d65897f487eebeab7caa6d443855ee152ca0b9c" +dependencies = [ + "memchr", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -520,6 +886,12 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" +[[package]] +name = "owo-colors" +version = "4.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c45bb4a6ae1280ec0803b1ef9d3455eb50f01efbbe1447ab020f1d54fba9d8" + [[package]] name = "percent-encoding" version = "2.3.2" @@ -538,6 +910,21 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + [[package]] name = "potential_utf" version = "0.1.6" @@ -577,13 +964,39 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "ref-cast" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "rustc-demangle" +version = "0.1.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b74b56ffa8bb2830709a538c2cbcae9aa062db0d2a42563bfb09bdaae44020eb" + [[package]] name = "rustix" version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ - "bitflags", + "bitflags 2.13.2", "errno", "libc", "linux-raw-sys", @@ -596,6 +1009,49 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "schemars" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cd191f9397d57d581cddd31014772520aa448f65ef991055d7f61582c65165f" +dependencies = [ + "dyn-clone", + "ref-cast", + "serde", + "serde_json", +] + +[[package]] +name = "schemars" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" +dependencies = [ + "dyn-clone", + "ref-cast", + "schemars_derive", + "serde", + "serde_json", +] + +[[package]] +name = "schemars_derive" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1c3a92094fa7d61aa124645844facb6b554dfc797136d0f5fd1f890e2bffc69" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn 3.0.9", +] + [[package]] name = "serde" version = "1.0.229" @@ -603,6 +1059,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" dependencies = [ "serde_core", + "serde_derive", ] [[package]] @@ -625,6 +1082,88 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "serde_derive_internals" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f852137cce035d6a4df67ccce505ff6b3e9fd3a10e3e52b24dc71e650bb1a9bd" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_json_lenient" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e033097bf0d2b59a62b42c18ebbb797503839b26afdda2c4e1415cb6c813540" +dependencies = [ + "itoa", + "memchr", + "ryu", + "serde", +] + +[[package]] +name = "serde_with" +version = "3.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9adc193c780ef8f159aee8b61e2d5801aaa555e6eb0947fe45530ec506296f" +dependencies = [ + "base64", + "bs58", + "chrono", + "hex", + "indexmap 1.9.3", + "indexmap 2.14.2", + "jiff", + "schemars 0.9.0", + "schemars 1.2.3", + "serde_core", + "serde_json", + "serde_with_macros", + "time", +] + +[[package]] +name = "serde_with_macros" +version = "3.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e17bbc68e28663bbbb90df47e058aa7eda4fb445b89fe70457bb94fbccf6e49" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_yaml" +version = "0.9.34+deprecated" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47" +dependencies = [ + "indexmap 2.14.2", + "itoa", + "ryu", + "serde", + "unsafe-libyaml", +] + [[package]] name = "shadow-rs" version = "1.7.1" @@ -638,6 +1177,15 @@ dependencies = [ "tzdb", ] +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + [[package]] name = "shlex" version = "2.0.1" @@ -668,6 +1216,27 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" +[[package]] +name = "strum" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "syn" version = "2.0.119" @@ -711,6 +1280,35 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + [[package]] name = "time" version = "0.3.55" @@ -753,6 +1351,65 @@ dependencies = [ "zerovec", ] +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-error" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b1581020d7a273442f5b45074a6a57d5757ad0a47dac0e9f0bd57b81936f3db" +dependencies = [ + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "sharded-slab", + "thread_local", + "tracing-core", +] + [[package]] name = "tz-rs" version = "0.7.3" @@ -791,6 +1448,12 @@ version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" +[[package]] +name = "unsafe-libyaml" +version = "0.2.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861" + [[package]] name = "url" version = "2.5.8" @@ -815,6 +1478,12 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + [[package]] name = "vcpkg" version = "0.2.15" @@ -1023,3 +1692,9 @@ dependencies = [ "quote", "syn 3.0.9", ] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml index f3c18759..cfbbd0c5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,8 +7,19 @@ members = ["komorebi", "version"] version = "0.1.0" [workspace.dependencies] +# upstream's layouts, at a revision that has the fix for resizing a tile by dragging its edge +# (LGUG2Z/komorebi#1765) and the placement helpers komorebi for KDE uses +komorebi-layouts = { git = "https://github.com/LGUG2Z/komorebi", rev = "f08aa55511d77ca56ab0e789efabeb0a237a463e", features = [ + "schemars", +] } + clap = { version = "4", features = ["derive", "wrap_help"] } +color-eyre = "0.6" +schemars = "1.1" +serde = { version = "1", features = ["derive"] } +serde_json = { package = "serde_json_lenient", version = "0.2" } shadow-rs = "1" +tracing = "0.1" [workspace.metadata.crane] name = "komorebi-workspace" diff --git a/README.md b/README.md index 02969688..8bc7172c 100644 --- a/README.md +++ b/README.md @@ -21,9 +21,16 @@ without a checkout of the toolchain. ## Crates -- [`komorebi`](komorebi): the daemon. +- [`komorebi`](komorebi): the daemon, and the library behind it. The library has + the vocabulary the window manager is written in (`core`), the `Ring` that + holds monitors, workspaces and containers, and the lists in which some + elements are locked in place. - [`version`](version): the version string every binary reports. +The layouts, which turn a work area and a number of containers into a rectangle +for each, are `komorebi-layouts` from [komorebi](https://github.com/LGUG2Z/komorebi), +a git dependency at the revision `Cargo.toml` pins. + ## Checks `just check` runs the formatting check, clippy with warnings denied, the tests diff --git a/deny.toml b/deny.toml index 241fefff..99171afc 100644 --- a/deny.toml +++ b/deny.toml @@ -10,6 +10,11 @@ no-default-features = false [output] feature-depth = 1 +[advisories] +ignore = [ + { id = "RUSTSEC-2024-0449", reason = "unsafe-libyaml comes with serde_yaml, which komorebi-layouts reads Windows-only custom layouts with; nothing here calls it" }, +] + [licenses] allow = ["Apache-2.0", "MIT", "Unicode-3.0", "Zlib", "LicenseRef-Komorebi-2.0"] confidence-threshold = 0.8 @@ -19,6 +24,11 @@ crate = "komorebi" expression = "LicenseRef-Komorebi-2.0" license-files = [] +[[licenses.clarify]] +crate = "komorebi-layouts" +expression = "LicenseRef-Komorebi-2.0" +license-files = [] + [[licenses.clarify]] crate = "version" expression = "LicenseRef-Komorebi-2.0" @@ -35,3 +45,4 @@ external-default-features = "allow" unknown-registry = "deny" unknown-git = "deny" allow-registry = ["https://github.com/rust-lang/crates.io-index"] +allow-git = ["https://github.com/LGUG2Z/komorebi"] diff --git a/komorebi/Cargo.toml b/komorebi/Cargo.toml index 57dd1555..31244095 100644 --- a/komorebi/Cargo.toml +++ b/komorebi/Cargo.toml @@ -5,6 +5,18 @@ description = "A tiling window manager for KDE Plasma" edition = "2024" [dependencies] +komorebi-layouts = { workspace = true } version = { path = "../version" } clap = { workspace = true } +schemars = { workspace = true, optional = true } +serde = { workspace = true } +serde_with = { version = "3", features = ["schemars_1"] } +strum = { version = "0.28", features = ["derive"] } + +[dev-dependencies] +serde_json = { workspace = true } + +[features] +default = ["schemars"] +schemars = ["dep:schemars"] diff --git a/komorebi/src/core/config_generation.rs b/komorebi/src/core/config_generation.rs new file mode 100644 index 00000000..273eee18 --- /dev/null +++ b/komorebi/src/core/config_generation.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 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); + } +} diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs new file mode 100644 index 00000000..a3e0c917 --- /dev/null +++ b/komorebi/src/core/mod.rs @@ -0,0 +1,254 @@ +//! The vocabulary of the window manager: the enums and small structs that configuration, +//! commands and the layout code are written in. +//! +//! The layout types ([`DefaultLayout`], [`Rect`], [`OperationDirection`] and the rest) are +//! those of `komorebi-layouts`, re-exported here so that the rest of the crate has one place to +//! import from. [`pathext`] resolves environment variables in configured paths and +//! [`config_generation`] holds the rules that match applications by what they are called. + +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; +pub use komorebi_layouts::Axis; +pub use komorebi_layouts::CycleDirection; +pub use komorebi_layouts::DEFAULT_RATIO; +pub use komorebi_layouts::DEFAULT_SECONDARY_RATIO; +pub use komorebi_layouts::DefaultLayout; +pub use komorebi_layouts::Direction; +pub use komorebi_layouts::GridLayoutOptions; +pub use komorebi_layouts::Layout; +pub use komorebi_layouts::LayoutDefaultEntry; +pub use komorebi_layouts::LayoutOptions; +pub use komorebi_layouts::MAX_RATIO; +pub use komorebi_layouts::MAX_RATIOS; +pub use komorebi_layouts::MIN_RATIO; +pub use komorebi_layouts::OperationDirection; +pub use komorebi_layouts::Rect; +pub use komorebi_layouts::ScrollingLayoutOptions; +pub use komorebi_layouts::Sizing; +pub use komorebi_layouts::validate_ratios; + +// Keep local modules that aren't in komorebi-layouts +pub mod config_generation; +pub mod pathext; + +#[derive( + Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize, Display, EnumString, ValueEnum, +)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Operation behavior for temporarily unmanaged and floating windows +pub enum OperationBehaviour { + /// Process commands on temporarily unmanaged/floated windows + #[default] + Op, + /// Ignore commands on temporarily unmanaged/floated windows + NoOp, +} + +#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, PartialEq)] +pub struct WindowManagementBehaviour { + /// The current WindowContainerBehaviour to be used + pub current_behaviour: WindowContainerBehaviour, + /// Override of `current_behaviour` to open new windows as floating windows + /// that can be later toggled to tiled, when false it will default to + /// `current_behaviour` again. + pub float_override: bool, + /// Determines if a new window should be spawned floating when on the floating layer and the + /// floating layer behavior is set to float. This value is always calculated when checking for + /// the management behavior on a specific workspace. + pub floating_layer_override: bool, + /// The floating layer behavior to be used if the float override is being used + pub floating_layer_behaviour: FloatingLayerBehaviour, + /// The `Placement` to be used when toggling a window to float + pub toggle_float_placement: Placement, + /// The `Placement` to be used when spawning a window on the floating layer with the + /// `FloatingLayerBehaviour` set to `FloatingLayerBehaviour::Float` + pub floating_layer_placement: Placement, + /// The `Placement` to be used when spawning a window with float override active + pub float_override_placement: Placement, + /// The `Placement` to be used when spawning a window that matches a 'floating_applications' rule + 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(Copy, Clone, Debug, PartialEq, Serialize, Deserialize, Display, EnumString, ValueEnum)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Focus follows mouse implementation +/// +/// The two exist on Windows. On KDE the compositor does it, so both ask KWin for its +/// "focus follows mouse" focus policy. +pub enum FocusFollowsMouseImplementation { + /// Custom FFM implementation (slightly more CPU-intensive) + Komorebi, + /// Native (legacy) Windows FFM implementation + Windows, +} + +#[derive( + Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize, Display, EnumString, ValueEnum, +)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Move behavior when the operation works across a monitor boundary +pub enum MoveBehaviour { + /// Swap the window container with the window container at the edge of the adjacent monitor + #[default] + Swap, + /// Insert the window container into the focused workspace on the adjacent monitor + Insert, + /// Do nothing if trying to move a window container in the direction of an adjacent monitor + NoOp, +} + +#[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, +} + +#[derive( + Clone, Copy, Debug, Default, Serialize, Deserialize, Display, EnumString, ValueEnum, PartialEq, +)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Behavior when focusing in a direction while a monocle container is active +pub enum MonocleFocusBehaviour { + /// Cycle the monocle container to the next/previous container in the workspace + Cycle, + /// Do nothing, allowing focus to fall through to cross-monitor logic + #[default] + NoOp, +} + +#[derive( + Copy, Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Display, EnumString, ValueEnum, +)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Application identifier +pub enum ApplicationIdentifier { + /// Executable name + #[serde(alias = "exe")] + Exe, + /// Role or subrole + #[serde(alias = "class")] + Class, + /// Window title + #[serde(alias = "title")] + Title, + /// Executable path + #[serde(alias = "path")] + Path, +} + +#[derive( + Copy, + Clone, + Debug, + Default, + Serialize, + Deserialize, + Display, + EnumString, + ValueEnum, + PartialEq, + Eq, + Hash, +)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub enum WindowKind { + Single, + Stack, + Monocle, + #[default] + Unfocused, + UnfocusedLocked, + Floating, +} diff --git a/komorebi/src/core/pathext.rs b/komorebi/src/core/pathext.rs new file mode 100644 index 00000000..729f7e88 --- /dev/null +++ b/komorebi/src/core/pathext.rs @@ -0,0 +1,223 @@ +//! Resolving environment variables in the paths of the configuration. + +use std::collections::HashMap; +use std::ffi::OsStr; +use std::path::Component; +use std::path::Path; +use std::path::PathBuf; + +use serde::Deserialize; +use serde::Serialize; + +/// Path extension trait +pub trait PathExt { + /// Resolve environment variable components in a path. + /// + /// Resolves the following formats: + /// - CMD: `%variable%` + /// - PowerShell: `$Env:variable` + /// - Bash: `$variable`. + fn replace_env(&self) -> PathBuf; +} + +/// Blanket implementation for all types that can be converted to a `Path`. +impl> PathExt for P { + fn replace_env(&self) -> PathBuf { + let mut out = PathBuf::new(); + + for c in self.as_ref().components() { + match c { + #[allow(unused_mut)] + Component::Normal(mut c) => { + #[cfg(target_os = "windows")] + // Special case for ~ and $HOME, replace with $Env:USERPROFILE + if c == OsStr::new("~") || c.eq_ignore_ascii_case("$HOME") { + c = OsStr::new("$Env:USERPROFILE"); + } + + #[cfg(unix)] + // Special case for ~, replace with $HOME (macOS and Linux) + if c == OsStr::new("~") { + c = OsStr::new("$HOME"); + } + + let bytes = c.as_encoded_bytes(); + + // %LOCALAPPDATA% + let var = if bytes[0] == b'%' && bytes[bytes.len() - 1] == b'%' { + Some(&bytes[1..bytes.len() - 1]) + } else { + // prefix length is 5 for $Env: and 1 for $ + // so we take the minimum of 5 and the length of the bytes + let prefix = &bytes[..5.min(bytes.len())]; + let prefix = unsafe { OsStr::from_encoded_bytes_unchecked(prefix) }; + + // $Env:LOCALAPPDATA + if prefix.eq_ignore_ascii_case("$Env:") { + Some(&bytes[5..]) + } else if bytes[0] == b'$' { + // $LOCALAPPDATA + Some(&bytes[1..]) + } else { + // not a variable + None + } + }; + + // if component is a variable, get the value from the environment + if let Some(var) = var { + let var = unsafe { OsStr::from_encoded_bytes_unchecked(var) }; + if let Some(value) = std::env::var_os(var) { + out.push(value); + continue; + } + } + + // if not a variable, or a value couldn't be obtained from environemnt + // then push the component as is + out.push(c); + } + + // other components are pushed as is + _ => out.push(c), + } + } + + out + } +} + +/// Replace environment variables in a path. This is a wrapper around +/// [`PathExt::replace_env`] to be used in Clap arguments parsing. +pub fn replace_env_in_path(input: &str) -> Result { + Ok(input.replace_env()) +} + +/// A wrapper around [`PathBuf`] that has a custom [Deserialize] implementation +/// that uses [`PathExt::replace_env`] to resolve environment variables +#[derive(Clone, Debug)] +pub struct ResolvedPathBuf(PathBuf); + +impl ResolvedPathBuf { + /// Create a new [`ResolvedPathBuf`] from a [`PathBuf`] + pub fn new(path: PathBuf) -> Self { + Self(path.replace_env()) + } +} + +impl From for PathBuf { + fn from(path: ResolvedPathBuf) -> Self { + path.0 + } +} + +impl serde_with::SerializeAs for ResolvedPathBuf { + fn serialize_as(path: &PathBuf, serializer: S) -> Result + where + S: serde::Serializer, + { + path.serialize(serializer) + } +} + +impl<'de> serde_with::DeserializeAs<'de, PathBuf> for ResolvedPathBuf { + fn deserialize_as(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + let path = PathBuf::deserialize(deserializer)?; + Ok(path.replace_env()) + } +} + +#[cfg(feature = "schemars")] +impl serde_with::schemars_1::JsonSchemaAs for ResolvedPathBuf { + fn schema_name() -> std::borrow::Cow<'static, str> { + std::borrow::Cow::Borrowed("PathBuf") + } + + fn json_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema { + schemars::json_schema!({ + "type": "string", + "description": "A file system path. Environment variables like $VAR are automatically resolved." + }) + } +} + +/// Custom deserializer for [`Option>`] that uses +/// [`PathExt::replace_env`] to resolve environment variables in the paths. +/// +/// This is used in `WorkspaceConfig` struct because we can't use +/// #[serde_with::serde_as] as it doesn't handle [`Option>`] +/// quite well and generated compiler errors that can't be fixed because of Rust's orphan rule. +pub fn resolve_option_hashmap_usize_path<'de, D>( + deserializer: D, +) -> Result>, D::Error> +where + D: serde::Deserializer<'de>, +{ + let map = Option::>::deserialize(deserializer)?; + Ok(map.map(|map| map.into_iter().map(|(k, v)| (k, v.replace_env())).collect())) +} + +#[cfg(test)] +mod tests { + use super::*; + + // helper functions + fn expected>(p: P) -> PathBuf { + // Ensure that the path is using the correct path separator for the OS. + p.as_ref().components().collect::() + } + + fn resolve>(p: P) -> PathBuf { + p.replace_env() + } + + #[test] + fn resolves_env_vars() { + // Set a variable for testing + unsafe { + std::env::set_var("VAR", "VALUE"); + } + + // %VAR% format + assert_eq!(resolve("/path/%VAR%/d"), expected("/path/VALUE/d")); + // $env:VAR format + assert_eq!(resolve("/path/$env:VAR/d"), expected("/path/VALUE/d")); + // $VAR format + assert_eq!(resolve("/path/$VAR/d"), expected("/path/VALUE/d")); + + // non-existent variable + assert_eq!(resolve("/path/%ASD%/to/d"), expected("/path/%ASD%/to/d")); + assert_eq!( + resolve("/path/$env:ASD/to/d"), + expected("/path/$env:ASD/to/d") + ); + assert_eq!(resolve("/path/$ASD/to/d"), expected("/path/$ASD/to/d")); + + #[cfg(target_os = "windows")] + { + // Set a $env:USERPROFILE variable for testing + unsafe { + std::env::set_var("USERPROFILE", "C:\\Users\\user"); + } + + // ~ and $HOME should be replaced with $Env:USERPROFILE + assert_eq!(resolve("~"), expected("C:\\Users\\user")); + assert_eq!(resolve("$HOME"), expected("C:\\Users\\user")); + } + + #[cfg(unix)] + { + // Set a $env:USERPROFILE variable for testing + unsafe { + std::env::set_var("HOME", "/Users/user"); + } + + // ~ and $HOME should be replaced with $Env:USERPROFILE + assert_eq!(resolve("~"), expected("/Users/user")); + assert_eq!(resolve("$HOME"), expected("/Users/user")); + } + } +} diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs new file mode 100644 index 00000000..b42ba833 --- /dev/null +++ b/komorebi/src/lib.rs @@ -0,0 +1,8 @@ +//! The komorebi daemon's library: the vocabulary the window manager is written in and the data +//! structures it is built from. + +#[macro_use] +pub mod ring; + +pub mod core; +pub mod lockable_sequence; diff --git a/komorebi/src/lockable_sequence.rs b/komorebi/src/lockable_sequence.rs new file mode 100644 index 00000000..421eb22d --- /dev/null +++ b/komorebi/src/lockable_sequence.rs @@ -0,0 +1,368 @@ +//! Lists in which some elements are locked in place. +//! +//! A locked container keeps its position in the layout when others are inserted, removed or +//! swapped around it. [`LockableSequence`] does that bookkeeping for a [`VecDeque`]. + +use std::collections::VecDeque; + +/// A trait for types that can be marked as locked or unlocked. +pub trait Lockable { + /// Returns `true` if the item is locked. + fn locked(&self) -> bool; + /// Sets the locked state of the item. + fn set_locked(&mut self, locked: bool) -> &mut Self; +} + +/// A sequence supporting insertion, removal, and swapping of elements while preserving the absolute +/// positions of locked items. +pub trait LockableSequence { + /// Inserts a value at `idx`, keeping locked elements at their absolute positions. + fn insert_respecting_locks(&mut self, idx: usize, value: T) -> usize; + /// Removes the element at `idx`, keeping locked elements at their absolute positions. + fn remove_respecting_locks(&mut self, idx: usize) -> Option; + /// Swaps the elements at indices `i` and `j`, keeping locked elements at their absolute positions. + fn swap_respecting_locks(&mut self, i: usize, j: usize); +} + +impl LockableSequence for VecDeque { + /// Insert `value` at logical index `idx`, with trying to keep locked elements + /// (`is_locked()`) anchored at their original positions. + /// + /// Returns the final index of the inserted element. + fn insert_respecting_locks(&mut self, mut idx: usize, value: T) -> usize { + // 1. Bounds check: if index is out of range, simply append. + if idx >= self.len() { + self.push_back(value); + return self.len() - 1; // last index + } + + // 2. Normal VecDeque insertion + self.insert(idx, value); + + // 3. Walk left-to-right once, swapping any misplaced locked element. After + // the VecDeque::insert all items after `idx` have moved right by one. For every locked + // element that is now to the right of an unlocked one, swap it back left exactly once. + for index in (idx + 1)..self.len() { + if self[index].locked() && !self[index - 1].locked() { + self.swap(index - 1, index); + + // If the element we just inserted participated in the swap, + // update `idx` so we can return its final location. + if idx == index - 1 { + idx = index; + } + } + } + idx + } + + /// Remove element at `idx`, with trying to keep locked elements + /// (`is_locked()`) anchored at their original positions. + /// + /// Returns the removed element, or `None` if `idx` is out of bounds. + fn remove_respecting_locks(&mut self, idx: usize) -> Option { + // 1. Bounds check: if index is out of range, do nothing. + if idx >= self.len() { + return None; + } + + // 2. Remove the element at the requested index. + // All elements after idx are now shifted left by 1. + let removed = self.remove(idx)?; + + // 3. If less than 2 elements remain, nothing to shift. + if self.len() < 2 { + return Some(removed); + } + + // 4. Iterate from the element just after the removed spot up to the second-to-last + // element, right-to-left. This loop "fixes" locked elements that were shifted left + // off their anchored positions: If a locked element now has an unlocked element + // to its right, swap them back to restore locked order. + for index in (idx..self.len() - 1).rev() { + // If current is locked and the next one is not locked, swap them. + if self[index].locked() && !self[index + 1].locked() { + self.swap(index, index + 1); + } + } + + // 5. Return the removed value. + Some(removed) + } + + /// Swaps the elements at indices `i` and `j`, along with their `locked` status, ensuring + /// the lock state remains associated with the position rather than the element itself. + fn swap_respecting_locks(&mut self, i: usize, j: usize) { + self.swap(i, j); + let locked_i = self[i].locked(); + let locked_j = self[j].locked(); + self[i].set_locked(locked_j); + self[j].set_locked(locked_i); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[derive(Debug, PartialEq)] + struct TestItem { + val: i32, + locked: bool, + } + + impl Lockable for TestItem { + fn locked(&self) -> bool { + self.locked + } + + fn set_locked(&mut self, locked: bool) -> &mut Self { + self.locked = locked; + self + } + } + + fn vals(v: &VecDeque) -> Vec { + v.iter().map(|x| x.val).collect() + } + + fn test_deque(items: &[(i32, bool)]) -> VecDeque { + items + .iter() + .cloned() + .map(|(val, locked)| TestItem { val, locked }) + .collect() + } + + #[test] + fn test_insert_respecting_locks() { + // Test case 1: Basic insertion with locked index + { + // Lock index 2 + let mut ring = test_deque(&[(0, false), (1, false), (2, true), (3, false), (4, false)]); + // Insert at index 0, should shift elements while keeping index 2 locked + ring.insert_respecting_locks( + 0, + TestItem { + val: 99, + locked: false, + }, + ); + // Element '2' remains at index 2, element '1' that was at index 1 is now at index 3 + assert_eq!(vals(&ring), vec![99, 0, 2, 1, 3, 4]); + } + + // Test case 2: Insert at a locked index (should insert after locked) + { + // Lock index 2 + let mut ring = test_deque(&[(0, false), (1, false), (2, true), (3, false), (4, false)]); + // Try to insert at locked index 2, should insert at index 3 instead + let actual_index = ring.insert_respecting_locks( + 2, + TestItem { + val: 99, + locked: false, + }, + ); + assert_eq!(actual_index, 3); + assert_eq!(vals(&ring), vec![0, 1, 2, 99, 3, 4]); + } + + // Test case 3: Multiple locked indices + { + // Lock index 1 and 3 + let mut ring = test_deque(&[(0, false), (1, true), (2, false), (3, true), (4, false)]); + // Insert at index 0, should maintain locked indices + ring.insert_respecting_locks( + 0, + TestItem { + val: 99, + locked: false, + }, + ); + // Elements '1' and '3' remain at indices 1 and 3 + assert_eq!(vals(&ring), vec![99, 1, 0, 3, 2, 4]); + } + + // Test case 4: Insert at end + { + // Lock index 2 + let mut ring = test_deque(&[(0, false), (1, false), (2, true), (3, false), (4, false)]); + let actual_index = ring.insert_respecting_locks( + 5, + TestItem { + val: 99, + locked: false, + }, + ); + assert_eq!(actual_index, 5); + assert_eq!(vals(&ring), vec![0, 1, 2, 3, 4, 99]); + } + + // Test case 5: Empty ring + { + let mut ring = test_deque(&[]); + // Insert into empty deque + let actual_index = ring.insert_respecting_locks( + 0, + TestItem { + val: 99, + locked: false, + }, + ); + assert_eq!(actual_index, 0); + assert_eq!(vals(&ring), vec![99]); + } + + // Test case 6: All indices locked + { + // Lock all indices + let mut ring = test_deque(&[(0, true), (1, true), (2, true), (3, true), (4, true)]); + // Try to insert at index 2, should insert at the end + let actual_index = ring.insert_respecting_locks( + 2, + TestItem { + val: 99, + locked: false, + }, + ); + assert_eq!(actual_index, 5); + assert_eq!(vals(&ring), vec![0, 1, 2, 3, 4, 99]); + } + + // Test case 7: Consecutive locked indices + { + // Lock index 2 and 3 + let mut ring = test_deque(&[(0, false), (1, false), (2, true), (3, true), (4, false)]); + // Insert at index 1, should maintain consecutive locked indices + ring.insert_respecting_locks( + 1, + TestItem { + val: 99, + locked: false, + }, + ); + // Elements '2' and '3' remain at indices 2 and 3 + assert_eq!(vals(&ring), vec![0, 99, 2, 3, 1, 4]); + } + } + + #[test] + fn test_remove_respecting_locks() { + // Test case 1: Remove a non-locked index before a locked index + { + // Lock index 2 + let mut ring = test_deque(&[(0, false), (1, false), (2, true), (3, false), (4, false)]); + let removed = ring.remove_respecting_locks(0); + assert_eq!(removed.map(|x| x.val), Some(0)); + // Elements '2' remain at index 2 + assert_eq!(vals(&ring), vec![1, 3, 2, 4]); + } + + // Test case 2: Remove a locked index + { + // Lock index 2 + let mut ring = test_deque(&[(0, false), (1, false), (2, true), (3, false), (4, false)]); + let removed = ring.remove_respecting_locks(2); + assert_eq!(removed.map(|x| x.val), Some(2)); + // Elements should stay at the same places + assert_eq!(vals(&ring), vec![0, 1, 3, 4]); + } + + // Test case 3: Remove an index after a locked index + { + // Lock index 1 + let mut ring = test_deque(&[(0, false), (1, true), (2, false), (3, false), (4, false)]); + let removed = ring.remove_respecting_locks(3); + assert_eq!(removed.map(|x| x.val), Some(3)); + // Elements should stay at the same places + assert_eq!(vals(&ring), vec![0, 1, 2, 4]); + } + + // Test case 4: Multiple locked indices + { + // Lock index 1 and 3 + let mut ring = test_deque(&[(0, false), (1, true), (2, false), (3, true), (4, false)]); + let removed = ring.remove_respecting_locks(0); + assert_eq!(removed.map(|x| x.val), Some(0)); + // Elements '1' and '3' remain at indices '1' and '3' + assert_eq!(vals(&ring), vec![2, 1, 4, 3]); + } + + // Test case 5: Remove the last element + { + // Lock index 2 + let mut ring = test_deque(&[(0, false), (1, false), (2, true), (3, false), (4, false)]); + let removed = ring.remove_respecting_locks(4); + assert_eq!(removed.map(|x| x.val), Some(4)); + // Index 2 should still be at the same place + assert_eq!(vals(&ring), vec![0, 1, 2, 3]); + } + + // Test case 6: Invalid index + { + // Lock index 2 + let mut ring = test_deque(&[(0, false), (1, false), (2, true), (3, false), (4, false)]); + let removed = ring.remove_respecting_locks(10); + assert_eq!(removed, None); + // Deque unchanged + assert_eq!(vals(&ring), vec![0, 1, 2, 3, 4]); + } + + // Test case 7: Remove enough elements to make a locked index invalid + { + // Lock index 2 + let mut ring = test_deque(&[(0, false), (1, false), (2, true)]); + ring.remove_respecting_locks(0); + // Index 2 should now be '1' + assert_eq!(vals(&ring), vec![1, 2]); + } + + // Test case 8: Removing an element before multiple locked indices + { + // Lock index 2 and 4 + let mut ring = test_deque(&[ + (0, false), + (1, false), + (2, true), + (3, false), + (4, true), + (5, false), + ]); + let removed = ring.remove_respecting_locks(1); + assert_eq!(removed.map(|x| x.val), Some(1)); + // Both indices should still be at the same place + assert_eq!(vals(&ring), vec![0, 3, 2, 5, 4]); + } + } + + #[test] + fn test_swap_respecting_locks_various_cases() { + // Swap unlocked and locked + let mut ring = test_deque(&[(0, false), (1, true), (2, false), (3, false)]); + ring.swap_respecting_locks(0, 1); + assert_eq!(vals(&ring), vec![1, 0, 2, 3]); + assert!(!ring[0].locked); + assert!(ring[1].locked); + ring.swap_respecting_locks(0, 1); + assert_eq!(vals(&ring), vec![0, 1, 2, 3]); + assert!(!ring[0].locked); + assert!(ring[1].locked); + + // Both locked + let mut ring = test_deque(&[(0, true), (1, false), (2, true)]); + ring.swap_respecting_locks(0, 2); + assert_eq!(vals(&ring), vec![2, 1, 0]); + assert!(ring[0].locked); + assert!(!ring[1].locked); + assert!(ring[2].locked); + + // Both unlocked + let mut ring = test_deque(&[(0, false), (1, true), (2, false)]); + ring.swap_respecting_locks(0, 2); + assert_eq!(vals(&ring), vec![2, 1, 0]); + assert!(!ring[0].locked); + assert!(ring[1].locked); + assert!(!ring[2].locked); + } +} diff --git a/komorebi/src/ring.rs b/komorebi/src/ring.rs new file mode 100644 index 00000000..0e16e2fb --- /dev/null +++ b/komorebi/src/ring.rs @@ -0,0 +1,138 @@ +//! [`Ring`], a list of elements with one of them focused. +//! +//! Monitors, workspaces and containers each keep their children in a ring, so that "the focused +//! one" is the same thing everywhere. + +use std::collections::VecDeque; + +use serde::Deserialize; +use serde::Serialize; + +/// A list of elements, one of which is focused. +/// +/// The focused index is not guaranteed to be in range: [`Ring::focus`] stores what it is given, and +/// [`Ring::focused`] and [`Ring::focused_mut`] return `None` when it is out of range, as it is for +/// an empty ring. +/// +/// # Example +/// +/// ```rust +/// use komorebi::ring::Ring; +/// +/// let mut ring = Ring::default(); +/// ring.elements_mut().push_back("a"); +/// ring.elements_mut().push_back("b"); +/// ring.focus(1); +/// +/// assert_eq!(ring.focused(), Some(&"b")); +/// assert_eq!(ring.focused_idx(), 1); +/// ``` +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct Ring { + elements: VecDeque, + focused: usize, +} + +impl Default for Ring { + fn default() -> Self { + Self { + elements: VecDeque::default(), + focused: 0, + } + } +} + +impl Ring { + /// The elements, in order. + pub const fn elements(&self) -> &VecDeque { + &self.elements + } + + /// The elements, in order, to add to or remove from. + pub fn elements_mut(&mut self) -> &mut VecDeque { + &mut self.elements + } + + /// Focuses the element at `idx`. + pub fn focus(&mut self, idx: usize) { + self.focused = idx; + } + + /// The focused element, if the focused index is in range. + pub fn focused(&self) -> Option<&T> { + self.elements.get(self.focused) + } + + /// The index that is focused, in range or not. + pub const fn focused_idx(&self) -> usize { + self.focused + } + + /// The focused element, to change, if the focused index is in range. + pub fn focused_mut(&mut self) -> Option<&mut T> { + self.elements.get_mut(self.focused) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn an_empty_ring_focuses_nothing() { + let mut ring: Ring = Ring::default(); + + assert_eq!(ring.focused(), None); + assert_eq!(ring.focused_mut(), None); + assert_eq!(ring.focused_idx(), 0); + } + + #[test] + fn focus_selects_the_element_at_that_index() { + let mut ring = Ring::default(); + ring.elements_mut().extend([10, 20, 30]); + + ring.focus(2); + + assert_eq!(ring.focused(), Some(&30)); + assert_eq!(ring.focused_idx(), 2); + } + + #[test] + fn the_focused_element_can_be_changed_in_place() { + let mut ring = Ring::default(); + ring.elements_mut().extend([1, 2]); + ring.focus(1); + + if let Some(element) = ring.focused_mut() { + *element = 5; + } + + assert_eq!(ring.elements(), &[1, 5]); + } + + #[test] + fn a_focused_index_past_the_end_focuses_nothing() { + let mut ring = Ring::default(); + ring.elements_mut().push_back('a'); + + ring.focus(3); + + assert_eq!(ring.focused(), None); + assert_eq!(ring.focused_idx(), 3); + } + + #[test] + fn a_ring_round_trips_through_json() { + let mut ring = Ring::default(); + ring.elements_mut() + .extend(["a".to_string(), "b".to_string()]); + ring.focus(1); + + let json = serde_json::to_string(&ring).expect("serializes"); + let back: Ring = serde_json::from_str(&json).expect("deserializes"); + + assert_eq!(back, ring); + } +}