From df9ceee17ec1cb6e1a9d562ce5d625c5d65ac4f2 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Wed, 17 Sep 2025 16:18:04 -0700 Subject: [PATCH] feat(wm): migrate ipc and impl basic socket messages This commit migrates another bunch of code from komorebi to start implementing inter-process communication using Unix domain sockets. For this commit a small subsection of the SocketMessage with maximum utility has been migrated: FocusWindow, MoveWindow, ChangeLayout, and TogglePause. This includes migrating their handlers in process_command, and setting up a UnixListener when creating a WindowManager instance. To be able to test this functionality I also implemented a basic skeleton of komorebic and migrated the komorebi-client library. There are some random fixes included here now that we are listening to a UnixListener on a separate thread, which includes wrapping structs from the objc2 crate which don't have Send and Sync implemented, so that they can be implemented in the komorebi lib. I also took the time to figure out how to calculate a monitor's work area size, excluding the dock and the menu bar, and started to split out Workspace and Monitor into their own modules. It looks like a lot of changes but most if this is just pulling in stuff from the Windows implementation. --- .gitignore | 2 +- Cargo.lock | 922 ++++++++++++++++++++++- Cargo.toml | 16 +- flake.nix | 37 +- komorebi-client/Cargo.toml | 8 + komorebi-client/src/lib.rs | 54 ++ komorebi/Cargo.toml | 15 +- komorebi/src/accessibility/mod.rs | 2 +- komorebi/src/application.rs | 14 +- komorebi/src/core/default_layout.rs | 3 +- komorebi/src/core/mod.rs | 31 + komorebi/src/core/operation_direction.rs | 6 +- komorebi/src/core/pathext.rs | 196 +++++ komorebi/src/core_graphics/mod.rs | 15 + komorebi/src/lib.rs | 70 ++ komorebi/src/lockable_sequence.rs | 363 +++++++++ komorebi/src/macos_api.rs | 72 +- komorebi/src/main.rs | 19 +- komorebi/src/monitor.rs | 88 +++ komorebi/src/process_command.rs | 122 +++ komorebi/src/window.rs | 23 +- komorebi/src/window_manager.rs | 255 ++++++- komorebi/src/workspace.rs | 29 +- komorebic/Cargo.toml | 13 + komorebic/src/main.rs | 100 +++ shell.nix | 3 +- 26 files changed, 2375 insertions(+), 103 deletions(-) create mode 100644 komorebi-client/Cargo.toml create mode 100644 komorebi-client/src/lib.rs create mode 100644 komorebi/src/core/pathext.rs create mode 100644 komorebi/src/lockable_sequence.rs create mode 100644 komorebi/src/monitor.rs create mode 100644 komorebi/src/process_command.rs create mode 100644 komorebic/Cargo.toml create mode 100644 komorebic/src/main.rs diff --git a/.gitignore b/.gitignore index b824c3d8..d7ae555d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,4 @@ /target -/result +/result* /.idea /.direnv diff --git a/Cargo.lock b/Cargo.lock index c8ecb3cb..cd2874b8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -26,6 +26,71 @@ dependencies = [ "memchr", ] +[[package]] +name = "android_system_properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + +[[package]] +name = "anstream" +version = "0.6.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ae563653d1938f79b1ab1b5e668c87c76a9930414574a6583a7b7e11a8e6192" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "862ed96ca487e809f1c8e5a8447f6ee2cf102f846893800b20cebdf541fc6bbd" + +[[package]] +name = "anstyle-parse" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e231f6134f61b71076a3eab506c379d4f36122f2af15a9ff04415ea4c3339e2" +dependencies = [ + "windows-sys 0.60.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e0633414522a32ffaac8ac6cc8f748e090c5717661fddeea04219e2344f5f2a" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.60.2", +] + +[[package]] +name = "autocfg" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" + [[package]] name = "backtrace" version = "0.3.75" @@ -38,9 +103,15 @@ dependencies = [ "miniz_oxide", "object", "rustc-demangle", - "windows-targets", + "windows-targets 0.52.6", ] +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + [[package]] name = "bitflags" version = "2.9.4" @@ -56,6 +127,22 @@ dependencies = [ "objc2", ] +[[package]] +name = "bumpalo" +version = "3.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46c5e41b57b8bba42a04676d81cb89e9ee8e859a1a66f80a5a72e1cb76b34d43" + +[[package]] +name = "cc" +version = "1.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65193589c6404eb80b450d618eaf9a2cafaaafd57ecce47370519ef674a7bd44" +dependencies = [ + "find-msvc-tools", + "shlex", +] + [[package]] name = "cfg-if" version = "1.0.3" @@ -68,6 +155,59 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" +[[package]] +name = "chrono" +version = "0.4.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "145052bdd345b87320e369255277e3fb5152762ad123a901ef5c262dd38fe8d2" +dependencies = [ + "iana-time-zone", + "num-traits", + "serde", + "windows-link 0.2.0", +] + +[[package]] +name = "clap" +version = "4.5.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7eac00902d9d136acd712710d71823fb8ac8004ca445a89e73a41d45aa712931" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.5.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ad9bbf750e73b5884fb8a211a9424a1906c1e156724260fdae972f31d70e1d6" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", + "terminal_size", +] + +[[package]] +name = "clap_derive" +version = "4.5.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbfd7eae0b0f1a6e63d4b13c9c478de77c2eb546fba158ad50b4203dc24b9f9c" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "clap_lex" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b94f61472cee1439c0b966b47e3aca9ae07e45d070759512cd390ea2bebc6675" + [[package]] name = "color-eyre" version = "0.6.5" @@ -95,6 +235,18 @@ dependencies = [ "tracing-error", ] +[[package]] +name = "colorchoice" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75" + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + [[package]] name = "ctrlc" version = "3.5.0" @@ -106,6 +258,72 @@ dependencies = [ "windows-sys 0.61.0", ] +[[package]] +name = "darling" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn", +] + +[[package]] +name = "darling_macro" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" +dependencies = [ + "darling_core", + "quote", + "syn", +] + +[[package]] +name = "deranged" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d630bccd429a5bb5a64b5e94f693bfc48c9f8566418fda4c494cc94f911f87cc" +dependencies = [ + "powerfmt", + "serde", +] + +[[package]] +name = "dirs" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" +dependencies = [ + "libc", + "option-ext", + "redox_users", + "windows-sys 0.61.0", +] + [[package]] name = "dispatch" version = "0.2.0" @@ -122,6 +340,28 @@ dependencies = [ "objc2", ] +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.0", +] + [[package]] name = "eyre" version = "0.6.12" @@ -132,36 +372,185 @@ dependencies = [ "once_cell", ] +[[package]] +name = "find-msvc-tools" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fd99930f64d146689264c637b5af2f0233a933bef0d8570e2526bf9e083192d" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "getrandom" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + [[package]] name = "gimli" version = "0.31.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f" +[[package]] +name = "hashbrown" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "iana-time-zone" +version = "0.1.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33e57f83510bb73707521ebaffa789ec8caf86f9657cad665b092b581d40e9fb" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + [[package]] name = "indenter" version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "964de6e86d545b246d84badc0fef527924ace5134f30641c203ef52ba83f58d5" +[[package]] +name = "indexmap" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" +dependencies = [ + "autocfg", + "hashbrown 0.12.3", + "serde", +] + +[[package]] +name = "indexmap" +version = "2.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92119844f513ffa41556430369ab02c295a3578af21cf945caa3e9e0c2481ac3" +dependencies = [ + "equivalent", + "hashbrown 0.15.5", + "serde", + "serde_core", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf" + +[[package]] +name = "itoa" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" + +[[package]] +name = "js-sys" +version = "0.3.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "852f13bec5eba4ba9afbeb93fd7c13fe56147f055939ae21c43a29a0ecb2702e" +dependencies = [ + "once_cell", + "wasm-bindgen", +] + [[package]] name = "komorebi" version = "0.1.0" dependencies = [ + "clap", "color-eyre", "ctrlc", + "dirs", + "lazy_static", "objc2", "objc2-app-kit", "objc2-application-services", "objc2-core-foundation", "objc2-core-graphics", + "parking_lot", "pastey", "serde", + "serde_json_lenient", + "serde_with", + "strum", "thiserror", "tracing", "tracing-subscriber", ] +[[package]] +name = "komorebi-client" +version = "0.1.0" +dependencies = [ + "komorebi", + "serde_json_lenient", +] + +[[package]] +name = "komorebic" +version = "0.1.0" +dependencies = [ + "clap", + "color-eyre", + "dirs", + "komorebi-client", + "lazy_static", + "pastey", +] + [[package]] name = "lazy_static" version = "1.5.0" @@ -174,6 +563,32 @@ version = "0.2.175" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a82ae493e598baaea5209805c49bbf2ea7de956d50d7da0da1164f9c6d28543" +[[package]] +name = "libredox" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "416f7e718bdb06000964960ffa43b4335ad4012ae8b99060261aa4a8088d5ccb" +dependencies = [ + "bitflags", + "libc", +] + +[[package]] +name = "linux-raw-sys" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039" + +[[package]] +name = "lock_api" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96936507f153605bddfcda068dd804796c84324ed2510809e5b2a624c81da765" +dependencies = [ + "autocfg", + "scopeguard", +] + [[package]] name = "log" version = "0.4.28" @@ -225,6 +640,21 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "num-conv" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + [[package]] name = "objc2" version = "0.6.2" @@ -417,12 +847,47 @@ version = "1.21.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" +[[package]] +name = "once_cell_polyfill" +version = "1.70.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4895175b425cb1f87721b59f0f286c2092bd4af812243672510e1ac53e2e0ad" + +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + [[package]] name = "owo-colors" version = "4.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "48dd4f4a2c8405440fd0462561f0e5806bd0f77e86f51c761481bdd4018b545e" +[[package]] +name = "parking_lot" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70d58bf43669b5795d1576d0641cfb6fbb2057bf629506267a92807158584a13" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc838d2a56b5b1a6c25f55575dfc605fabb63bb2365f6c2353ef9159aa69e4a5" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-targets 0.52.6", +] + [[package]] name = "pastey" version = "0.1.1" @@ -435,6 +900,12 @@ version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b" +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + [[package]] name = "proc-macro2" version = "1.0.101" @@ -453,6 +924,46 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "redox_syscall" +version = "0.5.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5407465600fb0548f1442edf71dd20683c6ed326200ace4b1ef0763521bb3b77" +dependencies = [ + "bitflags", +] + +[[package]] +name = "redox_users" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac" +dependencies = [ + "getrandom", + "libredox", + "thiserror", +] + +[[package]] +name = "ref-cast" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a0ae411dbe946a674d89546582cea4ba2bb8defac896622d6496f14c23ba5cf" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1165225c21bff1f3bbce98f5a1f889949bc902d3575308cc7b0de30b4f6d27c7" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "regex-automata" version = "0.4.10" @@ -476,6 +987,61 @@ version = "0.1.26" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "56f7d92ca342cea22a06f2121d944b4fd82af56988c270852495420f961d4ace" +[[package]] +name = "rustix" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd15f8a2c5551a84d56efdc1cd049089e409ac19a3072d5037a17fd70719ff3e" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.0", +] + +[[package]] +name = "rustversion" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" + +[[package]] +name = "ryu" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" + +[[package]] +name = "schemars" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cd191f9397d57d581cddd31014772520aa448f65ef991055d7f61582c65165f" +dependencies = [ + "dyn-clone", + "ref-cast", + "serde", + "serde_json", +] + +[[package]] +name = "schemars" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82d20c4491bc164fa2f6c5d44565947a52ad80b9505d8e36f8d54c27c739fcd0" +dependencies = [ + "dyn-clone", + "ref-cast", + "serde", + "serde_json", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + [[package]] name = "serde" version = "1.0.225" @@ -506,6 +1072,63 @@ dependencies = [ "syn", ] +[[package]] +name = "serde_json" +version = "1.0.145" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "402a6f66d8c709116cf22f558eab210f5a50187f702eb4d7e5ef38d9a7f1c79c" +dependencies = [ + "itoa", + "memchr", + "ryu", + "serde", + "serde_core", +] + +[[package]] +name = "serde_json_lenient" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e033097bf0d2b59a62b42c18ebbb797503839b26afdda2c4e1415cb6c813540" +dependencies = [ + "itoa", + "memchr", + "ryu", + "serde", +] + +[[package]] +name = "serde_with" +version = "3.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2c45cd61fefa9db6f254525d46e392b852e0e61d9a1fd36e5bd183450a556d5" +dependencies = [ + "base64", + "chrono", + "hex", + "indexmap 1.9.3", + "indexmap 2.11.3", + "schemars 0.9.0", + "schemars 1.0.4", + "serde", + "serde_derive", + "serde_json", + "serde_with_macros", + "time", +] + +[[package]] +name = "serde_with_macros" +version = "3.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de90945e6565ce0d9a25098082ed4ee4002e047cb59892c318d66821e14bb30f" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "sharded-slab" version = "0.1.7" @@ -515,12 +1138,45 @@ dependencies = [ "lazy_static", ] +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + [[package]] name = "smallvec" version = "1.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "strum" +version = "0.27.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.27.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7695ce3845ea4b33927c055a39dc438a45b059f7c1b3d91d38d10355fb8cbca7" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "syn" version = "2.0.106" @@ -532,6 +1188,16 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "terminal_size" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60b8cb979cb11c32ce1603f8137b22262a9d131aaa5c37b5678025f22b8becd0" +dependencies = [ + "rustix", + "windows-sys 0.60.2", +] + [[package]] name = "thiserror" version = "2.0.16" @@ -561,6 +1227,36 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "time" +version = "0.3.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83bde6f1ec10e72d583d91623c939f623002284ef622b87de38cfd546cbf2031" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40868e7c1d2f0b8d73e4a8c7f0ff63af4f6d19be117e90bd73eb1d62cf831c6b" + +[[package]] +name = "time-macros" +version = "0.2.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30cfb0125f12d9c277f35663a0a33f8c30190f4e4574868a330595412d34ebf3" +dependencies = [ + "num-conv", + "time-core", +] + [[package]] name = "tracing" version = "0.1.41" @@ -638,25 +1334,164 @@ version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f63a545481291138910575129486daeaf8ac54aee4387fe7906919f7830c7d9d" +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + [[package]] name = "valuable" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab10a69fbd0a177f5f649ad4d8d3305499c42bab9aef2f7ff592d0ec8f833819" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-backend" +version = "0.2.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb702423545a6007bbc368fde243ba47ca275e549c8a28617f56f6ba53b1d1c" +dependencies = [ + "bumpalo", + "log", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc65f4f411d91494355917b605e1480033152658d71f722a90647f56a70c88a0" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffc003a991398a8ee604a401e194b6b3a39677b3173d6e74495eb51b82e99a32" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-backend", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "293c37f4efa430ca14db3721dfbe48d8c33308096bd44d80ebaa775ab71ba1cf" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "windows-core" +version = "0.62.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57fe7168f7de578d2d8a05b07fd61870d2e73b4020e9f49aa00da8471723497c" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link 0.2.0", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a47fddd13af08290e67f4acabf4b459f647552718f683a7b415d290ac744a836" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-interface" +version = "0.59.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd9211b69f8dcdfa817bfd14bf1c97c9188afa36f4750130fcdf3f400eca9fa8" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-link" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a" + [[package]] name = "windows-link" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "45e46c0661abb7180e7b9c281db115305d49ca1709ab8242adf09666d2173c65" +[[package]] +name = "windows-result" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7084dcc306f89883455a206237404d3eaf961e5bd7e0f312f7c91f57eb44167f" +dependencies = [ + "windows-link 0.2.0", +] + +[[package]] +name = "windows-strings" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7218c655a553b0bed4426cf54b20d7ba363ef543b52d515b3e48d7fd55318dda" +dependencies = [ + "windows-link 0.2.0", +] + [[package]] name = "windows-sys" version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ - "windows-targets", + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.3", ] [[package]] @@ -665,7 +1500,7 @@ version = "0.61.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e201184e40b2ede64bc2ea34968b28e33622acdbbf37104f0e4a33f7abe657aa" dependencies = [ - "windows-link", + "windows-link 0.2.0", ] [[package]] @@ -674,14 +1509,31 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_gnullvm", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm 0.52.6", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.53.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5fe6031c4041849d7c496a8ded650796e7b6ecc19df1a431c1a363342e5dc91" +dependencies = [ + "windows-link 0.1.3", + "windows_aarch64_gnullvm 0.53.0", + "windows_aarch64_msvc 0.53.0", + "windows_i686_gnu 0.53.0", + "windows_i686_gnullvm 0.53.0", + "windows_i686_msvc 0.53.0", + "windows_x86_64_gnu 0.53.0", + "windows_x86_64_gnullvm 0.53.0", + "windows_x86_64_msvc 0.53.0", ] [[package]] @@ -690,44 +1542,92 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86b8d5f90ddd19cb4a147a5fa63ca848db3df085e25fee3cc10b39b6eebae764" + [[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7651a1f62a11b8cbd5e0d42526e55f2c99886c77e007179efff86c2b137e66c" + [[package]] name = "windows_i686_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" +[[package]] +name = "windows_i686_gnu" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1dc67659d35f387f5f6c479dc4e28f1d4bb90ddd1a5d3da2e5d97b42d6272c3" + [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce6ccbdedbf6d6354471319e781c0dfef054c81fbc7cf83f338a4296c0cae11" + [[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" +[[package]] +name = "windows_i686_msvc" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "581fee95406bb13382d2f65cd4a908ca7b1e4c2f1917f143ba16efe98a589b5d" + [[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e55b5ac9ea33f2fc1716d1742db15574fd6fc8dadc51caab1c16a3d3b4190ba" + [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a6e035dd0599267ce1ee132e51c27dd29437f63325753051e71dd9e42406c57" + [[package]] name = "windows_x86_64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "271414315aff87387382ec3d271b52d7ae78726f5d44ac98b4f4030c91880486" diff --git a/Cargo.toml b/Cargo.toml index 272a0c63..35a63335 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,5 +2,17 @@ resolver = "2" members = [ - "komorebi", -] \ No newline at end of file + "komorebi", "komorebi-client", + "komorebic", +] + + +[workspace.dependencies] +clap = { version = "4", features = ["derive", "wrap_help"] } +color-eyre = "0.6" +dirs = "6" +lazy_static = "1" +pastey = "0.1" +serde = { version = "1", features = ["derive"] } +serde_json = { package = "serde_json_lenient", version = "0.2" } +thiserror = "2" diff --git a/flake.nix b/flake.nix index 61198d2f..2f621e73 100644 --- a/flake.nix +++ b/flake.nix @@ -13,6 +13,7 @@ overlays = [ (import rust-overlay) ]; + pkgs = (import nixpkgs) { inherit system overlays; }; @@ -21,15 +22,12 @@ toolchain = pkgs.rust-bin.fromRustupToolchainFile ./rust-toolchain.toml; craneLib = (crane.mkLib pkgs).overrideToolchain toolchain; - - pname = "komorebi"; + src = craneLib.cleanCargoSource ./.; version = "0.1.0"; commonArgs = { - inherit pname version; - nativeBuildInputs = with pkgs; [ -# pkg-config - ]; + inherit src; + nativeBuildInputs = with pkgs; []; doCheck = false; buildInputs = with pkgs; [ gcc @@ -37,23 +35,34 @@ ]; }; - cargoArtifacts = craneLib.buildDepsOnly (commonArgs - // { - src = craneLib.cleanCargoSource (craneLib.path ./.); - }); + cargoArtifacts = craneLib.buildDepsOnly commonArgs; - komorebi = craneLib.buildPackage (commonArgs + komorebi = craneLib.buildPackage ( + commonArgs // { - inherit cargoArtifacts; + inherit version; + pname = "komorebi"; + cargoExtraArgs = "-p komorebi"; src = ./.; - }); + } + ); + + komorebic = craneLib.buildPackage ( + commonArgs + // { + inherit version; + pname = "komorebic"; + cargoExtraArgs = "-p komorebic"; + src = ./.; + } + ); in { devShells = flake-utils.lib.flattenTree { default = import ./shell.nix {inherit pkgs;}; }; packages = flake-utils.lib.flattenTree rec { - inherit komorebi; + inherit komorebi komorebic; default = komorebi; }; } diff --git a/komorebi-client/Cargo.toml b/komorebi-client/Cargo.toml new file mode 100644 index 00000000..6853093c --- /dev/null +++ b/komorebi-client/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "komorebi-client" +version = "0.1.0" +edition = "2024" + +[dependencies] +komorebi = { path = "../komorebi", default-features = false } +serde_json = { workspace = true } diff --git a/komorebi-client/src/lib.rs b/komorebi-client/src/lib.rs new file mode 100644 index 00000000..609bb5d1 --- /dev/null +++ b/komorebi-client/src/lib.rs @@ -0,0 +1,54 @@ +pub use komorebi::DATA_DIR; +pub use komorebi::core::SocketMessage; +pub use komorebi::core::default_layout::DefaultLayout; +pub use komorebi::core::operation_direction::OperationDirection; +pub use komorebi::core::pathext::PathExt; +use std::borrow::Borrow; +use std::io::BufReader; +use std::io::Read; +use std::io::Write; +use std::net::Shutdown; +use std::os::unix::net::UnixStream; +use std::time::Duration; + +const KOMOREBI: &str = "komorebi.sock"; + +pub fn send_message(message: &SocketMessage) -> std::io::Result<()> { + let socket = DATA_DIR.join(KOMOREBI); + let mut stream = UnixStream::connect(socket)?; + stream.set_write_timeout(Some(Duration::from_secs(1)))?; + stream.write_all(serde_json::to_string(message)?.as_bytes()) +} + +pub fn send_batch(messages: impl IntoIterator) -> std::io::Result<()> +where + Q: Borrow, +{ + let socket = DATA_DIR.join(KOMOREBI); + let mut stream = UnixStream::connect(socket)?; + stream.set_write_timeout(Some(Duration::from_secs(1)))?; + let msgs = messages.into_iter().fold(String::new(), |mut s, m| { + if let Ok(m_str) = serde_json::to_string(m.borrow()) { + s.push_str(&m_str); + s.push('\n'); + } + s + }); + stream.write_all(msgs.as_bytes()) +} + +pub fn send_query(message: &SocketMessage) -> std::io::Result { + let socket = DATA_DIR.join(KOMOREBI); + + let mut stream = UnixStream::connect(socket)?; + stream.set_read_timeout(Some(Duration::from_secs(1)))?; + stream.set_write_timeout(Some(Duration::from_secs(1)))?; + stream.write_all(serde_json::to_string(message)?.as_bytes())?; + stream.shutdown(Shutdown::Write)?; + + let mut reader = BufReader::new(stream); + let mut response = String::new(); + reader.read_to_string(&mut response)?; + + Ok(response) +} diff --git a/komorebi/Cargo.toml b/komorebi/Cargo.toml index 6e29f99a..41542be9 100644 --- a/komorebi/Cargo.toml +++ b/komorebi/Cargo.toml @@ -4,15 +4,22 @@ version = "0.1.0" edition = "2024" [dependencies] -color-eyre = { version = "0.6" } +clap = { workspace = true } +color-eyre = { workspace = true } ctrlc = { version = "3", features = ["termination"] } +dirs = { workspace = true } +lazy_static = { workspace = true } objc2 = "0.6" objc2-app-kit = "0.3" objc2-application-services = "0.3" objc2-core-foundation = { version = "0.3", features = ["CFDictionary", "CFString"] } objc2-core-graphics = { version = "0.3", features = ["CGWindow", "alloc"] } -pastey = "0.1" -serde = { version = "1", features = ["derive"]} -thiserror = "2" +parking_lot = "0.12" +pastey = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +serde_with = "3" +strum = { version = "0.27", features = ["derive"] } +thiserror = { workspace = true } tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } \ No newline at end of file diff --git a/komorebi/src/accessibility/mod.rs b/komorebi/src/accessibility/mod.rs index e79db36a..998c2648 100644 --- a/komorebi/src/accessibility/mod.rs +++ b/komorebi/src/accessibility/mod.rs @@ -134,7 +134,7 @@ impl AccessibilityApi { observer: &AXObserver, element: &AXUIElement, notifications: &[&'static str], - run_loop: &CFRetained, + run_loop: &CFRunLoop, ) -> Result<(), AccessibilityError> { AccessibilityApi::add_notifications_to_observer(observer, element, notifications)?; diff --git a/komorebi/src/application.rs b/komorebi/src/application.rs index 0da446e0..f76f9684 100644 --- a/komorebi/src/application.rs +++ b/komorebi/src/application.rs @@ -1,3 +1,5 @@ +use crate::AccessibilityObserver; +use crate::AccessibilityUiElement; use crate::accessibility::AccessibilityApi; use crate::accessibility::attribute_constants::kAXTitleAttribute; use crate::accessibility::attribute_constants::kAXWindowsAttribute; @@ -36,9 +38,9 @@ const NOTIFICATIONS: &[&str] = &[ #[derive(Debug, Clone)] pub struct Application { - element: CFRetained, + element: AccessibilityUiElement, pub process_id: i32, - pub observer: CFRetained, + pub observer: AccessibilityObserver, } #[instrument(skip_all)] @@ -84,12 +86,12 @@ impl Drop for Application { impl Application { pub fn new(process_id: i32) -> Result { Ok(Self { - element: AccessibilityApi::create_application(process_id), + element: AccessibilityUiElement(AccessibilityApi::create_application(process_id)), process_id, - observer: AccessibilityApi::create_observer( + observer: AccessibilityObserver(AccessibilityApi::create_observer( process_id, Some(application_observer_callback), - )?, + )?), }) } @@ -99,7 +101,7 @@ impl Application { } #[tracing::instrument(skip_all)] - pub fn observe(&self, run_loop: &CFRetained) -> Result<(), AccessibilityError> { + pub fn observe(&self, run_loop: &CFRunLoop) -> Result<(), AccessibilityError> { tracing::info!( "registering observer for process: {}, name: {}", self.process_id, diff --git a/komorebi/src/core/default_layout.rs b/komorebi/src/core/default_layout.rs index 43f208a4..d545a9f3 100644 --- a/komorebi/src/core/default_layout.rs +++ b/komorebi/src/core/default_layout.rs @@ -1,10 +1,11 @@ use crate::core::Sizing; use crate::core::operation_direction::OperationDirection; use crate::core::rect::Rect; +use clap::ValueEnum; use serde::Deserialize; use serde::Serialize; -#[derive(Clone, Copy, Debug, Serialize, Deserialize, Eq, PartialEq)] +#[derive(Clone, Copy, Debug, Serialize, Deserialize, Eq, PartialEq, ValueEnum)] pub enum DefaultLayout { BSP, Columns, diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index 2daf9079..61da4434 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -1,11 +1,17 @@ +use crate::core::default_layout::DefaultLayout; +use crate::core::operation_direction::OperationDirection; +use color_eyre::eyre; use serde::Deserialize; use serde::Serialize; +use std::str::FromStr; +use strum::Display; pub mod arrangement; pub mod default_layout; pub mod direction; pub mod layout; pub mod operation_direction; +pub mod pathext; pub mod rect; #[derive(Clone, Copy, Debug, Serialize, Deserialize)] @@ -13,3 +19,28 @@ pub enum Sizing { Increase, Decrease, } + +#[serde_with::serde_as] +#[derive(Clone, Debug, Serialize, Deserialize, Display)] +#[serde(tag = "type", content = "content")] +pub enum SocketMessage { + // Window / Container Commands + FocusWindow(OperationDirection), + MoveWindow(OperationDirection), + ChangeLayout(DefaultLayout), + TogglePause, +} + +impl SocketMessage { + pub fn as_bytes(&self) -> eyre::Result> { + Ok(serde_json::to_string(self)?.as_bytes().to_vec()) + } +} + +impl FromStr for SocketMessage { + type Err = serde_json::Error; + + fn from_str(s: &str) -> Result { + serde_json::from_str(s) + } +} diff --git a/komorebi/src/core/operation_direction.rs b/komorebi/src/core/operation_direction.rs index 0c66d6bf..dd526271 100644 --- a/komorebi/src/core/operation_direction.rs +++ b/komorebi/src/core/operation_direction.rs @@ -1,11 +1,11 @@ -use std::num::NonZeroUsize; - use crate::core::arrangement::Axis; use crate::core::direction::Direction; +use clap::ValueEnum; use serde::Deserialize; use serde::Serialize; +use std::num::NonZeroUsize; -#[derive(Clone, Copy, Debug, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Serialize, Deserialize, ValueEnum)] pub enum OperationDirection { Left, Right, diff --git a/komorebi/src/core/pathext.rs b/komorebi/src/core/pathext.rs new file mode 100644 index 00000000..7110c485 --- /dev/null +++ b/komorebi/src/core/pathext.rs @@ -0,0 +1,196 @@ +use std::collections::HashMap; +use std::env; +use std::ffi::OsStr; +use std::path::Component; +use std::path::Path; +use std::path::PathBuf; + +use serde::Deserialize; +use serde::Serialize; + +/// Path extension trait +pub trait PathExt { + /// Resolve environment variable components in a path. + /// + /// Resolves the following formats: + /// - CMD: `%variable%` + /// - PowerShell: `$Env:variable` + /// - Bash: `$variable`. + fn replace_env(&self) -> PathBuf; +} + +/// Blanket implementation for all types that can be converted to a `Path`. +impl> PathExt for P { + fn replace_env(&self) -> PathBuf { + let mut out = PathBuf::new(); + + for c in self.as_ref().components() { + match c { + Component::Normal(mut c) => { + // Special case for ~ and $HOME, replace with $Env:USERPROFILE + if c == OsStr::new("~") || c.eq_ignore_ascii_case("$HOME") { + c = OsStr::new("$Env:USERPROFILE"); + } + + let bytes = c.as_encoded_bytes(); + + // %LOCALAPPDATA% + let var = if bytes[0] == b'%' && bytes[bytes.len() - 1] == b'%' { + Some(&bytes[1..bytes.len() - 1]) + } else { + // prefix length is 5 for $Env: and 1 for $ + // so we take the minimum of 5 and the length of the bytes + let prefix = &bytes[..5.min(bytes.len())]; + let prefix = unsafe { OsStr::from_encoded_bytes_unchecked(prefix) }; + + // $Env:LOCALAPPDATA + if prefix.eq_ignore_ascii_case("$Env:") { + Some(&bytes[5..]) + } else if bytes[0] == b'$' { + // $LOCALAPPDATA + Some(&bytes[1..]) + } else { + // not a variable + None + } + }; + + // if component is a variable, get the value from the environment + if let Some(var) = var { + let var = unsafe { OsStr::from_encoded_bytes_unchecked(var) }; + if let Some(value) = env::var_os(var) { + out.push(value); + continue; + } + } + + // if not a variable, or a value couldn't be obtained from environemnt + // then push the component as is + out.push(c); + } + + // other components are pushed as is + _ => out.push(c), + } + } + + out + } +} + +/// Replace environment variables in a path. This is a wrapper around +/// [`PathExt::replace_env`] to be used in Clap arguments parsing. +pub fn replace_env_in_path(input: &str) -> Result { + Ok(input.replace_env()) +} + +/// A wrapper around [`PathBuf`] that has a custom [Deserialize] implementation +/// that uses [`PathExt::replace_env`] to resolve environment variables +#[derive(Clone, Debug)] +pub struct ResolvedPathBuf(PathBuf); + +impl ResolvedPathBuf { + /// Create a new [`ResolvedPathBuf`] from a [`PathBuf`] + pub fn new(path: PathBuf) -> Self { + Self(path.replace_env()) + } +} + +impl From for PathBuf { + fn from(path: ResolvedPathBuf) -> Self { + path.0 + } +} + +impl serde_with::SerializeAs for ResolvedPathBuf { + fn serialize_as(path: &PathBuf, serializer: S) -> Result + where + S: serde::Serializer, + { + path.serialize(serializer) + } +} + +impl<'de> serde_with::DeserializeAs<'de, PathBuf> for ResolvedPathBuf { + fn deserialize_as(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + let path = PathBuf::deserialize(deserializer)?; + Ok(path.replace_env()) + } +} + +// #[cfg(feature = "schemars")] +// impl serde_with::schemars_0_8::JsonSchemaAs for ResolvedPathBuf { +// fn schema_name() -> String { +// "PathBuf".to_owned() +// } +// +// fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema { +// ::json_schema(gen) +// } +// } + +/// Custom deserializer for [`Option>`] that uses +/// [`PathExt::replace_env`] to resolve environment variables in the paths. +/// +/// This is used in `WorkspaceConfig` struct because we can't use +/// #[serde_with::serde_as] as it doesn't handle [`Option>`] +/// quite well and generated compiler errors that can't be fixed because of Rust's orphan rule. +pub fn resolve_option_hashmap_usize_path<'de, D>( + deserializer: D, +) -> Result>, D::Error> +where + D: serde::Deserializer<'de>, +{ + let map = Option::>::deserialize(deserializer)?; + Ok(map.map(|map| map.into_iter().map(|(k, v)| (k, v.replace_env())).collect())) +} + +#[cfg(test)] +mod tests { + use super::*; + + // helper functions + fn expected>(p: P) -> PathBuf { + // Ensure that the path is using the correct path separator for the OS. + p.as_ref().components().collect::() + } + + fn resolve>(p: P) -> PathBuf { + p.replace_env() + } + + #[test] + fn resolves_env_vars() { + // Set a variable for testing + unsafe { + std::env::set_var("VAR", "VALUE"); + } + + // %VAR% format + assert_eq!(resolve("/path/%VAR%/d"), expected("/path/VALUE/d")); + // $env:VAR format + assert_eq!(resolve("/path/$env:VAR/d"), expected("/path/VALUE/d")); + // $VAR format + assert_eq!(resolve("/path/$VAR/d"), expected("/path/VALUE/d")); + + // non-existent variable + assert_eq!(resolve("/path/%ASD%/to/d"), expected("/path/%ASD%/to/d")); + assert_eq!( + resolve("/path/$env:ASD/to/d"), + expected("/path/$env:ASD/to/d") + ); + assert_eq!(resolve("/path/$ASD/to/d"), expected("/path/$ASD/to/d")); + + // Set a $env:USERPROFILE variable for testing + unsafe { + std::env::set_var("USERPROFILE", "C:\\Users\\user"); + } + + // ~ and $HOME should be replaced with $Env:USERPROFILE + assert_eq!(resolve("~"), expected("C:\\Users\\user")); + assert_eq!(resolve("$HOME"), expected("C:\\Users\\user")); + } +} diff --git a/komorebi/src/core_graphics/mod.rs b/komorebi/src/core_graphics/mod.rs index e3d8a8d4..660cd589 100644 --- a/komorebi/src/core_graphics/mod.rs +++ b/komorebi/src/core_graphics/mod.rs @@ -1,10 +1,13 @@ use crate::core_graphics::error::CoreGraphicsError; use objc2_core_foundation::CFArray; use objc2_core_foundation::CFRetained; +use objc2_core_foundation::CGFloat; +use objc2_core_foundation::CGPoint; use objc2_core_foundation::CGRect; use objc2_core_graphics::CGDisplayBounds; use objc2_core_graphics::CGGetOnlineDisplayList; use objc2_core_graphics::CGRectIntersectsRect; +use objc2_core_graphics::CGWarpMouseCursorPosition; use objc2_core_graphics::CGWindowListCopyWindowInfo; use objc2_core_graphics::CGWindowListOption; use objc2_core_graphics::kCGNullWindowID; @@ -14,6 +17,18 @@ pub mod error; pub struct CoreGraphicsApi; impl CoreGraphicsApi { + pub fn warp_mouse_cursor_position(x: i32, y: i32) -> Result<(), CoreGraphicsError> { + match unsafe { + CoreGraphicsError::from(CGWarpMouseCursorPosition(CGPoint::new( + x as CGFloat, + y as CGFloat, + ))) + } { + CoreGraphicsError::Success => Ok(()), + error => Err(error), + } + } + pub fn contains_rect(smaller: CGRect, bigger: CGRect) -> bool { unsafe { CGRectIntersectsRect(smaller, bigger) } } diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs index aaf8e6ea..ac464246 100644 --- a/komorebi/src/lib.rs +++ b/komorebi/src/lib.rs @@ -2,10 +2,19 @@ use crate::accessibility::error::AccessibilityError; use crate::core_graphics::error::CoreGraphicsError; +use core::pathext::PathExt; +use lazy_static::lazy_static; +use objc2_application_services::AXObserver; +use objc2_application_services::AXUIElement; use objc2_core_foundation::CFArray; use objc2_core_foundation::CFDictionary; +use objc2_core_foundation::CFRetained; +use objc2_core_foundation::CFRunLoop; use objc2_core_foundation::CFString; +use std::ops::Deref; +use std::path::PathBuf; use std::ptr::NonNull; +use std::sync::atomic::AtomicI32; #[macro_use] pub mod ring; @@ -14,11 +23,72 @@ pub mod accessibility; pub mod application; pub mod core; pub mod core_graphics; +pub mod lockable_sequence; pub mod macos_api; +mod monitor; +pub mod process_command; pub mod window; pub mod window_manager; pub mod workspace; +lazy_static! { + pub static ref HOME_DIR: PathBuf = { + std::env::var("KOMOREBI_CONFIG_HOME").map_or_else(|_| dirs::home_dir().expect("there is no home directory"), |home_path| { + let home = home_path.replace_env(); + + assert!( + home.is_dir(), + "$Env:KOMOREBI_CONFIG_HOME is set to '{home_path}', which is not a valid directory" + ); + + + home + }) + }; + pub static ref DATA_DIR: PathBuf = dirs::data_local_dir() + .expect("there is no local data directory") + .join("komorebi"); +} + +pub static DEFAULT_WORKSPACE_PADDING: AtomicI32 = AtomicI32::new(5); +pub static DEFAULT_CONTAINER_PADDING: AtomicI32 = AtomicI32::new(5); + +#[derive(Debug)] +pub struct CoreFoundationRunLoop(pub CFRetained); +unsafe impl Sync for CoreFoundationRunLoop {} +unsafe impl Send for CoreFoundationRunLoop {} +impl Deref for CoreFoundationRunLoop { + type Target = CFRunLoop; + + fn deref(&self) -> &Self::Target { + self.0.as_ref() + } +} + +#[derive(Debug, Clone)] +pub struct AccessibilityUiElement(pub CFRetained); +unsafe impl Sync for AccessibilityUiElement {} +unsafe impl Send for AccessibilityUiElement {} +impl Deref for AccessibilityUiElement { + type Target = AXUIElement; + + fn deref(&self) -> &Self::Target { + self.0.as_ref() + } +} + +#[derive(Debug, Clone)] +pub struct AccessibilityObserver(pub CFRetained); +unsafe impl Sync for AccessibilityObserver {} +unsafe impl Send for AccessibilityObserver {} +impl Deref for AccessibilityObserver { + type Target = AXObserver; + + fn deref(&self) -> &Self::Target { + self.0.as_ref() + } +} + pub fn cf_array_as(array: &CFArray) -> impl Iterator> + use<'_, T> { let count = CFArray::count(array); (0..count).flat_map(move |idx| { diff --git a/komorebi/src/lockable_sequence.rs b/komorebi/src/lockable_sequence.rs new file mode 100644 index 00000000..e4aed3a3 --- /dev/null +++ b/komorebi/src/lockable_sequence.rs @@ -0,0 +1,363 @@ +use std::collections::VecDeque; + +/// A trait for types that can be marked as locked or unlocked. +pub trait Lockable { + /// Returns `true` if the item is locked. + fn locked(&self) -> bool; + /// Sets the locked state of the item. + fn set_locked(&mut self, locked: bool) -> &mut Self; +} + +/// A sequence supporting insertion, removal, and swapping of elements while preserving the absolute +/// positions of locked items. +pub trait LockableSequence { + /// Inserts a value at `idx`, keeping locked elements at their absolute positions. + fn insert_respecting_locks(&mut self, idx: usize, value: T) -> usize; + /// Removes the element at `idx`, keeping locked elements at their absolute positions. + fn remove_respecting_locks(&mut self, idx: usize) -> Option; + /// Swaps the elements at indices `i` and `j`, keeping locked elements at their absolute positions. + fn swap_respecting_locks(&mut self, i: usize, j: usize); +} + +impl LockableSequence for VecDeque { + /// Insert `value` at logical index `idx`, with trying to keep locked elements + /// (`is_locked()`) anchored at their original positions. + /// + /// Returns the final index of the inserted element. + fn insert_respecting_locks(&mut self, mut idx: usize, value: T) -> usize { + // 1. Bounds check: if index is out of range, simply append. + if idx >= self.len() { + self.push_back(value); + return self.len() - 1; // last index + } + + // 2. Normal VecDeque insertion + self.insert(idx, value); + + // 3. Walk left-to-right once, swapping any misplaced locked element. After + // the VecDeque::insert all items after `idx` have moved right by one. For every locked + // element that is now to the right of an unlocked one, swap it back left exactly once. + for index in (idx + 1)..self.len() { + if self[index].locked() && !self[index - 1].locked() { + self.swap(index - 1, index); + + // If the element we just inserted participated in the swap, + // update `idx` so we can return its final location. + if idx == index - 1 { + idx = index; + } + } + } + idx + } + + /// Remove element at `idx`, with trying to keep locked elements + /// (`is_locked()`) anchored at their original positions. + /// + /// Returns the removed element, or `None` if `idx` is out of bounds. + fn remove_respecting_locks(&mut self, idx: usize) -> Option { + // 1. Bounds check: if index is out of range, do nothing. + if idx >= self.len() { + return None; + } + + // 2. Remove the element at the requested index. + // All elements after idx are now shifted left by 1. + let removed = self.remove(idx)?; + + // 3. If less than 2 elements remain, nothing to shift. + if self.len() < 2 { + return Some(removed); + } + + // 4. Iterate from the element just after the removed spot up to the second-to-last + // element, right-to-left. This loop "fixes" locked elements that were shifted left + // off their anchored positions: If a locked element now has an unlocked element + // to its right, swap them back to restore locked order. + for index in (idx..self.len() - 1).rev() { + // If current is locked and the next one is not locked, swap them. + if self[index].locked() && !self[index + 1].locked() { + self.swap(index, index + 1); + } + } + + // 5. Return the removed value. + Some(removed) + } + + /// Swaps the elements at indices `i` and `j`, along with their `locked` status, ensuring + /// the lock state remains associated with the position rather than the element itself. + fn swap_respecting_locks(&mut self, i: usize, j: usize) { + self.swap(i, j); + let locked_i = self[i].locked(); + let locked_j = self[j].locked(); + self[i].set_locked(locked_j); + self[j].set_locked(locked_i); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[derive(Debug, PartialEq)] + struct TestItem { + val: i32, + locked: bool, + } + + impl Lockable for TestItem { + fn locked(&self) -> bool { + self.locked + } + + fn set_locked(&mut self, locked: bool) -> &mut Self { + self.locked = locked; + self + } + } + + fn vals(v: &VecDeque) -> Vec { + v.iter().map(|x| x.val).collect() + } + + fn test_deque(items: &[(i32, bool)]) -> VecDeque { + items + .iter() + .cloned() + .map(|(val, locked)| TestItem { val, locked }) + .collect() + } + + #[test] + fn test_insert_respecting_locks() { + // Test case 1: Basic insertion with locked index + { + // Lock index 2 + let mut ring = test_deque(&[(0, false), (1, false), (2, true), (3, false), (4, false)]); + // Insert at index 0, should shift elements while keeping index 2 locked + ring.insert_respecting_locks( + 0, + TestItem { + val: 99, + locked: false, + }, + ); + // Element '2' remains at index 2, element '1' that was at index 1 is now at index 3 + assert_eq!(vals(&ring), vec![99, 0, 2, 1, 3, 4]); + } + + // Test case 2: Insert at a locked index (should insert after locked) + { + // Lock index 2 + let mut ring = test_deque(&[(0, false), (1, false), (2, true), (3, false), (4, false)]); + // Try to insert at locked index 2, should insert at index 3 instead + let actual_index = ring.insert_respecting_locks( + 2, + TestItem { + val: 99, + locked: false, + }, + ); + assert_eq!(actual_index, 3); + assert_eq!(vals(&ring), vec![0, 1, 2, 99, 3, 4]); + } + + // Test case 3: Multiple locked indices + { + // Lock index 1 and 3 + let mut ring = test_deque(&[(0, false), (1, true), (2, false), (3, true), (4, false)]); + // Insert at index 0, should maintain locked indices + ring.insert_respecting_locks( + 0, + TestItem { + val: 99, + locked: false, + }, + ); + // Elements '1' and '3' remain at indices 1 and 3 + assert_eq!(vals(&ring), vec![99, 1, 0, 3, 2, 4]); + } + + // Test case 4: Insert at end + { + // Lock index 2 + let mut ring = test_deque(&[(0, false), (1, false), (2, true), (3, false), (4, false)]); + let actual_index = ring.insert_respecting_locks( + 5, + TestItem { + val: 99, + locked: false, + }, + ); + assert_eq!(actual_index, 5); + assert_eq!(vals(&ring), vec![0, 1, 2, 3, 4, 99]); + } + + // Test case 5: Empty ring + { + let mut ring = test_deque(&[]); + // Insert into empty deque + let actual_index = ring.insert_respecting_locks( + 0, + TestItem { + val: 99, + locked: false, + }, + ); + assert_eq!(actual_index, 0); + assert_eq!(vals(&ring), vec![99]); + } + + // Test case 6: All indices locked + { + // Lock all indices + let mut ring = test_deque(&[(0, true), (1, true), (2, true), (3, true), (4, true)]); + // Try to insert at index 2, should insert at the end + let actual_index = ring.insert_respecting_locks( + 2, + TestItem { + val: 99, + locked: false, + }, + ); + assert_eq!(actual_index, 5); + assert_eq!(vals(&ring), vec![0, 1, 2, 3, 4, 99]); + } + + // Test case 7: Consecutive locked indices + { + // Lock index 2 and 3 + let mut ring = test_deque(&[(0, false), (1, false), (2, true), (3, true), (4, false)]); + // Insert at index 1, should maintain consecutive locked indices + ring.insert_respecting_locks( + 1, + TestItem { + val: 99, + locked: false, + }, + ); + // Elements '2' and '3' remain at indices 2 and 3 + assert_eq!(vals(&ring), vec![0, 99, 2, 3, 1, 4]); + } + } + + #[test] + fn test_remove_respecting_locks() { + // Test case 1: Remove a non-locked index before a locked index + { + // Lock index 2 + let mut ring = test_deque(&[(0, false), (1, false), (2, true), (3, false), (4, false)]); + let removed = ring.remove_respecting_locks(0); + assert_eq!(removed.map(|x| x.val), Some(0)); + // Elements '2' remain at index 2 + assert_eq!(vals(&ring), vec![1, 3, 2, 4]); + } + + // Test case 2: Remove a locked index + { + // Lock index 2 + let mut ring = test_deque(&[(0, false), (1, false), (2, true), (3, false), (4, false)]); + let removed = ring.remove_respecting_locks(2); + assert_eq!(removed.map(|x| x.val), Some(2)); + // Elements should stay at the same places + assert_eq!(vals(&ring), vec![0, 1, 3, 4]); + } + + // Test case 3: Remove an index after a locked index + { + // Lock index 1 + let mut ring = test_deque(&[(0, false), (1, true), (2, false), (3, false), (4, false)]); + let removed = ring.remove_respecting_locks(3); + assert_eq!(removed.map(|x| x.val), Some(3)); + // Elements should stay at the same places + assert_eq!(vals(&ring), vec![0, 1, 2, 4]); + } + + // Test case 4: Multiple locked indices + { + // Lock index 1 and 3 + let mut ring = test_deque(&[(0, false), (1, true), (2, false), (3, true), (4, false)]); + let removed = ring.remove_respecting_locks(0); + assert_eq!(removed.map(|x| x.val), Some(0)); + // Elements '1' and '3' remain at indices '1' and '3' + assert_eq!(vals(&ring), vec![2, 1, 4, 3]); + } + + // Test case 5: Remove the last element + { + // Lock index 2 + let mut ring = test_deque(&[(0, false), (1, false), (2, true), (3, false), (4, false)]); + let removed = ring.remove_respecting_locks(4); + assert_eq!(removed.map(|x| x.val), Some(4)); + // Index 2 should still be at the same place + assert_eq!(vals(&ring), vec![0, 1, 2, 3]); + } + + // Test case 6: Invalid index + { + // Lock index 2 + let mut ring = test_deque(&[(0, false), (1, false), (2, true), (3, false), (4, false)]); + let removed = ring.remove_respecting_locks(10); + assert_eq!(removed, None); + // Deque unchanged + assert_eq!(vals(&ring), vec![0, 1, 2, 3, 4]); + } + + // Test case 7: Remove enough elements to make a locked index invalid + { + // Lock index 2 + let mut ring = test_deque(&[(0, false), (1, false), (2, true)]); + ring.remove_respecting_locks(0); + // Index 2 should now be '1' + assert_eq!(vals(&ring), vec![1, 2]); + } + + // Test case 8: Removing an element before multiple locked indices + { + // Lock index 2 and 4 + let mut ring = test_deque(&[ + (0, false), + (1, false), + (2, true), + (3, false), + (4, true), + (5, false), + ]); + let removed = ring.remove_respecting_locks(1); + assert_eq!(removed.map(|x| x.val), Some(1)); + // Both indices should still be at the same place + assert_eq!(vals(&ring), vec![0, 3, 2, 5, 4]); + } + } + + #[test] + fn test_swap_respecting_locks_various_cases() { + // Swap unlocked and locked + let mut ring = test_deque(&[(0, false), (1, true), (2, false), (3, false)]); + ring.swap_respecting_locks(0, 1); + assert_eq!(vals(&ring), vec![1, 0, 2, 3]); + assert!(!ring[0].locked); + assert!(ring[1].locked); + ring.swap_respecting_locks(0, 1); + assert_eq!(vals(&ring), vec![0, 1, 2, 3]); + assert!(!ring[0].locked); + assert!(ring[1].locked); + + // Both locked + let mut ring = test_deque(&[(0, true), (1, false), (2, true)]); + ring.swap_respecting_locks(0, 2); + assert_eq!(vals(&ring), vec![2, 1, 0]); + assert!(ring[0].locked); + assert!(!ring[1].locked); + assert!(ring[2].locked); + + // Both unlocked + let mut ring = test_deque(&[(0, false), (1, true), (2, false)]); + ring.swap_respecting_locks(0, 2); + assert_eq!(vals(&ring), vec![2, 1, 0]); + assert!(!ring[0].locked); + assert!(ring[1].locked); + assert!(!ring[2].locked); + } +} diff --git a/komorebi/src/macos_api.rs b/komorebi/src/macos_api.rs index 5020e12d..cb5df965 100644 --- a/komorebi/src/macos_api.rs +++ b/komorebi/src/macos_api.rs @@ -1,24 +1,48 @@ use crate::LibraryError; +use crate::accessibility::attribute_constants::kAXPositionAttribute; +use crate::accessibility::attribute_constants::kAXSizeAttribute; use crate::application::Application; use crate::cf_array_as; use crate::core::rect::Rect; use crate::core_graphics::CoreGraphicsApi; -use crate::ring::Ring; +use crate::monitor::Monitor; use crate::window::WindowInfo; use crate::window_manager::Container; -use crate::window_manager::Monitor; use crate::window_manager::WindowManager; +use objc2::MainThreadMarker; +use objc2_app_kit::NSScreen; +use objc2_application_services::AXUIElement; use objc2_core_foundation::CFDictionary; +use objc2_core_foundation::CFString; +use objc2_core_foundation::CGPoint; +use objc2_core_foundation::CGSize; use std::collections::HashMap; +use std::ptr::NonNull; pub struct MacosApi; impl MacosApi { pub fn load_monitor_information(wm: &mut WindowManager) -> Result<(), LibraryError> { + let screens = NSScreen::screens(MainThreadMarker::new().unwrap()); + for display_id in CoreGraphicsApi::connected_display_ids()? { - let size = Rect::from(CoreGraphicsApi::display_bounds(display_id)); - let monitor = Monitor::new(display_id, size); - wm.monitors.elements_mut().push_back(monitor); + let display_bounds = CoreGraphicsApi::display_bounds(display_id); + + for screen in &screens { + let menu_bar_height = screen.frame().size.height + - screen.visibleFrame().size.height + - screen.visibleFrame().origin.y; + + if screen.frame() == display_bounds { + let size = Rect::from(display_bounds); + let mut work_area_size = Rect::from(display_bounds); + work_area_size.top += menu_bar_height as i32; + work_area_size.bottom = screen.visibleFrame().size.height as i32; + + let monitor = Monitor::new(display_id, size, work_area_size); + wm.monitors.elements_mut().push_back(monitor); + } + } } Ok(()) @@ -78,9 +102,7 @@ impl MacosApi { for (monitor_idx, windows) in monitor_window_map { for window in windows { - let mut container = Container { - windows: Ring::default(), - }; + let mut container = Container::default(); container.windows_mut().push_back(window); if let Some(Some(workspace)) = monitor_workspace_map.get_mut(monitor_idx) { @@ -91,4 +113,38 @@ impl MacosApi { Ok(()) } + + pub fn center_cursor_in_rect(rect: &Rect) -> Result<(), LibraryError> { + Ok(CoreGraphicsApi::warp_mouse_cursor_position( + rect.left + (rect.right / 2), + rect.top + (rect.bottom / 2), + )?) + } + + pub fn window_rect(element: &AXUIElement) -> Rect { + let mut position_receiver = std::ptr::null(); + let mut size_receiver = std::ptr::null(); + + unsafe { + element.copy_attribute_value( + &CFString::from_static_str(kAXPositionAttribute), + NonNull::from(&mut position_receiver), + ); + + element.copy_attribute_value( + &CFString::from_static_str(kAXSizeAttribute), + NonNull::from(&mut size_receiver), + ); + + let position = *position_receiver.cast::(); + let size = *position_receiver.cast::(); + + Rect { + left: position.x as i32, + top: position.y as i32, + right: size.width as i32, + bottom: size.height as i32, + } + } + } } diff --git a/komorebi/src/main.rs b/komorebi/src/main.rs index 8c434763..da29eb61 100644 --- a/komorebi/src/main.rs +++ b/komorebi/src/main.rs @@ -2,6 +2,8 @@ use color_eyre::eyre; use color_eyre::eyre::eyre; +use komorebi::DATA_DIR; +use komorebi::process_command::listen_for_commands; use komorebi::window_manager::WindowManager; use objc2::rc::autoreleasepool; use objc2_application_services::AXIsProcessTrusted; @@ -11,6 +13,7 @@ use objc2_core_graphics::CGDisplayBounds; use objc2_core_graphics::CGMainDisplayID; use objc2_core_graphics::CGPreflightScreenCaptureAccess; use objc2_core_graphics::CGRequestScreenCaptureAccess; +use parking_lot::Mutex; use std::sync::Arc; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; @@ -90,19 +93,19 @@ fn main() -> eyre::Result<()> { setup()?; check_permissions()?; + if !DATA_DIR.is_dir() { + std::fs::create_dir_all(&*DATA_DIR)?; + } + let display_size = unsafe { CGDisplayBounds(CGMainDisplayID()) }; tracing::info!("display size for main display is: {:?}", display_size); let run_loop = CFRunLoop::current().ok_or(eyre!("couldn't get CFRunLoop::current"))?; - let mut wm = WindowManager::new(&run_loop); - wm.init()?; + let wm = Arc::new(Mutex::new(WindowManager::new(&run_loop, None)?)); + wm.lock().init()?; + wm.lock().update_focused_workspace(true, true)?; - wm.monitors - .focused_mut() - .unwrap() - .focused_workspace_mut() - .unwrap() - .update()?; + listen_for_commands(wm.clone()); let quit_ctrlc = Arc::new(AtomicBool::new(false)); let quit_thread = quit_ctrlc.clone(); diff --git a/komorebi/src/monitor.rs b/komorebi/src/monitor.rs new file mode 100644 index 00000000..17288f5d --- /dev/null +++ b/komorebi/src/monitor.rs @@ -0,0 +1,88 @@ +use crate::DEFAULT_CONTAINER_PADDING; +use crate::DEFAULT_WORKSPACE_PADDING; +use crate::core::rect::Rect; +use crate::ring::Ring; +use crate::workspace::Workspace; +use crate::workspace::WorkspaceGlobals; +use color_eyre::eyre; +use color_eyre::eyre::eyre; +use std::sync::atomic::Ordering; + +impl_ring_elements!(Monitor, Workspace); + +#[derive(Debug)] +pub struct Monitor { + pub id: u32, + pub workspaces: Ring, + pub size: Rect, + pub work_area_offset: Option, + pub work_area_size: Rect, + pub window_based_work_area_offset: Option, + pub window_based_work_area_offset_limit: isize, + pub container_padding: Option, + pub workspace_padding: Option, +} + +impl Monitor { + #[allow(clippy::field_reassign_with_default)] + pub fn new(id: u32, size: Rect, work_area_size: Rect) -> Self { + let mut workspaces = Ring::default(); + workspaces.elements_mut().push_back(Workspace::default()); + + Self { + id, + workspaces, + size, + work_area_offset: None, + work_area_size, + window_based_work_area_offset: None, + window_based_work_area_offset_limit: 0, + container_padding: None, + workspace_padding: None, + } + } + + pub fn update_focused_workspace(&mut self, offset: Option) -> eyre::Result<()> { + let offset = if self.work_area_offset.is_some() { + self.work_area_offset + } else { + offset + }; + + let focused_workspace_idx = self.focused_workspace_idx(); + self.update_workspace_globals(focused_workspace_idx, offset); + self.focused_workspace_mut() + .ok_or_else(|| eyre!("there is no workspace"))? + .update()?; + + Ok(()) + } + + /// Updates the `globals` field of workspace with index `workspace_idx` + pub fn update_workspace_globals(&mut self, workspace_idx: usize, offset: Option) { + let container_padding = self + .container_padding + .or(Some(DEFAULT_CONTAINER_PADDING.load(Ordering::Relaxed))); + let workspace_padding = self + .workspace_padding + .or(Some(DEFAULT_WORKSPACE_PADDING.load(Ordering::Relaxed))); + let (border_width, border_offset) = (0, 0); + let work_area = self.work_area_size; + let work_area_offset = self.work_area_offset.or(offset); + let window_based_work_area_offset = self.window_based_work_area_offset; + let window_based_work_area_offset_limit = self.window_based_work_area_offset_limit; + + if let Some(workspace) = self.workspaces_mut().get_mut(workspace_idx) { + workspace.globals = WorkspaceGlobals { + container_padding, + workspace_padding, + border_width, + border_offset, + work_area, + work_area_offset, + window_based_work_area_offset, + window_based_work_area_offset_limit, + } + } + } +} diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs new file mode 100644 index 00000000..e5b64d43 --- /dev/null +++ b/komorebi/src/process_command.rs @@ -0,0 +1,122 @@ +use crate::core::SocketMessage; +use crate::window_manager::WindowManager; +use color_eyre::eyre; +use parking_lot::Mutex; +use std::io::BufRead; +use std::io::BufReader; +use std::os::unix::net::UnixStream; +use std::str::FromStr; +use std::sync::Arc; +use std::time::Duration; + +#[tracing::instrument] +pub fn listen_for_commands(wm: Arc>) { + std::thread::spawn(move || { + loop { + let wm = wm.clone(); + + let _ = std::thread::spawn(move || { + let listener = wm + .lock() + .command_listener + .try_clone() + .expect("could not clone unix listener"); + + tracing::info!("listening on komorebi.sock"); + for client in listener.incoming() { + match client { + Ok(stream) => { + let wm_clone = wm.clone(); + std::thread::spawn(move || { + match read_commands_uds(&wm_clone, stream) { + Ok(()) => {} + Err(error) => { + tracing::error!("failed to read command from uds {}", error) + } + } + }); + } + Err(error) => { + tracing::error!("failed to get unix stream {}", error); + break; + } + } + } + }) + .join(); + + tracing::error!("restarting failed thread"); + } + }); +} + +impl WindowManager { + #[tracing::instrument(skip(self, _reply))] + pub fn process_command( + &mut self, + message: SocketMessage, + mut _reply: impl std::io::Write, + ) -> eyre::Result<()> { + match message { + SocketMessage::FocusWindow(direction) => { + self.focus_container_in_direction(direction)?; + } + SocketMessage::MoveWindow(direction) => { + self.move_container_in_direction(direction)?; + } + SocketMessage::ChangeLayout(layout) => self.change_workspace_layout_default(layout)?, + SocketMessage::TogglePause => { + if self.is_paused { + tracing::info!("resuming"); + } else { + tracing::info!("pausing"); + } + + self.is_paused = !self.is_paused; + } + } + + Ok(()) + } +} + +pub fn read_commands_uds( + wm: &Arc>, + mut stream: UnixStream, +) -> eyre::Result<()> { + let reader = BufReader::new(stream.try_clone()?); + // TODO(raggi): while this processes more than one command, if there are + // replies there is no clearly defined protocol for framing yet - it's + // perhaps whole-json objects for now, but termination is signalled by + // socket shutdown. + for line in reader.lines() { + let message = SocketMessage::from_str(&line?)?; + + match wm.try_lock_for(Duration::from_secs(1)) { + None => { + tracing::warn!( + "could not acquire window manager lock, not processing message: {message}" + ); + } + Some(mut wm) => { + if wm.is_paused { + return match message { + SocketMessage::TogglePause + // | SocketMessage::State + // | SocketMessage::GlobalState + // | SocketMessage::Stop + => Ok(wm.process_command(message, &mut stream)?), + _ => { + tracing::trace!("ignoring while paused"); + Ok(()) + } + }; + } + + wm.process_command(message.clone(), &mut stream)?; + } + } + } + + Ok(()) +} diff --git a/komorebi/src/window.rs b/komorebi/src/window.rs index d28fbb43..38dc9c07 100644 --- a/komorebi/src/window.rs +++ b/komorebi/src/window.rs @@ -1,3 +1,6 @@ +use crate::AccessibilityObserver; +use crate::AccessibilityUiElement; +use crate::LibraryError; use crate::accessibility::AccessibilityApi; use crate::accessibility::attribute_constants::kAXMainAttribute; use crate::accessibility::attribute_constants::kAXPositionAttribute; @@ -122,9 +125,9 @@ impl WindowInfo { #[derive(Debug)] #[allow(unused)] pub struct Window { - element: CFRetained, + element: AccessibilityUiElement, application: Application, - observer: CFRetained, + observer: AccessibilityObserver, } impl Drop for Window { @@ -150,14 +153,14 @@ impl Window { )?; Ok(Self { - element, + element: AccessibilityUiElement(element), application, - observer, + observer: AccessibilityObserver(observer), }) } #[tracing::instrument(skip_all)] - pub fn observe(&self, run_loop: &CFRetained) -> Result<(), AccessibilityError> { + pub fn observe(&self, run_loop: &CFRunLoop) -> Result<(), AccessibilityError> { tracing::info!( "registering observer for process: {}, title: {}", self.application.process_id, @@ -183,7 +186,7 @@ impl Window { self.set_size(CGSize::new(rect.right as CGFloat, rect.bottom as CGFloat)) } - pub fn focus(&self) -> Result<(), AccessibilityError> { + pub fn focus(&self, focus_follows_mouse: bool) -> Result<(), LibraryError> { unsafe { NSRunningApplication::runningApplicationWithProcessIdentifier( self.application.process_id, @@ -195,8 +198,14 @@ impl Window { let cf_boolean = CFBoolean::new(true); let value = &**cf_boolean; - AccessibilityApi::set_attribute_cf_value(&self.element, kAXMainAttribute, value) + AccessibilityApi::set_attribute_cf_value(&self.element, kAXMainAttribute, value)?; } + + if focus_follows_mouse { + // MacosApi::center_cursor_in_rect(&MacosApi::window_rect(&self.element))? + } + + Ok(()) } pub fn set_point(&self, point: CGPoint) -> Result<(), AccessibilityError> { diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index 558594a5..4fc5b3aa 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -1,28 +1,67 @@ +use crate::CoreFoundationRunLoop; +use crate::DATA_DIR; use crate::LibraryError; use crate::application::Application; +use crate::core::default_layout::DefaultLayout; +use crate::core::layout::Layout; +use crate::core::operation_direction::OperationDirection; use crate::core::rect::Rect; +use crate::lockable_sequence::Lockable; use crate::macos_api::MacosApi; +use crate::monitor::Monitor; use crate::ring::Ring; use crate::window::Window; use crate::workspace::Workspace; +use color_eyre::eyre; +use color_eyre::eyre::eyre; use objc2_core_foundation::CFRetained; use objc2_core_foundation::CFRunLoop; use std::collections::HashMap; +use std::io::ErrorKind; +use std::os::unix::net::UnixListener; +use std::path::PathBuf; #[derive(Debug)] pub struct WindowManager { pub monitors: Ring, pub applications: HashMap, - pub run_loop: CFRetained, + pub run_loop: CoreFoundationRunLoop, + pub command_listener: UnixListener, + pub is_paused: bool, + pub mouse_follows_focus: bool, + pub work_area_offset: Option, } +impl_ring_elements!(WindowManager, Monitor); + impl WindowManager { - pub fn new(run_loop: &CFRetained) -> Self { - Self { + pub fn new( + run_loop: &CFRetained, + custom_socket_path: Option, + ) -> eyre::Result { + let socket = custom_socket_path.unwrap_or_else(|| DATA_DIR.join("komorebi.sock")); + + match std::fs::remove_file(&socket) { + Ok(()) => {} + Err(error) => match error.kind() { + ErrorKind::NotFound => {} + _ => { + return Err(error.into()); + } + }, + }; + + let listener = UnixListener::bind(&socket)?; + + Ok(Self { monitors: Ring::default(), applications: Default::default(), - run_loop: run_loop.clone(), - } + run_loop: CoreFoundationRunLoop(run_loop.clone()), + command_listener: listener, + is_paused: false, + mouse_follows_focus: true, + work_area_offset: None, + }) } #[tracing::instrument(skip(self))] @@ -33,41 +72,191 @@ impl WindowManager { } } -impl_ring_elements!(Monitor, Workspace); -#[derive(Debug)] -pub struct Monitor { - pub id: u32, - pub workspaces: Ring, - pub size: Rect, -} +impl WindowManager { + #[tracing::instrument(skip(self))] + pub fn focus_container_in_direction( + &mut self, + direction: OperationDirection, + ) -> eyre::Result<()> { + let workspace = self.focused_workspace()?; -impl Monitor { - #[allow(clippy::field_reassign_with_default)] - pub fn new(id: u32, size: Rect) -> Self { - let mut workspaces = Ring::default(); - let mut workspace = Workspace::default(); - workspace.work_area = size; - workspace.container_padding = Some(20); - workspace.workspace_padding = Some(20); - workspace.work_area_offset = Some(Rect { - left: 0, - top: 0, - right: 0, - bottom: 40, - }); + tracing::info!("focusing container"); - workspaces.elements_mut().push_back(workspace); - - Self { - id, - workspaces, - size, + match workspace.new_idx_for_direction(direction) { + None => {} + Some(idx) => { + let workspace = self.focused_workspace_mut()?; + workspace.focus_container(idx); + } } + + if let Ok(focused_window) = self.focused_window() { + focused_window.focus(self.mouse_follows_focus)?; + } + + Ok(()) + } + + #[tracing::instrument(skip(self))] + pub fn move_container_in_direction( + &mut self, + direction: OperationDirection, + ) -> eyre::Result<()> { + let workspace = self.focused_workspace()?; + + tracing::info!("moving container"); + + let origin_container_idx = workspace.focused_container_idx(); + let target_container_idx = workspace.new_idx_for_direction(direction); + + match target_container_idx { + None => {} + Some(new_idx) => { + let workspace = self.focused_workspace_mut()?; + workspace.swap_containers(origin_container_idx, new_idx); + workspace.focus_container(new_idx); + } + } + + self.update_focused_workspace(self.mouse_follows_focus, true)?; + + Ok(()) + } + + #[tracing::instrument(skip(self))] + pub fn update_focused_workspace( + &mut self, + follow_focus: bool, + trigger_focus: bool, + ) -> eyre::Result<()> { + tracing::info!("updating"); + + let offset = self.work_area_offset; + let mouse_follows_focus = self.mouse_follows_focus; + + self.focused_monitor_mut() + .ok_or_else(|| eyre!("there is no monitor"))? + .update_focused_workspace(offset)?; + + if follow_focus + && let Ok(window) = self.focused_window_mut() + && trigger_focus + { + window.focus(mouse_follows_focus)?; + } + + Ok(()) + } + + #[tracing::instrument(skip(self))] + pub fn change_workspace_layout_default(&mut self, layout: DefaultLayout) -> eyre::Result<()> { + tracing::info!("changing layout"); + + let monitor_count = self.monitors().len(); + let workspace = self.focused_workspace_mut()?; + + if monitor_count > 1 && matches!(layout, DefaultLayout::Scrolling) { + tracing::warn!( + "scrolling layout is only supported for a single monitor; not changing layout" + ); + return Ok(()); + } + + workspace.layout = Layout::Default(layout); + self.update_focused_workspace(self.mouse_follows_focus, false) + } + + pub fn focused_workspace_idx(&self) -> eyre::Result { + Ok(self + .focused_monitor() + .ok_or_else(|| eyre!("there is no monitor"))? + .focused_workspace_idx()) + } + + pub fn focused_workspace(&self) -> eyre::Result<&Workspace> { + self.focused_monitor() + .ok_or_else(|| eyre!("there is no monitor"))? + .focused_workspace() + .ok_or_else(|| eyre!("there is no workspace")) + } + + pub fn focused_workspace_mut(&mut self) -> eyre::Result<&mut Workspace> { + self.focused_monitor_mut() + .ok_or_else(|| eyre!("there is no monitor"))? + .focused_workspace_mut() + .ok_or_else(|| eyre!("there is no workspace")) + } + + pub fn focused_workspace_idx_for_monitor_idx(&self, idx: usize) -> eyre::Result { + Ok(self + .monitors() + .get(idx) + .ok_or_else(|| eyre!("there is no monitor at this index"))? + .focused_workspace_idx()) + } + + pub fn focused_workspace_for_monitor_idx(&self, idx: usize) -> eyre::Result<&Workspace> { + self.monitors() + .get(idx) + .ok_or_else(|| eyre!("there is no monitor at this index"))? + .focused_workspace() + .ok_or_else(|| eyre!("there is no workspace")) + } + + pub fn focused_workspace_for_monitor_idx_mut( + &mut self, + idx: usize, + ) -> eyre::Result<&mut Workspace> { + self.monitors_mut() + .get_mut(idx) + .ok_or_else(|| eyre!("there is no monitor at this index"))? + .focused_workspace_mut() + .ok_or_else(|| eyre!("there is no workspace")) + } + + pub fn focused_container(&self) -> eyre::Result<&Container> { + self.focused_workspace()? + .focused_container() + .ok_or_else(|| eyre!("there is no container")) + } + + pub fn focused_container_idx(&self) -> eyre::Result { + Ok(self.focused_workspace()?.focused_container_idx()) + } + + pub fn focused_container_mut(&mut self) -> eyre::Result<&mut Container> { + self.focused_workspace_mut()? + .focused_container_mut() + .ok_or_else(|| eyre!("there is no container")) + } + + pub fn focused_window(&self) -> eyre::Result<&Window> { + self.focused_container()? + .focused_window() + .ok_or_else(|| eyre!("there is no window")) + } + + fn focused_window_mut(&mut self) -> eyre::Result<&mut Window> { + self.focused_container_mut()? + .focused_window_mut() + .ok_or_else(|| eyre!("there is no window")) } } impl_ring_elements!(Container, Window); -#[derive(Debug)] +#[derive(Debug, Default)] pub struct Container { pub windows: Ring, + pub locked: bool, +} + +impl Lockable for Container { + fn locked(&self) -> bool { + self.locked + } + + fn set_locked(&mut self, locked: bool) -> &mut Self { + self.locked = locked; + self + } } diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index 51d6a663..012f8e7f 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -2,7 +2,9 @@ use crate::core::arrangement::Axis; use crate::core::default_layout::DefaultLayout; use crate::core::default_layout::LayoutOptions; use crate::core::layout::Layout; +use crate::core::operation_direction::OperationDirection; use crate::core::rect::Rect; +use crate::lockable_sequence::LockableSequence; use crate::ring::Ring; use crate::window_manager::Container; use color_eyre::eyre; @@ -18,7 +20,6 @@ pub struct Workspace { pub container_padding: Option, pub resize_dimensions: Vec>, pub layout: Layout, - pub work_area: Rect, pub work_area_offset: Option, pub latest_layout: Vec, pub layout_flip: Option, @@ -35,7 +36,6 @@ impl Default for Workspace { container_padding: None, resize_dimensions: vec![], layout: Layout::Default(DefaultLayout::UltrawideVerticalStack), - work_area: Default::default(), work_area_offset: None, latest_layout: vec![], layout_flip: None, @@ -81,7 +81,7 @@ impl Workspace { // self.globals.window_based_work_area_offset_limit; let mut adjusted_work_area = work_area_offset.map_or_else( - || self.work_area, + || work_area, |offset| { let mut with_offset = work_area; with_offset.left += offset.left; @@ -130,4 +130,27 @@ impl Workspace { Ok(()) } + + #[tracing::instrument(skip(self))] + pub fn focus_container(&mut self, idx: usize) { + tracing::info!("focusing container"); + + self.containers.focus(idx); + } + + pub fn swap_containers(&mut self, i: usize, j: usize) { + self.containers.elements_mut().swap_respecting_locks(i, j); + self.focus_container(j); + } + + pub fn new_idx_for_direction(&self, direction: OperationDirection) -> Option { + let len = NonZeroUsize::new(self.containers().len())?; + + direction.destination( + self.layout.as_boxed_direction().as_ref(), + self.layout_flip, + self.focused_container_idx(), + len, + ) + } } diff --git a/komorebic/Cargo.toml b/komorebic/Cargo.toml new file mode 100644 index 00000000..73bb2a8c --- /dev/null +++ b/komorebic/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "komorebic" +version = "0.1.0" +edition = "2024" + +[dependencies] +komorebi-client = { path = "../komorebi-client", default-features = false } + +clap = { workspace = true } +color-eyre = { workspace = true } +dirs = { workspace = true } +lazy_static = { workspace = true } +pastey = { workspace = true } \ No newline at end of file diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs new file mode 100644 index 00000000..0c8c939b --- /dev/null +++ b/komorebic/src/main.rs @@ -0,0 +1,100 @@ +#![warn(clippy::all)] + +use clap::Parser; +use color_eyre::eyre; +use komorebi_client::DefaultLayout; +use komorebi_client::OperationDirection; +use komorebi_client::PathExt; +use komorebi_client::SocketMessage; +use komorebi_client::send_message; +use lazy_static::lazy_static; +use std::path::PathBuf; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; + +lazy_static! { + static ref HAS_CUSTOM_CONFIG_HOME: AtomicBool = AtomicBool::new(false); + static ref HOME_DIR: PathBuf = { + std::env::var("KOMOREBI_CONFIG_HOME").map_or_else( + |_| dirs::home_dir().expect("there is no home directory"), + |home_path| { + let home = home_path.replace_env(); + if home.as_path().is_dir() { + HAS_CUSTOM_CONFIG_HOME.store(true, Ordering::SeqCst); + home + } else { + panic!( + "$Env:KOMOREBI_CONFIG_HOME is set to '{home_path}', which is not a valid directory", + ); + } + }, + ) + }; + static ref DATA_DIR: PathBuf = dirs::data_local_dir() + .expect("there is no local data directory") + .join("komorebi"); +} + +macro_rules! gen_enum_subcommand_args { + // SubCommand Pattern: Enum Type + ( $( $name:ident: $element:ty ),+ $(,)? ) => { + $( + pastey::paste! { + #[derive(clap::Parser)] + pub struct $name { + #[clap(value_enum)] + [<$element:snake>]: $element + } + } + )+ + }; +} + +gen_enum_subcommand_args! { + Focus: OperationDirection, + Move: OperationDirection, + ChangeLayout: DefaultLayout, +} + +#[derive(Parser)] +#[clap(author, about, version)] +struct Opts { + #[clap(subcommand)] + subcmd: SubCommand, +} + +#[derive(Parser)] +enum SubCommand { + /// Change focus to the window in the specified direction + #[clap(arg_required_else_help = true)] + Focus(Focus), + /// Move the focused window in the specified direction + #[clap(arg_required_else_help = true)] + Move(Move), + /// Toggle the paused state for all window tiling + TogglePause, + /// Set the layout on the focused workspace + #[clap(arg_required_else_help = true)] + ChangeLayout(ChangeLayout), +} + +fn main() -> eyre::Result<()> { + let opts: Opts = Opts::parse(); + + match opts.subcmd { + SubCommand::Focus(arg) => { + send_message(&SocketMessage::FocusWindow(arg.operation_direction))?; + } + SubCommand::Move(arg) => { + send_message(&SocketMessage::MoveWindow(arg.operation_direction))?; + } + SubCommand::TogglePause => { + send_message(&SocketMessage::TogglePause)?; + } + SubCommand::ChangeLayout(arg) => { + send_message(&SocketMessage::ChangeLayout(arg.default_layout))?; + } + } + + Ok(()) +} diff --git a/shell.nix b/shell.nix index 1bb344ac..1389867d 100644 --- a/shell.nix +++ b/shell.nix @@ -10,5 +10,6 @@ with pkgs; cargo-deny jq prettier + cargo-udeps ]; - } \ No newline at end of file + }