From d9a8634559c112ce0630abedc4583eb686d3422d Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sun, 21 Sep 2025 19:33:46 -0700 Subject: [PATCH] feat(config): migrate most of static config This commit migrates everything needed to get to the point where I can load my existing Windows komorebi.json file and have the key parts working as expected (workspace rules, manage rules, ignore rules, floating applications etc.) A lot of lift and shift, some wrangling things to work with the subtle changes in this codebase, but overall I'm very happy with this. --- Cargo.lock | 259 ++++- deny.toml | 4 +- dependencies.json | 28 +- komorebi/Cargo.toml | 1 + komorebi/src/core/mod.rs | 15 + komorebi/src/core/rect.rs | 4 +- komorebi/src/lib.rs | 4 + komorebi/src/main.rs | 62 +- komorebi/src/monitor.rs | 7 + komorebi/src/process_command.rs | 4 + komorebi/src/process_event.rs | 23 + komorebi/src/static_config.rs | 1683 +++++++++++++++++++++++++++++++ komorebi/src/window.rs | 580 +++++++++++ komorebi/src/window_manager.rs | 305 ++++++ komorebi/src/workspace.rs | 118 +++ 15 files changed, 3071 insertions(+), 26 deletions(-) create mode 100644 komorebi/src/static_config.rs diff --git a/Cargo.lock b/Cargo.lock index e2a6c09d..8a867a2c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -112,6 +112,12 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + [[package]] name = "bitflags" version = "2.9.4" @@ -351,7 +357,7 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "89a09f22a6c6069a18470eb92d2298acf25463f14256d24778e1230d789a2aec" dependencies = [ - "bitflags", + "bitflags 2.9.4", "objc2", ] @@ -387,6 +393,27 @@ dependencies = [ "once_cell", ] +[[package]] +name = "file-id" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13be71e6ca82e91bc0cb862bebaac0b2d1924a5a1d970c822b2f98b63fda8c3" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "filetime" +version = "0.2.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc0505cd1b6fa6580283f6bdf70a73fcf4aba1184038c90902b92b3dd0df63ed" +dependencies = [ + "cfg-if", + "libc", + "libredox", + "windows-sys 0.60.2", +] + [[package]] name = "find-msvc-tools" version = "0.1.1" @@ -399,6 +426,15 @@ version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" +[[package]] +name = "fsevent-sys" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76ee7a02da4d231650c7cea31349b889be2f45ddb3ef3032d2ec8185f6313fd2" +dependencies = [ + "libc", +] + [[package]] name = "getrandom" version = "0.2.16" @@ -440,6 +476,17 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "hotwatch" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9140219159163c92eb58c37955a0cc57c5814c3c44521955aae376064c668756" +dependencies = [ + "log", + "notify", + "notify-debouncer-full", +] + [[package]] name = "iana-time-zone" version = "0.1.64" @@ -499,6 +546,26 @@ dependencies = [ "serde_core", ] +[[package]] +name = "inotify" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8069d3ec154eb856955c1c0fbffefbf5f3c40a104ec912d4797314c1801abff" +dependencies = [ + "bitflags 1.3.2", + "inotify-sys", + "libc", +] + +[[package]] +name = "inotify-sys" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e05c02b5e89bff3b946cedeca278abc628fe811e604f027c45a8aa3cf793d0eb" +dependencies = [ + "libc", +] + [[package]] name = "is_terminal_polyfill" version = "1.70.1" @@ -530,6 +597,7 @@ dependencies = [ "crossbeam-channel", "ctrlc", "dirs", + "hotwatch", "lazy_static", "objc2", "objc2-app-kit", @@ -569,6 +637,26 @@ dependencies = [ "pastey", ] +[[package]] +name = "kqueue" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eac30106d7dce88daf4a3fcb4879ea939476d5074a9b7ddd0fb97fa4bed5596a" +dependencies = [ + "kqueue-sys", + "libc", +] + +[[package]] +name = "kqueue-sys" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed9625ffda8729b85e45cf04090035ac368927b8cebc34898e7c120f52e4838b" +dependencies = [ + "bitflags 1.3.2", + "libc", +] + [[package]] name = "lazy_static" version = "1.5.0" @@ -587,8 +675,9 @@ version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "416f7e718bdb06000964960ffa43b4335ad4012ae8b99060261aa4a8088d5ccb" dependencies = [ - "bitflags", + "bitflags 2.9.4", "libc", + "redox_syscall", ] [[package]] @@ -637,18 +726,62 @@ dependencies = [ "adler2", ] +[[package]] +name = "mio" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4a650543ca06a924e8b371db273b2756685faae30f8487da1b56505a8f78b0c" +dependencies = [ + "libc", + "log", + "wasi", + "windows-sys 0.48.0", +] + [[package]] name = "nix" version = "0.30.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "74523f3a35e05aba87a1d978330aef40f67b0304ac79c1c00b294c9830543db6" dependencies = [ - "bitflags", + "bitflags 2.9.4", "cfg-if", "cfg_aliases", "libc", ] +[[package]] +name = "notify" +version = "6.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6205bd8bb1e454ad2e27422015fb5e4f2bcc7e08fa8f27058670d208324a4d2d" +dependencies = [ + "bitflags 2.9.4", + "crossbeam-channel", + "filetime", + "fsevent-sys", + "inotify", + "kqueue", + "libc", + "log", + "mio", + "walkdir", + "windows-sys 0.48.0", +] + +[[package]] +name = "notify-debouncer-full" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4812c1eb49be776fb8df4961623bdc01ec9dfdc1abe8211ceb09150a2e64219" +dependencies = [ + "crossbeam-channel", + "file-id", + "notify", + "parking_lot", + "walkdir", +] + [[package]] name = "nu-ansi-term" version = "0.50.1" @@ -688,7 +821,7 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6f29f568bec459b0ddff777cec4fe3fd8666d82d5a40ebd0ff7e66134f89bcc" dependencies = [ - "bitflags", + "bitflags 2.9.4", "block2", "libc", "objc2", @@ -707,7 +840,7 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c9abc05b1f757ebfbd72f4f3f9a515662c67dfe66b26e71b37d818f56a1c2f17" dependencies = [ - "bitflags", + "bitflags 2.9.4", "libc", "objc2", "objc2-core-foundation", @@ -722,7 +855,7 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "17614fdcd9b411e6ff1117dfb1d0150f908ba83a7df81b1f118005fe0a8ea15d" dependencies = [ - "bitflags", + "bitflags 2.9.4", "objc2", "objc2-foundation", ] @@ -733,7 +866,7 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "291fbbf7d29287518e8686417cf7239c74700fd4b607623140a7d4a3c834329d" dependencies = [ - "bitflags", + "bitflags 2.9.4", "objc2", "objc2-foundation", ] @@ -744,7 +877,7 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c10c2894a6fed806ade6027bcd50662746363a9589d3ec9d9bef30a4e4bc166" dependencies = [ - "bitflags", + "bitflags 2.9.4", "block2", "dispatch2", "libc", @@ -757,7 +890,7 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "989c6c68c13021b5c2d6b71456ebb0f9dc78d752e86a98da7c716f4f9470f5a4" dependencies = [ - "bitflags", + "bitflags 2.9.4", "block2", "dispatch2", "libc", @@ -801,7 +934,7 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "900831247d2fe1a09a683278e5384cfb8c80c79fe6b166f9d14bfdde0ea1b03c" dependencies = [ - "bitflags", + "bitflags 2.9.4", "block2", "libc", "objc2", @@ -814,7 +947,7 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7282e9ac92529fa3457ce90ebb15f4ecbc383e8338060960760fa2cf75420c3c" dependencies = [ - "bitflags", + "bitflags 2.9.4", "objc2", "objc2-core-foundation", ] @@ -825,7 +958,7 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f246c183239540aab1782457b35ab2040d4259175bd1d0c58e46ada7b47a874" dependencies = [ - "bitflags", + "bitflags 2.9.4", "objc2", "objc2-foundation", ] @@ -836,7 +969,7 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "90ffb6a0cd5f182dc964334388560b12a57f7b74b3e2dec5e2722aa2dfb2ccd5" dependencies = [ - "bitflags", + "bitflags 2.9.4", "objc2", "objc2-foundation", ] @@ -847,7 +980,7 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e1f8e0ef3ab66b08c42644dcb34dba6ec0a574bbd8adbb8bdbdc7a2779731a44" dependencies = [ - "bitflags", + "bitflags 2.9.4", "objc2", "objc2-core-foundation", ] @@ -950,7 +1083,7 @@ version = "0.5.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5407465600fb0548f1442edf71dd20683c6ed326200ace4b1ef0763521bb3b77" dependencies = [ - "bitflags", + "bitflags 2.9.4", ] [[package]] @@ -1025,7 +1158,7 @@ version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cd15f8a2c5551a84d56efdc1cd049089e409ac19a3072d5037a17fd70719ff3e" dependencies = [ - "bitflags", + "bitflags 2.9.4", "errno", "libc", "linux-raw-sys", @@ -1044,6 +1177,15 @@ version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + [[package]] name = "schemars" version = "0.9.0" @@ -1378,6 +1520,16 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" @@ -1443,6 +1595,15 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.0", +] + [[package]] name = "windows-core" version = "0.62.0" @@ -1508,6 +1669,15 @@ dependencies = [ "windows-link 0.2.0", ] +[[package]] +name = "windows-sys" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +dependencies = [ + "windows-targets 0.48.5", +] + [[package]] name = "windows-sys" version = "0.52.0" @@ -1535,6 +1705,21 @@ dependencies = [ "windows-link 0.2.0", ] +[[package]] +name = "windows-targets" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" +dependencies = [ + "windows_aarch64_gnullvm 0.48.5", + "windows_aarch64_msvc 0.48.5", + "windows_i686_gnu 0.48.5", + "windows_i686_msvc 0.48.5", + "windows_x86_64_gnu 0.48.5", + "windows_x86_64_gnullvm 0.48.5", + "windows_x86_64_msvc 0.48.5", +] + [[package]] name = "windows-targets" version = "0.52.6" @@ -1568,6 +1753,12 @@ dependencies = [ "windows_x86_64_msvc 0.53.0", ] +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" + [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" @@ -1580,6 +1771,12 @@ version = "0.53.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "86b8d5f90ddd19cb4a147a5fa63ca848db3df085e25fee3cc10b39b6eebae764" +[[package]] +name = "windows_aarch64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" + [[package]] name = "windows_aarch64_msvc" version = "0.52.6" @@ -1592,6 +1789,12 @@ version = "0.53.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c7651a1f62a11b8cbd5e0d42526e55f2c99886c77e007179efff86c2b137e66c" +[[package]] +name = "windows_i686_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" + [[package]] name = "windows_i686_gnu" version = "0.52.6" @@ -1616,6 +1819,12 @@ version = "0.53.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ce6ccbdedbf6d6354471319e781c0dfef054c81fbc7cf83f338a4296c0cae11" +[[package]] +name = "windows_i686_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" + [[package]] name = "windows_i686_msvc" version = "0.52.6" @@ -1628,6 +1837,12 @@ version = "0.53.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "581fee95406bb13382d2f65cd4a908ca7b1e4c2f1917f143ba16efe98a589b5d" +[[package]] +name = "windows_x86_64_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" + [[package]] name = "windows_x86_64_gnu" version = "0.52.6" @@ -1640,6 +1855,12 @@ version = "0.53.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2e55b5ac9ea33f2fc1716d1742db15574fd6fc8dadc51caab1c16a3d3b4190ba" +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" + [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" @@ -1652,6 +1873,12 @@ version = "0.53.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0a6e035dd0599267ce1ee132e51c27dd29437f63325753051e71dd9e42406c57" +[[package]] +name = "windows_x86_64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" + [[package]] name = "windows_x86_64_msvc" version = "0.52.6" diff --git a/deny.toml b/deny.toml index cb8b0cf2..4bcaa988 100644 --- a/deny.toml +++ b/deny.toml @@ -15,6 +15,8 @@ ignore = [] allow = [ "0BSD", "Apache-2.0", + "Artistic-2.0", + "CC0-1.0", "MIT", "MPL-2.0", "Unicode-3.0", @@ -24,11 +26,9 @@ allow = [ # these are also ok, but not yet used - # "Artistic-2.0", # "BSD-2-Clause", # "BSD-3-Clause", # "BSL-1.0", - # "CC0-1.0", # "ISC", # "MIT-0", # "OFL-1.1", diff --git a/dependencies.json b/dependencies.json index 6ce3c607..cfe2f739 100644 --- a/dependencies.json +++ b/dependencies.json @@ -34,9 +34,11 @@ "dispatch2 0.3.0 registry+https://github.com/rust-lang/crates.io-index", "errno 0.3.14 registry+https://github.com/rust-lang/crates.io-index", "eyre 0.6.12 registry+https://github.com/rust-lang/crates.io-index", + "filetime 0.2.26 registry+https://github.com/rust-lang/crates.io-index", "fnv 1.0.7 registry+https://github.com/rust-lang/crates.io-index", "gimli 0.31.1 registry+https://github.com/rust-lang/crates.io-index", "heck 0.5.0 registry+https://github.com/rust-lang/crates.io-index", + "hotwatch 0.5.0 registry+https://github.com/rust-lang/crates.io-index", "ident_case 1.0.1 registry+https://github.com/rust-lang/crates.io-index", "indenter 0.3.4 registry+https://github.com/rust-lang/crates.io-index", "is_terminal_polyfill 1.70.1 registry+https://github.com/rust-lang/crates.io-index", @@ -93,12 +95,27 @@ "rustix 1.1.2 registry+https://github.com/rust-lang/crates.io-index" ] ], + [ + "Artistic-2.0", + [ + "file-id 0.1.0 registry+https://github.com/rust-lang/crates.io-index", + "notify-debouncer-full 0.1.0 registry+https://github.com/rust-lang/crates.io-index" + ] + ], [ "BSL-1.0", [ "ryu 1.0.20 registry+https://github.com/rust-lang/crates.io-index" ] ], + [ + "CC0-1.0", + [ + "file-id 0.1.0 registry+https://github.com/rust-lang/crates.io-index", + "notify 6.1.1 registry+https://github.com/rust-lang/crates.io-index", + "notify-debouncer-full 0.1.0 registry+https://github.com/rust-lang/crates.io-index" + ] + ], [ "MIT", [ @@ -134,9 +151,12 @@ "dispatch2 0.3.0 registry+https://github.com/rust-lang/crates.io-index", "errno 0.3.14 registry+https://github.com/rust-lang/crates.io-index", "eyre 0.6.12 registry+https://github.com/rust-lang/crates.io-index", + "filetime 0.2.26 registry+https://github.com/rust-lang/crates.io-index", "fnv 1.0.7 registry+https://github.com/rust-lang/crates.io-index", + "fsevent-sys 4.1.0 registry+https://github.com/rust-lang/crates.io-index", "gimli 0.31.1 registry+https://github.com/rust-lang/crates.io-index", "heck 0.5.0 registry+https://github.com/rust-lang/crates.io-index", + "hotwatch 0.5.0 registry+https://github.com/rust-lang/crates.io-index", "ident_case 1.0.1 registry+https://github.com/rust-lang/crates.io-index", "indenter 0.3.4 registry+https://github.com/rust-lang/crates.io-index", "is_terminal_polyfill 1.70.1 registry+https://github.com/rust-lang/crates.io-index", @@ -177,6 +197,7 @@ "regex-syntax 0.8.6 registry+https://github.com/rust-lang/crates.io-index", "rustc-demangle 0.1.26 registry+https://github.com/rust-lang/crates.io-index", "rustix 1.1.2 registry+https://github.com/rust-lang/crates.io-index", + "same-file 1.0.6 registry+https://github.com/rust-lang/crates.io-index", "scopeguard 1.2.0 registry+https://github.com/rust-lang/crates.io-index", "serde 1.0.225 registry+https://github.com/rust-lang/crates.io-index", "serde_core 1.0.225 registry+https://github.com/rust-lang/crates.io-index", @@ -201,7 +222,8 @@ "tracing-log 0.2.0 registry+https://github.com/rust-lang/crates.io-index", "tracing-subscriber 0.3.20 registry+https://github.com/rust-lang/crates.io-index", "unicode-ident 1.0.19 registry+https://github.com/rust-lang/crates.io-index", - "utf8parse 0.2.2 registry+https://github.com/rust-lang/crates.io-index" + "utf8parse 0.2.2 registry+https://github.com/rust-lang/crates.io-index", + "walkdir 2.5.0 registry+https://github.com/rust-lang/crates.io-index" ] ], [ @@ -220,7 +242,9 @@ "Unlicense", [ "aho-corasick 1.1.3 registry+https://github.com/rust-lang/crates.io-index", - "memchr 2.7.5 registry+https://github.com/rust-lang/crates.io-index" + "memchr 2.7.5 registry+https://github.com/rust-lang/crates.io-index", + "same-file 1.0.6 registry+https://github.com/rust-lang/crates.io-index", + "walkdir 2.5.0 registry+https://github.com/rust-lang/crates.io-index" ] ], [ diff --git a/komorebi/Cargo.toml b/komorebi/Cargo.toml index 31005369..324e797f 100644 --- a/komorebi/Cargo.toml +++ b/komorebi/Cargo.toml @@ -9,6 +9,7 @@ color-eyre = { workspace = true } crossbeam-channel = "0.5" ctrlc = { version = "3", features = ["termination"] } dirs = { workspace = true } +hotwatch = "0.5" lazy_static = { workspace = true } objc2 = "0.6" objc2-app-kit = "0.3" diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index aea9818e..1c81fef0 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -2,10 +2,12 @@ use crate::core::arrangement::Axis; use crate::core::cycle_direction::CycleDirection; use crate::core::default_layout::DefaultLayout; use crate::core::operation_direction::OperationDirection; +use crate::core::pathext::ResolvedPathBuf; use clap::ValueEnum; use color_eyre::eyre; use serde::Deserialize; use serde::Serialize; +use std::path::PathBuf; use std::str::FromStr; use strum::Display; use strum::EnumString; @@ -21,11 +23,23 @@ pub mod operation_direction; pub mod pathext; pub mod rect; +#[derive( + Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize, Display, EnumString, ValueEnum, +)] +pub enum OperationBehaviour { + /// Process komorebic commands on temporarily unmanaged/floated windows + #[default] + Op, + /// Ignore komorebic commands on temporarily unmanaged/floated windows + NoOp, +} + #[derive(Clone, Copy, Debug, Serialize, Deserialize, Display, EnumString, ValueEnum)] pub enum Sizing { Increase, Decrease, } + #[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, PartialEq)] pub struct WindowManagementBehaviour { /// The current WindowContainerBehaviour to be used @@ -217,6 +231,7 @@ pub enum SocketMessage { Promote, PromoteFocus, PromoteWindow(OperationDirection), + ReloadStaticConfiguration(#[serde_as(as = "ResolvedPathBuf")] PathBuf), } impl SocketMessage { diff --git a/komorebi/src/core/rect.rs b/komorebi/src/core/rect.rs index a125effd..f46fbfba 100644 --- a/komorebi/src/core/rect.rs +++ b/komorebi/src/core/rect.rs @@ -4,8 +4,10 @@ use objc2_core_foundation::CGFloat; use objc2_core_foundation::CGPoint; use objc2_core_foundation::CGRect; use objc2_core_foundation::CGSize; +use serde::Deserialize; +use serde::Serialize; -#[derive(Debug, Default, Copy, Clone, PartialEq)] +#[derive(Debug, Default, Copy, Clone, Serialize, Deserialize, PartialEq)] pub struct Rect { pub left: i32, pub top: i32, diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs index e0dd07d6..f7893fc9 100644 --- a/komorebi/src/lib.rs +++ b/komorebi/src/lib.rs @@ -5,6 +5,7 @@ use crate::core::ApplicationIdentifier; use crate::core::config_generation::IdWithIdentifier; use crate::core::config_generation::MatchingRule; use crate::core::config_generation::MatchingStrategy; +use crate::core::config_generation::WorkspaceMatchingRule; use crate::core_graphics::error::CoreGraphicsError; use crate::window::AspectRatio; use crate::window::PredefinedAspectRatio; @@ -50,6 +51,7 @@ pub mod notification_center_listener; pub mod process_command; pub mod process_event; pub mod reaper; +pub mod static_config; pub mod window; pub mod window_manager; pub mod window_manager_event; @@ -78,6 +80,8 @@ lazy_static! { static ref WINDOW_RESTORE_POSITIONS: Arc>> = Arc::new(Mutex::new(HashMap::new())); pub static ref UPDATE_MONITOR_WORK_AREAS: Arc = Arc::new(AtomicBool::new(false)); + static ref WORKSPACE_MATCHING_RULES: Arc>> = + Arc::new(Mutex::new(Vec::new())); static ref REGEX_IDENTIFIERS: Arc>> = Arc::new(Mutex::new(HashMap::new())); static ref MANAGE_IDENTIFIERS: Arc>> = Arc::new(Mutex::new(vec![])); diff --git a/komorebi/src/main.rs b/komorebi/src/main.rs index 910dc0b1..ce2eb93b 100644 --- a/komorebi/src/main.rs +++ b/komorebi/src/main.rs @@ -1,10 +1,13 @@ #![warn(clippy::all)] +use clap::Parser; use color_eyre::eyre; use color_eyre::eyre::OptionExt; use komorebi::DATA_DIR; +use komorebi::HOME_DIR; use komorebi::UPDATE_MONITOR_WORK_AREAS; use komorebi::ax_event_listener; +use komorebi::core::pathext::replace_env_in_path; use komorebi::display_reconfiguration_listener::DisplayReconfigurationListener; use komorebi::input_event_listener::InputEventListener; use komorebi::macos_api::MacosApi; @@ -13,6 +16,7 @@ use komorebi::notification_center_listener::NotificationCenterListener; use komorebi::process_command::listen_for_commands; use komorebi::process_event::listen_for_events; use komorebi::reaper; +use komorebi::static_config::StaticConfig; use komorebi::window_manager::WindowManager; use objc2::rc::autoreleasepool; use objc2_application_services::AXIsProcessTrusted; @@ -23,6 +27,7 @@ use objc2_core_graphics::CGMainDisplayID; use objc2_core_graphics::CGPreflightScreenCaptureAccess; use objc2_core_graphics::CGRequestScreenCaptureAccess; use parking_lot::Mutex; +use std::path::PathBuf; use std::sync::Arc; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; @@ -98,7 +103,23 @@ pub fn setup() -> eyre::Result<()> { Ok(()) } +#[derive(Parser)] +#[clap(author, about, version)] +struct Opts { + /// Path to a static configuration JSON file + #[clap(short, long)] + #[clap(value_parser = replace_env_in_path)] + config: Option, + // /// Do not attempt to auto-apply a dumped state temp file from a previously running instance of komorebi + // #[clap(long)] + // clean_state: bool, + // /// Level of log output verbosity + // #[clap(long, value_enum, default_value_t=LogLevel::Info)] + // log_level: LogLevel, +} + fn main() -> eyre::Result<()> { + let opts: Opts = Opts::parse(); setup()?; check_permissions()?; @@ -115,13 +136,44 @@ fn main() -> eyre::Result<()> { let run_loop = CFRunLoop::current().ok_or_eyre("couldn't get CFRunLoop::current")?; let _input_listener = InputEventListener::init(&run_loop); - let wm = Arc::new(Mutex::new(WindowManager::new( - &run_loop, - ax_event_listener::event_rx(), - None, - )?)); + let static_config = opts.config.map_or_else( + || { + let komorebi_json = HOME_DIR.join("komorebi.json"); + if komorebi_json.is_file() { + Option::from(komorebi_json) + } else { + None + } + }, + Option::from, + ); + + let wm = if let Some(config) = &static_config { + tracing::info!( + "creating window manager from static configuration file: {}", + config.display() + ); + + Arc::new(Mutex::new(StaticConfig::preload( + config, + ax_event_listener::event_rx(), + None, + &run_loop, + )?)) + } else { + Arc::new(Mutex::new(WindowManager::new( + &run_loop, + ax_event_listener::event_rx(), + None, + )?)) + }; wm.lock().init()?; + + if let Some(config) = &static_config { + StaticConfig::postload(config, &wm)?; + } + wm.lock().update_focused_workspace(true, true)?; listen_for_commands(wm.clone()); diff --git a/komorebi/src/monitor.rs b/komorebi/src/monitor.rs index 0b1afcc5..111c3c53 100644 --- a/komorebi/src/monitor.rs +++ b/komorebi/src/monitor.rs @@ -406,4 +406,11 @@ impl Monitor { pub fn remove_workspaces(&mut self) -> VecDeque { self.workspaces_mut().drain(..).collect() } + + pub fn ensure_workspace_count(&mut self, ensure_count: usize) { + if self.workspaces().len() < ensure_count { + self.workspaces_mut() + .resize(ensure_count, Workspace::default()); + } + } } diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index c83c87c8..888fcde0 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -69,6 +69,7 @@ impl WindowManager { mut _reply: impl std::io::Write, ) -> eyre::Result<()> { tracing::info!("processing command: {message}"); + self.handle_unmanaged_window_behaviour()?; match message { SocketMessage::Promote => self.promote_container_to_front()?, @@ -789,6 +790,9 @@ impl WindowManager { self.move_workspace_to_monitor(monitor_idx)?; } + SocketMessage::ReloadStaticConfiguration(ref pathbuf) => { + self.reload_static_configuration(pathbuf)?; + } } Ok(()) diff --git a/komorebi/src/process_event.rs b/komorebi/src/process_event.rs index 9f95b888..10b5cce0 100644 --- a/komorebi/src/process_event.rs +++ b/komorebi/src/process_event.rs @@ -43,11 +43,34 @@ impl WindowManager { return Ok(()); } + let mut should_manage = true; + { + let application = self.application(event.process_id())?; + if let Some(window_element) = application.main_window() + && let Ok(window) = Window::new(window_element, application.clone()) + { + let print_window = window.clone(); + should_manage = window.should_manage(Some(event))?; + + if !should_manage { + tracing::debug!( + "ignoring event as window should not be managed: {print_window}" + ); + } + } + } + + if !should_manage { + return Ok(()); + } + tracing::info!( "processing event: {event} for process {}", event.process_id() ); + self.enforce_workspace_rules()?; + match event { WindowManagerEvent::FocusChange(notification, process_id, _) => { let application = self.application(process_id)?; diff --git a/komorebi/src/static_config.rs b/komorebi/src/static_config.rs new file mode 100644 index 00000000..20e9a95e --- /dev/null +++ b/komorebi/src/static_config.rs @@ -0,0 +1,1683 @@ +use crate::CoreFoundationRunLoop; +use crate::DATA_DIR; +use crate::DEFAULT_CONTAINER_PADDING; +use crate::DEFAULT_WORKSPACE_PADDING; +use crate::FLOATING_APPLICATIONS; +use crate::FLOATING_WINDOW_TOGGLE_ASPECT_RATIO; +use crate::IGNORE_IDENTIFIERS; +use crate::MANAGE_IDENTIFIERS; +use crate::REGEX_IDENTIFIERS; +use crate::WORKSPACE_MATCHING_RULES; +use crate::core::CrossBoundaryBehaviour; +use crate::core::FloatingLayerBehaviour; +use crate::core::MoveBehaviour; +use crate::core::OperationBehaviour; +use crate::core::Placement; +use crate::core::SocketMessage; +use crate::core::WindowContainerBehaviour; +use crate::core::WindowManagementBehaviour; +use crate::core::arrangement::Axis; +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::default_layout::DefaultLayout; +use crate::core::default_layout::LayoutOptions; +use crate::core::layout::Layout; +use crate::core::pathext::ResolvedPathBuf; +use crate::core::rect::Rect; +use crate::monitor::Monitor; +use crate::ring::Ring; +use crate::window::AspectRatio; +use crate::window::PredefinedAspectRatio; +use crate::window_manager::WindowManager; +use crate::window_manager_event::WindowManagerEvent; +use crate::workspace::Workspace; +use color_eyre::eyre; +use crossbeam_channel::Receiver; +use hotwatch::EventKind; +use hotwatch::Hotwatch; +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; +use std::os::unix::net::UnixListener; +use std::os::unix::net::UnixStream; +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))] +// 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))] +// pub struct ThemeOptions { +// /// Specify Light or Dark variant for theme generation (default: Dark) +// #[serde(skip_serializing_if = "Option::is_none")] +// pub theme_variant: Option, +// /// Border colour when the container contains a single window (default: Base0D) +// #[serde(skip_serializing_if = "Option::is_none")] +// pub single_border: Option, +// /// Border colour when the container contains multiple windows (default: Base0B) +// #[serde(skip_serializing_if = "Option::is_none")] +// pub stack_border: Option, +// /// Border colour when the container is in monocle mode (default: Base0F) +// #[serde(skip_serializing_if = "Option::is_none")] +// pub monocle_border: Option, +// /// Border colour when the window is floating (default: Base09) +// #[serde(skip_serializing_if = "Option::is_none")] +// pub floating_border: Option, +// /// Border colour when the container is unfocused (default: Base01) +// #[serde(skip_serializing_if = "Option::is_none")] +// pub unfocused_border: Option, +// /// Border colour when the container is unfocused and locked (default: Base08) +// #[serde(skip_serializing_if = "Option::is_none")] +// 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 (default: Base0D) +// #[serde(skip_serializing_if = "Option::is_none")] +// pub bar_accent: Option, +// } + +// #[serde_with::serde_as] +// #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +// #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +// pub struct Wallpaper { +// /// Path to the wallpaper image file +// #[serde_as(as = "ResolvedPathBuf")] +// pub path: PathBuf, +// /// Generate and apply Base16 theme for this wallpaper (default: true) +// #[serde(skip_serializing_if = "Option::is_none")] +// pub generate_theme: Option, +// /// Specify Light or Dark variant for theme generation (default: Dark) +// #[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)] +pub struct WorkspaceConfig { + /// Name + pub name: String, + /// Layout (default: BSP) + #[serde(skip_serializing_if = "Option::is_none")] + pub layout: Option, + /// Layout-specific options (default: None) + #[serde(skip_serializing_if = "Option::is_none")] + pub layout_options: 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 (default: None) + #[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>, + /// Workspace specific work area offset (default: None) + #[serde(skip_serializing_if = "Option::is_none")] + pub work_area_offset: Option, + /// Apply this monitor's window-based work area offset (default: true) + #[serde(skip_serializing_if = "Option::is_none")] + pub apply_window_based_work_area_offset: Option, + /// Determine what happens when a new window is opened (default: Create) + #[serde(skip_serializing_if = "Option::is_none")] + pub window_container_behaviour: Option, + /// Window container behaviour rules in the format of threshold => behaviour (default: None) + #[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 (default: false) + #[serde(skip_serializing_if = "Option::is_none")] + pub float_override: Option, + /// Enable or disable tiling for the workspace (default: true) + #[serde(skip_serializing_if = "Option::is_none")] + pub tile: Option, + /// Specify an axis on which to flip the selected layout (default: None) + #[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 (default: Tile) + #[serde(skip_serializing_if = "Option::is_none")] + pub floating_layer_behaviour: Option, + // /// Specify a wallpaper for this workspace + // #[serde(skip_serializing_if = "Option::is_none")] + // pub wallpaper: Option, +} + +impl From<&Workspace> for WorkspaceConfig { + fn from(value: &Workspace) -> Self { + let mut layout_rules = HashMap::new(); + for (threshold, layout) in &value.layout_rules { + match layout { + Layout::Default(value) => { + layout_rules.insert(*threshold, *value); + } + } + } + let layout_rules = (!layout_rules.is_empty()).then_some(layout_rules); + + let mut window_container_behaviour_rules = HashMap::new(); + for (threshold, behaviour) in value.window_container_behaviour_rules.iter().flatten() { + window_container_behaviour_rules.insert(*threshold, *behaviour); + } + + let default_container_padding = DEFAULT_CONTAINER_PADDING.load(Ordering::SeqCst); + let default_workspace_padding = DEFAULT_WORKSPACE_PADDING.load(Ordering::SeqCst); + + let container_padding = value.container_padding.and_then(|container_padding| { + if container_padding == default_container_padding { + None + } else { + Option::from(container_padding) + } + }); + + let workspace_padding = value.workspace_padding.and_then(|workspace_padding| { + if workspace_padding == default_workspace_padding { + None + } else { + Option::from(workspace_padding) + } + }); + + let tile = if value.tile { None } else { Some(false) }; + + Self { + name: value + .name + .clone() + .unwrap_or_else(|| String::from("unnamed")), + layout: value + .tile + .then_some(match value.layout { + Layout::Default(layout) => Option::from(layout), + }) + .flatten(), + layout_options: value.layout_options, + custom_layout: value + .workspace_config + .as_ref() + .and_then(|c| c.custom_layout.clone()), + layout_rules, + container_padding, + workspace_padding, + initial_workspace_rules: value + .workspace_config + .as_ref() + .and_then(|c| c.initial_workspace_rules.clone()), + workspace_rules: value + .workspace_config + .as_ref() + .and_then(|c| c.workspace_rules.clone()), + work_area_offset: value.work_area_offset, + apply_window_based_work_area_offset: Some(value.apply_window_based_work_area_offset), + window_container_behaviour: value.window_container_behaviour, + window_container_behaviour_rules: Option::from(window_container_behaviour_rules), + float_override: value.float_override, + tile, + layout_flip: value.layout_flip, + floating_layer_behaviour: value.floating_layer_behaviour, + // wallpaper: None, + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct MonitorConfig { + /// Workspace configurations + pub workspaces: Vec, + /// Monitor-specific work area offset (default: None) + #[serde(skip_serializing_if = "Option::is_none")] + pub work_area_offset: Option, + /// Window based work area offset (default: None) + #[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 (default: 1) + #[serde(skip_serializing_if = "Option::is_none")] + 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 (default: Tile) + #[serde(skip_serializing_if = "Option::is_none")] + pub floating_layer_behaviour: Option, +} + +impl From<&Monitor> for MonitorConfig { + fn from(value: &Monitor) -> Self { + let mut workspaces = vec![]; + for w in value.workspaces() { + workspaces.push(WorkspaceConfig::from(w)); + } + + let default_container_padding = DEFAULT_CONTAINER_PADDING.load(Ordering::SeqCst); + let default_workspace_padding = DEFAULT_WORKSPACE_PADDING.load(Ordering::SeqCst); + + let container_padding = value.container_padding.and_then(|container_padding| { + if container_padding == default_container_padding { + None + } else { + Option::from(container_padding) + } + }); + + let workspace_padding = value.workspace_padding.and_then(|workspace_padding| { + if workspace_padding == default_workspace_padding { + None + } else { + Option::from(workspace_padding) + } + }); + + Self { + workspaces, + work_area_offset: value.work_area_offset, + window_based_work_area_offset: value.window_based_work_area_offset, + window_based_work_area_offset_limit: Some(value.window_based_work_area_offset_limit), + container_padding, + workspace_padding, + // wallpaper: value.wallpaper.clone(), + floating_layer_behaviour: value.floating_layer_behaviour, + } + } +} + +#[serde_with::serde_as] +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +#[serde(untagged)] +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)] +/// The `komorebi.json` static configuration file reference for `v0.1.39` +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 (default 50) + #[serde(skip_serializing_if = "Option::is_none")] + pub resize_delta: Option, + /// Determine what happens when a new window is opened (default: Create) + #[serde(skip_serializing_if = "Option::is_none")] + pub window_container_behaviour: Option, + /// Enable or disable float override, which makes it so every new window opens in floating mode + /// (default: false) + #[serde(skip_serializing_if = "Option::is_none")] + pub float_override: Option, + /// Determines what happens on a new window when on the `FloatingLayer` + /// (default: Tile) + #[serde(skip_serializing_if = "Option::is_none")] + pub floating_layer_behaviour: Option, + /// Determines the placement of a new window when toggling to float (default: CenterAndResize) + #[serde(skip_serializing_if = "Option::is_none")] + 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` (default: Center) + #[serde(skip_serializing_if = "Option::is_none")] + pub floating_layer_placement: Option, + /// Determines the `Placement` to be used when spawning a window with float override active + /// (default: None) + #[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 (default: None) + #[serde(skip_serializing_if = "Option::is_none")] + pub float_rule_placement: Option, + /// Determine what happens when a window is moved across a monitor boundary (default: Swap) + #[serde(skip_serializing_if = "Option::is_none")] + pub cross_monitor_move_behaviour: Option, + /// Determine what happens when an action is called on a window at a monitor boundary (default: Monitor) + #[serde(skip_serializing_if = "Option::is_none")] + pub cross_boundary_behaviour: Option, + /// Determine what happens when commands are sent while an unmanaged window is in the foreground (default: Op) + #[serde(skip_serializing_if = "Option::is_none")] + pub unmanaged_window_operation_behaviour: Option, + /// Enable or disable mouse follows focus (default: true) + #[serde(skip_serializing_if = "Option::is_none")] + pub mouse_follows_focus: Option, + /// Path to applications.json from komorebi-application-specific-configurations (default: None) + #[serde(skip_serializing_if = "Option::is_none")] + pub app_specific_configuration_path: Option, + // /// Width of the window border (default: 8) + // #[serde(skip_serializing_if = "Option::is_none")] + // #[serde(alias = "active_window_border_width")] + // pub border_width: Option, + // /// Offset of the window border (default: -1) + // #[serde(skip_serializing_if = "Option::is_none")] + // #[serde(alias = "active_window_border_offset")] + // pub border_offset: Option, + // /// Display an active window border (default: true) + // #[serde(skip_serializing_if = "Option::is_none")] + // #[serde(alias = "active_window_border")] + // pub border: Option, + // /// Active window border colours for different container types + // #[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 (default: 10) + #[serde(skip_serializing_if = "Option::is_none")] + pub default_workspace_padding: Option, + /// Global default container padding (default: 10) + #[serde(skip_serializing_if = "Option::is_none")] + pub default_container_padding: 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 (default: None) + #[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 + // #[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))] +// pub struct AnimationsConfig { +// /// Enable or disable animations (default: false) +// pub enabled: PerAnimationPrefixConfig, +// /// Set the animation duration in ms (default: 250) +// #[serde(skip_serializing_if = "Option::is_none")] +// pub duration: Option>, +// /// Set the animation style (default: Linear) +// #[serde(skip_serializing_if = "Option::is_none")] +// pub style: Option>, +// /// Set the animation FPS (default: 60) +// #[serde(skip_serializing_if = "Option::is_none")] +// pub fps: Option, +// } + +// #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +// #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +// #[serde(tag = "palette")] +// pub enum KomorebiTheme { +// /// A theme from catppuccin-egui +// Catppuccin { +// /// Name of the Catppuccin theme (theme previews: https://github.com/catppuccin/catppuccin) +// name: komorebi_themes::Catppuccin, +// /// Border colour when the container contains a single window (default: Blue) +// #[serde(skip_serializing_if = "Option::is_none")] +// single_border: Option, +// /// Border colour when the container contains multiple windows (default: Green) +// #[serde(skip_serializing_if = "Option::is_none")] +// stack_border: Option, +// /// Border colour when the container is in monocle mode (default: Pink) +// #[serde(skip_serializing_if = "Option::is_none")] +// monocle_border: Option, +// /// Border colour when the window is floating (default: Yellow) +// #[serde(skip_serializing_if = "Option::is_none")] +// floating_border: Option, +// /// Border colour when the container is unfocused (default: Base) +// #[serde(skip_serializing_if = "Option::is_none")] +// unfocused_border: Option, +// /// Border colour when the container is unfocused and locked (default: Red) +// #[serde(skip_serializing_if = "Option::is_none")] +// unfocused_locked_border: Option, +// /// Stackbar focused tab text colour (default: Green) +// #[serde(skip_serializing_if = "Option::is_none")] +// stackbar_focused_text: Option, +// /// Stackbar unfocused tab text colour (default: Text) +// #[serde(skip_serializing_if = "Option::is_none")] +// stackbar_unfocused_text: Option, +// /// Stackbar tab background colour (default: Base) +// #[serde(skip_serializing_if = "Option::is_none")] +// stackbar_background: Option, +// /// Komorebi status bar accent (default: Blue) +// #[serde(skip_serializing_if = "Option::is_none")] +// bar_accent: Option, +// }, +// /// A theme from base16-egui-themes +// Base16 { +// /// Name of the Base16 theme (theme previews: https://tinted-theming.github.io/tinted-gallery/) +// name: komorebi_themes::Base16, +// /// Border colour when the container contains a single window (default: Base0D) +// #[serde(skip_serializing_if = "Option::is_none")] +// single_border: Option, +// /// Border colour when the container contains multiple windows (default: Base0B) +// #[serde(skip_serializing_if = "Option::is_none")] +// stack_border: Option, +// /// Border colour when the container is in monocle mode (default: Base0F) +// #[serde(skip_serializing_if = "Option::is_none")] +// monocle_border: Option, +// /// Border colour when the window is floating (default: Base09) +// #[serde(skip_serializing_if = "Option::is_none")] +// floating_border: Option, +// /// Border colour when the container is unfocused (default: Base01) +// #[serde(skip_serializing_if = "Option::is_none")] +// unfocused_border: Option, +// /// Border colour when the container is unfocused and locked (default: Base08) +// #[serde(skip_serializing_if = "Option::is_none")] +// unfocused_locked_border: Option, +// /// Stackbar focused tab text colour (default: Base0B) +// #[serde(skip_serializing_if = "Option::is_none")] +// stackbar_focused_text: Option, +// /// Stackbar unfocused tab text colour (default: Base05) +// #[serde(skip_serializing_if = "Option::is_none")] +// stackbar_unfocused_text: Option, +// /// Stackbar tab background colour (default: Base01) +// #[serde(skip_serializing_if = "Option::is_none")] +// stackbar_background: Option, +// /// Komorebi status bar accent (default: Base0D) +// #[serde(skip_serializing_if = "Option::is_none")] +// bar_accent: Option, +// }, +// /// A custom Base16 theme +// Custom { +// /// Colours of the custom Base16 theme palette +// colours: Box, +// /// Border colour when the container contains a single window (default: Base0D) +// #[serde(skip_serializing_if = "Option::is_none")] +// single_border: Option, +// /// Border colour when the container contains multiple windows (default: Base0B) +// #[serde(skip_serializing_if = "Option::is_none")] +// stack_border: Option, +// /// Border colour when the container is in monocle mode (default: Base0F) +// #[serde(skip_serializing_if = "Option::is_none")] +// monocle_border: Option, +// /// Border colour when the window is floating (default: Base09) +// #[serde(skip_serializing_if = "Option::is_none")] +// floating_border: Option, +// /// Border colour when the container is unfocused (default: Base01) +// #[serde(skip_serializing_if = "Option::is_none")] +// unfocused_border: Option, +// /// Border colour when the container is unfocused and locked (default: Base08) +// #[serde(skip_serializing_if = "Option::is_none")] +// unfocused_locked_border: Option, +// /// Stackbar focused tab text colour (default: Base0B) +// #[serde(skip_serializing_if = "Option::is_none")] +// stackbar_focused_text: Option, +// /// Stackbar unfocused tab text colour (default: Base05) +// #[serde(skip_serializing_if = "Option::is_none")] +// stackbar_unfocused_text: Option, +// /// Stackbar tab background colour (default: Base01) +// #[serde(skip_serializing_if = "Option::is_none")] +// stackbar_background: Option, +// /// Komorebi status bar accent (default: Base0D) +// #[serde(skip_serializing_if = "Option::is_none")] +// bar_accent: Option, +// }, +// } + +// #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +// #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +// 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))] +// 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 (default: Never) +// #[serde(skip_serializing_if = "Option::is_none")] +// 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 { + let mut monitors = vec![]; + for m in value.monitors() { + monitors.push(MonitorConfig::from(m)); + } + + // let border_colours = if border_manager::FOCUSED.load(Ordering::SeqCst) == 0 { + // None + // } else { + // Option::from(BorderColours { + // single: Option::from(Colour::from(border_manager::FOCUSED.load(Ordering::SeqCst))), + // stack: Option::from(Colour::from(border_manager::STACK.load(Ordering::SeqCst))), + // monocle: Option::from(Colour::from(border_manager::MONOCLE.load(Ordering::SeqCst))), + // floating: Option::from(Colour::from( + // border_manager::FLOATING.load(Ordering::SeqCst), + // )), + // unfocused: Option::from(Colour::from( + // border_manager::UNFOCUSED.load(Ordering::SeqCst), + // )), + // unfocused_locked: Option::from(Colour::from( + // border_manager::UNFOCUSED_LOCKED.load(Ordering::SeqCst), + // )), + // }) + // }; + + Self { + // invisible_borders: None, + resize_delta: Option::from(value.resize_delta), + window_container_behaviour: Option::from( + value.window_management_behaviour.current_behaviour, + ), + float_override: Option::from(value.window_management_behaviour.float_override), + floating_layer_behaviour: Option::from( + value.window_management_behaviour.floating_layer_behaviour, + ), + toggle_float_placement: Option::from( + value.window_management_behaviour.toggle_float_placement, + ), + floating_layer_placement: Option::from( + value.window_management_behaviour.floating_layer_placement, + ), + float_override_placement: Option::from( + value.window_management_behaviour.float_override_placement, + ), + float_rule_placement: Option::from( + value.window_management_behaviour.float_rule_placement, + ), + cross_monitor_move_behaviour: Option::from(value.cross_monitor_move_behaviour), + cross_boundary_behaviour: Option::from(value.cross_boundary_behaviour), + unmanaged_window_operation_behaviour: Option::from( + value.unmanaged_window_operation_behaviour, + ), + // minimum_window_height: Some(window::MINIMUM_HEIGHT.load(Ordering::SeqCst)), + // minimum_window_width: Some(window::MINIMUM_WIDTH.load(Ordering::SeqCst)), + // focus_follows_mouse: value.focus_follows_mouse, + mouse_follows_focus: Option::from(value.mouse_follows_focus), + app_specific_configuration_path: None, + // border_width: Option::from(border_manager::BORDER_WIDTH.load(Ordering::SeqCst)), + // border_offset: Option::from(border_manager::BORDER_OFFSET.load(Ordering::SeqCst)), + // border: Option::from(border_manager::BORDER_ENABLED.load(Ordering::SeqCst)), + // border_colours, + // transparency: Option::from( + // transparency_manager::TRANSPARENCY_ENABLED.load(Ordering::SeqCst), + // ), + // transparency_alpha: Option::from( + // transparency_manager::TRANSPARENCY_ALPHA.load(Ordering::SeqCst), + // ), + // transparency_ignore_rules: None, + // border_style: Option::from(STYLE.load()), + // border_z_order: None, + // border_implementation: Option::from(IMPLEMENTATION.load()), + default_workspace_padding: Option::from( + DEFAULT_WORKSPACE_PADDING.load(Ordering::SeqCst), + ), + default_container_padding: Option::from( + DEFAULT_CONTAINER_PADDING.load(Ordering::SeqCst), + ), + monitors: Option::from(monitors), + // window_hiding_behaviour: Option::from(*HIDING_BEHAVIOUR.lock()), + global_work_area_offset: value.work_area_offset, + ignore_rules: None, + floating_applications: None, + manage_rules: None, + border_overflow_applications: None, + tray_and_multi_window_applications: None, + layered_applications: None, + object_name_change_applications: None, + object_name_change_title_ignore_list: None, + // monitor_index_preferences: Option::from(MONITOR_INDEX_PREFERENCES.lock().clone()), + // display_index_preferences: Option::from(DISPLAY_INDEX_PREFERENCES.read().clone()), + // stackbar: None, + // animation: None, + // theme: None, + // slow_application_compensation_time: Option::from( + // SLOW_APPLICATION_COMPENSATION_TIME.load(Ordering::SeqCst), + // ), + // slow_application_identifiers: Option::from(SLOW_APPLICATION_IDENTIFIERS.lock().clone()), + // bar_configurations: None, + // 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()), + } + } +} + +impl StaticConfig { + #[allow(clippy::cognitive_complexity, clippy::too_many_lines)] + fn apply_globals(&mut self) -> eyre::Result<()> { + *FLOATING_WINDOW_TOGGLE_ASPECT_RATIO.lock() = self + .floating_window_aspect_ratio + .unwrap_or(AspectRatio::Predefined(PredefinedAspectRatio::Standard)); + + // if let Some(monitor_index_preferences) = &self.monitor_index_preferences { + // let mut preferences = MONITOR_INDEX_PREFERENCES.lock(); + // preferences.clone_from(monitor_index_preferences); + // } + // + // if let Some(display_index_preferences) = &self.display_index_preferences { + // let mut preferences = DISPLAY_INDEX_PREFERENCES.write(); + // preferences.clone_from(display_index_preferences); + // } + + // if let Some(behaviour) = self.window_hiding_behaviour { + // let mut window_hiding_behaviour = HIDING_BEHAVIOUR.lock(); + // *window_hiding_behaviour = behaviour; + // } + + // if let Some(height) = self.minimum_window_height { + // window::MINIMUM_HEIGHT.store(height, Ordering::SeqCst); + // } + // + // if let Some(width) = self.minimum_window_width { + // window::MINIMUM_WIDTH.store(width, Ordering::SeqCst); + // } + + // if let Some(animations) = &self.animation { + // match &animations.enabled { + // PerAnimationPrefixConfig::Prefix(enabled) => { + // ANIMATION_ENABLED_PER_ANIMATION.lock().clone_from(enabled); + // } + // PerAnimationPrefixConfig::Global(enabled) => { + // ANIMATION_ENABLED_GLOBAL.store(*enabled, Ordering::SeqCst); + // ANIMATION_ENABLED_PER_ANIMATION.lock().clear(); + // } + // } + // + // match &animations.style { + // Some(PerAnimationPrefixConfig::Prefix(style)) => { + // ANIMATION_STYLE_PER_ANIMATION.lock().clone_from(style); + // } + // Some(PerAnimationPrefixConfig::Global(style)) => { + // let mut animation_style = ANIMATION_STYLE_GLOBAL.lock(); + // *animation_style = *style; + // ANIMATION_STYLE_PER_ANIMATION.lock().clear(); + // } + // None => {} + // } + // + // match &animations.duration { + // Some(PerAnimationPrefixConfig::Prefix(duration)) => { + // ANIMATION_DURATION_PER_ANIMATION.lock().clone_from(duration); + // } + // Some(PerAnimationPrefixConfig::Global(duration)) => { + // ANIMATION_DURATION_GLOBAL.store(*duration, Ordering::SeqCst); + // ANIMATION_DURATION_PER_ANIMATION.lock().clear(); + // } + // None => {} + // } + // + // ANIMATION_FPS.store( + // animations.fps.unwrap_or(DEFAULT_ANIMATION_FPS), + // Ordering::SeqCst, + // ); + // } + + if let Some(container) = self.default_container_padding { + DEFAULT_CONTAINER_PADDING.store(container, Ordering::SeqCst); + } + + if let Some(workspace) = self.default_workspace_padding { + DEFAULT_WORKSPACE_PADDING.store(workspace, Ordering::SeqCst); + } + + // border_manager::BORDER_WIDTH.store(self.border_width.unwrap_or(8), Ordering::SeqCst); + // border_manager::BORDER_OFFSET.store(self.border_offset.unwrap_or(-1), Ordering::SeqCst); + // border_manager::BORDER_ENABLED.store(self.border.unwrap_or(true), Ordering::SeqCst); + // + // if let Some(colours) = &self.border_colours { + // if let Some(single) = colours.single { + // border_manager::FOCUSED.store(u32::from(single), Ordering::SeqCst); + // } + // + // if let Some(stack) = colours.stack { + // border_manager::STACK.store(u32::from(stack), Ordering::SeqCst); + // } + // + // if let Some(monocle) = colours.monocle { + // border_manager::MONOCLE.store(u32::from(monocle), Ordering::SeqCst); + // } + // + // if let Some(floating) = colours.floating { + // border_manager::FLOATING.store(u32::from(floating), Ordering::SeqCst); + // } + // + // if let Some(unfocused) = colours.unfocused { + // border_manager::UNFOCUSED.store(u32::from(unfocused), Ordering::SeqCst); + // } + // + // if let Some(unfocused_locked) = colours.unfocused_locked { + // border_manager::UNFOCUSED_LOCKED + // .store(u32::from(unfocused_locked), Ordering::SeqCst); + // } + // } + // + // STYLE.store(self.border_style.unwrap_or_default()); + // + // if !*WINDOWS_11 + // && matches!( + // self.border_implementation.unwrap_or_default(), + // BorderImplementation::Windows + // ) + // { + // tracing::error!( + // "BorderImplementation::Windows is only supported on Windows 11 and above" + // ); + // } else { + // IMPLEMENTATION.store(self.border_implementation.unwrap_or_default()); + // match IMPLEMENTATION.load() { + // BorderImplementation::Komorebi => { + // border_manager::destroy_all_borders()?; + // } + // BorderImplementation::Windows => { + // // TODO: figure out how to call wm.remove_all_accents here + // } + // } + // + // border_manager::send_notification(None); + // } + // + // transparency_manager::TRANSPARENCY_ENABLED + // .store(self.transparency.unwrap_or(false), Ordering::SeqCst); + // transparency_manager::TRANSPARENCY_ALPHA + // .store(self.transparency_alpha.unwrap_or(200), Ordering::SeqCst); + + let mut ignore_identifiers = IGNORE_IDENTIFIERS.lock(); + let mut regex_identifiers = REGEX_IDENTIFIERS.lock(); + let mut manage_identifiers = MANAGE_IDENTIFIERS.lock(); + // let mut tray_and_multi_window_identifiers = TRAY_AND_MULTI_WINDOW_IDENTIFIERS.lock(); + // let mut object_name_change_identifiers = OBJECT_NAME_CHANGE_ON_LAUNCH.lock(); + // let mut object_name_change_title_ignore_list = OBJECT_NAME_CHANGE_TITLE_IGNORE_LIST.lock(); + // let mut layered_identifiers = LAYERED_WHITELIST.lock(); + // let mut transparency_blacklist = TRANSPARENCY_BLACKLIST.lock(); + // let mut slow_application_identifiers = SLOW_APPLICATION_IDENTIFIERS.lock(); + let mut floating_applications = FLOATING_APPLICATIONS.lock(); + // let mut no_titlebar_applications = NO_TITLEBAR.lock(); + + if let Some(rules) = &mut self.ignore_rules { + populate_rules(rules, &mut ignore_identifiers, &mut regex_identifiers)?; + } + + if let Some(rules) = &mut self.floating_applications { + populate_rules(rules, &mut floating_applications, &mut regex_identifiers)?; + } + + if let Some(rules) = &mut self.manage_rules { + populate_rules(rules, &mut manage_identifiers, &mut regex_identifiers)?; + } + + // if let Some(rules) = &mut self.object_name_change_applications { + // populate_rules( + // rules, + // &mut object_name_change_identifiers, + // &mut regex_identifiers, + // )?; + // } + // + // if let Some(regexes) = &mut self.object_name_change_title_ignore_list { + // let mut updated = vec![]; + // for r in regexes { + // if let Ok(regex) = Regex::new(r) { + // updated.push(regex); + // } + // } + // + // *object_name_change_title_ignore_list = updated; + // } + // + // if let Some(rules) = &mut self.layered_applications { + // populate_rules(rules, &mut layered_identifiers, &mut regex_identifiers)?; + // } + // + // if let Some(rules) = &mut self.tray_and_multi_window_applications { + // populate_rules( + // rules, + // &mut tray_and_multi_window_identifiers, + // &mut regex_identifiers, + // )?; + // } + // + // if let Some(rules) = &mut self.transparency_ignore_rules { + // populate_rules(rules, &mut transparency_blacklist, &mut regex_identifiers)?; + // } + // + // if let Some(rules) = &mut self.slow_application_identifiers { + // populate_rules( + // rules, + // &mut slow_application_identifiers, + // &mut regex_identifiers, + // )?; + // } + // + // if let Some(rules) = &mut self.remove_titlebar_applications { + // populate_rules(rules, &mut no_titlebar_applications, &mut regex_identifiers)?; + // } + // + // if let Some(stackbar) = &self.stackbar { + // if let Some(height) = &stackbar.height { + // STACKBAR_TAB_HEIGHT.store(*height, Ordering::SeqCst); + // } + // + // if let Some(label) = &stackbar.label { + // STACKBAR_LABEL.store(*label); + // } + // + // if let Some(mode) = &stackbar.mode { + // STACKBAR_MODE.store(*mode); + // } + // + // #[allow(clippy::assigning_clones)] + // if let Some(tabs) = &stackbar.tabs { + // if let Some(background) = &tabs.background { + // STACKBAR_TAB_BACKGROUND_COLOUR.store((*background).into(), Ordering::SeqCst); + // } + // + // if let Some(colour) = &tabs.focused_text { + // STACKBAR_FOCUSED_TEXT_COLOUR.store((*colour).into(), Ordering::SeqCst); + // } + // + // if let Some(colour) = &tabs.unfocused_text { + // STACKBAR_UNFOCUSED_TEXT_COLOUR.store((*colour).into(), Ordering::SeqCst); + // } + // + // if let Some(width) = &tabs.width { + // STACKBAR_TAB_WIDTH.store(*width, Ordering::SeqCst); + // } + // + // STACKBAR_FONT_SIZE.store(tabs.font_size.unwrap_or(0), Ordering::SeqCst); + // *STACKBAR_FONT_FAMILY.lock() = tabs.font_family.clone(); + // } + // } + // + // if let Some(theme) = &self.theme { + // theme_manager::send_notification(theme.clone()); + // } + + if let Some(path) = &self.app_specific_configuration_path { + match path { + AppSpecificConfigurationPath::Single(path) => handle_asc_file( + path, + &mut ignore_identifiers, + &mut vec![], + &mut vec![], + &mut vec![], + &mut manage_identifiers, + &mut floating_applications, + &mut vec![], + &mut vec![], + &mut regex_identifiers, + )?, + AppSpecificConfigurationPath::Multiple(paths) => { + for path in paths { + handle_asc_file( + path, + &mut ignore_identifiers, + &mut vec![], + &mut vec![], + &mut vec![], + &mut manage_identifiers, + &mut floating_applications, + &mut vec![], + &mut vec![], + &mut regex_identifiers, + )? + } + } + } + } + + // if let Some(behaviour) = self.window_handling_behaviour { + // WINDOW_HANDLING_BEHAVIOUR.store(behaviour); + // } + + Ok(()) + } + + pub fn read_raw(raw: &str) -> eyre::Result { + Ok(serde_json::from_str(raw)?) + } + + pub fn read(path: &PathBuf) -> eyre::Result { + let content = std::fs::read_to_string(path)?; + serde_json::from_str(&content).map_err(Into::into) + } + + #[allow(clippy::too_many_lines)] + pub fn preload( + path: &PathBuf, + incoming: Receiver, + unix_listener: Option, + run_loop: &CFRetained, + ) -> eyre::Result { + let mut value = Self::read(path)?; + value.apply_globals()?; + + let listener = match unix_listener { + Some(listener) => listener, + None => { + let socket = DATA_DIR.join("komorebi.sock"); + + match std::fs::remove_file(&socket) { + Ok(()) => {} + Err(error) => match error.kind() { + // Doing this because ::exists() doesn't work reliably on Windows via IntelliJ + ErrorKind::NotFound => {} + _ => { + return Err(error.into()); + } + }, + }; + + UnixListener::bind(&socket)? + } + }; + + let mut wm = WindowManager { + monitors: Ring::default(), + // monitor_usr_idx_map: HashMap::new(), + applications: Default::default(), + incoming_events: incoming, + command_listener: listener, + is_paused: false, + // virtual_desktop_id: current_virtual_desktop(), + work_area_offset: value.global_work_area_offset, + window_management_behaviour: WindowManagementBehaviour { + current_behaviour: value + .window_container_behaviour + .unwrap_or(WindowContainerBehaviour::Create), + float_override: value.float_override.unwrap_or_default(), + floating_layer_override: false, // this value is always automatically calculated + floating_layer_behaviour: FloatingLayerBehaviour::default(), + toggle_float_placement: value + .toggle_float_placement + .unwrap_or(Placement::CenterAndResize), + floating_layer_placement: value + .floating_layer_placement + .unwrap_or(Placement::Center), + float_override_placement: value.float_override_placement.unwrap_or(Placement::None), + float_rule_placement: value.float_rule_placement.unwrap_or(Placement::None), + }, + cross_monitor_move_behaviour: value + .cross_monitor_move_behaviour + .unwrap_or(MoveBehaviour::Swap), + cross_boundary_behaviour: value + .cross_boundary_behaviour + .unwrap_or(CrossBoundaryBehaviour::Monitor), + unmanaged_window_operation_behaviour: value + .unmanaged_window_operation_behaviour + .unwrap_or(OperationBehaviour::Op), + resize_delta: value.resize_delta.unwrap_or(50), + // focus_follows_mouse: value.focus_follows_mouse, + mouse_follows_focus: value.mouse_follows_focus.unwrap_or(true), + hotwatch: Hotwatch::new()?, + // has_pending_raise_op: false, + // pending_move_op: Arc::new(None), + // already_moved_window_handles: Arc::new(Mutex::new(HashSet::new())), + // uncloack_to_ignore: 0, + // known_hwnds: HashMap::new(), + run_loop: CoreFoundationRunLoop(run_loop.clone()), + minimized_windows: Default::default(), + already_moved_window_handles: Default::default(), + }; + + // match value.focus_follows_mouse { + // None => WindowsApi::disable_focus_follows_mouse()?, + // Some(FocusFollowsMouseImplementation::Windows) => { + // WindowsApi::enable_focus_follows_mouse()?; + // } + // Some(FocusFollowsMouseImplementation::Komorebi) => {} + // }; + + let bytes = SocketMessage::ReloadStaticConfiguration(path.clone()).as_bytes()?; + + wm.hotwatch.watch(path, move |event| match event.kind { + // Editing in Notepad sends a NoticeWrite while editing in (Neo)Vim sends + // a NoticeRemove, presumably because of the use of swap files? + EventKind::Modify(_) | EventKind::Remove(_) => { + let socket = DATA_DIR.join("komorebi.sock"); + let mut stream = + UnixStream::connect(socket).expect("could not connect to komorebi.sock"); + stream + .write_all(&bytes) + .expect("could not write to komorebi.sock"); + } + _ => {} + })?; + + Ok(wm) + } + + pub fn postload(path: &PathBuf, wm: &Arc>) -> eyre::Result<()> { + let mut value = Self::read(path)?; + let mut wm = wm.lock(); + + // let configs_with_preference: Vec<_> = + // DISPLAY_INDEX_PREFERENCES.read().keys().copied().collect(); + let configs_with_preference = []; + let mut configs_used = Vec::new(); + + let mut workspace_matching_rules = WORKSPACE_MATCHING_RULES.lock(); + workspace_matching_rules.clear(); + drop(workspace_matching_rules); + + let monitor_count = wm.monitors().len(); + + let offset = wm.work_area_offset; + for (i, monitor) in wm.monitors_mut().iter_mut().enumerate() { + let preferred_config_idx = None; + // let preferred_config_idx = { + // let display_index_preferences = DISPLAY_INDEX_PREFERENCES.read(); + // let c_idx = display_index_preferences.iter().find_map(|(c_idx, id)| { + // (monitor.serial_number_id.as_ref().is_some_and(|sn| sn == id) + // || monitor.device_id.eq(id)) + // .then_some(*c_idx) + // }); + // c_idx + // }; + + let idx = preferred_config_idx.or({ + // Monitor without preferred config idx. + // Get index of first config that is not a preferred config of some other monitor + // and that has not been used yet. This might return `None` as well, in that case + // this monitor won't have a config tied to it and will use the default values. + let m_config_count = value + .monitors + .as_ref() + .map(|ms| ms.len()) + .unwrap_or_default(); + (0..m_config_count) + .find(|i| !configs_with_preference.contains(i) && !configs_used.contains(i)) + }); + + if let Some(monitor_config) = value + .monitors + .as_mut() + .and_then(|ms| idx.and_then(|i| ms.get_mut(i))) + { + if let Some(used_config_idx) = idx { + configs_used.push(used_config_idx); + } + + monitor.ensure_workspace_count(monitor_config.workspaces.len()); + monitor.work_area_offset = monitor_config.work_area_offset; + monitor.window_based_work_area_offset = + monitor_config.window_based_work_area_offset; + monitor.window_based_work_area_offset_limit = monitor_config + .window_based_work_area_offset_limit + .unwrap_or(1); + monitor.container_padding = monitor_config.container_padding; + monitor.workspace_padding = monitor_config.workspace_padding; + // monitor.wallpaper = monitor_config.wallpaper.clone(); + monitor.floating_layer_behaviour = monitor_config.floating_layer_behaviour; + + monitor.update_workspaces_globals(offset); + for (j, ws) in monitor.workspaces_mut().iter_mut().enumerate() { + if let Some(workspace_config) = monitor_config.workspaces.get_mut(j) { + if monitor_count > 1 + && matches!(workspace_config.layout, Some(DefaultLayout::Scrolling)) + { + tracing::warn!( + "scrolling layout is only supported for a single monitor; falling back to columns layout" + ); + workspace_config.layout = Some(DefaultLayout::Columns); + } + + ws.load_static_config(workspace_config)?; + } + } + + // Check if this monitor config is the preferred config for this monitor and store + // a copy of the monitor itself on the monitor cache if it is. + // if idx == preferred_config_idx { + // let id = monitor + // .serial_number_id + // .as_ref() + // .map_or(&monitor.device_id, |sn| sn); + // monitor_reconciliator::insert_in_monitor_cache(id, monitor.clone()); + // } + + let mut workspace_matching_rules = WORKSPACE_MATCHING_RULES.lock(); + for (j, ws) in monitor_config.workspaces.iter().enumerate() { + if let Some(rules) = &ws.workspace_rules { + for r in rules { + workspace_matching_rules.push(WorkspaceMatchingRule { + monitor_index: i, + workspace_index: j, + matching_rule: r.clone(), + initial_only: false, + }); + } + } + + if let Some(rules) = &ws.initial_workspace_rules { + for r in rules { + workspace_matching_rules.push(WorkspaceMatchingRule { + monitor_index: i, + workspace_index: j, + matching_rule: r.clone(), + initial_only: true, + }); + } + } + } + } + } + + // Check for configs that should be tied to a specific display that isn't loaded right now + // and cache a monitor with those configs with the specific `serial_number_id` so that when + // those devices are connected later we can use the correct config from the cache. + // if configs_with_preference.len() > configs_used.len() { + // for i in configs_with_preference + // .iter() + // .filter(|i| !configs_used.contains(i)) + // { + // let id = { + // let display_index_preferences = DISPLAY_INDEX_PREFERENCES.read(); + // display_index_preferences.get(i).cloned() + // }; + // if let (Some(id), Some(monitor_config)) = + // (id, value.monitors.as_ref().and_then(|ms| ms.get(*i))) + // { + // // The name, device, device_id and serial_number_id can be empty here since + // // once the monitor with this preferred index actually connects the + // // `load_monitor_information` function will update these fields. + // let mut m = monitor::new( + // 0, + // Rect::default(), + // Rect::default(), + // "".into(), + // "".into(), + // "".into(), + // None, + // ); + // + // m.ensure_workspace_count(monitor_config.workspaces.len()); + // m.work_area_offset = monitor_config.work_area_offset; + // m.window_based_work_area_offset = monitor_config.window_based_work_area_offset; + // m.window_based_work_area_offset_limit = monitor_config + // .window_based_work_area_offset_limit + // .unwrap_or(1); + // m.container_padding = monitor_config.container_padding; + // m.workspace_padding = monitor_config.workspace_padding; + // m.floating_layer_behaviour = monitor_config.floating_layer_behaviour; + // + // m.update_workspaces_globals(offset); + // + // for (j, ws) in m.workspaces_mut().iter_mut().enumerate() { + // if let Some(workspace_config) = monitor_config.workspaces.get(j) { + // ws.load_static_config(workspace_config)?; + // } + // } + // + // monitor_reconciliator::insert_in_monitor_cache(&id, m); + // } + // } + // } + + wm.enforce_workspace_rules()?; + + // if value.border == Some(true) { + // border_manager::BORDER_ENABLED.store(true, Ordering::SeqCst); + // } + + Ok(()) + } + + pub fn reload(path: &PathBuf, wm: &mut WindowManager) -> eyre::Result<()> { + let mut value = Self::read(path)?; + + value.apply_globals()?; + + // let configs_with_preference: Vec<_> = + // DISPLAY_INDEX_PREFERENCES.read().keys().copied().collect(); + let configs_with_preference = []; + let mut configs_used = Vec::new(); + + let mut workspace_matching_rules = WORKSPACE_MATCHING_RULES.lock(); + workspace_matching_rules.clear(); + drop(workspace_matching_rules); + + let offset = wm.work_area_offset; + for (i, monitor) in wm.monitors_mut().iter_mut().enumerate() { + // let preferred_config_idx = { + // let display_index_preferences = DISPLAY_INDEX_PREFERENCES.read(); + // let c_idx = display_index_preferences.iter().find_map(|(c_idx, id)| { + // (monitor.serial_number_id.as_ref().is_some_and(|sn| sn == id) + // || monitor.device_id.eq(id)) + // .then_some(*c_idx) + // }); + // c_idx + // }; + + let preferred_config_idx = None; + + let idx = preferred_config_idx.or({ + // Monitor without preferred config idx. + // Get index of first config that is not a preferred config of some other monitor + // and that has not been used yet. This might return `None` as well, in that case + // this monitor won't have a config tied to it and will use the default values. + let m_config_count = value + .monitors + .as_ref() + .map(|ms| ms.len()) + .unwrap_or_default(); + (0..m_config_count) + .find(|i| !configs_with_preference.contains(i) && !configs_used.contains(i)) + }); + if let Some(monitor_config) = value + .monitors + .as_ref() + .and_then(|ms| idx.and_then(|i| ms.get(i))) + { + if let Some(used_config_idx) = idx { + configs_used.push(used_config_idx); + } + + monitor.ensure_workspace_count(monitor_config.workspaces.len()); + if monitor.work_area_offset.is_none() { + monitor.work_area_offset = monitor_config.work_area_offset; + } + monitor.window_based_work_area_offset = + monitor_config.window_based_work_area_offset; + monitor.window_based_work_area_offset_limit = monitor_config + .window_based_work_area_offset_limit + .unwrap_or(1); + monitor.container_padding = monitor_config.container_padding; + monitor.workspace_padding = monitor_config.workspace_padding; + // monitor.wallpaper = monitor_config.wallpaper.clone(); + monitor.floating_layer_behaviour = monitor_config.floating_layer_behaviour; + + monitor.update_workspaces_globals(offset); + + for (j, ws) in monitor.workspaces_mut().iter_mut().enumerate() { + if let Some(workspace_config) = monitor_config.workspaces.get(j) { + ws.load_static_config(workspace_config)?; + } + } + + // Check if this monitor config is the preferred config for this monitor and store + // a copy of the monitor itself on the monitor cache if it is. + // if idx == preferred_config_idx { + // let id = monitor + // .serial_number_id + // .as_ref() + // .map_or(&monitor.device_id, |sn| sn); + // monitor_reconciliator::insert_in_monitor_cache(id, monitor.clone()); + // } + + let mut workspace_matching_rules = WORKSPACE_MATCHING_RULES.lock(); + for (j, ws) in monitor_config.workspaces.iter().enumerate() { + if let Some(rules) = &ws.workspace_rules { + for r in rules { + workspace_matching_rules.push(WorkspaceMatchingRule { + monitor_index: i, + workspace_index: j, + matching_rule: r.clone(), + initial_only: false, + }); + } + } + + if let Some(rules) = &ws.initial_workspace_rules { + for r in rules { + workspace_matching_rules.push(WorkspaceMatchingRule { + monitor_index: i, + workspace_index: j, + matching_rule: r.clone(), + initial_only: true, + }); + } + } + } + } + } + + // Check for configs that should be tied to a specific display that isn't loaded right now + // and cache a monitor with those configs with the specific `serial_number_id` so that when + // those devices are connected later we can use the correct config from the cache. + // if configs_with_preference.len() > configs_used.len() { + // for i in configs_with_preference + // .iter() + // .filter(|i| !configs_used.contains(i)) + // { + // let id = { + // let display_index_preferences = DISPLAY_INDEX_PREFERENCES.read(); + // display_index_preferences.get(i).cloned() + // }; + // if let (Some(id), Some(monitor_config)) = + // (id, value.monitors.as_ref().and_then(|ms| ms.get(*i))) + // { + // // The name, device, device_id and serial_number_id can be empty here since + // // once the monitor with this preferred index actually connects the + // // `load_monitor_information` function will update these fields. + // let mut m = monitor::new( + // 0, + // Rect::default(), + // Rect::default(), + // "".into(), + // "".into(), + // "".into(), + // None, + // ); + // + // m.ensure_workspace_count(monitor_config.workspaces.len()); + // m.work_area_offset = monitor_config.work_area_offset; + // m.window_based_work_area_offset = monitor_config.window_based_work_area_offset; + // m.window_based_work_area_offset_limit = monitor_config + // .window_based_work_area_offset_limit + // .unwrap_or(1); + // m.container_padding = monitor_config.container_padding; + // m.workspace_padding = monitor_config.workspace_padding; + // m.floating_layer_behaviour = monitor_config.floating_layer_behaviour; + // + // m.update_workspaces_globals(offset); + // + // for (j, ws) in m.workspaces_mut().iter_mut().enumerate() { + // if let Some(workspace_config) = monitor_config.workspaces.get(j) { + // ws.load_static_config(workspace_config)?; + // } + // } + // + // monitor_reconciliator::insert_in_monitor_cache(&id, m); + // } + // } + // } + + wm.enforce_workspace_rules()?; + + // border_manager::BORDER_ENABLED.store(value.border.unwrap_or(true), Ordering::SeqCst); + wm.window_management_behaviour.current_behaviour = + value.window_container_behaviour.unwrap_or_default(); + wm.window_management_behaviour.float_override = value.float_override.unwrap_or_default(); + wm.window_management_behaviour.floating_layer_behaviour = + value.floating_layer_behaviour.unwrap_or_default(); + wm.window_management_behaviour.toggle_float_placement = value + .toggle_float_placement + .unwrap_or(Placement::CenterAndResize); + wm.window_management_behaviour.floating_layer_placement = + value.floating_layer_placement.unwrap_or(Placement::Center); + wm.window_management_behaviour.float_override_placement = + value.float_override_placement.unwrap_or(Placement::None); + wm.window_management_behaviour.float_rule_placement = + value.float_rule_placement.unwrap_or(Placement::None); + wm.cross_monitor_move_behaviour = value.cross_monitor_move_behaviour.unwrap_or_default(); + wm.cross_boundary_behaviour = value.cross_boundary_behaviour.unwrap_or_default(); + wm.unmanaged_window_operation_behaviour = value + .unmanaged_window_operation_behaviour + .unwrap_or_default(); + wm.resize_delta = value.resize_delta.unwrap_or(50); + wm.mouse_follows_focus = value.mouse_follows_focus.unwrap_or(true); + wm.work_area_offset = value.global_work_area_offset; + // wm.focus_follows_mouse = value.focus_follows_mouse; + + // match wm.focus_follows_mouse { + // None => WindowsApi::disable_focus_follows_mouse()?, + // Some(FocusFollowsMouseImplementation::Windows) => { + // WindowsApi::enable_focus_follows_mouse()?; + // } + // Some(FocusFollowsMouseImplementation::Komorebi) => {} + // }; + + let monitor_count = wm.monitors().len(); + + for i in 0..monitor_count { + wm.update_focused_workspace_by_monitor_idx(i)?; + // let ws_idx = wm.focused_workspace_idx_for_monitor_idx(i)?; + // wm.apply_wallpaper_for_monitor_workspace(i, ws_idx)?; + } + + Ok(()) + } +} + +fn populate_rules( + matching_rules: &mut Vec, + identifiers: &mut Vec, + regex_identifiers: &mut HashMap, +) -> eyre::Result<()> { + for matching_rule in matching_rules { + if !identifiers.contains(matching_rule) { + match matching_rule { + MatchingRule::Simple(simple) => { + if simple.matching_strategy.is_none() { + simple.matching_strategy = Option::from(MatchingStrategy::Legacy); + } + + if matches!(simple.matching_strategy, Some(MatchingStrategy::Regex)) { + let re = Regex::new(&simple.id)?; + regex_identifiers.insert(simple.id.clone(), re); + } + } + MatchingRule::Composite(composite) => { + for rule in composite { + if rule.matching_strategy.is_none() { + rule.matching_strategy = Option::from(MatchingStrategy::Legacy); + } + + if matches!(rule.matching_strategy, Some(MatchingStrategy::Regex)) { + let re = Regex::new(&rule.id)?; + regex_identifiers.insert(rule.id.clone(), re); + } + } + } + } + identifiers.push(matching_rule.clone()); + } + } + + Ok(()) +} + +#[allow(clippy::too_many_arguments)] +fn handle_asc_file( + path: &PathBuf, + ignore_identifiers: &mut Vec, + object_name_change_identifiers: &mut Vec, + layered_identifiers: &mut Vec, + tray_and_multi_window_identifiers: &mut Vec, + manage_identifiers: &mut Vec, + floating_applications: &mut Vec, + transparency_blacklist: &mut Vec, + slow_application_identifiers: &mut Vec, + regex_identifiers: &mut HashMap, +) -> eyre::Result<()> { + match path.extension() { + None => {} + Some(ext) => { + if ext.to_string_lossy().to_string().as_str() == "json" { + tracing::info!("loading applications.json from: {}", path.display()); + let mut asc = ApplicationSpecificConfiguration::load(path)?; + + for entry in asc.values_mut() { + match entry { + AscApplicationRulesOrSchema::Schema(_) => {} + AscApplicationRulesOrSchema::AscApplicationRules(entry) => { + if let Some(rules) = &mut entry.ignore { + populate_rules(rules, ignore_identifiers, regex_identifiers)?; + } + + if let Some(rules) = &mut entry.manage { + populate_rules(rules, manage_identifiers, regex_identifiers)?; + } + + if let Some(rules) = &mut entry.floating { + populate_rules(rules, floating_applications, regex_identifiers)?; + } + + if let Some(rules) = &mut entry.transparency_ignore { + populate_rules(rules, transparency_blacklist, regex_identifiers)?; + } + + if let Some(rules) = &mut entry.tray_and_multi_window { + populate_rules( + rules, + tray_and_multi_window_identifiers, + regex_identifiers, + )?; + } + + if let Some(rules) = &mut entry.layered { + populate_rules(rules, layered_identifiers, regex_identifiers)?; + } + + if let Some(rules) = &mut entry.object_name_change { + populate_rules( + rules, + object_name_change_identifiers, + regex_identifiers, + )?; + } + + if let Some(rules) = &mut entry.slow_application { + populate_rules( + rules, + slow_application_identifiers, + regex_identifiers, + )?; + } + } + } + } + } + } + } + + Ok(()) +} diff --git a/komorebi/src/window.rs b/komorebi/src/window.rs index 0739696a..aee7113c 100644 --- a/komorebi/src/window.rs +++ b/komorebi/src/window.rs @@ -1,7 +1,12 @@ use crate::AccessibilityObserver; use crate::AccessibilityUiElement; +use crate::FLOATING_APPLICATIONS; use crate::FLOATING_WINDOW_TOGGLE_ASPECT_RATIO; +use crate::IGNORE_IDENTIFIERS; use crate::LibraryError; +use crate::MANAGE_IDENTIFIERS; +use crate::PERMAIGNORE_CLASSES; +use crate::REGEX_IDENTIFIERS; use crate::WINDOW_RESTORE_POSITIONS; use crate::accessibility::AccessibilityApi; use crate::accessibility::attribute_constants::kAXFocusedAttribute; @@ -23,6 +28,10 @@ use crate::accessibility::notification_constants::kAXWindowResizedNotification; use crate::application::Application; use crate::ax_event_listener::event_tx; use crate::cf_dictionary_value; +use crate::core::ApplicationIdentifier; +use crate::core::config_generation::IdWithIdentifier; +use crate::core::config_generation::MatchingRule; +use crate::core::config_generation::MatchingStrategy; use crate::core::rect::Rect; use crate::core_graphics::CoreGraphicsApi; use crate::hidden_frame_bottom_left; @@ -31,6 +40,7 @@ use crate::reaper; use crate::reaper::ReaperNotification; use crate::window_manager_event::SystemNotification; use crate::window_manager_event::WindowManagerEvent; +use color_eyre::eyre; use objc2::__framework_prelude::Retained; use objc2_app_kit::NSApplicationActivationOptions; use objc2_app_kit::NSRunningApplication; @@ -51,13 +61,16 @@ use objc2_core_graphics::kCGWindowBounds; use objc2_core_graphics::kCGWindowName; use objc2_core_graphics::kCGWindowOwnerName; use objc2_core_graphics::kCGWindowOwnerPID; +use regex::Regex; use serde::Deserialize; use serde::Serialize; +use std::collections::HashMap; use std::collections::hash_map::Entry; use std::ffi::c_void; use std::fmt::Display; use std::fmt::Formatter; use std::fmt::Write; +use std::path::PathBuf; use std::ptr::NonNull; use std::str::FromStr; use strum::Display; @@ -184,6 +197,12 @@ impl Drop for Window { } } +impl PartialEq for Window { + fn eq(&self, other: &Self) -> bool { + self.id == other.id + } +} + impl Display for Window { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { let mut display = format!( @@ -330,6 +349,18 @@ impl Window { } } + pub fn path(&self) -> Option { + if let Ok(Some(path)) = self + .running_application() + .map(|app| unsafe { app.executableURL() }) + .map(|ns_url| ns_url.map(|url| url.to_file_path())) + { + path + } else { + None + } + } + pub fn role(&self) -> Option { AccessibilityApi::copy_attribute_value::(&self.element, kAXRoleAttribute) .map(|s| s.to_string()) @@ -506,6 +537,95 @@ impl Window { Ok(()) } + + #[tracing::instrument(skip_all)] + pub fn should_manage( + self, + event: Option, + // debug: &mut RuleDebug, + ) -> eyre::Result { + if !self.is_valid() { + return Ok(false); + } + + // debug.is_window = true; + + // let rect = Rect::from(MacosApi::window_rect(&self.element).unwrap_or_default()); + // + // if rect.right < MINIMUM_WIDTH.load(Ordering::SeqCst) { + // return Ok(false); + // } + // + // debug.has_minimum_width = true; + // + // if rect.bottom < MINIMUM_HEIGHT.load(Ordering::SeqCst) { + // return Ok(false); + // } + // + // debug.has_minimum_height = true; + + if self.title().is_none() { + return Ok(false); + } + + // debug.has_title = true; + + // let is_cloaked = self.is_cloaked().unwrap_or_default(); + // + // debug.is_cloaked = is_cloaked; + + // let mut allow_cloaked = false; + + // if let Some(event) = event { + // if matches!( + // event, + // WindowManagerEvent::Hide(_, _) | WindowManagerEvent::Cloak(_, _) + // ) { + // allow_cloaked = true; + // } + // } + + // debug.allow_cloaked = allow_cloaked; + + // match (allow_cloaked, is_cloaked) { + // // If allowing cloaked windows, we don't need to check the cloaked status + // (true, _) | + // // If not allowing cloaked windows, we need to ensure the window is not cloaked + // (false, false) => { + if let (Some(title), Some(exe_name), Some(role), Some(subrole), Some(path)) = ( + self.title(), + self.exe(), + self.role(), + self.subrole(), + self.path(), + ) { + // debug.title = Some(title.clone()); + // debug.exe_name = Some(exe_name.clone()); + // debug.class = Some(class.clone()); + // debug.path = Some(path.clone()); + // calls for styles can fail quite often for events with windows that aren't really "windows" + // since we have moved up calls of should_manage to the beginning of the process_event handler, + // we should handle failures here gracefully to be able to continue the execution of process_event + // if let (Ok(style), Ok(ex_style)) = (&self.style(), &self.ex_style()) { + // debug.window_style = Some(*style); + // debug.extended_window_style = Some(*ex_style); + let eligible = window_is_eligible( + self.id, + &title, + &exe_name, + &[&role, &subrole], + &path.to_string_lossy(), + event, + ); + // debug.should_manage = eligible; + return Ok(eligible); + // } + } + // } + // _ => {} + // } + Ok(false) + } } impl From<&CFDictionary> for WindowInfo { @@ -607,3 +727,463 @@ impl AspectRatio { } } } + +#[allow(clippy::too_many_arguments)] +fn window_is_eligible( + _window_id: u32, + title: &str, + exe_name: &str, + classes: &[&str], + path: &str, + // style: &WindowStyle, + // ex_style: &ExtendedWindowStyle, + _event: Option, + // debug: &mut RuleDebug, +) -> bool { + { + let permaignore_classes = PERMAIGNORE_CLASSES.lock(); + for class in classes { + if permaignore_classes.contains(&class.to_string()) { + // debug.matches_permaignore_class = Some(class.clone()); + return false; + } + } + } + + let regex_identifiers = REGEX_IDENTIFIERS.lock(); + + let ignore_identifiers = IGNORE_IDENTIFIERS.lock(); + let should_ignore = if let Some(_rule) = should_act( + title, + exe_name, + classes, + path, + &ignore_identifiers, + ®ex_identifiers, + ) { + // debug.matches_ignore_identifier = Some(rule); + true + } else { + false + }; + + let manage_identifiers = MANAGE_IDENTIFIERS.lock(); + let managed_override = if let Some(_rule) = should_act( + title, + exe_name, + classes, + path, + &manage_identifiers, + ®ex_identifiers, + ) { + // debug.matches_managed_override = Some(rule); + true + } else { + false + }; + + let floating_identifiers = FLOATING_APPLICATIONS.lock(); + if let Some(_rule) = should_act( + title, + exe_name, + classes, + path, + &floating_identifiers, + ®ex_identifiers, + ) { + // debug.matches_floating_applications = Some(rule); + } + + if should_ignore && !managed_override { + return false; + } + + // let layered_whitelist = LAYERED_WHITELIST.lock(); + // let mut allow_layered = if let Some(rule) = should_act( + // title, + // exe_name, + // class, + // path, + // &layered_whitelist, + // ®ex_identifiers, + // ) { + // debug.matches_layered_whitelist = Some(rule); + // true + // } else { + // false + // }; + // + // let known_layered_hwnds = transparency_manager::known_hwnds(); + + // allow_layered = if known_layered_hwnds.contains(&hwnd) + // // we always want to process hide events for windows with transparency, even on other + // // monitors, because we don't want to be left with ghost tiles + // || matches!(event, Some(WindowManagerEvent::Hide(_, _))) + // { + // debug.allow_layered_transparency = true; + // true + // } else { + // allow_layered + // }; + // + // let allow_wsl2_gui = { + // let wsl2_ui_processes = WSL2_UI_PROCESSES.lock(); + // let allow = wsl2_ui_processes.contains(exe_name); + // if allow { + // debug.matches_wsl2_gui = Some(exe_name.clone()) + // } + // + // allow + // }; + + // let titlebars_removed = NO_TITLEBAR.lock(); + // let allow_titlebar_removed = if let Some(rule) = should_act( + // title, + // exe_name, + // class, + // path, + // &titlebars_removed, + // ®ex_identifiers, + // ) { + // debug.matches_no_titlebar = Some(rule); + // true + // } else { + // false + // }; + // + // { + // let slow_application_identifiers = SLOW_APPLICATION_IDENTIFIERS.lock(); + // let should_sleep = should_act( + // title, + // exe_name, + // class, + // path, + // &slow_application_identifiers, + // ®ex_identifiers, + // ) + // .is_some(); + // + // if should_sleep { + // std::thread::sleep(Duration::from_millis( + // SLOW_APPLICATION_COMPENSATION_TIME.load(Ordering::SeqCst), + // )); + // } + // } + + // TODO: not sure about this new manage by default base case for macOS + true +} + +#[allow(clippy::cognitive_complexity, clippy::too_many_lines)] +pub fn should_act( + title: &str, + exe_name: &str, + classes: &[&str], + path: &str, + identifiers: &[MatchingRule], + regex_identifiers: &HashMap, +) -> Option { + let mut matching_rule = None; + for rule in identifiers { + match rule { + MatchingRule::Simple(identifier) => { + if should_act_individual( + title, + exe_name, + classes, + path, + identifier, + regex_identifiers, + ) { + matching_rule = Some(rule.clone()); + }; + } + MatchingRule::Composite(identifiers) => { + let mut composite_results = vec![]; + for identifier in identifiers { + composite_results.push(should_act_individual( + title, + exe_name, + classes, + path, + identifier, + regex_identifiers, + )); + } + + if composite_results.iter().all(|&x| x) { + matching_rule = Some(rule.clone()); + } + } + } + } + + matching_rule +} + +pub fn should_act_individual( + title: &str, + exe_name: &str, + classes: &[&str], + path: &str, + identifier: &IdWithIdentifier, + regex_identifiers: &HashMap, +) -> bool { + let mut should_act = false; + + let mut identifier = identifier.clone(); + identifier.id = identifier.id.replace(".exe", ""); + + match identifier.matching_strategy { + None | Some(MatchingStrategy::Legacy) => match identifier.kind { + ApplicationIdentifier::Title => { + if title.starts_with(&identifier.id) || title.ends_with(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Class => { + for class in classes { + if class.starts_with(&identifier.id) || class.ends_with(&identifier.id) { + should_act = true; + } + } + } + ApplicationIdentifier::Exe => { + if exe_name.eq(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Path => { + if path.eq(&identifier.id) { + should_act = true; + } + } + }, + Some(MatchingStrategy::Equals) => match identifier.kind { + ApplicationIdentifier::Title => { + if title.eq(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Class => { + for class in classes { + if class.eq(&identifier.id) { + should_act = true; + } + } + } + ApplicationIdentifier::Exe => { + if exe_name.eq(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Path => { + if path.eq(&identifier.id) { + should_act = true; + } + } + }, + Some(MatchingStrategy::DoesNotEqual) => match identifier.kind { + ApplicationIdentifier::Title => { + if !title.eq(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Class => { + for class in classes { + if !class.eq(&identifier.id) { + should_act = true; + } + } + } + ApplicationIdentifier::Exe => { + if !exe_name.eq(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Path => { + if !path.eq(&identifier.id) { + should_act = true; + } + } + }, + Some(MatchingStrategy::StartsWith) => match identifier.kind { + ApplicationIdentifier::Title => { + if title.starts_with(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Class => { + for class in classes { + if class.starts_with(&identifier.id) { + should_act = true; + } + } + } + ApplicationIdentifier::Exe => { + if exe_name.starts_with(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Path => { + if path.starts_with(&identifier.id) { + should_act = true; + } + } + }, + Some(MatchingStrategy::DoesNotStartWith) => match identifier.kind { + ApplicationIdentifier::Title => { + if !title.starts_with(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Class => { + for class in classes { + if !class.starts_with(&identifier.id) { + should_act = true; + } + } + } + ApplicationIdentifier::Exe => { + if !exe_name.starts_with(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Path => { + if !path.starts_with(&identifier.id) { + should_act = true; + } + } + }, + Some(MatchingStrategy::EndsWith) => match identifier.kind { + ApplicationIdentifier::Title => { + if title.ends_with(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Class => { + for class in classes { + if class.ends_with(&identifier.id) { + should_act = true; + } + } + } + ApplicationIdentifier::Exe => { + if exe_name.ends_with(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Path => { + if path.ends_with(&identifier.id) { + should_act = true; + } + } + }, + Some(MatchingStrategy::DoesNotEndWith) => match identifier.kind { + ApplicationIdentifier::Title => { + if !title.ends_with(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Class => { + for class in classes { + if !class.ends_with(&identifier.id) { + should_act = true; + } + } + } + ApplicationIdentifier::Exe => { + if !exe_name.ends_with(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Path => { + if !path.ends_with(&identifier.id) { + should_act = true; + } + } + }, + Some(MatchingStrategy::Contains) => match identifier.kind { + ApplicationIdentifier::Title => { + if title.contains(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Class => { + for class in classes { + if class.contains(&identifier.id) { + should_act = true; + } + } + } + ApplicationIdentifier::Exe => { + if exe_name.contains(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Path => { + if path.contains(&identifier.id) { + should_act = true; + } + } + }, + Some(MatchingStrategy::DoesNotContain) => match identifier.kind { + ApplicationIdentifier::Title => { + if !title.contains(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Class => { + for class in classes { + if !class.contains(&identifier.id) { + should_act = true; + } + } + } + ApplicationIdentifier::Exe => { + if !exe_name.contains(&identifier.id) { + should_act = true; + } + } + ApplicationIdentifier::Path => { + if !path.contains(&identifier.id) { + should_act = true; + } + } + }, + Some(MatchingStrategy::Regex) => match identifier.kind { + ApplicationIdentifier::Title => { + if let Some(re) = regex_identifiers.get(&identifier.id) + && re.is_match(title) + { + should_act = true; + } + } + ApplicationIdentifier::Class => { + if let Some(re) = regex_identifiers.get(&identifier.id) { + for class in classes { + if re.is_match(class) { + should_act = true; + } + } + } + } + ApplicationIdentifier::Exe => { + if let Some(re) = regex_identifiers.get(&identifier.id) + && re.is_match(exe_name) + { + should_act = true; + } + } + ApplicationIdentifier::Path => { + if let Some(re) = regex_identifiers.get(&identifier.id) + && re.is_match(path) + { + should_act = true; + } + } + }, + } + + should_act +} diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index 4791901c..b695d59c 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -1,16 +1,20 @@ use crate::CoreFoundationRunLoop; use crate::DATA_DIR; use crate::LibraryError; +use crate::REGEX_IDENTIFIERS; +use crate::WORKSPACE_MATCHING_RULES; use crate::accessibility::AccessibilityApi; use crate::application::Application; use crate::container::Container; use crate::core::CrossBoundaryBehaviour; use crate::core::MoveBehaviour; +use crate::core::OperationBehaviour; use crate::core::Placement; use crate::core::Sizing; use crate::core::WindowManagementBehaviour; use crate::core::arrangement::Arrangement; use crate::core::arrangement::Axis; +use crate::core::config_generation::MatchingRule; use crate::core::cycle_direction::CycleDirection; use crate::core::default_layout::DefaultLayout; use crate::core::layout::Layout; @@ -20,21 +24,28 @@ use crate::lockable_sequence::Lockable; use crate::macos_api::MacosApi; use crate::monitor::Monitor; use crate::ring::Ring; +use crate::static_config::StaticConfig; use crate::window::Window; +use crate::window::should_act_individual; use crate::window_manager_event::WindowManagerEvent; use crate::workspace::Workspace; use crate::workspace::WorkspaceLayer; use color_eyre::eyre; use color_eyre::eyre::OptionExt; +use color_eyre::eyre::bail; use crossbeam_channel::Receiver; +use hotwatch::Hotwatch; use objc2_core_foundation::CFRetained; use objc2_core_foundation::CFRunLoop; +use parking_lot::Mutex; use std::collections::HashMap; +use std::collections::HashSet; use std::collections::hash_map::Entry; use std::io::ErrorKind; use std::num::NonZeroUsize; use std::os::unix::net::UnixListener; use std::path::PathBuf; +use std::sync::Arc; #[derive(Debug)] pub struct WindowManager { @@ -44,6 +55,8 @@ pub struct WindowManager { pub command_listener: UnixListener, pub is_paused: bool, pub resize_delta: i32, + pub hotwatch: Hotwatch, + pub unmanaged_window_operation_behaviour: OperationBehaviour, pub window_management_behaviour: WindowManagementBehaviour, pub cross_monitor_move_behaviour: MoveBehaviour, pub cross_boundary_behaviour: CrossBoundaryBehaviour, @@ -51,10 +64,36 @@ pub struct WindowManager { pub work_area_offset: Option, pub incoming_events: Receiver, pub minimized_windows: HashMap, + pub already_moved_window_handles: Arc>>, } impl_ring_elements!(WindowManager, Monitor); +#[derive(Debug, Clone, Copy)] +struct EnforceWorkspaceRuleOp { + window_id: u32, + origin_monitor_idx: usize, + origin_workspace_idx: usize, + target_monitor_idx: usize, + target_workspace_idx: usize, + floating: bool, +} + +impl EnforceWorkspaceRuleOp { + const fn is_origin(&self, monitor_idx: usize, workspace_idx: usize) -> bool { + self.origin_monitor_idx == monitor_idx && self.origin_workspace_idx == workspace_idx + } + + const fn is_target(&self, monitor_idx: usize, workspace_idx: usize) -> bool { + self.target_monitor_idx == monitor_idx && self.target_workspace_idx == workspace_idx + } + + const fn is_enforced(&self) -> bool { + (self.origin_monitor_idx == self.target_monitor_idx) + && (self.origin_workspace_idx == self.target_workspace_idx) + } +} + impl WindowManager { #[allow(clippy::field_reassign_with_default)] pub fn new( @@ -87,6 +126,8 @@ impl WindowManager { command_listener: listener, is_paused: false, resize_delta: 50, + hotwatch: Hotwatch::new()?, + unmanaged_window_operation_behaviour: Default::default(), window_management_behaviour: behaviour, cross_monitor_move_behaviour: Default::default(), cross_boundary_behaviour: Default::default(), @@ -94,6 +135,7 @@ impl WindowManager { work_area_offset: None, incoming_events: incoming, minimized_windows: HashMap::new(), + already_moved_window_handles: Default::default(), }) } @@ -1851,4 +1893,267 @@ impl WindowManager { Ok(()) } + + #[tracing::instrument(skip(self), level = "debug")] + pub fn enforce_workspace_rules(&mut self) -> eyre::Result<()> { + let mut to_move = vec![]; + + let focused_monitor_idx = self.focused_monitor_idx(); + let focused_workspace_idx = self + .monitors() + .get(focused_monitor_idx) + .ok_or_eyre("there is no monitor with that index")? + .focused_workspace_idx(); + + // scope mutex locks to avoid deadlock if should_update_focused_workspace evaluates to true + // at the end of this function + { + let workspace_matching_rules = WORKSPACE_MATCHING_RULES.lock(); + let regex_identifiers = REGEX_IDENTIFIERS.lock(); + // Go through all the monitors and workspaces + for (i, monitor) in self.monitors().iter().enumerate() { + for (j, workspace) in monitor.workspaces().iter().enumerate() { + // And all the visible windows (at the top of a container) + for window in workspace.visible_windows().into_iter().flatten() { + if let ( + Some(exe_name), + Some(title), + Some(role), + Some(subrole), + Some(path), + ) = ( + window.exe(), + window.title(), + window.role(), + window.subrole(), + window.path(), + ) { + for rule in &*workspace_matching_rules { + let matched = match &rule.matching_rule { + MatchingRule::Simple(r) => should_act_individual( + &title, + &exe_name, + &[&role, &subrole], + &path.to_string_lossy(), + r, + ®ex_identifiers, + ), + MatchingRule::Composite(r) => { + let mut composite_results = vec![]; + for identifier in r { + composite_results.push(should_act_individual( + &title, + &exe_name, + &[&role, &subrole], + &path.to_string_lossy(), + identifier, + ®ex_identifiers, + )); + } + + composite_results.iter().all(|&x| x) + } + }; + + if matched { + let floating = workspace.floating_windows().contains(window); + + let mut already_moved_window_handles = + self.already_moved_window_handles.lock(); + + if rule.initial_only { + if !already_moved_window_handles.contains(&window.id) { + already_moved_window_handles.insert(window.id); + + self.add_window_handle_to_move_based_on_workspace_rule( + &window + .title() + .ok_or_eyre("could not read window title")?, + window.id, + i, + j, + rule.monitor_index, + rule.workspace_index, + floating, + &mut to_move, + ); + } + } else { + self.add_window_handle_to_move_based_on_workspace_rule( + &window + .title() + .ok_or_eyre("could not read window title")?, + window.id, + i, + j, + rule.monitor_index, + rule.workspace_index, + floating, + &mut to_move, + ); + } + } + } + } + } + } + } + } + + // Only retain operations where the target is not the current workspace + to_move.retain(|op| !op.is_target(focused_monitor_idx, focused_workspace_idx)); + // Only retain operations where the rule has not already been enforced + to_move.retain(|op| !op.is_enforced()); + + let mut should_update_focused_workspace = false; + let mut removed_windows = HashMap::new(); + + // Parse the operation and remove any windows that are not placed according to their rules + for op in &to_move { + let target_area = self + .monitors_mut() + .get_mut(op.target_monitor_idx) + .ok_or_eyre("there is no monitor with that index")? + .work_area_size; + + let origin_monitor = self + .monitors_mut() + .get_mut(op.origin_monitor_idx) + .ok_or_eyre("there is no monitor with that index")?; + + let origin_area = origin_monitor.work_area_size; + + let origin_workspace = origin_monitor + .workspaces_mut() + .get_mut(op.origin_workspace_idx) + .ok_or_eyre("there is no workspace with that index")?; + + // TODO: need to find a way to construct a lightweight window that can be operated on + // let mut window = Window::new(origin_workspace + // .window_by_id(op.window_id) + // .ok_or_eyre("there is no window with the requested id")?); + + let mut window = origin_workspace.remove_window(op.window_id)?; + + // If it is a floating window move it to the target area + if op.floating { + window.move_to_area(&origin_area, &target_area)?; + } + + // Hide the window we are about to remove if it is on the currently focused workspace + if op.is_origin(focused_monitor_idx, focused_workspace_idx) { + window.hide()?; + should_update_focused_workspace = true; + } + + removed_windows.insert(window.id, window); + } + + // Parse the operation again and associate those removed windows with the workspace that + // their rules have defined for them + for op in &to_move { + let window = removed_windows + .get_mut(&op.window_id) + .ok_or_eyre("there is no window")?; + + let target_monitor = self + .monitors_mut() + .get_mut(op.target_monitor_idx) + .ok_or_eyre("there is no monitor with that index")?; + + // The very first time this fn is called, the workspace might not even exist yet + if target_monitor + .workspaces() + .get(op.target_workspace_idx) + .is_none() + { + // If it doesn't, let's make sure it does for the next step + target_monitor.ensure_workspace_count(op.target_workspace_idx + 1); + } + + let target_workspace = target_monitor + .workspaces_mut() + .get_mut(op.target_workspace_idx) + .ok_or_eyre("there is no workspace with that index")?; + + if op.floating { + target_workspace + .floating_windows_mut() + // TODO: not sure about this clone + .push_back(window.clone()); + } else { + //TODO(alex-ds13): should this take into account the target workspace + //`window_container_behaviour`? + //In the case above a floating window should always be moved as floating, + //because it was set as so either manually by the user or by a + //`floating_applications` rule so it should stay that way. But a tiled window + //when moving to another workspace by a `workspace_rule` should honor that + //workspace `window_container_behaviour` in my opinion! Maybe this should be done + //on the `new_container_for_window` function instead. + // TODO: not sure about this clone + target_workspace.new_container_for_window(window)?; + } + } + + // Only re-tile the focused workspace if we need to + if should_update_focused_workspace { + self.update_focused_workspace(false, false)?; + } + + Ok(()) + } + + #[allow(clippy::too_many_arguments)] + #[tracing::instrument(skip(self), level = "debug")] + fn add_window_handle_to_move_based_on_workspace_rule( + &self, + window_title: &String, + window_id: u32, + origin_monitor_idx: usize, + origin_workspace_idx: usize, + target_monitor_idx: usize, + target_workspace_idx: usize, + floating: bool, + to_move: &mut Vec, + ) { + tracing::trace!( + "{} should be on monitor {}, workspace {}", + window_title, + target_monitor_idx, + target_workspace_idx + ); + + // Create an operation outline and save it for later in the fn + to_move.push(EnforceWorkspaceRuleOp { + window_id, + origin_monitor_idx, + origin_workspace_idx, + target_monitor_idx, + target_workspace_idx, + floating, + }); + } + + #[tracing::instrument(skip(self))] + pub fn reload_static_configuration(&mut self, pathbuf: &PathBuf) -> eyre::Result<()> { + tracing::info!("reloading static configuration"); + StaticConfig::reload(pathbuf, self) + } + + #[tracing::instrument(skip(self))] + pub fn handle_unmanaged_window_behaviour(&self) -> eyre::Result<()> { + if matches!( + self.unmanaged_window_operation_behaviour, + OperationBehaviour::NoOp + ) { + let workspace = self.focused_workspace()?; + let focused_hwnd = + MacosApi::foreground_window_id().ok_or_eyre("there is no foreground window")?; + if !workspace.contains_managed_window(focused_hwnd) { + bail!("ignoring commands while active window is not managed by komorebi"); + } + } + + Ok(()) + } } diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index 1b413c08..027088e7 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -11,6 +11,7 @@ use crate::core::rect::Rect; use crate::lockable_sequence::LockableSequence; use crate::macos_api::MacosApi; use crate::ring::Ring; +use crate::static_config::WorkspaceConfig; use crate::window::Window; use color_eyre::eyre; use color_eyre::eyre::OptionExt; @@ -46,6 +47,7 @@ pub struct Workspace { pub globals: WorkspaceGlobals, pub layer: WorkspaceLayer, pub floating_layer_behaviour: Option, + pub workspace_config: Option, } #[derive(Debug, Default, Copy, Clone, Serialize, Deserialize, PartialEq, Eq)] @@ -94,6 +96,7 @@ impl Default for Workspace { floating_windows: Default::default(), float_override: None, floating_layer_behaviour: None, + workspace_config: None, } } } @@ -113,6 +116,67 @@ pub struct WorkspaceGlobals { } impl Workspace { + pub fn load_static_config(&mut self, config: &WorkspaceConfig) -> eyre::Result<()> { + self.name = Option::from(config.name.clone()); + + self.container_padding = config.container_padding; + + self.workspace_padding = config.workspace_padding; + + if let Some(layout) = &config.layout { + self.layout = Layout::Default(*layout); + } + + self.tile = + !(config.custom_layout.is_none() && config.layout.is_none() && config.tile.is_none() + || config.tile.is_some_and(|tile| !tile)); + + let mut all_layout_rules = vec![]; + if let Some(layout_rules) = &config.layout_rules { + for (count, rule) in layout_rules { + all_layout_rules.push((*count, Layout::Default(*rule))); + } + + all_layout_rules.sort_by_key(|(i, _)| *i); + self.tile = true; + } + + self.layout_rules = all_layout_rules.clone(); + + self.work_area_offset = config.work_area_offset; + + self.apply_window_based_work_area_offset = + config.apply_window_based_work_area_offset.unwrap_or(true); + + self.window_container_behaviour = config.window_container_behaviour; + + if let Some(window_container_behaviour_rules) = &config.window_container_behaviour_rules { + if window_container_behaviour_rules.is_empty() { + self.window_container_behaviour_rules = None; + } else { + let mut all_rules = vec![]; + for (count, behaviour) in window_container_behaviour_rules { + all_rules.push((*count, *behaviour)); + } + + all_rules.sort_by_key(|(i, _)| *i); + self.window_container_behaviour_rules = Some(all_rules); + } + } else { + self.window_container_behaviour_rules = None; + } + + self.float_override = config.float_override; + self.layout_flip = config.layout_flip; + self.floating_layer_behaviour = config.floating_layer_behaviour; + // self.wallpaper = config.wallpaper.clone(); + self.layout_options = config.layout_options; + + self.workspace_config = Some(config.clone()); + + Ok(()) + } + #[tracing::instrument(skip(self))] pub fn focus_container(&mut self, idx: usize) { tracing::info!("focusing container"); @@ -350,6 +414,40 @@ impl Workspace { } } + if let Some(window) = &self.maximized_window + && window_id == window.id + { + return true; + } + + if let Some(container) = &self.monocle_container + && container.contains_window(window_id) + { + return true; + } + + for window in self.floating_windows() { + if window_id == window.id { + return true; + } + } + + false + } + + pub fn contains_managed_window(&self, window_id: u32) -> bool { + for container in self.containers() { + if container.contains_window(window_id) { + return true; + } + } + + if let Some(window) = &self.maximized_window + && window_id == window.id + { + return true; + } + if let Some(container) = &self.monocle_container && container.contains_window(window_id) { @@ -701,6 +799,26 @@ impl Workspace { self.floating_windows.focus(idx); } + + pub fn visible_windows(&self) -> Vec> { + let mut vec = vec![]; + + vec.push(self.maximized_window.as_ref()); + + if let Some(monocle) = &self.monocle_container { + vec.push(monocle.focused_window()); + } + + for container in self.containers() { + vec.push(container.focused_window()); + } + + for window in self.floating_windows() { + vec.push(Some(window)); + } + + vec + } } impl Workspace {