diff --git a/Cargo.lock b/Cargo.lock index f322b8d2..0b262c34 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -159,6 +159,30 @@ dependencies = [ "memchr", ] +[[package]] +name = "aligned-vec" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc890384c8602f339876ded803c97ad529f3842aba97f6392b3dba0dd171769b" +dependencies = [ + "equator", +] + +[[package]] +name = "alloc-no-stdlib" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" + +[[package]] +name = "alloc-stdlib" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94fb8275041c72129eb51b7d0322c29b8387a0386127718b096429201a5d6ece" +dependencies = [ + "alloc-no-stdlib", +] + [[package]] name = "android-activity" version = "0.6.0" @@ -260,6 +284,12 @@ dependencies = [ "num-traits", ] +[[package]] +name = "arbitrary" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" + [[package]] name = "arboard" version = "3.6.1" @@ -280,6 +310,17 @@ dependencies = [ "x11rb", ] +[[package]] +name = "arg_enum_proc_macro" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ae92a5119aa49cdbcf6b9f893fe4e1d98b04ccbf82ee0584ad948a44a734dea" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.106", +] + [[package]] name = "arrayref" version = "0.3.9" @@ -512,6 +553,29 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" +[[package]] +name = "av1-grain" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f3efb2ca85bc610acfa917b5aaa36f3fcbebed5b3182d7f877b02531c4b80c8" +dependencies = [ + "anyhow", + "arrayvec", + "log", + "nom", + "num-rational 0.4.2", + "v_frame", +] + +[[package]] +name = "avif-serialize" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47c8fbc0f831f4519fe8b810b6a7a91410ec83031b8233f730a0480029f6a23f" +dependencies = [ + "arrayvec", +] + [[package]] name = "backtrace" version = "0.3.76" @@ -577,6 +641,12 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" +[[package]] +name = "bit_field" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e4b40c7323adcfc0a41c4b88143ed58346ff65a288fc144329c5c45e05d70c6" + [[package]] name = "bitflags" version = "1.3.2" @@ -592,6 +662,12 @@ dependencies = [ "serde", ] +[[package]] +name = "bitstream-io" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6099cdc01846bc367c4e7dd630dc5966dccf36b652fae7a74e17b640411a91b2" + [[package]] name = "block" version = "0.1.6" @@ -657,6 +733,33 @@ dependencies = [ "piper", ] +[[package]] +name = "brotli" +version = "8.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bd8b9603c7aa97359dbd97ecf258968c95f3adddd6db2f7e7a5bef101c84560" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", + "brotli-decompressor", +] + +[[package]] +name = "brotli-decompressor" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "874bb8112abecc98cbd6d81ea4fa7e94fb9449648c93cc89aa40c81c24d7de03" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", +] + +[[package]] +name = "built" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56ed6191a7e78c36abdb16ab65341eefd73d64d303fffccdbb00d51e4205967b" + [[package]] name = "bumpalo" version = "3.19.0" @@ -772,6 +875,16 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" +[[package]] +name = "cfg-expr" +version = "0.15.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d067ad48b8650848b989a59a86c6c36a995d02d2bf778d45c3c5d57bc2718f02" +dependencies = [ + "smallvec", + "target-lexicon", +] + [[package]] name = "cfg-if" version = "1.0.3" @@ -807,6 +920,16 @@ dependencies = [ "windows-link 0.2.0", ] +[[package]] +name = "chrono-tz" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6139a8597ed92cf816dfb33f5dd6cf0bb93a6adc938f11039f371bc5bcd26c3" +dependencies = [ + "chrono", + "phf 0.12.1", +] + [[package]] name = "clap" version = "4.5.48" @@ -857,6 +980,15 @@ dependencies = [ "error-code", ] +[[package]] +name = "cmake" +version = "0.1.54" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7caa3f9de89ddbe2c607f4101924c5abec803763ae9534e4f4d7d8f84aa81f0" +dependencies = [ + "cc", +] + [[package]] name = "codespan-reporting" version = "0.11.1" @@ -980,6 +1112,19 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "core-graphics" +version = "0.22.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2581bbab3b8ffc6fcbd550bf46c355135d16e9ff2a6ea032ad6b9bf1d7efe4fb" +dependencies = [ + "bitflags 1.3.2", + "core-foundation 0.9.4", + "core-graphics-types", + "foreign-types 0.3.2", + "libc", +] + [[package]] name = "core-graphics" version = "0.23.2" @@ -1004,6 +1149,18 @@ dependencies = [ "libc", ] +[[package]] +name = "core-text" +version = "19.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99d74ada66e07c1cefa18f8abfba765b486f250de2e4a999e5727fc0dd4b4a25" +dependencies = [ + "core-foundation 0.9.4", + "core-graphics 0.22.3", + "foreign-types 0.3.2", + "libc", +] + [[package]] name = "cpufeatures" version = "0.2.17" @@ -1242,6 +1399,17 @@ dependencies = [ "libloading", ] +[[package]] +name = "dlopen2" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09b4f5f101177ff01b8ec4ecc81eead416a8aa42819a2869311b3420fa114ffa" +dependencies = [ + "libc", + "once_cell", + "winapi", +] + [[package]] name = "document-features" version = "0.2.11" @@ -1263,6 +1431,12 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + [[package]] name = "dyn-clone" version = "1.0.20" @@ -1331,6 +1505,15 @@ dependencies = [ "profiling", ] +[[package]] +name = "egui-phosphor" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "171d57331491e92f0a7c73fad1088716e3200984309f4f8684731b750cee1378" +dependencies = [ + "egui", +] + [[package]] name = "egui-wgpu" version = "0.31.1" @@ -1440,6 +1623,12 @@ dependencies = [ "syn 2.0.106", ] +[[package]] +name = "env_home" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7f84e12ccf0a7ddc17a6c41c93326024c42920d7ee630d04950e6926645c0fe" + [[package]] name = "epaint" version = "0.31.1" @@ -1464,6 +1653,26 @@ version = "0.31.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc7e7a64c02cf7a5b51e745a9e45f60660a286f151c238b9d397b3e923f5082f" +[[package]] +name = "equator" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4711b213838dfee0117e3be6ac926007d7f433d7bbe33595975d4190cb07e6fc" +dependencies = [ + "equator-macro", +] + +[[package]] +name = "equator-macro" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44f23cf4b44bfce11a86ace86f8a73ffdec849c9fd00a386a53d278bd9e81fb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.106", +] + [[package]] name = "equivalent" version = "1.0.2" @@ -1507,6 +1716,31 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "expat-sys" +version = "2.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "658f19728920138342f68408b7cf7644d90d4784353d8ebc32e7e8663dbe45fa" +dependencies = [ + "cmake", + "pkg-config", +] + +[[package]] +name = "exr" +version = "1.73.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83197f59927b46c04a183a619b7c29df34e63e63c7869320862268c0ef687e0" +dependencies = [ + "bit_field", + "half", + "lebe", + "miniz_oxide 0.8.9", + "rayon-core", + "smallvec", + "zune-inflate", +] + [[package]] name = "eyre" version = "0.6.12" @@ -1614,7 +1848,7 @@ dependencies = [ "serde_yaml", "shell-words", "shellexpand", - "toml", + "toml 0.5.11", ] [[package]] @@ -1629,6 +1863,19 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" +[[package]] +name = "font-loader" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c49d6b4c11dca1a1dd931a34a9f397e2da91abe3de4110505f3530a80e560b52" +dependencies = [ + "core-foundation 0.9.4", + "core-text", + "libc", + "servo-fontconfig", + "winapi", +] + [[package]] name = "foreign-types" version = "0.3.2" @@ -1680,6 +1927,17 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "freetype-sys" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a37d4011c0cc628dfa766fcc195454f4b068d7afdc2adfd28861191d866e731a" +dependencies = [ + "cmake", + "libc", + "pkg-config", +] + [[package]] name = "fs-tail" version = "0.1.4" @@ -1837,6 +2095,16 @@ dependencies = [ "weezl", ] +[[package]] +name = "gif" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae047235e33e2829703574b54fdec96bfbad892062d97fed2f76022287de61b" +dependencies = [ + "color_quant", + "weezl", +] + [[package]] name = "gimli" version = "0.32.3" @@ -2355,10 +2623,10 @@ dependencies = [ "bytemuck", "byteorder", "color_quant", - "gif", + "gif 0.11.4", "jpeg-decoder", "num-iter", - "num-rational", + "num-rational 0.3.2", "num-traits", "png 0.16.8", "scoped_threadpool", @@ -2373,12 +2641,38 @@ checksum = "529feb3e6769d234375c4cf1ee2ce713682b8e76538cb13f9fc23e1400a591e7" dependencies = [ "bytemuck", "byteorder-lite", + "color_quant", + "exr", + "gif 0.13.3", + "image-webp", "moxcms", "num-traits", "png 0.18.0", + "qoi", + "ravif", + "rayon", + "rgb", "tiff 0.10.3", + "zune-core", + "zune-jpeg", ] +[[package]] +name = "image-webp" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" +dependencies = [ + "byteorder-lite", + "quick-error", +] + +[[package]] +name = "imgref" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c5cedc30da3a610cac6b4ba17597bdf7152cf974e8aab3afb3d54455e371c8" + [[package]] name = "immutable-chunkmap" version = "2.1.2" @@ -2437,6 +2731,17 @@ dependencies = [ "libc", ] +[[package]] +name = "interpolate_name" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c34819042dc3d3971c46c2190835914dfbe0c3c13f61449b2997f4e9722dfa60" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.106", +] + [[package]] name = "io-uring" version = "0.7.10" @@ -2476,6 +2781,15 @@ version = "1.70.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf" +[[package]] +name = "itertools" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "1.0.15" @@ -2593,11 +2907,48 @@ dependencies = [ "tracing-subscriber", ] +[[package]] +name = "komorebi-bar" +version = "0.1.39" +dependencies = [ + "chrono", + "chrono-tz", + "clap", + "color-eyre", + "crossbeam-channel", + "dirs 6.0.0", + "dunce", + "eframe", + "egui-phosphor", + "font-loader", + "hotwatch", + "image 0.25.8", + "komorebi-client", + "komorebi-themes", + "lazy_static", + "netdev", + "num", + "num-derive", + "num-traits", + "parking_lot", + "random_word", + "reqwest", + "schemars 0.8.22", + "serde", + "serde_json_lenient", + "starship-battery", + "sysinfo", + "tracing", + "tracing-subscriber", + "which", +] + [[package]] name = "komorebi-client" version = "0.1.0" dependencies = [ "komorebi", + "komorebi-themes", "serde_json_lenient", ] @@ -2662,12 +3013,34 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" +[[package]] +name = "lazycell" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" + +[[package]] +name = "lebe" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8" + [[package]] name = "libc" version = "0.2.176" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "58f929b4d672ea937a23a1ab494143d968337a5f47e56d0815df1e0890ddf174" +[[package]] +name = "libfuzzer-sys" +version = "0.4.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5037190e1f70cbeef565bd267599242926f724d3b8a9f510fd7e0b540cfa4404" +dependencies = [ + "arbitrary", + "cc", +] + [[package]] name = "libgit2-sys" version = "0.18.2+1.9.1" @@ -2792,6 +3165,24 @@ dependencies = [ "logos-codegen", ] +[[package]] +name = "loop9" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fae87c125b03c1d2c0150c90365d7d6bcc53fb73a9acaef207d2d065860f062" +dependencies = [ + "imgref", +] + +[[package]] +name = "mach2" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d640282b302c0bb0a2a8e0233ead9035e3bed871f0b7e81fe4a1ec829765db44" +dependencies = [ + "libc", +] + [[package]] name = "malloc_buf" version = "0.0.6" @@ -2810,6 +3201,16 @@ dependencies = [ "regex-automata", ] +[[package]] +name = "maybe-rayon" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ea1f30cedd69f0a2954655f7188c6a834246d2bcf1e315e2ac40c4b24dc9519" +dependencies = [ + "cfg-if", + "rayon", +] + [[package]] name = "memchr" version = "2.7.6" @@ -3019,6 +3420,78 @@ dependencies = [ "jni-sys", ] +[[package]] +name = "netdev" +version = "0.36.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "862209dce034f82a44c95ce2b5183730d616f2a68746b9c1959aa2572e77c0a1" +dependencies = [ + "dlopen2", + "ipnet", + "libc", + "netlink-packet-core", + "netlink-packet-route", + "netlink-sys", + "once_cell", + "system-configuration", + "windows-sys 0.59.0", +] + +[[package]] +name = "netlink-packet-core" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72724faf704479d67b388da142b186f916188505e7e0b26719019c525882eda4" +dependencies = [ + "anyhow", + "byteorder", + "netlink-packet-utils", +] + +[[package]] +name = "netlink-packet-route" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc0e7987b28514adf555dc1f9a5c30dfc3e50750bbaffb1aec41ca7b23dcd8e4" +dependencies = [ + "anyhow", + "bitflags 2.9.4", + "byteorder", + "libc", + "log", + "netlink-packet-core", + "netlink-packet-utils", +] + +[[package]] +name = "netlink-packet-utils" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ede8a08c71ad5a95cdd0e4e52facd37190977039a4704eb82a283f713747d34" +dependencies = [ + "anyhow", + "byteorder", + "paste", + "thiserror 1.0.69", +] + +[[package]] +name = "netlink-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16c903aa70590cb93691bf97a767c8d1d6122d2cc9070433deb3bbf36ce8bd23" +dependencies = [ + "bytes", + "libc", + "log", +] + +[[package]] +name = "new_debug_unreachable" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" + [[package]] name = "nix" version = "0.29.0" @@ -3060,6 +3533,12 @@ dependencies = [ "minimal-lexical", ] +[[package]] +name = "noop_proc_macro" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0676bb32a98c1a483ce53e500a81ad9c3d5b3f7c920c28c24e9cb0980d0b5bc8" + [[package]] name = "notify" version = "6.1.1" @@ -3110,12 +3589,56 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "num" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23" +dependencies = [ + "num-bigint", + "num-complex", + "num-integer", + "num-iter", + "num-rational 0.4.2", + "num-traits", +] + +[[package]] +name = "num-bigint" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "num-traits", +] + [[package]] name = "num-conv" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" +[[package]] +name = "num-derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.106", +] + [[package]] name = "num-integer" version = "0.1.46" @@ -3147,6 +3670,17 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -3745,7 +4279,7 @@ dependencies = [ "approx", "num-traits", "palette_derive", - "phf", + "phf 0.8.0", "phf_codegen", ] @@ -3826,7 +4360,16 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3dfb61232e34fcb633f43d12c58f83c1df82962dcdfa565a4e866ffc17dafe12" dependencies = [ - "phf_shared", + "phf_shared 0.8.0", +] + +[[package]] +name = "phf" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "913273894cec178f401a31ec4b656318d95473527be05c0752cc41cdc32be8b7" +dependencies = [ + "phf_shared 0.12.1", ] [[package]] @@ -3836,7 +4379,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cbffee61585b0411840d3ece935cce9cb6321f01c45477d30066498cd5e1a815" dependencies = [ "phf_generator", - "phf_shared", + "phf_shared 0.8.0", ] [[package]] @@ -3845,7 +4388,7 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "17367f0cc86f2d25802b2c26ee58a7b23faeccf78a396094c13dced0d0182526" dependencies = [ - "phf_shared", + "phf_shared 0.8.0", "rand 0.7.3", ] @@ -3855,7 +4398,16 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c00cf8b9eafe68dde5e9eaa2cef8ee84a9336a47d566ec55ca16589633b65af7" dependencies = [ - "siphasher", + "siphasher 0.3.11", +] + +[[package]] +name = "phf_shared" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06005508882fb681fd97892ecff4b7fd0fee13ef1aa569f8695dae7ab9099981" +dependencies = [ + "siphasher 1.0.1", ] [[package]] @@ -3907,6 +4459,19 @@ version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c" +[[package]] +name = "plist" +version = "1.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3af6b589e163c5a788fab00ce0c0366f6efbb9959c2f9874b224936af7fce7e1" +dependencies = [ + "base64", + "indexmap 2.11.4", + "quick-xml 0.38.3", + "serde", + "time", +] + [[package]] name = "png" version = "0.16.8" @@ -3976,7 +4541,7 @@ version = "3.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "219cb19e96be00ab2e37d6e299658a0cfa83e52429179969b0f0121b4ac46983" dependencies = [ - "toml_edit", + "toml_edit 0.23.6", ] [[package]] @@ -3993,6 +4558,19 @@ name = "profiling" version = "1.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3eb8486b569e12e2c32ad3e204dbaba5e4b5b216e9367044f25f1dba42341773" +dependencies = [ + "profiling-procmacros", +] + +[[package]] +name = "profiling-procmacros" +version = "1.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52717f9a02b6965224f95ca2a81e2e0c5c43baacd28ca057577988930b6c3d5b" +dependencies = [ + "quote", + "syn 2.0.106", +] [[package]] name = "pxfm" @@ -4003,6 +4581,15 @@ dependencies = [ "num-traits", ] +[[package]] +name = "qoi" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f6d64c71eb498fe9eae14ce4ec935c555749aef511cca85b5568910d6e48001" +dependencies = [ + "bytemuck", +] + [[package]] name = "quick-error" version = "2.0.1" @@ -4111,6 +4698,16 @@ dependencies = [ "rand_core 0.6.4", ] +[[package]] +name = "rand" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.3", +] + [[package]] name = "rand_chacha" version = "0.2.2" @@ -4131,6 +4728,16 @@ dependencies = [ "rand_core 0.6.4", ] +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.3", +] + [[package]] name = "rand_core" version = "0.5.1" @@ -4149,6 +4756,15 @@ dependencies = [ "getrandom 0.2.16", ] +[[package]] +name = "rand_core" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38" +dependencies = [ + "getrandom 0.3.3", +] + [[package]] name = "rand_hc" version = "0.2.0" @@ -4167,6 +4783,69 @@ dependencies = [ "rand_core 0.5.1", ] +[[package]] +name = "random_word" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e47a395bdb55442b883c89062d6bcff25dc90fa5f8369af81e0ac6d49d78cf81" +dependencies = [ + "ahash", + "brotli", + "paste", + "rand 0.9.2", + "unicase", +] + +[[package]] +name = "rav1e" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd87ce80a7665b1cce111f8a16c1f3929f6547ce91ade6addf4ec86a8dda5ce9" +dependencies = [ + "arbitrary", + "arg_enum_proc_macro", + "arrayvec", + "av1-grain", + "bitstream-io", + "built", + "cfg-if", + "interpolate_name", + "itertools", + "libc", + "libfuzzer-sys", + "log", + "maybe-rayon", + "new_debug_unreachable", + "noop_proc_macro", + "num-derive", + "num-traits", + "once_cell", + "paste", + "profiling", + "rand 0.8.5", + "rand_chacha 0.3.1", + "simd_helpers", + "system-deps", + "thiserror 1.0.69", + "v_frame", + "wasm-bindgen", +] + +[[package]] +name = "ravif" +version = "0.11.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5825c26fddd16ab9f515930d49028a630efec172e903483c94796cfe31893e6b" +dependencies = [ + "avif-serialize", + "imgref", + "loop9", + "quick-error", + "rav1e", + "rayon", + "rgb", +] + [[package]] name = "raw-window-handle" version = "0.6.2" @@ -4639,6 +5318,15 @@ dependencies = [ "syn 2.0.106", ] +[[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", +] + [[package]] name = "serde_urlencoded" version = "0.7.1" @@ -4705,6 +5393,27 @@ dependencies = [ "yaml-rust", ] +[[package]] +name = "servo-fontconfig" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7e3e22fe5fd73d04ebf0daa049d3efe3eae55369ce38ab16d07ddd9ac5c217c" +dependencies = [ + "libc", + "servo-fontconfig-sys", +] + +[[package]] +name = "servo-fontconfig-sys" +version = "5.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e36b879db9892dfa40f95da1c38a835d41634b825fbd8c4c418093d53c24b388" +dependencies = [ + "expat-sys", + "freetype-sys", + "pkg-config", +] + [[package]] name = "sha1" version = "0.10.6" @@ -4718,9 +5427,9 @@ dependencies = [ [[package]] name = "shadow-rs" -version = "1.3.0" +version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8aa5c0570cd9654158bd39f0f8caba24edbc058313946e89f4648b1de1ecf49" +checksum = "72d18183cef626bce22836103349c7050d73db799be0171386b80947d157ae32" dependencies = [ "const_format", "git2", @@ -4774,12 +5483,27 @@ version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d66dc143e6b11c1eddc06d5c423cfc97062865baf299914ab64caa38182078fe" +[[package]] +name = "simd_helpers" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95890f873bec569a0362c235787f3aca6e1e887302ba4840839bcc6459c42da6" +dependencies = [ + "quote", +] + [[package]] name = "siphasher" version = "0.3.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d" +[[package]] +name = "siphasher" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56199f7ddabf13fe5074ce809e7d3f42b42ae711800501b5b16ea82ad029c39d" + [[package]] name = "slab" version = "0.4.11" @@ -4871,6 +5595,24 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" +[[package]] +name = "starship-battery" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b781e3db6801873ce18c19041da668920c46223cdc7059ea20e2f8fe1ba85a2" +dependencies = [ + "cfg-if", + "core-foundation 0.10.1", + "lazycell", + "libc", + "mach2", + "nix 0.30.1", + "num-traits", + "plist", + "uom", + "windows-sys 0.60.2", +] + [[package]] name = "static_assertions" version = "1.1.0" @@ -5015,6 +5757,25 @@ dependencies = [ "libc", ] +[[package]] +name = "system-deps" +version = "6.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3e535eb8dded36d55ec13eddacd30dec501792ff23a0b1682c38601b8cf2349" +dependencies = [ + "cfg-expr", + "heck", + "pkg-config", + "toml 0.8.23", + "version-compare", +] + +[[package]] +name = "target-lexicon" +version = "0.12.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1" + [[package]] name = "tempfile" version = "3.23.0" @@ -5258,6 +6019,27 @@ dependencies = [ "serde", ] +[[package]] +name = "toml" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" +dependencies = [ + "serde", + "serde_spanned", + "toml_datetime 0.6.11", + "toml_edit 0.22.27", +] + +[[package]] +name = "toml_datetime" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" +dependencies = [ + "serde", +] + [[package]] name = "toml_datetime" version = "0.7.2" @@ -5267,6 +6049,19 @@ dependencies = [ "serde_core", ] +[[package]] +name = "toml_edit" +version = "0.22.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" +dependencies = [ + "indexmap 2.11.4", + "serde", + "serde_spanned", + "toml_datetime 0.6.11", + "winnow", +] + [[package]] name = "toml_edit" version = "0.23.6" @@ -5274,7 +6069,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f3effe7c0e86fdff4f69cdd2ccc1b96f933e24811c5441d44904e8683e27184b" dependencies = [ "indexmap 2.11.4", - "toml_datetime", + "toml_datetime 0.7.2", "toml_parser", "winnow", ] @@ -5480,6 +6275,12 @@ dependencies = [ "winapi", ] +[[package]] +name = "unicase" +version = "2.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75b844d17643ee918803943289730bec8aac480150456169e647ed0b576ba539" + [[package]] name = "unicode-ident" version = "1.0.19" @@ -5510,6 +6311,16 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" +[[package]] +name = "uom" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd5cfe7d84f6774726717f358a37f5bca8fca273bed4de40604ad129d1107b49" +dependencies = [ + "num-traits", + "typenum", +] + [[package]] name = "url" version = "2.5.7" @@ -5534,6 +6345,17 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" +[[package]] +name = "v_frame" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "666b7727c8875d6ab5db9533418d7c764233ac9c0cff1d469aec8fa127597be2" +dependencies = [ + "aligned-vec", + "num-traits", + "wasm-bindgen", +] + [[package]] name = "valuable" version = "0.1.1" @@ -5546,6 +6368,12 @@ version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" +[[package]] +name = "version-compare" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "852e951cb7832cb45cb1169900d19760cfa39b82bc0ea9c0e5a14ae88411c98b" + [[package]] name = "version_check" version = "0.9.5" @@ -5927,6 +6755,18 @@ dependencies = [ "web-sys", ] +[[package]] +name = "which" +version = "7.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d643ce3fd3e5b54854602a080f34fb10ab75e0b813ee32d00ca2b44fa74762" +dependencies = [ + "either", + "env_home", + "rustix 1.1.2", + "winsafe", +] + [[package]] name = "winapi" version = "0.3.9" @@ -6494,7 +7334,7 @@ dependencies = [ "cfg_aliases", "concurrent-queue", "core-foundation 0.9.4", - "core-graphics", + "core-graphics 0.23.2", "cursor-icon", "dpi", "js-sys", @@ -6539,6 +7379,12 @@ dependencies = [ "memchr", ] +[[package]] +name = "winsafe" +version = "0.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904" + [[package]] name = "wit-bindgen" version = "0.46.0" @@ -6842,6 +7688,15 @@ version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f423a2c17029964870cfaabb1f13dfab7d092a62a29a89264f4d36990ca414a" +[[package]] +name = "zune-inflate" +version = "0.2.54" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02" +dependencies = [ + "simd-adler32", +] + [[package]] name = "zune-jpeg" version = "0.4.21" diff --git a/Cargo.toml b/Cargo.toml index a9a94344..15a74e7e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "2" members = [ "komorebi", "komorebi-client", - "komorebic", + "komorebic", "komorebi-bar" ] @@ -12,8 +12,15 @@ chrono = "0.4" chrono-tz = "0.10" clap = { version = "4", features = ["derive", "wrap_help"] } color-eyre = "0.6" +crossbeam-channel = "0.5" +crossbeam-utils = "0.8" dirs = "6" +dunce = "1" +eframe = "0.31" +egui_extras = "0.31" +hotwatch = "0.5" lazy_static = "1" +parking_lot = "0.12" pastey = "0.1" schemars = "0.8" serde = { version = "1", features = ["derive"] } @@ -21,3 +28,7 @@ serde_json = { package = "serde_json_lenient", version = "0.2" } shadow-rs = "1" sysinfo = "0.37" thiserror = "2" +tracing = "0.1" +tracing-appender = "0.2" +tracing-subscriber = { version = "0.3", features = ["env-filter"] } +which = "7" diff --git a/docs/komorebi.bar.example.json b/docs/komorebi.bar.example.json new file mode 100644 index 00000000..d1254319 --- /dev/null +++ b/docs/komorebi.bar.example.json @@ -0,0 +1,64 @@ +{ + "$schema": "https://raw.githubusercontent.com/LGUG2Z/komorebi/v0.1.38/schema.bar.json", + "monitor": 0, + "font_family": "JetBrainsMono Nerd Font", + "height": 30, + "theme": { + "palette": "Base16", + "name": "Ashes", + "accent": "Base0D" + }, + "left_widgets": [ + { + "Komorebi": { + "workspaces": { + "enable": true, + "hide_empty_workspaces": false + }, + "layout": { + "enable": true + }, + "focused_window": { + "enable": true, + "show_icon": true + } + } + } + ], + "right_widgets": [ + { + "Update": { + "enable": true + } + }, + { + "Storage": { + "enable": true + } + }, + { + "Memory": { + "enable": true + } + }, + { + "Network": { + "enable": true, + "show_activity": true, + "show_total_activity": true, + } + }, + { + "Date": { + "enable": true, + "format": "DayDateMonthYear" + } + }, + { + "Time": { + "enable": true, + "format": "TwentyFourHour" + } + }, + ] +} diff --git a/komorebi-bar/Cargo.toml b/komorebi-bar/Cargo.toml new file mode 100644 index 00000000..2d9e42cc --- /dev/null +++ b/komorebi-bar/Cargo.toml @@ -0,0 +1,47 @@ +[package] +name = "komorebi-bar" +version = "0.1.39" +edition = "2024" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +komorebi-client = { path = "../komorebi-client", default-features = false } +komorebi-themes = { git = "https://github.com/LGUG2Z/komorebi", version = "0.1.38" } + +chrono-tz = { workspace = true } +chrono = { workspace = true } +clap = { workspace = true } +color-eyre = { workspace = true } +crossbeam-channel = { workspace = true } +dirs = { workspace = true } +dunce = { workspace = true } +eframe = { workspace = true } +egui-phosphor = "0.9" +font-loader = "0.11" +hotwatch = { workspace = true } +image = "0.25" +lazy_static = { workspace = true } +netdev = "0.36" +num = "0.4" +num-derive = "0.4" +num-traits = "0.2" +parking_lot = { workspace = true } +random_word = { version = "0.5", features = ["en"] } +reqwest = { version = "0.12", features = ["blocking"] } +schemars = { workspace = true, optional = true } +serde = { workspace = true } +serde_json = { workspace = true } +starship-battery = "0.10" +sysinfo = { workspace = true } +tracing = { workspace = true } +tracing-subscriber = { workspace = true } +which = { workspace = true } +#windows = { workspace = true } +#windows-core = { workspace = true } +#windows-icons = { git = "https://github.com/LGUG2Z/windows-icons", rev = "0c9d7ee1b807347c507d3a9862dd007b4d3f4354" } +#windows-icons-fallback = { package = "windows-icons", git = "https://github.com/LGUG2Z/windows-icons", rev = "d67cc9920aa9b4883393e411fb4fa2ddd4c498b5" } + +[features] +default = ["schemars"] +schemars = ["dep:schemars", "komorebi-client/default", "komorebi-themes/default"] diff --git a/komorebi-bar/src/bar.rs b/komorebi-bar/src/bar.rs new file mode 100644 index 00000000..e80277bd --- /dev/null +++ b/komorebi-bar/src/bar.rs @@ -0,0 +1,1347 @@ +use crate::AUTO_SELECT_FILL_COLOUR; +use crate::AUTO_SELECT_TEXT_COLOUR; +use crate::BAR_HEIGHT; +use crate::DEFAULT_PADDING; +use crate::KomorebiEvent; +use crate::MAX_LABEL_WIDTH; +use crate::MONITOR_LEFT; +use crate::MONITOR_RIGHT; +use crate::MONITOR_TOP; +use crate::config::KomobarConfig; +use crate::config::KomobarTheme; +use crate::config::MonitorConfigOrIndex; +use crate::config::Position; +use crate::config::PositionConfig; +use crate::config::get_individual_spacing; +use crate::render::Color32Ext; +use crate::render::Grouping; +use crate::render::RenderConfig; +use crate::render::RenderExt; +use crate::widgets::komorebi::Komorebi; +use crate::widgets::komorebi::MonitorInfo; +use crate::widgets::widget::BarWidget; +use crate::widgets::widget::WidgetConfig; +use crossbeam_channel::Receiver; +use crossbeam_channel::TryRecvError; +use eframe::egui::Align; +use eframe::egui::Align2; +use eframe::egui::Area; +use eframe::egui::CentralPanel; +use eframe::egui::Color32; +use eframe::egui::Context; +use eframe::egui::FontData; +use eframe::egui::FontDefinitions; +use eframe::egui::FontFamily; +use eframe::egui::FontId; +use eframe::egui::Frame; +use eframe::egui::Id; +use eframe::egui::Layout; +use eframe::egui::Margin; +use eframe::egui::Pos2; +use eframe::egui::Rgba; +use eframe::egui::Style; +use eframe::egui::TextStyle; +use eframe::egui::Vec2; +use eframe::egui::ViewportCommand; +use eframe::egui::Visuals; +use font_loader::system_fonts; +use font_loader::system_fonts::FontPropertyBuilder; +use komorebi_client::Colour; +use komorebi_client::NotificationEvent; +use komorebi_client::PathExt; +use komorebi_client::SocketMessage; +use komorebi_themes::Base16Wrapper; +use komorebi_themes::Catppuccin; +use komorebi_themes::catppuccin_egui; +use lazy_static::lazy_static; +use parking_lot::Mutex; +use std::cell::RefCell; +use std::path::PathBuf; +use std::process::ChildStdin; +use std::rc::Rc; +use std::sync::Arc; +use std::sync::atomic::Ordering; + +lazy_static! { + static ref SESSION_STDIN: Mutex> = Mutex::new(None); +} + +// fn start_powershell() -> Result<()> { +// // found running session, do nothing +// if SESSION_STDIN.lock().as_mut().is_some() { +// tracing::debug!("PowerShell session already started"); +// return Ok(()); +// } +// +// tracing::debug!("Starting PowerShell session"); +// +// let mut child = Command::new("powershell.exe") +// .args(["-NoLogo", "-NoProfile", "-Command", "-"]) +// .stdin(Stdio::piped()) +// .creation_flags(CREATE_NO_WINDOW) +// .spawn()?; +// +// let stdin = child.stdin.take().expect("stdin piped"); +// +// // Store stdin for later commands +// let mut session_stdin = SESSION_STDIN.lock(); +// *session_stdin = Option::from(stdin); +// +// Ok(()) +// } + +// fn stop_powershell() -> Result<()> { +// tracing::debug!("Stopping PowerShell session"); +// +// if let Some(mut session_stdin) = SESSION_STDIN.lock().take() { +// if let Err(e) = session_stdin.write_all(b"exit\n") { +// tracing::error!(error = %e, "failed to write exit command to PowerShell stdin"); +// return Err(e); +// } +// if let Err(e) = session_stdin.flush() { +// tracing::error!(error = %e, "failed to flush PowerShell stdin"); +// return Err(e); +// } +// +// tracing::debug!("PowerShell session stopped"); +// } else { +// tracing::debug!("PowerShell session already stopped"); +// } +// +// Ok(()) +// } + +// pub fn exec_powershell(cmd: &str) -> Result<()> { +// if let Some(session_stdin) = SESSION_STDIN.lock().as_mut() { +// if let Err(e) = writeln!(session_stdin, "{cmd}") { +// tracing::error!(error = %e, cmd = cmd, "failed to write command to PowerShell stdin"); +// return Err(e); +// } +// +// if let Err(e) = session_stdin.flush() { +// tracing::error!(error = %e, "failed to flush PowerShell stdin"); +// return Err(e); +// } +// +// return Ok(()); +// } +// +// Err(Error::new( +// ErrorKind::NotFound, +// "PowerShell session not started", +// )) +// } + +pub struct Komobar { + // pub hwnd: Option, + pub monitor_index: Option, + pub disabled: bool, + pub config: KomobarConfig, + pub render_config: Rc>, + pub monitor_info: Option>>, + pub left_widgets: Vec>, + pub center_widgets: Vec>, + pub right_widgets: Vec>, + pub rx_gui: Receiver, + pub rx_config: Receiver, + pub bg_color: Rc>, + pub bg_color_with_alpha: Rc>, + pub scale_factor: f32, + pub size_rect: komorebi_client::Rect, + pub work_area_offset: komorebi_client::Rect, + applied_theme_on_first_frame: bool, + mouse_follows_focus: bool, + // input_config: InputConfig, +} + +// struct InputConfig { +// accumulated_scroll_delta: Vec2, +// act_on_vertical_scroll: bool, +// act_on_horizontal_scroll: bool, +// vertical_scroll_threshold: f32, +// horizontal_scroll_threshold: f32, +// vertical_scroll_max_threshold: f32, +// horizontal_scroll_max_threshold: f32, +// } + +pub fn apply_theme( + ctx: &Context, + theme: KomobarTheme, + bg_color: Rc>, + bg_color_with_alpha: Rc>, + transparency_alpha: Option, + grouping: Option, + render_config: Rc>, +) { + let (auto_select_fill, auto_select_text) = match theme { + KomobarTheme::Catppuccin { + name: catppuccin, + accent: catppuccin_value, + auto_select_fill: catppuccin_auto_select_fill, + auto_select_text: catppuccin_auto_select_text, + } => { + match catppuccin { + Catppuccin::Frappe => { + catppuccin_egui::set_theme(ctx, catppuccin_egui::FRAPPE); + let catppuccin_value = catppuccin_value.unwrap_or_default(); + let accent = catppuccin_value.color32(catppuccin.as_theme()); + + ctx.style_mut(|style| { + style.visuals.selection.stroke.color = accent; + style.visuals.widgets.hovered.fg_stroke.color = accent; + style.visuals.widgets.active.fg_stroke.color = accent; + style.visuals.override_text_color = None; + }); + + bg_color.replace(catppuccin_egui::FRAPPE.base); + } + Catppuccin::Latte => { + catppuccin_egui::set_theme(ctx, catppuccin_egui::LATTE); + let catppuccin_value = catppuccin_value.unwrap_or_default(); + let accent = catppuccin_value.color32(catppuccin.as_theme()); + + ctx.style_mut(|style| { + style.visuals.selection.stroke.color = accent; + style.visuals.widgets.hovered.fg_stroke.color = accent; + style.visuals.widgets.active.fg_stroke.color = accent; + style.visuals.override_text_color = None; + }); + + bg_color.replace(catppuccin_egui::LATTE.base); + } + Catppuccin::Macchiato => { + catppuccin_egui::set_theme(ctx, catppuccin_egui::MACCHIATO); + let catppuccin_value = catppuccin_value.unwrap_or_default(); + let accent = catppuccin_value.color32(catppuccin.as_theme()); + + ctx.style_mut(|style| { + style.visuals.selection.stroke.color = accent; + style.visuals.widgets.hovered.fg_stroke.color = accent; + style.visuals.widgets.active.fg_stroke.color = accent; + style.visuals.override_text_color = None; + }); + + bg_color.replace(catppuccin_egui::MACCHIATO.base); + } + Catppuccin::Mocha => { + catppuccin_egui::set_theme(ctx, catppuccin_egui::MOCHA); + let catppuccin_value = catppuccin_value.unwrap_or_default(); + let accent = catppuccin_value.color32(catppuccin.as_theme()); + + ctx.style_mut(|style| { + style.visuals.selection.stroke.color = accent; + style.visuals.widgets.hovered.fg_stroke.color = accent; + style.visuals.widgets.active.fg_stroke.color = accent; + style.visuals.override_text_color = None; + }); + + bg_color.replace(catppuccin_egui::MOCHA.base); + } + } + + ( + catppuccin_auto_select_fill.map(|c| c.color32(catppuccin.as_theme())), + catppuccin_auto_select_text.map(|c| c.color32(catppuccin.as_theme())), + ) + } + KomobarTheme::Base16 { + name: base16, + accent: base16_value, + auto_select_fill: base16_auto_select_fill, + auto_select_text: base16_auto_select_text, + } => { + ctx.set_style(base16.style()); + let base16_value = base16_value.unwrap_or_default(); + let accent = base16_value.color32(Base16Wrapper::Base16(base16)); + + ctx.style_mut(|style| { + style.visuals.selection.stroke.color = accent; + style.visuals.widgets.hovered.fg_stroke.color = accent; + style.visuals.widgets.active.fg_stroke.color = accent; + }); + + bg_color.replace(base16.background()); + + ( + base16_auto_select_fill.map(|c| c.color32(Base16Wrapper::Base16(base16))), + base16_auto_select_text.map(|c| c.color32(Base16Wrapper::Base16(base16))), + ) + } + KomobarTheme::Custom { + colours, + accent: base16_value, + auto_select_fill: base16_auto_select_fill, + auto_select_text: base16_auto_select_text, + } => { + let background = colours.background(); + ctx.set_style(colours.style()); + let base16_value = base16_value.unwrap_or_default(); + let accent = base16_value.color32(Base16Wrapper::Custom(colours.clone())); + + ctx.style_mut(|style| { + style.visuals.selection.stroke.color = accent; + style.visuals.widgets.hovered.fg_stroke.color = accent; + style.visuals.widgets.active.fg_stroke.color = accent; + }); + + bg_color.replace(background); + + ( + base16_auto_select_fill.map(|c| c.color32(Base16Wrapper::Custom(colours.clone()))), + base16_auto_select_text.map(|c| c.color32(Base16Wrapper::Custom(colours.clone()))), + ) + } + }; + + AUTO_SELECT_FILL_COLOUR.store( + auto_select_fill.map_or(0, |c| Colour::from(c).into()), + Ordering::SeqCst, + ); + AUTO_SELECT_TEXT_COLOUR.store( + auto_select_text.map_or(0, |c| Colour::from(c).into()), + Ordering::SeqCst, + ); + + // Apply transparency_alpha + let theme_color = *bg_color.borrow(); + + bg_color_with_alpha.replace(theme_color.try_apply_alpha(transparency_alpha)); + + // apply rounding to the widgets + if let Some(Grouping::Bar(config) | Grouping::Alignment(config) | Grouping::Widget(config)) = + &grouping + && let Some(rounding) = config.rounding + { + ctx.style_mut(|style| { + style.visuals.widgets.noninteractive.corner_radius = rounding.into(); + style.visuals.widgets.inactive.corner_radius = rounding.into(); + style.visuals.widgets.hovered.corner_radius = rounding.into(); + style.visuals.widgets.active.corner_radius = rounding.into(); + style.visuals.widgets.open.corner_radius = rounding.into(); + }); + } + + // Update RenderConfig's background_color so that widgets will have the new color + render_config.borrow_mut().background_color = *bg_color.borrow(); +} + +impl Komobar { + pub fn apply_config( + &mut self, + ctx: &Context, + previous_monitor_info: Option>>, + ) { + MAX_LABEL_WIDTH.store( + self.config.max_label_width.unwrap_or(400.0) as i32, + Ordering::SeqCst, + ); + + if let Some(font_family) = &self.config.font_family { + tracing::info!("attempting to add custom font family: {font_family}"); + Self::add_custom_font(ctx, font_family); + } + + // Update the `size_rect` so that the bar position can be changed on the EGUI update + // function + self.update_size_rect(); + + self.try_apply_theme(ctx); + + if let Some(font_size) = &self.config.font_size { + tracing::info!("attempting to set custom font size: {font_size}"); + Self::set_font_size(ctx, *font_size); + } + + self.render_config.replace((&self.config).new_renderconfig( + ctx, + *self.bg_color.borrow(), + self.config.icon_scale, + )); + + let mut monitor_info = previous_monitor_info; + let mut komorebi_widgets = Vec::new(); + + for (idx, widget_config) in self.config.left_widgets.iter().enumerate() { + if let WidgetConfig::Komorebi(config) = widget_config { + komorebi_widgets.push((Komorebi::from(config), idx, Alignment::Left)); + } + } + + if let Some(center_widgets) = &self.config.center_widgets { + for (idx, widget_config) in center_widgets.iter().enumerate() { + if let WidgetConfig::Komorebi(config) = widget_config { + komorebi_widgets.push((Komorebi::from(config), idx, Alignment::Center)); + } + } + } + + for (idx, widget_config) in self.config.right_widgets.iter().enumerate() { + if let WidgetConfig::Komorebi(config) = widget_config { + komorebi_widgets.push((Komorebi::from(config), idx, Alignment::Right)); + } + } + + let mut left_widgets = self + .config + .left_widgets + .iter() + .filter(|config| config.enabled()) + .map(|config| config.as_boxed_bar_widget()) + .collect::>>(); + + let mut center_widgets = match &self.config.center_widgets { + Some(center_widgets) => center_widgets + .iter() + .filter(|config| config.enabled()) + .map(|config| config.as_boxed_bar_widget()) + .collect::>>(), + None => vec![], + }; + + let mut right_widgets = self + .config + .right_widgets + .iter() + .filter(|config| config.enabled()) + .map(|config| config.as_boxed_bar_widget()) + .collect::>>(); + + if !komorebi_widgets.is_empty() { + komorebi_widgets + .into_iter() + .for_each(|(mut widget, idx, side)| { + match monitor_info { + None => { + monitor_info = Some(widget.monitor_info.clone()); + } + Some(ref previous) => { + if widget.workspaces.is_some() { + previous + .borrow_mut() + .update_from_self(&widget.monitor_info.borrow()); + } + + widget.monitor_info = previous.clone(); + } + } + + let boxed: Box = Box::new(widget); + match side { + Alignment::Left => left_widgets[idx] = boxed, + Alignment::Center => center_widgets[idx] = boxed, + Alignment::Right => right_widgets[idx] = boxed, + } + }); + } + + right_widgets.reverse(); + + self.left_widgets = left_widgets; + self.center_widgets = center_widgets; + self.right_widgets = right_widgets; + + let (usr_monitor_index, config_work_area_offset) = match &self.config.monitor { + MonitorConfigOrIndex::MonitorConfig(monitor_config) => { + (monitor_config.index, monitor_config.work_area_offset) + } + MonitorConfigOrIndex::Index(idx) => (*idx, None), + }; + + let mapped_info = self.monitor_info.as_ref().map(|info| { + let monitor = info.borrow(); + ( + monitor.monitor_usr_idx_map.get(&usr_monitor_index).copied(), + monitor.mouse_follows_focus, + ) + }); + + if let Some(info) = mapped_info { + self.monitor_index = info.0; + self.mouse_follows_focus = info.1; + } + + if let Some(monitor_index) = self.monitor_index { + if let (prev_rect, Some(new_rect)) = (&self.work_area_offset, &config_work_area_offset) + { + if new_rect != prev_rect { + self.work_area_offset = *new_rect; + if let Err(error) = komorebi_client::send_message( + &SocketMessage::MonitorWorkAreaOffset(monitor_index, *new_rect), + ) { + tracing::error!( + "error applying work area offset to monitor '{}': {}", + monitor_index, + error, + ); + } else { + tracing::info!("work area offset applied to monitor: {}", monitor_index); + } + } + } else if let Some(height) = self.config.height.or(Some(BAR_HEIGHT)) { + // We only add the `bottom_margin` to the work_area_offset since the top margin is + // already considered on the `size_rect.top` + let bottom_margin = self + .config + .margin + .as_ref() + .map_or(0, |v| v.to_individual(0.0).bottom as i32); + let new_rect = komorebi_client::Rect { + left: 0, + top: (height as i32) + + (self.size_rect.top - MONITOR_TOP.load(Ordering::SeqCst)) + + bottom_margin, + right: 0, + bottom: (height as i32) + + (self.size_rect.top - MONITOR_TOP.load(Ordering::SeqCst)) + + bottom_margin, + }; + + if new_rect != self.work_area_offset { + self.work_area_offset = new_rect; + if let Err(error) = komorebi_client::send_message( + &SocketMessage::MonitorWorkAreaOffset(monitor_index, new_rect), + ) { + tracing::error!( + "error applying work area offset to monitor '{monitor_index}': {error}" + ); + } else { + tracing::info!("work area offset applied to monitor: {monitor_index}",); + } + } + } + } else if self.monitor_info.is_some() && !self.disabled { + tracing::warn!( + "couldn't find the monitor index of this bar! Disabling the bar until the monitor connects..." + ); + self.disabled = true; + } else { + tracing::warn!( + "couldn't find the monitor index of this bar, if the bar is starting up this is normal until it receives the first state from komorebi." + ); + self.disabled = true; + } + + // if let Some(mouse) = &self.config.mouse { + // self.input_config.act_on_vertical_scroll = + // mouse.on_scroll_up.is_some() || mouse.on_scroll_down.is_some(); + // self.input_config.act_on_horizontal_scroll = + // mouse.on_scroll_left.is_some() || mouse.on_scroll_right.is_some(); + // self.input_config.vertical_scroll_threshold = mouse + // .vertical_scroll_threshold + // .unwrap_or(30.0) + // .clamp(10.0, 300.0); + // self.input_config.horizontal_scroll_threshold = mouse + // .horizontal_scroll_threshold + // .unwrap_or(30.0) + // .clamp(10.0, 300.0); + // // limit how many "ticks" can be accumulated + // self.input_config.vertical_scroll_max_threshold = + // self.input_config.vertical_scroll_threshold * 3.0; + // self.input_config.horizontal_scroll_max_threshold = + // self.input_config.horizontal_scroll_threshold * 3.0; + // + // if mouse.has_command() { + // start_powershell().unwrap_or_else(|_| { + // tracing::error!("failed to start powershell session"); + // }); + // } else { + // stop_powershell().unwrap_or_else(|_| { + // tracing::error!("failed to stop powershell session"); + // }); + // } + // } + + tracing::info!("widget configuration options applied"); + + self.monitor_info = monitor_info; + } + + /// Updates the `size_rect` field. Returns a bool indicating if the field was changed or not + fn update_size_rect(&mut self) { + let position = self.config.position.clone().unwrap_or(PositionConfig { + start: Some(Position { + x: MONITOR_LEFT.load(Ordering::SeqCst) as f32, + y: MONITOR_TOP.load(Ordering::SeqCst) as f32, + }), + end: Some(Position { + x: MONITOR_RIGHT.load(Ordering::SeqCst) as f32, + y: BAR_HEIGHT, + }), + }); + + let mut start = position.start.unwrap_or(Position { + x: MONITOR_LEFT.load(Ordering::SeqCst) as f32, + y: MONITOR_TOP.load(Ordering::SeqCst) as f32, + }); + + let mut end = position.end.unwrap_or(Position { + x: MONITOR_RIGHT.load(Ordering::SeqCst) as f32, + y: BAR_HEIGHT, + }); + + if let Some(height) = self.config.height { + end.y = height; + } + + let margin = get_individual_spacing(0.0, &self.config.margin); + + start.y += margin.top; + start.x += margin.left; + end.x -= margin.left + margin.right; + + if end.y == 0.0 { + tracing::warn!( + "position.end.y is set to 0.0 which will make your bar invisible on a config reload - this is usually set to 50.0 by default" + ) + } + + self.size_rect = komorebi_client::Rect { + left: start.x as i32, + top: start.y as i32, + right: end.x as i32, + bottom: end.y as i32, + }; + } + + fn try_apply_theme(&mut self, ctx: &Context) { + match &self.config.theme { + Some(theme) => { + apply_theme( + ctx, + theme.clone(), + self.bg_color.clone(), + self.bg_color_with_alpha.clone(), + self.config.transparency_alpha, + self.config.grouping, + self.render_config.clone(), + ); + } + None => { + let 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 + + }, + ); + + let bar_transparency_alpha = self.config.transparency_alpha; + let bar_grouping = self.config.grouping; + let config = home_dir.join("komorebi.json"); + match komorebi_client::StaticConfig::read(&config) { + Ok(config) => { + if let Some(theme) = config.theme { + apply_theme( + ctx, + KomobarTheme::from(theme), + self.bg_color.clone(), + self.bg_color_with_alpha.clone(), + bar_transparency_alpha, + bar_grouping, + self.render_config.clone(), + ); + } + } + Err(_) => { + ctx.set_style(Style::default()); + self.bg_color.replace(Style::default().visuals.panel_fill); + + // apply rounding to the widgets since we didn't call `apply_theme` + if let Some( + Grouping::Bar(config) + | Grouping::Alignment(config) + | Grouping::Widget(config), + ) = &bar_grouping + && let Some(rounding) = config.rounding + { + ctx.style_mut(|style| { + style.visuals.widgets.noninteractive.corner_radius = + rounding.into(); + style.visuals.widgets.inactive.corner_radius = rounding.into(); + style.visuals.widgets.hovered.corner_radius = rounding.into(); + style.visuals.widgets.active.corner_radius = rounding.into(); + style.visuals.widgets.open.corner_radius = rounding.into(); + }); + } + } + } + } + } + } + + pub fn new( + cc: &eframe::CreationContext<'_>, + rx_gui: Receiver, + rx_config: Receiver, + config: KomobarConfig, + ) -> Self { + let mut komobar = Self { + // hwnd: process_hwnd(), + monitor_index: None, + disabled: false, + config, + render_config: Rc::new(RefCell::new(RenderConfig::new())), + monitor_info: None, + left_widgets: vec![], + center_widgets: vec![], + right_widgets: vec![], + rx_gui, + rx_config, + bg_color: Rc::new(RefCell::new(Style::default().visuals.panel_fill)), + bg_color_with_alpha: Rc::new(RefCell::new(Style::default().visuals.panel_fill)), + scale_factor: cc.egui_ctx.native_pixels_per_point().unwrap_or(1.0), + size_rect: komorebi_client::Rect::default(), + work_area_offset: komorebi_client::Rect::default(), + applied_theme_on_first_frame: false, + mouse_follows_focus: false, + // input_config: InputConfig { + // accumulated_scroll_delta: Vec2::new(0.0, 0.0), + // act_on_vertical_scroll: false, + // act_on_horizontal_scroll: false, + // vertical_scroll_threshold: 0.0, + // horizontal_scroll_threshold: 0.0, + // vertical_scroll_max_threshold: 0.0, + // horizontal_scroll_max_threshold: 0.0, + // }, + }; + + komobar.apply_config(&cc.egui_ctx, None); + // needs a double apply the first time for some reason + komobar.apply_config(&cc.egui_ctx, None); + + komobar + } + + fn set_font_size(ctx: &Context, font_size: f32) { + ctx.style_mut(|style| { + style.text_styles = [ + (TextStyle::Small, FontId::new(9.0, FontFamily::Proportional)), + ( + TextStyle::Body, + FontId::new(font_size, FontFamily::Proportional), + ), + ( + TextStyle::Button, + FontId::new(font_size, FontFamily::Proportional), + ), + ( + TextStyle::Heading, + FontId::new(18.0, FontFamily::Proportional), + ), + ( + TextStyle::Monospace, + FontId::new(font_size, FontFamily::Monospace), + ), + ] + .into(); + }); + } + + fn add_custom_font(ctx: &Context, name: &str) { + let mut fonts = FontDefinitions::default(); + egui_phosphor::add_to_fonts(&mut fonts, egui_phosphor::Variant::Regular); + + // let mut fallbacks = HashMap::new(); + + // fallbacks.insert("Microsoft YaHei", "C:\\Windows\\Fonts\\msyh.ttc"); // chinese + // fallbacks.insert("Malgun Gothic", "C:\\Windows\\Fonts\\malgun.ttf"); // korean + // fallbacks.insert("Leelawadee UI", "C:\\Windows\\Fonts\\LeelawUI.ttf"); // thai + + // for (name, path) in fallbacks { + // if let Ok(bytes) = std::fs::read(path) { + // fonts + // .font_data + // .insert(name.to_owned(), Arc::from(FontData::from_owned(bytes))); + // + // for family in [FontFamily::Proportional, FontFamily::Monospace] { + // fonts + // .families + // .entry(family) + // .or_default() + // .insert(0, name.to_owned()); + // } + // } + // } + + let property = FontPropertyBuilder::new().family(name).build(); + + if let Some((font, _)) = system_fonts::get(&property) { + fonts + .font_data + .insert(name.to_owned(), Arc::new(FontData::from_owned(font))); + + for family in [FontFamily::Proportional, FontFamily::Monospace] { + fonts + .families + .entry(family) + .or_default() + .insert(0, name.to_owned()); + } + } + + // Tell egui to use these fonts: + ctx.set_fonts(fonts); + } + + pub fn position_bar(&self, ctx: &Context) { + ctx.send_viewport_cmd(ViewportCommand::OuterPosition(Pos2::new( + self.size_rect.top as f32, + self.size_rect.left as f32, + ))); + + ctx.send_viewport_cmd(ViewportCommand::InnerSize(Vec2::new( + self.size_rect.right as f32, + self.size_rect.bottom as f32, + ))); + } + + fn update_monitor_coordinates(&mut self, monitor_size: &komorebi_client::Rect) { + // Store the new monitor coordinates + MONITOR_TOP.store(monitor_size.top, Ordering::SeqCst); + MONITOR_LEFT.store(monitor_size.left, Ordering::SeqCst); + MONITOR_RIGHT.store(monitor_size.right, Ordering::SeqCst); + + // Since the `config.position` is changed on `main.rs` we need to update it here. + // If the user had set up some `start` position, that will be overriden here + // since we have no way to know what was that value since it might have been + // changed on `main.rs`. However if the users use the new configs this won't be + // a problem for them. + if let Some(start) = self.config.position.as_mut().and_then(|p| p.start.as_mut()) { + start.x = monitor_size.left as f32; + start.y = monitor_size.top as f32; + } + } +} +impl eframe::App for Komobar { + // Needed for transparency + fn clear_color(&self, _visuals: &Visuals) -> [f32; 4] { + Rgba::TRANSPARENT.to_array() + } + + fn update(&mut self, ctx: &Context, _frame: &mut eframe::Frame) { + // if self.hwnd.is_none() { + // self.hwnd = process_hwnd(); + // } + + if self.scale_factor != ctx.native_pixels_per_point().unwrap_or(1.0) { + self.scale_factor = ctx.native_pixels_per_point().unwrap_or(1.0); + self.apply_config(ctx, self.monitor_info.clone()); + } + + if let Ok(updated_config) = self.rx_config.try_recv() { + self.config = updated_config; + self.apply_config(ctx, self.monitor_info.clone()); + } + + match self.rx_gui.try_recv() { + Err(error) => match error { + TryRecvError::Empty => {} + TryRecvError::Disconnected => { + tracing::error!( + "failed to receive komorebi notification on gui thread: {error}" + ); + } + }, + Ok(KomorebiEvent::Notification(notification)) => { + let state = ¬ification.state; + let usr_monitor_index = match &self.config.monitor { + MonitorConfigOrIndex::MonitorConfig(monitor_config) => monitor_config.index, + MonitorConfigOrIndex::Index(idx) => *idx, + }; + let monitor_index = state.monitor_usr_idx_map.get(&usr_monitor_index).copied(); + self.monitor_index = monitor_index; + let mut should_apply_config = false; + + {} + + if self.monitor_index.is_none() + || self + .monitor_index + .is_some_and(|idx| idx >= state.monitors.elements().len()) + { + if !self.disabled { + // Monitor for this bar got disconnected lets disable the bar until it + // reconnects + self.disabled = true; + tracing::warn!( + "This bar's monitor got disconnected. The bar will be disabled until it reconnects..." + ); + } + return; + } else { + if self.disabled { + tracing::info!("Found this bar's monitor. The bar will be enabled!"); + + // Restore the bar in case it has been minimized when the monitor + // disconnected + // if let Some(hwnd) = self.hwnd { + // let window = komorebi_client::Window::from(hwnd); + // if window.is_miminized() { + // komorebi_client::WindowsApi::restore_window(hwnd); + // } + // } + + // Reset the current `work_area_offset` so that it gets recalculated and + // properly applied again, since if the monitor has connected for the first + // time it won't have the work_area_offset applied but the bar thinks it + // does. + self.work_area_offset = komorebi_client::Rect::default(); + + should_apply_config = true; + } + self.disabled = false; + } + + if matches!(notification.event, NotificationEvent::Monitor(_)) { + let monitor_index = self.monitor_index.expect("should have a monitor index"); + + let monitor_size = state.monitors.elements()[monitor_index].size; + + self.update_monitor_coordinates(&monitor_size); + + should_apply_config = true; + } + + if self.disabled { + return; + } + + // Check if monitor coordinates/size has changed + if let Some(monitor_index) = self.monitor_index { + let monitor_size = state.monitors.elements()[monitor_index].size; + let top = MONITOR_TOP.load(Ordering::SeqCst); + let left = MONITOR_LEFT.load(Ordering::SeqCst); + let right = MONITOR_RIGHT.load(Ordering::SeqCst); + let rect = komorebi_client::Rect { + top, + left, + bottom: monitor_size.bottom, + right, + }; + if monitor_size != rect { + tracing::info!( + "Monitor coordinates/size has changed, storing new coordinates: {:#?}", + monitor_size + ); + + self.update_monitor_coordinates(&monitor_size); + + should_apply_config = true; + } + } + + if let Some(monitor_info) = &self.monitor_info { + monitor_info.borrow_mut().update( + self.monitor_index, + notification.state, + self.render_config.borrow().show_all_icons, + ); + handle_notification( + ctx, + notification.event, + self.bg_color.clone(), + self.bg_color_with_alpha.clone(), + self.config.transparency_alpha, + self.config.grouping, + self.config.theme.clone(), + self.render_config.clone(), + ); + } + + if should_apply_config { + self.apply_config(ctx, self.monitor_info.clone()); + + // Reposition the Bar + self.position_bar(ctx); + } + } + Ok(KomorebiEvent::Reconnect) => { + if let Some(monitor_index) = self.monitor_index { + if let Err(error) = komorebi_client::send_message( + &SocketMessage::MonitorWorkAreaOffset(monitor_index, self.work_area_offset), + ) { + tracing::error!( + "error applying work area offset to monitor '{}': {}", + monitor_index, + error, + ); + } else { + tracing::info!("work area offset applied to monitor: {}", monitor_index); + } + } + } + } + + if self.disabled { + // The check for disabled is performed above, if we get here and the bar is still + // disabled then we should return without drawing anything. + return; + } + + if !self.applied_theme_on_first_frame { + self.try_apply_theme(ctx); + self.applied_theme_on_first_frame = true; + } + + // Check if egui's Window size is the expected one, if not, update it + if let Some(current_rect) = ctx.input(|i| i.viewport().outer_rect) { + // Get the correct size according to scale factor + let current_rect = komorebi_client::Rect { + left: (current_rect.min.x * self.scale_factor) as i32, + top: (current_rect.min.y * self.scale_factor) as i32, + right: ((current_rect.max.x - current_rect.min.x) * self.scale_factor) as i32, + bottom: ((current_rect.max.y - current_rect.min.y) * self.scale_factor) as i32, + }; + + if self.size_rect != current_rect { + self.position_bar(ctx); + } + } + + let frame = match &self.config.padding { + None => { + if let Some(frame) = &self.config.frame { + Frame::NONE + .inner_margin(Margin::symmetric( + frame.inner_margin.x as i8, + frame.inner_margin.y as i8, + )) + .fill(*self.bg_color_with_alpha.borrow()) + } else { + Frame::NONE + .inner_margin(Margin::same(0)) + .fill(*self.bg_color_with_alpha.borrow()) + } + } + Some(padding) => { + let padding = padding.to_individual(DEFAULT_PADDING); + Frame::NONE + .inner_margin(Margin { + top: padding.top as i8, + bottom: padding.bottom as i8, + left: padding.left as i8, + right: padding.right as i8, + }) + .fill(*self.bg_color_with_alpha.borrow()) + } + }; + + let mut render_config = self.render_config.borrow_mut(); + + let frame = render_config.change_frame_on_bar(frame, &ctx.style()); + + CentralPanel::default().frame(frame).show(ctx, |ui| { + // if let Some(mouse_config) = &self.config.mouse { + // let command = if ui + // .input(|i| i.pointer.button_double_clicked(PointerButton::Primary)) + // { + // tracing::debug!("Input: primary button double clicked"); + // &mouse_config.on_primary_double_click + // } else if ui.input(|i| i.pointer.button_clicked(PointerButton::Secondary)) { + // tracing::debug!("Input: secondary button clicked"); + // &mouse_config.on_secondary_click + // } else if ui.input(|i| i.pointer.button_clicked(PointerButton::Middle)) { + // tracing::debug!("Input: middle button clicked"); + // &mouse_config.on_middle_click + // } else if ui.input(|i| i.pointer.button_clicked(PointerButton::Extra1)) { + // tracing::debug!("Input: extra1 button clicked"); + // &mouse_config.on_extra1_click + // } else if ui.input(|i| i.pointer.button_clicked(PointerButton::Extra2)) { + // tracing::debug!("Input: extra2 button clicked"); + // &mouse_config.on_extra2_click + // } else if self.input_config.act_on_vertical_scroll + // || self.input_config.act_on_horizontal_scroll + // { + // let scroll_delta = ui.input(|input| input.smooth_scroll_delta); + // + // self.input_config.accumulated_scroll_delta += scroll_delta; + // + // if scroll_delta.y != 0.0 && self.input_config.act_on_vertical_scroll { + // // Do not store more than the max threshold + // self.input_config.accumulated_scroll_delta.y = + // self.input_config.accumulated_scroll_delta.y.clamp( + // -self.input_config.vertical_scroll_max_threshold, + // self.input_config.vertical_scroll_max_threshold, + // ); + // + // // When the accumulated scroll passes the threshold, trigger a tick. + // if self.input_config.accumulated_scroll_delta.y.abs() + // >= self.input_config.vertical_scroll_threshold + // { + // let direction_command = + // if self.input_config.accumulated_scroll_delta.y > 0.0 { + // &mouse_config.on_scroll_up + // } else { + // &mouse_config.on_scroll_down + // }; + // + // // Remove one tick's worth of scroll from the accumulator, preserving any excess. + // self.input_config.accumulated_scroll_delta.y -= + // self.input_config.vertical_scroll_threshold + // * self.input_config.accumulated_scroll_delta.y.signum(); + // + // tracing::debug!( + // "Input: vertical scroll ticked. excess: {} | threshold: {}", + // self.input_config.accumulated_scroll_delta.y, + // self.input_config.vertical_scroll_threshold + // ); + // + // direction_command + // } else { + // &None + // } + // } else if scroll_delta.x != 0.0 && self.input_config.act_on_horizontal_scroll { + // // Do not store more than the max threshold + // self.input_config.accumulated_scroll_delta.x = + // self.input_config.accumulated_scroll_delta.x.clamp( + // -self.input_config.horizontal_scroll_max_threshold, + // self.input_config.horizontal_scroll_max_threshold, + // ); + // + // // When the accumulated scroll passes the threshold, trigger a tick. + // if self.input_config.accumulated_scroll_delta.x.abs() + // >= self.input_config.horizontal_scroll_threshold + // { + // let direction_command = + // if self.input_config.accumulated_scroll_delta.x > 0.0 { + // &mouse_config.on_scroll_left + // } else { + // &mouse_config.on_scroll_right + // }; + // + // // Remove one tick's worth of scroll from the accumulator, preserving any excess. + // self.input_config.accumulated_scroll_delta.x -= + // self.input_config.horizontal_scroll_threshold + // * self.input_config.accumulated_scroll_delta.x.signum(); + // + // tracing::debug!( + // "Input: horizontal scroll ticked. excess: {} | threshold: {}", + // self.input_config.accumulated_scroll_delta.x, + // self.input_config.horizontal_scroll_threshold + // ); + // + // direction_command + // } else { + // &None + // } + // } else { + // &None + // } + // } else { + // &None + // }; + // + // if let Some(command) = command { + // command.execute(self.mouse_follows_focus); + // } + // } + + // Apply grouping logic for the bar as a whole + let area_frame = if let Some(frame) = &self.config.frame { + Frame::NONE + .inner_margin(Margin::symmetric(0, frame.inner_margin.y as i8)) + .outer_margin(Margin::same(0)) + } else { + Frame::NONE + .inner_margin(Margin::same(0)) + .outer_margin(Margin::same(0)) + }; + + let available_height = ui.max_rect().max.y; + ctx.style_mut(|style| { + style.spacing.interact_size.y = available_height; + }); + + if !self.left_widgets.is_empty() { + // Left-aligned widgets layout + Area::new(Id::new("left_panel")) + .anchor(Align2::LEFT_CENTER, [0.0, 0.0]) // Align in the left center of the window + .show(ctx, |ui| { + let mut left_area_frame = area_frame; + if let Some(padding) = self + .config + .padding + .as_ref() + .map(|s| s.to_individual(DEFAULT_PADDING)) + { + left_area_frame.inner_margin.left = padding.left as i8; + left_area_frame.inner_margin.top = padding.top as i8; + left_area_frame.inner_margin.bottom = padding.bottom as i8; + } else if let Some(frame) = &self.config.frame { + left_area_frame.inner_margin.left = frame.inner_margin.x as i8; + left_area_frame.inner_margin.top = frame.inner_margin.y as i8; + left_area_frame.inner_margin.bottom = frame.inner_margin.y as i8; + } + + left_area_frame.show(ui, |ui| { + ui.horizontal(|ui| { + let mut render_conf = render_config.clone(); + render_conf.alignment = Some(Alignment::Left); + + render_config.apply_on_alignment(ui, |ui| { + for w in &mut self.left_widgets { + w.render(ctx, ui, &mut render_conf); + } + }); + }); + }); + }); + } + + if !self.right_widgets.is_empty() { + // Right-aligned widgets layout + Area::new(Id::new("right_panel")) + .anchor(Align2::RIGHT_CENTER, [0.0, 0.0]) // Align in the right center of the window + .show(ctx, |ui| { + let mut right_area_frame = area_frame; + if let Some(padding) = self + .config + .padding + .as_ref() + .map(|s| s.to_individual(DEFAULT_PADDING)) + { + right_area_frame.inner_margin.right = padding.right as i8; + right_area_frame.inner_margin.top = padding.top as i8; + right_area_frame.inner_margin.bottom = padding.bottom as i8; + } else if let Some(frame) = &self.config.frame { + right_area_frame.inner_margin.right = frame.inner_margin.x as i8; + right_area_frame.inner_margin.top = frame.inner_margin.y as i8; + right_area_frame.inner_margin.bottom = frame.inner_margin.y as i8; + } + + right_area_frame.show(ui, |ui| { + let initial_size = Vec2 { + x: ui.available_size_before_wrap().x, + y: ui.spacing().interact_size.y, + }; + ui.allocate_ui_with_layout( + initial_size, + Layout::right_to_left(Align::Center), + |ui| { + let mut render_conf = render_config.clone(); + render_conf.alignment = Some(Alignment::Right); + + render_config.apply_on_alignment(ui, |ui| { + for w in &mut self.right_widgets { + w.render(ctx, ui, &mut render_conf); + } + }); + }, + ); + }); + }); + } + + if !self.center_widgets.is_empty() { + // Floating center widgets + Area::new(Id::new("center_panel")) + .anchor(Align2::CENTER_CENTER, [0.0, 0.0]) // Align in the center of the window + .show(ctx, |ui| { + let mut center_area_frame = area_frame; + if let Some(padding) = self + .config + .padding + .as_ref() + .map(|s| s.to_individual(DEFAULT_PADDING)) + { + center_area_frame.inner_margin.top = padding.top as i8; + center_area_frame.inner_margin.bottom = padding.bottom as i8; + } else if let Some(frame) = &self.config.frame { + center_area_frame.inner_margin.top = frame.inner_margin.y as i8; + center_area_frame.inner_margin.bottom = frame.inner_margin.y as i8; + } + + center_area_frame.show(ui, |ui| { + ui.horizontal(|ui| { + let mut render_conf = render_config.clone(); + render_conf.alignment = Some(Alignment::Center); + + render_config.apply_on_alignment(ui, |ui| { + for w in &mut self.center_widgets { + w.render(ctx, ui, &mut render_conf); + } + }); + }); + }); + }); + } + }); + } +} + +#[derive(Copy, Clone)] +pub enum Alignment { + Left, + Center, + Right, +} + +#[allow(clippy::too_many_arguments)] +fn handle_notification( + ctx: &Context, + event: komorebi_client::NotificationEvent, + bg_color: Rc>, + bg_color_with_alpha: Rc>, + transparency_alpha: Option, + grouping: Option, + default_theme: Option, + render_config: Rc>, +) { + if let NotificationEvent::Socket(message) = event { + match message { + SocketMessage::ReloadStaticConfiguration(path) => { + if let Ok(config) = komorebi_client::StaticConfig::read(&path) { + if let Some(theme) = config.theme { + apply_theme( + ctx, + KomobarTheme::from(theme), + bg_color.clone(), + bg_color_with_alpha.clone(), + transparency_alpha, + grouping, + render_config, + ); + tracing::info!("applied theme from updated komorebi.json"); + } else if let Some(default_theme) = default_theme { + apply_theme( + ctx, + default_theme, + bg_color.clone(), + bg_color_with_alpha.clone(), + transparency_alpha, + grouping, + render_config, + ); + tracing::info!( + "removed theme from updated komorebi.json and applied default theme" + ); + } else { + tracing::warn!( + "theme was removed from updated komorebi.json but there was no default theme to apply" + ); + } + } + } + SocketMessage::Theme(theme) => { + apply_theme( + ctx, + KomobarTheme::from(*theme), + bg_color, + bg_color_with_alpha.clone(), + transparency_alpha, + grouping, + render_config, + ); + tracing::info!("applied theme from komorebi socket message"); + } + _ => {} + } + } +} diff --git a/komorebi-bar/src/config.rs b/komorebi-bar/src/config.rs new file mode 100644 index 00000000..33ae0103 --- /dev/null +++ b/komorebi-bar/src/config.rs @@ -0,0 +1,699 @@ +use crate::DEFAULT_PADDING; +// use crate::bar::exec_powershell; +use crate::render::Grouping; +use crate::widgets::widget::WidgetConfig; +use color_eyre::eyre; +use eframe::egui::Pos2; +use eframe::egui::TextBuffer; +use eframe::egui::Vec2; +use komorebi_client::KomorebiTheme; +use komorebi_client::Rect; +use serde::Deserialize; +use serde::Serialize; +use std::collections::HashMap; +use std::path::PathBuf; + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// The `komorebi.bar.json` configuration file reference for `v0.1.39` +pub struct KomobarConfig { + /// Bar height (default: 50) + pub height: Option, + /// Bar padding. Use one value for all sides or use a grouped padding for horizontal and/or + /// vertical definition which can each take a single value for a symmetric padding or two + /// values for each side, i.e.: + /// ```json + /// "padding": { + /// "horizontal": 10 + /// } + /// ``` + /// or: + /// ```json + /// "padding": { + /// "horizontal": [left, right] + /// } + /// ``` + /// You can also set individual padding on each side like this: + /// ```json + /// "padding": { + /// "top": 10, + /// "bottom": 10, + /// "left": 10, + /// "right": 10, + /// } + /// ``` + /// By default, padding is set to 10 on all sides. + pub padding: Option, + /// Bar margin. Use one value for all sides or use a grouped margin for horizontal and/or + /// vertical definition which can each take a single value for a symmetric margin or two + /// values for each side, i.e.: + /// ```json + /// "margin": { + /// "horizontal": 10 + /// } + /// ``` + /// or: + /// ```json + /// "margin": { + /// "vertical": [top, bottom] + /// } + /// ``` + /// You can also set individual margin on each side like this: + /// ```json + /// "margin": { + /// "top": 10, + /// "bottom": 10, + /// "left": 10, + /// "right": 10, + /// } + /// ``` + /// By default, margin is set to 0 on all sides. + pub margin: Option, + /// Bar positioning options + #[serde(alias = "viewport")] + pub position: Option, + /// Frame options (see: https://docs.rs/egui/latest/egui/containers/frame/struct.Frame.html) + pub frame: Option, + /// The monitor index or the full monitor options + pub monitor: MonitorConfigOrIndex, + /// Font family + pub font_family: Option, + /// Font size (default: 12.5) + pub font_size: Option, + /// Scale of the icons relative to the font_size [[1.0-2.0]]. (default: 1.4) + pub icon_scale: Option, + /// Max label width before text truncation (default: 400.0) + pub max_label_width: Option, + /// Theme + pub theme: Option, + /// Alpha value for the color transparency [[0-255]] (default: 200) + pub transparency_alpha: Option, + /// Spacing between widgets (default: 10.0) + pub widget_spacing: Option, + /// Visual grouping for widgets + pub grouping: Option, + /// Options for mouse interaction on the bar + // pub mouse: Option, + /// Left side widgets (ordered left-to-right) + pub left_widgets: Vec, + /// Center widgets (ordered left-to-right) + pub center_widgets: Option>, + /// Right side widgets (ordered left-to-right) + pub right_widgets: Vec, +} + +impl KomobarConfig { + pub fn aliases(raw: &str) { + let mut map = HashMap::new(); + map.insert("position", ["viewport"]); + map.insert("end", ["inner_frame"]); + + let mut display = false; + + for aliases in map.values() { + for a in aliases { + if raw.contains(a) { + display = true; + } + } + } + + if display { + println!( + "\nYour bar configuration file contains some options that have been renamed or deprecated:\n" + ); + for (canonical, aliases) in map { + for alias in aliases { + if raw.contains(alias) { + println!(r#""{alias}" is now "{canonical}""#); + } + } + } + } + } + + pub fn show_all_icons_on_komorebi_workspace(widgets: &[WidgetConfig]) -> bool { + widgets + .iter() + .any(|w| matches!(w, WidgetConfig::Komorebi(config) if config.workspaces.is_some_and(|w| w.enable && w.display.is_some_and(|s| matches!(s, + WorkspacesDisplayFormat::AllIcons + | WorkspacesDisplayFormat::AllIconsAndText + | WorkspacesDisplayFormat::AllIconsAndTextOnSelected))))) + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct PositionConfig { + /// The desired starting position of the bar (0,0 = top left of the screen) + #[serde(alias = "position")] + pub start: Option, + /// The desired size of the bar from the starting position (usually monitor width x desired height) + #[serde(alias = "inner_size")] + pub end: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct FrameConfig { + /// Margin inside the painted frame + pub inner_margin: Position, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[serde(untagged)] +pub enum MonitorConfigOrIndex { + /// The monitor index where you want the bar to show + Index(usize), + /// The full monitor options with the index and an optional work_area_offset + MonitorConfig(MonitorConfig), +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct MonitorConfig { + /// Komorebi monitor index of the monitor on which to render the bar + pub index: usize, + /// Automatically apply a work area offset for this monitor to accommodate the bar + pub work_area_offset: Option, +} + +pub type Padding = SpacingKind; +pub type Margin = SpacingKind; + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[serde(untagged)] +// WARNING: To any developer messing with this code in the future: The order here matters! +// `Grouped` needs to come last, otherwise serde might mistaken an `IndividualSpacingConfig` for a +// `GroupedSpacingConfig` with both `vertical` and `horizontal` set to `None` ignoring the +// individual values. +pub enum SpacingKind { + All(f32), + Individual(IndividualSpacingConfig), + Grouped(GroupedSpacingConfig), +} + +impl SpacingKind { + pub fn to_individual(&self, default: f32) -> IndividualSpacingConfig { + match self { + SpacingKind::All(m) => IndividualSpacingConfig::all(*m), + SpacingKind::Grouped(grouped_spacing_config) => { + let vm = grouped_spacing_config.vertical.as_ref().map_or( + IndividualSpacingConfig::vertical(default), + |vm| match vm { + GroupedSpacingOptions::Symmetrical(m) => { + IndividualSpacingConfig::vertical(*m) + } + GroupedSpacingOptions::Split(tm, bm) => { + IndividualSpacingConfig::vertical(*tm).bottom(*bm) + } + }, + ); + let hm = grouped_spacing_config.horizontal.as_ref().map_or( + IndividualSpacingConfig::horizontal(default), + |hm| match hm { + GroupedSpacingOptions::Symmetrical(m) => { + IndividualSpacingConfig::horizontal(*m) + } + GroupedSpacingOptions::Split(lm, rm) => { + IndividualSpacingConfig::horizontal(*lm).right(*rm) + } + }, + ); + IndividualSpacingConfig { + top: vm.top, + bottom: vm.bottom, + left: hm.left, + right: hm.right, + } + } + SpacingKind::Individual(m) => *m, + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct GroupedSpacingConfig { + pub vertical: Option, + pub horizontal: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[serde(untagged)] +pub enum GroupedSpacingOptions { + Symmetrical(f32), + Split(f32, f32), +} + +#[derive(Copy, Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct IndividualSpacingConfig { + pub top: f32, + pub bottom: f32, + pub left: f32, + pub right: f32, +} + +#[allow(dead_code)] +impl IndividualSpacingConfig { + pub const ZERO: Self = IndividualSpacingConfig { + top: 0.0, + bottom: 0.0, + left: 0.0, + right: 0.0, + }; + + pub fn all(value: f32) -> Self { + IndividualSpacingConfig { + top: value, + bottom: value, + left: value, + right: value, + } + } + + pub fn horizontal(value: f32) -> Self { + IndividualSpacingConfig { + top: 0.0, + bottom: 0.0, + left: value, + right: value, + } + } + + pub fn vertical(value: f32) -> Self { + IndividualSpacingConfig { + top: value, + bottom: value, + left: 0.0, + right: 0.0, + } + } + + pub fn top(self, value: f32) -> Self { + IndividualSpacingConfig { top: value, ..self } + } + + pub fn bottom(self, value: f32) -> Self { + IndividualSpacingConfig { + bottom: value, + ..self + } + } + + pub fn left(self, value: f32) -> Self { + IndividualSpacingConfig { + left: value, + ..self + } + } + + pub fn right(self, value: f32) -> Self { + IndividualSpacingConfig { + right: value, + ..self + } + } +} + +pub fn get_individual_spacing( + default: f32, + spacing: &Option, +) -> IndividualSpacingConfig { + spacing + .as_ref() + .map_or(IndividualSpacingConfig::all(default), |s| { + s.to_individual(default) + }) +} + +// #[derive(Clone, Debug, Serialize, Deserialize)] +// #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +// #[serde(untagged)] +// pub enum MouseMessage { +// /// Send a message to the komorebi client. +// /// By default, a batch of messages are sent in the following order: +// /// FocusMonitorAtCursor => +// /// MouseFollowsFocus(false) => +// /// {message} => +// /// MouseFollowsFocus({original.value}) +// /// +// /// Example: +// /// ```json +// /// "on_extra2_click": { +// /// "message": { +// /// "type": "NewWorkspace" +// /// } +// /// }, +// /// ``` +// /// or: +// /// ```json +// /// "on_middle_click": { +// /// "focus_monitor_at_cursor": false, +// /// "ignore_mouse_follows_focus": false, +// /// "message": { +// /// "type": "TogglePause" +// /// } +// /// } +// /// ``` +// /// or: +// /// ```json +// /// "on_scroll_up": { +// /// "message": { +// /// "type": "CycleFocusWorkspace", +// /// "content": "Previous" +// /// } +// /// } +// /// ``` +// Komorebi(KomorebiMouseMessage), +// /// Execute a custom command. +// /// CMD (%variable%), Bash ($variable) and PowerShell ($Env:variable) variables will be resolved. +// /// Example: `komorebic toggle-pause` +// Command(String), +// } +// +// #[derive(Clone, Debug, Serialize, Deserialize)] +// #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +// pub struct KomorebiMouseMessage { +// /// Send the FocusMonitorAtCursor message (default:true) +// pub focus_monitor_at_cursor: Option, +// /// Wrap the {message} with a MouseFollowsFocus(false) and MouseFollowsFocus({original.value}) message (default:true) +// pub ignore_mouse_follows_focus: Option, +// /// The message to send to the komorebi client +// pub message: komorebi_client::SocketMessage, +// } +// +// #[derive(Clone, Debug, Serialize, Deserialize)] +// #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +// pub struct MouseConfig { +// /// Command to send on primary/left double button click +// pub on_primary_double_click: Option, +// /// Command to send on secondary/right button click +// pub on_secondary_click: Option, +// /// Command to send on middle button click +// pub on_middle_click: Option, +// /// Command to send on extra1/back button click +// pub on_extra1_click: Option, +// /// Command to send on extra2/forward button click +// pub on_extra2_click: Option, +// +// /// Defines how many points a user needs to scroll vertically to make a "tick" on a mouse/touchpad/touchscreen (default: 30) +// pub vertical_scroll_threshold: Option, +// /// Command to send on scrolling up (every tick) +// pub on_scroll_up: Option, +// /// Command to send on scrolling down (every tick) +// pub on_scroll_down: Option, +// +// /// Defines how many points a user needs to scroll horizontally to make a "tick" on a mouse/touchpad/touchscreen (default: 30) +// pub horizontal_scroll_threshold: Option, +// /// Command to send on scrolling left (every tick) +// pub on_scroll_left: Option, +// /// Command to send on scrolling right (every tick) +// pub on_scroll_right: Option, +// } +// +// impl MouseConfig { +// pub fn has_command(&self) -> bool { +// [ +// &self.on_primary_double_click, +// &self.on_secondary_click, +// &self.on_middle_click, +// &self.on_extra1_click, +// &self.on_extra2_click, +// &self.on_scroll_up, +// &self.on_scroll_down, +// &self.on_scroll_left, +// &self.on_scroll_right, +// ] +// .iter() +// .any(|opt| matches!(opt, Some(MouseMessage::Command(_)))) +// } +// } +// +// impl MouseMessage { +// pub fn execute(&self, mouse_follows_focus: bool) { +// match self { +// MouseMessage::Komorebi(config) => { +// let mut messages = Vec::new(); +// +// if config.focus_monitor_at_cursor.unwrap_or(true) { +// messages.push(SocketMessage::FocusMonitorAtCursor); +// } +// +// if config.ignore_mouse_follows_focus.unwrap_or(true) { +// messages.push(SocketMessage::MouseFollowsFocus(false)); +// messages.push(config.message.clone()); +// messages.push(SocketMessage::MouseFollowsFocus(mouse_follows_focus)); +// } else { +// messages.push(config.message.clone()); +// } +// +// tracing::debug!("Sending messages: {messages:?}"); +// +// if komorebi_client::send_batch(messages).is_err() { +// tracing::error!("could not send commands"); +// } +// } +// MouseMessage::Command(cmd) => { +// tracing::debug!("Executing command: {}", cmd); +// +// let cmd_no_env = cmd.replace_env(); +// +// if exec_powershell(cmd_no_env.to_str().expect("Invalid command")).is_err() { +// tracing::error!("Failed to execute '{}'", cmd); +// } +// } +// }; +// } +// } + +impl KomobarConfig { + pub fn read(path: &PathBuf) -> eyre::Result { + let content = std::fs::read_to_string(path)?; + let mut value: Self = match path.extension().unwrap().to_string_lossy().as_str() { + "json" => serde_json::from_str(&content)?, + _ => panic!("unsupported format"), + }; + + if value.frame.is_none() { + value.frame = Some(FrameConfig { + inner_margin: Position { + x: DEFAULT_PADDING, + y: DEFAULT_PADDING, + }, + }); + } + + Ok(value) + } +} + +#[derive(Copy, Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct Position { + /// X coordinate + pub x: f32, + /// Y coordinate + pub y: f32, +} + +impl From for Vec2 { + fn from(value: Position) -> Self { + Self { + x: value.x, + y: value.y, + } + } +} + +impl From for Pos2 { + fn from(value: Position) -> Self { + Self { + x: value.x, + y: value.y, + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[serde(tag = "palette")] +pub enum KomobarTheme { + /// A theme from catppuccin-egui + Catppuccin { + /// Name of the Catppuccin theme (theme previews: https://github.com/catppuccin/catppuccin) + name: komorebi_themes::Catppuccin, + accent: Option, + auto_select_fill: Option, + auto_select_text: 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, + accent: Option, + auto_select_fill: Option, + auto_select_text: Option, + }, + /// A custom Base16 theme + Custom { + /// Colours of the custom Base16 theme palette + colours: Box, + accent: Option, + auto_select_fill: Option, + auto_select_text: Option, + }, +} + +impl From for KomobarTheme { + fn from(value: KomorebiTheme) -> Self { + match value { + KomorebiTheme::Catppuccin { + name, bar_accent, .. + } => Self::Catppuccin { + name, + accent: bar_accent, + auto_select_fill: None, + auto_select_text: None, + }, + KomorebiTheme::Base16 { + name, bar_accent, .. + } => Self::Base16 { + name, + accent: bar_accent, + auto_select_fill: None, + auto_select_text: None, + }, + KomorebiTheme::Custom { + colours, + bar_accent, + .. + } => Self::Custom { + colours, + accent: bar_accent, + auto_select_fill: None, + auto_select_text: None, + }, + } + } +} + +#[derive(Copy, Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub enum LabelPrefix { + /// Show no prefix + None, + /// Show an icon + Icon, + /// Show text + Text, + /// Show an icon and text + IconAndText, +} + +#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub enum DisplayFormat { + /// Show only icon + Icon, + /// Show only text + Text, + /// Show an icon and text for the selected element, and text on the rest + TextAndIconOnSelected, + /// Show both icon and text + IconAndText, + /// Show an icon and text for the selected element, and icons on the rest + IconAndTextOnSelected, +} + +macro_rules! extend_enum { + ($existing_enum:ident, $new_enum:ident, { $($(#[$meta:meta])* $variant:ident),* $(,)? }) => { + #[derive(Copy, Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq)] + #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] + pub enum $new_enum { + // Add new variants + $( + $(#[$meta])* + $variant, + )* + // Include a variant that wraps the existing enum and flatten it when deserializing + #[serde(untagged)] + Existing($existing_enum), + } + + // Implement From for the existing enum + impl From<$existing_enum> for $new_enum { + fn from(value: $existing_enum) -> Self { + $new_enum::Existing(value) + } + } + }; +} + +extend_enum!(DisplayFormat, WorkspacesDisplayFormat, { + /// Show all icons only + AllIcons, + /// Show both all icons and text + AllIconsAndText, + /// Show all icons and text for the selected element, and all icons on the rest + AllIconsAndTextOnSelected, +}); + +#[cfg(test)] +mod tests { + use serde::Deserialize; + use serde::Serialize; + use serde_json::json; + + #[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq)] + #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] + pub enum OriginalDisplayFormat { + /// Show None Of The Things + NoneOfTheThings, + } + + extend_enum!(OriginalDisplayFormat, ExtendedDisplayFormat, { + /// Show Some Of The Things + SomeOfTheThings, + }); + + #[derive(serde::Deserialize)] + struct ExampleConfig { + #[allow(unused)] + format: ExtendedDisplayFormat, + } + + #[test] + pub fn extend_new_variant() { + let raw = json!({ + "format": "SomeOfTheThings", + }) + .to_string(); + + assert!(serde_json::from_str::(&raw).is_ok()) + } + + #[test] + pub fn extend_existing_variant() { + let raw = json!({ + "format": "NoneOfTheThings", + }) + .to_string(); + + assert!(serde_json::from_str::(&raw).is_ok()) + } + + #[test] + pub fn extend_invalid_variant() { + let raw = json!({ + "format": "ALLOFTHETHINGS", + }) + .to_string(); + + assert!(serde_json::from_str::(&raw).is_err()) + } +} diff --git a/komorebi-bar/src/main.rs b/komorebi-bar/src/main.rs new file mode 100644 index 00000000..29a07c31 --- /dev/null +++ b/komorebi-bar/src/main.rs @@ -0,0 +1,373 @@ +mod bar; +mod config; +mod render; +mod selected_frame; +mod ui; +mod widgets; + +use crate::bar::Komobar; +use crate::config::KomobarConfig; +use crate::config::Position; +use crate::config::PositionConfig; +use clap::Parser; +use color_eyre::eyre; +use config::MonitorConfigOrIndex; +use eframe::egui::ViewportBuilder; +use font_loader::system_fonts; +use hotwatch::EventKind; +use hotwatch::Hotwatch; +use komorebi_client::PathExt; +use komorebi_client::SocketMessage; +use komorebi_client::SubscribeOptions; +use komorebi_client::replace_env_in_path; +use std::io::BufReader; +use std::io::Read; +use std::path::PathBuf; +use std::sync::atomic::AtomicI32; +use std::sync::atomic::AtomicU32; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering; +use std::time::Duration; +use tracing_subscriber::EnvFilter; + +pub static MAX_LABEL_WIDTH: AtomicI32 = AtomicI32::new(400); +pub static MONITOR_LEFT: AtomicI32 = AtomicI32::new(0); +pub static MONITOR_TOP: AtomicI32 = AtomicI32::new(0); +pub static MONITOR_RIGHT: AtomicI32 = AtomicI32::new(0); +pub static MONITOR_INDEX: AtomicUsize = AtomicUsize::new(0); +pub static BAR_HEIGHT: f32 = 50.0; +pub static DEFAULT_PADDING: f32 = 10.0; + +pub static AUTO_SELECT_FILL_COLOUR: AtomicU32 = AtomicU32::new(0); +pub static AUTO_SELECT_TEXT_COLOUR: AtomicU32 = AtomicU32::new(0); + +#[derive(Parser)] +#[clap(author, about, version)] +struct Opts { + /// Print the JSON schema of the configuration file and exit + #[clap(long)] + schema: bool, + /// Print a list of fonts available on this system and exit + #[clap(long)] + fonts: bool, + /// Path to a JSON or YAML configuration file + #[clap(short, long)] + #[clap(value_parser = replace_env_in_path)] + config: Option, + /// Write an example komorebi.bar.json to disk + #[clap(long)] + quickstart: bool, + /// Print a list of aliases that can be renamed to canonical variants + #[clap(long)] + #[clap(hide = true)] + aliases: bool, +} + +pub enum KomorebiEvent { + Notification(komorebi_client::Notification), + Reconnect, +} + +fn main() -> eyre::Result<()> { + let opts: Opts = Opts::parse(); + + #[cfg(feature = "schemars")] + if opts.schema { + let settings = schemars::r#gen::SchemaSettings::default().with(|s| { + s.option_nullable = false; + s.option_add_null_type = false; + s.inline_subschemas = true; + }); + + let generator = settings.into_generator(); + let socket_message = generator.into_root_schema_for::(); + let schema = serde_json::to_string_pretty(&socket_message)?; + + println!("{schema}"); + std::process::exit(0); + } + + if opts.fonts { + for font in system_fonts::query_all() { + println!("{font}"); + } + + std::process::exit(0); + } + + if std::env::var("RUST_LIB_BACKTRACE").is_err() { + unsafe { + std::env::set_var("RUST_LIB_BACKTRACE", "1"); + } + } + + color_eyre::install()?; + + if std::env::var("RUST_LOG").is_err() { + unsafe { + std::env::set_var("RUST_LOG", "info"); + } + } + + tracing::subscriber::set_global_default( + tracing_subscriber::fmt::Subscriber::builder() + .with_env_filter(EnvFilter::from_default_env()) + .finish(), + )?; + + let home_dir: PathBuf = std::env::var("KOMOREBI_CONFIG_HOME").map_or_else( + |_| { + dirs::home_dir() + .expect("there is no home directory") + .join(".config") + .join("komorebi") + }, + |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 + }, + ); + + if opts.quickstart { + let komorebi_bar_json = include_str!("../../docs/komorebi.bar.example.json").to_string(); + std::fs::write(home_dir.join("komorebi.bar.json"), komorebi_bar_json)?; + println!( + "Example komorebi.bar.json file written to {}", + home_dir.display() + ); + + std::process::exit(0); + } + + let default_config_path = home_dir.join("komorebi.bar.json"); + + let config_path = opts.config.or_else(|| { + default_config_path + .is_file() + .then_some(default_config_path.clone()) + }); + + let mut config = match config_path { + None => { + let komorebi_bar_json = + include_str!("../../docs/komorebi.bar.example.json").to_string(); + + std::fs::write(&default_config_path, komorebi_bar_json)?; + tracing::info!( + "created example configuration file: {}", + default_config_path.display() + ); + + KomobarConfig::read(&default_config_path)? + } + Some(ref config) => { + if !opts.aliases { + tracing::info!("found configuration file: {}", config.display()); + } + + KomobarConfig::read(config)? + } + }; + + let config_path = config_path.unwrap_or(default_config_path); + + if opts.aliases { + KomobarConfig::aliases(&std::fs::read_to_string(&config_path)?); + std::process::exit(0); + } + + let state = serde_json::from_str::(&komorebi_client::send_query( + &SocketMessage::State, + )?)?; + + let (usr_monitor_index, work_area_offset) = match &config.monitor { + MonitorConfigOrIndex::MonitorConfig(monitor_config) => { + (monitor_config.index, monitor_config.work_area_offset) + } + MonitorConfigOrIndex::Index(idx) => (*idx, None), + }; + let monitor_index = state + .monitor_usr_idx_map + .get(&usr_monitor_index) + .map_or(usr_monitor_index, |i| *i); + + MONITOR_RIGHT.store( + state.monitors.elements()[monitor_index].size.right, + Ordering::SeqCst, + ); + + MONITOR_TOP.store( + state.monitors.elements()[monitor_index].size.top, + Ordering::SeqCst, + ); + + MONITOR_LEFT.store( + state.monitors.elements()[monitor_index].size.left, + Ordering::SeqCst, + ); + + MONITOR_INDEX.store(monitor_index, Ordering::SeqCst); + + match config.position { + None => { + config.position = Some(PositionConfig { + start: Some(Position { + x: state.monitors.elements()[monitor_index].size.left as f32, + y: state.monitors.elements()[monitor_index].size.top as f32, + }), + end: Some(Position { + x: state.monitors.elements()[monitor_index].size.right as f32, + y: 50.0, + }), + }) + } + Some(ref mut position) => { + if position.start.is_none() { + position.start = Some(Position { + x: state.monitors.elements()[monitor_index].size.left as f32, + y: state.monitors.elements()[monitor_index].size.top as f32, + }); + } + + if position.end.is_none() { + position.end = Some(Position { + x: state.monitors.elements()[monitor_index].size.right as f32, + y: 50.0, + }) + } + } + } + + let viewport_builder = ViewportBuilder::default() + .with_decorations(false) + .with_transparent(true) + .with_taskbar(false); + + let native_options = eframe::NativeOptions { + viewport: viewport_builder, + ..Default::default() + }; + + if let Some(rect) = &work_area_offset { + komorebi_client::send_message(&SocketMessage::MonitorWorkAreaOffset(monitor_index, *rect))?; + tracing::info!("work area offset applied to monitor: {}", monitor_index); + } + + let (tx_gui, rx_gui) = crossbeam_channel::unbounded(); + let (tx_config, rx_config) = crossbeam_channel::unbounded(); + + let mut hotwatch = Hotwatch::new()?; + let config_path_cl = config_path.clone(); + + hotwatch.watch(config_path, move |event| match event.kind { + EventKind::Modify(_) | EventKind::Remove(_) => match KomobarConfig::read(&config_path_cl) { + Ok(updated) => { + tracing::info!("configuration file updated: {}", config_path_cl.display()); + + if let Err(error) = tx_config.send(updated) { + tracing::error!("could not send configuration update to gui: {error}") + } + } + Err(error) => { + tracing::error!("{error}"); + } + }, + _ => {} + })?; + + tracing::info!("watching configuration file for changes"); + + eframe::run_native( + "komorebi-bar", + native_options, + Box::new(|cc| { + let ctx_repainter = cc.egui_ctx.clone(); + std::thread::spawn(move || loop { + std::thread::sleep(Duration::from_secs(1)); + ctx_repainter.request_repaint(); + }); + + let ctx_komorebi = cc.egui_ctx.clone(); + std::thread::spawn(move || { + let subscriber_name = format!("komorebi-bar-{}", random_word::get(random_word::Lang::En)); + + let listener = komorebi_client::subscribe_with_options(&subscriber_name, SubscribeOptions { + filter_state_changes: true, + }) + .expect("could not subscribe to komorebi notifications"); + + tracing::info!("subscribed to komorebi notifications: \"{}\"", subscriber_name); + + for client in listener.incoming() { + match client { + Ok(subscription) => { + let mut buffer = Vec::new(); + let mut reader = BufReader::new(subscription); + + // this is when we know a shutdown has been sent + if matches!(reader.read_to_end(&mut buffer), Ok(0)) { + tracing::info!("disconnected from komorebi"); + + // keep trying to reconnect to komorebi + while komorebi_client::send_message( + &SocketMessage::AddSubscriberSocket(subscriber_name.clone()), + ) + .is_err() + { + std::thread::sleep(Duration::from_secs(1)); + } + + tracing::info!("reconnected to komorebi"); + + if let Err(error) = tx_gui.send(KomorebiEvent::Reconnect) { + tracing::error!("could not send komorebi reconnect event to gui thread: {error}") + } + + ctx_komorebi.request_repaint(); + continue; + } + + match String::from_utf8(buffer) { + Ok(notification_string) => { + match serde_json::from_str::( + ¬ification_string, + ) { + Ok(notification) => { + tracing::debug!("received notification from komorebi"); + + if let Err(error) = tx_gui.send(KomorebiEvent::Notification(notification)) { + tracing::error!("could not send komorebi notification update to gui thread: {error}") + } + + ctx_komorebi.request_repaint(); + } + Err(error) => { + tracing::error!("could not deserialize komorebi notification: {error}"); + } + } + } + Err(error) => { + tracing::error!( + "komorebi notification string was invalid utf8: {error}" + ) + } + } + } + Err(error) => { + tracing::error!("{error}"); + } + } + } + }); + + Ok(Box::new(Komobar::new(cc, rx_gui, rx_config, config))) + }), + ) + .map_err(|error| color_eyre::eyre::Error::msg(error.to_string())) +} diff --git a/komorebi-bar/src/render.rs b/komorebi-bar/src/render.rs new file mode 100644 index 00000000..88b43234 --- /dev/null +++ b/komorebi-bar/src/render.rs @@ -0,0 +1,429 @@ +use crate::AUTO_SELECT_FILL_COLOUR; +use crate::AUTO_SELECT_TEXT_COLOUR; +use crate::bar::Alignment; +use crate::config::KomobarConfig; +use crate::config::MonitorConfigOrIndex; +use eframe::egui::Color32; +use eframe::egui::Context; +use eframe::egui::CornerRadius; +use eframe::egui::FontId; +use eframe::egui::Frame; +use eframe::egui::InnerResponse; +use eframe::egui::Margin; +use eframe::egui::Shadow; +use eframe::egui::TextStyle; +use eframe::egui::Ui; +use komorebi_client::Colour; +use komorebi_client::Rgb; +use serde::Deserialize; +use serde::Serialize; +use std::num::NonZeroU32; +use std::sync::Arc; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering; + +static SHOW_KOMOREBI_LAYOUT_OPTIONS: AtomicUsize = AtomicUsize::new(0); + +#[derive(Copy, Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[serde(tag = "kind")] +pub enum Grouping { + /// No grouping is applied + None, + /// Widgets are grouped as a whole + Bar(GroupingConfig), + /// Widgets are grouped by alignment + Alignment(GroupingConfig), + /// Widgets are grouped individually + Widget(GroupingConfig), +} + +#[derive(Clone)] +pub struct RenderConfig { + /// Komorebi monitor index of the monitor on which to render the bar + pub monitor_idx: usize, + /// Spacing between widgets + pub spacing: f32, + /// Sets how widgets are grouped + pub grouping: Grouping, + /// Background color + pub background_color: Color32, + /// Alignment of the widgets + pub alignment: Option, + /// Add more inner margin when adding a widget group + pub more_inner_margin: bool, + /// Set to true after the first time the apply_on_widget was called on an alignment + pub applied_on_widget: bool, + /// FontId for text + pub text_font_id: FontId, + /// FontId for icon (based on scaling the text font id) + pub icon_font_id: FontId, + /// Show all icons on the workspace section of the Komorebi widget + pub show_all_icons: bool, + /// Background color of the selected frame + pub auto_select_fill: Option, + /// Text color of the selected frame + pub auto_select_text: Option, +} + +pub trait RenderExt { + fn new_renderconfig( + &self, + ctx: &Context, + background_color: Color32, + icon_scale: Option, + ) -> RenderConfig; +} + +impl RenderExt for &KomobarConfig { + fn new_renderconfig( + &self, + ctx: &Context, + background_color: Color32, + icon_scale: Option, + ) -> RenderConfig { + let text_font_id = ctx + .style() + .text_styles + .get(&TextStyle::Body) + .cloned() + .unwrap_or_else(FontId::default); + + let mut icon_font_id = text_font_id.clone(); + icon_font_id.size *= icon_scale.unwrap_or(1.4).clamp(1.0, 2.0); + + let monitor_idx = match &self.monitor { + MonitorConfigOrIndex::MonitorConfig(monitor_config) => monitor_config.index, + MonitorConfigOrIndex::Index(idx) => *idx, + }; + + // check if any of the alignments have a komorebi widget with the workspace set to show all icons + let show_all_icons = + KomobarConfig::show_all_icons_on_komorebi_workspace(&self.left_widgets) + || self + .center_widgets + .as_ref() + .is_some_and(|list| KomobarConfig::show_all_icons_on_komorebi_workspace(list)) + || KomobarConfig::show_all_icons_on_komorebi_workspace(&self.right_widgets); + + RenderConfig { + monitor_idx, + spacing: self.widget_spacing.unwrap_or(10.0), + grouping: self.grouping.unwrap_or(Grouping::None), + background_color, + alignment: None, + more_inner_margin: false, + applied_on_widget: false, + text_font_id, + icon_font_id, + show_all_icons, + auto_select_fill: NonZeroU32::new(AUTO_SELECT_FILL_COLOUR.load(Ordering::SeqCst)) + .map(|c| Colour::Rgb(Rgb::from(c.get())).into()), + auto_select_text: NonZeroU32::new(AUTO_SELECT_TEXT_COLOUR.load(Ordering::SeqCst)) + .map(|c| Colour::Rgb(Rgb::from(c.get())).into()), + } + } +} + +impl RenderConfig { + pub fn load_show_komorebi_layout_options() -> bool { + SHOW_KOMOREBI_LAYOUT_OPTIONS.load(Ordering::SeqCst) != 0 + } + + pub fn store_show_komorebi_layout_options(show: bool) { + SHOW_KOMOREBI_LAYOUT_OPTIONS.store(show as usize, Ordering::SeqCst); + } + + pub fn new() -> Self { + Self { + monitor_idx: 0, + spacing: 0.0, + grouping: Grouping::None, + background_color: Color32::BLACK, + alignment: None, + more_inner_margin: false, + applied_on_widget: false, + text_font_id: FontId::default(), + icon_font_id: FontId::default(), + show_all_icons: false, + auto_select_fill: None, + auto_select_text: None, + } + } + + pub fn change_frame_on_bar( + &mut self, + frame: Frame, + ui_style: &Arc, + ) -> Frame { + self.alignment = None; + + if let Grouping::Bar(config) = self.grouping { + return self.define_group_frame( + //TODO: this outer margin can be a config + Some(Margin { + left: 10, + right: 10, + top: 6, + bottom: 6, + }), + config, + ui_style, + ); + } + + frame + } + + pub fn apply_on_alignment( + &mut self, + ui: &mut Ui, + add_contents: impl FnOnce(&mut Ui) -> R, + ) -> InnerResponse { + self.alignment = None; + + if let Grouping::Alignment(config) = self.grouping { + return self.define_group(None, config, ui, add_contents); + } + + Self::fallback_group(ui, add_contents) + } + + pub fn apply_on_widget( + &mut self, + more_inner_margin: bool, + ui: &mut Ui, + add_contents: impl FnOnce(&mut Ui) -> R, + ) -> InnerResponse { + self.more_inner_margin = more_inner_margin; + let outer_margin = self.widget_outer_margin(ui); + + if let Grouping::Widget(config) = self.grouping { + return self.define_group(Some(outer_margin), config, ui, add_contents); + } + + self.fallback_widget_group(Some(outer_margin), ui, add_contents) + } + + fn fallback_group(ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> InnerResponse { + InnerResponse { + inner: add_contents(ui), + response: ui.response().clone(), + } + } + + fn fallback_widget_group( + &mut self, + outer_margin: Option, + ui: &mut Ui, + add_contents: impl FnOnce(&mut Ui) -> R, + ) -> InnerResponse { + Frame::NONE + .outer_margin(outer_margin.unwrap_or(Margin::ZERO)) + .inner_margin(match self.more_inner_margin { + true => Margin::symmetric(5, 0), + false => Margin::same(0), + }) + .show(ui, add_contents) + } + + fn define_group( + &mut self, + outer_margin: Option, + config: GroupingConfig, + ui: &mut Ui, + add_contents: impl FnOnce(&mut Ui) -> R, + ) -> InnerResponse { + self.define_group_frame(outer_margin, config, ui.style()) + .show(ui, add_contents) + } + + pub fn define_group_frame( + &mut self, + outer_margin: Option, + config: GroupingConfig, + ui_style: &Arc, + ) -> Frame { + Frame::group(ui_style) + .outer_margin(outer_margin.unwrap_or(Margin::ZERO)) + .inner_margin(match self.more_inner_margin { + true => Margin::symmetric(6, 1), + false => Margin::symmetric(1, 1), + }) + .stroke(ui_style.visuals.widgets.noninteractive.bg_stroke) + .corner_radius(match config.rounding { + Some(rounding) => rounding.into(), + None => ui_style.visuals.widgets.noninteractive.corner_radius, + }) + .fill( + self.background_color + .try_apply_alpha(config.transparency_alpha), + ) + .shadow(match config.style { + Some(style) => match style { + // new styles can be added if needed here + GroupingStyle::Default => Shadow::NONE, + GroupingStyle::DefaultWithShadowB4O1S3 => Shadow { + blur: 4, + offset: [1, 1], + spread: 3, + color: Color32::BLACK.try_apply_alpha(config.transparency_alpha), + }, + GroupingStyle::DefaultWithShadowB4O0S3 => Shadow { + blur: 4, + offset: [0, 0], + spread: 3, + color: Color32::BLACK.try_apply_alpha(config.transparency_alpha), + }, + GroupingStyle::DefaultWithShadowB0O1S3 => Shadow { + blur: 0, + offset: [1, 1], + spread: 3, + color: Color32::BLACK.try_apply_alpha(config.transparency_alpha), + }, + GroupingStyle::DefaultWithGlowB3O1S2 => Shadow { + blur: 3, + offset: [1, 1], + spread: 2, + color: ui_style + .visuals + .selection + .stroke + .color + .try_apply_alpha(config.transparency_alpha), + }, + GroupingStyle::DefaultWithGlowB3O0S2 => Shadow { + blur: 3, + offset: [0, 0], + spread: 2, + color: ui_style + .visuals + .selection + .stroke + .color + .try_apply_alpha(config.transparency_alpha), + }, + GroupingStyle::DefaultWithGlowB0O1S2 => Shadow { + blur: 0, + offset: [1, 1], + spread: 2, + color: ui_style + .visuals + .selection + .stroke + .color + .try_apply_alpha(config.transparency_alpha), + }, + }, + None => Shadow::NONE, + }) + } + + fn widget_outer_margin(&mut self, ui: &mut Ui) -> Margin { + let spacing = if self.applied_on_widget { + // Remove the default item spacing from the margin + (self.spacing - ui.spacing().item_spacing.x) as i8 + } else { + 0 + }; + + if !self.applied_on_widget { + self.applied_on_widget = true; + } + + Margin { + left: match self.alignment { + Some(align) => match align { + Alignment::Left => spacing, + Alignment::Center => spacing, + Alignment::Right => 0, + }, + None => 0, + }, + right: match self.alignment { + Some(align) => match align { + Alignment::Left => 0, + Alignment::Center => 0, + Alignment::Right => spacing, + }, + None => 0, + }, + top: 0, + bottom: 0, + } + } +} + +#[derive(Copy, Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct GroupingConfig { + /// Styles for the grouping + pub style: Option, + /// Alpha value for the color transparency [[0-255]] (default: 200) + pub transparency_alpha: Option, + /// Rounding values for the 4 corners. Can be a single or 4 values. + pub rounding: Option, +} + +#[derive(Copy, Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub enum GroupingStyle { + #[serde(alias = "CtByte")] + Default, + /// A shadow is added under the default group. (blur: 4, offset: x-1 y-1, spread: 3) + #[serde(alias = "CtByteWithShadow")] + #[serde(alias = "DefaultWithShadow")] + DefaultWithShadowB4O1S3, + /// A shadow is added under the default group. (blur: 4, offset: x-0 y-0, spread: 3) + DefaultWithShadowB4O0S3, + /// A shadow is added under the default group. (blur: 0, offset: x-1 y-1, spread: 3) + DefaultWithShadowB0O1S3, + /// A glow is added under the default group. (blur: 3, offset: x-1 y-1, spread: 2) + DefaultWithGlowB3O1S2, + /// A glow is added under the default group. (blur: 3, offset: x-0 y-0, spread: 2) + DefaultWithGlowB3O0S2, + /// A glow is added under the default group. (blur: 0, offset: x-1 y-1, spread: 2) + DefaultWithGlowB0O1S2, +} + +#[derive(Copy, Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[serde(untagged)] +pub enum RoundingConfig { + /// All 4 corners are the same + Same(f32), + /// All 4 corners are custom. Order: NW, NE, SW, SE + Individual([f32; 4]), +} + +impl From for CornerRadius { + fn from(value: RoundingConfig) -> Self { + match value { + RoundingConfig::Same(value) => Self::same(value as u8), + RoundingConfig::Individual(values) => { + let values = values.map(|f| f as u8); + Self { + nw: values[0], + ne: values[1], + sw: values[2], + se: values[3], + } + } + } + } +} + +pub trait Color32Ext { + fn try_apply_alpha(self, transparency_alpha: Option) -> Self; +} + +impl Color32Ext for Color32 { + /// Tries to apply the alpha value to the Color32 + fn try_apply_alpha(self, transparency_alpha: Option) -> Self { + if let Some(alpha) = transparency_alpha { + return Color32::from_rgba_unmultiplied(self.r(), self.g(), self.b(), alpha); + } + + self + } +} diff --git a/komorebi-bar/src/selected_frame.rs b/komorebi-bar/src/selected_frame.rs new file mode 100644 index 00000000..6a9347e1 --- /dev/null +++ b/komorebi-bar/src/selected_frame.rs @@ -0,0 +1,89 @@ +use eframe::egui::Color32; +use eframe::egui::CursorIcon; +use eframe::egui::Frame; +use eframe::egui::Margin; +use eframe::egui::Response; +use eframe::egui::Sense; +use eframe::egui::Stroke; +use eframe::egui::Ui; + +/// Same as SelectableLabel, but supports all content +pub struct SelectableFrame { + selected: bool, + selected_fill: Option, +} + +impl SelectableFrame { + pub fn new(selected: bool) -> Self { + Self { + selected, + selected_fill: None, + } + } + + pub fn new_auto(selected: bool, selected_fill: Option) -> Self { + Self { + selected, + selected_fill, + } + } + + pub fn show(self, ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> Response { + let Self { + selected, + selected_fill, + } = self; + + Frame::NONE + .show(ui, |ui| { + let response = ui.interact(ui.max_rect(), ui.unique_id(), Sense::click()); + + if ui.is_rect_visible(response.rect) { + // take into account the stroke width + let inner_margin = Margin::symmetric( + ui.style().spacing.button_padding.x as i8 - 1, + ui.style().spacing.button_padding.y as i8 - 1, + ); + + // since the stroke is drawn inside the frame, we always reserve space for it + if selected && response.hovered() { + let visuals = ui.style().interact_selectable(&response, selected); + + Frame::NONE + .stroke(Stroke::new(1.0, visuals.bg_stroke.color)) + .corner_radius(visuals.corner_radius) + .fill(selected_fill.unwrap_or(visuals.bg_fill)) + .inner_margin(inner_margin) + .show(ui, add_contents); + } else if response.hovered() || response.highlighted() || response.has_focus() { + let visuals = ui.style().interact_selectable(&response, selected); + + Frame::NONE + .stroke(Stroke::new(1.0, visuals.bg_stroke.color)) + .corner_radius(visuals.corner_radius) + .fill(visuals.bg_fill) + .inner_margin(inner_margin) + .show(ui, add_contents); + } else if selected { + let visuals = ui.style().interact_selectable(&response, selected); + + Frame::NONE + .stroke(Stroke::new(1.0, visuals.bg_fill)) + .corner_radius(visuals.corner_radius) + .fill(selected_fill.unwrap_or(visuals.bg_fill)) + .inner_margin(inner_margin) + .show(ui, add_contents); + } else { + Frame::NONE + .stroke(Stroke::new(1.0, Color32::TRANSPARENT)) + .inner_margin(inner_margin) + .show(ui, add_contents); + } + } + + response + }) + .inner + .on_hover_cursor(CursorIcon::PointingHand) + } +} diff --git a/komorebi-bar/src/ui.rs b/komorebi-bar/src/ui.rs new file mode 100644 index 00000000..24d58444 --- /dev/null +++ b/komorebi-bar/src/ui.rs @@ -0,0 +1,22 @@ +use eframe::egui::Align; +use eframe::egui::Layout; +use eframe::egui::Response; +use eframe::egui::Ui; +use eframe::egui::Vec2; +use eframe::egui::Widget; + +pub struct CustomUi<'ui>(pub &'ui mut Ui); + +impl CustomUi<'_> { + pub fn add_sized_left_to_right( + &mut self, + max_size: impl Into, + widget: impl Widget, + ) -> Response { + let layout = + Layout::from_main_dir_and_cross_align(self.0.layout().main_dir(), Align::Center); + self.0 + .allocate_ui_with_layout(max_size.into(), layout, |ui| ui.add(widget)) + .inner + } +} diff --git a/komorebi-bar/src/widgets/applications.rs b/komorebi-bar/src/widgets/applications.rs new file mode 100644 index 00000000..2bdbae1e --- /dev/null +++ b/komorebi-bar/src/widgets/applications.rs @@ -0,0 +1,404 @@ +use super::ImageIcon; +use crate::render::RenderConfig; +use crate::selected_frame::SelectableFrame; +use crate::widgets::widget::BarWidget; +use eframe::egui::Color32; +use eframe::egui::Context; +use eframe::egui::CornerRadius; +use eframe::egui::FontId; +use eframe::egui::Frame; +use eframe::egui::Image; +use eframe::egui::Label; +use eframe::egui::Margin; +use eframe::egui::RichText; +use eframe::egui::Sense; +use eframe::egui::Stroke; +use eframe::egui::StrokeKind; +use eframe::egui::Ui; +use eframe::egui::Vec2; +use eframe::egui::vec2; +use komorebi_client::PathExt; +use serde::Deserialize; +use serde::Serialize; +use std::process::Command; +use std::sync::Arc; +use std::time::Duration; +use std::time::Instant; +use tracing; + +/// Minimum interval between consecutive application launches to prevent accidental spamming. +const MIN_LAUNCH_INTERVAL: Duration = Duration::from_millis(800); + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct ApplicationsConfig { + /// Enables or disables the applications widget. + pub enable: bool, + /// Whether to show the launch command on hover (optional). + /// Could be overridden per application. Defaults to `false` if not set. + pub show_command_on_hover: Option, + /// Horizontal spacing between application buttons. + pub spacing: Option, + /// Default display format for all applications (optional). + /// Could be overridden per application. Defaults to `Icon`. + pub display: Option, + /// List of configured applications to display. + pub items: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct AppConfig { + /// Whether to enable this application button (optional). + /// Inherits from the global `Applications` setting if omitted. + pub enable: Option, + /// Whether to show the launch command on hover (optional). + /// Inherits from the global `Applications` setting if omitted. + pub show_command_on_hover: Option, + /// Display name of the application. + pub name: String, + /// Optional icon: a path to an image or a text-based glyph (e.g., from Nerd Fonts). + /// If not set, and if the `command` is a path to an executable, an icon might be extracted from it. + /// Note: glyphs require a compatible `font_family`. + pub icon: Option, + /// Command to execute (e.g. path to the application or shell command). + pub command: String, + /// Display format for this application button (optional). Overrides global format if set. + pub display: Option, +} + +#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Default)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub enum DisplayFormat { + /// Show only the application icon. + #[default] + Icon, + /// Show only the application name as text. + Text, + /// Show both the application icon and name. + IconAndText, +} + +#[derive(Clone, Debug)] +pub struct Applications { + /// Whether the applications widget is enabled. + pub enable: bool, + /// Horizontal spacing between application buttons. + pub spacing: Option, + /// Applications to be rendered in the UI. + pub items: Vec, +} + +impl BarWidget for Applications { + fn render(&mut self, ctx: &Context, ui: &mut Ui, config: &mut RenderConfig) { + if !self.enable { + return; + } + + let icon_config = IconConfig { + font_id: config.icon_font_id.clone(), + size: config.icon_font_id.size, + color: ctx.style().visuals.selection.stroke.color, + }; + + if let Some(spacing) = self.spacing { + ui.spacing_mut().item_spacing.x = spacing; + } + + config.apply_on_widget(false, ui, |ui| { + for app in &mut self.items { + app.render(ctx, ui, &icon_config); + } + }); + } +} + +impl From<&ApplicationsConfig> for Applications { + fn from(applications_config: &ApplicationsConfig) -> Self { + let items = applications_config + .items + .iter() + .enumerate() + .map(|(index, config)| { + let command = UserCommand::new(&config.command); + + App { + enable: config.enable.unwrap_or(applications_config.enable), + #[allow(clippy::obfuscated_if_else)] + name: config + .name + .is_empty() + .then(|| format!("App {}", index + 1)) + .unwrap_or_else(|| config.name.clone()), + icon: Icon::try_from_path(config.icon.as_deref()) + .or_else(|| Icon::try_from_command(&command)), + command, + display: config + .display + .or(applications_config.display) + .unwrap_or_default(), + show_command_on_hover: config + .show_command_on_hover + .or(applications_config.show_command_on_hover) + .unwrap_or(false), + } + }) + .collect(); + + Self { + enable: applications_config.enable, + items, + spacing: applications_config.spacing, + } + } +} + +/// A single resolved application entry used at runtime. +#[derive(Clone, Debug)] +pub struct App { + /// Whether this application is enabled. + pub enable: bool, + /// Display name of the application. Defaults to "App N" if not set. + pub name: String, + /// Icon to display for this application, if available. + pub icon: Option, + /// Command to execute when the application is launched. + pub command: UserCommand, + /// Display format (icon, text, or both). + pub display: DisplayFormat, + /// Whether to show the launch command on hover. + pub show_command_on_hover: bool, +} + +impl App { + /// Renders the application button in the provided `Ui` context with a given icon size. + #[inline] + pub fn render(&mut self, ctx: &Context, ui: &mut Ui, icon_config: &IconConfig) { + if self.enable + && SelectableFrame::new(false) + .show(ui, |ui| { + ui.spacing_mut().item_spacing = Vec2::splat(4.0); + + match self.display { + DisplayFormat::Icon => self.draw_icon(ctx, ui, icon_config), + DisplayFormat::Text => self.draw_name(ui), + DisplayFormat::IconAndText => { + self.draw_icon(ctx, ui, icon_config); + self.draw_name(ui); + } + } + + // Add hover text with command information + let response = ui.response(); + if self.show_command_on_hover { + response.on_hover_text(format!("Launch: {}", self.command.as_ref())); + } + }) + .clicked() + { + // Launch the application when clicked + self.command.launch_if_ready(); + } + } + + /// Draws the application's icon within the UI if available, + /// or falls back to a default placeholder icon. + #[inline] + fn draw_icon(&self, ctx: &Context, ui: &mut Ui, icon_config: &IconConfig) { + if let Some(icon) = &self.icon { + icon.draw(ctx, ui, icon_config); + } else { + Icon::draw_fallback(ui, Vec2::splat(icon_config.size)); + } + } + + /// Displays the application's name as a non-selectable label within the UI. + #[inline] + fn draw_name(&self, ui: &mut Ui) { + ui.add(Label::new(&self.name).selectable(false)); + } +} + +/// Holds image/text data to be used as an icon in the UI. +/// This represents source icon data before rendering. +#[derive(Clone, Debug)] +pub enum Icon { + /// RGBA image used for rendering the icon. + Image(ImageIcon), + /// Text-based icon, e.g. from a font like Nerd Fonts. + Text(String), +} + +impl Icon { + /// Attempts to create an [`Icon`] from a string path or text glyph/glyphs. + /// + /// - Environment variables in the path are resolved using [`PathExt::replace_env`]. + /// - Uses [`ImageIcon::try_load`] to load and cache the icon image based on the resolved path. + /// - If the path is invalid but the string is non-empty, it is interpreted as a text-based icon and + /// returned as [`Icon::Text`]. + /// - Returns `None` if the input is empty, `None`, or image loading fails. + #[inline] + pub fn try_from_path(icon: Option<&str>) -> Option { + let icon = icon.map(str::trim)?; + if icon.is_empty() { + return None; + } + + let path = icon.replace_env(); + if !path.is_file() { + return Some(Icon::Text(icon.to_owned())); + } + + let image_icon = ImageIcon::try_load(path.as_ref(), || match image::open(&path) { + Ok(img) => Some(img), + Err(err) => { + tracing::error!("Failed to load icon from {:?}, error: {}", path, err); + None + } + })?; + + Some(Icon::Image(image_icon)) + } + + /// Attempts to create an [`Icon`] by extracting an image from the executable path of a [`UserCommand`]. + /// + /// - Uses [`ImageIcon::try_load`] to load and cache the icon image based on the resolved executable path. + /// - Returns [`Icon::Image`] if an icon is successfully extracted. + /// - Returns `None` if the executable path is unavailable or icon extraction fails. + #[inline] + pub fn try_from_command(_command: &UserCommand) -> Option { + // let path = command.get_executable()?; + // let image_icon = ImageIcon::try_load(path.as_ref(), || { + // let path_str = path.to_str()?; + // windows_icons::get_icon_by_path(path_str) + // .or_else(|| windows_icons_fallback::get_icon_by_path(path_str)) + // })?; + // Some(Icon::Image(image_icon)) + None + } + + /// Renders the icon in the given [`Ui`] using the provided [`IconConfig`]. + #[inline] + pub fn draw(&self, ctx: &Context, ui: &mut Ui, icon_config: &IconConfig) { + match self { + Icon::Image(image_icon) => { + Frame::NONE + .inner_margin(Margin::same(ui.style().spacing.button_padding.y as i8)) + .show(ui, |ui| { + ui.add( + Image::from_texture(&image_icon.texture(ctx)) + .maintain_aspect_ratio(true) + .fit_to_exact_size(Vec2::splat(icon_config.size)), + ); + }); + } + Icon::Text(icon) => { + let rich_text = RichText::new(icon) + .font(icon_config.font_id.clone()) + .size(icon_config.size) + .color(icon_config.color); + ui.add(Label::new(rich_text).selectable(false)); + } + } + } + + /// Draws a fallback icon when the specified icon cannot be loaded. + /// Displays a simple crossed-out rectangle as a placeholder. + #[inline] + pub fn draw_fallback(ui: &mut Ui, icon_size: Vec2) { + let (response, painter) = ui.allocate_painter(icon_size, Sense::hover()); + let stroke = Stroke::new(1.0, ui.style().visuals.text_color()); + let mut rect = response.rect; + let rounding = CornerRadius::same((rect.width() * 0.1) as u8); + rect = rect.shrink(stroke.width); + let c = rect.center(); + let r = rect.width() / 2.0; + painter.rect_stroke(rect, rounding, stroke, StrokeKind::Outside); + painter.line_segment([c - vec2(r, r), c + vec2(r, r)], stroke); + } +} + +/// Configuration structure for icon rendering +#[derive(Clone, Debug)] +pub struct IconConfig { + /// Font used for text-based icons + pub font_id: FontId, + /// Size of the icon + pub size: f32, + /// Color of the icon used for text-based icons + pub color: Color32, +} + +/// A structure to manage command execution with cooldown prevention. +#[derive(Clone, Debug)] +pub struct UserCommand { + /// The command string to execute + pub command: Arc, + /// Last time this command was executed (used for cooldown control) + pub last_launch: Instant, +} + +impl AsRef for UserCommand { + #[inline] + fn as_ref(&self) -> &str { + &self.command + } +} + +impl UserCommand { + /// Creates a new [`UserCommand`] with environment variables in the command path + /// resolved using [`PathExt::replace_env`]. + #[inline] + pub fn new(command: &str) -> Self { + // Allow immediate launch by initializing last_launch in the past + let last_launch = Instant::now() - 2 * MIN_LAUNCH_INTERVAL; + + Self { + command: Arc::from(command.replace_env().to_str().unwrap_or_default()), + last_launch, + } + } + + // /// Attempts to resolve the executable path from the command string. + // /// + // /// Resolution logic: + // /// - Splits the command by ".exe" and checks if the first part is an existing file. + // /// - If not, attempts to locate the binary using [`which`] on this name. + // /// - If still unresolved, takes the first word (separated by whitespace) and attempts + // /// to find it in the system `PATH` using [`which`]. + // /// + // /// Returns `None` if no executable path can be determined. + // #[inline] + // pub fn get_executable(&self) -> Option> { + // if let Some(binary) = self.command.split(".exe").next().map(Path::new) { + // if binary.is_file() { + // return Some(Cow::Borrowed(binary)); + // } else if let Ok(binary) = which(binary) { + // return Some(Cow::Owned(binary)); + // } + // } + // + // which(self.command.split(' ').next()?).ok().map(Cow::Owned) + // } + + /// Attempts to launch the specified command in a separate thread if enough time has passed + /// since the last launch. This prevents repeated launches from rapid consecutive clicks. + /// + /// Errors during launch are logged using the `tracing` crate. + pub fn launch_if_ready(&mut self) { + let now = Instant::now(); + // Check if enough time has passed since the last launch + if now.duration_since(self.last_launch) < MIN_LAUNCH_INTERVAL { + return; + } + + self.last_launch = now; + let command_string = self.command.clone(); + // Launch the application in a separate thread to avoid blocking the UI + std::thread::spawn(move || { + if let Err(e) = Command::new("cmd").args(["/C", &command_string]).spawn() { + tracing::error!("Failed to launch command '{}': {}", command_string, e); + } + }); + } +} diff --git a/komorebi-bar/src/widgets/battery.rs b/komorebi-bar/src/widgets/battery.rs new file mode 100644 index 00000000..f44ebe1d --- /dev/null +++ b/komorebi-bar/src/widgets/battery.rs @@ -0,0 +1,189 @@ +use crate::config::LabelPrefix; +use crate::render::RenderConfig; +use crate::selected_frame::SelectableFrame; +use crate::widgets::widget::BarWidget; +use eframe::egui::Align; +use eframe::egui::Context; +use eframe::egui::Label; +use eframe::egui::TextFormat; +use eframe::egui::Ui; +use eframe::egui::text::LayoutJob; +use serde::Deserialize; +use serde::Serialize; +use starship_battery::Manager; +use starship_battery::State; +use starship_battery::units::ratio::percent; +use std::process::Command; +use std::time::Duration; +use std::time::Instant; + +#[derive(Copy, Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct BatteryConfig { + /// Enable the Battery widget + pub enable: bool, + /// Hide the widget if the battery is at full charge + pub hide_on_full_charge: Option, + /// Data refresh interval (default: 10 seconds) + pub data_refresh_interval: Option, + /// Display label prefix + pub label_prefix: Option, + /// Select when the current percentage is under this value [[1-100]] + pub auto_select_under: Option, +} + +impl From for Battery { + fn from(value: BatteryConfig) -> Self { + let data_refresh_interval = value.data_refresh_interval.unwrap_or(10); + + Self { + enable: value.enable, + hide_on_full_charge: value.hide_on_full_charge.unwrap_or(false), + manager: Manager::new().unwrap(), + last_state: None, + data_refresh_interval, + label_prefix: value.label_prefix.unwrap_or(LabelPrefix::Icon), + auto_select_under: value.auto_select_under.map(|u| u.clamp(1, 100)), + state: BatteryState::Discharging, + last_updated: Instant::now() + .checked_sub(Duration::from_secs(data_refresh_interval)) + .unwrap(), + } + } +} + +pub enum BatteryState { + Charging, + Discharging, + High, + Medium, + Low, + Warning, +} + +#[derive(Clone, Debug)] +struct BatteryOutput { + label: String, + selected: bool, +} + +pub struct Battery { + pub enable: bool, + hide_on_full_charge: bool, + manager: Manager, + pub state: BatteryState, + data_refresh_interval: u64, + label_prefix: LabelPrefix, + auto_select_under: Option, + last_state: Option, + last_updated: Instant, +} + +impl Battery { + fn output(&mut self) -> Option { + let mut output = self.last_state.clone(); + + let now = Instant::now(); + if now.duration_since(self.last_updated) > Duration::from_secs(self.data_refresh_interval) { + output = None; + + if let Ok(mut batteries) = self.manager.batteries() + && let Some(Ok(first)) = batteries.nth(0) + { + let percentage = first.state_of_charge().get::().round() as u8; + + if percentage == 100 && self.hide_on_full_charge { + output = None + } else { + match first.state() { + State::Charging => self.state = BatteryState::Charging, + State::Discharging => { + self.state = match percentage { + p if p > 75 => BatteryState::Discharging, + p if p > 50 => BatteryState::High, + p if p > 25 => BatteryState::Medium, + p if p > 10 => BatteryState::Low, + _ => BatteryState::Warning, + } + } + _ => {} + } + + let selected = self.auto_select_under.is_some_and(|u| percentage <= u); + + output = Some(BatteryOutput { + label: match self.label_prefix { + LabelPrefix::Text | LabelPrefix::IconAndText => { + format!("BAT: {percentage}%") + } + LabelPrefix::None | LabelPrefix::Icon => { + format!("{percentage}%") + } + }, + selected, + }) + } + } + + self.last_state.clone_from(&output); + self.last_updated = now; + } + + output + } +} + +impl BarWidget for Battery { + fn render(&mut self, ctx: &Context, ui: &mut Ui, config: &mut RenderConfig) { + if self.enable { + let output = self.output(); + if let Some(output) = output { + let emoji = match self.state { + BatteryState::Charging => egui_phosphor::regular::BATTERY_CHARGING, + BatteryState::Discharging => egui_phosphor::regular::BATTERY_FULL, + BatteryState::High => egui_phosphor::regular::BATTERY_HIGH, + BatteryState::Medium => egui_phosphor::regular::BATTERY_MEDIUM, + BatteryState::Low => egui_phosphor::regular::BATTERY_LOW, + BatteryState::Warning => egui_phosphor::regular::BATTERY_WARNING, + }; + + let auto_text_color = config.auto_select_text.filter(|_| output.selected); + + let mut layout_job = LayoutJob::simple( + match self.label_prefix { + LabelPrefix::Icon | LabelPrefix::IconAndText => emoji.to_string(), + LabelPrefix::None | LabelPrefix::Text => String::new(), + }, + config.icon_font_id.clone(), + auto_text_color.unwrap_or(ctx.style().visuals.selection.stroke.color), + 100.0, + ); + + layout_job.append( + &output.label, + 10.0, + TextFormat { + font_id: config.text_font_id.clone(), + color: auto_text_color.unwrap_or(ctx.style().visuals.text_color()), + valign: Align::Center, + ..Default::default() + }, + ); + + let auto_focus_fill = config.auto_select_fill; + + config.apply_on_widget(false, ui, |ui| { + if SelectableFrame::new_auto(output.selected, auto_focus_fill) + .show(ui, |ui| ui.add(Label::new(layout_job).selectable(false))) + .clicked() + && let Err(error) = Command::new("cmd.exe") + .args(["/C", "start", "ms-settings:batterysaver"]) + .spawn() + { + eprintln!("{error}") + } + }); + } + } + } +} diff --git a/komorebi-bar/src/widgets/cpu.rs b/komorebi-bar/src/widgets/cpu.rs new file mode 100644 index 00000000..9fff789a --- /dev/null +++ b/komorebi-bar/src/widgets/cpu.rs @@ -0,0 +1,132 @@ +use crate::config::LabelPrefix; +use crate::render::RenderConfig; +use crate::selected_frame::SelectableFrame; +use crate::widgets::widget::BarWidget; +use eframe::egui::Align; +use eframe::egui::Context; +use eframe::egui::Label; +use eframe::egui::TextFormat; +use eframe::egui::Ui; +use eframe::egui::text::LayoutJob; +use serde::Deserialize; +use serde::Serialize; +use std::process::Command; +use std::time::Duration; +use std::time::Instant; +use sysinfo::RefreshKind; +use sysinfo::System; + +#[derive(Copy, Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct CpuConfig { + /// Enable the Cpu widget + pub enable: bool, + /// Data refresh interval (default: 10 seconds) + pub data_refresh_interval: Option, + /// Display label prefix + pub label_prefix: Option, + /// Select when the current percentage is over this value [[1-100]] + pub auto_select_over: Option, +} + +impl From for Cpu { + fn from(value: CpuConfig) -> Self { + let data_refresh_interval = value.data_refresh_interval.unwrap_or(10); + + Self { + enable: value.enable, + system: System::new_with_specifics( + RefreshKind::default().without_memory().without_processes(), + ), + data_refresh_interval, + label_prefix: value.label_prefix.unwrap_or(LabelPrefix::IconAndText), + auto_select_over: value.auto_select_over.map(|o| o.clamp(1, 100)), + last_updated: Instant::now() + .checked_sub(Duration::from_secs(data_refresh_interval)) + .unwrap(), + } + } +} + +#[derive(Clone, Debug)] +struct CpuOutput { + label: String, + selected: bool, +} + +pub struct Cpu { + pub enable: bool, + system: System, + data_refresh_interval: u64, + label_prefix: LabelPrefix, + auto_select_over: Option, + last_updated: Instant, +} + +impl Cpu { + fn output(&mut self) -> CpuOutput { + let now = Instant::now(); + if now.duration_since(self.last_updated) > Duration::from_secs(self.data_refresh_interval) { + self.system.refresh_cpu_usage(); + self.last_updated = now; + } + + let used = self.system.global_cpu_usage() as u8; + let selected = self.auto_select_over.is_some_and(|o| used >= o); + + CpuOutput { + label: match self.label_prefix { + LabelPrefix::Text | LabelPrefix::IconAndText => format!("CPU: {used}%"), + LabelPrefix::None | LabelPrefix::Icon => format!("{used}%"), + }, + selected, + } + } +} + +impl BarWidget for Cpu { + fn render(&mut self, ctx: &Context, ui: &mut Ui, config: &mut RenderConfig) { + if self.enable { + let output = self.output(); + if !output.label.is_empty() { + let auto_text_color = config.auto_select_text.filter(|_| output.selected); + + let mut layout_job = LayoutJob::simple( + match self.label_prefix { + LabelPrefix::Icon | LabelPrefix::IconAndText => { + egui_phosphor::regular::CPU.to_string() + } + LabelPrefix::None | LabelPrefix::Text => String::new(), + }, + config.icon_font_id.clone(), + auto_text_color.unwrap_or(ctx.style().visuals.selection.stroke.color), + 100.0, + ); + + layout_job.append( + &output.label, + 10.0, + TextFormat { + font_id: config.text_font_id.clone(), + color: auto_text_color.unwrap_or(ctx.style().visuals.text_color()), + valign: Align::Center, + ..Default::default() + }, + ); + + let auto_focus_fill = config.auto_select_fill; + + config.apply_on_widget(false, ui, |ui| { + if SelectableFrame::new_auto(output.selected, auto_focus_fill) + .show(ui, |ui| ui.add(Label::new(layout_job).selectable(false))) + .clicked() + && let Err(error) = + Command::new("cmd.exe").args(["/C", "taskmgr.exe"]).spawn() + { + eprintln!("{error}") + } + }); + } + } + } +} diff --git a/komorebi-bar/src/widgets/date.rs b/komorebi-bar/src/widgets/date.rs new file mode 100644 index 00000000..5fe662fa --- /dev/null +++ b/komorebi-bar/src/widgets/date.rs @@ -0,0 +1,240 @@ +use crate::config::LabelPrefix; +use crate::render::RenderConfig; +use crate::selected_frame::SelectableFrame; +use crate::widgets::widget::BarWidget; +use chrono::Local; +use chrono_tz::Tz; +use eframe::egui::Align; +use eframe::egui::Context; +use eframe::egui::Label; +use eframe::egui::TextFormat; +use eframe::egui::Ui; +use eframe::egui::WidgetText; +use eframe::egui::text::LayoutJob; +use serde::Deserialize; +use serde::Serialize; +use std::time::Duration; +use std::time::Instant; + +/// Custom format with additive modifiers for integer format specifiers +#[derive(Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct CustomModifiers { + /// Custom format (https://docs.rs/chrono/latest/chrono/format/strftime/index.html) + format: String, + /// Additive modifiers for integer format specifiers (e.g. { "%U": 1 } to increment the zero-indexed week number by 1) + modifiers: std::collections::HashMap, +} + +impl CustomModifiers { + fn apply(&self, output: &str) -> String { + let int_formatters = vec![ + "%Y", "%C", "%y", "%m", "%d", "%e", "%w", "%u", "%U", "%W", "%G", "%g", "%V", "%j", + "%H", "%k", "%I", "%l", "%M", "%S", "%f", + ]; + + let mut modified_output = output.to_string(); + + for (modifier, value) in &self.modifiers { + // check if formatter is integer type + if !int_formatters.contains(&modifier.as_str()) { + continue; + } + + // get the strftime value of modifier + let formatted_modifier = Local::now().format(modifier).to_string(); + + // find the gotten value in the original output + if let Some(pos) = modified_output.find(&formatted_modifier) { + let start = pos; + let end = start + formatted_modifier.len(); + // replace that value with the modified value + if let Ok(num) = formatted_modifier.parse::() { + modified_output.replace_range(start..end, &(num + value).to_string()); + } + } + } + + modified_output + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct DateConfig { + /// Enable the Date widget + pub enable: bool, + /// Set the Date format + pub format: DateFormat, + /// Display label prefix + pub label_prefix: Option, + /// TimeZone (https://docs.rs/chrono-tz/latest/chrono_tz/enum.Tz.html) + /// + /// Use a custom format to display additional information, i.e.: + /// ```json + /// { + /// "Date": { + /// "enable": true, + /// "format": { "Custom": "%D %Z (Tokyo)" }, + /// "timezone": "Asia/Tokyo" + /// } + ///} + /// ``` + pub timezone: Option, +} + +impl From for Date { + fn from(value: DateConfig) -> Self { + let data_refresh_interval = 1; + + Self { + enable: value.enable, + format: value.format, + label_prefix: value.label_prefix.unwrap_or(LabelPrefix::Icon), + timezone: value.timezone, + data_refresh_interval, + last_state: String::new(), + last_updated: Instant::now() + .checked_sub(Duration::from_secs(data_refresh_interval)) + .unwrap(), + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub enum DateFormat { + /// Month/Date/Year format (09/08/24) + MonthDateYear, + /// Year-Month-Date format (2024-09-08) + YearMonthDate, + /// Date-Month-Year format (8-Sep-2024) + DateMonthYear, + /// Day Date Month Year format (8 September 2024) + DayDateMonthYear, + /// Custom format (https://docs.rs/chrono/latest/chrono/format/strftime/index.html) + Custom(String), + /// Custom format with modifiers + CustomModifiers(CustomModifiers), +} + +impl DateFormat { + pub fn next(&mut self) { + match self { + DateFormat::MonthDateYear => *self = Self::YearMonthDate, + DateFormat::YearMonthDate => *self = Self::DateMonthYear, + DateFormat::DateMonthYear => *self = Self::DayDateMonthYear, + DateFormat::DayDateMonthYear => *self = Self::MonthDateYear, + _ => {} + }; + } + + pub fn fmt_string(&self) -> String { + match self { + DateFormat::MonthDateYear => String::from("%D"), + DateFormat::YearMonthDate => String::from("%F"), + DateFormat::DateMonthYear => String::from("%v"), + DateFormat::DayDateMonthYear => String::from("%A %e %B %Y"), + DateFormat::Custom(custom) => custom.to_string(), + DateFormat::CustomModifiers(custom) => custom.format.clone(), + } + } +} + +#[derive(Clone, Debug)] +pub struct Date { + pub enable: bool, + pub format: DateFormat, + label_prefix: LabelPrefix, + timezone: Option, + data_refresh_interval: u64, + last_state: String, + last_updated: Instant, +} + +impl Date { + fn output(&mut self) -> String { + let mut output = self.last_state.clone(); + let now = Instant::now(); + + if now.duration_since(self.last_updated) > Duration::from_secs(self.data_refresh_interval) { + let formatted = match &self.timezone { + Some(timezone) => match timezone.parse::() { + Ok(tz) => Local::now() + .with_timezone(&tz) + .format(&self.format.fmt_string()) + .to_string() + .trim() + .to_string(), + Err(_) => format!("Invalid timezone: {timezone}"), + }, + None => Local::now() + .format(&self.format.fmt_string()) + .to_string() + .trim() + .to_string(), + }; + + // if custom modifiers are used, apply them + output = match &self.format { + DateFormat::CustomModifiers(custom) => custom.apply(&formatted), + _ => formatted, + }; + + self.last_state.clone_from(&output); + self.last_updated = now; + } + + output + } +} + +impl BarWidget for Date { + fn render(&mut self, ctx: &Context, ui: &mut Ui, config: &mut RenderConfig) { + if self.enable { + let mut output = self.output(); + if !output.is_empty() { + let mut layout_job = LayoutJob::simple( + match self.label_prefix { + LabelPrefix::Icon | LabelPrefix::IconAndText => { + egui_phosphor::regular::CALENDAR_DOTS.to_string() + } + LabelPrefix::None | LabelPrefix::Text => String::new(), + }, + config.icon_font_id.clone(), + ctx.style().visuals.selection.stroke.color, + 100.0, + ); + + if let LabelPrefix::Text | LabelPrefix::IconAndText = self.label_prefix { + output.insert_str(0, "DATE: "); + } + + layout_job.append( + &output, + 10.0, + TextFormat { + font_id: config.text_font_id.clone(), + color: ctx.style().visuals.text_color(), + valign: Align::Center, + ..Default::default() + }, + ); + + config.apply_on_widget(false, ui, |ui| { + if SelectableFrame::new(false) + .show(ui, |ui| { + ui.add( + Label::new(WidgetText::LayoutJob(layout_job.clone())) + .selectable(false), + ) + }) + .clicked() + { + self.format.next() + } + }); + } + } + } +} diff --git a/komorebi-bar/src/widgets/keyboard.rs b/komorebi-bar/src/widgets/keyboard.rs new file mode 100644 index 00000000..8e7f4c33 --- /dev/null +++ b/komorebi-bar/src/widgets/keyboard.rs @@ -0,0 +1,177 @@ +use crate::config::LabelPrefix; +use crate::render::RenderConfig; +use crate::widgets::widget::BarWidget; +use eframe::egui::Align; +use eframe::egui::Context; +use eframe::egui::Label; +use eframe::egui::TextFormat; +use eframe::egui::Ui; +use eframe::egui::WidgetText; +use eframe::egui::text::LayoutJob; +use serde::Deserialize; +use serde::Serialize; +use std::time::Duration; +use std::time::Instant; +use windows::Win32::Globalization::LCIDToLocaleName; +use windows::Win32::Globalization::LOCALE_ALLOW_NEUTRAL_NAMES; +use windows::Win32::System::SystemServices::LOCALE_NAME_MAX_LENGTH; +use windows::Win32::UI::Input::KeyboardAndMouse::GetKeyboardLayout; +use windows::Win32::UI::WindowsAndMessaging::GetForegroundWindow; +use windows::Win32::UI::WindowsAndMessaging::GetWindowThreadProcessId; + +const DEFAULT_DATA_REFRESH_INTERVAL: u64 = 1; +const ERROR_TEXT: &str = "Error"; + +#[derive(Copy, Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct KeyboardConfig { + /// Enable the Input widget + pub enable: bool, + /// Data refresh interval (default: 1 second) + pub data_refresh_interval: Option, + /// Display label prefix + pub label_prefix: Option, +} + +impl From for Keyboard { + fn from(value: KeyboardConfig) -> Self { + let data_refresh_interval = value + .data_refresh_interval + .unwrap_or(DEFAULT_DATA_REFRESH_INTERVAL); + + Self { + enable: value.enable, + data_refresh_interval, + label_prefix: value.label_prefix.unwrap_or(LabelPrefix::IconAndText), + last_updated: Instant::now(), + lang_name: get_lang(), + } + } +} + +pub struct Keyboard { + pub enable: bool, + data_refresh_interval: u64, + label_prefix: LabelPrefix, + last_updated: Instant, + lang_name: String, +} + +/// Retrieves the name of the active keyboard layout for the current foreground window. +/// +/// This function determines the active keyboard layout by querying the system for the +/// foreground window's thread ID and its associated keyboard layout. It then attempts +/// to retrieve the locale name corresponding to the keyboard layout. +/// +/// # Failure Cases +/// +/// This function can fail in two distinct scenarios: +/// +/// 1. **Failure to Retrieve the Locale Name**: +/// If the system fails to retrieve the locale name (e.g., due to an invalid or unsupported +/// language identifier), the function will return `Err(())`. +/// +/// 2. **Invalid UTF-16 Characters in the Locale Name**: +/// If the retrieved locale name contains invalid UTF-16 sequences, the conversion to a Rust +/// `String` will fail, and the function will return `Err(())`. +/// +/// # Returns +/// +/// - `Ok(String)`: The name of the active keyboard layout as a valid UTF-8 string. +/// - `Err(())`: Indicates that the function failed to retrieve the locale name or encountered +/// invalid UTF-16 characters during conversion. +fn get_active_keyboard_layout() -> Result { + let foreground_window_tid = unsafe { GetWindowThreadProcessId(GetForegroundWindow(), None) }; + let lcid = unsafe { GetKeyboardLayout(foreground_window_tid) }; + + // Extract the low word (language identifier) from the keyboard layout handle. + let lang_id = (lcid.0 as u32) & 0xFFFF; + let mut locale_name_buffer = [0; LOCALE_NAME_MAX_LENGTH as usize]; + let char_count = unsafe { + LCIDToLocaleName( + lang_id, + Some(&mut locale_name_buffer), + LOCALE_ALLOW_NEUTRAL_NAMES, + ) + }; + + match char_count { + 0 => Err(()), + _ => String::from_utf16(&locale_name_buffer[..char_count as usize]).map_err(|_| ()), + } +} + +/// Retrieves the name of the active keyboard layout or a fallback error message. +/// +/// # Behavior +/// +/// - **Success Case**: +/// If [`get_active_keyboard_layout`] succeeds, this function returns the retrieved keyboard +/// layout name as a `String`. +/// +/// - **Failure Case**: +/// If [`get_active_keyboard_layout`] fails, this function returns the value of `ERROR_TEXT` +/// as a fallback message. This ensures that the function always returns a valid `String`, +/// even in error scenarios. +/// +/// # Returns +/// +/// A `String` representing either: +/// - The name of the active keyboard layout, or +/// - The fallback error message (`ERROR_TEXT`) if the layout name cannot be retrieved. +fn get_lang() -> String { + get_active_keyboard_layout() + .map(|l| l.trim_end_matches('\0').to_string()) + .unwrap_or_else(|_| ERROR_TEXT.to_string()) +} + +impl Keyboard { + fn output(&mut self) -> String { + let now = Instant::now(); + if now.duration_since(self.last_updated) > Duration::from_secs(self.data_refresh_interval) { + self.last_updated = now; + self.lang_name = get_lang(); + } + + match self.label_prefix { + LabelPrefix::Text | LabelPrefix::IconAndText => format!("KB: {}", self.lang_name), + LabelPrefix::None | LabelPrefix::Icon => self.lang_name.clone(), + } + } +} + +impl BarWidget for Keyboard { + fn render(&mut self, ctx: &Context, ui: &mut Ui, config: &mut RenderConfig) { + if self.enable { + let output = self.output(); + if !output.is_empty() { + let mut layout_job = LayoutJob::simple( + match self.label_prefix { + LabelPrefix::Icon | LabelPrefix::IconAndText => { + egui_phosphor::regular::KEYBOARD.to_string() + } + LabelPrefix::None | LabelPrefix::Text => String::new(), + }, + config.icon_font_id.clone(), + ctx.style().visuals.selection.stroke.color, + 100.0, + ); + + layout_job.append( + &output, + 10.0, + TextFormat { + font_id: config.text_font_id.clone(), + color: ctx.style().visuals.text_color(), + valign: Align::Center, + ..Default::default() + }, + ); + + config.apply_on_widget(true, ui, |ui| { + ui.add(Label::new(WidgetText::LayoutJob(layout_job.clone())).selectable(false)) + }); + } + } + } +} diff --git a/komorebi-bar/src/widgets/komorebi.rs b/komorebi-bar/src/widgets/komorebi.rs new file mode 100644 index 00000000..c3ad933c --- /dev/null +++ b/komorebi-bar/src/widgets/komorebi.rs @@ -0,0 +1,1015 @@ +use super::ImageIcon; +use crate::MAX_LABEL_WIDTH; +use crate::MONITOR_INDEX; +use crate::config::DisplayFormat; +use crate::config::DisplayFormat::*; +use crate::config::WorkspacesDisplayFormat; +use crate::render::RenderConfig; +use crate::selected_frame::SelectableFrame; +use crate::ui::CustomUi; +use crate::widgets::komorebi_layout::KomorebiLayout; +use crate::widgets::widget::BarWidget; +use eframe::egui::Align; +use eframe::egui::Color32; +use eframe::egui::Context; +use eframe::egui::CornerRadius; +use eframe::egui::FontId; +use eframe::egui::Frame; +use eframe::egui::Image; +use eframe::egui::Label; +use eframe::egui::Margin; +use eframe::egui::Response; +use eframe::egui::RichText; +use eframe::egui::Sense; +use eframe::egui::Stroke; +use eframe::egui::StrokeKind; +use eframe::egui::TextFormat; +use eframe::egui::Ui; +use eframe::egui::Vec2; +use eframe::egui::text::LayoutJob; +use eframe::egui::vec2; +use komorebi_client::Container; +use komorebi_client::PathExt; +use komorebi_client::Rect; +use komorebi_client::SocketMessage; +use komorebi_client::SocketMessage::*; +use komorebi_client::State; +use komorebi_client::Window; +use komorebi_client::Workspace; +use komorebi_client::WorkspaceLayer; +use serde::Deserialize; +use serde::Serialize; +use std::cell::RefCell; +use std::collections::BTreeMap; +use std::collections::HashMap; +use std::io::Result as IoResult; +use std::path::Path; +use std::rc::Rc; +use std::sync::atomic::Ordering; + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct KomorebiConfig { + /// Configure the Workspaces widget + pub workspaces: Option, + /// Configure the Layout widget + pub layout: Option, + /// Configure the Workspace Layer widget + pub workspace_layer: Option, + /// Configure the Focused Container widget + #[serde(alias = "focused_window")] + pub focused_container: Option, + /// Configure the Locked Container widget + pub locked_container: Option, + /// Configure the Configuration Switcher widget + pub configuration_switcher: Option, +} + +#[derive(Copy, Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct KomorebiWorkspacesConfig { + /// Enable the Komorebi Workspaces widget + pub enable: bool, + /// Hide workspaces without any windows + pub hide_empty_workspaces: bool, + /// Display format of the workspace + pub display: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct KomorebiLayoutConfig { + /// Enable the Komorebi Layout widget + pub enable: bool, + /// List of layout options + pub options: Option>, + /// Display format of the current layout + pub display: Option, +} + +#[derive(Copy, Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct KomorebiWorkspaceLayerConfig { + /// Enable the Komorebi Workspace Layer widget + pub enable: bool, + /// Display format of the current layer + pub display: Option, + /// Show the widget event if the layer is Tiling + pub show_when_tiling: Option, +} + +#[derive(Copy, Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct KomorebiFocusedContainerConfig { + /// Enable the Komorebi Focused Container widget + pub enable: bool, + /// DEPRECATED: use 'display' instead (Show the icon of the currently focused container) + pub show_icon: Option, + /// Display format of the currently focused container + pub display: Option, +} + +#[derive(Copy, Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct KomorebiLockedContainerConfig { + /// Enable the Komorebi Locked Container widget + pub enable: bool, + /// Display format of the current locked state + pub display: Option, + /// Show the widget event if the layer is unlocked + pub show_when_unlocked: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct KomorebiConfigurationSwitcherConfig { + /// Enable the Komorebi Configurations widget + pub enable: bool, + /// A map of display friendly name => path to configuration.json + pub configurations: BTreeMap, +} + +impl From<&KomorebiConfig> for Komorebi { + fn from(cfg: &KomorebiConfig) -> Self { + let configuration_switcher = cfg.configuration_switcher.clone().map(|mut cs| { + for location in cs.configurations.values_mut() { + let path = Path::new(location).replace_env(); + *location = dunce::simplified(&path).to_string_lossy().to_string(); + } + cs + }); + + Self { + monitor_info: Rc::new(RefCell::new(MonitorInfo { + hide_empty_workspaces: cfg + .workspaces + .map(|w| w.hide_empty_workspaces) + .unwrap_or_default(), + ..Default::default() + })), + workspaces: cfg.workspaces.and_then(WorkspacesBar::try_from), + layout: cfg.layout.clone(), + focused_container: cfg + .focused_container + .and_then(FocusedContainerBar::try_from), + workspace_layer: cfg.workspace_layer.and_then(WorkspaceLayerBar::try_from), + locked_container: cfg.locked_container.and_then(LockedContainerBar::try_from), + configuration_switcher, + } + } +} + +#[derive(Clone, Debug)] +pub struct Komorebi { + pub monitor_info: Rc>, + pub workspaces: Option, + pub layout: Option, + pub focused_container: Option, + pub workspace_layer: Option, + pub locked_container: Option, + pub configuration_switcher: Option, +} + +impl BarWidget for Komorebi { + fn render(&mut self, ctx: &Context, ui: &mut Ui, config: &mut RenderConfig) { + self.render_workspaces(ctx, ui, config); + self.render_workspace_layer(ctx, ui, config); + self.render_layout(ctx, ui, config); + self.render_config_switcher(ui, config); + self.render_locked_container(ctx, ui, config); + self.render_focused_container(ctx, ui, config); + } +} + +impl Komorebi { + /// Renders the workspace bar for the current monitor. + /// Updates the focused workspace when a workspace is clicked. + fn render_workspaces(&mut self, ctx: &Context, ui: &mut Ui, config: &mut RenderConfig) { + let monitor_info = &mut *self.monitor_info.borrow_mut(); + + let bar = match &mut self.workspaces { + Some(wg) if !monitor_info.workspaces.is_empty() => wg, + _ => return, + }; + + bar.text_size = Vec2::splat(config.text_font_id.size); + bar.icon_size = Vec2::splat(config.icon_font_id.size); + + config.apply_on_widget(false, ui, |ui| { + for (index, workspace) in monitor_info.workspaces.iter().enumerate() { + if !workspace.should_show { + continue; + } + + let response = SelectableFrame::new(workspace.is_selected) + .show(ui, |ui| (bar.renderer)(bar, ctx, ui, workspace)); + + if response.clicked() { + let message = FocusMonitorWorkspaceNumber(monitor_info.monitor_index, index); + if Self::send_with_mouse_follow_off(monitor_info, message).is_ok() { + monitor_info.focused_workspace_idx = Some(index); + } + } + } + }); + } + + /// Renders the workspace layer bar for the current monitor. + /// Handles user clicks to toggle the workspace layer. + fn render_workspace_layer(&mut self, ctx: &Context, ui: &mut Ui, config: &mut RenderConfig) { + let Some(bar) = &self.workspace_layer else { + return; + }; + + let monitor_info = &*self.monitor_info.borrow(); + let Some(layer) = monitor_info.focused_workspace_layer() else { + return; + }; + + if (matches!(layer, WorkspaceLayer::Floating) + || bar.show_when_tiling && matches!(layer, WorkspaceLayer::Tiling)) + { + let size = Vec2::splat(config.icon_font_id.size); + config.apply_on_widget(false, ui, |ui| { + let layer_frame = SelectableFrame::new(false) + .show(ui, |ui| (bar.renderer)(ctx, ui, &layer, size)) + .on_hover_text(layer.to_string()); + + if layer_frame.clicked() { + let _ = Self::send_messages(&[ + FocusMonitorAtCursor, + MouseFollowsFocus(false), + ToggleWorkspaceLayer, + MouseFollowsFocus(monitor_info.mouse_follows_focus), + ]); + } + }); + } + } + + /// Renders the configuration switcher bar. + /// For each available configuration, displays a selectable label. + /// On click, sends a message to replace the current Komorebi configuration. + fn render_config_switcher(&mut self, ui: &mut Ui, config: &mut RenderConfig) { + let configuration_switcher = match &self.configuration_switcher { + Some(config) if config.enable => config, + _ => return, + }; + for (name, location) in configuration_switcher.configurations.iter() { + let path = Path::new(location); + if path.is_file() { + config.apply_on_widget(false, ui, |ui| { + let response = SelectableFrame::new(false) + .show(ui, |ui| ui.add(Label::new(name).selectable(false))); + if response.clicked() { + let path = dunce::canonicalize(path).unwrap_or_else(|_| path.to_owned()); + let _ = Self::send_messages(&[ReplaceConfiguration(path)]); + } + }); + } + } + } + + fn render_layout(&mut self, ctx: &Context, ui: &mut Ui, config: &mut RenderConfig) { + if let Some(layout_config) = &self.layout + && layout_config.enable + { + let monitor_info = &mut *self.monitor_info.borrow_mut(); + let workspace_idx = monitor_info.focused_workspace_idx; + monitor_info + .layout + .show(ctx, ui, config, layout_config, workspace_idx); + } + } + + /// Renders the locked container bar for the current monitor. + /// + /// Shows lock status and allows toggling the lock state when clicked. + /// Only renders if a focused container exists and either the container is locked + /// or `show_when_unlocked` is enabled in the bar configuration. + fn render_locked_container(&mut self, ctx: &Context, ui: &mut Ui, config: &mut RenderConfig) { + let Some(bar) = &self.locked_container else { + return; + }; + + let monitor_info = &*self.monitor_info.borrow(); + let is_locked = monitor_info + .focused_container() + .map(|container| container.is_locked) + .unwrap_or_default(); + + let (icon_font, txt_font) = (config.icon_font_id.clone(), config.text_font_id.clone()); + if (bar.show_when_unlocked || is_locked) && monitor_info.focused_container().is_some() { + config.apply_on_widget(false, ui, |ui| { + SelectableFrame::new(false) + .show(ui, |ui| { + (bar.renderer)(ctx, ui, is_locked, icon_font, txt_font) + }) + .clicked() + .then(|| Self::send_messages(&[FocusMonitorAtCursor, ToggleLock])); + }); + } + } + + fn render_focused_container(&mut self, ctx: &Context, ui: &mut Ui, config: &mut RenderConfig) { + let Some(bar) = &self.focused_container else { + return; + }; + let monitor_info = &*self.monitor_info.borrow(); + let Some(container) = monitor_info.focused_container() else { + return; + }; + config.apply_on_widget(false, ui, |ui| { + let (len, focused_idx) = (container.windows.len(), container.focused_window_idx); + + for (idx, window) in container.windows.iter().enumerate() { + let selected = idx == focused_idx && len != 1; + let text_color = if selected { + ctx.style().visuals.selection.stroke.color + } else { + ui.style().visuals.text_color() + }; + + let response = SelectableFrame::new(selected).show(ui, |ui| { + (bar.renderer)(bar, ctx, ui, window, text_color, idx == focused_idx) + }); + + if response.clicked() && !selected { + let _ = Self::send_with_mouse_follow_off(monitor_info, FocusStackWindow(idx)); + } + } + }); + } + + /// Sends a message to Komorebi, temporarily disabling MouseFollowsFocus if it's enabled. + fn send_with_mouse_follow_off(monitor: &MonitorInfo, message: SocketMessage) -> IoResult<()> { + let messages: &[SocketMessage] = if monitor.mouse_follows_focus { + &[MouseFollowsFocus(false), message, MouseFollowsFocus(true)] + } else { + &[message] + }; + Self::send_messages(messages) + } + + /// Sends a batch of messages to Komorebi, logging errors on failure. + fn send_messages(messages: &[SocketMessage]) -> IoResult<()> { + komorebi_client::send_batch(messages).map_err(|err| { + tracing::error!("Failed to send message(s): {:?}\nError: {}", messages, err); + err + }) + } +} + +/// Workspace bar with a pre-selected render strategy for efficient +/// workspace display +#[derive(Clone, Debug)] +pub struct WorkspacesBar { + /// Chosen rendering function for this widget + renderer: fn(&Self, &Context, &mut Ui, &WorkspaceInfo), + /// Text size (default: 12.5) + text_size: Vec2, + /// Icon size (default: 12.5 * 1.4) + icon_size: Vec2, +} + +impl WorkspacesBar { + /// Creates a `WorkspacesBar` instance from a workspace configuration. + /// + /// Selects a render strategy based on the given display format + /// for optimal performance. Returns `None` if the widget is disabled. + fn try_from(value: KomorebiWorkspacesConfig) -> Option { + use WorkspacesDisplayFormat::*; + if !value.enable { + return None; + } + // Selects a render strategy according to the workspace config's display format + // for better performance + let renderer: fn(&Self, &Context, &mut Ui, &WorkspaceInfo) = + match value.display.unwrap_or(DisplayFormat::Text.into()) { + // 1: Show icons if any, fallback if none | Only hover workspace name + AllIcons | Existing(DisplayFormat::Icon) => |bar, ctx, ui, ws| { + bar.show_icons(ctx, ui, ws) + .unwrap_or_else(|| bar.show_fallback_icon(ctx, ui, ws)) + .on_hover_text(&ws.name); + }, + // 2: Show icons, with no fallback | Label workspace name (no hover) + AllIconsAndText | Existing(DisplayFormat::IconAndText) => |bar, ctx, ui, ws| { + bar.show_icons(ctx, ui, ws); + Self::show_label(ctx, ui, ws); + }, + // 3: Show icons, fallback if no icons and not selected | Label workspace name if selected else hover + AllIconsAndTextOnSelected | Existing(DisplayFormat::IconAndTextOnSelected) => { + |bar, ctx, ui, ws| { + if bar.show_icons(ctx, ui, ws).is_none() && !ws.is_selected { + bar.show_fallback_icon(ctx, ui, ws); + } + if ws.is_selected { + Self::show_label(ctx, ui, ws); + } else { + ui.response().on_hover_text(&ws.name); + } + } + } + // 4: Show icons if selected and has icons (no fallback) | Label workspace name + Existing(DisplayFormat::TextAndIconOnSelected) => |bar, ctx, ui, ws| { + if ws.is_selected { + bar.show_icons(ctx, ui, ws); + } + Self::show_label(ctx, ui, ws); + }, + // 5: Never show icon (no icons at all) | Label workspace name always + Existing(DisplayFormat::Text) => |_, ctx, ui, ws| { + Self::show_label(ctx, ui, ws); + }, + }; + + Some(Self { + renderer, + icon_size: Vec2::splat(12.5), + text_size: Vec2::splat(12.5 * 1.4), + }) + } + + /// Draws all window icons for the workspace, using larger size for the focused container. + /// Returns response if icons exist, or None. + fn show_icons(&self, ctx: &Context, ui: &mut Ui, ws: &WorkspaceInfo) -> Option { + ws.has_icons.then(|| { + Frame::NONE + .inner_margin(Margin::same(ui.style().spacing.button_padding.y as i8)) + .show(ui, |ui| { + for container in &ws.containers { + for icon in container.windows.iter().filter_map(|win| win.icon.as_ref()) { + ui.add( + Image::from(&icon.texture(ctx)) + .maintain_aspect_ratio(true) + .fit_to_exact_size(if container.is_focused { + self.icon_size + } else { + self.text_size + }), + ); + } + } + }) + .response + }) + } + + /// Draws a fallback icon (a rectangle with a diagonal) for the workspace. + fn show_fallback_icon(&self, ctx: &Context, ui: &mut Ui, ws: &WorkspaceInfo) -> Response { + let (response, painter) = ui.allocate_painter(self.icon_size, Sense::hover()); + let stroke: Stroke = Stroke::new( + 1.0, + if ws.is_selected { + ctx.style().visuals.selection.stroke.color + } else { + ui.style().visuals.text_color() + }, + ); + let mut rect = response.rect; + let rounding = CornerRadius::same((rect.width() * 0.1) as u8); + rect = rect.shrink(stroke.width); + let c = rect.center(); + let r = rect.width() / 2.0; + painter.rect_stroke(rect, rounding, stroke, StrokeKind::Outside); + painter.line_segment([c - vec2(r, r), c + vec2(r, r)], stroke); + response + } + + /// Shows the workspace label (colored if selected). + fn show_label(ctx: &Context, ui: &mut Ui, ws: &WorkspaceInfo) -> Response { + if ws.is_selected { + let text = RichText::new(&ws.name).color(ctx.style().visuals.selection.stroke.color); + ui.add(Label::new(text).selectable(false)) + } else { + ui.add(Label::new(&ws.name).selectable(false)) + } + } +} + +/// Structure for displaying the focused container's windows in the bar. +/// Uses a pre-selected rendering strategy (based on config) for efficient display +#[derive(Clone, Debug)] +pub struct FocusedContainerBar { + /// Chosen rendering function for this widget + renderer: fn(&Self, &Context, &mut Ui, &WindowInfo, Color32, focused: bool), + /// Icon size (default: 12.5 * 1.4) + icon_size: Vec2, +} + +impl FocusedContainerBar { + /// Creates a `FocusedContainerBar` from the given configuration. + /// + /// Selects a render strategy based on the display format or legacy icon setting. + /// Returns `None` if the widget is disabled. + fn try_from(value: KomorebiFocusedContainerConfig) -> Option { + if !value.enable { + return None; + } + // Handle legacy setting - convert show_icon to display format + let format = value + .display + .unwrap_or(if value.show_icon.unwrap_or(false) { + IconAndText + } else { + Text + }); + + // Select renderer strategy based on display format for better performance + let renderer: fn(&FocusedContainerBar, &Context, &mut Ui, &WindowInfo, Color32, bool) = + match format { + Icon => |_self, ctx, ui, info, _color, _focused| { + FocusedContainerBar::show_icon::(_self, ctx, ui, info); + }, + Text => |_self, _ctx, ui, info, color, _focused| { + FocusedContainerBar::show_title(_self, ui, info, color); + }, + IconAndText => |_self, ctx, ui, info, color, _focused| { + FocusedContainerBar::show_icon::(_self, ctx, ui, info); + FocusedContainerBar::show_title(_self, ui, info, color); + }, + IconAndTextOnSelected => |_self, ctx, ui, info, color, focused| { + FocusedContainerBar::show_icon::(_self, ctx, ui, info); + if focused { + FocusedContainerBar::show_title(_self, ui, info, color); + } + }, + TextAndIconOnSelected => |_self, ctx, ui, info, color, focused| { + if focused { + FocusedContainerBar::show_icon::(_self, ctx, ui, info); + } + FocusedContainerBar::show_title(_self, ui, info, color); + }, + }; + + Some(FocusedContainerBar { + renderer, + icon_size: Vec2::splat(12.5 * 1.4), + }) + } + + /// Draws window icon(s) at configured size; adds hover text if HOVEL is true. + fn show_icon(&self, ctx: &Context, ui: &mut Ui, info: &WindowInfo) { + let inner_response = Frame::NONE + .inner_margin(Margin::same(ui.style().spacing.button_padding.y as i8)) + .show(ui, |ui| { + for icon in info.icon.iter() { + let img = Image::from(&icon.texture(ctx)).maintain_aspect_ratio(true); + ui.add(img.fit_to_exact_size(self.icon_size)); + } + }); + if HOVEL && let Some(title) = &info.title { + inner_response.response.on_hover_text(title); + } + } + + /// Renders the window title label in color, truncating if needed. + fn show_title(&self, ui: &mut Ui, info: &WindowInfo, color: Color32) { + if let Some(title) = &info.title { + let text = Label::new(RichText::new(title).color(color)).selectable(false); + + let x = MAX_LABEL_WIDTH.load(Ordering::SeqCst) as f32; + let y = ui.available_height(); + CustomUi(ui).add_sized_left_to_right(Vec2::new(x, y), text.truncate()); + } + } +} + +/// Workspace layer bar with a pre-selected render strategy for efficient +/// layer display +#[derive(Clone, Debug)] +pub struct WorkspaceLayerBar { + /// Show the widget even if the layer is Tiling + show_when_tiling: bool, + /// Chosen rendering function for this widget + renderer: fn(&Context, &mut Ui, &WorkspaceLayer, Vec2), +} + +impl WorkspaceLayerBar { + /// Creates a `WorkspaceLayerBar` from the given configuration. + /// + /// Selects a render strategy based on the display format. + /// Returns `None` if the widget is disabled. + fn try_from(value: KomorebiWorkspaceLayerConfig) -> Option { + if !value.enable { + return None; + } + let display_format = value.display.unwrap_or(Text); + + // Select renderer strategy based on display format for better performance + let renderer: fn(&Context, &mut Ui, &WorkspaceLayer, Vec2) = match display_format { + Icon => Self::draw_layer_icon, + Text => |_ctx, ui, layer, _size| { + ui.add(Label::new(layer.to_string()).selectable(false)); + }, + _ => |ctx, ui, layer, size| { + Self::draw_layer_icon(ctx, ui, layer, size); + ui.add(Label::new(layer.to_string()).selectable(false)); + }, + }; + + Some(Self { + show_when_tiling: value.show_when_tiling.unwrap_or_default(), + renderer, + }) + } + + /// Draws an icon representing the current workspace layer. + fn draw_layer_icon(ctx: &Context, ui: &mut Ui, layer: &WorkspaceLayer, size: Vec2) { + if matches!(layer, WorkspaceLayer::Tiling) { + let (response, painter) = ui.allocate_painter(size, Sense::hover()); + let color = ctx.style().visuals.selection.stroke.color; + let stroke = Stroke::new(1.0, color); + let mut rect = response.rect; + let corner = CornerRadius::same((rect.width() * 0.1) as u8); + rect = rect.shrink(stroke.width); + + // tiling + let mut rect_left = response.rect; + rect_left.set_width(rect.width() * 0.48); + rect_left.set_height(rect.height() * 0.98); + let mut rect_right = rect_left; + rect_left = rect_left.translate(Vec2::new( + rect.width() * 0.01 + stroke.width, + rect.width() * 0.01 + stroke.width, + )); + rect_right = rect_right.translate(Vec2::new( + rect.width() * 0.51 + stroke.width, + rect.width() * 0.01 + stroke.width, + )); + painter.rect_filled(rect_left, corner, color); + painter.rect_stroke(rect_right, corner, stroke, StrokeKind::Outside); + } else { + let (response, painter) = ui.allocate_painter(size, Sense::hover()); + let color = ctx.style().visuals.selection.stroke.color; + let stroke = Stroke::new(1.0, color); + let mut rect = response.rect; + let corner = CornerRadius::same((rect.width() * 0.1) as u8); + rect = rect.shrink(stroke.width); + + // floating + let mut rect_left = response.rect; + rect_left.set_width(rect.width() * 0.65); + rect_left.set_height(rect.height() * 0.65); + let mut rect_right = rect_left; + rect_left = rect_left.translate(Vec2::new( + rect.width() * 0.01 + stroke.width, + rect.width() * 0.01 + stroke.width, + )); + rect_right = rect_right.translate(Vec2::new( + rect.width() * 0.34 + stroke.width, + rect.width() * 0.34 + stroke.width, + )); + painter.rect_filled(rect_left, corner, color); + painter.rect_stroke(rect_right, corner, stroke, StrokeKind::Outside); + } + } +} + +/// Locked container bar for displaying and interacting with container lock state +#[derive(Clone, Debug)] +pub struct LockedContainerBar { + /// Show the widget even when unlocked + show_when_unlocked: bool, + /// Chosen rendering function for this widget + renderer: fn(&Context, &mut Ui, bool, FontId, FontId), +} + +impl LockedContainerBar { + /// Creates a `LockedContainerBar` from the given configuration. + /// + /// Selects a render strategy based on the display format. + /// Returns `None` if the widget is disabled. + fn try_from(value: KomorebiLockedContainerConfig) -> Option { + if !value.enable { + return None; + } + let display_format = value.display.unwrap_or(DisplayFormat::Text); + + // Select renderer strategy based on display format for better performance + let renderer: fn(&Context, &mut Ui, bool, FontId, FontId) = match display_format { + DisplayFormat::Icon => |ctx, ui, is_locked, icon_font, _txt_font| { + let layout_job = Self::icon_layout(ctx, is_locked, icon_font); + ui.add(Label::new(layout_job).selectable(false)); + }, + DisplayFormat::Text => |ctx, ui, is_locked, _icon_font, txt_font| { + let mut layout_job = LayoutJob::default(); + Self::append_text(&mut layout_job, ctx, is_locked, txt_font); + ui.add(Label::new(layout_job).selectable(false)); + }, + _ => |ctx, ui: &mut Ui, is_locked, icon_font, txt_font| { + let mut layout_job = Self::icon_layout(ctx, is_locked, icon_font); + Self::append_text(&mut layout_job, ctx, is_locked, txt_font); + ui.add(Label::new(layout_job).selectable(false)); + }, + }; + + Some(Self { + show_when_unlocked: value.show_when_unlocked.unwrap_or_default(), + renderer, + }) + } + + /// Builds a layout job for the lock/unlock icon, + /// using the provided font and current lock state. + fn icon_layout(ctx: &Context, is_locked: bool, icon_font: FontId) -> LayoutJob { + LayoutJob::simple( + if is_locked { + egui_phosphor::regular::LOCK_KEY.to_string() + } else { + egui_phosphor::regular::LOCK_SIMPLE_OPEN.to_string() + }, + icon_font, + ctx.style().visuals.selection.stroke.color, + 100.0, + ) + } + + /// Appends lock/unlock status text to the given layout job, + /// using the specified font and current lock state. + fn append_text(job: &mut LayoutJob, ctx: &Context, is_locked: bool, txt_font: FontId) { + job.append( + if is_locked { "Locked" } else { "Unlocked" }, + 10.0, + TextFormat { + font_id: txt_font, + color: ctx.style().visuals.text_color(), + valign: Align::Center, + ..Default::default() + }, + ) + } +} + +/// Represents the full state of a single monitor for the Komorebi bar/UI. +/// +/// Includes all workspaces, containers, windows, layout, focus, +/// display options, and monitor indices. Used to render the current monitor +/// state in UI widgets. +/// +/// Updated whenever Komorebi state changes. +#[derive(Clone, Debug)] +pub struct MonitorInfo { + pub workspaces: Vec, + pub layout: KomorebiLayout, + pub mouse_follows_focus: bool, + pub work_area_offset: Option, + pub monitor_index: usize, + pub monitor_usr_idx_map: HashMap, + pub focused_workspace_idx: Option, + pub show_all_icons: bool, + pub hide_empty_workspaces: bool, +} + +impl Default for MonitorInfo { + fn default() -> Self { + Self { + workspaces: Vec::new(), + layout: KomorebiLayout::Default(komorebi_client::DefaultLayout::BSP), + mouse_follows_focus: true, + work_area_offset: None, + monitor_index: MONITOR_INDEX.load(Ordering::SeqCst), + monitor_usr_idx_map: HashMap::new(), + focused_workspace_idx: None, + show_all_icons: false, + hide_empty_workspaces: false, + } + } +} + +impl MonitorInfo { + /// Returns a reference to the currently focused workspace, if any. + pub fn focused_workspace(&self) -> Option<&WorkspaceInfo> { + self.workspaces.get(self.focused_workspace_idx?) + } + + /// Returns the layer of the focused workspace, if available. + pub fn focused_workspace_layer(&self) -> Option { + self.focused_workspace().map(|ws| ws.layer) + } + + /// Returns the focused container within the focused workspace, if any. + pub fn focused_container(&self) -> Option<&ContainerInfo> { + self.focused_workspace() + .and_then(WorkspaceInfo::focused_container) + } +} + +impl MonitorInfo { + pub fn update_from_self(&mut self, config: &Self) { + self.hide_empty_workspaces = config.hide_empty_workspaces; + } + + /// Updates monitor state from the given State, setting all fields based on the selected + /// monitor and its workspaces + pub fn update(&mut self, monitor_index: Option, state: State, show_all_icons: bool) { + self.show_all_icons = show_all_icons; + self.monitor_usr_idx_map = state.monitor_usr_idx_map; + + match monitor_index { + Some(idx) if idx < state.monitors.elements().len() => self.monitor_index = idx, + // The bar's monitor is diconnected, so the bar is disabled no need to check anything + // any further otherwise we'll get `OutOfBounds` panics. + _ => return, + }; + self.mouse_follows_focus = state.mouse_follows_focus; + + let monitor = &state.monitors.elements()[self.monitor_index]; + self.work_area_offset = monitor.work_area_offset; + self.focused_workspace_idx = Some(monitor.focused_workspace_idx()); + + // Layout + let focused_ws = &monitor.workspaces()[monitor.focused_workspace_idx()]; + self.layout = Self::resolve_layout(focused_ws, state.is_paused); + + self.workspaces.clear(); + self.workspaces.extend(Self::workspaces( + self.show_all_icons, + self.hide_empty_workspaces, + self.focused_workspace_idx, + monitor.workspaces().iter().enumerate(), + )); + } + + /// Builds an iterator of WorkspaceInfo for the monitor. + fn workspaces<'a, I>( + show_all_icons: bool, + hide_empty_ws: bool, + focused_ws_idx: Option, + iter: I, + ) -> impl Iterator + 'a + where + I: Iterator + 'a, + { + let fn_containers_from = if show_all_icons { + |ws| ContainerInfo::from_all_containers(ws) + } else { + |ws| { + ContainerInfo::from_focused_container(ws) + .into_iter() + .collect() + } + }; + iter.map(move |(index, ws)| { + let containers = fn_containers_from(ws); + WorkspaceInfo { + name: ws + .name + .to_owned() + .unwrap_or_else(|| format!("{}", index + 1)), + focused_container_idx: containers.iter().position(|c| c.is_focused), + has_icons: containers + .iter() + .any(|container| container.windows.iter().any(|window| window.icon.is_some())), + containers, + layer: ws.layer, + should_show: !hide_empty_ws || focused_ws_idx == Some(index) || !ws.is_empty(), + is_selected: focused_ws_idx == Some(index), + } + }) + } + + /// Determines the current layout of the focused workspace + fn resolve_layout(focused_ws: &Workspace, is_paused: bool) -> KomorebiLayout { + if focused_ws.monocle_container.is_some() { + KomorebiLayout::Monocle + } else if !focused_ws.tile { + KomorebiLayout::Floating + } else if is_paused { + KomorebiLayout::Paused + } else { + match focused_ws.layout { + komorebi_client::Layout::Default(layout) => KomorebiLayout::Default(layout), + } + } + } +} + +/// Describes the state of a single workspace on a monitor. +/// +/// Contains the workspace name, its containers (tiled, floating, +/// monocle), focus state, layer (tiling/floating), and display +/// flags for UI rendering. +#[derive(Clone, Debug)] +pub struct WorkspaceInfo { + pub name: String, + pub containers: Vec, + pub focused_container_idx: Option, + pub layer: WorkspaceLayer, + pub should_show: bool, + pub is_selected: bool, + pub has_icons: bool, +} + +impl WorkspaceInfo { + /// Returns a reference to the focused container in this workspace, if any. + pub fn focused_container(&self) -> Option<&ContainerInfo> { + self.containers.get(self.focused_container_idx?) + } +} + +/// Holds information about a window container (tiled, floating, or monocle) +/// within a workspace. +/// +/// Includes a list of windows, the focused window index, and flags for focus +/// and lock status. +#[derive(Clone, Debug)] +pub struct ContainerInfo { + pub windows: Vec, + pub focused_window_idx: usize, + pub is_focused: bool, + pub is_locked: bool, +} + +impl ContainerInfo { + /// Returns all containers for the given workspace in the following order: + /// + /// 1. The monocle container (if present) is included first. + /// 2. All tiled containers are included next. + /// 3. All floating windows are added last, each as a separate container. + /// + /// Function ensures only one container is marked as focused, prioritizing + /// floating → monocle → tiled. + pub fn from_all_containers(ws: &Workspace) -> Vec { + let has_focused_float = ws.floating_windows().iter().any(|w| w.is_focused()); + + // Monocle container first if present + let monocle = ws + .monocle_container + .as_ref() + .map(|c| Self::from_container(c, !has_focused_float)); + + // All tiled containers, focus only if there's no monocle/focused float + let has_focused_monocle_or_float = has_focused_float || monocle.is_some(); + let tiled = ws.containers().iter().enumerate().map(|(i, c)| { + let is_focused = !has_focused_monocle_or_float && i == ws.focused_container_idx(); + Self::from_container(c, is_focused) + }); + + // All floating windows + let floats = ws.floating_windows().iter().map(Self::from_window); + // All windows + monocle.into_iter().chain(tiled).chain(floats).collect() + } + + /// Creates a `ContainerInfo` for the currently focused item in the workspace. + /// + /// The function checks focus in the following order: + /// 1. Focused floating window + /// 2. Monocle container + /// 3. Focused tiled container + pub fn from_focused_container(ws: &Workspace) -> Option { + if let Some(window) = ws.floating_windows().iter().find(|w| w.is_focused()) { + return Some(Self::from_window(window)); + } + if let Some(container) = &ws.monocle_container { + Some(Self::from_container(container, true)) + } else { + ws.focused_container() + .map(|container| Self::from_container(container, true)) + } + } + + /// Creates a `ContainerInfo` from a given container. + pub fn from_container(container: &Container, is_focused: bool) -> Self { + Self { + windows: container.windows().iter().map(WindowInfo::from).collect(), + focused_window_idx: container.focused_window_idx(), + is_focused, + is_locked: container.locked, + } + } + + /// Creates a `ContainerInfo` from a single floating window. + /// The window becomes the only entry in `windows`, is marked as focused + /// if applicable, and `is_locked` is set to false. + pub fn from_window(window: &Window) -> Self { + Self { + windows: vec![window.into()], + focused_window_idx: 0, + is_focused: window.is_focused(), + is_locked: false, // locked is only container feature + } + } +} + +/// Stores basic information about a single window in a container. +/// Contains the window's title and its icon, if available. +#[derive(Clone, Debug)] +pub struct WindowInfo { + pub title: Option, + pub icon: Option, +} + +impl From<&Window> for WindowInfo { + fn from(value: &Window) -> Self { + Self { + title: value.title(), + icon: None, + // icon: ImageIcon::try_load(value.hwnd, || { + // windows_icons::get_icon_by_hwnd(value.hwnd) + // .or_else(|| windows_icons_fallback::get_icon_by_process_id(value.process_id())) + // }), + } + } +} diff --git a/komorebi-bar/src/widgets/komorebi_layout.rs b/komorebi-bar/src/widgets/komorebi_layout.rs new file mode 100644 index 00000000..85bc9388 --- /dev/null +++ b/komorebi-bar/src/widgets/komorebi_layout.rs @@ -0,0 +1,323 @@ +use crate::config::DisplayFormat; +use crate::render::RenderConfig; +use crate::selected_frame::SelectableFrame; +use crate::widgets::komorebi::KomorebiLayoutConfig; +use eframe::egui::Context; +use eframe::egui::CornerRadius; +use eframe::egui::FontId; +use eframe::egui::Frame; +use eframe::egui::Label; +use eframe::egui::Sense; +use eframe::egui::Stroke; +use eframe::egui::StrokeKind; +use eframe::egui::Ui; +use eframe::egui::Vec2; +use eframe::egui::vec2; +use komorebi_client::SocketMessage; +use serde::Deserialize; +use serde::Deserializer; +use serde::Serialize; +use serde::de::Error; +use serde_json::from_str; +use std::fmt::Display; +use std::fmt::Formatter; + +#[derive(Copy, Clone, Debug, Serialize, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[serde(untagged)] +pub enum KomorebiLayout { + Default(komorebi_client::DefaultLayout), + Monocle, + Floating, + Paused, + Custom, +} + +impl<'de> Deserialize<'de> for KomorebiLayout { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let s: String = String::deserialize(deserializer)?; + + // Attempt to deserialize the string as a DefaultLayout + if let Ok(default_layout) = from_str::(&format!("\"{s}\"")) + { + return Ok(KomorebiLayout::Default(default_layout)); + } + + // Handle other cases + match s.as_str() { + "Monocle" => Ok(KomorebiLayout::Monocle), + "Floating" => Ok(KomorebiLayout::Floating), + "Paused" => Ok(KomorebiLayout::Paused), + "Custom" => Ok(KomorebiLayout::Custom), + _ => Err(Error::custom(format!("Invalid layout: {s}"))), + } + } +} + +impl Display for KomorebiLayout { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + match self { + KomorebiLayout::Default(layout) => write!(f, "{layout}"), + KomorebiLayout::Monocle => write!(f, "Monocle"), + KomorebiLayout::Floating => write!(f, "Floating"), + KomorebiLayout::Paused => write!(f, "Paused"), + KomorebiLayout::Custom => write!(f, "Custom"), + } + } +} + +impl KomorebiLayout { + fn is_default(&mut self) -> bool { + matches!(self, KomorebiLayout::Default(_)) + } + + fn on_click( + &mut self, + show_options: &bool, + monitor_idx: usize, + workspace_idx: Option, + ) -> bool { + if self.is_default() { + !show_options + } else { + self.on_click_option(monitor_idx, workspace_idx); + false + } + } + + fn on_click_option(&mut self, monitor_idx: usize, workspace_idx: Option) { + match self { + KomorebiLayout::Default(option) => { + if let Some(ws_idx) = workspace_idx + && komorebi_client::send_message(&SocketMessage::WorkspaceLayout( + monitor_idx, + ws_idx, + *option, + )) + .is_err() + { + tracing::error!("could not send message to komorebi: WorkspaceLayout"); + } + } + KomorebiLayout::Monocle => { + if komorebi_client::send_batch([ + SocketMessage::FocusMonitorAtCursor, + SocketMessage::ToggleMonocle, + ]) + .is_err() + { + tracing::error!("could not send message to komorebi: ToggleMonocle"); + } + } + KomorebiLayout::Floating => { + if komorebi_client::send_batch([ + SocketMessage::FocusMonitorAtCursor, + SocketMessage::ToggleTiling, + ]) + .is_err() + { + tracing::error!("could not send message to komorebi: ToggleTiling"); + } + } + KomorebiLayout::Paused => { + if komorebi_client::send_message(&SocketMessage::TogglePause).is_err() { + tracing::error!("could not send message to komorebi: TogglePause"); + } + } + KomorebiLayout::Custom => {} + } + } + + fn show_icon(&mut self, is_selected: bool, font_id: FontId, ctx: &Context, ui: &mut Ui) { + // paint custom icons for the layout + let size = Vec2::splat(font_id.size); + let (response, painter) = ui.allocate_painter(size, Sense::hover()); + let color = if is_selected { + ctx.style().visuals.selection.stroke.color + } else { + ui.style().visuals.text_color() + }; + let stroke = Stroke::new(1.0, color); + let mut rect = response.rect; + let rounding = CornerRadius::same((rect.width() * 0.1) as u8); + rect = rect.shrink(stroke.width); + let c = rect.center(); + let r = rect.width() / 2.0; + painter.rect_stroke(rect, rounding, stroke, StrokeKind::Outside); + + match self { + KomorebiLayout::Default(layout) => match layout { + komorebi_client::DefaultLayout::BSP => { + painter.line_segment([c - vec2(0.0, r), c + vec2(0.0, r)], stroke); + painter.line_segment([c, c + vec2(r, 0.0)], stroke); + painter.line_segment([c + vec2(r / 2.0, 0.0), c + vec2(r / 2.0, r)], stroke); + } + komorebi_client::DefaultLayout::Columns => { + painter.line_segment([c - vec2(r / 2.0, r), c + vec2(-r / 2.0, r)], stroke); + painter.line_segment([c - vec2(0.0, r), c + vec2(0.0, r)], stroke); + painter.line_segment([c - vec2(-r / 2.0, r), c + vec2(r / 2.0, r)], stroke); + } + komorebi_client::DefaultLayout::Rows => { + painter.line_segment([c - vec2(r, r / 2.0), c + vec2(r, -r / 2.0)], stroke); + painter.line_segment([c - vec2(r, 0.0), c + vec2(r, 0.0)], stroke); + painter.line_segment([c - vec2(r, -r / 2.0), c + vec2(r, r / 2.0)], stroke); + } + komorebi_client::DefaultLayout::VerticalStack => { + painter.line_segment([c - vec2(0.0, r), c + vec2(0.0, r)], stroke); + painter.line_segment([c, c + vec2(r, 0.0)], stroke); + } + komorebi_client::DefaultLayout::RightMainVerticalStack => { + painter.line_segment([c - vec2(0.0, r), c + vec2(0.0, r)], stroke); + painter.line_segment([c - vec2(r, 0.0), c], stroke); + } + komorebi_client::DefaultLayout::HorizontalStack => { + painter.line_segment([c - vec2(r, 0.0), c + vec2(r, 0.0)], stroke); + painter.line_segment([c, c + vec2(0.0, r)], stroke); + } + komorebi_client::DefaultLayout::UltrawideVerticalStack => { + painter.line_segment([c - vec2(r / 2.0, r), c + vec2(-r / 2.0, r)], stroke); + painter.line_segment([c + vec2(r / 2.0, 0.0), c + vec2(r, 0.0)], stroke); + painter.line_segment([c - vec2(-r / 2.0, r), c + vec2(r / 2.0, r)], stroke); + } + komorebi_client::DefaultLayout::Grid => { + painter.line_segment([c - vec2(r, 0.0), c + vec2(r, 0.0)], stroke); + painter.line_segment([c - vec2(0.0, r), c + vec2(0.0, r)], stroke); + } + // TODO: @CtByte can you think of a nice icon to draw here? + komorebi_client::DefaultLayout::Scrolling => { + painter.line_segment([c - vec2(r / 2.0, r), c + vec2(-r / 2.0, r)], stroke); + painter.line_segment([c - vec2(0.0, r), c + vec2(0.0, r)], stroke); + painter.line_segment([c - vec2(-r / 2.0, r), c + vec2(r / 2.0, r)], stroke); + } + }, + KomorebiLayout::Monocle => {} + KomorebiLayout::Floating => { + let mut rect_left = response.rect; + rect_left.set_width(rect.width() * 0.5); + rect_left.set_height(rect.height() * 0.5); + let mut rect_right = rect_left; + rect_left = rect_left.translate(Vec2::new( + rect.width() * 0.1 + stroke.width, + rect.width() * 0.1 + stroke.width, + )); + rect_right = rect_right.translate(Vec2::new( + rect.width() * 0.35 + stroke.width, + rect.width() * 0.35 + stroke.width, + )); + painter.rect_filled(rect_left, rounding, color); + painter.rect_stroke(rect_right, rounding, stroke, StrokeKind::Outside); + } + KomorebiLayout::Paused => { + let mut rect_left = response.rect; + rect_left.set_width(rect.width() * 0.25); + rect_left.set_height(rect.height() * 0.8); + let mut rect_right = rect_left; + rect_left = rect_left.translate(Vec2::new( + rect.width() * 0.2 + stroke.width, + rect.width() * 0.1 + stroke.width, + )); + rect_right = rect_right.translate(Vec2::new( + rect.width() * 0.55 + stroke.width, + rect.width() * 0.1 + stroke.width, + )); + painter.rect_filled(rect_left, rounding, color); + painter.rect_filled(rect_right, rounding, color); + } + KomorebiLayout::Custom => { + painter.line_segment([c - vec2(0.0, r), c + vec2(0.0, r)], stroke); + painter.line_segment([c + vec2(0.0, r / 2.0), c + vec2(r, r / 2.0)], stroke); + painter.line_segment([c - vec2(0.0, r / 3.0), c - vec2(r, r / 3.0)], stroke); + } + } + } + + pub fn show( + &mut self, + ctx: &Context, + ui: &mut Ui, + render_config: &mut RenderConfig, + layout_config: &KomorebiLayoutConfig, + workspace_idx: Option, + ) { + let monitor_idx = render_config.monitor_idx; + let font_id = render_config.icon_font_id.clone(); + let mut show_options = RenderConfig::load_show_komorebi_layout_options(); + let format = layout_config.display.unwrap_or(DisplayFormat::IconAndText); + + if !self.is_default() { + show_options = false; + } + + render_config.apply_on_widget(false, ui, |ui| { + let layout_frame = SelectableFrame::new(false) + .show(ui, |ui| { + if let DisplayFormat::Icon | DisplayFormat::IconAndText = format { + self.show_icon(true, font_id.clone(), ctx, ui); + } + + if let DisplayFormat::Text | DisplayFormat::IconAndText = format { + ui.add(Label::new(self.to_string()).selectable(false)); + } + }) + .on_hover_text(self.to_string()); + + if layout_frame.clicked() { + show_options = self.on_click(&show_options, monitor_idx, workspace_idx); + } + + if show_options && let Some(workspace_idx) = workspace_idx { + Frame::NONE.show(ui, |ui| { + ui.add( + Label::new(egui_phosphor::regular::ARROW_FAT_LINES_RIGHT.to_string()) + .selectable(false), + ); + + let mut layout_options = layout_config.options.clone().unwrap_or(vec![ + KomorebiLayout::Default(komorebi_client::DefaultLayout::BSP), + KomorebiLayout::Default(komorebi_client::DefaultLayout::Columns), + KomorebiLayout::Default(komorebi_client::DefaultLayout::Rows), + KomorebiLayout::Default(komorebi_client::DefaultLayout::VerticalStack), + KomorebiLayout::Default( + komorebi_client::DefaultLayout::RightMainVerticalStack, + ), + KomorebiLayout::Default(komorebi_client::DefaultLayout::HorizontalStack), + KomorebiLayout::Default( + komorebi_client::DefaultLayout::UltrawideVerticalStack, + ), + KomorebiLayout::Default(komorebi_client::DefaultLayout::Grid), + //KomorebiLayout::Custom, + KomorebiLayout::Monocle, + KomorebiLayout::Floating, + KomorebiLayout::Paused, + ]); + + for layout_option in &mut layout_options { + let is_selected = self == layout_option; + + if SelectableFrame::new(is_selected) + .show(ui, |ui| { + layout_option.show_icon(is_selected, font_id.clone(), ctx, ui) + }) + .on_hover_text(match layout_option { + KomorebiLayout::Default(layout) => layout.to_string(), + KomorebiLayout::Monocle => "Toggle monocle".to_string(), + KomorebiLayout::Floating => "Toggle tiling".to_string(), + KomorebiLayout::Paused => "Toggle pause".to_string(), + KomorebiLayout::Custom => "Custom".to_string(), + }) + .clicked() + { + layout_option.on_click_option(monitor_idx, Some(workspace_idx)); + show_options = false; + }; + } + }); + } + }); + + RenderConfig::store_show_komorebi_layout_options(show_options); + } +} diff --git a/komorebi-bar/src/widgets/media.rs b/komorebi-bar/src/widgets/media.rs new file mode 100644 index 00000000..2428d063 --- /dev/null +++ b/komorebi-bar/src/widgets/media.rs @@ -0,0 +1,122 @@ +use crate::MAX_LABEL_WIDTH; +use crate::render::RenderConfig; +use crate::selected_frame::SelectableFrame; +use crate::ui::CustomUi; +use crate::widgets::widget::BarWidget; +use eframe::egui::Align; +use eframe::egui::Context; +use eframe::egui::Label; +use eframe::egui::TextFormat; +use eframe::egui::Ui; +use eframe::egui::Vec2; +use eframe::egui::text::LayoutJob; +use serde::Deserialize; +use serde::Serialize; +use std::sync::atomic::Ordering; +use windows::Media::Control::GlobalSystemMediaTransportControlsSessionManager; + +#[derive(Copy, Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct MediaConfig { + /// Enable the Media widget + pub enable: bool, +} + +impl From for Media { + fn from(value: MediaConfig) -> Self { + Self::new(value.enable) + } +} + +#[derive(Clone, Debug)] +pub struct Media { + pub enable: bool, + pub session_manager: GlobalSystemMediaTransportControlsSessionManager, +} + +impl Media { + pub fn new(enable: bool) -> Self { + Self { + enable, + session_manager: GlobalSystemMediaTransportControlsSessionManager::RequestAsync() + .unwrap() + .get() + .unwrap(), + } + } + + pub fn toggle(&self) { + if let Ok(session) = self.session_manager.GetCurrentSession() + && let Ok(op) = session.TryTogglePlayPauseAsync() + { + op.get().unwrap_or_default(); + } + } + + fn output(&mut self) -> String { + if let Ok(session) = self.session_manager.GetCurrentSession() + && let Ok(operation) = session.TryGetMediaPropertiesAsync() + && let Ok(properties) = operation.get() + && let (Ok(artist), Ok(title)) = (properties.Artist(), properties.Title()) + { + if artist.is_empty() { + return format!("{title}"); + } + + if title.is_empty() { + return format!("{artist}"); + } + + return format!("{artist} - {title}"); + } + + String::new() + } +} + +impl BarWidget for Media { + fn render(&mut self, ctx: &Context, ui: &mut Ui, config: &mut RenderConfig) { + if self.enable { + let output = self.output(); + if !output.is_empty() { + let mut layout_job = LayoutJob::simple( + egui_phosphor::regular::HEADPHONES.to_string(), + config.icon_font_id.clone(), + ctx.style().visuals.selection.stroke.color, + 100.0, + ); + + layout_job.append( + &output, + 10.0, + TextFormat { + font_id: config.text_font_id.clone(), + color: ctx.style().visuals.text_color(), + valign: Align::Center, + ..Default::default() + }, + ); + + config.apply_on_widget(false, ui, |ui| { + if SelectableFrame::new(false) + .show(ui, |ui| { + let available_height = ui.available_height(); + let mut custom_ui = CustomUi(ui); + + custom_ui.add_sized_left_to_right( + Vec2::new( + MAX_LABEL_WIDTH.load(Ordering::SeqCst) as f32, + available_height, + ), + Label::new(layout_job).selectable(false).truncate(), + ) + }) + .clicked() + { + self.toggle(); + } + }); + } + } + } +} diff --git a/komorebi-bar/src/widgets/memory.rs b/komorebi-bar/src/widgets/memory.rs new file mode 100644 index 00000000..145d8547 --- /dev/null +++ b/komorebi-bar/src/widgets/memory.rs @@ -0,0 +1,137 @@ +use crate::config::LabelPrefix; +use crate::render::RenderConfig; +use crate::selected_frame::SelectableFrame; +use crate::widgets::widget::BarWidget; +use eframe::egui::Align; +use eframe::egui::Context; +use eframe::egui::Label; +use eframe::egui::TextFormat; +use eframe::egui::Ui; +use eframe::egui::text::LayoutJob; +use serde::Deserialize; +use serde::Serialize; +use std::process::Command; +use std::time::Duration; +use std::time::Instant; +use sysinfo::RefreshKind; +use sysinfo::System; + +#[derive(Copy, Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct MemoryConfig { + /// Enable the Memory widget + pub enable: bool, + /// Data refresh interval (default: 10 seconds) + pub data_refresh_interval: Option, + /// Display label prefix + pub label_prefix: Option, + /// Select when the current percentage is over this value [[1-100]] + pub auto_select_over: Option, +} + +impl From for Memory { + fn from(value: MemoryConfig) -> Self { + let data_refresh_interval = value.data_refresh_interval.unwrap_or(10); + + Self { + enable: value.enable, + system: System::new_with_specifics( + RefreshKind::default().without_cpu().without_processes(), + ), + data_refresh_interval, + label_prefix: value.label_prefix.unwrap_or(LabelPrefix::IconAndText), + auto_select_over: value.auto_select_over.map(|o| o.clamp(1, 100)), + last_updated: Instant::now() + .checked_sub(Duration::from_secs(data_refresh_interval)) + .unwrap(), + } + } +} + +#[derive(Clone, Debug)] +struct MemoryOutput { + label: String, + selected: bool, +} + +pub struct Memory { + pub enable: bool, + system: System, + data_refresh_interval: u64, + label_prefix: LabelPrefix, + auto_select_over: Option, + last_updated: Instant, +} + +impl Memory { + fn output(&mut self) -> MemoryOutput { + let now = Instant::now(); + if now.duration_since(self.last_updated) > Duration::from_secs(self.data_refresh_interval) { + self.system.refresh_memory(); + self.last_updated = now; + } + + let used = self.system.used_memory(); + let total = self.system.total_memory(); + let usage = ((used * 100) / total) as u8; + let selected = self.auto_select_over.is_some_and(|o| usage >= o); + + MemoryOutput { + label: match self.label_prefix { + LabelPrefix::Text | LabelPrefix::IconAndText => { + format!("RAM: {usage}%") + } + LabelPrefix::None | LabelPrefix::Icon => format!("{usage}%"), + }, + selected, + } + } +} + +impl BarWidget for Memory { + fn render(&mut self, ctx: &Context, ui: &mut Ui, config: &mut RenderConfig) { + if self.enable { + let output = self.output(); + if !output.label.is_empty() { + let auto_text_color = config.auto_select_text.filter(|_| output.selected); + + let mut layout_job = LayoutJob::simple( + match self.label_prefix { + LabelPrefix::Icon | LabelPrefix::IconAndText => { + egui_phosphor::regular::MEMORY.to_string() + } + LabelPrefix::None | LabelPrefix::Text => String::new(), + }, + config.icon_font_id.clone(), + auto_text_color.unwrap_or(ctx.style().visuals.selection.stroke.color), + 100.0, + ); + + layout_job.append( + &output.label, + 10.0, + TextFormat { + font_id: config.text_font_id.clone(), + color: auto_text_color.unwrap_or(ctx.style().visuals.text_color()), + valign: Align::Center, + ..Default::default() + }, + ); + + let auto_focus_fill = config.auto_select_fill; + + config.apply_on_widget(false, ui, |ui| { + if SelectableFrame::new_auto(output.selected, auto_focus_fill) + .show(ui, |ui| ui.add(Label::new(layout_job).selectable(false))) + .clicked() + && let Err(error) = Command::new("open") + .args(["-a", "Activity Monitor"]) + .spawn() + { + eprintln!("{error}") + } + }); + } + } + } +} diff --git a/komorebi-bar/src/widgets/mod.rs b/komorebi-bar/src/widgets/mod.rs new file mode 100644 index 00000000..56b19d53 --- /dev/null +++ b/komorebi-bar/src/widgets/mod.rs @@ -0,0 +1,173 @@ +use eframe::egui::ColorImage; +use eframe::egui::Context; +use eframe::egui::TextureHandle; +use eframe::egui::TextureOptions; +use image::RgbaImage; +use std::collections::HashMap; +use std::path::Path; +use std::sync::Arc; +use std::sync::LazyLock; +use std::sync::RwLock; + +pub mod applications; +pub mod battery; +pub mod cpu; +pub mod date; +// pub mod keyboard; +pub mod komorebi; +mod komorebi_layout; +// pub mod media; +pub mod memory; +pub mod network; +pub mod storage; +pub mod time; +pub mod update; +pub mod widget; + +/// Global cache for icon images and their associated GPU textures. +pub static ICONS_CACHE: IconsCache = IconsCache::new(); + +/// In-memory cache for icon images and their associated GPU textures. +/// +/// Stores raw [`ColorImage`]s and [`TextureHandle`]s keyed by [`ImageIconId`]. +/// Texture entries are context-dependent and automatically invalidated when the [`Context`] changes. +#[allow(clippy::type_complexity)] +pub struct IconsCache { + textures: LazyLock, HashMap)>>, + images: LazyLock>>>, +} + +impl IconsCache { + /// Creates a new empty IconsCache instance. + #[inline] + pub const fn new() -> Self { + Self { + textures: LazyLock::new(|| RwLock::new((None, HashMap::new()))), + images: LazyLock::new(|| RwLock::new(HashMap::new())), + } + } + + /// Retrieves or creates a texture handle for the given icon ID and image. + /// + /// If a texture for the given ID already exists for the current [`Context`], it is reused. + /// Otherwise, a new texture is created, inserted into the cache, and returned. + /// The cache is reset if the [`Context`] has changed. + #[inline] + pub fn texture(&self, ctx: &Context, id: &ImageIconId, img: &Arc) -> TextureHandle { + if let Some(texture) = self.get_texture(ctx, id) { + return texture; + } + let texture_handle = ctx.load_texture("icon", img.clone(), TextureOptions::default()); + self.insert_texture(ctx, id.clone(), texture_handle.clone()); + texture_handle + } + + /// Returns the cached texture for the given icon ID if it exists and matches the current [`Context`]. + pub fn get_texture(&self, ctx: &Context, id: &ImageIconId) -> Option { + let textures_lock = self.textures.read().unwrap(); + if textures_lock.0.as_ref() == Some(ctx) { + return textures_lock.1.get(id).cloned(); + } + None + } + + /// Inserts a texture handle, resetting the cache if the [`Context`] has changed. + pub fn insert_texture(&self, ctx: &Context, id: ImageIconId, texture: TextureHandle) { + let mut textures_lock = self.textures.write().unwrap(); + + if textures_lock.0.as_ref() != Some(ctx) { + textures_lock.0 = Some(ctx.clone()); + textures_lock.1.clear(); + } + + textures_lock.1.insert(id, texture); + } + + /// Returns the cached image for the given icon ID, if available. + pub fn get_image(&self, id: &ImageIconId) -> Option> { + self.images.read().unwrap().get(id).cloned() + } + + /// Caches a raw [`ColorImage`] associated with the given icon ID. + pub fn insert_image(&self, id: ImageIconId, image: Arc) { + self.images.write().unwrap().insert(id, image); + } +} + +#[inline] +fn rgba_to_color_image(rgba_image: &RgbaImage) -> ColorImage { + let size = [rgba_image.width() as usize, rgba_image.height() as usize]; + let pixels = rgba_image.as_flat_samples(); + ColorImage::from_rgba_unmultiplied(size, pixels.as_slice()) +} + +/// Represents an image-based icon with a unique ID and pixel data. +#[derive(Clone, Debug)] +pub struct ImageIcon { + /// Unique identifier for the image icon, used for texture caching. + pub id: ImageIconId, + /// Shared pixel data of the icon in `ColorImage` format. + pub image: Arc, +} + +impl ImageIcon { + /// Creates a new [`ImageIcon`] from the given ID and image data. + #[inline] + pub fn new(id: ImageIconId, image: Arc) -> Self { + Self { id, image } + } + + /// Loads an [`ImageIcon`] from [`ICONS_CACHE`] or calls `loader` if not cached. + /// The loaded image is converted to a [`ColorImage`], cached, and returned. + #[inline] + pub fn try_load(id: impl Into, loader: F) -> Option + where + F: FnOnce() -> Option, + I: Into, + { + let id = id.into(); + let image = ICONS_CACHE.get_image(&id).or_else(|| { + let img = loader()?; + let img = Arc::new(rgba_to_color_image(&img.into())); + ICONS_CACHE.insert_image(id.clone(), img.clone()); + Some(img) + })?; + + Some(ImageIcon::new(id, image)) + } + + /// Returns a texture handle for the icon, using the given [`Context`]. + /// + /// If the texture is already cached in [`ICONS_CACHE`], it is reused. + /// Otherwise, a new texture is created from the [`ColorImage`] and cached. + #[inline] + pub fn texture(&self, ctx: &Context) -> TextureHandle { + ICONS_CACHE.texture(ctx, &self.id, &self.image) + } +} + +/// Unique identifier for an image-based icon. +/// +/// Used to distinguish cached images and textures by either a file path +/// or a Windows window handle. +#[derive(Clone, Debug, Eq, Hash, PartialEq)] +pub enum ImageIconId { + /// Identifier based on a file system path. + Path(Arc), + /// Windows HWND handle. + Hwnd(isize), +} + +impl From<&Path> for ImageIconId { + #[inline] + fn from(value: &Path) -> Self { + Self::Path(value.into()) + } +} + +impl From for ImageIconId { + #[inline] + fn from(value: isize) -> Self { + Self::Hwnd(value) + } +} diff --git a/komorebi-bar/src/widgets/network.rs b/komorebi-bar/src/widgets/network.rs new file mode 100644 index 00000000..25c4b6ed --- /dev/null +++ b/komorebi-bar/src/widgets/network.rs @@ -0,0 +1,553 @@ +use crate::bar::Alignment; +use crate::config::LabelPrefix; +use crate::render::RenderConfig; +use crate::selected_frame::SelectableFrame; +use crate::widgets::widget::BarWidget; +use eframe::egui::Align; +use eframe::egui::Color32; +use eframe::egui::Context; +use eframe::egui::Label; +use eframe::egui::TextFormat; +use eframe::egui::Ui; +use eframe::egui::text::LayoutJob; +use num_derive::FromPrimitive; +use serde::Deserialize; +use serde::Serialize; +use std::fmt; +use std::process::Command; +use std::time::Duration; +use std::time::Instant; +use sysinfo::Networks; + +#[derive(Copy, Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct NetworkConfig { + /// Enable the Network widget + pub enable: bool, + /// Show total received and transmitted activity + #[serde(alias = "show_total_data_transmitted")] + pub show_total_activity: bool, + /// Show received and transmitted activity + #[serde(alias = "show_network_activity")] + pub show_activity: bool, + /// Show default interface + pub show_default_interface: Option, + /// Characters to reserve for received and transmitted activity + #[serde(alias = "network_activity_fill_characters")] + pub activity_left_padding: Option, + /// Data refresh interval (default: 10 seconds) + pub data_refresh_interval: Option, + /// Display label prefix + pub label_prefix: Option, + /// Select when the value is over a limit (1MiB is 1048576 bytes (1024*1024)) + pub auto_select: Option, +} + +#[derive(Copy, Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct NetworkSelectConfig { + /// Select the total received data when it's over this value + pub total_received_over: Option, + /// Select the total transmitted data when it's over this value + pub total_transmitted_over: Option, + /// Select the received data when it's over this value + pub received_over: Option, + /// Select the transmitted data when it's over this value + pub transmitted_over: Option, +} + +impl From for Network { + fn from(value: NetworkConfig) -> Self { + let default_refresh_interval = 10; + let data_refresh_interval = value.data_refresh_interval.unwrap_or(10); + + Self { + enable: value.enable, + show_total_activity: value.show_total_activity, + show_activity: value.show_activity, + show_default_interface: value.show_default_interface.unwrap_or(true), + networks_network_activity: Networks::new_with_refreshed_list(), + default_interface: String::new(), + default_refresh_interval, + data_refresh_interval, + label_prefix: value.label_prefix.unwrap_or(LabelPrefix::Icon), + auto_select: value.auto_select, + activity_left_padding: value.activity_left_padding.unwrap_or_default(), + last_updated_default_interface: Instant::now() + .checked_sub(Duration::from_secs(default_refresh_interval)) + .unwrap(), + last_state_total_activity: vec![], + last_state_activity: vec![], + last_updated_network_activity: Instant::now() + .checked_sub(Duration::from_secs(data_refresh_interval)) + .unwrap(), + } + } +} + +pub struct Network { + pub enable: bool, + pub show_total_activity: bool, + pub show_activity: bool, + pub show_default_interface: bool, + networks_network_activity: Networks, + default_refresh_interval: u64, + data_refresh_interval: u64, + label_prefix: LabelPrefix, + auto_select: Option, + default_interface: String, + last_updated_default_interface: Instant, + last_state_total_activity: Vec, + last_state_activity: Vec, + last_updated_network_activity: Instant, + activity_left_padding: usize, +} + +impl Network { + fn default_interface(&mut self) { + let now = Instant::now(); + + if now.duration_since(self.last_updated_default_interface) + > Duration::from_secs(self.default_refresh_interval) + { + if let Ok(interface) = netdev::get_default_interface() + && let Some(friendly_name) = &interface.friendly_name + { + self.default_interface.clone_from(friendly_name); + } + + self.last_updated_default_interface = now; + } + } + + fn network_activity(&mut self) -> (Vec, Vec) { + let mut activity = self.last_state_activity.clone(); + let mut total_activity = self.last_state_total_activity.clone(); + let now = Instant::now(); + + if now.duration_since(self.last_updated_network_activity) + > Duration::from_secs(self.data_refresh_interval) + { + activity.clear(); + total_activity.clear(); + + if let Ok(interface) = netdev::get_default_interface() + && let Some(friendly_name) = &interface.friendly_name + { + self.default_interface.clone_from(friendly_name); + + self.networks_network_activity.refresh(true); + + for (interface_name, data) in &self.networks_network_activity { + if friendly_name.eq(interface_name) { + if self.show_activity { + let received = + Self::to_pretty_bytes(data.received(), self.data_refresh_interval); + let transmitted = Self::to_pretty_bytes( + data.transmitted(), + self.data_refresh_interval, + ); + + activity.push(NetworkReading::new( + NetworkReadingFormat::Speed, + ReadingValue::from(received), + ReadingValue::from(transmitted), + )); + } + + if self.show_total_activity { + let total_received = Self::to_pretty_bytes(data.total_received(), 1); + let total_transmitted = + Self::to_pretty_bytes(data.total_transmitted(), 1); + + total_activity.push(NetworkReading::new( + NetworkReadingFormat::Total, + ReadingValue::from(total_received), + ReadingValue::from(total_transmitted), + )) + } + } + } + } + + self.last_state_activity.clone_from(&activity); + self.last_state_total_activity.clone_from(&total_activity); + self.last_updated_network_activity = now; + } + + (activity, total_activity) + } + + fn reading_to_labels( + &self, + select_received: bool, + select_transmitted: bool, + ctx: &Context, + reading: &NetworkReading, + config: RenderConfig, + ) -> (Label, Label) { + let (text_down, text_up) = match self.label_prefix { + LabelPrefix::None | LabelPrefix::Icon => match reading.format { + NetworkReadingFormat::Speed => ( + format!( + "{: >width$}/s ", + reading.received.pretty, + width = self.activity_left_padding + ), + format!( + "{: >width$}/s", + reading.transmitted.pretty, + width = self.activity_left_padding + ), + ), + NetworkReadingFormat::Total => ( + format!("{} ", reading.received.pretty), + reading.transmitted.pretty.clone(), + ), + }, + LabelPrefix::Text | LabelPrefix::IconAndText => match reading.format { + NetworkReadingFormat::Speed => ( + format!( + "DOWN: {: >width$}/s ", + reading.received.pretty, + width = self.activity_left_padding + ), + format!( + "UP: {: >width$}/s", + reading.transmitted.pretty, + width = self.activity_left_padding + ), + ), + NetworkReadingFormat::Total => ( + format!("\u{2211}DOWN: {}/s ", reading.received.pretty), + format!("\u{2211}UP: {}/s", reading.transmitted.pretty), + ), + }, + }; + + let auto_text_color_received = config.auto_select_text.filter(|_| select_received); + let auto_text_color_transmitted = config.auto_select_text.filter(|_| select_transmitted); + + // icon + let mut layout_job_down = LayoutJob::simple( + match self.label_prefix { + LabelPrefix::Icon | LabelPrefix::IconAndText => { + if select_received { + egui_phosphor::regular::ARROW_FAT_LINES_DOWN.to_string() + } else { + egui_phosphor::regular::ARROW_FAT_DOWN.to_string() + } + } + LabelPrefix::None | LabelPrefix::Text => String::new(), + }, + config.icon_font_id.clone(), + auto_text_color_received.unwrap_or(ctx.style().visuals.selection.stroke.color), + 100.0, + ); + + // text + layout_job_down.append( + &text_down, + ctx.style().spacing.item_spacing.x, + TextFormat { + font_id: config.text_font_id.clone(), + color: auto_text_color_received.unwrap_or(ctx.style().visuals.text_color()), + valign: Align::Center, + ..Default::default() + }, + ); + + // icon + let mut layout_job_up = LayoutJob::simple( + match self.label_prefix { + LabelPrefix::Icon | LabelPrefix::IconAndText => { + if select_transmitted { + egui_phosphor::regular::ARROW_FAT_LINES_UP.to_string() + } else { + egui_phosphor::regular::ARROW_FAT_UP.to_string() + } + } + LabelPrefix::None | LabelPrefix::Text => String::new(), + }, + config.icon_font_id.clone(), + auto_text_color_transmitted.unwrap_or(ctx.style().visuals.selection.stroke.color), + 100.0, + ); + + // text + layout_job_up.append( + &text_up, + ctx.style().spacing.item_spacing.x, + TextFormat { + font_id: config.text_font_id.clone(), + color: auto_text_color_transmitted.unwrap_or(ctx.style().visuals.text_color()), + valign: Align::Center, + ..Default::default() + }, + ); + + ( + Label::new(layout_job_down).selectable(false), + Label::new(layout_job_up).selectable(false), + ) + } + + fn to_pretty_bytes(input_in_bytes: u64, timespan_in_s: u64) -> (u64, String) { + let input = input_in_bytes as f32 / timespan_in_s as f32; + let mut magnitude = input.log(1024f32) as u32; + + // let the base unit be KiB + if magnitude < 1 { + magnitude = 1; + } + + let base: Option = num::FromPrimitive::from_u32(magnitude); + let result = input / ((1u64) << (magnitude * 10)) as f32; + + ( + input as u64, + match base { + Some(DataUnit::B) => format!("{result:.1} B"), + Some(unit) => format!("{result:.1} {unit}iB"), + None => String::from("Unknown data unit"), + }, + ) + } + + fn show_frame( + &self, + selected: bool, + auto_focus_fill: Option, + ui: &mut Ui, + add_contents: impl FnOnce(&mut Ui) -> R, + ) { + if SelectableFrame::new_auto(selected, auto_focus_fill) + .show(ui, add_contents) + .clicked() + && let Err(error) = Command::new("open") + .args(["x-apple.systempreferences:com.apple.Network-Settings.extension"]) + .spawn() + { + eprintln!("{error}"); + } + } +} + +impl BarWidget for Network { + fn render(&mut self, ctx: &Context, ui: &mut Ui, config: &mut RenderConfig) { + if self.enable { + let is_reversed = matches!(config.alignment, Some(Alignment::Right)); + + // widget spacing: make sure to use the same config to call the apply_on_widget function + let mut render_config = config.clone(); + + if self.show_total_activity || self.show_activity { + let (activity, total_activity) = self.network_activity(); + + if self.show_total_activity { + for reading in &total_activity { + render_config.apply_on_widget(false, ui, |ui| { + let select_received = self.auto_select.is_some_and(|f| { + f.total_received_over + .is_some_and(|o| reading.received.value > o) + }); + let select_transmitted = self.auto_select.is_some_and(|f| { + f.total_transmitted_over + .is_some_and(|o| reading.transmitted.value > o) + }); + + let labels = self.reading_to_labels( + select_received, + select_transmitted, + ctx, + reading, + config.clone(), + ); + + if is_reversed { + self.show_frame( + select_transmitted, + config.auto_select_fill, + ui, + |ui| ui.add(labels.1), + ); + self.show_frame( + select_received, + config.auto_select_fill, + ui, + |ui| ui.add(labels.0), + ); + } else { + self.show_frame( + select_received, + config.auto_select_fill, + ui, + |ui| ui.add(labels.0), + ); + self.show_frame( + select_transmitted, + config.auto_select_fill, + ui, + |ui| ui.add(labels.1), + ); + } + }); + } + } + + if self.show_activity { + for reading in &activity { + render_config.apply_on_widget(false, ui, |ui| { + let select_received = self.auto_select.is_some_and(|f| { + f.received_over.is_some_and(|o| reading.received.value > o) + }); + let select_transmitted = self.auto_select.is_some_and(|f| { + f.transmitted_over + .is_some_and(|o| reading.transmitted.value > o) + }); + + let labels = self.reading_to_labels( + select_received, + select_transmitted, + ctx, + reading, + config.clone(), + ); + + if is_reversed { + self.show_frame( + select_transmitted, + config.auto_select_fill, + ui, + |ui| ui.add(labels.1), + ); + self.show_frame( + select_received, + config.auto_select_fill, + ui, + |ui| ui.add(labels.0), + ); + } else { + self.show_frame( + select_received, + config.auto_select_fill, + ui, + |ui| ui.add(labels.0), + ); + self.show_frame( + select_transmitted, + config.auto_select_fill, + ui, + |ui| ui.add(labels.1), + ); + } + }); + } + } + } + + if self.show_default_interface { + self.default_interface(); + + if !self.default_interface.is_empty() { + let mut layout_job = LayoutJob::simple( + match self.label_prefix { + LabelPrefix::Icon | LabelPrefix::IconAndText => { + egui_phosphor::regular::WIFI_HIGH.to_string() + } + LabelPrefix::None | LabelPrefix::Text => String::new(), + }, + config.icon_font_id.clone(), + ctx.style().visuals.selection.stroke.color, + 100.0, + ); + + if let LabelPrefix::Text | LabelPrefix::IconAndText = self.label_prefix { + self.default_interface.insert_str(0, "NET: "); + } + + layout_job.append( + &self.default_interface, + 10.0, + TextFormat { + font_id: config.text_font_id.clone(), + color: ctx.style().visuals.text_color(), + valign: Align::Center, + ..Default::default() + }, + ); + + render_config.apply_on_widget(false, ui, |ui| { + self.show_frame(false, None, ui, |ui| { + ui.add(Label::new(layout_job).selectable(false)) + }); + }); + } + } + + // widget spacing: pass on the config that was use for calling the apply_on_widget function + *config = render_config.clone(); + } + } +} + +#[derive(Clone)] +enum NetworkReadingFormat { + Speed = 0, + Total = 1, +} + +#[derive(Clone)] +struct ReadingValue { + value: u64, + pretty: String, +} + +impl From<(u64, String)> for ReadingValue { + fn from(value: (u64, String)) -> Self { + Self { + value: value.0, + pretty: value.1, + } + } +} + +#[derive(Clone)] +struct NetworkReading { + format: NetworkReadingFormat, + received: ReadingValue, + transmitted: ReadingValue, +} + +impl NetworkReading { + fn new( + format: NetworkReadingFormat, + received: ReadingValue, + transmitted: ReadingValue, + ) -> Self { + Self { + format, + received, + transmitted, + } + } +} + +#[derive(Debug, FromPrimitive)] +enum DataUnit { + B = 0, + K = 1, + M = 2, + G = 3, + T = 4, + P = 5, + E = 6, + Z = 7, + Y = 8, +} + +impl fmt::Display for DataUnit { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{self:?}") + } +} diff --git a/komorebi-bar/src/widgets/storage.rs b/komorebi-bar/src/widgets/storage.rs new file mode 100644 index 00000000..070edb68 --- /dev/null +++ b/komorebi-bar/src/widgets/storage.rs @@ -0,0 +1,171 @@ +use crate::bar::Alignment; +use crate::config::LabelPrefix; +use crate::render::RenderConfig; +use crate::selected_frame::SelectableFrame; +use crate::widgets::widget::BarWidget; +use eframe::egui::Align; +use eframe::egui::Context; +use eframe::egui::Label; +use eframe::egui::TextFormat; +use eframe::egui::Ui; +use eframe::egui::text::LayoutJob; +use serde::Deserialize; +use serde::Serialize; +use std::process::Command; +use std::time::Duration; +use std::time::Instant; +use sysinfo::Disks; + +#[derive(Copy, Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct StorageConfig { + /// Enable the Storage widget + pub enable: bool, + /// Data refresh interval (default: 10 seconds) + pub data_refresh_interval: Option, + /// Display label prefix + pub label_prefix: Option, + /// Show disks that are read only. (default: false) + pub show_read_only_disks: Option, + /// Show removable disks. (default: true) + pub show_removable_disks: Option, + /// Select when the current percentage is over this value [[1-100]] + pub auto_select_over: Option, + /// Hide when the current percentage is under this value [[1-100]] + pub auto_hide_under: Option, +} + +impl From for Storage { + fn from(value: StorageConfig) -> Self { + Self { + enable: value.enable, + disks: Disks::new_with_refreshed_list(), + data_refresh_interval: value.data_refresh_interval.unwrap_or(10), + label_prefix: value.label_prefix.unwrap_or(LabelPrefix::IconAndText), + show_read_only_disks: value.show_read_only_disks.unwrap_or(false), + show_removable_disks: value.show_removable_disks.unwrap_or(true), + auto_select_over: value.auto_select_over.map(|o| o.clamp(1, 100)), + auto_hide_under: value.auto_hide_under.map(|o| o.clamp(1, 100)), + last_updated: Instant::now(), + } + } +} + +struct StorageDisk { + label: String, + selected: bool, +} + +pub struct Storage { + pub enable: bool, + disks: Disks, + data_refresh_interval: u64, + label_prefix: LabelPrefix, + show_read_only_disks: bool, + show_removable_disks: bool, + auto_select_over: Option, + auto_hide_under: Option, + last_updated: Instant, +} + +impl Storage { + fn output(&mut self) -> Vec { + let now = Instant::now(); + if now.duration_since(self.last_updated) > Duration::from_secs(self.data_refresh_interval) { + self.disks.refresh(true); + self.last_updated = now; + } + + let mut disks = vec![]; + + for disk in &self.disks { + if disk.is_read_only() && !self.show_read_only_disks { + continue; + } + if disk.is_removable() && !self.show_removable_disks { + continue; + } + let mount = disk.mount_point(); + let total = disk.total_space(); + let available = disk.available_space(); + let used = total - available; + let percentage = ((used * 100) / total) as u8; + + let hide = self.auto_hide_under.is_some_and(|u| percentage <= u); + + if !hide { + let selected = self.auto_select_over.is_some_and(|o| percentage >= o); + + disks.push(StorageDisk { + label: match self.label_prefix { + LabelPrefix::Text | LabelPrefix::IconAndText => { + format!("{} {}%", mount.to_string_lossy(), percentage) + } + LabelPrefix::None | LabelPrefix::Icon => format!("{percentage}%"), + }, + selected, + }) + } + } + + disks.sort_by(|a, b| a.label.cmp(&b.label)); + + disks + } +} + +impl BarWidget for Storage { + fn render(&mut self, ctx: &Context, ui: &mut Ui, config: &mut RenderConfig) { + if self.enable { + let mut output = self.output(); + let is_reversed = matches!(config.alignment, Some(Alignment::Right)); + + if is_reversed { + output.reverse(); + } + + for output in output { + let auto_text_color = config.auto_select_text.filter(|_| output.selected); + + let mut layout_job = LayoutJob::simple( + match self.label_prefix { + LabelPrefix::Icon | LabelPrefix::IconAndText => { + egui_phosphor::regular::HARD_DRIVES.to_string() + } + LabelPrefix::None | LabelPrefix::Text => String::new(), + }, + config.icon_font_id.clone(), + auto_text_color.unwrap_or(ctx.style().visuals.selection.stroke.color), + 100.0, + ); + + layout_job.append( + &output.label, + 10.0, + TextFormat { + font_id: config.text_font_id.clone(), + color: auto_text_color.unwrap_or(ctx.style().visuals.text_color()), + valign: Align::Center, + ..Default::default() + }, + ); + + let auto_focus_fill = config.auto_select_fill; + + config.apply_on_widget(false, ui, |ui| { + if SelectableFrame::new_auto(output.selected, auto_focus_fill) + .show(ui, |ui| ui.add(Label::new(layout_job).selectable(false))) + .clicked() + { + let parts: Vec<&str> = output.label.split(' ').collect(); + let path = parts[..parts.len() - 1].join(" "); + + if let Err(error) = Command::new("open").args([path]).spawn() { + eprintln!("{error}") + } + } + }); + } + } + } +} diff --git a/komorebi-bar/src/widgets/time.rs b/komorebi-bar/src/widgets/time.rs new file mode 100644 index 00000000..240ab0f2 --- /dev/null +++ b/komorebi-bar/src/widgets/time.rs @@ -0,0 +1,538 @@ +use crate::bar::Alignment; +use crate::config::LabelPrefix; +use crate::render::RenderConfig; +use crate::selected_frame::SelectableFrame; +use crate::widgets::widget::BarWidget; +use chrono::Local; +use chrono::NaiveTime; +use chrono_tz::Tz; +use eframe::egui::Align; +use eframe::egui::Context; +use eframe::egui::CornerRadius; +use eframe::egui::Label; +use eframe::egui::Sense; +use eframe::egui::Stroke; +use eframe::egui::TextFormat; +use eframe::egui::Ui; +use eframe::egui::Vec2; +use eframe::egui::text::LayoutJob; +use eframe::epaint::StrokeKind; +use lazy_static::lazy_static; +use serde::Deserialize; +use serde::Serialize; +use std::time::Duration; +use std::time::Instant; + +lazy_static! { + static ref TIME_RANGES: Vec<(&'static str, NaiveTime)> = { + vec![ + ( + egui_phosphor::regular::MOON, + NaiveTime::from_hms_opt(0, 0, 0).expect("invalid"), + ), + ( + egui_phosphor::regular::ALARM, + NaiveTime::from_hms_opt(6, 0, 0).expect("invalid"), + ), + ( + egui_phosphor::regular::BREAD, + NaiveTime::from_hms_opt(6, 1, 0).expect("invalid"), + ), + ( + egui_phosphor::regular::BARBELL, + NaiveTime::from_hms_opt(6, 30, 0).expect("invalid"), + ), + ( + egui_phosphor::regular::COFFEE, + NaiveTime::from_hms_opt(8, 0, 0).expect("invalid"), + ), + ( + egui_phosphor::regular::CLOCK, + NaiveTime::from_hms_opt(8, 30, 0).expect("invalid"), + ), + ( + egui_phosphor::regular::HAMBURGER, + NaiveTime::from_hms_opt(12, 0, 0).expect("invalid"), + ), + ( + egui_phosphor::regular::CLOCK_AFTERNOON, + NaiveTime::from_hms_opt(12, 30, 0).expect("invalid"), + ), + ( + egui_phosphor::regular::FORK_KNIFE, + NaiveTime::from_hms_opt(18, 0, 0).expect("invalid"), + ), + ( + egui_phosphor::regular::MOON_STARS, + NaiveTime::from_hms_opt(18, 30, 0).expect("invalid"), + ), + ] + }; +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct TimeConfig { + /// Enable the Time widget + pub enable: bool, + /// Set the Time format + pub format: TimeFormat, + /// Display label prefix + pub label_prefix: Option, + /// TimeZone (https://docs.rs/chrono-tz/latest/chrono_tz/enum.Tz.html) + /// + /// Use a custom format to display additional information, i.e.: + /// ```json + /// { + /// "Time": { + /// "enable": true, + /// "format": { "Custom": "%T %Z (Tokyo)" }, + /// "timezone": "Asia/Tokyo" + /// } + ///} + /// ``` + pub timezone: Option, + /// Change the icon depending on the time. The default icon is used between 8:30 and 12:00. (default: false) + pub changing_icon: Option, +} + +impl From for Time { + fn from(value: TimeConfig) -> Self { + // using 1 second made the widget look "less accurate" and lagging (especially having multiple with seconds). + // This is still better than getting an update every frame + let data_refresh_interval = 500; + + Self { + enable: value.enable, + format: value.format, + label_prefix: value.label_prefix.unwrap_or(LabelPrefix::Icon), + timezone: value.timezone, + changing_icon: value.changing_icon.unwrap_or_default(), + data_refresh_interval_millis: data_refresh_interval, + last_state: TimeOutput::new(), + last_updated: Instant::now() + .checked_sub(Duration::from_millis(data_refresh_interval)) + .unwrap(), + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub enum TimeFormat { + /// Twelve-hour format (with seconds) + TwelveHour, + /// Twelve-hour format (without seconds) + TwelveHourWithoutSeconds, + /// Twenty-four-hour format (with seconds) + TwentyFourHour, + /// Twenty-four-hour format (without seconds) + TwentyFourHourWithoutSeconds, + /// Twenty-four-hour format displayed as a binary clock with circles (with seconds) (https://en.wikipedia.org/wiki/Binary_clock) + BinaryCircle, + /// Twenty-four-hour format displayed as a binary clock with rectangles (with seconds) (https://en.wikipedia.org/wiki/Binary_clock) + BinaryRectangle, + /// Custom format (https://docs.rs/chrono/latest/chrono/format/strftime/index.html) + Custom(String), +} + +impl TimeFormat { + pub fn toggle(&mut self) { + match self { + TimeFormat::TwelveHour => *self = TimeFormat::TwelveHourWithoutSeconds, + TimeFormat::TwelveHourWithoutSeconds => *self = TimeFormat::TwentyFourHour, + TimeFormat::TwentyFourHour => *self = TimeFormat::TwentyFourHourWithoutSeconds, + TimeFormat::TwentyFourHourWithoutSeconds => *self = TimeFormat::BinaryCircle, + TimeFormat::BinaryCircle => *self = TimeFormat::BinaryRectangle, + TimeFormat::BinaryRectangle => *self = TimeFormat::TwelveHour, + _ => {} + }; + } + + fn fmt_string(&self) -> String { + match self { + TimeFormat::TwelveHour => String::from("%l:%M:%S %p"), + TimeFormat::TwelveHourWithoutSeconds => String::from("%l:%M %p"), + TimeFormat::TwentyFourHour => String::from("%T"), + TimeFormat::TwentyFourHourWithoutSeconds => String::from("%H:%M"), + TimeFormat::BinaryCircle => String::from("c%T"), + TimeFormat::BinaryRectangle => String::from("r%T"), + TimeFormat::Custom(format) => format.to_string(), + } + } +} + +#[derive(Clone, Debug)] +struct TimeOutput { + label: String, + icon: String, +} + +impl TimeOutput { + fn new() -> Self { + Self { + label: String::new(), + icon: String::new(), + } + } +} + +#[derive(Clone, Debug)] +pub struct Time { + pub enable: bool, + pub format: TimeFormat, + label_prefix: LabelPrefix, + timezone: Option, + changing_icon: bool, + data_refresh_interval_millis: u64, + last_state: TimeOutput, + last_updated: Instant, +} + +impl Time { + fn output(&mut self) -> TimeOutput { + let mut output = self.last_state.clone(); + let now = Instant::now(); + + if now.duration_since(self.last_updated) + > Duration::from_millis(self.data_refresh_interval_millis) + { + let (formatted, current_time) = match &self.timezone { + Some(timezone) => match timezone.parse::() { + Ok(tz) => { + let dt = Local::now().with_timezone(&tz); + ( + dt.format(&self.format.fmt_string()) + .to_string() + .trim() + .to_string(), + Some(dt.time()), + ) + } + Err(_) => (format!("Invalid timezone: {timezone:?}"), None), + }, + None => { + let dt = Local::now(); + ( + dt.format(&self.format.fmt_string()) + .to_string() + .trim() + .to_string(), + Some(dt.time()), + ) + } + }; + + if current_time.is_none() { + return TimeOutput { + label: formatted, + icon: egui_phosphor::regular::WARNING_CIRCLE.to_string(), + }; + } + + let current_range = match &self.changing_icon { + true => TIME_RANGES + .iter() + .rev() + .find(|&(_, start)| current_time.unwrap() > *start) + .cloned(), + false => None, + } + .unwrap_or((egui_phosphor::regular::CLOCK, NaiveTime::default())); + + output = TimeOutput { + label: formatted, + icon: current_range.0.to_string(), + }; + + self.last_state.clone_from(&output); + self.last_updated = now; + } + + output + } + + fn paint_binary_circle( + &mut self, + size: f32, + number: u32, + max_power: usize, + ctx: &Context, + ui: &mut Ui, + ) { + let full_height = size; + let height = full_height / 4.0; + let width = height; + let offset = height / 2.0 - height / 8.0; + + let (response, painter) = + ui.allocate_painter(Vec2::new(width, full_height + offset * 2.0), Sense::hover()); + let color = ctx.style().visuals.text_color(); + + let c = response.rect.center(); + let r = height / 2.0 - 0.5; + + if number == 1 || number == 3 || number == 5 || number == 7 || number == 9 { + painter.circle_filled(c + Vec2::new(0.0, height * 1.50 + offset), r, color); + } else { + painter.circle_filled(c + Vec2::new(0.0, height * 1.50 + offset), r / 2.5, color); + } + + if number == 2 || number == 3 || number == 6 || number == 7 { + painter.circle_filled(c + Vec2::new(0.0, height * 0.50 + offset), r, color); + } else { + painter.circle_filled(c + Vec2::new(0.0, height * 0.50 + offset), r / 2.5, color); + } + + if number == 4 || number == 5 || number == 6 || number == 7 { + painter.circle_filled(c + Vec2::new(0.0, -height * 0.50 + offset), r, color); + } else if max_power > 2 { + painter.circle_filled(c + Vec2::new(0.0, -height * 0.50 + offset), r / 2.5, color); + } + + if number == 8 || number == 9 { + painter.circle_filled(c + Vec2::new(0.0, -height * 1.50 + offset), r, color); + } else if max_power > 3 { + painter.circle_filled(c + Vec2::new(0.0, -height * 1.50 + offset), r / 2.5, color); + } + } + + fn paint_binary_rect( + &mut self, + size: f32, + number: u32, + max_power: usize, + ctx: &Context, + ui: &mut Ui, + ) { + let full_height = size; + let height = full_height / 4.0; + let width = height * 1.5; + let offset = height / 2.0 - height / 8.0; + + let (response, painter) = + ui.allocate_painter(Vec2::new(width, full_height + offset * 2.0), Sense::hover()); + let color = ctx.style().visuals.text_color(); + let stroke = Stroke::new(1.0, color); + + let round_all = CornerRadius::same((response.rect.width() * 0.1) as u8); + let round_top = CornerRadius { + nw: round_all.nw, + ne: round_all.ne, + ..Default::default() + }; + let round_none = CornerRadius::ZERO; + let round_bottom = CornerRadius { + sw: round_all.nw, + se: round_all.ne, + ..Default::default() + }; + + if max_power == 2 { + let mut rect = response + .rect + .shrink2(Vec2::new(stroke.width, stroke.width + offset)); + rect.set_height(rect.height() - height * 2.0); + rect = rect.translate(Vec2::new(0.0, height * 2.0 + offset)); + painter.rect_stroke(rect, round_all, stroke, StrokeKind::Outside); + } else if max_power == 3 { + let mut rect = response + .rect + .shrink2(Vec2::new(stroke.width, stroke.width + offset)); + rect.set_height(rect.height() - height); + rect = rect.translate(Vec2::new(0.0, height + offset)); + painter.rect_stroke(rect, round_all, stroke, StrokeKind::Outside); + } else { + let mut rect = response + .rect + .shrink2(Vec2::new(stroke.width, stroke.width + offset)); + rect = rect.translate(Vec2::new(0.0, 0.0 + offset)); + painter.rect_stroke(rect, round_all, stroke, StrokeKind::Outside); + } + + let mut rect_bin = response.rect; + rect_bin.set_width(width); + + if number == 1 || number == 5 || number == 9 { + rect_bin.set_height(height); + painter.rect_filled( + rect_bin.translate(Vec2::new(stroke.width, height * 3.0 + offset * 2.0)), + round_bottom, + color, + ); + } + if number == 2 { + rect_bin.set_height(height); + painter.rect_filled( + rect_bin.translate(Vec2::new(stroke.width, height * 2.0 + offset * 2.0)), + if max_power == 2 { + round_top + } else { + round_none + }, + color, + ); + } + if number == 3 { + rect_bin.set_height(height * 2.0); + painter.rect_filled( + rect_bin.translate(Vec2::new(stroke.width, height * 2.0 + offset * 2.0)), + round_bottom, + color, + ); + } + if number == 4 || number == 5 { + rect_bin.set_height(height); + painter.rect_filled( + rect_bin.translate(Vec2::new(stroke.width, height * 1.0 + offset * 2.0)), + if max_power == 3 { + round_top + } else { + round_none + }, + color, + ); + } + if number == 6 { + rect_bin.set_height(height * 2.0); + painter.rect_filled( + rect_bin.translate(Vec2::new(stroke.width, height * 1.0 + offset * 2.0)), + if max_power == 3 { + round_top + } else { + round_none + }, + color, + ); + } + if number == 7 { + rect_bin.set_height(height * 3.0); + painter.rect_filled( + rect_bin.translate(Vec2::new(stroke.width, height + offset * 2.0)), + if max_power == 3 { + round_all + } else { + round_bottom + }, + color, + ); + } + if number == 8 || number == 9 { + rect_bin.set_height(height); + painter.rect_filled( + rect_bin.translate(Vec2::new(stroke.width, 0.0 + offset * 2.0)), + round_top, + color, + ); + } + } +} + +impl BarWidget for Time { + fn render(&mut self, ctx: &Context, ui: &mut Ui, config: &mut RenderConfig) { + if self.enable { + let mut output = self.output(); + if !output.label.is_empty() { + let use_binary_circle = output.label.starts_with('c'); + let use_binary_rectangle = output.label.starts_with('r'); + + let mut layout_job = LayoutJob::simple( + match self.label_prefix { + LabelPrefix::Icon | LabelPrefix::IconAndText => output.icon, + LabelPrefix::None | LabelPrefix::Text => String::new(), + }, + config.icon_font_id.clone(), + ctx.style().visuals.selection.stroke.color, + 100.0, + ); + + if let LabelPrefix::Text | LabelPrefix::IconAndText = self.label_prefix { + output.label.insert_str(0, "TIME: "); + } + + if !use_binary_circle && !use_binary_rectangle { + layout_job.append( + &output.label, + 10.0, + TextFormat { + font_id: config.text_font_id.clone(), + color: ctx.style().visuals.text_color(), + valign: Align::Center, + ..Default::default() + }, + ); + } + + let font_id = config.icon_font_id.clone(); + let is_reversed = matches!(config.alignment, Some(Alignment::Right)); + + config.apply_on_widget(false, ui, |ui| { + if SelectableFrame::new(false) + .show(ui, |ui| { + if !is_reversed { + ui.add(Label::new(layout_job.clone()).selectable(false)); + } + + if use_binary_circle || use_binary_rectangle { + let ordered_output = if is_reversed { + output.label.chars().rev().collect() + } else { + output.label + }; + + for (section_index, section) in + ordered_output.split(':').enumerate() + { + ui.scope(|ui| { + ui.spacing_mut().item_spacing = Vec2::splat(2.0); + for (number_index, number_char) in + section.chars().enumerate() + { + if let Some(number) = number_char.to_digit(10) { + // the hour is the second char in the first section (in reverse, it's in the last section) + let max_power = match ( + is_reversed, + section_index, + number_index, + ) { + (true, 2, 1) | (false, 0, 1) => 2, + (true, _, 1) | (false, _, 0) => 3, + _ => 4, + }; + + if use_binary_circle { + self.paint_binary_circle( + font_id.size, + number, + max_power, + ctx, + ui, + ); + } else if use_binary_rectangle { + self.paint_binary_rect( + font_id.size, + number, + max_power, + ctx, + ui, + ); + } + } + } + }); + } + } + + if is_reversed { + ui.add(Label::new(layout_job.clone()).selectable(false)); + } + }) + .clicked() + { + self.format.toggle() + } + }); + } + } + } +} diff --git a/komorebi-bar/src/widgets/update.rs b/komorebi-bar/src/widgets/update.rs new file mode 100644 index 00000000..f33391ea --- /dev/null +++ b/komorebi-bar/src/widgets/update.rs @@ -0,0 +1,156 @@ +use crate::config::LabelPrefix; +use crate::render::RenderConfig; +use crate::selected_frame::SelectableFrame; +use crate::widgets::widget::BarWidget; +use eframe::egui::Align; +use eframe::egui::Context; +use eframe::egui::Label; +use eframe::egui::TextFormat; +use eframe::egui::Ui; +use eframe::egui::text::LayoutJob; +use serde::Deserialize; +use serde::Serialize; +use std::process::Command; +use std::time::Duration; +use std::time::Instant; + +#[derive(Copy, Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub struct UpdateConfig { + /// Enable the Update widget + pub enable: bool, + /// Data refresh interval (default: 12 hours) + pub data_refresh_interval: Option, + /// Display label prefix + pub label_prefix: Option, +} + +impl From for Update { + fn from(value: UpdateConfig) -> Self { + let data_refresh_interval = value.data_refresh_interval.unwrap_or(12); + + let mut latest_version = String::new(); + + let client = reqwest::blocking::Client::new(); + if let Ok(response) = client + .get("https://api.github.com/repos/LGUG2Z/komorebi/releases/latest") + .header("User-Agent", "komorebi-bar-version-checker") + .send() + { + #[derive(Deserialize)] + struct Release { + tag_name: String, + } + + if let Ok(release) = + serde_json::from_str::(&response.text().unwrap_or_default()) + { + let trimmed = release.tag_name.trim_start_matches("v"); + latest_version = trimmed.to_string(); + } + } + + Self { + enable: value.enable, + data_refresh_interval, + installed_version: env!("CARGO_PKG_VERSION").to_string(), + latest_version, + label_prefix: value.label_prefix.unwrap_or(LabelPrefix::IconAndText), + last_updated: Instant::now() + .checked_sub(Duration::from_secs(data_refresh_interval)) + .unwrap(), + } + } +} + +pub struct Update { + pub enable: bool, + data_refresh_interval: u64, + installed_version: String, + latest_version: String, + label_prefix: LabelPrefix, + last_updated: Instant, +} + +impl Update { + fn output(&mut self) -> String { + let now = Instant::now(); + if now.duration_since(self.last_updated) + > Duration::from_secs((self.data_refresh_interval * 60) * 60) + { + let client = reqwest::blocking::Client::new(); + if let Ok(response) = client + .get("https://api.github.com/repos/LGUG2Z/komorebi/releases/latest") + .header("User-Agent", "komorebi-bar-version-checker") + .send() + { + #[derive(Deserialize)] + struct Release { + tag_name: String, + } + + if let Ok(release) = + serde_json::from_str::(&response.text().unwrap_or_default()) + { + let trimmed = release.tag_name.trim_start_matches("v"); + self.latest_version = trimmed.to_string(); + } + } + + self.last_updated = now; + } + + if self.latest_version > self.installed_version { + format!("Update available! v{}", self.latest_version) + } else { + String::new() + } + } +} + +impl BarWidget for Update { + fn render(&mut self, ctx: &Context, ui: &mut Ui, config: &mut RenderConfig) { + if self.enable { + let output = self.output(); + if !output.is_empty() { + let mut layout_job = LayoutJob::simple( + match self.label_prefix { + LabelPrefix::Icon | LabelPrefix::IconAndText => { + egui_phosphor::regular::ROCKET_LAUNCH.to_string() + } + LabelPrefix::None | LabelPrefix::Text => String::new(), + }, + config.icon_font_id.clone(), + ctx.style().visuals.selection.stroke.color, + 100.0, + ); + + layout_job.append( + &output, + 10.0, + TextFormat { + font_id: config.text_font_id.clone(), + color: ctx.style().visuals.text_color(), + valign: Align::Center, + ..Default::default() + }, + ); + + config.apply_on_widget(false, ui, |ui| { + if SelectableFrame::new(false) + .show(ui, |ui| ui.add(Label::new(layout_job).selectable(false))) + .clicked() + && let Err(error) = Command::new("explorer.exe") + .args([format!( + "https://github.com/LGUG2Z/komorebi/releases/v{}", + self.latest_version + )]) + .spawn() + { + eprintln!("{error}") + } + }); + } + } + } +} diff --git a/komorebi-bar/src/widgets/widget.rs b/komorebi-bar/src/widgets/widget.rs new file mode 100644 index 00000000..d91fe1f8 --- /dev/null +++ b/komorebi-bar/src/widgets/widget.rs @@ -0,0 +1,94 @@ +use crate::render::RenderConfig; +use crate::widgets::applications::Applications; +use crate::widgets::applications::ApplicationsConfig; +use crate::widgets::battery::Battery; +use crate::widgets::battery::BatteryConfig; +use crate::widgets::cpu::Cpu; +use crate::widgets::cpu::CpuConfig; +use crate::widgets::date::Date; +use crate::widgets::date::DateConfig; +// use crate::widgets::keyboard::Keyboard; +// use crate::widgets::keyboard::KeyboardConfig; +use crate::widgets::komorebi::Komorebi; +use crate::widgets::komorebi::KomorebiConfig; +// use crate::widgets::media::Media; +// use crate::widgets::media::MediaConfig; +use crate::widgets::memory::Memory; +use crate::widgets::memory::MemoryConfig; +use crate::widgets::network::Network; +use crate::widgets::network::NetworkConfig; +use crate::widgets::storage::Storage; +use crate::widgets::storage::StorageConfig; +use crate::widgets::time::Time; +use crate::widgets::time::TimeConfig; +use crate::widgets::update::Update; +use crate::widgets::update::UpdateConfig; +use eframe::egui::Context; +use eframe::egui::Ui; +use serde::Deserialize; +use serde::Serialize; + +pub trait BarWidget { + fn render(&mut self, ctx: &Context, ui: &mut Ui, config: &mut RenderConfig); +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +pub enum WidgetConfig { + Applications(ApplicationsConfig), + Battery(BatteryConfig), + Cpu(CpuConfig), + Date(DateConfig), + // Keyboard(KeyboardConfig), + Komorebi(KomorebiConfig), + // Media(MediaConfig), + Memory(MemoryConfig), + Network(NetworkConfig), + Storage(StorageConfig), + Time(TimeConfig), + Update(UpdateConfig), +} + +impl WidgetConfig { + pub fn as_boxed_bar_widget(&self) -> Box { + match self { + WidgetConfig::Applications(config) => Box::new(Applications::from(config)), + WidgetConfig::Battery(config) => Box::new(Battery::from(*config)), + WidgetConfig::Cpu(config) => Box::new(Cpu::from(*config)), + WidgetConfig::Date(config) => Box::new(Date::from(config.clone())), + // WidgetConfig::Keyboard(config) => Box::new(Keyboard::from(*config)), + WidgetConfig::Komorebi(config) => Box::new(Komorebi::from(config)), + // WidgetConfig::Media(config) => Box::new(Media::from(*config)), + WidgetConfig::Memory(config) => Box::new(Memory::from(*config)), + WidgetConfig::Network(config) => Box::new(Network::from(*config)), + WidgetConfig::Storage(config) => Box::new(Storage::from(*config)), + WidgetConfig::Time(config) => Box::new(Time::from(config.clone())), + WidgetConfig::Update(config) => Box::new(Update::from(*config)), + } + } + + pub fn enabled(&self) -> bool { + match self { + WidgetConfig::Applications(config) => config.enable, + WidgetConfig::Battery(config) => config.enable, + WidgetConfig::Cpu(config) => config.enable, + WidgetConfig::Date(config) => config.enable, + // WidgetConfig::Keyboard(config) => config.enable, + WidgetConfig::Komorebi(config) => { + config.workspaces.as_ref().is_some_and(|w| w.enable) + || config.layout.as_ref().is_some_and(|w| w.enable) + || config.focused_container.as_ref().is_some_and(|w| w.enable) + || config + .configuration_switcher + .as_ref() + .is_some_and(|w| w.enable) + } + // WidgetConfig::Media(config) => config.enable, + WidgetConfig::Memory(config) => config.enable, + WidgetConfig::Network(config) => config.enable, + WidgetConfig::Storage(config) => config.enable, + WidgetConfig::Time(config) => config.enable, + WidgetConfig::Update(config) => config.enable, + } + } +} diff --git a/komorebi-client/Cargo.toml b/komorebi-client/Cargo.toml index 3799e2df..ba54d833 100644 --- a/komorebi-client/Cargo.toml +++ b/komorebi-client/Cargo.toml @@ -5,6 +5,7 @@ edition = "2024" [dependencies] komorebi = { path = "../komorebi", default-features = false } +komorebi-themes = { git = "https://github.com/LGUG2Z/komorebi", version = "0.1.38"} serde_json = { workspace = true } [features] diff --git a/komorebi-client/src/lib.rs b/komorebi-client/src/lib.rs index 8e63854c..215fcae8 100644 --- a/komorebi-client/src/lib.rs +++ b/komorebi-client/src/lib.rs @@ -1,21 +1,33 @@ pub use komorebi::DATA_DIR; pub use komorebi::Notification; +pub use komorebi::NotificationEvent; +pub use komorebi::container::Container; pub use komorebi::core::ApplicationIdentifier; pub use komorebi::core::MoveBehaviour; pub use komorebi::core::OperationBehaviour; pub use komorebi::core::Sizing; pub use komorebi::core::SocketMessage; pub use komorebi::core::StateQuery; +pub use komorebi::core::SubscribeOptions; pub use komorebi::core::WindowKind; pub use komorebi::core::arrangement::Axis; pub use komorebi::core::asc::ApplicationSpecificConfiguration; pub use komorebi::core::cycle_direction::CycleDirection; pub use komorebi::core::default_layout::DefaultLayout; +pub use komorebi::core::layout::Layout; pub use komorebi::core::operation_direction::OperationDirection; pub use komorebi::core::pathext::PathExt; pub use komorebi::core::pathext::replace_env_in_path; pub use komorebi::core::rect::Rect; +pub use komorebi::monitor_reconciliator::MonitorNotification; +pub use komorebi::state::State; +pub use komorebi::static_config::KomorebiTheme; pub use komorebi::static_config::StaticConfig; +pub use komorebi::window::Window; +pub use komorebi::workspace::Workspace; +pub use komorebi::workspace::WorkspaceLayer; +pub use komorebi_themes::colour::Colour; +pub use komorebi_themes::colour::Rgb; use std::borrow::Borrow; use std::io::BufReader; use std::io::Read; @@ -86,3 +98,29 @@ pub fn subscribe(name: &str) -> std::io::Result { Ok(listener) } + +pub fn subscribe_with_options( + name: &str, + options: SubscribeOptions, +) -> std::io::Result { + let socket = DATA_DIR.join(name); + + match std::fs::remove_file(&socket) { + Ok(()) => {} + Err(error) => match error.kind() { + std::io::ErrorKind::NotFound => {} + _ => { + return Err(error); + } + }, + }; + + let listener = UnixListener::bind(&socket)?; + + send_message(&SocketMessage::AddSubscriberSocketWithOptions( + name.to_string(), + options, + ))?; + + Ok(listener) +} diff --git a/komorebi/Cargo.toml b/komorebi/Cargo.toml index a6d960fd..c76fdb54 100644 --- a/komorebi/Cargo.toml +++ b/komorebi/Cargo.toml @@ -6,32 +6,31 @@ edition = "2024" [dependencies] komorebi-themes = { git = "https://github.com/LGUG2Z/komorebi", version = "0.1.38"} +quickxml_to_serde = { git = "https://github.com/LGUG2Z/quickxml_to_serde.git", version = "0.6.1" } +block2 = "0.3" clap = { workspace = true } color-eyre = { workspace = true } -crossbeam-channel = "0.5" -crossbeam-utils = "0.8" +crossbeam-channel = { workspace = true } +crossbeam-utils = { workspace = true } ctrlc = { version = "3", features = ["termination"] } -dispatch2 = "0.3" dirs = { workspace = true } -hotwatch = "0.5" +dispatch2 = "0.3" +hotwatch = { workspace = true } lazy_static = { workspace = true } nanoid = "0.4" -block2 = "0.3" objc2 = "0.6" -objc2-core-services = "0.3" objc2-app-kit = "0.3" objc2-application-services = "0.3" -objc2-quartz-core = "0.3" -objc2-core-video = "0.3" objc2-core-foundation = { version = "0.3", features = ["CFDictionary", "CFString"] } objc2-core-graphics = { version = "0.3", features = ["CGWindow", "alloc"] } +objc2-core-services = "0.3" +objc2-core-video = "0.3" objc2-foundation = "0.3" -parking_lot = "0.12" +objc2-quartz-core = "0.3" +parking_lot = { workspace = true } pastey = { workspace = true } quick-xml = { version = "0.38", features = ["serialize"] } -# forked to patch in serde_json_lenient and update some old dependencies -quickxml_to_serde = { git = "https://github.com/LGUG2Z/quickxml_to_serde.git", version = "0.6.1" } regex = "1" schemars = { workspace = true, optional = true } serde = { workspace = true } @@ -41,9 +40,9 @@ shadow-rs = { workspace = true } strum = { version = "0.27", features = ["derive"] } sysinfo = { workspace = true } thiserror = { workspace = true } -tracing = "0.1" -tracing-appender = "0.2" -tracing-subscriber = { version = "0.3", features = ["env-filter"] } +tracing = { workspace = true } +tracing-appender = { workspace = true } +tracing-subscriber = { workspace = true } [build-dependencies] shadow-rs = { workspace = true } diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs index e92a1b7e..5769aa50 100644 --- a/komorebi/src/lib.rs +++ b/komorebi/src/lib.rs @@ -113,12 +113,18 @@ lazy_static! { static ref REGEX_IDENTIFIERS: Arc>> = Arc::new(Mutex::new(HashMap::new())); static ref MANAGE_IDENTIFIERS: Arc>> = Arc::new(Mutex::new(vec![])); - static ref IGNORE_IDENTIFIERS: Arc>> = - Arc::new(Mutex::new(vec![MatchingRule::Simple(IdWithIdentifier { + static ref IGNORE_IDENTIFIERS: Arc>> = Arc::new(Mutex::new(vec![ + MatchingRule::Simple(IdWithIdentifier { kind: ApplicationIdentifier::Exe, id: String::from("Spotlight"), matching_strategy: Option::from(MatchingStrategy::Equals), - })])); + }), + MatchingRule::Simple(IdWithIdentifier { + kind: ApplicationIdentifier::Exe, + id: String::from("komorebi-bar"), + matching_strategy: Option::from(MatchingStrategy::Equals), + }) + ])); static ref SESSION_FLOATING_APPLICATIONS: Arc>> = Arc::new(Mutex::new(Vec::new())); static ref FLOATING_APPLICATIONS: Arc>> = @@ -181,12 +187,13 @@ pub fn notify_subscribers( ) -> eyre::Result<()> { let is_override_event = matches!( notification.event, - NotificationEvent::Socket(SocketMessage::AddSubscriberSocket(_)) + NotificationEvent::Monitor(_) + | NotificationEvent::Socket(SocketMessage::AddSubscriberSocket(_)) | NotificationEvent::Socket(SocketMessage::AddSubscriberSocketWithOptions(_, _)) - // | NotificationEvent::Socket(SocketMessage::Theme(_)) - | NotificationEvent::Socket(SocketMessage::ReloadStaticConfiguration(_)) // | NotificationEvent::WindowManager(WindowManagerEvent::TitleUpdate(_, _)) - // | NotificationEvent::WindowManager(WindowManagerEvent::Show(_, _)) - // | NotificationEvent::WindowManager(WindowManagerEvent::Uncloak(_, _)) + | NotificationEvent::Socket(SocketMessage::Theme(_)) + | NotificationEvent::Socket(SocketMessage::ReloadStaticConfiguration(_)) + // | NotificationEvent::WindowManager(WindowManagerEvent::TitleUpdate(_, _)) + | NotificationEvent::WindowManager(WindowManagerEvent::Show(_, _)) // | NotificationEvent::WindowManager(WindowManagerEvent::Uncloak(_, _)) ); let notification = &serde_json::to_string(¬ification)?; @@ -259,7 +266,7 @@ impl Default for AccessibilityUiElement { } } -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Default)] pub struct AccessibilityObserver(pub Option>); unsafe impl Sync for AccessibilityObserver {} unsafe impl Send for AccessibilityObserver {} @@ -271,12 +278,6 @@ impl Deref for AccessibilityObserver { } } -impl Default for AccessibilityObserver { - fn default() -> Self { - Self(None) - } -} - 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/macos_api.rs b/komorebi/src/macos_api.rs index f4cd7829..b57e33bd 100644 --- a/komorebi/src/macos_api.rs +++ b/komorebi/src/macos_api.rs @@ -53,10 +53,13 @@ pub struct MacosApi; impl MacosApi { pub fn set_wallpaper(path: &Path, display_id: u32) -> eyre::Result<()> { - let path_str = path.to_str().ok_or_eyre("Invalid path encoding")?; + let path_str = path + .to_str() + .ok_or_eyre("Invalid path encoding")? + .to_string(); - DispatchQueue::main().exec_sync(|| { - let ns_path = NSString::from_str(path_str); + DispatchQueue::main().exec_async(move || { + let ns_path = NSString::from_str(&path_str); let url = unsafe { NSURL::fileURLWithPath(&ns_path) }; let mtm = unsafe { MainThreadMarker::new_unchecked() }; diff --git a/komorebi/src/main.rs b/komorebi/src/main.rs index 6c3550bc..3b57add4 100644 --- a/komorebi/src/main.rs +++ b/komorebi/src/main.rs @@ -257,15 +257,16 @@ fn main() -> eyre::Result<()> { StaticConfig::postload(config, &wm)?; } - wm.lock().update_focused_workspace(true, true)?; + wm.lock().retile_all(false)?; border_manager::listen_for_notifications(wm.clone(), CoreFoundationRunLoop(run_loop)); theme_manager::listen_for_notifications(); - listen_for_commands(wm.clone()); - listen_for_events(wm.clone()); monitor_reconciliator::listen_for_notifications(wm.clone())?; reaper::listen_for_notifications(wm.clone()); + listen_for_commands(wm.clone()); + listen_for_events(wm.clone()); + let quit_ctrlc = Arc::new(AtomicBool::new(false)); let quit_thread = quit_ctrlc.clone(); diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index 240607e8..7638ef64 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -1756,8 +1756,7 @@ pub fn read_commands_uds( SocketMessage::TogglePause | SocketMessage::State | SocketMessage::GlobalState - // | SocketMessage::Stop - => Ok(wm.process_command(message, &mut stream)?), + | SocketMessage::Stop => Ok(wm.process_command(message, &mut stream)?), _ => { tracing::trace!("ignoring while paused"); Ok(()) diff --git a/komorebi/src/window.rs b/komorebi/src/window.rs index aca11f61..8bacc78e 100644 --- a/komorebi/src/window.rs +++ b/komorebi/src/window.rs @@ -338,6 +338,10 @@ impl Window { AccessibilityApi::copy_attribute_names(&self.element).is_some() } + pub fn is_focused(&self) -> bool { + MacosApi::foreground_window_id().unwrap_or_default() == self.id + } + #[tracing::instrument(skip_all)] pub fn observe( &self, diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs index c411e5c1..39364751 100644 --- a/komorebic/src/main.rs +++ b/komorebic/src/main.rs @@ -558,6 +558,9 @@ struct Start { #[clap(short, long)] #[clap(value_parser = replace_env_in_path)] config: Option, + /// Start komorebi-bar in a background process + #[clap(long)] + bar: bool, // /// Do not attempt to auto-apply a dumped state temp file from a previously running instance of komorebi // #[clap(long)] // clean_state: bool, @@ -568,6 +571,9 @@ struct Stop { /// Do not restore windows after stopping komorebi #[clap(long, hide = true)] ignore_restore: bool, + /// Stop komorebi-bar if it is running as a background process + #[clap(long)] + bar: bool, } #[derive(Parser)] @@ -1472,6 +1478,17 @@ fn main() -> eyre::Result<()> { return Ok(()); } + if arg.bar { + let mut command = &mut Command::new("komorebi-bar"); + + command = command + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .stdin(Stdio::null()); + + command.spawn()?; + } + println!("\nThank you for using komorebi!\n"); println!("# Commercial Use License"); println!( @@ -1504,6 +1521,10 @@ fn main() -> eyre::Result<()> { send_message(&SocketMessage::Stop)?; } + if arg.bar { + Command::new("pkill").arg("komorebi-bar").spawn()?; + } + // TODO: see if we need a force quit sometimes like we do on Windows // let mut system = sysinfo::System::new_all(); // system.refresh_processes(ProcessesToUpdate::All, true);