diff --git a/.release-plz.toml b/.release-plz.toml index d46416c2..aaa69958 100644 --- a/.release-plz.toml +++ b/.release-plz.toml @@ -30,6 +30,7 @@ changelog_include=[ "soar-operations", "soar-package", "soar-registry", + "soar-tui", "soar-utils" ] changelog_path="./CHANGELOG.md" diff --git a/Cargo.lock b/Cargo.lock index e7abd1a1..9414c12f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -25,7 +25,7 @@ checksum = "35f0f96ce78e38c3dc6d8948aa8163d06385be74000f3c7a95bf1eef35d3ea32" dependencies = [ "cipher", "cpubits", - "cpufeatures", + "cpufeatures 0.3.1", ] [[package]] @@ -37,6 +37,12 @@ dependencies = [ "memchr", ] +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + [[package]] name = "android_system_properties" version = "0.1.6" @@ -115,6 +121,30 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "approx" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6" +dependencies = [ + "num-traits", +] + +[[package]] +name = "ar_archive_writer" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "523e5e187fff36fcb8d1d19ccf0ca4ca43ec3d158316057f66dc6f72716bc5ec" +dependencies = [ + "object 0.39.1", +] + [[package]] name = "arrayvec" version = "0.7.8" @@ -141,11 +171,11 @@ dependencies = [ "no_std_io2", "rayon", "solana-nohash-hasher", - "thiserror", + "thiserror 2.0.21", "tracing", "xxhash-rust", - "zstd 0.13.3", - "zstd-safe 7.3.0", + "zstd 0.13.5", + "zstd-safe 7.4.1", ] [[package]] @@ -158,7 +188,7 @@ dependencies = [ "cfg-if", "libc", "miniz_oxide 0.8.9", - "object", + "object 0.37.3", "rustc-demangle", "windows-link", ] @@ -172,12 +202,39 @@ dependencies = [ "backtrace", ] +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + [[package]] name = "base64" version = "0.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" +[[package]] +name = "bit-set" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0700ddab506f33b20a03b13996eccd309a48e5ff77d0d95926aa0210fb4e95f1" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + [[package]] name = "bitflags" version = "2.13.2" @@ -206,10 +263,19 @@ dependencies = [ "cc", "cfg-if", "constant_time_eq 0.4.2", - "cpufeatures", + "cpufeatures 0.3.1", "memmap2", ] +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + [[package]] name = "block-buffer" version = "0.12.1" @@ -246,6 +312,12 @@ version = "3.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +[[package]] +name = "by_address" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64fa3c856b712db6612c019f14756e64e4bcea13337a6b33b696333a9eaa2d06" + [[package]] name = "bytecount" version = "0.6.9" @@ -279,6 +351,15 @@ dependencies = [ "libbz2-rs-sys", ] +[[package]] +name = "castaway" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a" +dependencies = [ + "rustversion", +] + [[package]] name = "cbc" version = "0.2.1" @@ -331,7 +412,7 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" dependencies = [ - "crypto-common", + "crypto-common 0.2.2", "inout", ] @@ -396,6 +477,20 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" +[[package]] +name = "compact_str" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9dfdd1c2274d9aa354115b09dc9a901d6c5576818cdf70d14cae2bdb47df00ab" +dependencies = [ + "castaway", + "cfg-if", + "itoa", + "rustversion", + "ryu", + "static_assertions", +] + [[package]] name = "compak" version = "0.2.2" @@ -444,6 +539,15 @@ dependencies = [ "rustversion", ] +[[package]] +name = "convert_case" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9" +dependencies = [ + "unicode-segmentation", +] + [[package]] name = "convert_case" version = "0.11.0" @@ -504,6 +608,15 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + [[package]] name = "cpufeatures" version = "0.3.1" @@ -522,6 +635,12 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "critical-section" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" + [[package]] name = "crossbeam-deque" version = "0.8.8" @@ -547,6 +666,43 @@ version = "0.8.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" +[[package]] +name = "crossterm" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8b9f2e4c67f833b660cdb0a3523065869fb35570177239812ed4c905aeff87b" +dependencies = [ + "bitflags 2.13.2", + "crossterm_winapi", + "derive_more", + "document-features", + "mio", + "parking_lot", + "rustix", + "signal-hook", + "signal-hook-mio", + "winapi", +] + +[[package]] +name = "crossterm_winapi" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b" +dependencies = [ + "winapi", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + [[package]] name = "crypto-common" version = "0.2.2" @@ -556,11 +712,21 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "csscolorparser" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb2a7d3066da2de787b7f032c736763eb7ae5d355f81a68bab2675a96008b0bf" +dependencies = [ + "lab", + "phf 0.11.3", +] + [[package]] name = "ctutils" -version = "0.4.3" +version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03bb0e1cc970d482d121d9a1744999169b69a07470b3d644a7894e53fcaf4574" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" dependencies = [ "cmov", ] @@ -571,8 +737,18 @@ version = "0.21.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9cdf337090841a411e2a7f3deb9187445851f91b309c0c0a29e05f74a00a48c0" dependencies = [ - "darling_core", - "darling_macro", + "darling_core 0.21.3", + "darling_macro 0.21.3", +] + +[[package]] +name = "darling" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" +dependencies = [ + "darling_core 0.24.1", + "darling_macro 0.24.1", ] [[package]] @@ -589,17 +765,41 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "darling_core" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 3.0.9", +] + [[package]] name = "darling_macro" version = "0.21.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d38308df82d1080de0afee5d069fa14b0326a88c14f15c5ccda35b4a6c414c81" dependencies = [ - "darling_core", + "darling_core 0.21.3", "quote", "syn 2.0.119", ] +[[package]] +name = "darling_macro" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" +dependencies = [ + "darling_core 0.24.1", + "quote", + "syn 3.0.9", +] + [[package]] name = "deku" version = "0.20.3" @@ -618,19 +818,47 @@ version = "0.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bec2a42b511fc5efd9183f4f71c17885d627b17e7fd9a61a92089406caa4397e" dependencies = [ - "darling", + "darling 0.21.3", "proc-macro-crate", "proc-macro2", "quote", "syn 2.0.119", ] +[[package]] +name = "deltae" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5729f5117e208430e437df2f4843f5e5952997175992d1414f94c57d61e270b4" + [[package]] name = "deranged" version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" +[[package]] +name = "derive_more" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" +dependencies = [ + "derive_more-impl", +] + +[[package]] +name = "derive_more-impl" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" +dependencies = [ + "convert_case 0.10.0", + "proc-macro2", + "quote", + "rustc_version", + "syn 2.0.119", +] + [[package]] name = "diesel" version = "2.3.14" @@ -678,15 +906,25 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer 0.10.4", + "crypto-common 0.1.7", +] + [[package]] name = "digest" version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ - "block-buffer", + "block-buffer 0.12.1", "const-oid", - "crypto-common", + "crypto-common 0.2.2", "ctutils", "zeroize", ] @@ -718,8 +956,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c278cf01d971a2ce2e4a97f2af1c13706e111c2c05636a88f93520b61c75b3cb" dependencies = [ "documented-macros", - "phf", - "thiserror", + "phf 0.13.1", + "thiserror 2.0.21", ] [[package]] @@ -728,8 +966,8 @@ version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3605d4f0b4326a3a1909b6d258b47478c0d47bb668ad2cb7d4a6e2d22e852f5c" dependencies = [ - "convert_case", - "itertools", + "convert_case 0.11.0", + "itertools 0.15.0", "optfield", "proc-macro2", "quote", @@ -749,7 +987,7 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dd122633e4bef06db27737f21d3738fb89c8f6d5360d6d9d7635dda142a7757e" dependencies = [ - "darling", + "darling 0.21.3", "either", "heck", "proc-macro2", @@ -805,6 +1043,25 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "euclid" +version = "0.22.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06" +dependencies = [ + "num-traits", +] + +[[package]] +name = "fancy-regex" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b95f7c0680e4142284cf8b22c14a476e87d61b004a3a0861872b32ef7ead40a2" +dependencies = [ + "bit-set", + "regex", +] + [[package]] name = "fast-glob" version = "1.1.2" @@ -829,6 +1086,17 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "filedescriptor" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e40758ed24c9b2eeb76c35fb0aebc66c626084edd827e07e1552279814c6682d" +dependencies = [ + "libc", + "thiserror 1.0.69", + "winapi", +] + [[package]] name = "filetime" version = "0.2.29" @@ -845,6 +1113,18 @@ version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" +[[package]] +name = "finl_unicode" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ded33109e99472f809cb7495544506eea45e366725dacf2a383e184f660456" + +[[package]] +name = "fixedbitset" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80" + [[package]] name = "flate2" version = "1.1.10" @@ -918,6 +1198,16 @@ dependencies = [ "slab", ] +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + [[package]] name = "getrandom" version = "0.2.17" @@ -929,6 +1219,18 @@ dependencies = [ "wasi", ] +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + [[package]] name = "getrandom" version = "0.4.3" @@ -938,7 +1240,7 @@ dependencies = [ "cfg-if", "js-sys", "libc", - "r-efi", + "r-efi 6.0.0", "wasm-bindgen", ] @@ -965,6 +1267,8 @@ version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" dependencies = [ + "allocator-api2", + "equivalent", "foldhash", ] @@ -974,13 +1278,19 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + [[package]] name = "hmac" version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" dependencies = [ - "digest", + "digest 0.11.3", ] [[package]] @@ -1229,6 +1539,15 @@ dependencies = [ "web-time", ] +[[package]] +name = "indoc" +version = "2.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a37b2691796cffeb8a8cd305ac66e65841559f147f4e63231d0eafa4db5384d1" +dependencies = [ + "rustversion", +] + [[package]] name = "inout" version = "0.2.5" @@ -1239,6 +1558,19 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "instability" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c3b5acc1e2fd9375041a388da33d1eb8aed5f7a8c0dd3543e3ea2805adfbe20" +dependencies = [ + "darling 0.24.1", + "indoc", + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "is_ci" version = "1.2.0" @@ -1251,6 +1583,15 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + [[package]] name = "itertools" version = "0.15.0" @@ -1287,6 +1628,23 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "kasuari" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f14c90e40a6133f4805b83542a7ed7364f56070b447f56e7f4e90297122209" +dependencies = [ + "hashbrown", + "portable-atomic", + "thiserror 2.0.21", +] + +[[package]] +name = "lab" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf36173d4167ed999940f804952e6b08197cae5ad5d572eb4db150ce8ad5d58f" + [[package]] name = "landlock" version = "0.4.7" @@ -1295,7 +1653,7 @@ checksum = "4cca98e95f35b29d469dade6724c6f96cec9236640f745a0e99b0334ec320ab1" dependencies = [ "enumflags2", "libc", - "thiserror", + "thiserror 2.0.21", ] [[package]] @@ -1336,6 +1694,12 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + [[package]] name = "libsqlite3-sys" version = "0.38.2" @@ -1347,6 +1711,15 @@ dependencies = [ "vcpkg", ] +[[package]] +name = "line-clipping" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e752191d037c44ad111a8caa762921926658402f01cc1253f7bef2020ece4f5e" +dependencies = [ + "bitflags 2.13.2", +] + [[package]] name = "linux-raw-sys" version = "0.12.1" @@ -1401,7 +1774,7 @@ version = "0.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7277c9742229dc25243236d578b6471a798c554512c6f6a04365ec2e87c2a3bb" dependencies = [ - "sha2", + "sha2 0.11.1", ] [[package]] @@ -1410,6 +1783,16 @@ version = "0.23.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1c46f3fcd2e888afdb01a07efc071cb21300e07c68d32c3e8b01b5c8cb1fcaa" +[[package]] +name = "mac_address" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3d0581a75c45969c63afd2bb87b1d8b25cfcc556c7a918cf9bb13b0fe8d2381" +dependencies = [ + "nix 0.31.3", + "windows-sys 0.61.2", +] + [[package]] name = "matchers" version = "0.2.0" @@ -1425,7 +1808,7 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bd76fb0fd6b2e4be62a73f8e0858ca97f81babcb1af322dcaca196f735f17f80" dependencies = [ - "digest", + "digest 0.11.3", ] [[package]] @@ -1443,6 +1826,21 @@ dependencies = [ "libc", ] +[[package]] +name = "memmem" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a64a92489e2744ce060c349162be1c5f33c6969234104dbd99ddb5feb08b8c15" + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + [[package]] name = "miette" version = "7.6.0" @@ -1527,6 +1925,18 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "mio" +version = "1.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" +dependencies = [ + "libc", + "log", + "wasi", + "windows-sys 0.61.2", +] + [[package]] name = "moxcms" version = "0.8.1" @@ -1537,16 +1947,29 @@ dependencies = [ "pxfm", ] +[[package]] +name = "nix" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "libc", +] + [[package]] name = "nix" version = "0.31.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" dependencies = [ - "bitflags", + "bitflags 2.13.2", "cfg-if", "cfg_aliases", "libc", + "memoffset", ] [[package]] @@ -1593,6 +2016,17 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" +[[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.119", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -1602,6 +2036,15 @@ dependencies = [ "autocfg", ] +[[package]] +name = "num_threads" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cabcc654086861f9e1bc5115258de62ef92c79b20f4615a1b0cc57c4e82027d4" +dependencies = [ + "libc", +] + [[package]] name = "object" version = "0.37.3" @@ -1611,6 +2054,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "object" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b" +dependencies = [ + "memchr", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -1652,12 +2104,54 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "ordered-float" +version = "4.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7bb71e1b3fa6ca1c61f383464aaf2bb0e2f8e772a1f01d486832464de363b951" +dependencies = [ + "num-traits", +] + [[package]] name = "owo-colors" version = "4.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c45bb4a6ae1280ec0803b1ef9d3455eb50f01efbbe1447ab020f1d54fba9d8" +[[package]] +name = "palette" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddeed8580d347d2abf3dcf06a5f0b3dc020258338526b277847cd4248a70fc64" +dependencies = [ + "approx", + "libm", + "palette_derive", + "palette_math", +] + +[[package]] +name = "palette_derive" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88537020289b719d81be994ccf1bbf4990f477e2f69ee52fe3e45f43a02e56be" +dependencies = [ + "by_address", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "palette_math" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e6eb142958d64335fb0e345c5b9ead2ecd6fc438c307e9d7d3c4fd428dbaf12" +dependencies = [ + "libm", +] + [[package]] name = "papergrid" version = "0.18.0" @@ -1700,7 +2194,7 @@ version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "112d82ceb8c5bf524d9af484d4e4970c9fd5a0cc15ba14ad93dccd28873b0629" dependencies = [ - "digest", + "digest 0.11.3", "hmac", ] @@ -1710,14 +2204,97 @@ version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]] +name = "pest" +version = "2.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ec53fd1d256900a9a771bf2720d42cef6f8bc91b4e25065fbd291e3e7222576" +dependencies = [ + "memchr", + "pest_stack_guard", + "ucd-trie", +] + +[[package]] +name = "pest_derive" +version = "2.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adcf794fd301ddc20818a6b4de85ed507f4b45300245cec948982e69e12e3bd7" +dependencies = [ + "pest", + "pest_generator", +] + +[[package]] +name = "pest_generator" +version = "2.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3073afae5db334c25dea9fc3e230a4f191e920c1df080cb9c0b37c9ce1dbb41" +dependencies = [ + "pest", + "pest_meta", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "pest_meta" +version = "2.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7bc7f614b3742541642af1685faaa910bf6333e3cd3729c2cccd118146a57327" +dependencies = [ + "pest", +] + +[[package]] +name = "pest_stack_guard" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ac6154fd4418b8f0b82532c59c26f303f9ca59a64c883e8ce3971fd82733439" +dependencies = [ + "psm", + "stacker", +] + +[[package]] +name = "phf" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" +dependencies = [ + "phf_macros 0.11.3", + "phf_shared 0.11.3", +] + [[package]] name = "phf" version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" dependencies = [ - "phf_macros", - "phf_shared", + "phf_macros 0.13.1", + "phf_shared 0.13.1", +] + +[[package]] +name = "phf_codegen" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aef8048c789fa5e851558d709946d6d79a8ff88c0440c587967f8e94bfb1216a" +dependencies = [ + "phf_generator 0.11.3", + "phf_shared 0.11.3", +] + +[[package]] +name = "phf_generator" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" +dependencies = [ + "phf_shared 0.11.3", + "rand", ] [[package]] @@ -1727,7 +2304,20 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" dependencies = [ "fastrand", - "phf_shared", + "phf_shared 0.13.1", +] + +[[package]] +name = "phf_macros" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f84ac04429c13a7ff43785d75ad27569f2951ce0ffd30a3321230db2fc727216" +dependencies = [ + "phf_generator 0.11.3", + "phf_shared 0.11.3", + "proc-macro2", + "quote", + "syn 2.0.119", ] [[package]] @@ -1736,13 +2326,22 @@ version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" dependencies = [ - "phf_generator", - "phf_shared", + "phf_generator 0.13.1", + "phf_shared 0.13.1", "proc-macro2", "quote", "syn 2.0.119", ] +[[package]] +name = "phf_shared" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" +dependencies = [ + "siphasher", +] + [[package]] name = "phf_shared" version = "0.13.1" @@ -1776,7 +2375,7 @@ version = "0.18.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" dependencies = [ - "bitflags", + "bitflags 2.13.2", "crc32fast", "fdeflate", "flate2", @@ -1820,52 +2419,184 @@ checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" name = "ppmd-rust" version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "494b4379484fc92217cc7d9e3a532375b1d01a61889ec8333025dc3b0377af56" +checksum = "494b4379484fc92217cc7d9e3a532375b1d01a61889ec8333025dc3b0377af56" + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "psm" +version = "0.1.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622" +dependencies = [ + "ar_archive_writer", + "cc", +] + +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "radium" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" + +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" + +[[package]] +name = "ratatui" +version = "0.30.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3274ba0a2c5e1bcad2a2005d20f4dc59dad26b2eb0940fb094500dba4099d57d" +dependencies = [ + "instability", + "ratatui-core", + "ratatui-crossterm", + "ratatui-macros", + "ratatui-termina", + "ratatui-termwiz", + "ratatui-widgets", + "serde", +] [[package]] -name = "proc-macro-crate" -version = "3.5.0" +name = "ratatui-core" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +checksum = "cbb175c433c8e28a809d1f5773a2ae96e68c0ce40db865cbab1020bf33ae479c" dependencies = [ - "toml_edit", + "bitflags 2.13.2", + "compact_str", + "critical-section", + "hashbrown", + "itertools 0.14.0", + "kasuari", + "lru", + "palette", + "serde", + "strum", + "thiserror 2.0.21", + "unicode-segmentation", + "unicode-truncate", + "unicode-width 0.2.2", ] [[package]] -name = "proc-macro2" -version = "1.0.107" +name = "ratatui-crossterm" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +checksum = "567584a3b0e6a8203c23de40b4861497266725eb5363dbfd18a1edd603cca9f0" dependencies = [ - "unicode-ident", + "cfg-if", + "crossterm", + "instability", + "ratatui-core", ] [[package]] -name = "pxfm" -version = "0.1.30" +name = "ratatui-macros" +version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" +checksum = "ed7dc68daa7498a43e4d68e0eb078427e10c38fbcfbb1e42d955f1fa2140d814" +dependencies = [ + "ratatui-core", + "ratatui-widgets", +] [[package]] -name = "quote" -version = "1.0.47" +name = "ratatui-termina" +version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +checksum = "c0bf912d9e66f057a759d92e386a280ea886b352ab757d6ac4d653c7ed2c43c2" dependencies = [ - "proc-macro2", + "instability", + "ratatui-core", + "termina", ] [[package]] -name = "r-efi" -version = "6.0.0" +name = "ratatui-termwiz" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +checksum = "faf03e0380b7744054d6cb74224fe3adf062a029754933f575ca1e3b4c2ce977" +dependencies = [ + "ratatui-core", + "termwiz", +] [[package]] -name = "radium" -version = "0.7.0" +name = "ratatui-widgets" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" +checksum = "66e3d19bcc9130ca376277d93b60767ff121ace3be06f5f95f81dd68956407d1" +dependencies = [ + "bitflags 2.13.2", + "hashbrown", + "indoc", + "instability", + "itertools 0.14.0", + "line-clipping", + "ratatui-core", + "serde", + "strum", + "time", + "unicode-segmentation", + "unicode-width 0.2.2", +] [[package]] name = "rayon" @@ -1893,7 +2624,7 @@ version = "0.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" dependencies = [ - "bitflags", + "bitflags 2.13.2", ] [[package]] @@ -1934,7 +2665,7 @@ dependencies = [ "fast-glob", "serde", "serde_json", - "thiserror", + "thiserror 2.0.21", "urlencoding", ] @@ -1958,7 +2689,7 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "353b74f9810d5b085b6c42c9d86a5f0fdb795553235cdd48753b32e3809d18a7" dependencies = [ - "thiserror", + "thiserror 2.0.21", ] [[package]] @@ -1967,13 +2698,22 @@ version = "0.1.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b74b56ffa8bb2830709a538c2cbcae9aa062db0d2a42563bfb09bdaae44020eb" +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + [[package]] name = "rustix" version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" dependencies = [ - "bitflags", + "bitflags 2.13.2", "errno", "libc", "linux-raw-sys", @@ -2033,6 +2773,12 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + [[package]] name = "schannel" version = "0.1.30" @@ -2074,7 +2820,7 @@ version = "3.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" dependencies = [ - "bitflags", + "bitflags 2.13.2", "core-foundation", "core-foundation-sys", "libc", @@ -2189,7 +2935,7 @@ dependencies = [ "js-sys", "lzma-rust2 0.23.0", "ppmd-rust", - "sha2", + "sha2 0.11.1", "wasm-bindgen", ] @@ -2200,8 +2946,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214" dependencies = [ "cfg-if", - "cpufeatures", - "digest", + "cpufeatures 0.3.1", + "digest 0.11.3", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", ] [[package]] @@ -2211,8 +2968,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" dependencies = [ "cfg-if", - "cpufeatures", - "digest", + "cpufeatures 0.3.1", + "digest 0.11.3", ] [[package]] @@ -2230,6 +2987,37 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +[[package]] +name = "signal-hook" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2" +dependencies = [ + "libc", + "signal-hook-registry", +] + +[[package]] +name = "signal-hook-mio" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b75a19a7a740b25bc7944bdee6172368f988763b744e3d4dfe753f6b4ece40cc" +dependencies = [ + "libc", + "mio", + "signal-hook", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + [[package]] name = "simd-adler32" version = "0.3.10" @@ -2262,7 +3050,7 @@ dependencies = [ "clap_complete", "indicatif", "miette", - "nix", + "nix 0.31.3", "nu-ansi-term", "regex", "semver", @@ -2276,6 +3064,7 @@ dependencies = [ "soar-operations", "soar-package", "soar-registry", + "soar-tui", "soar-utils", "tabled", "tempfile", @@ -2296,7 +3085,7 @@ dependencies = [ "serde", "soar-utils", "tempfile", - "thiserror", + "thiserror 2.0.21", "toml 1.1.8+spec-1.1.0", "toml_edit", "tracing", @@ -2313,7 +3102,7 @@ dependencies = [ "landlock", "libsqlite3-sys", "miette", - "nix", + "nix 0.31.3", "percent-encoding", "regex", "serde", @@ -2325,7 +3114,7 @@ dependencies = [ "soar-package", "soar-utils", "tempfile", - "thiserror", + "thiserror 2.0.21", "toml 1.1.8+spec-1.1.0", "tracing", "ureq", @@ -2346,7 +3135,7 @@ dependencies = [ "soar-registry", "soar-utils", "tempfile", - "thiserror", + "thiserror 2.0.21", "tracing", ] @@ -2359,17 +3148,17 @@ dependencies = [ "flate2", "httpdate", "miette", - "nix", + "nix 0.31.3", "percent-encoding", "regex", "releasekit", "rustls-native-certs", "serde", "serde_json", - "sha2", + "sha2 0.11.1", "soar-utils", "tempfile", - "thiserror", + "thiserror 2.0.21", "tracing", "ureq", "url", @@ -2421,7 +3210,7 @@ dependencies = [ "squishy", "stipplefs", "tempfile", - "thiserror", + "thiserror 2.0.21", "tokio", "tracing", "zstd 0.14.3", @@ -2439,23 +3228,41 @@ dependencies = [ "soar-dl", "soar-utils", "tempfile", - "thiserror", + "thiserror 2.0.21", "tracing", "ureq", "url", "zstd 0.14.3", ] +[[package]] +name = "soar-tui" +version = "0.1.0" +dependencies = [ + "chrono", + "nucleo-matcher", + "ratatui", + "serde_json", + "soar-config", + "soar-core", + "soar-events", + "soar-operations", + "soar-utils", + "tokio", + "tracing", + "tracing-subscriber", +] + [[package]] name = "soar-utils" version = "0.6.0" dependencies = [ "blake3", "miette", - "nix", + "nix 0.31.3", "serial_test", "tempfile", - "thiserror", + "thiserror 2.0.21", ] [[package]] @@ -2487,11 +3294,11 @@ dependencies = [ "positioned-io", "rayon", "serde", - "sha2", - "thiserror", + "sha2 0.11.1", + "thiserror 2.0.21", "xxhash-rust", "zerocopy", - "zstd-safe 7.3.0", + "zstd-safe 7.4.1", ] [[package]] @@ -2500,6 +3307,25 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +[[package]] +name = "stacker" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967" +dependencies = [ + "cc", + "cfg-if", + "libc", + "psm", + "windows-sys 0.61.2", +] + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + [[package]] name = "stipplefs" version = "0.2.0" @@ -2565,6 +3391,17 @@ version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b7401a30af6cb5818bb64852270bb722533397edcfc7344954a38f420819ece2" +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "syn" version = "2.0.119" @@ -2634,12 +3471,25 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.3", + "getrandom 0.3.4", "once_cell", "rustix", "windows-sys 0.61.2", ] +[[package]] +name = "termina" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9048a889effe34a5cddee0af7f53285198b16dca3be510858d38dfdb3e62a04e" +dependencies = [ + "bitflags 2.13.2", + "parking_lot", + "rustix", + "signal-hook", + "windows-sys 0.61.2", +] + [[package]] name = "terminal_size" version = "0.4.4" @@ -2650,6 +3500,69 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "terminfo" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4ea810f0692f9f51b382fff5893887bb4580f5fa246fde546e0b13e7fcee662" +dependencies = [ + "fnv", + "nom", + "phf 0.11.3", + "phf_codegen", +] + +[[package]] +name = "termios" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "411c5bf740737c7918b8b1fe232dca4dc9f8e754b8ad5e20966814001ed0ac6b" +dependencies = [ + "libc", +] + +[[package]] +name = "termwiz" +version = "0.23.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4676b37242ccbd1aabf56edb093a4827dc49086c0ffd764a5705899e0f35f8f7" +dependencies = [ + "anyhow", + "base64 0.22.1", + "bitflags 2.13.2", + "fancy-regex", + "filedescriptor", + "finl_unicode", + "fixedbitset", + "hex", + "lazy_static", + "libc", + "log", + "memmem", + "nix 0.29.0", + "num-derive", + "num-traits", + "ordered-float", + "pest", + "pest_derive", + "phf 0.11.3", + "sha2 0.10.9", + "signal-hook", + "siphasher", + "terminfo", + "termios", + "thiserror 1.0.69", + "ucd-trie", + "unicode-segmentation", + "vtparse", + "wezterm-bidi", + "wezterm-blob-leases", + "wezterm-color-types", + "wezterm-dynamic", + "wezterm-input-types", + "winapi", +] + [[package]] name = "testing_table" version = "0.3.0" @@ -2670,13 +3583,33 @@ dependencies = [ "unicode-width 0.2.2", ] +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + [[package]] name = "thiserror" version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" dependencies = [ - "thiserror-impl", + "thiserror-impl 2.0.21", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", ] [[package]] @@ -2707,7 +3640,9 @@ checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" dependencies = [ "deranged", "js-sys", + "libc", "num-conv", + "num_threads", "powerfmt", "serde_core", "time-core", @@ -2747,8 +3682,12 @@ version = "1.54.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" dependencies = [ + "libc", + "mio", "pin-project-lite", + "signal-hook-registry", "tokio-macros", + "windows-sys 0.61.2", ] [[package]] @@ -2915,6 +3854,12 @@ version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" +[[package]] +name = "ucd-trie" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971" + [[package]] name = "unicode-ident" version = "1.0.27" @@ -2927,6 +3872,17 @@ version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" +[[package]] +name = "unicode-truncate" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16b380a1238663e5f8a691f9039c73e1cdae598a30e9855f541d29b08b53e9a5" +dependencies = [ + "itertools 0.14.0", + "unicode-segmentation", + "unicode-width 0.2.2", +] + [[package]] name = "unicode-width" version = "0.1.14" @@ -2957,7 +3913,7 @@ version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cde93ff05758a36a851a398a772b0b79a82fbe3c186a46f2696baaeaf84c966b" dependencies = [ - "base64", + "base64 0.23.1", "cookie_store", "flate2", "log", @@ -2977,7 +3933,7 @@ version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "841583fc36089d7d59419568ae157f43a5a03a2e5a81ba87c77d1596ef46e922" dependencies = [ - "base64", + "base64 0.23.1", "http", "httparse", "log", @@ -3019,6 +3975,17 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" +[[package]] +name = "uuid" +version = "1.29.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c14b15dffa2f4bd712103e857140aa04a4f2ff6e955c77d7eb8e53ee02a3b64" +dependencies = [ + "getrandom 0.4.3", + "js-sys", + "wasm-bindgen", +] + [[package]] name = "valuable" version = "0.1.1" @@ -3047,12 +4014,30 @@ dependencies = [ "memchr", ] +[[package]] +name = "vtparse" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d9b2acfb050df409c972a37d3b8e08cdea3bddb0c09db9d53137e504cfabed0" +dependencies = [ + "utf8parse", +] + [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + [[package]] name = "wasm-bindgen" version = "0.2.129" @@ -3117,6 +4102,78 @@ dependencies = [ "rustls-pki-types", ] +[[package]] +name = "wezterm-bidi" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c0a6e355560527dd2d1cf7890652f4f09bb3433b6aadade4c9b5ed76de5f3ec" +dependencies = [ + "log", + "wezterm-dynamic", +] + +[[package]] +name = "wezterm-blob-leases" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "692daff6d93d94e29e4114544ef6d5c942a7ed998b37abdc19b17136ea428eb7" +dependencies = [ + "getrandom 0.3.4", + "mac_address", + "sha2 0.10.9", + "thiserror 1.0.69", + "uuid", +] + +[[package]] +name = "wezterm-color-types" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7de81ef35c9010270d63772bebef2f2d6d1f2d20a983d27505ac850b8c4b4296" +dependencies = [ + "csscolorparser", + "deltae", + "lazy_static", + "wezterm-dynamic", +] + +[[package]] +name = "wezterm-dynamic" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f2ab60e120fd6eaa68d9567f3226e876684639d22a4219b313ff69ec0ccd5ac" +dependencies = [ + "log", + "ordered-float", + "strsim", + "thiserror 1.0.69", + "wezterm-dynamic-derive", +] + +[[package]] +name = "wezterm-dynamic-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46c0cf2d539c645b448eaffec9ec494b8b19bd5077d9e58cb1ae7efece8d575b" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "wezterm-input-types" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7012add459f951456ec9d6c7e6fc340b1ce15d6fc9629f8c42853412c029e57e" +dependencies = [ + "bitflags 1.3.2", + "euclid", + "lazy_static", + "serde", + "wezterm-dynamic", +] + [[package]] name = "winapi" version = "0.3.9" @@ -3295,6 +4352,12 @@ dependencies = [ "memchr", ] +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + [[package]] name = "writeable" version = "0.6.4" @@ -3446,7 +4509,7 @@ dependencies = [ "indexmap", "lzma-rust2 0.22.0", "memchr", - "nix", + "nix 0.31.3", "pbkdf2", "sha1", "time", @@ -3482,11 +4545,11 @@ dependencies = [ [[package]] name = "zstd" -version = "0.13.3" +version = "0.13.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a" +checksum = "50adf04cf3ec914b0b9905c9dde90c80fe74bfd701e331fc80a39c512c525278" dependencies = [ - "zstd-safe 7.3.0", + "zstd-safe 7.4.1", ] [[package]] @@ -3500,9 +4563,9 @@ dependencies = [ [[package]] name = "zstd-safe" -version = "7.3.0" +version = "7.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64d80649ab6db9d9f6f9c80a40becd948eda4714a0a5ac8c4d157a32231c7882" +checksum = "498d94ad68720c89b4fbe41b9090850651e68cb2dd9210ce7ffbff3a94653819" dependencies = [ "zstd-sys", ] @@ -3535,6 +4598,6 @@ dependencies = [ "clap", "md4", "sha1", - "thiserror", + "thiserror 2.0.21", "ureq", ] diff --git a/Cargo.toml b/Cargo.toml index 8655b1e2..8f93c5ff 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -38,6 +38,7 @@ nu-ansi-term = "0.50.3" onelf-format = "0.6.1" once_cell = "1.21" percent-encoding = "2.3.2" +ratatui = "0.30" rayon = "1.12.0" releasekit = { version = "0.1.0", default-features = false } regex = { version = "1.13.1", default-features = false, features = [ @@ -59,6 +60,7 @@ soar-events = { version = "0.4.0", path = "crates/soar-events" } soar-operations = { version = "0.7.2", path = "crates/soar-operations" } soar-package = { version = "0.8.1", path = "crates/soar-package" } soar-registry = { version = "0.7.1", path = "crates/soar-registry" } +soar-tui = { version = "0.1.0", path = "crates/soar-tui" } soar-utils = { version = "0.6.0", path = "crates/soar-utils" } squishy = { version = "0.5.3", features = ["appimage", "dwarfs"] } stipplefs = { version = "0.2.0", default-features = false, features = ["fs", "read", "zstd"] } @@ -66,7 +68,7 @@ tabled = { version = "0.22", default-features = false, features = ["ansi"] } terminal_size = "0.4" tempfile = "3.27.0" thiserror = "2.0.21" -tokio = { version = "1.54.1", features = ["macros", "rt-multi-thread", "sync", "time"] } +tokio = { version = "1.54.1", features = ["macros", "rt-multi-thread", "signal", "sync", "time"] } toml = "1.1.8" toml_edit = "0.25.17" tracing = { version = "0.1.44", default-features = false } diff --git a/crates/soar-cli/Cargo.toml b/crates/soar-cli/Cargo.toml index 4a2a4f8d..8ab33413 100644 --- a/crates/soar-cli/Cargo.toml +++ b/crates/soar-cli/Cargo.toml @@ -16,7 +16,9 @@ name = "soar" path = "src/main.rs" [features] +default = ["tui"] self = [] +tui = ["dep:soar-tui"] [dependencies] clap = { workspace = true } @@ -37,6 +39,7 @@ soar-events = { workspace = true } soar-operations = { workspace = true } soar-package = { workspace = true } soar-registry = { workspace = true } +soar-tui = { workspace = true, optional = true } soar-utils = { workspace = true } tabled = { workspace = true } tempfile = { workspace = true } diff --git a/crates/soar-cli/src/apply.rs b/crates/soar-cli/src/apply.rs index f93154ce..ba223c32 100644 --- a/crates/soar-cli/src/apply.rs +++ b/crates/soar-cli/src/apply.rs @@ -17,6 +17,7 @@ use tabled::{ use tracing::{info, warn}; use crate::{ + interrupt::InterruptGuard, json_output::{self, ApplyDiffJson}, progress::create_wait_job, utils::{Colored, Icons, display_settings, icon_or, json_enabled}, @@ -190,9 +191,16 @@ pub async fn apply_packages( } } - let report = - apply::execute_apply(ctx, diff, no_verify, &packages_path.to_string_lossy()).await?; - display_apply_report(&report); + { + let _interrupt = InterruptGuard::install(ctx.cancel_token().clone()); + let report = + apply::execute_apply(ctx, diff, no_verify, &packages_path.to_string_lossy()).await?; + display_apply_report(&report); + + if ctx.cancel_token().is_cancelled() { + return Err(SoarError::Cancelled); + } + } if !deferred_system.is_empty() { return apply_system(deferred_system.len()); @@ -332,4 +340,7 @@ fn display_apply_report(report: &ApplyReport) { if report.failed_count > 0 { warn!(" Failed: {}", report.failed_count); } + if report.cancelled_count > 0 { + warn!(" Cancelled: {}", report.cancelled_count); + } } diff --git a/crates/soar-cli/src/cli.rs b/crates/soar-cli/src/cli.rs index 7ecb99b9..d1953fb8 100644 --- a/crates/soar-cli/src/cli.rs +++ b/crates/soar-cli/src/cli.rs @@ -577,6 +577,11 @@ pub enum Commands { only_system: bool, }, + /// Open the interactive terminal interface + #[cfg(feature = "tui")] + #[clap(name = "tui")] + Tui, + /// Generate default packages configuration #[clap(name = "defpackages")] DefPackages, @@ -642,4 +647,11 @@ mod tests { assert_eq!(connections, Some(expected)); } } + + #[cfg(feature = "tui")] + #[test] + fn tui_parses() { + let args = Args::try_parse_from(["soar", "tui"]).unwrap(); + assert!(matches!(args.command, Commands::Tui)); + } } diff --git a/crates/soar-cli/src/health.rs b/crates/soar-cli/src/health.rs index 075b27bb..3c16c44d 100644 --- a/crates/soar-cli/src/health.rs +++ b/crates/soar-cli/src/health.rs @@ -1,5 +1,5 @@ use nu_ansi_term::Color::{Blue, Green, Red, Yellow}; -use soar_core::SoarResult; +use soar_core::{SoarResult, error::SoarError}; use soar_operations::{SoarContext, health}; use tabled::{ builder::Builder, @@ -7,7 +7,10 @@ use tabled::{ }; use tracing::info; -use crate::utils::{Colored, Icons, icon_or, term_width}; +use crate::{ + interrupt::InterruptGuard, + utils::{Colored, Icons, icon_or, term_width}, +}; pub async fn display_health(ctx: &SoarContext) -> SoarResult<()> { let report = health::check_health(ctx)?; @@ -113,9 +116,10 @@ pub fn remove_broken_symlinks(ctx: &SoarContext) -> SoarResult<()> { } pub async fn remove_broken_packages(ctx: &SoarContext) -> SoarResult<()> { + let _interrupt = InterruptGuard::install(ctx.cancel_token().clone()); let report = health::remove_broken_packages(ctx).await?; - if report.removed.is_empty() && report.failed.is_empty() { + if report.removed.is_empty() && report.failed.is_empty() && !ctx.cancel_token().is_cancelled() { info!("No broken packages found."); return Ok(()); } @@ -128,6 +132,10 @@ pub async fn remove_broken_packages(ctx: &SoarContext) -> SoarResult<()> { tracing::error!("Failed to remove {}: {}", failed.pkg_name, failed.error); } + if ctx.cancel_token().is_cancelled() { + return Err(SoarError::Cancelled); + } + if !report.removed.is_empty() && report.failed.is_empty() { info!("Removed all broken packages"); } else if !report.failed.is_empty() { diff --git a/crates/soar-cli/src/install.rs b/crates/soar-cli/src/install.rs index 1ba3fba4..aa4b7fca 100644 --- a/crates/soar-cli/src/install.rs +++ b/crates/soar-cli/src/install.rs @@ -1,5 +1,5 @@ use nu_ansi_term::Color::{Blue, Cyan, Green, Magenta, Red, Yellow}; -use soar_core::{SoarResult, package::install::InstallTarget}; +use soar_core::{SoarResult, error::SoarError, package::install::InstallTarget}; use soar_operations::{InstallOptions, InstallReport, ResolveResult, SoarContext, install, search}; use tabled::{ builder::Builder, @@ -8,6 +8,7 @@ use tabled::{ use tracing::{debug, error, info, warn}; use crate::{ + interrupt::InterruptGuard, progress::create_wait_job, utils::{ Colored, Icons, ask_target_action, display_settings, icon_or, select_package_interactively, @@ -126,9 +127,14 @@ pub async fn install_packages( return Ok(()); } + let _interrupt = InterruptGuard::install(ctx.cancel_token().clone()); let report = install::perform_installation(ctx, install_targets, &options).await?; display_install_report(&report, no_notes); + if ctx.cancel_token().is_cancelled() { + return Err(SoarError::Cancelled); + } + Ok(()) } @@ -387,9 +393,14 @@ async fn install_with_show( return Ok(()); } + let _interrupt = InterruptGuard::install(ctx.cancel_token().clone()); let report = install::perform_installation(ctx, install_targets, options).await?; display_install_report(&report, no_notes); + if ctx.cancel_token().is_cancelled() { + return Err(SoarError::Cancelled); + } + Ok(()) } @@ -471,7 +482,8 @@ fn display_install_report(report: &InstallReport, no_notes: bool) { let installed_count = report.installed.len(); let failed_count = report.failed.len(); - let total_packages = installed_count + failed_count; + let cancelled_count = report.cancelled.len(); + let total_packages = installed_count + failed_count + cancelled_count; if use_icons { let mut builder = Builder::new(); @@ -492,7 +504,13 @@ fn display_install_report(report: &InstallReport, no_notes: bool) { format!("{}", Colored(Red, failed_count)), ]); } - if installed_count == 0 && failed_count == 0 { + if cancelled_count > 0 { + builder.push_record([ + format!("{} Cancelled", icon_or(Icons::WARNING, "!")), + format!("{}", Colored(Yellow, cancelled_count)), + ]); + } + if installed_count == 0 && failed_count == 0 && cancelled_count == 0 { builder.push_record([ format!("{} Status", icon_or(Icons::WARNING, "!")), "No packages installed".to_string(), @@ -509,15 +527,22 @@ fn display_install_report(report: &InstallReport, no_notes: bool) { info!("\n{table}"); } else if installed_count > 0 { info!( - "Installed {}/{} packages{}", + "Installed {}/{} packages{}{}", installed_count, total_packages, if failed_count > 0 { format!(", {} failed", failed_count) } else { String::new() + }, + if cancelled_count > 0 { + format!(", {} cancelled", cancelled_count) + } else { + String::new() } ); + } else if cancelled_count > 0 { + info!("No packages installed, {} cancelled.", cancelled_count); } else { info!("No packages installed."); } diff --git a/crates/soar-cli/src/interrupt.rs b/crates/soar-cli/src/interrupt.rs new file mode 100644 index 00000000..b954d7ae --- /dev/null +++ b/crates/soar-cli/src/interrupt.rs @@ -0,0 +1,97 @@ +//! Turning Ctrl-C into a cancel request for the running operation. + +use std::sync::{ + Arc, + atomic::{AtomicBool, Ordering}, +}; + +use soar_utils::cancel::CancelToken; + +/// What a Ctrl-C means at this point. +#[derive(Debug, PartialEq, Eq)] +enum OnInterrupt { + /// Ask the operation to stop at its next safe point. + Cancel, + /// Quit now. + Exit, +} + +/// First press cancels. A second press, or any press after the operation is +/// over, exits. +fn on_interrupt(presses: u32, finished: bool) -> OnInterrupt { + if presses == 1 && !finished { + OnInterrupt::Cancel + } else { + OnInterrupt::Exit + } +} + +/// Turns Ctrl-C into cancelling `token` while the guard lives. +/// +/// tokio never removes a signal handler once installed, so after the guard +/// drops, Ctrl-C exits at once instead of being ignored. +pub struct InterruptGuard { + finished: Arc, +} + +impl InterruptGuard { + /// Cancels `token` on the first Ctrl-C until the returned guard drops. + pub fn install(token: CancelToken) -> InterruptGuard { + let finished = Arc::new(AtomicBool::new(false)); + tokio::spawn({ + let finished = Arc::clone(&finished); + async move { + let mut presses = 0u32; + loop { + if tokio::signal::ctrl_c().await.is_err() { + return; + } + presses += 1; + match on_interrupt(presses, finished.load(Ordering::Relaxed)) { + OnInterrupt::Cancel => { + token.cancel(); + if !crate::utils::json_enabled() { + crate::progress::suspend(|| { + eprintln!("Aborting. Press Ctrl-C again to quit now.") + }); + } + } + OnInterrupt::Exit => { + crate::progress::stop(); + std::process::exit(130); + } + } + } + } + }); + InterruptGuard { + finished, + } + } +} + +impl Drop for InterruptGuard { + fn drop(&mut self) { + self.finished.store(true, Ordering::Relaxed); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_first_press_cancels() { + assert_eq!(on_interrupt(1, false), OnInterrupt::Cancel); + } + + #[test] + fn a_second_press_exits() { + assert_eq!(on_interrupt(2, false), OnInterrupt::Exit); + } + + #[test] + fn a_press_after_the_operation_is_over_exits() { + assert_eq!(on_interrupt(1, true), OnInterrupt::Exit); + } +} diff --git a/crates/soar-cli/src/main.rs b/crates/soar-cli/src/main.rs index 2d779f94..5ec1c514 100644 --- a/crates/soar-cli/src/main.rs +++ b/crates/soar-cli/src/main.rs @@ -3,8 +3,7 @@ use std::{ ffi::OsString, fs, io::{IsTerminal as _, Read}, - os::unix::fs::PermissionsExt as _, - path::{Path, PathBuf}, + path::Path, process::Command, sync::{Arc, Mutex}, }; @@ -23,8 +22,8 @@ use progress::{ProgressGuard, create_download_job, handle_download_progress, spa use remove::remove_packages; use run::run_package; use soar_config::config::{ - self, CONFIG_PATH, Config, PATH_ENV_SUFFIXES, enable_system_mode, generate_default_config, - get_config, path_env_var, set_current_profile, + self, CONFIG_PATH, Config, enable_system_mode, generate_default_config, get_config, + path_env_var, set_current_profile, }; use soar_core::{ SoarResult, @@ -33,7 +32,10 @@ use soar_core::{ }; use soar_dl::http_client::configure_http_client; use soar_events::EventSinkHandle; -use soar_operations::SoarContext; +use soar_operations::{ + SoarContext, + privilege::{ESCALATION_DIRS, escalated_command, find_escalation_tool}, +}; use soar_utils::path::resolve_path; use tracing::{debug, info, warn}; use update::update_packages; @@ -50,6 +52,7 @@ mod cli; mod download; mod health; mod install; +mod interrupt; mod json2db; mod json_output; mod list; @@ -97,7 +100,7 @@ pub fn create_context_for(answers_with_document: bool) -> (SoarContext, Option

bool { return true; } + #[cfg(feature = "tui")] + if matches!(command, cli::Commands::Tui) { + return true; + } + matches!( command, cli::Commands::Install { .. } @@ -168,35 +176,6 @@ fn requires_root(command: &cli::Commands) -> bool { ) } -/// Directories a privilege escalation tool is taken from. -/// -/// They are writable only by root. A tool found through `PATH` could be any -/// program the user's environment points at, which would then show the -/// password prompt. -const ESCALATION_DIRS: &[&str] = &[ - "/run/wrappers/bin", - "/usr/local/bin", - "/usr/bin", - "/bin", - "/usr/sbin", - "/sbin", -]; - -/// The absolute path of `doas` or else `sudo`, from [`ESCALATION_DIRS`]. -/// -/// Probing by running the escalation tool would prompt for a password just to -/// learn whether it is installed, which is what the caller is trying to avoid. -fn find_escalation_tool() -> Option { - ["doas", "sudo"].iter().find_map(|name| { - ESCALATION_DIRS - .iter() - .map(|dir| Path::new(dir).join(name)) - .find(|path| { - fs::metadata(path).is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0) - }) - }) -} - /// Handle system mode - check for root privileges and re-exec with sudo/doas if needed fn handle_system_mode(command: &cli::Commands) -> SoarResult<()> { if nix::unistd::geteuid().is_root() { @@ -215,7 +194,7 @@ fn handle_system_mode(command: &cli::Commands) -> SoarResult<()> { .map_err(|e| SoarError::Custom(format!("Failed to get current executable path: {e}")))?; let args: Vec = env::args().skip(1).collect(); - let escalation_cmd = find_escalation_tool().ok_or_else(|| { + let tool = find_escalation_tool().ok_or_else(|| { SoarError::Custom(format!( "System mode requires root privileges. Neither 'doas' nor 'sudo' found in {}.", ESCALATION_DIRS.join(", ") @@ -224,45 +203,65 @@ fn handle_system_mode(command: &cli::Commands) -> SoarResult<()> { debug!( "System mode requires root privileges. Re-executing with {}...", - escalation_cmd.display() + tool.path.display() ); - // sudo and doas both reset the environment, so the system overrides are - // handed to the privileged process explicitly. Without this, a read-only - // `--system` command and a privileged one would resolve different trees. - let forwarded: Vec = PATH_ENV_SUFFIXES - .iter() - .filter_map(|suffix| { - let var = path_env_var(suffix, true); - env::var_os(&var).map(|value| { - let mut assignment = OsString::from(format!("{var}=")); - assignment.push(value); - assignment - }) - }) - .collect(); - - let mut command = Command::new(&escalation_cmd); - if !forwarded.is_empty() { - command.arg("env").args(&forwarded); - } + let os_args: Vec = args.iter().map(OsString::from).collect(); + let mut command = escalated_command(&tool, &[], ¤t_exe, &os_args); - let status = command - .arg(¤t_exe) - .args(&args) - .status() - .with_context(|| { - format!( - "executing {} {:?} {:?}", - escalation_cmd.display(), - current_exe, - args - ) - })?; + let status = command.status().with_context(|| { + format!( + "executing {} {:?} {:?}", + tool.path.display(), + current_exe, + args + ) + })?; std::process::exit(status.code().unwrap_or(1)); } +/// Rebuilds the global options a privileged soar child needs, so it reads +/// the same configuration and connections this process was given. The +/// configuration path is the resolved one, since the child starts in the +/// working directory the interface runs in, not the one the user typed in. +#[cfg(feature = "tui")] +fn global_args(args: &Args, config_path: &Path) -> Vec { + let mut forward: Vec = Vec::new(); + if args.config.is_some() { + forward.push("--config".into()); + forward.push(config_path.as_os_str().to_os_string()); + } + if let Some(profile) = &args.profile { + forward.push("--profile".into()); + forward.push(profile.into()); + } + if let Some(proxy) = &args.proxy { + forward.push("--proxy".into()); + forward.push(proxy.into()); + } + if let Some(headers) = &args.header { + for header in headers { + forward.push("--header".into()); + forward.push(header.into()); + } + } + if let Some(user_agent) = &args.user_agent { + forward.push("--user-agent".into()); + forward.push(user_agent.into()); + } + if args.ipv4 { + forward.push("-4".into()); + } + if args.ipv6 { + forward.push("-6".into()); + } + if args.no_color { + forward.push("--no-color".into()); + } + forward +} + /// Replaces a `-` among `values` with the words `read` supplies. /// /// This runs on lists clap has already parsed, so whatever stdin holds can @@ -357,6 +356,12 @@ async fn handle_cli() -> SoarResult<()> { let mut args = Args::parse(); expand_stdin(&mut args.command)?; + #[cfg(feature = "tui")] + if !matches!(args.command, cli::Commands::Tui) { + setup_logging(&args); + } + + #[cfg(not(feature = "tui"))] setup_logging(&args); if args.no_color { @@ -428,6 +433,20 @@ async fn handle_cli() -> SoarResult<()> { } }); + #[cfg(feature = "tui")] + // The match below moves the command out of `args`, so the global + // options the interface forwards to a privileged child are rebuilt + // here, after the configuration path has been resolved. + let forward_args = if matches!(args.command, cli::Commands::Tui) { + let config_path = CONFIG_PATH + .read() + .map(|path| path.to_path_buf()) + .unwrap_or_default(); + global_args(&args, &config_path) + } else { + Vec::new() + }; + match args.command { cli::Commands::DefConfig { repositories, @@ -750,6 +769,28 @@ async fn handle_cli() -> SoarResult<()> { let mut cmd = cli::Args::command(); clap_complete::generate(shell, &mut cmd, "soar", &mut std::io::stdout()); } + #[cfg(feature = "tui")] + cli::Commands::Tui => { + if utils::json_enabled() { + return Err(SoarError::Custom("soar tui does not support --json".into())); + } + if !std::io::stdin().is_terminal() || !std::io::stdout().is_terminal() { + return Err(SoarError::Custom( + "soar tui needs an interactive terminal".into(), + )); + } + let no_color = !*COLOR.read().unwrap() + || env::var_os("NO_COLOR").is_some_and(|v| !v.is_empty()); + soar_tui::run(soar_tui::TuiOptions { + version: env!("CARGO_PKG_VERSION").to_string(), + no_color, + icons: get_config().display().icons(), + verbosity: args.verbose, + quiet: args.quiet, + forward_args, + }) + .await?; + } _ => unreachable!(), } @@ -785,6 +826,14 @@ async fn main() { .ok(); if let Err(err) = handle_cli().await { + // An aborted operation has already said what finished and what did + // not, so a full report would only repeat it. + if matches!(err, SoarError::Cancelled) { + if !utils::json_enabled() { + eprintln!("Aborted"); + } + std::process::exit(130); + } // Use miette's error display for Diagnostic errors eprintln!("{:?}", miette::Report::new(err)); // Anything driving soar reads the exit code to know whether the work @@ -854,14 +903,35 @@ mod tests { assert!(open_in_editor("false", &path).is_err()); } + #[cfg(feature = "tui")] #[test] - fn the_escalation_tool_comes_from_a_root_owned_directory() { - if let Some(tool) = find_escalation_tool() { - assert!( - ESCALATION_DIRS - .iter() - .any(|dir| tool.parent() == Some(Path::new(dir))) - ); - } + fn tui_requires_root_in_system_mode() { + assert!(requires_root(&cli::Commands::Tui)); + } + + #[cfg(feature = "tui")] + #[test] + fn the_tui_child_gets_the_resolved_global_options() { + let args = Args::try_parse_from(["soar", "-c", "x.toml", "-p", "work", "tui"]).unwrap(); + let forward: Vec = global_args(&args, Path::new("/home/user/.config/soar/x.toml")) + .into_iter() + .map(|arg| arg.to_string_lossy().into_owned()) + .collect(); + let config_at = forward.iter().position(|arg| arg == "--config").unwrap(); + let path = &forward[config_at + 1]; + assert!(Path::new(path).is_absolute(), "config path is {path}"); + assert!(path.ends_with("x.toml"), "config path is {path}"); + let profile_at = forward.iter().position(|arg| arg == "--profile").unwrap(); + assert_eq!(forward[profile_at + 1], "work"); + assert!(!forward.iter().any(|arg| arg == "--json")); + assert!(!forward.iter().any(|arg| arg == "-S")); + } + + #[cfg(feature = "tui")] + #[test] + fn global_options_not_given_stay_out_of_the_forwarded_arguments() { + let args = Args::try_parse_from(["soar", "-4", "tui"]).unwrap(); + let forward = global_args(&args, Path::new("/unused/config.toml")); + assert_eq!(forward, [OsString::from("-4")]); } } diff --git a/crates/soar-cli/src/progress.rs b/crates/soar-cli/src/progress.rs index 48fa0e91..7429dcf7 100644 --- a/crates/soar-cli/src/progress.rs +++ b/crates/soar-cli/src/progress.rs @@ -8,7 +8,7 @@ use indicatif::{MultiProgress, ProgressBar, ProgressStyle}; use nu_ansi_term::Color::{Cyan, Green, Red, Yellow}; use soar_dl::types::Progress; use soar_events::{ - BuildStage, InstallStage, LogLevel, OperationId, RemoveStage, SoarEvent, SyncStage, + BuildStage, EventSink, InstallStage, LogLevel, OperationId, RemoveStage, SoarEvent, SyncStage, UpdateCleanupStage, VerifyStage, }; @@ -27,6 +27,24 @@ pub fn stop() { MULTI.clear().ok(); } +/// Prints the lines a hook or build command wrote, and drops everything else. +/// +/// Used when the progress display is off, where no other event has anywhere +/// to go. Keeping the lines on stdout is where a child's output used to land +/// when it owned the terminal. +pub struct OutputOnlySink; + +impl EventSink for OutputOnlySink { + fn emit(&self, event: SoarEvent) { + if let SoarEvent::ProcessOutput { + line, .. + } = event + { + println!("{line}"); + } + } +} + /// Handle returned by [`spawn_event_handler`] that owns the background progress thread. /// /// Call [`finish`](ProgressGuard::finish) after dropping the [`SoarContext`] to join the @@ -437,6 +455,13 @@ pub fn spawn_event_handler(receiver: Receiver) -> ProgressGuard { } } + // ── Hook and build output ───────────────────────────── + SoarEvent::ProcessOutput { + line, .. + } => { + suspend(|| println!("{line}")); + } + // ── Removal stages ───────────────────────────────────── SoarEvent::Removing { op_id, @@ -610,6 +635,25 @@ pub fn spawn_event_handler(receiver: Receiver) -> ProgressGuard { pb.finish_and_clear(); } } + SoarEvent::OperationCancelled { + op_id, + pkg_name, + .. + } => { + remove_ops.remove(&op_id); + set_fetches.remove(&op_id); + MULTI.suspend(|| { + eprintln!( + " {} {}: {}", + Red.paint("✗"), + Cyan.paint(&pkg_name), + Red.paint("cancelled") + ); + }); + if let Some(pb) = jobs.remove(&op_id) { + pb.finish_and_clear(); + } + } // Emitted for things that fail without aborting the run, a // repository that could not be synced most of all. Without a diff --git a/crates/soar-cli/src/remove.rs b/crates/soar-cli/src/remove.rs index a2a9cf71..c4a74647 100644 --- a/crates/soar-cli/src/remove.rs +++ b/crates/soar-cli/src/remove.rs @@ -1,9 +1,12 @@ use nu_ansi_term::Color::{Blue, Cyan, Green, LightRed}; -use soar_core::SoarResult; +use soar_core::{SoarResult, error::SoarError}; use soar_operations::{RemoveResolveResult, SoarContext, remove}; use tracing::{debug, error, info, warn}; -use crate::utils::{Colored, confirm_action, select_package_interactively}; +use crate::{ + interrupt::InterruptGuard, + utils::{Colored, confirm_action, select_package_interactively}, +}; pub async fn remove_packages( ctx: &SoarContext, @@ -68,6 +71,7 @@ pub async fn remove_packages( return Ok(()); } + let _interrupt = InterruptGuard::install(ctx.cancel_token().clone()); let report = remove::perform_removal(ctx, to_remove).await?; for removed in &report.removed { @@ -81,6 +85,10 @@ pub async fn remove_packages( error!("Failed to remove {}: {}", failed.pkg_name, failed.error); } + if ctx.cancel_token().is_cancelled() { + return Err(SoarError::Cancelled); + } + debug!("package removal completed"); Ok(()) } diff --git a/crates/soar-cli/src/update.rs b/crates/soar-cli/src/update.rs index d7dc3023..043f98c5 100644 --- a/crates/soar-cli/src/update.rs +++ b/crates/soar-cli/src/update.rs @@ -1,5 +1,5 @@ -use nu_ansi_term::Color::{Blue, Cyan, Green, Red}; -use soar_core::SoarResult; +use nu_ansi_term::Color::{Blue, Cyan, Green, Red, Yellow}; +use soar_core::{SoarResult, error::SoarError}; use soar_operations::{SoarContext, UpdateInfo, UpdateReport, update}; use tabled::{ builder::Builder, @@ -8,6 +8,7 @@ use tabled::{ use tracing::{error, info}; use crate::{ + interrupt::InterruptGuard, json_output::{self, Listing, UpdateJson}, progress::create_wait_job, utils::{Colored, Icons, ask_target_action, display_settings, icon_or, json_enabled}, @@ -45,9 +46,14 @@ pub async fn update_packages( } } + let _interrupt = InterruptGuard::install(ctx.cancel_token().clone()); let report = update::perform_update(ctx, updates, keep, no_verify).await?; display_update_report(&report); + if ctx.cancel_token().is_cancelled() { + return Err(SoarError::Cancelled); + } + Ok(()) } @@ -90,7 +96,8 @@ fn display_update_report(report: &UpdateReport) { let updated_count = report.updated.len(); let failed_count = report.failed.len(); - let total_packages = updated_count + failed_count; + let cancelled_count = report.cancelled.len(); + let total_packages = updated_count + failed_count + cancelled_count; if use_icons { let mut builder = Builder::new(); @@ -111,7 +118,13 @@ fn display_update_report(report: &UpdateReport) { format!("{}", Colored(Red, failed_count)), ]); } - if updated_count == 0 && failed_count == 0 { + if cancelled_count > 0 { + builder.push_record([ + format!("{} Cancelled", icon_or(Icons::WARNING, "!")), + format!("{}", Colored(Yellow, cancelled_count)), + ]); + } + if updated_count == 0 && failed_count == 0 && cancelled_count == 0 { builder.push_record([ format!("{} Status", icon_or(Icons::WARNING, "!")), "No packages updated".to_string(), @@ -128,13 +141,18 @@ fn display_update_report(report: &UpdateReport) { info!("\n{table}"); } else { info!( - "Updated {}/{} packages{}", + "Updated {}/{} packages{}{}", updated_count, total_packages, if failed_count > 0 { format!(", {} failed", failed_count) } else { String::new() + }, + if cancelled_count > 0 { + format!(", {} cancelled", cancelled_count) + } else { + String::new() } ); } diff --git a/crates/soar-core/src/error.rs b/crates/soar-core/src/error.rs index 67e69a24..bf0a4fb8 100644 --- a/crates/soar-core/src/error.rs +++ b/crates/soar-core/src/error.rs @@ -69,7 +69,11 @@ pub enum SoarError { #[error(transparent)] #[diagnostic(transparent)] - DownloadError(#[from] soar_dl::error::DownloadError), + DownloadError(soar_dl::error::DownloadError), + + #[error("Cancelled")] + #[diagnostic(code(soar::cancelled))] + Cancelled, #[error(transparent)] #[diagnostic(transparent)] @@ -199,6 +203,15 @@ impl SoarError { } } +impl From for SoarError { + fn from(err: soar_dl::error::DownloadError) -> Self { + match err { + soar_dl::error::DownloadError::Cancelled => Self::Cancelled, + err => Self::DownloadError(err), + } + } +} + impl From> for SoarError { fn from(_: std::sync::PoisonError) -> Self { Self::PoisonError diff --git a/crates/soar-core/src/lib.rs b/crates/soar-core/src/lib.rs index c0f9ea57..87f0230c 100644 --- a/crates/soar-core/src/lib.rs +++ b/crates/soar-core/src/lib.rs @@ -4,6 +4,7 @@ pub mod constants; pub mod database; pub mod error; pub mod package; +pub mod process; pub mod sandbox; pub mod utils; diff --git a/crates/soar-core/src/package/hooks.rs b/crates/soar-core/src/package/hooks.rs index 58fa22c9..86c3a2ea 100644 --- a/crates/soar-core/src/package/hooks.rs +++ b/crates/soar-core/src/package/hooks.rs @@ -3,7 +3,11 @@ use std::{path::Path, process::Command}; use soar_config::{config::get_config, packages::SandboxConfig}; use tracing::{debug, warn}; -use crate::{SoarError, SoarResult, error::ErrorContext, sandbox}; +use crate::{ + SoarError, SoarResult, + process::{self, ProcessContext}, + sandbox, +}; /// Environment variables passed to hook commands. pub struct HookEnv<'a> { @@ -16,12 +20,14 @@ pub struct HookEnv<'a> { /// Run a hook command with environment variables set. /// /// This is the shared hook execution logic used by both package installation -/// and removal operations. +/// and removal operations. Each line the hook prints is reported through +/// `ctx`, and a cancelled token stops the hook. pub fn run_hook( hook_name: &str, command: &str, env: &HookEnv, sandbox_config: Option<&SandboxConfig>, + ctx: &ProcessContext, ) -> SoarResult<()> { debug!("running {} hook: {}", hook_name, command); @@ -61,7 +67,7 @@ pub fn run_hook( cmd = cmd.write_path(path); } } - cmd.run()? + process::run(cmd.build()?, ctx)? } else { if sandbox_enabled && sandbox_config.is_some_and(|s| s.is_required()) { return Err(SoarError::Custom(format!( @@ -82,17 +88,16 @@ pub fn run_hook( hook_name ); } - Command::new("sh") - .arg("-c") + let mut cmd = Command::new("sh"); + cmd.arg("-c") .arg(command) .env("INSTALL_DIR", env.install_dir) .env("BIN_DIR", &bin_dir) .env("PKG_NAME", env.pkg_name) .env("PKG_ID", env.pkg_id) .env("PKG_VERSION", env.pkg_version) - .current_dir(env.install_dir) - .status() - .with_context(|| format!("executing {} hook", hook_name))? + .current_dir(env.install_dir); + process::run(cmd, ctx)? }; if !status.success() { diff --git a/crates/soar-core/src/package/install.rs b/crates/soar-core/src/package/install.rs index 5491b1ef..2403f87f 100644 --- a/crates/soar-core/src/package/install.rs +++ b/crates/soar-core/src/package/install.rs @@ -28,6 +28,7 @@ use soar_dl::{ }; use soar_events::{BuildStage, EventSinkHandle, InstallStage, OperationId, SoarEvent}; use soar_utils::{ + cancel::CancelToken, error::FileSystemResult, fs::{safe_remove, walk_dir}, hash::calculate_checksum, @@ -43,6 +44,7 @@ use crate::{ package::{ local::local_path_from_url, remove::remove_provide_symlinks, update_info::UpdateInfo, }, + process::{self, ProcessContext}, utils::get_extract_dir, }; @@ -56,6 +58,7 @@ async fn install_extras( package: &Package, install_dir: &Path, connections: usize, + cancel: &CancelToken, ) -> SoarResult<()> { let Some(extras) = &package.extra else { return Ok(()); @@ -90,7 +93,8 @@ async fn install_extras( let mut dl = Download::new(&e.url) .output(dest.to_string_lossy()) .overwrite(OverwriteMode::Skip) - .connections(connections); + .connections(connections) + .cancel(cancel.clone()); if let Some(sum) = e.blake3.as_ref() { dl = dl.checksum(sum); } @@ -526,6 +530,7 @@ pub struct PackageInstaller { integrate: bool, events: EventSinkHandle, op_id: OperationId, + cancel: CancelToken, } /// A zsync feed and the installed copy to rebuild the new artifact from. @@ -576,6 +581,7 @@ impl PackageInstaller { config: Config, events: EventSinkHandle, op_id: OperationId, + cancel: CancelToken, ) -> SoarResult { let install_dir = install_dir.as_ref().to_path_buf(); let package = &target.package; @@ -692,9 +698,32 @@ impl PackageInstaller { integrate: target.integrate, events, op_id, + cancel, }) } + /// Stops before a stage starts once the token has been cancelled. + /// + /// The stages past this point have touched nothing a later install + /// cannot rebuild on its own. + fn ensure_not_cancelled(&self) -> SoarResult<()> { + if self.cancel.is_cancelled() { + return Err(SoarError::Cancelled); + } + Ok(()) + } + + /// The event reporting and cancellation state shared by every command + /// this installer runs. + fn process_context(&self) -> ProcessContext<'_> { + ProcessContext { + events: &self.events, + op_id: self.op_id, + pkg_name: &self.package.pkg_name, + cancel: &self.cancel, + } + } + /// Run a hook command with environment variables set. fn run_hook(&self, hook_name: &str, command: &str) -> SoarResult<()> { use super::hooks::{HookEnv, run_hook}; @@ -712,7 +741,13 @@ impl PackageInstaller { stage: InstallStage::RunningHook(hook_name.to_string()), }); - run_hook(hook_name, command, &env, self.sandbox.as_ref()) + run_hook( + hook_name, + command, + &env, + self.sandbox.as_ref(), + &self.process_context(), + ) } /// Run post_download hook if configured. @@ -824,6 +859,8 @@ impl PackageInstaller { } for (i, cmd) in build_config.commands.iter().enumerate() { + self.ensure_not_cancelled()?; + debug!( "running build command {}/{}: {}", i + 1, @@ -874,9 +911,10 @@ impl PackageInstaller { sandbox_cmd = sandbox_cmd.write_path(path); } } - sandbox_cmd.run()? + process::run(sandbox_cmd.build()?, &self.process_context())? } else { - Command::new("sh") + let mut build_cmd = Command::new("sh"); + build_cmd .arg("-c") .arg(cmd) .env("INSTALL_DIR", &self.install_dir) @@ -885,9 +923,8 @@ impl PackageInstaller { .env("PKG_ID", self.package.pkg_id.as_deref().unwrap_or_default()) .env("PKG_VERSION", &self.package.version) .env("NPROC", &nproc) - .current_dir(&self.install_dir) - .status() - .with_context(|| format!("executing build command {}", i + 1))? + .current_dir(&self.install_dir); + process::run(build_cmd, &self.process_context())? }; if !status.success() { @@ -1066,6 +1103,8 @@ impl PackageInstaller { } pub async fn download_package(&self) -> SoarResult> { + self.ensure_not_cancelled()?; + debug!( pkg_name = self.package.pkg_name, pkg_id = self.package.pkg_id, @@ -1091,7 +1130,8 @@ impl PackageInstaller { .output(output_path.to_string_lossy()) .parallel(self.config.ghcr_concurrency.unwrap_or(8)) .connections(self.config.download_concurrency.unwrap_or(8)) - .overwrite(OverwriteMode::Skip); + .overwrite(OverwriteMode::Skip) + .cancel(self.cancel.clone()); if let Some(ref cb) = self.progress_callback { let cb = cb.clone(); @@ -1129,6 +1169,7 @@ impl PackageInstaller { debug!("OCI download completed successfully"); break; } + Err(err @ DownloadError::Cancelled) => return Err(err.into()), Err(err) => { if err.is_transient() { warn!( @@ -1153,6 +1194,8 @@ impl PackageInstaller { // A layer is checked against its digest, but the digest comes from // the registry. The binary is held to the repository's checksum // before any hook or build step runs against it. + self.ensure_not_cancelled()?; + let binary = self.install_dir.join(&self.package.pkg_name); if binary.is_file() { self.verify_pinned_checksum(&binary, url)?; @@ -1160,8 +1203,11 @@ impl PackageInstaller { // Run post_download hook for OCI packages // For OCI packages, content is directly placed, so post_extract also applies + self.ensure_not_cancelled()?; self.run_post_download_hook()?; + self.ensure_not_cancelled()?; self.run_post_extract_hook()?; + self.ensure_not_cancelled()?; self.run_build()?; Ok(None) @@ -1184,6 +1230,7 @@ impl PackageInstaller { &seed.url, &seed.seed, output_path, + Some(&self.cancel), callback.map(|cb| move |p| cb(p)), )?; self.verify_pinned_checksum(output_path, &seed.url)?; @@ -1212,7 +1259,8 @@ impl PackageInstaller { .overwrite(OverwriteMode::Skip) .extract(should_extract) .extract_to(&extract_dir) - .connections(self.config.download_concurrency.unwrap_or(8)); + .connections(self.config.download_concurrency.unwrap_or(8)) + .cancel(self.cancel.clone()); if let Some(ref bsum) = self.package.bsum { dl = dl.checksum(bsum); @@ -1228,6 +1276,7 @@ impl PackageInstaller { dl.execute()? }; + self.ensure_not_cancelled()?; self.run_post_download_hook()?; let checksum = if PathBuf::from(&file_path).exists() { @@ -1239,6 +1288,7 @@ impl PackageInstaller { let extract_path = PathBuf::from(&extract_dir); let extracted = extract_path.exists(); if extracted { + self.ensure_not_cancelled()?; fs::remove_file(file_path).ok(); for entry in fs::read_dir(&extract_path) @@ -1364,6 +1414,7 @@ impl PackageInstaller { &self.package, &self.install_dir, self.config.download_concurrency.unwrap_or(8), + &self.cancel, ) .await?; @@ -1426,7 +1477,9 @@ impl PackageInstaller { } } + self.ensure_not_cancelled()?; self.run_post_extract_hook()?; + self.ensure_not_cancelled()?; self.run_build()?; Ok(checksum) @@ -1622,6 +1675,7 @@ mod tests { }; use soar_db::models::types::{PackageExtra, PackageFile}; + use soar_utils::cancel::CancelToken; use tempfile::tempdir; use super::{ @@ -1631,7 +1685,8 @@ mod tests { /// Runs `install_extras`, which never waits on anything, to completion. fn install_side_files(package: &Package, dir: &Path) { - let future = std::pin::pin!(install_extras(package, dir, 8)); + let cancel = CancelToken::new(); + let future = std::pin::pin!(install_extras(package, dir, 8, &cancel)); let mut cx = std::task::Context::from_waker(std::task::Waker::noop()); match std::future::Future::poll(future, &mut cx) { std::task::Poll::Ready(result) => result.unwrap(), diff --git a/crates/soar-core/src/package/remove.rs b/crates/soar-core/src/package/remove.rs index 97b372e0..fee86b53 100644 --- a/crates/soar-core/src/package/remove.rs +++ b/crates/soar-core/src/package/remove.rs @@ -3,6 +3,7 @@ use std::{ fs, os::unix::fs::PermissionsExt, path::{Component, Path, PathBuf}, + sync::Arc, }; use soar_config::{ @@ -10,13 +11,16 @@ use soar_config::{ packages::{PackageHooks, SandboxConfig}, }; use soar_db::{models::types::PackageProvide, repository::core::CoreRepository}; +use soar_events::{EventSinkHandle, NullSink, OperationId}; use soar_utils::{ + cancel::CancelToken, error::FileSystemResult, fs::{remove_contained_dir, walk_dir}, }; use tracing::{debug, trace, warn}; use super::hooks::{HookEnv, run_hook}; +use crate::process::ProcessContext; /// Remove every symlink under `dir` that points into `installed_path`. /// @@ -134,6 +138,9 @@ pub struct PackageRemover { config: Config, hooks: Option, sandbox: Option, + events: EventSinkHandle, + op_id: OperationId, + cancel: CancelToken, } /// Give every directory under `path` the owner write bit. @@ -176,9 +183,27 @@ impl PackageRemover { config, hooks: None, sandbox: None, + events: Arc::new(NullSink), + op_id: 0, + cancel: CancelToken::new(), } } + /// Report the hook's printed lines as events of one operation. + /// + /// Without this, hook output is dropped. + pub fn with_events(mut self, events: EventSinkHandle, op_id: OperationId) -> Self { + self.events = events; + self.op_id = op_id; + self + } + + /// Stop a running hook through this token. + pub fn with_cancel(mut self, cancel: CancelToken) -> Self { + self.cancel = cancel; + self + } + /// Set hooks configuration for the package removal. pub fn with_hooks(mut self, hooks: Option) -> Self { self.hooks = hooks; @@ -200,8 +225,14 @@ impl PackageRemover { pkg_name: &self.package.pkg_name, pkg_version: &self.package.version, }; + let ctx = ProcessContext { + events: &self.events, + op_id: self.op_id, + pkg_name: &self.package.pkg_name, + cancel: &self.cancel, + }; - run_hook(hook_name, command, &env, self.sandbox.as_ref()) + run_hook(hook_name, command, &env, self.sandbox.as_ref(), &ctx) } /// Run pre_remove hook if configured. diff --git a/crates/soar-core/src/process.rs b/crates/soar-core/src/process.rs new file mode 100644 index 00000000..ce55578d --- /dev/null +++ b/crates/soar-core/src/process.rs @@ -0,0 +1,319 @@ +//! Running package hooks and build commands. +//! +//! A hook or build command used to inherit the terminal, so its output went +//! straight to the screen and its stdin belonged to the user. Running it here +//! instead delivers each printed line as an event tied to the package, and +//! lets an operation abort the child. + +use std::{ + io::{BufRead as _, BufReader}, + os::unix::process::CommandExt as _, + process::{Command, ExitStatus, Stdio}, + sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }, + thread, + time::{Duration, Instant}, +}; + +use soar_events::{EventSinkHandle, OperationId, SoarEvent}; +use soar_utils::cancel::CancelToken; + +use crate::{ + SoarResult, + error::{ErrorContext as _, SoarError}, +}; + +/// How often the running child is polled for exit and cancellation. +const POLL_INTERVAL: Duration = Duration::from_millis(50); + +/// How long the readers may keep draining after the child has exited. The +/// command's own output is worth waiting for, but a process it daemonized +/// cannot hold the whole operation hostage over its leftover pipes. +const READER_GRACE: Duration = Duration::from_secs(10); + +/// Where a child's output goes, and what can stop it. +pub struct ProcessContext<'a> { + /// Sink the printed lines are reported through. + pub events: &'a EventSinkHandle, + /// Operation the child belongs to. + pub op_id: OperationId, + /// Name of the package the child works for. + pub pkg_name: &'a str, + /// Flag that asks the child to be stopped. + pub cancel: &'a CancelToken, +} + +/// Runs `cmd` to completion, reporting each line it prints as a +/// [`SoarEvent::ProcessOutput`]. +/// +/// The child gets no input. If `cancel` fires, the child is killed and +/// [`SoarError::Cancelled`] is returned. +pub fn run(mut cmd: Command, ctx: &ProcessContext) -> SoarResult { + // The command must never start under a token that already fired, or a + // fast command could finish before the first poll sees the cancellation. + if ctx.cancel.is_cancelled() { + return Err(SoarError::Cancelled); + } + + let program = cmd.get_program().to_string_lossy().into_owned(); + cmd.stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + // A group of its own lets a cancel take the command's own children + // down with it, so the pipes close and the readers finish. + .process_group(0); + + let mut child = cmd.spawn().with_context(|| format!("starting {program}"))?; + + let events = ctx.events.clone(); + let op_id = ctx.op_id; + let pkg_name = ctx.pkg_name; + + thread::scope(|scope| { + // Each reader marks its stream done, so the drain after a normal + // exit can tell a closed pipe from one a leftover process still + // holds without blocking on the join. + let out_done = Arc::new(AtomicBool::new(false)); + let err_done = Arc::new(AtomicBool::new(false)); + if let Some(out) = child.stdout.take() { + let events = events.clone(); + let done = Arc::clone(&out_done); + scope.spawn(move || { + read_lines(out, events, op_id, pkg_name); + done.store(true, Ordering::Release); + }); + } else { + out_done.store(true, Ordering::Release); + } + if let Some(err) = child.stderr.take() { + let done = Arc::clone(&err_done); + scope.spawn(move || { + read_lines(err, events, op_id, pkg_name); + done.store(true, Ordering::Release); + }); + } else { + err_done.store(true, Ordering::Release); + } + + loop { + let status = child + .try_wait() + .with_context(|| format!("waiting for {program}"))?; + if let Some(status) = status { + // The child is gone, but a process it left behind may still + // hold the pipes. Keep draining for a bounded grace, with + // the token still live, so the command's own output is kept + // without a daemonized leftover holding the operation + // hostage. Killing the group closes the pipes and lets the + // readers finish. + let deadline = Instant::now() + READER_GRACE; + let mut cancelled = false; + while !out_done.load(Ordering::Acquire) || !err_done.load(Ordering::Acquire) { + if ctx.cancel.is_cancelled() { + cancelled = true; + } + if cancelled || Instant::now() >= deadline { + kill_group(child.id()); + break; + } + thread::sleep(POLL_INTERVAL); + } + if cancelled { + return Err(SoarError::Cancelled); + } + return Ok(status); + } + if ctx.cancel.is_cancelled() { + kill_group(child.id()); + let _ = child.wait(); + return Err(SoarError::Cancelled); + } + thread::sleep(POLL_INTERVAL); + } + }) +} + +/// Kills the process group the child led. +/// +/// The child leads its own group, so the signal takes its own children down +/// with it and the pipes close. A group that already exited fails the call, +/// which is fine here. +fn kill_group(pid: u32) { + let group = -(pid as i32); + unsafe { + nix::libc::kill(group, nix::libc::SIGKILL); + } +} + +/// Emits each line of `stream` as [`SoarEvent::ProcessOutput`]. +/// +/// Bytes that are not UTF-8 are replaced rather than dropping the line, and +/// a carriage return left behind by a CRLF ending is trimmed. +fn read_lines( + stream: R, + events: EventSinkHandle, + op_id: OperationId, + pkg_name: &str, +) { + for chunk in BufReader::new(stream).split(b'\n') { + let Ok(chunk) = chunk else { + break; + }; + let line = String::from_utf8_lossy(&chunk); + events.emit(SoarEvent::ProcessOutput { + op_id, + pkg_name: pkg_name.to_string(), + line: line.trim_end_matches('\r').to_string(), + }); + } +} + +#[cfg(test)] +mod tests { + use std::{process::Command, sync::Arc, time::Instant}; + + use soar_events::{CollectorSink, EventSinkHandle, NullSink, SoarEvent}; + use soar_utils::cancel::CancelToken; + + use super::*; + + fn context<'a>(events: &'a EventSinkHandle, cancel: &'a CancelToken) -> ProcessContext<'a> { + ProcessContext { + events, + op_id: 1, + pkg_name: "probe", + cancel, + } + } + + fn shell(script: &str) -> Command { + let mut cmd = Command::new("sh"); + cmd.arg("-c").arg(script); + cmd + } + + fn output_lines(events: &CollectorSink) -> Vec { + events + .events() + .into_iter() + .filter_map(|event| { + match event { + SoarEvent::ProcessOutput { + line, .. + } => Some(line), + _ => None, + } + }) + .collect() + } + + #[test] + fn both_streams_arrive_as_lines() { + let collector = Arc::new(CollectorSink::default()); + let events: EventSinkHandle = collector.clone(); + let cancel = CancelToken::new(); + let ctx = context(&events, &cancel); + + let status = run(shell("echo a; echo b >&2"), &ctx).unwrap(); + + assert!(status.success()); + let mut lines = output_lines(&collector); + lines.sort(); + assert_eq!(lines, vec!["a", "b"]); + } + + #[test] + fn an_already_cancelled_command_is_never_started() { + let dir = tempfile::tempdir().unwrap(); + let marker = dir.path().join("marker"); + let events: EventSinkHandle = Arc::new(NullSink); + let cancel = CancelToken::new(); + cancel.cancel(); + let ctx = context(&events, &cancel); + + let result = run(shell(&format!("touch {}", marker.display())), &ctx); + + assert!(matches!(result, Err(SoarError::Cancelled))); + assert!(!marker.exists(), "the command ran despite the cancellation"); + } + + #[test] + fn a_cancelled_child_is_killed_and_reports_cancelled() { + let events: EventSinkHandle = Arc::new(NullSink); + let cancel = CancelToken::new(); + let ctx = context(&events, &cancel); + + let canceller = cancel.clone(); + let timer = thread::spawn(move || { + thread::sleep(Duration::from_millis(100)); + canceller.cancel(); + }); + + let start = Instant::now(); + let result = run(shell("sleep 5"), &ctx); + timer.join().unwrap(); + let elapsed = start.elapsed(); + + assert!(matches!(result, Err(SoarError::Cancelled))); + assert!( + elapsed < Duration::from_secs(1), + "cancellation took {elapsed:?}" + ); + } + + #[test] + #[cfg(unix)] + fn a_daemonized_leftover_cannot_hold_a_finished_child_hostage() { + let collector = Arc::new(CollectorSink::default()); + let events: EventSinkHandle = collector.clone(); + let cancel = CancelToken::new(); + let ctx = context(&events, &cancel); + + // The child itself exits at once, but the sleep it daemonized keeps + // the pipes open. Cancelling after the start has to be seen by the + // drain that follows the exit, since the poll loop is already done. + let canceller = cancel.clone(); + let timer = thread::spawn(move || { + thread::sleep(Duration::from_millis(300)); + canceller.cancel(); + }); + + let start = Instant::now(); + let result = run(shell("echo hi; sleep 300 &"), &ctx); + timer.join().unwrap(); + let elapsed = start.elapsed(); + + assert!(matches!(result, Err(SoarError::Cancelled))); + assert!( + elapsed < Duration::from_secs(5), + "a leftover holding the pipes stalled the call for {elapsed:?}" + ); + assert!(output_lines(&collector).iter().any(|line| line == "hi")); + } + + #[test] + fn a_child_reading_stdin_finishes() { + let events: EventSinkHandle = Arc::new(NullSink); + let cancel = CancelToken::new(); + let ctx = context(&events, &cancel); + + let status = run(shell("read x; echo got"), &ctx).unwrap(); + + assert!(status.success()); + } + + #[test] + fn a_non_utf8_line_still_arrives() { + let collector = Arc::new(CollectorSink::default()); + let events: EventSinkHandle = collector.clone(); + let cancel = CancelToken::new(); + let ctx = context(&events, &cancel); + + let status = run(shell("printf 'b\\377d\\n'"), &ctx).unwrap(); + + assert!(status.success()); + assert_eq!(output_lines(&collector), ["b\u{fffd}d"]); + } +} diff --git a/crates/soar-core/src/sandbox.rs b/crates/soar-core/src/sandbox.rs index 98e765d5..6ec93893 100644 --- a/crates/soar-core/src/sandbox.rs +++ b/crates/soar-core/src/sandbox.rs @@ -134,7 +134,7 @@ impl<'a> SandboxedCommand<'a> { /// Create a new sandboxed command builder. /// /// Set a working directory with [`working_dir`](Self::working_dir) - /// before [`run`](Self::run). A deleted current directory is an + /// before [`build`](Self::build). A deleted current directory is an /// error, never a silent fallback to `/`. pub fn new(command: &'a str) -> Self { Self { @@ -195,8 +195,12 @@ impl<'a> SandboxedCommand<'a> { self } - /// Run the command and return the exit status. - pub fn run(self) -> SoarResult { + /// Build the configured command, including the Landlock `pre_exec`. + /// + /// The command has not started. Run it through + /// [`crate::process::run`], so its output arrives as events and a + /// cancel can stop it. + pub fn build(self) -> SoarResult { let working_dir = match self.working_dir { Some(dir) => dir, None => { @@ -207,7 +211,7 @@ impl<'a> SandboxedCommand<'a> { })? } }; - run_sandboxed_command( + build_sandboxed_command( self.command, &working_dir, &self.env_vars, @@ -216,6 +220,14 @@ impl<'a> SandboxedCommand<'a> { &self.extra_write_paths, ) } + + /// Run the command and return the exit status. + #[cfg(test)] + pub(crate) fn run(self) -> SoarResult { + self.build()? + .status() + .map_err(|e| SoarError::SandboxExecution(e.to_string())) + } } /// Check if Landlock is supported on this system. @@ -524,15 +536,19 @@ fn check_landlock_support(supported: bool, required: bool) -> SoarResult<()> { Ok(()) } -/// Execute a shell command with Landlock sandbox restrictions. -fn run_sandboxed_command( +/// Build a shell command with Landlock sandbox restrictions applied. +/// +/// The returned command has not started; the caller runs it and reads its +/// output. The ruleset is built here, in the parent, and enforced by the +/// command's `pre_exec` in the forked child. +fn build_sandboxed_command( command: &str, working_dir: &Path, env_vars: &[(String, String)], config: &SandboxConfig, extra_read_paths: &[PathBuf], extra_write_paths: &[PathBuf], -) -> SoarResult { +) -> SoarResult { // If sandbox is disabled, run directly if !config.enabled { debug!("Sandbox disabled, running command directly"); @@ -541,9 +557,7 @@ fn run_sandboxed_command( for (key, value) in env_vars { cmd.env(key, value); } - return cmd - .status() - .map_err(|e| SoarError::SandboxExecution(e.to_string())); + return Ok(cmd); } // Check Landlock support. A required sandbox fails closed. @@ -556,9 +570,7 @@ fn run_sandboxed_command( for (key, value) in env_vars { cmd.env(key, value); } - return cmd - .status() - .map_err(|e| SoarError::SandboxExecution(e.to_string())); + return Ok(cmd); } // Build the ruleset in the parent. The child only enforces it. @@ -615,8 +627,7 @@ fn run_sandboxed_command( }); } - cmd.status() - .map_err(|e| SoarError::SandboxExecution(e.to_string())) + Ok(cmd) } #[cfg(test)] diff --git a/crates/soar-db/src/models/metadata.rs b/crates/soar-db/src/models/metadata.rs index 5c42c397..07bd4719 100644 --- a/crates/soar-db/src/models/metadata.rs +++ b/crates/soar-db/src/models/metadata.rs @@ -137,6 +137,7 @@ pub struct PackageListing { pub pkg_name: String, pub pkg_type: Option, pub version: String, + pub description: Option, } /// Minimal package data for fuzzy search candidate matching. diff --git a/crates/soar-dl/src/download.rs b/crates/soar-dl/src/download.rs index 90cffc49..9426ce74 100644 --- a/crates/soar-dl/src/download.rs +++ b/crates/soar-dl/src/download.rs @@ -6,7 +6,7 @@ use std::{ sync::Arc, }; -use soar_utils::fs::is_elf; +use soar_utils::{cancel::CancelToken, fs::is_elf}; use tracing::{debug, trace, warn}; use ureq::{ Body, @@ -49,6 +49,9 @@ pub struct Download { /// ranges; more than one splits a range-capable server's file between /// them. pub connections: usize, + /// Token that asks the download to stop at its next read. A cancelled + /// download keeps its partial file and resume state. + pub cancel: Option, } impl Download { @@ -81,6 +84,7 @@ impl Download { ghcr_blob: false, expected_checksum: None, connections: DEFAULT_CONNECTIONS, + cancel: None, } } @@ -102,6 +106,24 @@ impl Download { self } + /// Sets a token that asks this download to stop at its next read. + /// + /// Cancelling keeps the partial file and its resume state, so a later + /// attempt continues where this one stopped. + /// + /// # Examples + /// + /// ``` + /// use soar_dl::download::Download; + /// use soar_utils::cancel::CancelToken; + /// + /// let dl = Download::new("https://example.com/file").cancel(CancelToken::new()); + /// ``` + pub fn cancel(mut self, token: CancelToken) -> Self { + self.cancel = Some(token); + self + } + /// Sets the expected blake3 checksum (hex) to verify the downloaded file /// against before it is made executable or extracted. /// @@ -244,8 +266,9 @@ impl Download { /// directories as needed, respects the configured overwrite mode (skip, force, or prompt), /// supports resuming interrupted downloads when resume metadata is available, and persists /// resume state during an active download. After a successful download, it clears any - /// stored resume metadata, sets the executable bit on ELF binaries, and—if extraction was - /// requested—extracts the archive into the configured destination directory. + /// stored resume metadata, sets the executable bit on ELF binaries, and + /// extracts the archive into the configured destination directory when + /// extraction was requested. /// /// # Returns /// @@ -266,6 +289,10 @@ impl Download { pub fn execute(self) -> Result { debug!(url = self.url, "starting download"); + if self.cancel.as_ref().is_some_and(CancelToken::is_cancelled) { + return Err(DownloadError::Cancelled); + } + if let Some(ref cb) = self.on_progress { cb(Progress::Preparing); } @@ -322,6 +349,10 @@ impl Download { if resume_info.is_none() { if self.is_complete(&output_path, head_size) { debug!(path = %output_path.display(), "file exists, skipping download"); + // A retained file still gets the same finalization + // as a fresh download, or a complete archive kept + // by a later Skip would never be extracted. + self.extract_if_requested(&output_path)?; return Ok(output_path); } warn!(path = %output_path.display(), "existing file is not a complete download, re-downloading"); @@ -366,45 +397,52 @@ impl Download { } finish_resume(&file)?; - - // Extraction is driven by what the file actually is, not by what the - // caller guessed it would be. compak detects by magic number, so an - // ELF (an AppImage, say) is never mistaken for an archive even when - // extraction was requested. - if self.extract { - match compak::detect_from_file(&output_path) { - Err( - err @ compak::error::ArchiveError::Io { - .. - }, - ) => return Err(err.into()), - Ok(format) => { - let extract_dir = self.extract_to.unwrap_or_else(|| { - output_path - .parent() - .map(PathBuf::from) - .unwrap_or_else(|| PathBuf::from(".")) - }); - debug!(archive = %output_path.display(), dest = %extract_dir.display(), - ?format, "extracting archive"); - // A failure here fails the install. A bare .gz of a single - // file shares its magic number with the tar-wrapped form, - // but detection decompresses far enough to tell the two - // apart, so what is left is a download that really is - // broken, and swallowing that installs an empty package. - compak::extract_archive(&output_path, &extract_dir)?; - } - Err(_) => { - trace!(path = %output_path.display(), - "not an archive, installing as-is"); - } - } - } + self.extract_if_requested(&output_path)?; debug!(path = %output_path.display(), "download completed successfully"); Ok(output_path) } + /// Runs the requested extraction on a finished archive. + /// + /// Extraction is driven by what the file actually is, not by what the + /// caller guessed it would be. compak detects by magic number, so an + /// ELF (an AppImage, say) is never mistaken for an archive even when + /// extraction was requested. + fn extract_if_requested(&self, output_path: &Path) -> Result<(), DownloadError> { + if !self.extract { + return Ok(()); + } + match compak::detect_from_file(output_path) { + Err( + err @ compak::error::ArchiveError::Io { + .. + }, + ) => return Err(err.into()), + Ok(format) => { + let extract_dir = self.extract_to.clone().unwrap_or_else(|| { + output_path + .parent() + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(".")) + }); + debug!(archive = %output_path.display(), dest = %extract_dir.display(), + ?format, "extracting archive"); + // A failure here fails the install. A bare .gz of a single + // file shares its magic number with the tar-wrapped form, + // but detection decompresses far enough to tell the two + // apart, so what is left is a download that really is + // broken, and swallowing that installs an empty package. + compak::extract_archive(output_path, &extract_dir)?; + } + Err(_) => { + trace!(path = %output_path.display(), + "not an archive, installing as-is"); + } + } + Ok(()) + } + /// Whether the file already at `path` is this download, finished: it /// matches the expected checksum, or, without one, the size the server /// reports. Existence alone proves nothing, since an interrupted download @@ -450,11 +488,24 @@ impl Download { /// /// `PathBuf::from("-")` on success. fn download_to_stdout(&self) -> Result { + if self.cancel.as_ref().is_some_and(CancelToken::is_cancelled) { + return Err(DownloadError::Cancelled); + } let resp = Http::fetch(&self.url, None, None, self.ghcr_blob)?; let mut stdout = std::io::stdout(); let mut reader = resp.into_body().into_reader(); + let mut buffer = vec![0u8; READ_BUFFER]; - std::io::copy(&mut reader, &mut stdout)?; + loop { + if self.cancel.as_ref().is_some_and(CancelToken::is_cancelled) { + return Err(DownloadError::Cancelled); + } + let n = reader.read(&mut buffer)?; + if n == 0 { + break; + } + stdout.write_all(&buffer[..n])?; + } stdout.flush()?; Ok(PathBuf::from("-")) @@ -480,6 +531,10 @@ impl Download { resume_info: Option, remote: Option, ) -> Result { + if self.cancel.as_ref().is_some_and(CancelToken::is_cancelled) { + return Err(DownloadError::Cancelled); + } + if resume_info .as_ref() .is_some_and(|info| info.etag.as_deref().and_then(strong_etag).is_none()) @@ -597,6 +652,9 @@ impl Download { written: Vec, etag: Option<&str>, ) -> Result { + if self.cancel.as_ref().is_some_and(CancelToken::is_cancelled) { + return Err(DownloadError::Cancelled); + } let current: u64 = written.iter().sum(); let info = ResumeInfo { downloaded: current, @@ -654,6 +712,7 @@ impl Download { connections: self.connections, ranges, written, + cancel: self.cancel.as_ref(), on_progress: self.on_progress.as_ref(), }); @@ -691,6 +750,10 @@ impl Download { path: &Path, resume_info: Option, ) -> Result { + if self.cancel.as_ref().is_some_and(CancelToken::is_cancelled) { + return Err(DownloadError::Cancelled); + } + let (resume_from, etag) = resume_info .as_ref() .map(|r| (Some(r.downloaded), r.etag.as_deref())) @@ -774,6 +837,13 @@ impl Download { if n == 0 { break; } + // The token is only honored while the transfer is still short of + // EOF: reporting a cancelled download once the last chunk is in + // would leave a complete file that a later Skip treats as done + // without ever finalizing it. + if self.cancel.as_ref().is_some_and(CancelToken::is_cancelled) { + return Err(DownloadError::Cancelled); + } file.write_all(&buffer[..n])?; downloaded += n as u64; @@ -1377,4 +1447,138 @@ mod tests { assert_eq!(preparing, 1); assert!(matches!(seen[0], Progress::Preparing)); } + + #[test] + fn an_already_cancelled_download_returns_cancelled() { + let base = crate::test_server::serve(vec![("/file".into(), body())]); + let dir = tempfile::tempdir().unwrap(); + let out = dir.path().join("file"); + let token = CancelToken::new(); + token.cancel(); + + let result = Download::new(format!("{base}/file")) + .output(out.to_string_lossy()) + .cancel(token) + .execute(); + + assert!(matches!(result, Err(DownloadError::Cancelled))); + assert!(!out.exists(), "a download that never started left a file"); + } + + #[test] + fn a_download_cancelled_on_its_first_chunk_keeps_the_partial_file() { + // Larger than one read buffer, so the chunk that triggers the + // callback is not also the last one and the token fires mid-transfer. + let data = vec![9u8; READ_BUFFER + 4096]; + let base = crate::test_server::serve(vec![("/file".into(), data.clone())]); + let dir = tempfile::tempdir().unwrap(); + let out = dir.path().join("file"); + let token = CancelToken::new(); + + let result = Download::new(format!("{base}/file")) + .output(out.to_string_lossy()) + .cancel(token.clone()) + .progress(move |p| { + if matches!(p, Progress::Chunk { .. }) { + token.cancel(); + } + }) + .execute(); + + assert!(matches!(result, Err(DownloadError::Cancelled))); + assert!(out.exists(), "the partial file was deleted"); + assert!( + std::fs::metadata(&out).unwrap().len() < data.len() as u64, + "the file was already complete when cancelled" + ); + } + + #[test] + fn a_cancel_that_arrives_at_eof_does_not_fail_a_finished_transfer() { + let base = crate::test_server::serve(vec![("/file".into(), body())]); + let dir = tempfile::tempdir().unwrap(); + let out = dir.path().join("file"); + let token = CancelToken::new(); + + // The token fires only after the last chunk is written, so the next + // read is EOF and the transfer is already complete. + let result = Download::new(format!("{base}/file")) + .output(out.to_string_lossy()) + .cancel(token.clone()) + .progress(move |p| { + if let Progress::Chunk { + current, + total, + .. + } = p + && current == total + { + token.cancel(); + } + }) + .execute(); + + assert!( + result.is_ok(), + "a transfer that reached EOF must not be reported cancelled: {result:?}" + ); + assert_eq!(std::fs::read(&out).unwrap(), body()); + } + + /// Builds a minimal gzip-compressed tar holding one regular file. + /// + /// The header is assembled by hand because the archive only has to be + /// good enough for compak to detect and unpack, and this crate wires up + /// no packing API. + fn tar_gz_with_member(name: &str, contents: &[u8]) -> Vec { + let mut header = [0u8; 512]; + header[..name.len()].copy_from_slice(name.as_bytes()); + header[100..108].copy_from_slice(b"0000644\0"); + header[108..116].copy_from_slice(b"0000000\0"); + header[116..124].copy_from_slice(b"0000000\0"); + let size = format!("{:011o}\0", contents.len()); + header[124..136].copy_from_slice(size.as_bytes()); + header[136..148].copy_from_slice(b"00000000000\0"); + header[148..156].copy_from_slice(b" "); + header[156] = b'0'; + header[257..263].copy_from_slice(b"ustar\0"); + header[263..265].copy_from_slice(b"00"); + let sum: u32 = header.iter().map(|&b| b as u32).sum(); + let checksum = format!("{sum:06o}\0 "); + header[148..156].copy_from_slice(checksum.as_bytes()); + + let padding = (512 - contents.len() % 512) % 512; + let mut tar = header.to_vec(); + tar.extend_from_slice(contents); + tar.resize(tar.len() + padding + 1024, 0); + + let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::none()); + gz.write_all(&tar).unwrap(); + gz.finish().unwrap() + } + + #[test] + fn skip_finalizes_a_retained_archive_instead_of_returning_it_raw() { + let dir = tempfile::tempdir().unwrap(); + let extract_dir = dir.path().join("unpacked"); + let archive = dir.path().join("pkg.tar.gz"); + std::fs::write(&archive, tar_gz_with_member("member.txt", b"contents")).unwrap(); + let checksum = soar_utils::hash::calculate_checksum(&archive).unwrap(); + + // The archive is already on disk and matches its checksum, so the + // Skip fast path retains it without any request being made. The + // member file only appears if that path finalizes the archive. + Download::new("http://127.0.0.1:9/unused") + .output(archive.to_string_lossy()) + .overwrite(OverwriteMode::Skip) + .checksum(checksum) + .extract(true) + .extract_to(&extract_dir) + .execute() + .unwrap(); + + let member = extract_dir.join("member.txt"); + assert!(member.is_file(), "the retained archive was not extracted"); + assert_eq!(std::fs::read(&member).unwrap(), b"contents"); + } } diff --git a/crates/soar-dl/src/error.rs b/crates/soar-dl/src/error.rs index 636cb522..5509c258 100644 --- a/crates/soar-dl/src/error.rs +++ b/crates/soar-dl/src/error.rs @@ -98,6 +98,12 @@ pub enum DownloadError { #[diagnostic(code(soar_dl::resume_mismatch))] ResumeMismatch, + /// The download was asked to stop through its cancel token. Partial + /// files and resume metadata are left for the next attempt. + #[error("Download cancelled")] + #[diagnostic(code(soar_dl::cancelled))] + Cancelled, + #[error("Server does not support segmented downloads: {url}")] #[diagnostic(code(soar_dl::range_unsupported))] RangeUnsupported { url: String }, diff --git a/crates/soar-dl/src/oci.rs b/crates/soar-dl/src/oci.rs index 1d01ac06..ad697d26 100644 --- a/crates/soar-dl/src/oci.rs +++ b/crates/soar-dl/src/oci.rs @@ -13,7 +13,7 @@ use std::{ use percent_encoding::{AsciiSet, CONTROLS, utf8_percent_encode}; use serde::Deserialize; use sha2::{Digest, Sha256}; -use soar_utils::fs::is_elf; +use soar_utils::{cancel::CancelToken, fs::is_elf}; use tracing::{debug, trace, warn}; use ureq::http::header::{ACCEPT, ACCEPT_ENCODING, AUTHORIZATION, ETAG, IF_RANGE, RANGE}; @@ -254,6 +254,7 @@ pub struct OciDownload { extract_to: Option, parallel: usize, connections: Option, + cancel: Option, on_progress: Option>, } @@ -291,6 +292,7 @@ impl OciDownload { extract_to: None, parallel: 1, connections: None, + cancel: None, on_progress: None, } } @@ -427,6 +429,24 @@ impl OciDownload { self } + /// Sets a token that asks this download to stop at its next read. + /// + /// Cancelling keeps the partial layers and their resume state, so a + /// later attempt continues where this one stopped. + /// + /// # Examples + /// + /// ``` + /// use soar_dl::oci::OciDownload; + /// use soar_utils::cancel::CancelToken; + /// + /// let dl = OciDownload::new("ghcr.io/org/repo:tag").cancel(CancelToken::new()); + /// ``` + pub fn cancel(mut self, token: CancelToken) -> Self { + self.cancel = Some(token); + self + } + /// Registers a progress callback to receive download `Progress` events. /// /// The provided callback will be invoked with progress updates (e.g., Starting, Chunk, Complete) @@ -484,6 +504,10 @@ impl OciDownload { "starting OCI download" ); + if self.cancel.as_ref().is_some_and(CancelToken::is_cancelled) { + return Err(DownloadError::Cancelled); + } + if let Some(cb) = &self.on_progress { cb(Progress::Preparing); } @@ -577,6 +601,9 @@ impl OciDownload { let total_size: u64 = layers.iter().map(|l| l.size).sum(); for layer in layers { + if self.cancel.as_ref().is_some_and(CancelToken::is_cancelled) { + return Err(DownloadError::Cancelled); + } let filename = layer.title().unwrap(); let path = safe_layer_path(output_dir, filename)?; @@ -597,6 +624,7 @@ impl OciDownload { &self.reference, layer, &path, + self.cancel.as_ref(), self.on_progress.as_ref(), &downloaded, total_size, @@ -675,10 +703,14 @@ impl OciDownload { let errors = Arc::clone(&errors); let extract = self.extract; let extract_to = self.extract_to.clone(); + let cancel = self.cancel.clone(); let on_progress = self.on_progress.clone(); thread::spawn(move || { for layer in chunk { + if cancel.as_ref().is_some_and(CancelToken::is_cancelled) { + break; + } let filename = match layer.title() { Some(f) => f, None => continue, @@ -709,6 +741,7 @@ impl OciDownload { &reference, &layer, &path, + cancel.as_ref(), on_progress.as_ref(), &downloaded, total_size, @@ -726,6 +759,7 @@ impl OciDownload { } lock(&paths).push(path); } + Err(DownloadError::Cancelled) => break, Err(e) => { lock(&errors).push((format!("{filename}: {e}"), e.is_transient())); } @@ -741,6 +775,10 @@ impl OciDownload { } } + if self.cancel.as_ref().is_some_and(CancelToken::is_cancelled) { + return Err(DownloadError::Cancelled); + } + let errors = lock(&errors); if !errors.is_empty() { return Err(DownloadError::Multiple { @@ -768,6 +806,9 @@ impl OciDownload { /// let manifest = dl.fetch_manifest().unwrap(); /// ``` pub fn fetch_manifest(&self) -> Result { + if self.cancel.as_ref().is_some_and(CancelToken::is_cancelled) { + return Err(DownloadError::Cancelled); + } let url = registry_url( &self.api, &self.reference.package, @@ -832,6 +873,9 @@ impl OciDownload { /// println!("Downloaded to: {:?}", downloaded); /// ``` pub fn download_blob(&self) -> Result, DownloadError> { + if self.cancel.as_ref().is_some_and(CancelToken::is_cancelled) { + return Err(DownloadError::Cancelled); + } let filename = self .reference .package @@ -865,6 +909,12 @@ impl OciDownload { dl }; + let dl = if let Some(ref token) = self.cancel { + dl.cancel(token.clone()) + } else { + dl + }; + let dl = if let Some(ref cb) = self.on_progress { let cb = cb.clone(); dl.progress(move |p| cb(p)) @@ -924,6 +974,7 @@ impl OciDownload { &self.reference, layer, path, + self.cancel.as_ref(), self.on_progress.as_ref(), &counter, total_size, @@ -949,17 +1000,23 @@ fn lock(mutex: &Mutex) -> std::sync::MutexGuard<'_, T> { /// - Marks the file executable (0o755) if it appears to be an ELF binary and removes any resume metadata on success. /// /// Returns `Ok(())` on success or a `DownloadError` on failure. +#[allow(clippy::too_many_arguments)] fn download_layer_impl( api: &str, reference: &OciReference, layer: &OciLayer, path: &Path, + cancel: Option<&CancelToken>, on_progress: Option<&Arc>, downloaded: &AtomicU64, total_size: u64, ) -> Result<(), DownloadError> { let url = registry_url(api, &reference.package, "blobs", &layer.digest); + if cancel.is_some_and(CancelToken::is_cancelled) { + return Err(DownloadError::Cancelled); + } + trace!( digest = layer.digest, size = layer.size, @@ -971,6 +1028,9 @@ fn download_layer_impl( info.segments.is_none() && info.etag.as_deref().and_then(strong_etag).is_some() }); let resp = loop { + if cancel.is_some_and(CancelToken::is_cancelled) { + return Err(DownloadError::Cancelled); + } let mut req = SHARED_AGENT .get(&url) .header(AUTHORIZATION, "Bearer QQ==") @@ -1051,6 +1111,9 @@ fn download_layer_impl( let mut last_checkpoint = layer_downloaded / (1024 * 1024); loop { + if cancel.is_some_and(CancelToken::is_cancelled) { + return Err(DownloadError::Cancelled); + } let n = reader.read(&mut buffer)?; if n == 0 { break; diff --git a/crates/soar-dl/src/segmented.rs b/crates/soar-dl/src/segmented.rs index ddaf9102..85478c84 100644 --- a/crates/soar-dl/src/segmented.rs +++ b/crates/soar-dl/src/segmented.rs @@ -20,6 +20,7 @@ use std::{ time::{Duration, Instant, SystemTime}, }; +use soar_utils::cancel::CancelToken; use tracing::{debug, trace}; use crate::{ @@ -175,6 +176,9 @@ pub(crate) struct Job<'a> { pub ranges: Vec<(u64, u64)>, /// Bytes of each chunk already on disk, from a resume state. pub written: Vec, + /// Token that asks the whole download to stop, where the caller holds + /// one. Cancellation keeps the partial state for the next attempt. + pub cancel: Option<&'a CancelToken>, pub on_progress: Option<&'a Arc>, } @@ -233,6 +237,9 @@ impl Shared { /// ignores a range request surfaces as [`DownloadError::RangeUnsupported`] so /// the caller can fall back to a single stream. pub(crate) fn run(job: Job) -> Result<(), DownloadError> { + if job.cancel.is_some_and(CancelToken::is_cancelled) { + return Err(DownloadError::Cancelled); + } let initial: u64 = job.written.iter().sum(); let ranges = Arc::new(job.ranges.clone()); let partial = (0..job.ranges.len()) @@ -293,6 +300,7 @@ pub(crate) fn run(job: Job) -> Result<(), DownloadError> { path: job.path, total: job.total, file: job.file, + cancel: job.cancel, progress: job.on_progress.cloned(), }; handles.push(scope.spawn(move || worker.run())); @@ -310,6 +318,12 @@ pub(crate) fn run(job: Job) -> Result<(), DownloadError> { } }); + // The caller's token outranks worker errors: an abort ends the download + // with its partial state kept for the next attempt. + if job.cancel.is_some_and(CancelToken::is_cancelled) { + return Err(DownloadError::Cancelled); + } + if let Some(index) = outcomes .iter() .position(|outcome| matches!(outcome, Outcome::Failed(DownloadError::RetryAfter { .. }))) @@ -351,14 +365,31 @@ struct Worker<'a> { path: &'a Path, total: u64, file: &'a File, + cancel: Option<&'a CancelToken>, progress: Option>, } impl Worker<'_> { + /// Whether this worker should stop: another worker's failure cancelled + /// the run, or the caller's token fired. The caller's request is mirrored + /// into the shared flag so every wait and retry path stops the same way. + fn cancelled(&self) -> bool { + if self.shared.cancel.load(Ordering::Relaxed) { + return true; + } + if let Some(token) = self.cancel + && token.is_cancelled() + { + self.shared.cancel.store(true, Ordering::Relaxed); + return true; + } + false + } + fn run(self) -> Outcome { let mut worker = self; loop { - if worker.shared.cancel.load(Ordering::Relaxed) { + if worker.cancelled() { return Outcome::Cancelled; } match worker.next_chunk() { @@ -368,9 +399,7 @@ impl Worker<'_> { // Cancellation is fallout from another worker's // failure; that worker's error is the one worth // reporting. - if worker.shared.cancel.load(Ordering::Relaxed) - && !matches!(err, DownloadError::RetryAfter { .. }) - { + if worker.cancelled() && !matches!(err, DownloadError::RetryAfter { .. }) { return Outcome::Cancelled; } worker.shared.cancel.store(true, Ordering::Relaxed); @@ -422,6 +451,9 @@ impl Worker<'_> { if cursor > end { return Ok(()); } + if self.cancelled() { + return Err(DownloadError::Cancelled); + } if !self.wait_for_shared_retry() { return Ok(()); } @@ -441,7 +473,7 @@ impl Worker<'_> { let can_retry = err.is_transient() && attempts < MAX_ATTEMPTS && failures < MAX_CHUNK_FAILURES - && !self.shared.cancel.load(Ordering::Relaxed); + && !self.cancelled(); if let ( DownloadError::HttpError { status, @@ -503,7 +535,7 @@ impl Worker<'_> { return false; } } - _ => return !self.shared.cancel.load(Ordering::Relaxed), + _ => return !self.cancelled(), } } } @@ -511,7 +543,7 @@ impl Worker<'_> { fn wait_for_retry(&self, delay: Duration) -> bool { let deadline = Instant::now() + delay; loop { - if self.shared.cancel.load(Ordering::Relaxed) { + if self.cancelled() { return false; } let remaining = deadline.saturating_duration_since(Instant::now()); @@ -613,6 +645,9 @@ impl Worker<'_> { if *cursor > end { return Ok(()); } + if self.cancelled() { + return Err(DownloadError::Cancelled.into()); + } // Never read past the chunk's last byte, whatever the server // sends; a body that overshoots its Content-Range must not leak // into the neighboring chunks. @@ -628,13 +663,6 @@ impl Worker<'_> { )) .into()); } - if self.shared.cancel.load(Ordering::Relaxed) { - return Err(DownloadError::Io(std::io::Error::new( - std::io::ErrorKind::Interrupted, - "cancelled", - )) - .into()); - } self.file.write_all_at(&buffer[..n], *cursor)?; *cursor += n as u64; self.shared.chunk_written[index].store(*cursor - start, Ordering::Release); @@ -751,6 +779,7 @@ mod tests { connections: 1, ranges: vec![(10, 19)], written: vec![0], + cancel: None, on_progress: None, }); assert!(matches!( @@ -780,6 +809,7 @@ mod tests { connections: 1, ranges: vec![(0, 4)], written: vec![0], + cancel: None, on_progress: None, }); assert!(result.is_err()); @@ -807,6 +837,7 @@ mod tests { connections: 1, ranges: vec![(0, 99)], written: vec![0], + cancel: None, on_progress: None, }); assert!(result.is_err()); @@ -839,6 +870,7 @@ mod tests { connections: 1, ranges: vec![(0, 4)], written: vec![0], + cancel: None, on_progress: None, }); assert!(matches!( @@ -875,6 +907,7 @@ mod tests { path: path.path(), total: REPORT_INTERVAL * 2, file: &unsyncable, + cancel: None, progress: None, }; worker.maybe_report(REPORT_INTERVAL); @@ -907,6 +940,7 @@ mod tests { path: file.path(), total: REPORT_INTERVAL * 2, file: file.as_file(), + cancel: None, progress: None, }; worker.maybe_report(REPORT_INTERVAL); @@ -941,6 +975,7 @@ mod tests { path: file.path(), total: 0, file: file.as_file(), + cancel: None, progress: None, }; let thread = std::thread::spawn(move || { @@ -980,6 +1015,7 @@ mod tests { connections: 1, ranges: vec![(0, 4)], written: vec![0], + cancel: None, on_progress: None, }); assert!(matches!( @@ -1036,6 +1072,7 @@ mod tests { connections: 1, ranges: vec![(0, 4)], written: vec![0], + cancel: None, on_progress: None, }) .unwrap(); @@ -1072,6 +1109,7 @@ mod tests { connections: 1, ranges: vec![(0, 4)], written: vec![0], + cancel: None, on_progress: None, }) .unwrap_err(); @@ -1112,6 +1150,7 @@ mod tests { connections: 2, ranges: vec![(0, 4), (5, 9)], written: vec![0, 0], + cancel: None, on_progress: None, }) .unwrap_err(); @@ -1156,6 +1195,7 @@ mod tests { connections: 1, ranges: vec![(0, 4)], written: vec![0], + cancel: None, on_progress: None, }) .unwrap_err(); @@ -1191,6 +1231,7 @@ mod tests { connections: 1, ranges: vec![(0, 4)], written: vec![0], + cancel: None, on_progress: None, }); assert!(result.is_err()); @@ -1219,6 +1260,7 @@ mod tests { connections: 1, ranges: vec![(0, 4)], written: vec![0], + cancel: None, on_progress: None, }); assert!(matches!( @@ -1449,6 +1491,7 @@ mod tests { connections: 2, ranges: vec![(0, 4), (5, 9)], written: vec![0, 0], + cancel: None, on_progress: None, }); assert_eq!(server.join().unwrap(), 2, "requests did not overlap"); @@ -1867,6 +1910,40 @@ mod tests { assert_eq!(std::fs::read(&out).unwrap(), shrank); } + #[test] + fn a_segmented_download_cancelled_on_its_first_chunk_stops_promptly() { + if !supports_xattrs() { + return; + } + let content = body(16); + let base = test_server::serve(vec![("/file".into(), content)]); + let dir = tempfile::tempdir().unwrap(); + let out = dir.path().join("file"); + let token = CancelToken::new(); + + let (tx, rx) = std::sync::mpsc::channel(); + let worker = token.clone(); + thread::spawn(move || { + let result = Download::new(format!("{base}/file")) + .output(out.to_string_lossy()) + .overwrite(OverwriteMode::Force) + .connections(4) + .cancel(worker.clone()) + .progress(move |p| { + if matches!(p, Progress::Chunk { .. }) { + worker.cancel(); + } + }) + .execute(); + tx.send(result).unwrap(); + }); + + let result = rx + .recv_timeout(Duration::from_secs(10)) + .expect("segmented download did not stop after cancellation"); + assert!(matches!(result, Err(DownloadError::Cancelled))); + } + fn read_resume_segments(path: &std::path::Path) -> Option> { crate::xattr::read_resume(path).and_then(|info| info.segments) } diff --git a/crates/soar-dl/src/zsync.rs b/crates/soar-dl/src/zsync.rs index 2b108304..6658b6a4 100644 --- a/crates/soar-dl/src/zsync.rs +++ b/crates/soar-dl/src/zsync.rs @@ -6,10 +6,18 @@ //! Both matter for an AppImage, where a release changes a fraction of a file //! measured in tens of megabytes. -use std::{fs::File, path::Path}; - +use std::{ + fs::File, + path::Path, + sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }, +}; + +use soar_utils::cancel::CancelToken; use tracing::debug; -use zsync_rs::{ControlFile, HttpClient, ZsyncAssembly, checksum::calc_sha1_stream}; +use zsync_rs::{AssemblyError, ControlFile, HttpClient, ZsyncAssembly, checksum::calc_sha1_stream}; use crate::{error::DownloadError, http_client::shared_agent, types::Progress}; @@ -148,6 +156,9 @@ pub fn differs_from(target: &ZsyncTarget, installed: impl AsRef) -> bool { /// Build `output` from the remote artifact, reusing every block `seed` already /// holds and fetching only the rest. /// +/// A token passed as `cancel` stops the transfer at its next block fetch, +/// leaving what was assembled so far on disk. +/// /// The result is verified against the control file's checksums before it is /// moved into place, so a mismatched or truncated transfer fails here rather /// than producing a broken package. Those checksums are only as trustworthy as @@ -158,13 +169,14 @@ pub fn download( url: &str, seed: &Path, output: &Path, + cancel: Option<&CancelToken>, on_progress: Option, ) -> Result<(), DownloadError> where F: Fn(Progress) + Send + Sync + 'static, { ensure_https(url, "zsync control file")?; - assemble(url, seed, output, on_progress) + assemble(url, seed, output, cancel, on_progress) } /// The transfer itself, with the scheme already settled by the caller. @@ -175,11 +187,16 @@ fn assemble( url: &str, seed: &Path, output: &Path, + cancel: Option<&CancelToken>, on_progress: Option, ) -> Result<(), DownloadError> where F: Fn(Progress) + Send + Sync + 'static, { + if cancel.is_some_and(CancelToken::is_cancelled) { + return Err(DownloadError::Cancelled); + } + if let Some(ref callback) = on_progress { callback(Progress::Preparing); } @@ -196,19 +213,35 @@ where let mut assembly = ZsyncAssembly::with_client(control, output, Some(base_url_of(url)), http) .map_err(|e| DownloadError::Zsync(format!("reading zsync control file: {e}")))?; - if let Some(callback) = on_progress { - let total = 0; + // download_missing_blocks walks every missing range in one call, so the + // crate's own abort flag is the only thing that can stop a range already + // in flight. The callback is installed even without a caller callback, + // since raising that flag from the token is its job too. + let abort = Arc::new(AtomicBool::new(false)); + assembly.set_abort_flag(Arc::clone(&abort)); + if let Some(ref callback) = on_progress { callback(Progress::Starting { - total, + total: 0, }); - assembly.set_progress_callback(move |done, total| { + } + // The callback owns a clone of the token, since it has to keep watching + // it for as long as the assembly lives. + let callback_cancel = cancel.cloned(); + assembly.set_progress_callback(move |done, total| { + if callback_cancel + .as_ref() + .is_some_and(CancelToken::is_cancelled) + { + abort.store(true, Ordering::Relaxed); + return; + } + if let Some(ref callback) = on_progress { callback(Progress::Chunk { total, current: done, }); - }); - } - + } + }); // Everything the installed copy already holds is taken from disk; only // what it does not is fetched. if seed.exists() { @@ -220,9 +253,17 @@ where } while !assembly.is_complete() { - let fetched = assembly - .download_missing_blocks() - .map_err(|e| DownloadError::Zsync(format!("fetching blocks: {e}")))?; + if cancel.is_some_and(CancelToken::is_cancelled) { + return Err(DownloadError::Cancelled); + } + let fetched = assembly.download_missing_blocks().map_err(|err| { + match err { + // Aborted is only ever raised by the flag the token raised, + // so it is a cancellation rather than a transfer failure. + AssemblyError::Aborted => DownloadError::Cancelled, + err => DownloadError::Zsync(format!("fetching blocks: {err}")), + } + })?; // No progress and still incomplete means the remote will not serve // what is missing, and looping would spin forever. if fetched == 0 { @@ -353,6 +394,7 @@ mod tests { "http://e.test/App.AppImage.zsync", Path::new("/nonexistent/seed"), &out, + None, None::, ) .unwrap_err(); @@ -486,7 +528,14 @@ mod tests { // No seed, so every block comes off the wire: this is what proves the // relative entry resolved against the right base. let out = dir.path().join("rebuilt.AppImage"); - assemble(&feed, Path::new("/nonexistent"), &out, None::).unwrap(); + assemble( + &feed, + Path::new("/nonexistent"), + &out, + None, + None::, + ) + .unwrap(); assert_eq!(fs::read(&out).unwrap(), bytes, "rebuilt artifact differs"); } @@ -507,11 +556,42 @@ mod tests { let feed = format!("http://127.0.0.1:{port}/App-x86_64.AppImage.zsync"); let out = dir.path().join("rebuilt.AppImage"); - assemble(&feed, &seed, &out, None::).unwrap(); + assemble(&feed, &seed, &out, None, None::).unwrap(); assert_eq!(fs::read(&out).unwrap(), new, "rebuilt artifact differs"); } + #[test] + fn a_cancelled_transfer_stops_at_the_next_block() { + let dir = tempfile::tempdir().unwrap(); + let bytes = artifact_bytes(512 * 1024, 11); + publish(dir.path(), "App-x86_64.AppImage", &bytes); + + let port = serve(dir.path()); + let feed = format!("http://127.0.0.1:{port}/App-x86_64.AppImage.zsync"); + + let out = dir.path().join("rebuilt.AppImage"); + let cancel = CancelToken::new(); + let hook = cancel.clone(); + + // No seed, so blocks come off the wire and the per-block callback + // fires; cancelling on its first report has to reach the crate's + // own abort flag, or the whole transfer would run to the end. + let result = assemble( + &feed, + Path::new("/nonexistent"), + &out, + Some(&cancel), + Some(move |p: Progress| { + if matches!(p, Progress::Chunk { .. }) { + hook.cancel(); + } + }), + ); + + assert!(matches!(result, Err(DownloadError::Cancelled))); + } + #[test] fn a_substituted_artifact_is_refused() { let dir = tempfile::tempdir().unwrap(); @@ -529,7 +609,13 @@ mod tests { let feed = format!("http://127.0.0.1:{port}/App-x86_64.AppImage.zsync"); let out = dir.path().join("rebuilt.AppImage"); - let result = assemble(&feed, Path::new("/nonexistent"), &out, None::); + let result = assemble( + &feed, + Path::new("/nonexistent"), + &out, + None, + None::, + ); assert!( result.is_err(), "a substituted artifact must not be accepted" diff --git a/crates/soar-events/src/event.rs b/crates/soar-events/src/event.rs index d1b71b80..2e1d1dd1 100644 --- a/crates/soar-events/src/event.rs +++ b/crates/soar-events/src/event.rs @@ -1,7 +1,7 @@ use crate::OperationId; /// All event types emitted by soar operations. -#[derive(Debug, Clone, serde::Serialize)] +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[serde(tag = "type", rename_all = "snake_case")] pub enum SoarEvent { /// Contacting the remote. No bytes have moved yet and the size is unknown. @@ -99,6 +99,12 @@ pub enum SoarEvent { pkg_name: String, stage: BuildStage, }, + /// A line a hook or build command printed. + ProcessOutput { + op_id: OperationId, + pkg_name: String, + line: String, + }, /// Operation completed successfully. OperationComplete { op_id: OperationId, @@ -110,6 +116,11 @@ pub enum SoarEvent { pkg_name: String, error: String, }, + /// An operation stopped because it was cancelled. + OperationCancelled { + op_id: OperationId, + pkg_name: String, + }, /// Repository sync progress. SyncProgress { repo_name: String, stage: SyncStage }, /// Batch operation overall progress. @@ -130,7 +141,7 @@ pub enum SoarEvent { } /// Verification stages. -#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum VerifyStage { /// Calculating and verifying checksum (blake3). @@ -144,7 +155,7 @@ pub enum VerifyStage { } /// Installation stages. -#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum InstallStage { /// Extracting package archive. @@ -169,7 +180,7 @@ pub enum InstallStage { } /// Package removal stages. -#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum RemoveStage { /// Running pre-remove hook. @@ -189,7 +200,7 @@ pub enum RemoveStage { } /// Repository sync stages. -#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum SyncStage { /// Fetching metadata from remote. @@ -207,7 +218,7 @@ pub enum SyncStage { } /// Update check result for a single package. -#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum UpdateCheckStatus { /// A newer version is available. @@ -222,7 +233,7 @@ pub enum UpdateCheckStatus { } /// Old version cleanup stages after update. -#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum UpdateCleanupStage { /// Removing the old version. @@ -234,7 +245,7 @@ pub enum UpdateCleanupStage { } /// Hook execution stages. -#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum HookStage { /// Hook is starting. @@ -246,7 +257,7 @@ pub enum HookStage { } /// Package execution stages (run command). -#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum RunStage { /// Using a cached binary (already downloaded). @@ -260,7 +271,7 @@ pub enum RunStage { } /// Build stages (for source packages). -#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum BuildStage { /// Running build command N of M. @@ -275,7 +286,7 @@ pub enum BuildStage { } /// Log levels. -#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum LogLevel { Debug, diff --git a/crates/soar-events/src/lib.rs b/crates/soar-events/src/lib.rs index 3bcbba8c..5fb51d66 100644 --- a/crates/soar-events/src/lib.rs +++ b/crates/soar-events/src/lib.rs @@ -73,6 +73,11 @@ mod tests { level: LogLevel::Warning, message: "m".into(), }); + sink.emit(SoarEvent::ProcessOutput { + op_id: 1, + pkg_name: "a".into(), + line: "hello from hook".into(), + }); assert_eq!( out.text(), @@ -87,6 +92,8 @@ mod tests { "\n", r#"{"type":"log","level":"warning","message":"m"}"#, "\n", + r#"{"type":"process_output","op_id":1,"pkg_name":"a","line":"hello from hook"}"#, + "\n", ) ); } @@ -251,322 +258,352 @@ mod tests { assert_send_sync::(); } - #[test] - fn test_all_event_variants() { - let collector = CollectorSink::default(); - - // Download lifecycle - collector.emit(SoarEvent::DownloadStarting { - op_id: 1, - pkg_name: "a".into(), - total: 100, - }); - collector.emit(SoarEvent::DownloadResuming { - op_id: 1, - pkg_name: "a".into(), - current: 50, - total: 100, - }); - collector.emit(SoarEvent::DownloadProgress { - op_id: 1, - pkg_name: "a".into(), - current: 75, - total: 100, - }); - collector.emit(SoarEvent::DownloadComplete { - op_id: 1, - pkg_name: "a".into(), - total: 100, - }); - collector.emit(SoarEvent::DownloadRetry { - op_id: 2, - pkg_name: "b".into(), - }); - collector.emit(SoarEvent::DownloadAborted { - op_id: 2, - pkg_name: "b".into(), - }); - collector.emit(SoarEvent::DownloadRecovered { - op_id: 3, - pkg_name: "c".into(), - }); - - // Verification - collector.emit(SoarEvent::Verifying { - op_id: 1, - pkg_name: "a".into(), - stage: VerifyStage::Checksum, - }); - collector.emit(SoarEvent::Verifying { - op_id: 1, - pkg_name: "a".into(), - stage: VerifyStage::Signature, - }); - collector.emit(SoarEvent::Verifying { - op_id: 1, - pkg_name: "a".into(), - stage: VerifyStage::Passed, - }); - collector.emit(SoarEvent::Verifying { - op_id: 1, - pkg_name: "a".into(), - stage: VerifyStage::Failed("bad checksum".into()), - }); - - // Installation stages - collector.emit(SoarEvent::Installing { - op_id: 1, - pkg_name: "a".into(), - stage: InstallStage::Extracting, - }); - collector.emit(SoarEvent::Installing { - op_id: 1, - pkg_name: "a".into(), - stage: InstallStage::ExtractingNested, - }); - collector.emit(SoarEvent::Installing { - op_id: 1, - pkg_name: "a".into(), - stage: InstallStage::LinkingBinaries, - }); - collector.emit(SoarEvent::Installing { - op_id: 1, - pkg_name: "a".into(), - stage: InstallStage::DesktopIntegration, - }); - collector.emit(SoarEvent::Installing { - op_id: 1, - pkg_name: "a".into(), - stage: InstallStage::SetupPortable, - }); - collector.emit(SoarEvent::Installing { - op_id: 1, - pkg_name: "a".into(), - stage: InstallStage::RecordingDatabase, - }); - collector.emit(SoarEvent::Installing { - op_id: 1, - pkg_name: "a".into(), - stage: InstallStage::RunningHook("post_install".into()), - }); - collector.emit(SoarEvent::Installing { - op_id: 1, - pkg_name: "a".into(), - stage: InstallStage::Complete, - }); - - // Removal stages - collector.emit(SoarEvent::Removing { - op_id: 5, - pkg_name: "e".into(), - stage: RemoveStage::RunningHook("pre_remove".into()), - }); - collector.emit(SoarEvent::Removing { - op_id: 5, - pkg_name: "e".into(), - stage: RemoveStage::UnlinkingBinaries, - }); - collector.emit(SoarEvent::Removing { - op_id: 5, - pkg_name: "e".into(), - stage: RemoveStage::UnlinkingDesktop, - }); - collector.emit(SoarEvent::Removing { - op_id: 5, - pkg_name: "e".into(), - stage: RemoveStage::UnlinkingIcons, - }); - collector.emit(SoarEvent::Removing { - op_id: 5, - pkg_name: "e".into(), - stage: RemoveStage::RemovingDirectory, - }); - collector.emit(SoarEvent::Removing { - op_id: 5, - pkg_name: "e".into(), - stage: RemoveStage::CleaningDatabase, - }); - collector.emit(SoarEvent::Removing { - op_id: 5, - pkg_name: "e".into(), - stage: RemoveStage::Complete { - size_freed: Some(1024 * 1024), + /// One value of every event variant. + fn every_variant() -> Vec { + vec![ + // Download lifecycle + SoarEvent::DownloadPreparing { + op_id: 1, + pkg_name: "a".into(), }, - }); - - // Update checks - collector.emit(SoarEvent::UpdateCheck { - pkg_name: "f".into(), - status: UpdateCheckStatus::Available { - current_version: "1.0.0".into(), - new_version: "2.0.0".into(), + SoarEvent::DownloadStarting { + op_id: 1, + pkg_name: "a".into(), + total: 100, }, - }); - collector.emit(SoarEvent::UpdateCheck { - pkg_name: "g".into(), - status: UpdateCheckStatus::UpToDate { - version: "1.0.0".into(), + SoarEvent::DownloadResuming { + op_id: 1, + pkg_name: "a".into(), + current: 50, + total: 100, }, - }); - collector.emit(SoarEvent::UpdateCheck { - pkg_name: "h".into(), - status: UpdateCheckStatus::Skipped { - reason: "pinned".into(), + SoarEvent::DownloadProgress { + op_id: 1, + pkg_name: "a".into(), + current: 75, + total: 100, }, - }); - - // Update cleanup - collector.emit(SoarEvent::UpdateCleanup { - op_id: 1, - pkg_name: "a".into(), - old_version: "1.0.0".into(), - stage: UpdateCleanupStage::Removing, - }); - collector.emit(SoarEvent::UpdateCleanup { - op_id: 1, - pkg_name: "a".into(), - old_version: "1.0.0".into(), - stage: UpdateCleanupStage::Complete { - size_freed: Some(512), + SoarEvent::DownloadComplete { + op_id: 1, + pkg_name: "a".into(), + total: 100, }, - }); - collector.emit(SoarEvent::UpdateCleanup { - op_id: 1, - pkg_name: "a".into(), - old_version: "1.0.0".into(), - stage: UpdateCleanupStage::Kept, - }); - - // Hook execution - collector.emit(SoarEvent::Hook { - op_id: 5, - pkg_name: "e".into(), - hook_name: "pre_remove".into(), - stage: HookStage::Starting, - }); - collector.emit(SoarEvent::Hook { - op_id: 5, - pkg_name: "e".into(), - hook_name: "pre_remove".into(), - stage: HookStage::Complete, - }); - collector.emit(SoarEvent::Hook { - op_id: 6, - pkg_name: "i".into(), - hook_name: "post_install".into(), - stage: HookStage::Failed { - exit_code: Some(1), + SoarEvent::DownloadRetry { + op_id: 2, + pkg_name: "b".into(), }, - }); - - // Run command - collector.emit(SoarEvent::Running { - op_id: 7, - pkg_name: "j".into(), - stage: RunStage::CacheHit, - }); - collector.emit(SoarEvent::Running { - op_id: 8, - pkg_name: "k".into(), - stage: RunStage::Downloading, - }); - collector.emit(SoarEvent::Running { - op_id: 7, - pkg_name: "j".into(), - stage: RunStage::Executing, - }); - collector.emit(SoarEvent::Running { - op_id: 7, - pkg_name: "j".into(), - stage: RunStage::Complete { - exit_code: 0, + SoarEvent::DownloadAborted { + op_id: 2, + pkg_name: "b".into(), }, - }); - - // Build - collector.emit(SoarEvent::Building { - op_id: 4, - pkg_name: "d".into(), - stage: BuildStage::Sandboxing, - }); - collector.emit(SoarEvent::Building { - op_id: 4, - pkg_name: "d".into(), - stage: BuildStage::Running { - command_index: 0, - total_commands: 3, + SoarEvent::DownloadRecovered { + op_id: 3, + pkg_name: "c".into(), }, - }); - collector.emit(SoarEvent::Building { - op_id: 4, - pkg_name: "d".into(), - stage: BuildStage::CommandComplete { - command_index: 0, + // Verification + SoarEvent::Verifying { + op_id: 1, + pkg_name: "a".into(), + stage: VerifyStage::Checksum, }, - }); - - // Operation completion - collector.emit(SoarEvent::OperationComplete { - op_id: 1, - pkg_name: "a".into(), - }); - collector.emit(SoarEvent::OperationFailed { - op_id: 2, - pkg_name: "b".into(), - error: "not found".into(), - }); - - // Sync stages - collector.emit(SoarEvent::SyncProgress { - repo_name: "repo".into(), - stage: SyncStage::Fetching, - }); - collector.emit(SoarEvent::SyncProgress { - repo_name: "repo".into(), - stage: SyncStage::UpToDate, - }); - collector.emit(SoarEvent::SyncProgress { - repo_name: "repo".into(), - stage: SyncStage::Decompressing, - }); - collector.emit(SoarEvent::SyncProgress { - repo_name: "repo".into(), - stage: SyncStage::WritingDatabase, - }); - collector.emit(SoarEvent::SyncProgress { - repo_name: "repo".into(), - stage: SyncStage::Validating, - }); - collector.emit(SoarEvent::SyncProgress { - repo_name: "repo".into(), - stage: SyncStage::Complete { - package_count: Some(500), + SoarEvent::Verifying { + op_id: 1, + pkg_name: "a".into(), + stage: VerifyStage::Signature, }, - }); + SoarEvent::Verifying { + op_id: 1, + pkg_name: "a".into(), + stage: VerifyStage::Passed, + }, + SoarEvent::Verifying { + op_id: 1, + pkg_name: "a".into(), + stage: VerifyStage::Failed("bad checksum".into()), + }, + // Installation stages + SoarEvent::Installing { + op_id: 1, + pkg_name: "a".into(), + stage: InstallStage::Extracting, + }, + SoarEvent::Installing { + op_id: 1, + pkg_name: "a".into(), + stage: InstallStage::ExtractingNested, + }, + SoarEvent::Installing { + op_id: 1, + pkg_name: "a".into(), + stage: InstallStage::LinkingBinaries, + }, + SoarEvent::Installing { + op_id: 1, + pkg_name: "a".into(), + stage: InstallStage::DesktopIntegration, + }, + SoarEvent::Installing { + op_id: 1, + pkg_name: "a".into(), + stage: InstallStage::FetchingSet("onelf".into()), + }, + SoarEvent::Installing { + op_id: 1, + pkg_name: "a".into(), + stage: InstallStage::SetupPortable, + }, + SoarEvent::Installing { + op_id: 1, + pkg_name: "a".into(), + stage: InstallStage::RecordingDatabase, + }, + SoarEvent::Installing { + op_id: 1, + pkg_name: "a".into(), + stage: InstallStage::RunningHook("post_install".into()), + }, + SoarEvent::Installing { + op_id: 1, + pkg_name: "a".into(), + stage: InstallStage::Complete, + }, + // Removal stages + SoarEvent::Removing { + op_id: 5, + pkg_name: "e".into(), + stage: RemoveStage::RunningHook("pre_remove".into()), + }, + SoarEvent::Removing { + op_id: 5, + pkg_name: "e".into(), + stage: RemoveStage::UnlinkingBinaries, + }, + SoarEvent::Removing { + op_id: 5, + pkg_name: "e".into(), + stage: RemoveStage::UnlinkingDesktop, + }, + SoarEvent::Removing { + op_id: 5, + pkg_name: "e".into(), + stage: RemoveStage::UnlinkingIcons, + }, + SoarEvent::Removing { + op_id: 5, + pkg_name: "e".into(), + stage: RemoveStage::RemovingDirectory, + }, + SoarEvent::Removing { + op_id: 5, + pkg_name: "e".into(), + stage: RemoveStage::CleaningDatabase, + }, + SoarEvent::Removing { + op_id: 5, + pkg_name: "e".into(), + stage: RemoveStage::Complete { + size_freed: Some(1024 * 1024), + }, + }, + // Update checks + SoarEvent::UpdateCheck { + pkg_name: "f".into(), + status: UpdateCheckStatus::Available { + current_version: "1.0.0".into(), + new_version: "2.0.0".into(), + }, + }, + SoarEvent::UpdateCheck { + pkg_name: "g".into(), + status: UpdateCheckStatus::UpToDate { + version: "1.0.0".into(), + }, + }, + SoarEvent::UpdateCheck { + pkg_name: "h".into(), + status: UpdateCheckStatus::Skipped { + reason: "pinned".into(), + }, + }, + // Update cleanup + SoarEvent::UpdateCleanup { + op_id: 1, + pkg_name: "a".into(), + old_version: "1.0.0".into(), + stage: UpdateCleanupStage::Removing, + }, + SoarEvent::UpdateCleanup { + op_id: 1, + pkg_name: "a".into(), + old_version: "1.0.0".into(), + stage: UpdateCleanupStage::Complete { + size_freed: Some(512), + }, + }, + SoarEvent::UpdateCleanup { + op_id: 1, + pkg_name: "a".into(), + old_version: "1.0.0".into(), + stage: UpdateCleanupStage::Kept, + }, + // Hook execution + SoarEvent::Hook { + op_id: 5, + pkg_name: "e".into(), + hook_name: "pre_remove".into(), + stage: HookStage::Starting, + }, + SoarEvent::Hook { + op_id: 5, + pkg_name: "e".into(), + hook_name: "pre_remove".into(), + stage: HookStage::Complete, + }, + SoarEvent::Hook { + op_id: 6, + pkg_name: "i".into(), + hook_name: "post_install".into(), + stage: HookStage::Failed { + exit_code: Some(1), + }, + }, + // Run command + SoarEvent::Running { + op_id: 7, + pkg_name: "j".into(), + stage: RunStage::CacheHit, + }, + SoarEvent::Running { + op_id: 8, + pkg_name: "k".into(), + stage: RunStage::Downloading, + }, + SoarEvent::Running { + op_id: 7, + pkg_name: "j".into(), + stage: RunStage::Executing, + }, + SoarEvent::Running { + op_id: 7, + pkg_name: "j".into(), + stage: RunStage::Complete { + exit_code: 0, + }, + }, + // Build + SoarEvent::Building { + op_id: 4, + pkg_name: "d".into(), + stage: BuildStage::Sandboxing, + }, + SoarEvent::Building { + op_id: 4, + pkg_name: "d".into(), + stage: BuildStage::Running { + command_index: 0, + total_commands: 3, + }, + }, + SoarEvent::Building { + op_id: 4, + pkg_name: "d".into(), + stage: BuildStage::CommandComplete { + command_index: 0, + }, + }, + // Operation completion + SoarEvent::OperationComplete { + op_id: 1, + pkg_name: "a".into(), + }, + SoarEvent::OperationFailed { + op_id: 2, + pkg_name: "b".into(), + error: "not found".into(), + }, + // Process output and cancellation + SoarEvent::ProcessOutput { + op_id: 1, + pkg_name: "a".into(), + line: "hello from hook".into(), + }, + SoarEvent::OperationCancelled { + op_id: 2, + pkg_name: "b".into(), + }, + // Sync stages + SoarEvent::SyncProgress { + repo_name: "repo".into(), + stage: SyncStage::Fetching, + }, + SoarEvent::SyncProgress { + repo_name: "repo".into(), + stage: SyncStage::UpToDate, + }, + SoarEvent::SyncProgress { + repo_name: "repo".into(), + stage: SyncStage::Decompressing, + }, + SoarEvent::SyncProgress { + repo_name: "repo".into(), + stage: SyncStage::WritingDatabase, + }, + SoarEvent::SyncProgress { + repo_name: "repo".into(), + stage: SyncStage::Validating, + }, + SoarEvent::SyncProgress { + repo_name: "repo".into(), + stage: SyncStage::Complete { + package_count: Some(500), + }, + }, + // Batch, apply, log + SoarEvent::BatchProgress { + completed: 5, + total: 10, + failed: 1, + }, + SoarEvent::ApplyComplete { + installed: 3, + updated: 1, + removed: 2, + failed: 0, + }, + SoarEvent::Log { + level: LogLevel::Debug, + message: "debug".into(), + }, + SoarEvent::Log { + level: LogLevel::Info, + message: "info".into(), + }, + SoarEvent::Log { + level: LogLevel::Warning, + message: "warning".into(), + }, + SoarEvent::Log { + level: LogLevel::Error, + message: "error".into(), + }, + ] + } - // Batch + Log - collector.emit(SoarEvent::BatchProgress { - completed: 5, - total: 10, - failed: 1, - }); - collector.emit(SoarEvent::Log { - level: LogLevel::Debug, - message: "debug".into(), - }); - collector.emit(SoarEvent::Log { - level: LogLevel::Info, - message: "info".into(), - }); - collector.emit(SoarEvent::Log { - level: LogLevel::Warning, - message: "warning".into(), - }); - collector.emit(SoarEvent::Log { - level: LogLevel::Error, - message: "error".into(), - }); + #[test] + fn test_all_event_variants() { + let collector = CollectorSink::default(); + for event in every_variant() { + collector.emit(event); + } + assert_eq!(collector.len(), 60); + } - assert_eq!(collector.len(), 55); + #[test] + fn every_variant_round_trips_through_json() { + for event in every_variant() { + let json = serde_json::to_string(&event).unwrap(); + let parsed: SoarEvent = serde_json::from_str(&json).unwrap(); + assert_eq!(parsed, event); + } } } diff --git a/crates/soar-operations/src/apply.rs b/crates/soar-operations/src/apply.rs index 6850e1ce..e97ce7b5 100644 --- a/crates/soar-operations/src/apply.rs +++ b/crates/soar-operations/src/apply.rs @@ -7,6 +7,7 @@ use soar_core::{ connection::DieselDatabase, models::{InstalledPackage, Package}, }, + error::SoarError, package::{ install::InstallTarget, release_source::{ReleaseSource, run_version_command}, @@ -237,6 +238,7 @@ pub async fn execute_apply( let mut updated_count = 0; let mut removed_count = 0; let mut failed_count = 0; + let mut cancelled_count = 0; // Apply pending version updates for in-sync packages for (pkg_name, version) in &diff.pending_version_updates { @@ -251,7 +253,7 @@ pub async fn execute_apply( } // Install new packages - if !diff.to_install.is_empty() { + if !ctx.cancel_token().is_cancelled() && !diff.to_install.is_empty() { let mut version_updates: Vec<(String, String)> = Vec::new(); for (pkg, target) in &diff.to_install { if !tracks_own_version(pkg) || pkg.floats_on_forge() { @@ -280,6 +282,7 @@ pub async fn execute_apply( let report = perform_installation(ctx, targets, &options).await?; installed_count = report.installed.len(); failed_count += report.failed.len(); + cancelled_count += report.cancelled.len(); let succeeded: HashSet<&str> = report .installed @@ -304,7 +307,7 @@ pub async fn execute_apply( } // Update packages - if !diff.to_update.is_empty() { + if !ctx.cancel_token().is_cancelled() && !diff.to_update.is_empty() { let mut update_version_updates: Vec<(String, String)> = Vec::new(); for (pkg, target) in &diff.to_update { if !tracks_own_version(pkg) || pkg.floats_on_forge() { @@ -333,6 +336,7 @@ pub async fn execute_apply( let report = perform_installation(ctx, targets, &options).await?; updated_count = report.installed.len(); failed_count += report.failed.len(); + cancelled_count += report.cancelled.len(); let succeeded: HashSet<&str> = report .installed @@ -357,8 +361,20 @@ pub async fn execute_apply( } // Remove pruned packages - if !diff.to_remove.is_empty() { + if !ctx.cancel_token().is_cancelled() && !diff.to_remove.is_empty() { for pkg in diff.to_remove { + // Cancellation is checked per package, so a batch stops between + // removals instead of running every remaining one once the + // token has fired. + if ctx.cancel_token().is_cancelled() { + ctx.events().emit(SoarEvent::OperationCancelled { + op_id: next_op_id(), + pkg_name: pkg.pkg_name.clone(), + }); + cancelled_count += 1; + continue; + } + let op_id = next_op_id(); ctx.events().emit(SoarEvent::Removing { op_id, @@ -369,6 +385,8 @@ pub async fn execute_apply( let (hooks, sandbox) = get_package_hooks(&pkg.pkg_name); match PackageRemover::new(pkg.clone(), diesel_db.clone(), ctx.config().clone()) .await + .with_events(ctx.events().clone(), op_id) + .with_cancel(ctx.cancel_token().clone()) .with_hooks(hooks) .with_sandbox(sandbox) .remove() @@ -384,6 +402,13 @@ pub async fn execute_apply( }); removed_count += 1; } + Err(SoarError::Cancelled) => { + ctx.events().emit(SoarEvent::OperationCancelled { + op_id, + pkg_name: pkg.pkg_name.clone(), + }); + cancelled_count += 1; + } Err(e) => { ctx.events().emit(SoarEvent::OperationFailed { op_id, @@ -408,6 +433,7 @@ pub async fn execute_apply( updated_count, removed_count, failed_count, + cancelled_count, }) } diff --git a/crates/soar-operations/src/context.rs b/crates/soar-operations/src/context.rs index 357ea5db..b772b8da 100644 --- a/crates/soar-operations/src/context.rs +++ b/crates/soar-operations/src/context.rs @@ -23,7 +23,7 @@ use soar_db::{ }; use soar_events::{EventSinkHandle, LogLevel, SoarEvent, SyncStage}; use soar_registry::{MetadataContent, fetch_metadata}; -use soar_utils::system::is_root; +use soar_utils::{cancel::CancelToken, system::is_root}; use tokio::sync::OnceCell as AsyncOnceCell; use tracing::{debug, trace}; @@ -117,6 +117,7 @@ fn replace_metadata_db( #[derive(Clone)] pub struct SoarContext { inner: Arc, + cancel: CancelToken, } struct SoarContextInner { @@ -135,6 +136,29 @@ impl SoarContext { diesel_core_db: OnceCell::new(), metadata_manager: AsyncOnceCell::new(), }), + cancel: CancelToken::new(), + } + } + + /// The token the operation running through this context is aborted + /// through. + /// + /// A frontend creates one token per operation it may want to abort and + /// hands it to [`SoarContext::with_cancel`], so an abort reaches only the + /// work of that operation. + pub fn cancel_token(&self) -> &CancelToken { + &self.cancel + } + + /// A context sharing everything with this one, but aborted through + /// `cancel`. + /// + /// A frontend creates one token per operation it may want to abort, so + /// cancelling one operation never stops another. + pub fn with_cancel(&self, cancel: CancelToken) -> SoarContext { + SoarContext { + inner: self.inner.clone(), + cancel, } } @@ -424,6 +448,11 @@ impl SoarContext { #[cfg(test)] mod tests { + use std::sync::Arc; + + use soar_events::NullSink; + use soar_utils::cancel::CancelToken; + use super::*; fn mode(path: &Path) -> u32 { @@ -450,4 +479,19 @@ mod tests { .collect(); assert_eq!(left.len(), 2, "temporary files left behind: {left:?}"); } + + #[test] + fn with_cancel_aborts_through_its_own_token_only() { + let ctx = SoarContext::new(Config::default_config::<&str>(&[]), Arc::new(NullSink)); + let token = CancelToken::new(); + let scoped = ctx.with_cancel(token.clone()); + + assert!(!scoped.cancel_token().is_cancelled()); + assert!(!ctx.cancel_token().is_cancelled()); + + token.cancel(); + + assert!(scoped.cancel_token().is_cancelled()); + assert!(!ctx.cancel_token().is_cancelled()); + } } diff --git a/crates/soar-operations/src/health.rs b/crates/soar-operations/src/health.rs index 81c574c0..568176ee 100644 --- a/crates/soar-operations/src/health.rs +++ b/crates/soar-operations/src/health.rs @@ -3,7 +3,7 @@ use std::{ path::{Path, PathBuf}, }; -use soar_core::{SoarResult, package::remove::PackageRemover}; +use soar_core::{SoarResult, error::SoarError, package::remove::PackageRemover}; use soar_db::repository::core::CoreRepository; use soar_events::{RemoveStage, SoarEvent}; use soar_utils::{error::FileSystemResult, fs::walk_dir, path::resolve_path}; @@ -71,8 +71,19 @@ pub async fn remove_broken_packages(ctx: &SoarContext) -> SoarResult SoarResult SoarResult { + ctx.events().emit(SoarEvent::OperationCancelled { + op_id, + pkg_name: pkg_name.clone(), + }); + cancelled.push(pkg_name); + } Err(err) => { ctx.events().emit(SoarEvent::OperationFailed { op_id, @@ -123,6 +143,7 @@ pub async fn remove_broken_packages(ctx: &SoarContext) -> SoarResult SoarResult { debug!(count = targets.len(), "performing installation"); - let diesel_db = ctx.diesel_core_db()?.clone(); let parallel_limit = ctx.config().parallel_limit.unwrap_or(4); let semaphore = Arc::new(Semaphore::new(parallel_limit as usize)); let installed = Arc::new(Mutex::new(Vec::new())); let failed = Arc::new(Mutex::new(Vec::new())); let warnings = Arc::new(Mutex::new(Vec::new())); + let cancelled = Arc::new(Mutex::new(Vec::new())); let total = targets.len() as u32; let completed = Arc::new(AtomicU32::new(0)); @@ -756,12 +756,26 @@ pub async fn perform_installation( let mut handles = Vec::new(); for target in targets { + if ctx.cancel_token().is_cancelled() { + let op_id = next_op_id(); + ctx.events().emit(SoarEvent::OperationCancelled { + op_id, + pkg_name: target.package.pkg_name.clone(), + }); + cancelled + .lock() + .unwrap() + .push(target.package.pkg_name.clone()); + continue; + } + let permit = semaphore.clone().acquire_owned().await.unwrap(); + let db = ctx.diesel_core_db()?.clone(); let ctx = ctx.clone(); - let db = diesel_db.clone(); let installed = installed.clone(); let failed = failed.clone(); let warnings = warnings.clone(); + let cancelled = cancelled.clone(); let completed = completed.clone(); let failed_count = failed_count.clone(); let binary_only = options.binary_only; @@ -816,6 +830,17 @@ pub async fn perform_installation( warn!(error = %err, "could not remove the superseded version"); } } + SoarError::Cancelled => { + let op_id = next_op_id(); + ctx.events().emit(SoarEvent::OperationCancelled { + op_id, + pkg_name: target.package.pkg_name.clone(), + }); + cancelled + .lock() + .unwrap() + .push(target.package.pkg_name.clone()); + } _ => { let op_id = next_op_id(); ctx.events().emit(SoarEvent::OperationFailed { @@ -854,11 +879,13 @@ pub async fn perform_installation( let installed = Arc::try_unwrap(installed).unwrap().into_inner().unwrap(); let failed = Arc::try_unwrap(failed).unwrap().into_inner().unwrap(); let warnings = Arc::try_unwrap(warnings).unwrap().into_inner().unwrap(); + let cancelled = Arc::try_unwrap(cancelled).unwrap().into_inner().unwrap(); Ok(InstallReport { installed, failed, warnings, + cancelled, }) } @@ -1123,12 +1150,17 @@ async fn install_single_package( config.clone(), events.clone(), op_id, + ctx.cancel_token().clone(), ) .await?; // Download let downloaded_checksum = installer.download_package().await?; + if ctx.cancel_token().is_cancelled() { + return Err(SoarError::Cancelled); + } + // Signature verification let mut verified_sig_count = 0usize; if let Some(repository) = config.get_repository(&pkg.repo_name) { @@ -1214,6 +1246,13 @@ async fn install_single_package( } } + // Cancellation is honored only up to here: once linking starts the rest + // runs to completion, because stopping after the links are published + // would leave them with no database row to match. + if ctx.cancel_token().is_cancelled() { + return Err(SoarError::Cancelled); + } + // Create symlinks events.emit(SoarEvent::Installing { op_id, @@ -1409,6 +1448,12 @@ fn cleanup_sig_files(install_dir: &Path) { #[cfg(test)] mod tests { + use std::{fs, path::Path, sync::Arc}; + + use soar_config::config::Config; + use soar_events::{CollectorSink, EventSinkHandle}; + use soar_utils::cancel::CancelToken; + use super::*; fn pkg(repo_name: &str, ghcr: Option<&str>, bsum: Option<&str>) -> Package { @@ -1420,6 +1465,65 @@ mod tests { } } + fn named_target(name: &str) -> InstallTarget { + InstallTarget { + package: Package { + pkg_name: name.to_string(), + ..Default::default() + }, + ..Default::default() + } + } + + /// A context whose config keeps every path inside `root`. + fn context_in(root: &Path, events: EventSinkHandle) -> SoarContext { + let mut config = Config::default_config::<&str>(&[]); + config.db_path = Some(root.join("db").display().to_string()); + config.bin_path = Some(root.join("bin").display().to_string()); + fs::create_dir_all(root.join("bin")).unwrap(); + SoarContext::new(config, events) + } + + #[tokio::test] + async fn a_cancelled_install_skips_every_target_without_touching_files() { + let root = tempfile::tempdir().unwrap(); + let collector = Arc::new(CollectorSink::default()); + let events: EventSinkHandle = collector.clone(); + let token = CancelToken::new(); + let ctx = context_in(root.path(), events).with_cancel(token.clone()); + token.cancel(); + + let report = perform_installation( + &ctx, + vec![named_target("one"), named_target("two")], + &InstallOptions::default(), + ) + .await + .unwrap(); + + assert_eq!(report.cancelled, ["one", "two"]); + assert!(report.installed.is_empty()); + assert!(report.failed.is_empty()); + assert!(report.warnings.is_empty()); + + let cancelled_events = collector + .events() + .iter() + .filter(|e| matches!(e, SoarEvent::OperationCancelled { .. })) + .count(); + assert_eq!(cancelled_events, 2); + + assert!( + !root.path().join("db").exists(), + "the core database was created" + ); + assert!( + !root.path().join("packages").exists(), + "a package directory was created" + ); + assert_eq!(fs::read_dir(root.path().join("bin")).unwrap().count(), 0); + } + #[test] fn local_source_skips_integrity_gate() { assert!(source_skips_integrity_gate(&pkg("local", None, None))); diff --git a/crates/soar-operations/src/lib.rs b/crates/soar-operations/src/lib.rs index 4bb8392e..4e8a714d 100644 --- a/crates/soar-operations/src/lib.rs +++ b/crates/soar-operations/src/lib.rs @@ -1,4 +1,5 @@ pub mod context; +pub mod privilege; pub mod progress; pub mod types; pub mod utils; diff --git a/crates/soar-operations/src/list.rs b/crates/soar-operations/src/list.rs index 0eba0704..86d2fb56 100644 --- a/crates/soar-operations/src/list.rs +++ b/crates/soar-operations/src/list.rs @@ -167,6 +167,7 @@ pub async fn list_packages( pkg_family: entry.pkg.pkg_family, pkg_type: entry.pkg.pkg_type, version: entry.pkg.version, + description: entry.pkg.description.unwrap_or_default(), ..Default::default() }; diff --git a/crates/soar-operations/src/privilege.rs b/crates/soar-operations/src/privilege.rs new file mode 100644 index 00000000..d6972b06 --- /dev/null +++ b/crates/soar-operations/src/privilege.rs @@ -0,0 +1,133 @@ +//! Finding a privilege escalation tool and building commands that run through it. + +use std::{ + env, + ffi::OsString, + fs, + os::unix::fs::PermissionsExt as _, + path::{Path, PathBuf}, + process::{Command, Stdio}, +}; + +use soar_config::config::{PATH_ENV_SUFFIXES, path_env_var}; + +/// Directories a privilege escalation tool is taken from. +/// +/// They are writable only by root. A tool found through `PATH` could be any +/// program the user's environment points at, which would then show the +/// password prompt. +pub const ESCALATION_DIRS: &[&str] = &[ + "/run/wrappers/bin", + "/usr/local/bin", + "/usr/bin", + "/bin", + "/usr/sbin", + "/sbin", +]; + +/// Which program grants root. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum EscalationKind { + /// The `doas` program. + Doas, + /// The `sudo` program. + Sudo, +} + +/// A privilege escalation program found in a root-owned directory. +#[derive(Debug, Clone)] +pub struct EscalationTool { + /// Absolute path of the tool. + pub path: PathBuf, + /// Which program the path holds. + pub kind: EscalationKind, +} + +/// Finds `doas`, or else `sudo`, in [`ESCALATION_DIRS`]. +/// +/// Probing by running the escalation tool would prompt for a password just to +/// learn whether it is installed, which is what the caller is trying to avoid. +pub fn find_escalation_tool() -> Option { + [ + ("doas", EscalationKind::Doas), + ("sudo", EscalationKind::Sudo), + ] + .iter() + .find_map(|(name, kind)| { + ESCALATION_DIRS + .iter() + .map(|dir| Path::new(dir).join(name)) + .find(|path| { + fs::metadata(path).is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0) + }) + .map(|path| { + EscalationTool { + path, + kind: *kind, + } + }) + }) +} + +/// Builds `tool tool_args... [env VAR=value...] exe args...`. +/// +/// sudo and doas reset the environment, so the system path overrides are +/// handed to the privileged process explicitly. `tool_args` are options +/// for the tool itself, such as `-n`. +pub fn escalated_command( + tool: &EscalationTool, + tool_args: &[&str], + exe: &Path, + args: &[OsString], +) -> Command { + let forwarded: Vec = PATH_ENV_SUFFIXES + .iter() + .filter_map(|suffix| { + let var = path_env_var(suffix, true); + env::var_os(&var).map(|value| { + let mut assignment = OsString::from(format!("{var}=")); + assignment.push(value); + assignment + }) + }) + .collect(); + + let mut command = Command::new(&tool.path); + command.args(tool_args); + if !forwarded.is_empty() { + command.arg("env").args(&forwarded); + } + command.arg(exe).args(args); + command +} + +/// Whether `tool` would run a command without asking for a password, +/// because the user's credentials are cached or no password is required. +/// +/// Runs `tool -n true` with no terminal input, so it never prompts. +pub fn runs_without_password(tool: &EscalationTool) -> bool { + Command::new(&tool.path) + .arg("-n") + .arg("true") + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .is_ok_and(|status| status.success()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_escalation_tool_comes_from_a_root_owned_directory() { + if let Some(tool) = find_escalation_tool() { + assert!( + ESCALATION_DIRS + .iter() + .any(|dir| tool.path.parent() == Some(Path::new(dir))) + ); + } + } +} diff --git a/crates/soar-operations/src/remove.rs b/crates/soar-operations/src/remove.rs index ae14445a..cf58ef27 100644 --- a/crates/soar-operations/src/remove.rs +++ b/crates/soar-operations/src/remove.rs @@ -127,8 +127,19 @@ pub async fn perform_removal( let mut removed = Vec::new(); let mut failed = Vec::new(); + let mut cancelled = Vec::new(); for pkg in packages { + if ctx.cancel_token().is_cancelled() { + let op_id = next_op_id(); + ctx.events().emit(SoarEvent::OperationCancelled { + op_id, + pkg_name: pkg.pkg_name.clone(), + }); + cancelled.push(pkg.pkg_name.clone()); + continue; + } + let op_id = next_op_id(); ctx.events().emit(SoarEvent::Removing { @@ -146,6 +157,8 @@ pub async fn perform_removal( let (hooks, sandbox) = get_package_hooks(&pkg.pkg_name); let remover = PackageRemover::new(pkg.clone(), diesel_db.clone(), ctx.config().clone()) .await + .with_events(ctx.events().clone(), op_id) + .with_cancel(ctx.cancel_token().clone()) .with_hooks(hooks) .with_sandbox(sandbox); @@ -169,6 +182,13 @@ pub async fn perform_removal( version: pkg.version, }); } + Err(SoarError::Cancelled) => { + ctx.events().emit(SoarEvent::OperationCancelled { + op_id, + pkg_name: pkg.pkg_name.clone(), + }); + cancelled.push(pkg.pkg_name); + } Err(err) => { ctx.events().emit(SoarEvent::OperationFailed { op_id, @@ -187,5 +207,74 @@ pub async fn perform_removal( Ok(RemoveReport { removed, failed, + cancelled, }) } + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use soar_config::config::Config; + use soar_events::{CollectorSink, EventSinkHandle, SoarEvent}; + use soar_utils::cancel::CancelToken; + use tempfile::tempdir; + + use super::*; + + fn installed(name: &str) -> InstalledPackage { + InstalledPackage { + id: 1, + repo_name: "local".into(), + pkg_id: None, + pkg_name: name.into(), + pkg_family: None, + pkg_type: None, + version: "1.0".into(), + size: 0, + checksum: None, + installed_path: String::new(), + installed_date: String::new(), + profile: "default".into(), + pinned: false, + is_installed: true, + detached: false, + unlinked: false, + provides: None, + portable_path: None, + portable_home: None, + portable_config: None, + portable_share: None, + portable_cache: None, + install_patterns: None, + download_url: None, + update_info: None, + } + } + + #[tokio::test] + async fn a_cancelled_removal_skips_every_package() { + let root = tempdir().unwrap(); + let mut config = Config::default_config::<&str>(&[]); + config.db_path = Some(root.path().join("db").display().to_string()); + + let collector = Arc::new(CollectorSink::default()); + let events: EventSinkHandle = collector.clone(); + let token = CancelToken::new(); + let ctx = SoarContext::new(config, events).with_cancel(token.clone()); + token.cancel(); + + let report = perform_removal(&ctx, vec![installed("foo")]).await.unwrap(); + + assert_eq!(report.cancelled, ["foo"]); + assert!(report.removed.is_empty()); + assert!(report.failed.is_empty()); + + let cancelled_events = collector + .events() + .iter() + .filter(|e| matches!(e, SoarEvent::OperationCancelled { .. })) + .count(); + assert_eq!(cancelled_events, 1); + } +} diff --git a/crates/soar-operations/src/types.rs b/crates/soar-operations/src/types.rs index 6e3ad209..33626402 100644 --- a/crates/soar-operations/src/types.rs +++ b/crates/soar-operations/src/types.rs @@ -53,6 +53,9 @@ pub struct InstallReport { pub installed: Vec, pub failed: Vec, pub warnings: Vec, + /// Names of the packages skipped or stopped because the operation was + /// cancelled. + pub cancelled: Vec, } /// Info about a successfully installed package. @@ -92,6 +95,9 @@ pub enum RemoveResolveResult { pub struct RemoveReport { pub removed: Vec, pub failed: Vec, + /// Names of the packages skipped or stopped because the operation was + /// cancelled. + pub cancelled: Vec, } pub struct RemovedInfo { @@ -115,6 +121,9 @@ pub struct UpdateReport { pub updated: Vec, pub failed: Vec, pub url_updates: Vec, + /// Names of the packages skipped or stopped because the operation was + /// cancelled. + pub cancelled: Vec, } /// Tracks URL packages that need their packages.toml updated after successful update. @@ -216,6 +225,9 @@ pub struct ApplyReport { pub updated_count: usize, pub removed_count: usize, pub failed_count: usize, + /// How many packages were skipped or stopped because the operation was + /// cancelled. + pub cancelled_count: usize, } // ---- Run ---- diff --git a/crates/soar-operations/src/update.rs b/crates/soar-operations/src/update.rs index 91f674f5..d4f575ee 100644 --- a/crates/soar-operations/src/update.rs +++ b/crates/soar-operations/src/update.rs @@ -802,6 +802,7 @@ pub async fn perform_update( Ok(UpdateReport { updated: install_report.installed, failed: install_report.failed, + cancelled: install_report.cancelled, url_updates, }) } diff --git a/crates/soar-tui/Cargo.toml b/crates/soar-tui/Cargo.toml new file mode 100644 index 00000000..a4f5f0bb --- /dev/null +++ b/crates/soar-tui/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "soar-tui" +version = "0.1.0" +description = "Terminal user interface for soar" +license.workspace = true +edition.workspace = true +rust-version.workspace = true +repository.workspace = true +keywords.workspace = true +readme.workspace = true +categories.workspace = true + +[dependencies] +chrono = { workspace = true } +nucleo-matcher = { workspace = true } +ratatui = { workspace = true } +serde_json = { workspace = true } +soar-config = { workspace = true } +soar-core = { workspace = true } +soar-events = { workspace = true } +soar-operations = { workspace = true } +soar-utils = { workspace = true } +tokio = { workspace = true } +tracing = { workspace = true } +tracing-subscriber = { workspace = true } + diff --git a/crates/soar-tui/src/action.rs b/crates/soar-tui/src/action.rs new file mode 100644 index 00000000..a6ca064e --- /dev/null +++ b/crates/soar-tui/src/action.rs @@ -0,0 +1,106 @@ +//! What a pressed key means. + +use crate::views::ViewId; + +/// One thing a key can ask the interface to do. +/// +/// Every variant corresponds to one row of the keymap tables in +/// [`crate::keymap`]. View-local actions reach the active view once the views +/// hold their own state. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Action { + /// Shows one of the seven views. + View(ViewId), + /// Moves to the next view, wrapping around. + NextView, + /// Moves to the previous view, wrapping around. + PrevView, + /// Opens the help overlay. + Help, + /// Quits the interface. + Quit, + /// Reloads the active view's data. + Reload, + /// Moves the cursor one row down. + Down, + /// Moves the cursor one row up. + Up, + /// Moves the cursor to the first row. + Top, + /// Moves the cursor to the last row. + Bottom, + /// Moves the cursor half a page down. + PageDown, + /// Moves the cursor half a page up. + PageUp, + /// Clears the filter, then clears the marks. + Escape, + /// Edits the view's filter. + Filter, + /// Marks or unmarks the current row. + ToggleMark, + /// Marks every row, or clears all marks. + MarkAll, + /// Installs the marked packages, or the current row. + Install, + /// Installs through the install options dialog. + InstallWithOptions, + /// Picks a version of the package, then installs it. + PickVersion, + /// Runs the package without installing it. + RunPackage, + /// Installs from a name, URL, or path. + InstallByQuery, + /// Cycles the repository filter. + CycleRepo, + /// Opens or closes the full-screen detail. + ToggleDetail, + /// Removes the marked packages, or the current row. + Remove, + /// Switches the current package to another variant. + SwitchVariant, + /// Checks updates for the marked packages, or the current row. + UpdateSelected, + /// Cycles the sort order. + CycleSort, + /// Updates the marked packages, or all when none are marked. + Update, + /// Toggles keeping old versions during an update. + ToggleKeepOld, + /// Shows or hides the skipped rows. + ToggleSkipped, + /// Applies the changes packages.toml describes. + Apply, + /// Toggles pruning packages missing from packages.toml. + TogglePrune, + /// Opens packages.toml in an editor. + EditPackages, + /// Creates the default packages.toml when it is missing. + CreatePackages, + /// Syncs every repository. + Sync, + /// Enables or disables the current repository. + ToggleEnabled, + /// Adds a repository. + AddRepo, + /// Removes the current repository. + RemoveRepo, + /// Opens config.toml in an editor. + EditConfig, + /// Cleans the package cache. + CleanCache, + /// Fixes broken symlinks. + FixSymlinks, + /// Removes broken packages. + RemoveBroken, + /// Focuses the detail pane of the current job. + FocusDetail, + /// Focuses the log pane. + FocusLog, + /// Removes finished jobs from the list. + ClearFinished, + /// Asks the running job to stop, with a confirm first. + AbortJob, + /// Aborts or drops the job the Jobs view points at. + AbortSelected, +} diff --git a/crates/soar-tui/src/app.rs b/crates/soar-tui/src/app.rs new file mode 100644 index 00000000..60601e0d --- /dev/null +++ b/crates/soar-tui/src/app.rs @@ -0,0 +1,7598 @@ +//! The interface's state and how it reacts to messages. + +use std::{ + collections::{HashSet, VecDeque}, + path::PathBuf, + time::{Duration, Instant}, +}; + +use ratatui::{ + crossterm::event::{ + Event, KeyCode, KeyEvent, KeyEventKind, MouseButton, MouseEvent, MouseEventKind, + }, + layout::{Position, Rect}, + text::{Line, Span}, +}; +use soar_config::repository::Repository; +use soar_core::{ + database::models::{InstalledPackage, Package}, + package::install::InstallTarget, +}; +use soar_events::{LogLevel as EventLevel, SoarEvent, UpdateCheckStatus}; +use soar_operations::{InstalledEntry, PrepareRunResult, VariantInfo, privilege::EscalationTool}; + +use crate::{ + action::Action, + effect::{Effect, Suspended}, + format, + jobs::{ + InstallChoices, Job, JobId, JobKind, JobOutcome, JobSpec, JobState, Jobs, OutcomeLine, + RepoChange, SystemMode, + }, + keymap, + loadable::Loadable, + log::{Log, LogLevel}, + msg::{Loaded, Msg, Resolution}, + privileged::EscalationProbe, + progress::Tracker, + theme::Theme, + views::{ + ViewId, + apply::ApplyView, + browse::{BrowseView, PackageKey}, + health::HealthView, + installed::InstalledView, + jobs::{JobsFocus, JobsView}, + repos::ReposView, + updates::UpdatesView, + }, + widgets::{ + authorize::Authorize, + confirm::Confirm, + form::{Field, FieldValue, Form, FormValues}, + help::Help, + overlay::{OnAccept, Overlay, OverlayOutcome, QuitGuard, Value}, + picker::Picker, + text_input::{Prompt, TextInput}, + toast::{ToastKind, Toasts}, + }, +}; + +/// Facts about this session, shown in the header. +pub(crate) struct AppEnv { + /// The version string shown in the header. + pub(crate) version: String, + /// The profile the interface runs against. + pub(crate) profile: String, + /// Whether the session manages the system tree. + pub(crate) system: bool, + /// The configuration file the repositories view opens in an editor. + pub(crate) config_path: PathBuf, + /// The declared packages file the apply view edits and creates. + pub(crate) packages_path: PathBuf, +} + +/// An install being arranged, from the resolution to the accepted confirm. +/// It holds what the queries resolved to and what the user picked until +/// the confirm queues the job or the flow is cancelled. +pub(crate) struct PendingInstall { + /// The options the install runs with. + choices: InstallChoices, + /// The resolved install plans, ready to run. + targets: Vec, + /// The variants the user chose for ambiguous queries. + picked: Vec, + /// The ambiguous queries still to ask about, each with the packages + /// it matched. + ambiguous: VecDeque<(String, Vec)>, +} + +/// How long the finished-job summary stays in the activity strip after the +/// last job ends. +const STRIP_LINGER: Duration = Duration::from_secs(3); + +/// How many rows a health fix confirm lists before the rest fold into a +/// count. +const CONFIRM_ROWS: usize = 10; + +/// How many rows the wheel moves the list under the pointer by. +const WHEEL_ROWS: usize = 3; + +/// Where chrome elements landed in the last frame, so pointer clicks can +/// find what they hit. +#[derive(Debug, Default)] +pub(crate) struct LayoutCache { + /// The rect of each header tab, in screen coordinates. + pub(crate) tabs: Vec<(Rect, ViewId)>, + /// The rows area of the focused view's main list, with the index of + /// its first visible row. + pub(crate) list: Option<(Rect, usize)>, + /// The rows area of the detail pane on screen, when one fills the + /// screen or sits beside the jobs list. + pub(crate) detail: Option, + /// The rows area of the jobs view's log pane. + pub(crate) log: Option, + /// The rect an open overlay covers, when one is open. + pub(crate) overlay: Option, +} + +/// The interface's whole state. Every change goes through [`App::update`]. +pub(crate) struct App { + /// The view on screen. + pub(crate) view: ViewId, + /// The session facts shown in the header. + pub(crate) env: AppEnv, + /// Whether the user asked to quit. + pub(crate) quit: bool, + /// Whether the screen needs a redraw. + pub(crate) dirty: bool, + /// The colors and glyphs this session draws with. + pub(crate) theme: Theme, + /// Spinner frame counter, advanced on every tick. + pub(crate) frame: u64, + /// Where chrome elements landed in the last frame. + pub(crate) layout: LayoutCache, + /// The overlay capturing input, if one is open. + pub(crate) overlay: Option, + /// The brief notifications stacked over the body. + pub(crate) toasts: Toasts, + /// The mutating operations, run one at a time from a queue. + pub(crate) jobs: Jobs, + /// Progress of soar work outside the queue, such as the metadata sync on + /// first load or a download started by running a package. + pub(crate) background: Tracker, + /// When the finished-job summary leaves the activity strip. + pub(crate) activity_until: Option, + /// The last time a message arrived, for elapsed times on screen. + pub(crate) now: Instant, + /// The rolling log of everything the interface and soar printed. + pub(crate) log: Log, + /// The cursor state of the jobs view. + pub(crate) jobs_view: JobsView, + /// The package catalog view. + pub(crate) browse: BrowseView, + /// The installed packages view. + pub(crate) installed: InstalledView, + /// The available updates view. + pub(crate) updates: UpdatesView, + /// The declarative packages view. + pub(crate) apply: ApplyView, + /// The repositories view. + pub(crate) repos: ReposView, + /// The health checks and the paths they ran against. + pub(crate) health: HealthView, + /// The install being arranged, from the resolution to the confirm. + pub(crate) pending: Option, + /// The run waiting for its variant to be picked: the arguments the + /// run prompt collected with the packages the ambiguous query + /// matched. The picker's accept turns the chosen package into an + /// exact query and prepares the run again. + pub(crate) run_pick: Option<(Vec, Vec)>, + /// The variants loaded for a switch: the package name they belong to + /// with the variants themselves. The picker's accept links the + /// chosen one, and closing the picker drops them. + pub(crate) variant_pick: Option<(String, Vec)>, + /// The rows the update confirm was opened for, by index into the + /// ready updates list, sorted ascending. The confirm's accept moves + /// those entries out of the list, and closing the confirm drops the + /// indexes unused. + pub(crate) update_pick: Option>, + /// The package the version picker was opened for, with its newest + /// version and the older ones. The picker's accept reads the picked + /// index against this package, so a catalog reload while the picker + /// is open cannot aim the pick at another row. + pub(crate) version_pick: Option<(PackageKey, String, Vec)>, + /// The package the run prompt was opened for, as the query, the + /// repository, and the package id a run needs. Accepting the prompt + /// runs this package with the typed arguments, whatever row the + /// cursor sits on by then. + pub(crate) run_args: Option<(String, Option, Option)>, + /// Whether the interface quits once the running job finishes. + pub(crate) quit_when_idle: bool, + /// The number of the password check in flight. Every submission + /// numbers itself so an answer from a check a newer one replaced can + /// be dropped. + pub(crate) pass_check: u32, + /// The number of the catalog load in flight. Every load numbers + /// itself so a reply from a load a newer one replaced, success or + /// error, can be dropped instead of overwriting newer state. + pub(crate) catalog_load: u32, + /// The number of the installed list load in flight, numbered like + /// the catalog's so a replaced load's reply is dropped. + pub(crate) installed_load: u32, + /// The job the abort confirm was opened for. The confirm names that + /// job, so accepting it stops that one and not whatever runs by the + /// time the answer comes. + pub(crate) abort_pick: Option, + /// The plan number the apply confirm was opened against. A fresh + /// plan arriving under the confirm retires it, so accepting can + /// never queue removals the confirm never named. + pub(crate) apply_pick: Option, + /// The error that ended the terminal input, if any. The interface + /// cannot show it once its input is gone, so the entry point prints + /// it after the terminal is restored. + pub(crate) fatal: Option, +} + +impl App { + /// Creates the state the interface starts in: on the first view, dirty so + /// the first frame gets drawn. + pub(crate) fn new(env: AppEnv, theme: Theme) -> App { + App { + view: ViewId::Browse, + env, + quit: false, + dirty: true, + theme, + frame: 0, + layout: LayoutCache::default(), + overlay: None, + toasts: Toasts::default(), + jobs: Jobs::new(), + background: Tracker::default(), + activity_until: None, + now: Instant::now(), + log: Log::new(), + jobs_view: JobsView::default(), + browse: BrowseView::default(), + installed: InstalledView::default(), + updates: UpdatesView::default(), + apply: ApplyView::default(), + repos: ReposView::default(), + health: HealthView::default(), + pending: None, + run_pick: None, + variant_pick: None, + update_pick: None, + version_pick: None, + run_args: None, + quit_when_idle: false, + pass_check: 0, + catalog_load: 0, + installed_load: 0, + abort_pick: None, + apply_pick: None, + fatal: None, + } + } + + /// The number of available updates, shown beside the Updates tab. + pub(crate) fn updates_badge(&self) -> Option { + self.updates.list.ready().map(Vec::len) + } + + /// Whether the last job failed without being seen, shown beside the Jobs + /// tab. Opening the Jobs view clears it. + pub(crate) fn jobs_attention(&self) -> bool { + self.jobs.attention && self.view != ViewId::Jobs + } + + /// The message at the right end of the status bar: how many rows are + /// marked for the next bulk action. + pub(crate) fn status_right(&self) -> String { + let marked = match self.view { + ViewId::Browse if !self.browse.marks.is_empty() => Some(self.browse.marks.len()), + ViewId::Installed if !self.installed.marks.is_empty() => { + Some(self.installed.marks.len()) + } + _ => None, + }; + marked + .map(|count| format!("{count} marked")) + .unwrap_or_default() + } + + /// The live value shown after a status bar hint, such as the repository + /// the catalog list is narrowed to or the order the installed list + /// sorts in. + pub(crate) fn hint_suffix(&self, action: &Action) -> Option { + if *action == Action::CycleRepo && self.view == ViewId::Browse { + let name = self.browse.repo_filter.as_deref().unwrap_or("all"); + return Some(format!(": {name}")); + } + if *action == Action::CycleSort && self.view == ViewId::Installed { + return Some(format!(": {}", self.installed.sort.label())); + } + None + } + + /// Whether a bound key's hint applies right now. Hints that name an + /// action with nothing to do stay off the status bar. + pub(crate) fn hint_visible(&self, action: &Action) -> bool { + if *action == Action::CreatePackages { + return self + .apply + .plan + .ready() + .is_some_and(|plan| plan.diff.is_none()); + } + true + } + + /// The height of the activity strip above the status bar: a rule, a + /// summary line, and up to four operation lines while a job runs, then + /// a rule and a summary line for three seconds after the last one + /// finishes, then a rule plus one line per repository still syncing + /// and a summary for other background work, then nothing. + pub(crate) fn activity_height(&self) -> u16 { + if let Some(job) = self.running_job() { + let lines = if job.kind == JobKind::Sync { + job.tracker.sync.len() + } else { + job.tracker.active().count() + }; + 2 + lines.min(4) as u16 + u16::from(lines > 4) + } else if self.activity_until.is_some() { + 2 + } else { + let syncing = self.background.active_sync().count(); + let preparing = self.background.active().next().is_some(); + if syncing == 0 && !preparing { + return 0; + } + 1 + syncing.min(4) as u16 + u16::from(syncing > 4) + u16::from(preparing) + } + } + + /// Queues a brief notification and marks the screen for a redraw. + pub(crate) fn toast(&mut self, kind: ToastKind, text: impl Into, now: Instant) { + self.toasts.push(kind, text, now); + self.dirty = true; + } + + /// Adds a job to the queue and starts it right away when nothing runs + /// and nothing waits for authorization. The views call this as their + /// actions are accepted; until then only tests do. + #[allow(dead_code)] + pub(crate) fn enqueue(&mut self, spec: JobSpec, now: Instant) -> Vec { + // Wait-and-quit drops the queue and leaves at the next idle + // moment, so a confirmation accepted after it must not sneak an + // unapproved job past the guard, and must not hold the quit open + // either. + if self.quit_when_idle { + self.toast( + ToastKind::Info, + "Quitting soon, so no new work is accepted", + now, + ); + return Vec::new(); + } + let id = self.jobs.next_id; + self.jobs.next_id += 1; + self.jobs.list.push(Job { + id, + kind: spec.kind(), + title: spec.title(), + state: JobState::Queued, + spec: Some(spec), + tracker: Tracker::default(), + }); + self.dirty = true; + if self.running_job().is_none() && !self.authorizing() { + self.start_next(now) + } else { + Vec::new() + } + } + + /// Whether any job waits for the user to authorize the administrator + /// pass. While one does, the queue holds still, since the pass that + /// follows it must run before anything else. + fn authorizing(&self) -> bool { + self.jobs + .list + .iter() + .any(|job| matches!(job.state, JobState::Authorizing)) + } + + /// The job waiting for the administrator authorization, if any. + fn authorizing_job(&self) -> Option<&Job> { + self.jobs + .list + .iter() + .find(|job| matches!(job.state, JobState::Authorizing)) + } + + /// The job waiting for the administrator authorization, for finishing + /// or starting it. + fn authorizing_job_mut(&mut self) -> Option<&mut Job> { + self.jobs + .list + .iter_mut() + .find(|job| matches!(job.state, JobState::Authorizing)) + } + + /// The job currently running, if any. The quit guard and the activity + /// strip read it. + pub(crate) fn running_job(&self) -> Option<&Job> { + self.jobs + .list + .iter() + .find(|job| matches!(job.state, JobState::Running { .. })) + } + + /// The job currently running, for feeding it progress events. + pub(crate) fn running_job_mut(&mut self) -> Option<&mut Job> { + self.jobs + .list + .iter_mut() + .find(|job| matches!(job.state, JobState::Running { .. })) + } + + /// How many jobs are waiting for their turn, shown by the activity + /// strip's summary line. + pub(crate) fn queued_count(&self) -> usize { + self.jobs + .list + .iter() + .filter(|job| matches!(job.state, JobState::Queued)) + .count() + } + + /// Starts the first queued job, taking its spec, and returns the effect + /// that runs it. A queued system pass first waits for the user to + /// authorize it, so its turn returns the probe instead. Nothing starts + /// while a job waits for authorization. + fn start_next(&mut self, now: Instant) -> Vec { + if self.authorizing() { + return Vec::new(); + } + let Some(job) = self + .jobs + .list + .iter_mut() + .find(|job| matches!(job.state, JobState::Queued)) + else { + return Vec::new(); + }; + if matches!( + job.spec, + Some(JobSpec::ApplySystem { + mode: SystemMode::Pending, + .. + }) + ) { + job.state = JobState::Authorizing; + self.dirty = true; + return vec![Effect::ProbeEscalation]; + } + let Some(spec) = job.spec.take() else { + return Vec::new(); + }; + job.state = JobState::Running { + started: now, + aborting: false, + }; + self.dirty = true; + vec![Effect::StartJob { + id: job.id, + spec, + }] + } + + /// Starts the job whose authorization succeeded, taking its spec. + fn start_authorizing(&mut self, now: Instant) -> Vec { + let Some(job) = self.authorizing_job_mut() else { + return Vec::new(); + }; + let JobState::Authorizing = job.state else { + return Vec::new(); + }; + let Some(spec) = job.spec.take() else { + return Vec::new(); + }; + job.state = JobState::Running { + started: now, + aborting: false, + }; + let id = job.id; + self.dirty = true; + vec![Effect::StartJob { + id, + spec, + }] + } + + /// Finishes the job waiting for authorization as withdrawn by the + /// user, then starts the next one. + fn skip_authorizing(&mut self, now: Instant) -> Vec { + let Some(job) = self.authorizing_job() else { + return Vec::new(); + }; + let id = job.id; + let outcome = JobOutcome { + ok: true, + aborted: true, + headline: "System packages skipped".to_string(), + lines: Vec::new(), + }; + self.on_job_finished(id, outcome, now) + } + + /// Drops the pick and prompt state an open overlay kept, so nothing + /// outlives the overlay it belonged to. + fn drop_overlay_state(&mut self) { + self.run_pick = None; + self.variant_pick = None; + self.update_pick = None; + self.version_pick = None; + self.run_args = None; + self.abort_pick = None; + self.apply_pick = None; + } + + /// Opens the administrator password dialog for the authorizing job. + /// While `busy`, it shows the password being checked. + fn open_authorize(&mut self, busy: bool) { + let names = match self.authorizing_job() { + Some(Job { + spec: Some(JobSpec::ApplySystem { + names, .. + }), + .. + }) => names.clone(), + _ => return, + }; + // The dialog takes the overlay slot from whatever else is open, + // so the state that overlay kept goes the way its own close path + // would drop it. + if self.overlay.is_some() && !matches!(self.overlay, Some(Overlay::Authorize(_))) { + self.drop_overlay_state(); + } + self.overlay = Some(Overlay::Authorize(if busy { + Authorize::waiting(names) + } else { + Authorize::new(names) + })); + self.dirty = true; + } + + /// The open password dialog, for showing why a password was refused. + fn authorize_mut(&mut self) -> Option<&mut Authorize> { + match self.overlay.as_mut() { + Some(Overlay::Authorize(dialog)) => Some(dialog), + _ => None, + } + } + + /// Marks a finished job, tells the user how it went, and starts the + /// next one. A job that never ran, because its authorization failed + /// or was withdrawn, finishes with the moment it was given up as its + /// start. + fn on_job_finished(&mut self, id: JobId, outcome: JobOutcome, now: Instant) -> Vec { + let Some(job) = self.jobs.list.iter_mut().find(|job| job.id == id) else { + return Vec::new(); + }; + let kind = job.kind; + let started = match job.state { + JobState::Running { + started, .. + } => started, + JobState::Authorizing => now, + _ => return Vec::new(), + }; + let ok = outcome.ok; + let aborted = outcome.aborted; + let headline = outcome.headline.clone(); + job.state = JobState::Finished { + started, + ended: now, + outcome, + }; + self.dirty = true; + self.toast( + if aborted { + ToastKind::Warning + } else if ok { + ToastKind::Success + } else { + ToastKind::Error + }, + headline, + now, + ); + if !ok && !aborted { + self.jobs.attention = true; + } + if matches!( + kind, + JobKind::Install | JobKind::Remove | JobKind::Update | JobKind::Switch + ) { + self.browse.details.clear(); + self.dirty = true; + } + // Whatever starts next was never named by an open abort confirm, + // so the confirm goes with the job it was opened for. + self.retire_abort_confirm(id); + let mut effects = self.after_job(kind, now); + if self.quit_when_idle + && self.running_job().is_none() + && !self.authorizing() + && self.queued_count() == 0 + { + self.quit = true; + self.dirty = true; + return effects; + } + effects.extend(self.start_next(now)); + if self.running_job().is_none() { + self.activity_until = Some(now + STRIP_LINGER); + } + effects + } + + /// The effects that reload the views the finished job changed. An + /// install changes which packages are marked installed, so the + /// catalog reloads and its installed markers move without a manual + /// reload. Every job that installs, removes, or replaces packages also + /// changes the installed list, so it reloads with the catalog. A sync + /// replaces the metadata databases on disk and a repository change + /// replaces the configuration, both of which the runner's context + /// caches, so the context is rebuilt before anything reads either and + /// the repositories reload from the fresh configuration. Jobs that + /// change what is installed also start a fresh update check + /// so the list and its count catch up, but only when the updates view + /// has loaded its list before, and an update job resets the list to + /// loading first because it took its entries out of it. An apply moves + /// the installation to what the packages file declares, so its plan + /// recomputes with the prune flag in force while the catalog and the + /// installed list reload. Jobs that fix + /// the installation reload the health view unconditionally, and the + /// install and removal jobs reload it once it has loaded its report. + fn after_job(&mut self, kind: JobKind, now: Instant) -> Vec { + let mut effects = match kind { + JobKind::Sync => { + self.repos.start(); + let mut effects = vec![ + Effect::RebuildContext, + self.catalog_effect(), + self.installed_effect(), + Effect::LoadRepos, + ]; + if !self.updates.list.is_idle() { + let check = self.check_effect(self.updates.scope.clone(), now); + effects.push(check); + } + effects + } + JobKind::Repo => { + self.repos.start(); + // A disabled or removed repository must leave the catalog + // with it, the same as an edited configuration. + vec![ + Effect::RebuildContext, + Effect::LoadRepos, + self.catalog_effect(), + self.installed_effect(), + ] + } + JobKind::Install => { + let mut effects = vec![self.catalog_effect(), self.installed_effect()]; + if !self.health.report.is_idle() { + self.health.start(); + effects.push(Effect::LoadHealth); + } + effects + } + JobKind::Remove | JobKind::Switch => { + let mut effects = vec![self.installed_effect()]; + if kind == JobKind::Remove && !self.health.report.is_idle() { + self.health.start(); + effects.push(Effect::LoadHealth); + } + effects + } + JobKind::Apply => { + let mut effects = vec![ + self.apply_effect(), + self.catalog_effect(), + self.installed_effect(), + ]; + if !self.health.report.is_idle() { + self.health.start(); + effects.push(Effect::LoadHealth); + } + effects + } + JobKind::ApplySystem => { + vec![self.apply_effect()] + } + JobKind::RemoveBrokenPackages => { + self.health.start(); + vec![self.installed_effect(), Effect::LoadHealth] + } + JobKind::CleanCache | JobKind::RemoveBrokenSymlinks => { + self.health.start(); + vec![Effect::LoadHealth] + } + JobKind::CreatePackagesConfig => { + vec![self.apply_effect()] + } + JobKind::Update => { + let check = self.check_effect(self.updates.scope.clone(), now); + vec![check, self.installed_effect(), self.catalog_effect()] + } + }; + if matches!( + kind, + JobKind::Install | JobKind::Remove | JobKind::Switch | JobKind::Apply + ) && !self.updates.list.is_idle() + { + let check = self.check_effect(self.updates.scope.clone(), now); + effects.push(check); + } + effects + } + + /// The effects to run when the interface starts: loading the package + /// catalog the first view shows, and the installed list the second + /// one shows. + pub(crate) fn startup(&mut self) -> Vec { + self.browse.catalog = Loadable::Loading; + self.installed.list = Loadable::Loading; + vec![self.catalog_effect(), self.installed_effect()] + } + + /// Applies one message and returns the work it asks for. + pub(crate) fn update(&mut self, msg: Msg, now: Instant) -> Vec { + self.now = now; + match msg { + Msg::Input(Event::Key(key)) if key.kind == KeyEventKind::Press => { + if self.overlay.is_some() { + self.on_overlay_key(key, now) + } else { + self.on_key(key, now) + } + } + Msg::Input(Event::Resize(..)) => { + self.dirty = true; + Vec::new() + } + Msg::Input(Event::Mouse(mouse)) => self.on_mouse(mouse, now), + Msg::Input(_) => Vec::new(), + Msg::Output(line) => { + let (level, text) = Log::parse_output(&line); + self.log.push(level, text.clone()); + if level == LogLevel::Error && self.running_job().is_none() { + self.toast(ToastKind::Error, text, now); + } + Vec::new() + } + Msg::Soar(event) => self.on_soar(event, now), + Msg::Loaded(Loaded::Catalog { + check, + result, + }) => { + // Two loads can overlap, as when a manual reload races + // the reload a repository change started, so a reply + // from a load a newer one replaced must not overwrite + // what the newer state already holds, whatever it found. + if check != self.catalog_load { + return Vec::new(); + } + let catalog_ok = result.is_ok(); + self.browse.catalog = match result { + Ok(rows) => Loadable::Ready(rows), + Err(error) => Loadable::Failed(error), + }; + self.browse.refilter(now); + self.dirty = true; + // The first catalog load quietly starts an update check so + // the header badge fills without a visit to the view. + if catalog_ok && self.updates.list.is_idle() { + return vec![self.check_effect(None, now)]; + } + Vec::new() + } + Msg::Loaded(Loaded::Installed { + check, + result, + }) => { + if check != self.installed_load { + return Vec::new(); + } + self.installed.list = match result { + Ok(listing) => Loadable::Ready(listing), + Err(error) => Loadable::Failed(error), + }; + self.installed.refilter(); + self.dirty = true; + Vec::new() + } + Msg::Loaded(Loaded::Updates { + check, + result, + }) => { + if check != self.updates.check { + return Vec::new(); + } + self.updates.loaded(result); + // A fresh list moves every row, so a confirm holding row + // indexes into the old one can no longer be trusted. + if self.update_pick.take().is_some() { + self.close_update_confirm(); + } + self.dirty = true; + Vec::new() + } + Msg::Loaded(Loaded::ApplyDiff { + check, + result, + }) => { + if check != self.apply.check { + return Vec::new(); + } + self.apply.loaded(result); + // The plan the confirm named is gone, so accepting it + // could queue removals the user never saw named. + if self.apply_pick.take().is_some() { + self.close_apply_confirm(); + self.toast( + ToastKind::Info, + "The plan changed, so the confirm closed", + now, + ); + } + self.dirty = true; + Vec::new() + } + Msg::Loaded(Loaded::Repos(result)) => { + self.repos.loaded(result); + self.dirty = true; + Vec::new() + } + Msg::Loaded(Loaded::Health(result)) => { + self.health.loaded(result); + self.dirty = true; + Vec::new() + } + Msg::Loaded(Loaded::Detail { + key, + result, + }) => { + let state = match *result { + Ok(package) => Loadable::Ready(package), + Err(error) => Loadable::Failed(error), + }; + self.browse.cache_detail(key, state); + self.dirty = true; + Vec::new() + } + Msg::Loaded(Loaded::Resolved { + choices, + result, + }) => { + match result { + Ok(resolutions) => self.on_resolved(choices, resolutions, now), + Err(error) => { + self.toast(ToastKind::Error, error, now); + Vec::new() + } + } + } + Msg::Loaded(Loaded::RunReady { + args, + result, + }) => { + match *result { + Ok(PrepareRunResult::Ready { + path, .. + }) => { + self.dirty = true; + vec![Effect::Suspend(Suspended::Exec { + path, + args, + })] + } + Ok(PrepareRunResult::Ambiguous(ambiguous)) => { + self.open_run_picker(ambiguous.query, ambiguous.candidates, args); + Vec::new() + } + Err(error) => { + self.toast(ToastKind::Error, error, now); + Vec::new() + } + } + } + Msg::Loaded(Loaded::Variants { + name, + result, + }) => self.on_variants_loaded(name, *result, now), + Msg::Loaded(Loaded::Escalation(probe)) => { + if self.authorizing_job().is_none() { + return Vec::new(); + } + match probe { + EscalationProbe::Ready => { + if let Some(job) = self.authorizing_job_mut() + && let Some(JobSpec::ApplySystem { + mode, .. + }) = job.spec.as_mut() + { + *mode = SystemMode::Direct; + } + self.start_authorizing(now) + } + EscalationProbe::Password => { + self.open_authorize(false); + Vec::new() + } + EscalationProbe::Terminal(tool) => { + self.open_system_terminal(tool); + Vec::new() + } + EscalationProbe::Unavailable(message) => { + let Some(job) = self.authorizing_job() else { + return Vec::new(); + }; + let id = job.id; + let title = job.title.clone(); + let outcome = JobOutcome { + ok: false, + aborted: false, + headline: format!("{title} failed"), + lines: vec![OutcomeLine::Failed { + name: title, + error: message, + }], + }; + self.on_job_finished(id, outcome, now) + } + } + } + Msg::Loaded(Loaded::Authenticated { + check, + result, + }) => { + let waiting = + matches!(&self.overlay, Some(Overlay::Authorize(dialog)) if dialog.is_busy()); + if !waiting || check != self.pass_check || self.authorizing_job().is_none() { + return Vec::new(); + } + match result { + Ok(()) => { + self.overlay = None; + if let Some(job) = self.authorizing_job_mut() + && let Some(JobSpec::ApplySystem { + mode, .. + }) = job.spec.as_mut() + { + *mode = SystemMode::Direct; + } + self.start_authorizing(now) + } + Err(error) => { + if let Some(dialog) = self.authorize_mut() { + dialog.fail(error); + } + Vec::new() + } + } + } + Msg::JobFinished { + id, + outcome, + } => self.on_job_finished(id, outcome, now), + Msg::Edited(path) => { + // Each edited file drives the views that read it; anything + // else just needs a repaint. + self.dirty = true; + if path == self.env.config_path { + vec![ + Effect::RebuildContext, + Effect::LoadRepos, + self.catalog_effect(), + self.installed_effect(), + ] + } else if path == self.env.packages_path { + vec![self.apply_effect()] + } else { + Vec::new() + } + } + Msg::InputFailed(error) => { + // The reader is gone and no key will ever arrive, so the + // interface quits and the entry point reports why. + self.fatal = Some(error); + self.quit = true; + self.dirty = true; + Vec::new() + } + Msg::Redraw => { + self.dirty = true; + Vec::new() + } + Msg::Tick => { + self.frame += 1; + if self.toasts.expire(now) { + self.dirty = true; + } + if self.running_job().is_some() || self.authorizing() { + self.dirty = true; + } else if self.activity_until.is_some_and(|until| until <= now) { + self.activity_until = None; + self.dirty = true; + } + let mut effects = Vec::new(); + if let Some(key) = self.browse.due_detail(now) + && let Some(version) = self.browse.row_version(&key) + { + effects.push(Effect::LoadDetail { + key, + version, + }); + } + effects + } + } + } + + /// Feeds one operation event into the running job's progress, or into + /// the background tracker when no job runs, so a download or a sync + /// started outside the queue still lands somewhere. Update checks are + /// the Updates view's data, and log lines belong in the log buffer, + /// which collects them later. + fn on_soar(&mut self, event: SoarEvent, now: Instant) -> Vec { + match event { + SoarEvent::UpdateCheck { + pkg_name, + status, + } => { + // The events carry no check number, so while a check and + // the one that replaced it run together the counters + // take strays from both. The load cannot tell them apart + // and drops the lot, but only when a replacement + // actually happened; otherwise the progress is the + // check's own and stays for the skipped view. + if self.updates.list.is_loading() { + self.updates.checked += 1; + if let UpdateCheckStatus::Skipped { + reason, + } = status + { + self.updates.skipped.push((pkg_name, reason)); + } + self.dirty = true; + } + } + SoarEvent::Log { + level, + message, + } => { + let level = match level { + EventLevel::Debug => LogLevel::Debug, + EventLevel::Info => LogLevel::Info, + EventLevel::Warning => LogLevel::Warn, + EventLevel::Error => LogLevel::Error, + }; + self.log.push(level, message.clone()); + if level == LogLevel::Error && self.running_job().is_none() { + self.toast(ToastKind::Error, message, now); + } + } + SoarEvent::ProcessOutput { + line, + pkg_name, + op_id, + } => { + let clean = Log::strip_ansi(&line); + self.log + .push(LogLevel::Info, format!("{pkg_name}: {clean}")); + self.feed_tracker( + &SoarEvent::ProcessOutput { + op_id, + pkg_name, + line, + }, + now, + ); + } + _ => self.feed_tracker(&event, now), + } + Vec::new() + } + + /// Hands one operation event to the running job's progress, or to the + /// background tracker when no job runs. + fn feed_tracker(&mut self, event: &SoarEvent, now: Instant) { + if let Some(job) = self.running_job_mut() { + job.tracker.apply(event, now); + } else { + self.background.apply(event, now); + } + self.dirty = true; + } + + /// Hands a pressed key to the open overlay. While one is open nothing + /// else in the interface reacts to keys. + fn on_overlay_key(&mut self, key: KeyEvent, now: Instant) -> Vec { + let Some(overlay) = self.overlay.take() else { + return Vec::new(); + }; + self.dirty = true; + match overlay.handle(key) { + OverlayOutcome::Stay(overlay) => { + self.overlay = Some(overlay); + Vec::new() + } + OverlayOutcome::Close => self.on_overlay_close(now), + OverlayOutcome::Accept(accept, value) => self.on_accept(accept, value, now), + OverlayOutcome::Authenticate(secret) => { + // The dialog goes back up in its waiting state, and the + // secret travels to the runner alone. + self.pass_check = self.pass_check.wrapping_add(1); + let check = self.pass_check; + self.open_authorize(true); + vec![Effect::Authenticate { + secret, + check, + }] + } + } + } + + /// Responds to an overlay closing without acting. While an install is + /// being arranged only the flow's own overlays can be open, so the + /// close means one step further: the variant picker drops the query it + /// was asking about, and the confirm cancels the whole install. The + /// same close drops what a run variant picker kept, ending that flow, + /// and what a switch variants picker kept. While a job waits for the + /// administrator authorization, a closed dialog is a declined one, so + /// the pass is skipped. + fn on_overlay_close(&mut self, now: Instant) -> Vec { + if self.authorizing() { + return self.skip_authorizing(now); + } + self.drop_overlay_state(); + let Some(mut pending) = self.pending.take() else { + return Vec::new(); + }; + if pending.ambiguous.pop_front().is_some() { + self.pending = Some(pending); + self.advance_pending(); + } + Vec::new() + } + + /// Carries out what an accepted overlay asked for. + fn on_accept(&mut self, accept: OnAccept, value: Option, now: Instant) -> Vec { + match accept { + OnAccept::QuitWait => { + self.wait_and_quit(now, false); + Vec::new() + } + OnAccept::QuitAbort => self.wait_and_quit(now, true), + OnAccept::QuitForce => { + self.quit = true; + self.dirty = true; + Vec::new() + } + OnAccept::Abort => self.abort_confirmed(now), + OnAccept::Remove(packages) => { + self.installed.marks.clear(); + self.dirty = true; + self.enqueue( + JobSpec::Remove { + packages, + }, + now, + ) + } + OnAccept::UpdateNow => self.update_now(now), + OnAccept::PickVariant => { + match value { + Some(Value::Index(index)) => { + self.pick_variant(index); + Vec::new() + } + _ => Vec::new(), + } + } + OnAccept::InstallNow => self.install_now(now), + OnAccept::InstallWithOptions => { + match value { + Some(Value::Form(FormValues(values))) => self.install_with_options(values, now), + _ => Vec::new(), + } + } + OnAccept::PickVersion => { + match value { + Some(Value::Index(index)) => self.install_picked_version(index, now), + _ => Vec::new(), + } + } + OnAccept::InstallByQuery => { + match value { + Some(Value::Text(text)) => self.install_by_query(text), + _ => Vec::new(), + } + } + OnAccept::RunArguments => { + match value { + Some(Value::Text(text)) => self.run_with_arguments(text), + _ => Vec::new(), + } + } + OnAccept::RunVariant => { + match value { + Some(Value::Index(index)) => self.run_picked_variant(index), + _ => Vec::new(), + } + } + OnAccept::SwitchVariant => { + match value { + Some(Value::Index(index)) => self.switch_picked_variant(index, now), + _ => Vec::new(), + } + } + OnAccept::SwitchConfirm { + id, + name, + } => { + self.enqueue( + JobSpec::Switch { + id, + name, + }, + now, + ) + } + OnAccept::RepoEnabled { + name, + enabled, + } => { + let mut effects = self.enqueue( + JobSpec::Repo(RepoChange::SetEnabled { + name: name.clone(), + enabled, + }), + now, + ); + if enabled { + effects.extend(self.enqueue(JobSpec::Sync, now)); + } + effects + } + OnAccept::RepoRemoved { + name, + } => self.enqueue(JobSpec::Repo(RepoChange::Remove(name)), now), + OnAccept::CleanCacheConfirm => self.enqueue(JobSpec::CleanCache, now), + OnAccept::FixSymlinksConfirm => self.enqueue(JobSpec::RemoveBrokenSymlinks, now), + OnAccept::RemoveBrokenConfirm => self.enqueue(JobSpec::RemoveBrokenPackages, now), + OnAccept::AddRepo => { + match value { + Some(Value::Form(FormValues(values))) => self.add_repo(values, now), + _ => Vec::new(), + } + } + OnAccept::ApplyPlan => self.apply_plan(now), + OnAccept::SystemTerminal { + tool, + } => self.run_system_terminal(tool, now), + #[cfg(test)] + OnAccept::Test => Vec::new(), + } + } + + /// Sets up the install the resolution described: resolved targets go + /// straight in, ambiguous queries queue for a picker, and the + /// not-found and already installed ones toast. Then the flow's first + /// step opens. + fn on_resolved( + &mut self, + choices: InstallChoices, + resolutions: Vec, + now: Instant, + ) -> Vec { + let mut pending = PendingInstall { + choices, + targets: Vec::new(), + picked: Vec::new(), + ambiguous: VecDeque::new(), + }; + for resolution in resolutions { + match resolution { + Resolution::Ready(targets) => pending.targets.extend(targets), + Resolution::Ambiguous { + query, + candidates, + } => pending.ambiguous.push_back((query, candidates)), + Resolution::NotFound { + query, + suggestions, + } => { + let text = if suggestions.is_empty() { + format!("Not found: {query}.") + } else { + let near = suggestions.join(", "); + format!("Not found: {query}. Did you mean {near}?") + }; + self.toast(ToastKind::Warning, text, now); + } + Resolution::AlreadyInstalled { + name, .. + } => { + self.toast(ToastKind::Info, format!("{name} is already installed"), now); + } + } + } + self.pending = Some(pending); + self.advance_pending(); + Vec::new() + } + + /// Opens the next step of the install being arranged: a picker for the + /// head ambiguous query, or the confirm listing everything to install + /// once every query is decided. The confirm clears the flow again + /// when nothing remains to install. While a pass is being authorized + /// the flow opens nowhere: the resolution may answer long after the + /// password dialog took the overlay slot, and stealing it back would + /// leave the pass with no dialog to serve, so the install waits for a + /// retry and the flow goes with the dropped resolution. + fn advance_pending(&mut self) { + if self.authorizing() { + self.pending = None; + return; + } + // The flow's overlay takes the slot from whatever else is open, + // so the state that overlay kept goes the way its own close + // path would drop it. + if self.overlay.is_some() && !matches!(self.overlay, Some(Overlay::Picker(_))) { + self.drop_overlay_state(); + } + let picker = self.pending.as_ref().and_then(|pending| { + let (query, candidates) = pending.ambiguous.front()?; + let rows = variant_rows(candidates); + Some((query.clone(), rows)) + }); + let Some((query, rows)) = picker else { + self.confirm_pending(); + return; + }; + self.overlay = Some(Overlay::Picker(Picker::new( + format!("Choose a variant of \"{query}\""), + rows, + OnAccept::PickVariant, + ))); + self.dirty = true; + } + + /// Opens the non-destructive confirm naming every package the pending + /// install sets up, with each download size and the total, and a + /// summary of the options that differ from a plain install. The flow + /// ends when nothing remains to install. + fn confirm_pending(&mut self) { + let nothing = self + .pending + .as_ref() + .is_none_or(|pending| pending.targets.is_empty() && pending.picked.is_empty()); + if nothing { + self.pending = None; + return; + } + let Some(pending) = self.pending.as_ref() else { + return; + }; + let mut lines: Vec> = Vec::new(); + for target in &pending.targets { + lines.push(package_line(&target.package)); + } + for package in &pending.picked { + lines.push(package_line(package)); + } + if let Some(options) = options_line(&pending.choices) { + lines.push(options); + } + let total: u64 = pending + .targets + .iter() + .map(|target| package_size(&target.package)) + .chain(pending.picked.iter().map(package_size)) + .sum(); + lines.push(Line::raw(format!("Download size: {}", format::size(total)))); + let count = pending.targets.len() + pending.picked.len(); + let title = match count { + 1 => { + let name = pending + .picked + .first() + .map(|p| p.pkg_name.as_str()) + .or_else(|| { + pending + .targets + .first() + .map(|target| target.package.pkg_name.as_str()) + }) + .unwrap_or("package"); + format!("Install {name}") + } + _ => format!("Install {count} packages"), + }; + self.overlay = Some(Overlay::Confirm(Confirm::new( + title, + lines, + "Install", + false, + OnAccept::InstallNow, + ))); + self.dirty = true; + } + + /// Records the variant the user chose for the head ambiguous query, + /// then moves on to the next step of the flow. + fn pick_variant(&mut self, index: usize) { + let Some(mut pending) = self.pending.take() else { + return; + }; + if let Some((_, candidates)) = pending.ambiguous.pop_front() + && let Some(package) = candidates.into_iter().nth(index) + { + pending.picked.push(package); + } + self.pending = Some(pending); + self.advance_pending(); + } + + /// Queues the install the confirm accepted, with the marks that + /// started it cleared. + fn install_now(&mut self, now: Instant) -> Vec { + let Some(pending) = self.pending.take() else { + return Vec::new(); + }; + self.browse.marks.clear(); + self.dirty = true; + self.enqueue( + JobSpec::Install { + targets: pending.targets, + picked: pending.picked, + options: pending.choices, + }, + now, + ) + } + + /// Starts the install flow for `(key, version)` pairs: rows already + /// installed are reported and skipped unless a reinstall was asked + /// for, and the rest resolves into install targets. Each query pins + /// the exact variant its catalog row shows. + fn install_versions( + &mut self, + versions: Vec<(PackageKey, String)>, + choices: InstallChoices, + now: Instant, + ) -> Vec { + let mut queries = Vec::new(); + let mut installed = Vec::new(); + for (key, version) in versions { + let Some(row) = self.browse.row(&key) else { + // The catalog reloaded while an overlay was open and the + // row is gone: the query still resolves, and the + // resolution itself reports an installed package. + queries.push(key.query(&version)); + continue; + }; + if row.installed && !choices.force { + installed.push(row.key.pkg_name.clone()); + } else { + queries.push(key.query(&version)); + } + } + let message = match installed.as_slice() { + [] => None, + [one] => { + Some(format!( + "{one} is already installed. Use I and Force reinstall to reinstall." + )) + } + many => { + let count = many.len(); + Some(format!( + "{count} packages are already installed. Use I and Force reinstall to reinstall." + )) + } + }; + if let Some(message) = message { + self.toast(ToastKind::Info, message, now); + } + if queries.is_empty() { + return Vec::new(); + } + vec![Effect::Resolve { + queries, + choices, + }] + } + + /// Opens the install options dialog over the selected rows, marks or + /// the cursor row. The rows are read again when the form is accepted. + fn open_install_options(&mut self) { + let keys = self.browse.selected_keys(); + let Some(first) = keys.first() else { + return; + }; + let title = if keys.len() == 1 { + let name = &first.pkg_name; + format!("Install {name} with options") + } else { + let count = keys.len(); + format!("Install {count} packages with options") + }; + let fields = vec![ + Field::Check { + label: "Force reinstall", + checked: false, + }, + Field::Check { + label: "Binary only", + checked: false, + }, + Field::Check { + label: "Skip checksum verification", + checked: false, + }, + Field::Check { + label: "Portable", + checked: false, + }, + Field::Text { + label: "Portable path", + input: TextInput::default(), + }, + ]; + self.overlay = Some(Overlay::Form(Form::new( + title, + fields, + "Install", + OnAccept::InstallWithOptions, + ))); + self.dirty = true; + } + + /// Builds the install choices out of the accepted options form and + /// starts the flow for the selected rows. Force keeps already + /// installed rows in, asking for a reinstall. An empty portable path + /// means the default portable location. + fn install_with_options(&mut self, values: Vec, now: Instant) -> Vec { + let mut choices = InstallChoices::default(); + let mut portable = false; + let mut portable_path = String::new(); + for (position, value) in values.into_iter().enumerate() { + match (position, value) { + (0, FieldValue::Check(force)) => choices.force = force, + (1, FieldValue::Check(binary_only)) => choices.binary_only = binary_only, + (2, FieldValue::Check(no_verify)) => choices.no_verify = no_verify, + (3, FieldValue::Check(on)) => portable = on, + (4, FieldValue::Text(path)) => portable_path = path, + _ => {} + } + } + if portable { + choices.portable = Some(portable_path); + } + let versions = self.browse.selected_versions(); + self.install_versions(versions, choices, now) + } + + /// Opens the version picker for the row under the cursor, the + /// catalog's newest version first and the repository's older ones + /// after it. + fn open_version_picker(&mut self, now: Instant) { + let Some(row) = self.browse.cursor_row() else { + return; + }; + if row.other_versions.is_empty() { + let name = row.key.pkg_name.clone(); + self.toast(ToastKind::Info, format!("{name} has only one version"), now); + return; + } + self.version_pick = Some(( + row.key.clone(), + row.version.clone(), + row.other_versions.clone(), + )); + let muted = self.theme.muted(); + let mut rows = vec![Line::from(vec![ + Span::raw(format!("{} ", row.version)), + Span::styled("latest", muted), + ])]; + rows.extend( + row.other_versions + .iter() + .map(|version| Line::raw(version.clone())), + ); + let name = &row.key.pkg_name; + self.overlay = Some(Overlay::Picker(Picker::new( + format!("Versions of {name}"), + rows, + OnAccept::PickVersion, + ))); + self.dirty = true; + } + + /// Starts the install flow for the row under the cursor at the version + /// the user picked: the first entry is the catalog's newest, the rest + /// follow the row's other versions. + fn install_picked_version(&mut self, index: usize, now: Instant) -> Vec { + let Some((key, latest, others)) = self.version_pick.take() else { + return Vec::new(); + }; + let version = if index == 0 { + latest + } else { + let Some(version) = others.get(index - 1) else { + return Vec::new(); + }; + version.clone() + }; + self.install_versions(vec![(key, version)], InstallChoices::default(), now) + } + + /// Starts the install flow for the queries the prompt collected, split + /// on whitespace. Nothing is checked against the catalog here: the + /// resolution reports already installed packages itself. + fn install_by_query(&mut self, text: String) -> Vec { + let queries: Vec = text.split_whitespace().map(String::from).collect(); + if queries.is_empty() { + return Vec::new(); + } + vec![Effect::Resolve { + queries, + choices: InstallChoices::default(), + }] + } + + /// Opens the run prompt for the row under the cursor. Its text splits + /// on whitespace with no shell parsing, and an empty text runs the + /// package without arguments. + fn open_run_prompt(&mut self) { + let Some(row) = self.browse.cursor_row() else { + return; + }; + let query = match row.key.pkg_family.as_deref() { + Some(family) => format!("{family}/{}:{}", row.key.pkg_name, row.key.repo_name), + None => format!("{}:{}", row.key.pkg_name, row.key.repo_name), + }; + self.run_args = Some(( + query, + Some(row.key.repo_name.clone()), + row.key.pkg_id.clone(), + )); + let name = &row.key.pkg_name; + self.overlay = Some(Overlay::Prompt( + Prompt::new(format!("Run {name} with arguments"), OnAccept::RunArguments).allow_empty(), + )); + self.dirty = true; + } + + /// Opens the danger confirm naming the rows the removal takes: the + /// marked rows, or the row under the cursor. Each line shows the size + /// on disk the removal frees, and the records travel inside the + /// accept action until the confirm is accepted. An empty selection + /// opens nothing. + fn open_remove_confirm(&mut self) { + let entries = self.installed.selected_entries(); + if entries.is_empty() { + return; + } + let mut lines: Vec> = entries.iter().map(installed_package_line).collect(); + let total: u64 = entries.iter().map(|entry| entry.disk_size).sum(); + lines.push(Line::raw(format!("{} will be freed.", format::size(total)))); + let packages: Vec = + entries.into_iter().map(|entry| entry.package).collect(); + let title = match packages.as_slice() { + [one] => format!("Remove {}", one.pkg_name), + many => format!("Remove {} packages", many.len()), + }; + self.overlay = Some(Overlay::Confirm(Confirm::new( + title, + lines, + "Remove", + true, + OnAccept::Remove(packages), + ))); + self.dirty = true; + } + + /// Starts the switch flow for the row under the cursor: the + /// installed variants of the row's package name load in the + /// background, and the flow's step opens once they arrive. + fn open_switch_flow(&mut self) -> Vec { + let Some(entry) = self.installed.cursor_entry() else { + return Vec::new(); + }; + let name = entry.package.pkg_name.clone(); + vec![Effect::LoadVariants { + name, + }] + } + + /// Opens the step the loaded variants ask for: an info toast when + /// the package is not installed or has no other variant, a confirm + /// for a sole inactive one, and a picker when several are + /// installed. A failed load toasts the error. + fn on_variants_loaded( + &mut self, + name: String, + result: Result, String>, + now: Instant, + ) -> Vec { + let variants = match result { + Ok(variants) => variants, + Err(error) => { + self.toast(ToastKind::Error, error, now); + return Vec::new(); + } + }; + // The load may answer long after the password dialog took the + // overlay slot, so no step of the switch may open while a pass + // is being authorized, and the flow waits for a retry instead. + if self.authorizing() { + self.toast( + ToastKind::Info, + "A pass is being authorized, so the switch waits. Try again once it finishes.", + now, + ); + return Vec::new(); + } + match variants.as_slice() { + [] => { + self.toast(ToastKind::Info, format!("{name} is not installed"), now); + Vec::new() + } + [only] if only.is_active => { + self.toast( + ToastKind::Info, + format!("{name} has no other variants"), + now, + ); + Vec::new() + } + [only] => self.confirm_switch(name, only), + _ => { + self.open_variant_picker(name, variants); + Vec::new() + } + } + } + + /// Opens the non-destructive confirm naming the sole inactive + /// variant the switch links, noting that the active variant of the + /// package moves to it. + fn confirm_switch(&mut self, name: String, variant: &VariantInfo) -> Vec { + // The confirm takes the overlay slot from whatever else is + // open, so the state that overlay kept goes the way its own + // close path would drop it. + if self.overlay.is_some() && !matches!(self.overlay, Some(Overlay::Confirm(_))) { + self.drop_overlay_state(); + } + let package = &variant.package; + let target = match package.pkg_family.as_deref() { + Some(family) => format!("{family}/{}", package.pkg_name), + None => package.pkg_name.clone(), + }; + let body = vec![ + Line::raw(format!( + "{target} {} {}", + package.version, package.repo_name + )), + Line::raw(format!("The active variant of {name} changes to this one.")), + ]; + self.overlay = Some(Overlay::Confirm(Confirm::new( + format!("Switch {} to {}", name, package.version), + body, + "Switch", + false, + OnAccept::SwitchConfirm { + id: package.id, + name, + }, + ))); + self.dirty = true; + Vec::new() + } + + /// Opens the confirm that turns the cursor repository on or off. + /// Disabling explains what leaves Browse; enabling explains that a + /// sync brings its packages in, and accepting one queues the sync + /// right after the change. + fn open_repo_enabled_confirm(&mut self) { + let Some(repo) = self.repos.cursor_row() else { + return; + }; + let name = repo.name.clone(); + let (title, body, label, enabled) = if repo.enabled { + ( + format!("Disable {name}"), + "Its packages will no longer appear in Browse. Installed packages stay installed.", + "Disable", + false, + ) + } else { + ( + format!("Enable {name}"), + "Its packages will appear in Browse after the next sync.", + "Enable", + true, + ) + }; + self.overlay = Some(Overlay::Confirm(Confirm::new( + title, + vec![Line::raw(body)], + label, + false, + OnAccept::RepoEnabled { + name, + enabled, + }, + ))); + self.dirty = true; + } + + /// Opens the danger confirm that removes the cursor repository from + /// the config file, noting that installed packages stay installed. + fn open_repo_removed_confirm(&mut self) { + let Some(repo) = self.repos.cursor_row() else { + return; + }; + let name = repo.name.clone(); + self.overlay = Some(Overlay::Confirm(Confirm::new( + format!("Remove {name}"), + vec![Line::raw( + "This edits config.toml. Installed packages stay installed.", + )], + "Remove", + true, + OnAccept::RepoRemoved { + name, + }, + ))); + self.dirty = true; + } + + /// Opens the form that adds a repository: a name and a URL the form + /// insists on, an optional public key and sync interval, and two + /// toggles that start switched on. + fn open_add_repo_form(&mut self) { + let fields = vec![ + Field::RequiredText { + label: "Name", + input: TextInput::default(), + }, + Field::RequiredText { + label: "URL", + input: TextInput::default(), + }, + Field::Text { + label: "Public key", + input: TextInput::default(), + }, + Field::Check { + label: "Enabled", + checked: true, + }, + Field::Check { + label: "Desktop integration", + checked: true, + }, + Field::Text { + label: "Sync interval", + input: TextInput::default(), + }, + ]; + self.overlay = Some(Overlay::Form(Form::new( + "Add repository", + fields, + "Add", + OnAccept::AddRepo, + ))); + self.dirty = true; + } + + /// Queues the addition of the repository the form collected, followed + /// by a sync that brings its packages into Browse. Every text value is + /// trimmed, an empty public key leaves signature verification to + /// soar's own rule, and an empty sync interval keeps the default. + fn add_repo(&mut self, values: Vec, now: Instant) -> Vec { + let mut name = String::new(); + let mut url = String::new(); + let mut pubkey = String::new(); + let mut interval = String::new(); + let mut enabled = true; + let mut desktop = true; + for (position, value) in values.into_iter().enumerate() { + match (position, value) { + (0, FieldValue::Text(value)) => name = value, + (1, FieldValue::Text(value)) => url = value, + (2, FieldValue::Text(value)) => pubkey = value, + (3, FieldValue::Check(on)) => enabled = on, + (4, FieldValue::Check(on)) => desktop = on, + (5, FieldValue::Text(value)) => interval = value, + _ => {} + } + } + let key = pubkey.trim(); + let interval = interval.trim(); + let repository = Repository { + name: name.trim().to_string(), + url: url.trim().to_string(), + pubkey: (!key.is_empty()).then(|| key.to_string()), + enabled: Some(enabled), + desktop_integration: Some(desktop), + signature_verification: None, + sync_interval: (!interval.is_empty()).then(|| interval.to_string()), + }; + let mut effects = self.enqueue(JobSpec::Repo(RepoChange::Add(repository)), now); + effects.extend(self.enqueue(JobSpec::Sync, now)); + effects + } + + /// Opens the picker over the installed variants, the active one + /// marked. The variants stay in the state until one is picked or + /// the picker closes. While a pass is being authorized the picker + /// opens nowhere: the load may answer long after the password dialog + /// took the overlay slot, and stealing it back would leave the pass + /// with no dialog to serve, so the switch waits for a retry instead. + fn open_variant_picker(&mut self, name: String, variants: Vec) { + if self.authorizing() { + return; + } + // The picker takes the overlay slot from whatever else is open, + // so the state that overlay kept goes the way its own close + // path would drop it. + if self.overlay.is_some() && !matches!(self.overlay, Some(Overlay::Picker(_))) { + self.drop_overlay_state(); + } + let rows = variant_pick_rows(&variants, &self.theme); + self.variant_pick = Some((name.clone(), variants)); + self.overlay = Some(Overlay::Picker(Picker::new( + format!("Variants of {name}"), + rows, + OnAccept::SwitchVariant, + ))); + self.dirty = true; + } + + /// Links the variant the variants picker chose, when it is not the + /// active one already. Choosing the active one only closes the + /// flow. + fn switch_picked_variant(&mut self, index: usize, now: Instant) -> Vec { + let Some((name, variants)) = self.variant_pick.take() else { + return Vec::new(); + }; + let Some(variant) = variants.into_iter().nth(index) else { + return Vec::new(); + }; + if variant.is_active { + return Vec::new(); + } + let id = variant.package.id; + self.enqueue( + JobSpec::Switch { + id, + name, + }, + now, + ) + } + + /// Opens the non-destructive confirm naming the updates to apply: the + /// marked rows, or every row when none are marked. Each line shows + /// the package moving from its current to its new version, and the + /// keep-old choice appears when it is on. An empty list only toasts. + /// The selected indexes stay in the state until the confirm is + /// accepted, so closing it leaves the list untouched. + fn open_update_confirm(&mut self, now: Instant) { + let Some(list) = self.updates.list.ready() else { + self.toast(ToastKind::Info, "Nothing to update", now); + return; + }; + if list.is_empty() { + self.toast(ToastKind::Info, "Nothing to update", now); + return; + } + let indexes: Vec = if self.updates.marks.is_empty() { + (0..list.len()).collect() + } else { + let mut marks: Vec = self.updates.marks.iter().copied().collect(); + marks.sort_unstable(); + marks + }; + let arrow = self.theme.sym().arrow; + let mut lines: Vec> = indexes + .iter() + .map(|&index| { + let info = &list[index]; + Line::raw(format!( + "{} {} {arrow} {}", + info.pkg_name, info.current_version, info.new_version + )) + }) + .collect(); + if self.updates.keep_old { + lines.push(Line::raw("Keep old versions: yes")); + } + let title = match indexes.as_slice() { + [one] => format!("Update {}", list[*one].pkg_name), + many => format!("Update {} packages", many.len()), + }; + self.update_pick = Some(indexes); + self.overlay = Some(Overlay::Confirm(Confirm::new( + title, + lines, + "Update", + false, + OnAccept::UpdateNow, + ))); + self.dirty = true; + } + + /// Queues the updates the confirm accepted: the selected entries move + /// out of the ready list in its order, the list drops to loading + /// because it is now missing them, and the marks clear. The fresh + /// check the job's end starts refills the list. While a recheck has + /// the list loading, the indexes no longer point anywhere, so the + /// acceptance says so instead of updating nothing. + fn update_now(&mut self, now: Instant) -> Vec { + let Some(indexes) = self.update_pick.take() else { + return Vec::new(); + }; + let marked: HashSet = indexes.into_iter().collect(); + let Loadable::Ready(list) = &mut self.updates.list else { + self.toast( + ToastKind::Info, + "The update list is being rechecked; try again once it finishes", + now, + ); + return Vec::new(); + }; + let (chosen, _rest): (Vec<_>, Vec<_>) = std::mem::take(list) + .into_iter() + .enumerate() + .partition(|(index, _)| marked.contains(index)); + let updates = chosen.into_iter().map(|(_, info)| info).collect(); + self.updates.list = Loadable::Loading; + self.updates.marks.clear(); + self.dirty = true; + self.enqueue( + JobSpec::Update { + updates, + keep_old: self.updates.keep_old, + }, + now, + ) + } + + /// Opens the confirm that applies the loaded plan, naming how much of + /// it installs, updates, and removes, every removal by name, and what + /// waits for the system pass. Danger when anything would be removed. + /// A plan with nothing to do only notes it, and one that has not + /// loaded opens nothing. + fn open_apply_confirm(&mut self, now: Instant) { + let Some(plan) = self.apply.plan.ready() else { + return; + }; + let Some(diff) = plan.diff.as_ref() else { + return; + }; + if !diff.has_changes() && !diff.has_toml_updates() && plan.system.is_empty() { + self.toast(ToastKind::Info, "Nothing to apply", now); + return; + } + let mut lines: Vec> = Vec::new(); + let install = diff.to_install.len(); + if install > 0 { + lines.push(Line::raw(format!("Install {install}"))); + } + let update = diff.to_update.len(); + if update > 0 { + lines.push(Line::raw(format!("Update {update}"))); + } + let remove = diff.to_remove.len(); + if remove > 0 { + lines.push(Line::raw(format!("Remove {remove}"))); + for package in &diff.to_remove { + lines.push(Line::raw(package.pkg_name.clone())); + } + } + if !plan.system.is_empty() { + lines.push(Line::raw(format!( + "System {} (asks for administrator rights)", + plan.system.len() + ))); + } + // The confirm names this plan, so a fresh computation landing + // under it can be told apart from the one the user accepted. + self.apply_pick = Some(self.apply.check); + self.overlay = Some(Overlay::Confirm(Confirm::new( + "Apply packages.toml", + lines, + "Apply", + remove > 0, + OnAccept::ApplyPlan, + ))); + self.dirty = true; + } + + /// Queues the apply the confirm accepted. The diff moves out of the + /// plan into the job when it still changes something, and the plan + /// drops to loading so it recomputes once the installation changed. + /// The packages marked `system = true` follow in their own job, + /// applied through the administrator pass. + fn apply_plan(&mut self, now: Instant) -> Vec { + self.apply_pick = None; + let Some(plan) = self.apply.plan.ready_mut() else { + return Vec::new(); + }; + let system = std::mem::take(&mut plan.system); + let packages_path = plan.path.to_string_lossy().into_owned(); + let diff = plan + .diff + .take() + .filter(|diff| diff.has_changes() || diff.has_toml_updates()); + self.apply.start(); + self.dirty = true; + let mut effects = match diff { + Some(diff) => { + self.enqueue( + JobSpec::Apply { + diff, + packages_path: packages_path.clone(), + }, + now, + ) + } + None => Vec::new(), + }; + if !system.is_empty() { + effects.extend(self.enqueue( + JobSpec::ApplySystem { + names: system, + packages_path, + mode: SystemMode::Pending, + }, + now, + )); + } + effects + } + + /// Opens the confirm that hands the terminal to doas for the system + /// pass, since only doas itself can ask for its password. + fn open_system_terminal(&mut self, tool: EscalationTool) { + // The confirm takes the overlay slot from whatever else is + // open, so the state that overlay kept goes the way its own + // close path would drop it. + if self.overlay.is_some() && !matches!(self.overlay, Some(Overlay::Confirm(_))) { + self.drop_overlay_state(); + } + let mut body: Vec> = Vec::new(); + for row in format::wrap( + "doas will ask for your password in the terminal. soar pauses until it finishes.", + 56, + ) { + body.push(Line::raw(row)); + } + self.overlay = Some(Overlay::Confirm(Confirm::new( + "Administrator rights needed", + body, + "Continue", + false, + OnAccept::SystemTerminal { + tool, + }, + ))); + self.dirty = true; + } + + /// Starts the system pass with the terminal handed over: the job is + /// running while the interface is suspended, and the runner reports + /// the outcome when the pass is over. + fn run_system_terminal(&mut self, tool: EscalationTool, now: Instant) -> Vec { + let Some(job) = self.authorizing_job_mut() else { + return Vec::new(); + }; + let JobState::Authorizing = job.state else { + return Vec::new(); + }; + if let Some(JobSpec::ApplySystem { + mode, .. + }) = job.spec.as_mut() + { + *mode = SystemMode::Terminal; + } + let id = job.id; + let spec = job.spec.take(); + job.state = JobState::Running { + started: now, + aborting: false, + }; + self.dirty = true; + match spec { + Some(JobSpec::ApplySystem { + packages_path, + names, + .. + }) => { + vec![Effect::Suspend(Suspended::SystemPass { + id, + tool, + packages_path, + names, + })] + } + _ => Vec::new(), + } + } + + /// Opens the non-destructive confirm naming the cache directory the + /// clean empties, with the path taken from the loaded paths list. + /// While the report is not loaded nothing opens, since there would be + /// no path to name. + fn open_clean_cache_confirm(&mut self) { + let Some(cache) = self.health.report.ready().and_then(|(_, paths)| { + paths + .iter() + .find(|(label, _)| label == "Cache") + .map(|(_, path)| path.clone()) + }) else { + return; + }; + self.overlay = Some(Overlay::Confirm(Confirm::new( + "Clean cache", + vec![Line::raw(format::home_relative(&cache))], + "Clean", + false, + OnAccept::CleanCacheConfirm, + ))); + self.dirty = true; + } + + /// Opens the danger confirm listing the broken symlinks the fix + /// removes, the first ten with the rest folded into a count. Nothing + /// broken only leaves a note, and a report that has not loaded opens + /// nothing. + fn open_fix_symlinks_confirm(&mut self, now: Instant) { + let Some(symlinks) = self + .health + .report + .ready() + .map(|(report, _)| &report.broken_symlinks) + else { + return; + }; + if symlinks.is_empty() { + self.toast(ToastKind::Info, "No broken symlinks", now); + return; + } + let rows: Vec = symlinks + .iter() + .take(CONFIRM_ROWS) + .map(|path| path.display().to_string()) + .collect(); + let count = symlinks.len(); + let title = if count == 1 { + "Remove 1 broken symlink".to_string() + } else { + format!("Remove {count} broken symlinks") + }; + self.open_health_fix_confirm(title, rows, count, OnAccept::FixSymlinksConfirm); + } + + /// Opens the danger confirm naming each broken package and its + /// install path, the first ten with the rest folded into a count. + /// Nothing broken only leaves a note, and a report that has not + /// loaded opens nothing. + fn open_remove_broken_confirm(&mut self, now: Instant) { + let Some(broken) = self + .health + .report + .ready() + .map(|(report, _)| &report.broken_packages) + else { + return; + }; + if broken.is_empty() { + self.toast(ToastKind::Info, "No broken packages", now); + return; + } + let rows: Vec = broken + .iter() + .take(CONFIRM_ROWS) + .map(|package| format!("{} {}", package.pkg_name, package.installed_path)) + .collect(); + let count = broken.len(); + let title = if count == 1 { + "Remove 1 broken package".to_string() + } else { + format!("Remove {count} broken packages") + }; + self.open_health_fix_confirm(title, rows, count, OnAccept::RemoveBrokenConfirm); + } + + /// Opens the danger confirm carrying the rows a health fix names, + /// with the rows past the tenth folded into a muted count. + fn open_health_fix_confirm( + &mut self, + title: String, + rows: Vec, + total: usize, + accept: OnAccept, + ) { + let mut lines: Vec> = rows.into_iter().map(Line::raw).collect(); + let hidden = total.saturating_sub(CONFIRM_ROWS); + if hidden > 0 { + lines.push(Line::styled( + format!("{} and {hidden} more", self.theme.sym().ellipsis), + self.theme.muted(), + )); + } + self.overlay = Some(Overlay::Confirm(Confirm::new( + title, lines, "Remove", true, accept, + ))); + self.dirty = true; + } + + /// Prepares the run of the row under the cursor with the arguments + /// the prompt collected. The query names the row's package without + /// pinning its version, so the newest variant runs and an ambiguity + /// still gets to ask. + fn run_with_arguments(&mut self, text: String) -> Vec { + let Some((query, repo, pkg_id)) = self.run_args.take() else { + return Vec::new(); + }; + let args: Vec = text.split_whitespace().map(String::from).collect(); + vec![Effect::PrepareRun { + query, + repo, + pkg_id, + args, + }] + } + + /// Opens the picker asking which variant of an ambiguous query to + /// run, keeping the arguments and the candidates until one is picked. + /// While a pass is being authorized the picker opens nowhere: the + /// preparation may answer long after the password dialog took the + /// overlay slot, and stealing it back would leave the pass with no + /// dialog to serve, so the run waits for a retry instead. + fn open_run_picker(&mut self, query: String, candidates: Vec, args: Vec) { + if self.authorizing() { + return; + } + // The picker takes the overlay slot from whatever else is open, + // so the state that overlay kept goes the way its own close + // path would drop it. + if self.overlay.is_some() && !matches!(self.overlay, Some(Overlay::Picker(_))) { + self.drop_overlay_state(); + } + let rows = variant_rows(&candidates); + self.run_pick = Some((args, candidates)); + self.overlay = Some(Overlay::Picker(Picker::new( + format!("Choose a variant of \"{query}\""), + rows, + OnAccept::RunVariant, + ))); + self.dirty = true; + } + + /// Prepares the run again for the exact variant the picker chose, + /// pinning its version and package id so it cannot turn ambiguous + /// again. + fn run_picked_variant(&mut self, index: usize) -> Vec { + let Some((args, candidates)) = self.run_pick.take() else { + return Vec::new(); + }; + let Some(package) = candidates.into_iter().nth(index) else { + return Vec::new(); + }; + vec![Effect::PrepareRun { + query: variant_query(&package), + repo: Some(package.repo_name.clone()), + pkg_id: package.pkg_id.clone(), + args, + }] + } + + /// Drops every queued job and quits once the running one finishes. With + /// `stop_running`, the running job is asked to stop first, unless it + /// has no safe stop point: a sync and the system pass, which runs as + /// root in another process the interface cannot stop. When nothing + /// runs or queues anymore, the only job was waiting for its pass, so + /// withdrawing it is the quit: the dialog goes with the job and the + /// interface leaves at once, since no finished job remains to consume + /// the wait. + fn wait_and_quit(&mut self, now: Instant, stop_running: bool) -> Vec { + self.jobs + .list + .retain(|job| !matches!(job.state, JobState::Queued | JobState::Authorizing)); + self.quit_when_idle = true; + self.dirty = true; + if self.running_job().is_none() && self.queued_count() == 0 { + self.overlay = None; + self.quit = true; + return Vec::new(); + } + self.toast( + ToastKind::Info, + "Quitting after the current job finishes", + now, + ); + if stop_running + && self + .running_job() + .is_some_and(|job| !matches!(job.kind, JobKind::Sync | JobKind::ApplySystem)) + { + return self.abort_running(); + } + Vec::new() + } + + /// Marks the running job as asked to stop and returns the effect that + /// cancels its token. A job already stopping is left alone. + fn abort_running(&mut self) -> Vec { + let Some(job) = self.running_job_mut() else { + return Vec::new(); + }; + let JobState::Running { + aborting, .. + } = &mut job.state + else { + return Vec::new(); + }; + if *aborting { + return Vec::new(); + } + *aborting = true; + self.dirty = true; + vec![Effect::AbortJob] + } + + /// Stops the job the abort confirm was opened for, if it still runs. + /// The confirm names the job running when it opened, and another job + /// may have taken its place by the time the answer comes, so only the + /// named one may be stopped. A job that finished meanwhile only gets + /// a note, and nothing is cancelled. + fn abort_confirmed(&mut self, now: Instant) -> Vec { + let Some(id) = self.abort_pick.take() else { + return Vec::new(); + }; + if self.running_job().is_some_and(|job| job.id == id) { + return self.abort_running(); + } + let title = self + .jobs + .list + .iter() + .find(|job| job.id == id) + .map(|job| job.title.clone()); + let note = match title { + Some(title) => format!("{title} already finished"), + None => "That job already finished".to_string(), + }; + self.toast(ToastKind::Info, note, now); + Vec::new() + } + + /// Retires an open abort confirm whose job just finished, mirroring + /// how a fresh update check retires the update confirm: whatever + /// runs next was never named by it, so it must not stay open. + fn retire_abort_confirm(&mut self, id: JobId) { + if self.abort_pick != Some(id) { + return; + } + self.abort_pick = None; + if let Some(Overlay::Confirm(confirm)) = &self.overlay + && matches!(confirm.action(), OnAccept::Abort) + { + self.overlay = None; + } + } + + /// Asks to stop the running job. Nothing running says so, a sync has + /// no safe stop point, the system pass runs as root in another + /// process the interface cannot stop cleanly, and a job already + /// stopping is left alone. Anything else opens the confirm naming + /// what an abort keeps. + fn request_abort(&mut self, now: Instant) { + let Some(job) = self.running_job() else { + self.toast(ToastKind::Info, "Nothing is running", now); + return; + }; + if job.kind == JobKind::Sync { + self.toast(ToastKind::Warning, "Sync cannot be aborted", now); + return; + } + if job.kind == JobKind::ApplySystem { + self.toast(ToastKind::Info, "System apply cannot be aborted", now); + return; + } + if matches!( + job.state, + JobState::Running { + aborting: true, + .. + } + ) { + return; + } + let title = job.title.clone(); + self.abort_pick = Some(job.id); + self.overlay = Some(Overlay::Confirm(Confirm::new( + format!("Abort {title}?"), + vec![ + Line::raw("Packages that already finished stay installed."), + Line::raw("Downloads in progress are kept and resume next time."), + ], + "Abort", + true, + OnAccept::Abort, + ))); + self.dirty = true; + } + + /// Finds what a pressed key means and carries its action out. While a + /// view's filter holds focus, the keys go to it first: Enter keeps the + /// text and returns focus to the list, Esc clears the text and returns + /// focus, and the keys it does not use, such as the arrows, reach the + /// view. + fn on_key(&mut self, key: KeyEvent, now: Instant) -> Vec { + if self.view == ViewId::Browse && self.browse.filter_focused { + return self.on_filter_key(key, now); + } + if self.view == ViewId::Installed && self.installed.filter_focused { + return self.on_installed_filter_key(key, now); + } + if let Some(action) = keymap::lookup(self.view, key) { + return self.on_action(action, now); + } + Vec::new() + } + + /// Feeds one pressed key to the catalog filter while it holds focus, + /// rebuilding the visible rows on every change, then lets the keys the + /// input does not use move the cursor or act on the view. + fn on_filter_key(&mut self, key: KeyEvent, now: Instant) -> Vec { + match key.code { + KeyCode::Enter => { + self.browse.filter_focused = false; + self.dirty = true; + return Vec::new(); + } + KeyCode::Esc => { + self.browse.filter.clear(); + self.browse.filter_focused = false; + self.browse.refilter(now); + self.dirty = true; + return Vec::new(); + } + _ => {} + } + if self.browse.filter.handle(key) { + self.browse.refilter(now); + self.dirty = true; + return Vec::new(); + } + if let Some(action) = keymap::lookup(self.view, key) { + return self.on_action(action, now); + } + Vec::new() + } + + /// Feeds one pressed key to the installed list's filter while it holds + /// focus, rebuilding the visible rows on every change, then lets the + /// keys the input does not use move the cursor or act on the view. + fn on_installed_filter_key(&mut self, key: KeyEvent, now: Instant) -> Vec { + match key.code { + KeyCode::Enter => { + self.installed.filter_focused = false; + self.dirty = true; + return Vec::new(); + } + KeyCode::Esc => { + self.installed.filter.clear(); + self.installed.filter_focused = false; + self.installed.refilter(); + self.dirty = true; + return Vec::new(); + } + _ => {} + } + if self.installed.filter.handle(key) { + self.installed.refilter(); + self.dirty = true; + return Vec::new(); + } + if let Some(action) = keymap::lookup(self.view, key) { + return self.on_action(action, now); + } + Vec::new() + } + + /// Handles one pointer event. The wheel scrolls the list under the + /// pointer and a left click switches tabs or moves the list cursor; + /// with an overlay open only a left click outside a confirm or picker + /// does anything, closing it the way esc does. + fn on_mouse(&mut self, mouse: MouseEvent, now: Instant) -> Vec { + if self.overlay.is_some() { + return self.on_overlay_mouse(mouse, now); + } + match mouse.kind { + MouseEventKind::Down(MouseButton::Left) => self.on_click(mouse, now), + MouseEventKind::ScrollDown | MouseEventKind::ScrollUp => self.on_wheel(mouse, now), + _ => Vec::new(), + } + } + + /// The pointer events an open overlay reacts to: a left click outside + /// a confirm or picker closes it through the same close path as the + /// esc key, so everything the close arranges still happens. Every + /// other pointer event is ignored. + fn on_overlay_mouse(&mut self, mouse: MouseEvent, now: Instant) -> Vec { + let dismiss = matches!( + &self.overlay, + Some(Overlay::Confirm(_) | Overlay::Picker(_)) + ) && mouse.kind == MouseEventKind::Down(MouseButton::Left) + && !self + .layout + .overlay + .is_some_and(|rect| rect.contains(Position::new(mouse.column, mouse.row))); + if !dismiss { + return Vec::new(); + } + self.overlay = None; + self.dirty = true; + self.on_overlay_close(now) + } + + /// One left click's hit test: a header tab switches views through the + /// same path the number keys take, and a row of the list under the + /// pointer moves the cursor onto itself, or toggles the detail when + /// the cursor already sat there. + fn on_click(&mut self, mouse: MouseEvent, now: Instant) -> Vec { + let position = Position::new(mouse.column, mouse.row); + if let Some((_, view)) = self + .layout + .tabs + .iter() + .find(|(rect, _)| rect.contains(position)) + { + return self.on_action(Action::View(*view), now); + } + let Some((rect, offset)) = self.layout.list else { + return Vec::new(); + }; + if !rect.contains(position) { + return Vec::new(); + } + let index = offset + usize::from(mouse.row - rect.y); + if index >= self.list_len() { + return Vec::new(); + } + if self.cursor_selected() == index { + return self.on_action(Action::ToggleDetail, now); + } + self.move_cursor_to(index, now); + Vec::new() + } + + /// The wheel: scrolls the pane under the pointer by the wheel's row + /// count, three rows per notch, the way the keyboard movement keys + /// move it. A detail or log pane under the pointer scrolls itself + /// whatever pane the keyboard focus sits on. + fn on_wheel(&mut self, mouse: MouseEvent, now: Instant) -> Vec { + let position = Position::new(mouse.column, mouse.row); + let down = mouse.kind == MouseEventKind::ScrollDown; + let action = if down { Action::Down } else { Action::Up }; + if self.view == ViewId::Jobs && self.layout.log.is_some_and(|rect| rect.contains(position)) + { + let saved = self.jobs_view.focus; + self.jobs_view.focus = JobsFocus::Log; + for _ in 0..WHEEL_ROWS { + self.scroll_jobs(action); + } + self.jobs_view.focus = saved; + return Vec::new(); + } + if self + .layout + .detail + .is_some_and(|rect| rect.contains(position)) + { + match self.view { + ViewId::Browse if self.browse.detail_open => { + for _ in 0..WHEEL_ROWS { + self.scroll_browse(action, now); + } + } + ViewId::Installed if self.installed.detail_open => { + for _ in 0..WHEEL_ROWS { + self.scroll_installed(action); + } + } + ViewId::Jobs => { + let saved = self.jobs_view.focus; + self.jobs_view.focus = JobsFocus::Detail; + for _ in 0..WHEEL_ROWS { + self.scroll_jobs(action); + } + self.jobs_view.focus = saved; + } + _ => {} + } + return Vec::new(); + } + let Some((rect, _)) = self.layout.list else { + return Vec::new(); + }; + if !rect.contains(position) { + return Vec::new(); + } + for _ in 0..WHEEL_ROWS { + match self.view { + ViewId::Browse => self.scroll_browse(action, now), + ViewId::Installed => self.scroll_installed(action), + ViewId::Updates => self.scroll_updates(action), + ViewId::Repos => self.scroll_repos(action), + ViewId::Health => self.scroll_health(action), + ViewId::Apply => self.scroll_apply(action), + ViewId::Jobs => { + let len = self.jobs.list.len(); + if down { + self.jobs_view.cursor.down(1, len); + } else { + self.jobs_view.cursor.up(1); + } + } + } + } + self.dirty = true; + Vec::new() + } + + /// The number of rows the focused view's list holds, zero before its + /// data loads. + fn list_len(&self) -> usize { + match self.view { + ViewId::Browse => self.browse.visible.len(), + ViewId::Installed => self.installed.visible.len(), + ViewId::Updates => self.updates.ready_len(), + ViewId::Apply => self.apply.body_rows, + ViewId::Repos => self.repos.ready_len(), + ViewId::Health => self.health.paths_len(), + ViewId::Jobs => self.jobs.list.len(), + } + } + + /// The row the focused view's list cursor sits on. + fn cursor_selected(&self) -> usize { + match self.view { + ViewId::Browse => self.browse.cursor.selected, + ViewId::Installed => self.installed.cursor.selected, + ViewId::Updates => self.updates.cursor.selected, + ViewId::Apply => self.apply.cursor.selected, + ViewId::Repos => self.repos.cursor.selected, + ViewId::Health => self.health.cursor.selected, + ViewId::Jobs => self.jobs_view.cursor.selected, + } + } + + /// Moves the focused view's list cursor to `index`, leaving the view + /// exactly as the keyboard movement keys would. + fn move_cursor_to(&mut self, index: usize, now: Instant) { + match self.view { + ViewId::Browse => { + self.browse.cursor.selected = index; + self.browse.note_cursor(now); + } + ViewId::Installed => self.installed.cursor.selected = index, + ViewId::Updates => self.updates.cursor.selected = index, + ViewId::Apply => self.apply.cursor.selected = index, + ViewId::Repos => self.repos.cursor.selected = index, + ViewId::Health => self.health.cursor.selected = index, + ViewId::Jobs => self.jobs_view.cursor.selected = index, + } + self.dirty = true; + } + + /// Carries out one action. View-local actions act on the view's own + /// state; the global ones act on the interface as a whole. + fn on_action(&mut self, action: Action, now: Instant) -> Vec { + match action { + Action::View(view) => return self.switch_to(view, now), + Action::NextView => return self.switch_to(self.view.next(), now), + Action::PrevView => return self.switch_to(self.view.prev(), now), + Action::Quit => self.on_quit(), + Action::Help => { + self.overlay = Some(Overlay::Help(Help::new(self.view))); + self.dirty = true; + } + Action::Escape => { + if self.view == ViewId::Browse { + self.escape_browse(now); + } else if self.view == ViewId::Installed { + self.escape_installed(); + } else if self.view == ViewId::Updates && self.updates.scope.is_some() { + return self.escape_updates_scope(now); + } else if self.view == ViewId::Jobs && self.jobs_view.focus != JobsFocus::List { + self.jobs_view.focus = JobsFocus::List; + self.dirty = true; + } + } + Action::FocusDetail => { + if self.view == ViewId::Jobs && !self.jobs.list.is_empty() { + self.jobs_view.focus = JobsFocus::Detail; + self.dirty = true; + } + } + Action::FocusLog => { + if self.view == ViewId::Jobs { + self.jobs_view.focus = JobsFocus::Log; + self.dirty = true; + } + } + Action::ClearFinished => { + if self.view == ViewId::Jobs { + self.jobs + .list + .retain(|job| !matches!(job.state, JobState::Finished { .. })); + self.jobs_view.cursor.clamp(self.jobs.list.len()); + self.dirty = true; + } + } + Action::Sync if self.view == ViewId::Repos => { + if self.jobs.list.iter().any(|job| { + job.kind == JobKind::Sync && !matches!(job.state, JobState::Finished { .. }) + }) { + self.toast(ToastKind::Info, "Sync already pending", now); + } else { + return self.enqueue(JobSpec::Sync, now); + } + } + Action::ToggleEnabled if self.view == ViewId::Repos => { + self.open_repo_enabled_confirm(); + } + Action::RemoveRepo if self.view == ViewId::Repos => { + self.open_repo_removed_confirm(); + } + Action::AddRepo if self.view == ViewId::Repos => { + self.open_add_repo_form(); + } + Action::EditConfig if self.view == ViewId::Repos => { + if self.running_job().is_some() { + self.toast( + ToastKind::Error, + "Wait for the running job to finish before editing config", + now, + ); + } else { + self.dirty = true; + return vec![Effect::Suspend(Suspended::Edit( + self.env.config_path.clone(), + ))]; + } + } + Action::CleanCache if self.view == ViewId::Health => { + self.open_clean_cache_confirm(); + } + Action::FixSymlinks if self.view == ViewId::Health => { + self.open_fix_symlinks_confirm(now); + } + Action::RemoveBroken if self.view == ViewId::Health => { + self.open_remove_broken_confirm(now); + } + Action::Down + | Action::Up + | Action::Top + | Action::Bottom + | Action::PageDown + | Action::PageUp => { + if self.view == ViewId::Browse { + self.scroll_browse(action, now); + } else if self.view == ViewId::Installed { + self.scroll_installed(action); + } else if self.view == ViewId::Updates { + self.scroll_updates(action); + } else if self.view == ViewId::Repos { + self.scroll_repos(action); + } else if self.view == ViewId::Health { + self.scroll_health(action); + } else if self.view == ViewId::Apply { + self.scroll_apply(action); + } else { + self.scroll_jobs(action); + } + } + Action::AbortJob => self.request_abort(now), + Action::AbortSelected => self.abort_selected(now), + Action::Filter if self.view == ViewId::Browse => { + self.browse.filter_focused = true; + self.dirty = true; + } + Action::Filter if self.view == ViewId::Installed => { + self.installed.filter_focused = true; + self.dirty = true; + } + Action::ToggleMark if self.view == ViewId::Browse => { + self.browse.toggle_mark(now); + self.dirty = true; + } + Action::ToggleMark if self.view == ViewId::Installed => { + self.installed.toggle_mark(); + self.dirty = true; + } + Action::ToggleMark if self.view == ViewId::Updates => { + if !self.updates_table_hidden() { + self.updates.toggle_mark(); + self.dirty = true; + } + } + Action::MarkAll if self.view == ViewId::Updates => { + if !self.updates_table_hidden() { + self.updates.mark_all(); + self.dirty = true; + } + } + Action::ToggleKeepOld if self.view == ViewId::Updates => { + self.updates.keep_old = !self.updates.keep_old; + self.dirty = true; + } + Action::ToggleSkipped if self.view == ViewId::Updates => { + self.updates.show_skipped = !self.updates.show_skipped; + self.dirty = true; + } + Action::Update if self.view == ViewId::Updates => { + if self.updates_table_hidden() { + self.toast(ToastKind::Info, "Press S to return to the list", now); + } else { + self.open_update_confirm(now); + } + } + Action::UpdateSelected if self.view == ViewId::Installed => { + return self.check_selected_for_updates(now); + } + Action::TogglePrune if self.view == ViewId::Apply => { + self.apply.prune = !self.apply.prune; + self.dirty = true; + return vec![self.apply_effect()]; + } + Action::Apply if self.view == ViewId::Apply => { + self.open_apply_confirm(now); + } + Action::EditPackages if self.view == ViewId::Apply => { + if self.running_job().is_some() { + self.toast( + ToastKind::Error, + "Wait for the running job to finish before editing packages.toml", + now, + ); + } else { + let path = self + .apply + .plan + .ready() + .map(|plan| plan.path.clone()) + .unwrap_or_else(|| self.env.packages_path.clone()); + self.dirty = true; + return vec![Effect::Suspend(Suspended::Edit(path))]; + } + } + Action::CreatePackages if self.view == ViewId::Apply => { + let missing = self + .apply + .plan + .ready() + .is_some_and(|plan| plan.diff.is_none()); + if missing { + return self.enqueue(JobSpec::CreatePackagesConfig, now); + } + } + Action::CycleRepo if self.view == ViewId::Browse => { + self.browse.cycle_repo(now); + self.dirty = true; + } + Action::CycleSort if self.view == ViewId::Installed => { + self.installed.cycle_sort(); + self.dirty = true; + } + Action::ToggleDetail if self.view == ViewId::Browse => self.toggle_detail(), + Action::ToggleDetail if self.view == ViewId::Installed => { + self.installed.toggle_detail(); + self.dirty = true; + } + Action::Remove if self.view == ViewId::Installed => { + self.open_remove_confirm(); + } + Action::SwitchVariant if self.view == ViewId::Installed => { + return self.open_switch_flow(); + } + Action::Install if self.view == ViewId::Browse => { + let versions = self.browse.selected_versions(); + return self.install_versions(versions, InstallChoices::default(), now); + } + Action::InstallWithOptions if self.view == ViewId::Browse => { + self.open_install_options(); + } + Action::PickVersion if self.view == ViewId::Browse => { + self.open_version_picker(now); + } + Action::InstallByQuery if self.view == ViewId::Browse => { + self.overlay = Some(Overlay::Prompt(Prompt::new( + "Install by name, URL, or path", + OnAccept::InstallByQuery, + ))); + self.dirty = true; + } + Action::RunPackage if self.view == ViewId::Browse => { + self.open_run_prompt(); + } + Action::Reload if self.view == ViewId::Browse => { + self.browse.catalog = Loadable::Loading; + self.dirty = true; + return vec![self.catalog_effect()]; + } + Action::Reload if self.view == ViewId::Installed => { + self.installed.list = Loadable::Loading; + self.dirty = true; + return vec![self.installed_effect()]; + } + Action::Reload if self.view == ViewId::Updates => { + let check = self.check_effect(self.updates.scope.clone(), now); + self.dirty = true; + return vec![check]; + } + Action::Reload if self.view == ViewId::Apply => { + self.dirty = true; + return vec![self.apply_effect()]; + } + Action::Reload if self.view == ViewId::Repos => { + self.repos.start(); + self.dirty = true; + return vec![Effect::LoadRepos]; + } + Action::Reload if self.view == ViewId::Health => { + self.health.start(); + self.dirty = true; + return vec![Effect::LoadHealth]; + } + _ => {} + } + Vec::new() + } + + /// The catalog's esc: closes the full-screen detail first, then clears + /// the filter, then the repository filter, then clears the marks, one + /// press each. + fn escape_browse(&mut self, now: Instant) { + if self.browse.detail_open { + self.browse.detail_open = false; + self.dirty = true; + } else if !self.browse.filter.is_empty() { + self.browse.filter.clear(); + self.browse.refilter(now); + self.dirty = true; + } else if self.browse.repo_filter.is_some() { + self.browse.repo_filter = None; + self.browse.refilter(now); + self.dirty = true; + } else if !self.browse.marks.is_empty() { + self.browse.marks.clear(); + self.dirty = true; + } + } + + /// The installed list's esc: closes the full-screen detail first, then + /// clears the filter, then clears the marks, one press each. + fn escape_installed(&mut self) { + if self.installed.detail_open { + self.installed.detail_open = false; + self.dirty = true; + } else if !self.installed.filter.is_empty() { + self.installed.filter.clear(); + self.installed.refilter(); + self.dirty = true; + } else if !self.installed.marks.is_empty() { + self.installed.marks.clear(); + self.dirty = true; + } + } + + /// Starts a check and builds the effect that runs it, numbered for + /// this start, so a result from a check a newer start replaced is + /// dropped when it arrives. A check that starts while the update + /// confirm is open closes it first: its picks are indexes into a + /// list the fresh check is about to replace. + fn check_effect(&mut self, names: Option>, now: Instant) -> Effect { + if self.update_pick.take().is_some() { + self.close_update_confirm(); + self.toast( + ToastKind::Info, + "The update list is being rechecked, so the confirm closed", + now, + ); + } + self.updates.start_check(); + Effect::CheckUpdates { + names, + check: self.updates.check, + } + } + + /// Starts a catalog load and builds the effect that runs it, numbered + /// for this start, so a reply from a load a newer start replaced is + /// dropped when it arrives. + fn catalog_effect(&mut self) -> Effect { + self.catalog_load = self.catalog_load.wrapping_add(1); + Effect::LoadCatalog { + check: self.catalog_load, + } + } + + /// Starts an installed list load and builds the effect that runs it, + /// numbered like the catalog's so a replaced load's reply is dropped. + fn installed_effect(&mut self) -> Effect { + self.installed_load = self.installed_load.wrapping_add(1); + Effect::LoadInstalled { + check: self.installed_load, + } + } + + /// Starts a plan computation and builds the effect that runs it, + /// numbered for this start, so a result from a computation a newer + /// start replaced is dropped when it arrives. + fn apply_effect(&mut self) -> Effect { + self.apply.start(); + Effect::ComputeApplyDiff { + prune: self.apply.prune, + check: self.apply.check, + } + } + + /// Drops an open update confirm whose list a fresh check replaced, so + /// accepting it cannot update rows that moved under it. + fn close_update_confirm(&mut self) { + if let Some(Overlay::Confirm(confirm)) = &self.overlay + && matches!(confirm.action(), OnAccept::UpdateNow) + { + self.overlay = None; + } + } + + /// Drops an open apply confirm whose plan a fresh computation + /// replaced, so accepting it cannot queue removals the confirm never + /// named. + fn close_apply_confirm(&mut self) { + if let Some(Overlay::Confirm(confirm)) = &self.overlay + && matches!(confirm.action(), OnAccept::ApplyPlan) + { + self.overlay = None; + } + } + + /// Drops the updates scope and checks everything again, so esc backs + /// the view out to the full list. + fn escape_updates_scope(&mut self, now: Instant) -> Vec { + self.updates.scope = None; + let check = self.check_effect(None, now); + self.dirty = true; + vec![check] + } + + /// Moves to the updates view and checks only the packages selected in + /// the installed list: marked rows, or the row under the cursor. + /// Duplicate names collapse to one check, keeping first order. + fn check_selected_for_updates(&mut self, now: Instant) -> Vec { + let mut names: Vec = Vec::new(); + for entry in self.installed.selected_entries() { + let name = entry.package.pkg_name; + if !names.contains(&name) { + names.push(name); + } + } + if names.is_empty() { + return Vec::new(); + } + self.updates.scope = Some(names.clone()); + let check = self.check_effect(Some(names), now); + let mut effects = self.switch_to(ViewId::Updates, now); + effects.push(check); + effects + } + + /// Opens the full-screen detail on the row under the cursor, or closes + /// it back to the list. + fn toggle_detail(&mut self) { + if self.browse.detail_open { + self.browse.detail_open = false; + } else if self.browse.cursor_row().is_some() { + self.browse.detail_open = true; + self.browse.detail.top(); + } + self.dirty = true; + } + + /// How many rows a page key moves: half the current view's main list + /// height, or ten rows when no list is on screen. The main list is + /// the view's own, even where a page key scrolls another pane, such + /// as the jobs view's detail or log. + fn page_rows(&self) -> usize { + self.layout + .list + .map_or(10, |(rect, _)| usize::from(rect.height / 2).max(1)) + } + + /// Moves the catalog cursor, or scrolls the detail pane while it fills + /// the screen. The drawn window follows at render time. + fn scroll_browse(&mut self, action: Action, now: Instant) { + let page = self.page_rows(); + if self.browse.detail_open { + let len = self.browse.detail_rows; + match action { + Action::Down => self.browse.detail.down(1, len), + Action::Up => self.browse.detail.up(1), + Action::PageDown => self.browse.detail.down(page, len), + Action::PageUp => self.browse.detail.up(page), + Action::Top => self.browse.detail.top(), + _ => self.browse.detail.bottom(len), + } + } else { + let len = self.browse.visible.len(); + match action { + Action::Down => self.browse.cursor.down(1, len), + Action::Up => self.browse.cursor.up(1), + Action::PageDown => self.browse.cursor.down(page, len), + Action::PageUp => self.browse.cursor.up(page), + Action::Top => self.browse.cursor.top(), + _ => self.browse.cursor.bottom(len), + } + self.browse.note_cursor(now); + } + self.dirty = true; + } + + /// Moves the installed list's cursor, or scrolls the detail pane while + /// it fills the screen. The drawn window follows at render time. + fn scroll_installed(&mut self, action: Action) { + let page = self.page_rows(); + if self.installed.detail_open { + let len = self.installed.detail_rows; + match action { + Action::Down => self.installed.detail.down(1, len), + Action::Up => self.installed.detail.up(1), + Action::PageDown => self.installed.detail.down(page, len), + Action::PageUp => self.installed.detail.up(page), + Action::Top => self.installed.detail.top(), + _ => self.installed.detail.bottom(len), + } + } else { + let len = self.installed.visible.len(); + match action { + Action::Down => self.installed.cursor.down(1, len), + Action::Up => self.installed.cursor.up(1), + Action::PageDown => self.installed.cursor.down(page, len), + Action::PageUp => self.installed.cursor.up(page), + Action::Top => self.installed.cursor.top(), + _ => self.installed.cursor.bottom(len), + } + } + self.dirty = true; + } + + /// Whether the skipped list replaces the updates table, so keys + /// aimed at its rows must not reach them. + fn updates_table_hidden(&self) -> bool { + self.updates.show_skipped && !self.updates.skipped.is_empty() + } + + /// Moves the updates list's cursor. The drawn window follows at render + /// time, and the cursor clamps to the empty list while it loads. + fn scroll_updates(&mut self, action: Action) { + if self.updates_table_hidden() { + return; + } + let page = self.page_rows(); + let len = self.updates.ready_len(); + match action { + Action::Down => self.updates.cursor.down(1, len), + Action::Up => self.updates.cursor.up(1), + Action::PageDown => self.updates.cursor.down(page, len), + Action::PageUp => self.updates.cursor.up(page), + Action::Top => self.updates.cursor.top(), + _ => self.updates.cursor.bottom(len), + } + self.dirty = true; + } + + /// Moves the repositories list's cursor. The drawn window follows at + /// render time, and the cursor clamps to the empty list while it + /// loads. + fn scroll_repos(&mut self, action: Action) { + let page = self.page_rows(); + let len = self.repos.ready_len(); + match action { + Action::Down => self.repos.cursor.down(1, len), + Action::Up => self.repos.cursor.up(1), + Action::PageDown => self.repos.cursor.down(page, len), + Action::PageUp => self.repos.cursor.up(page), + Action::Top => self.repos.cursor.top(), + _ => self.repos.cursor.bottom(len), + } + self.dirty = true; + } + + /// Moves the paths pane's cursor over the loaded paths list. The + /// drawn window follows at render time. + fn scroll_health(&mut self, action: Action) { + let page = self.page_rows(); + let len = self.health.paths_len(); + match action { + Action::Down => self.health.cursor.down(1, len), + Action::Up => self.health.cursor.up(1), + Action::PageDown => self.health.cursor.down(page, len), + Action::PageUp => self.health.cursor.up(page), + Action::Top => self.health.cursor.top(), + _ => self.health.cursor.bottom(len), + } + self.dirty = true; + } + + /// Moves the plan body's cursor. The drawn window follows at render + /// time, and the length comes from the last frame the body drew. + fn scroll_apply(&mut self, action: Action) { + let page = self.page_rows(); + let len = self.apply.body_rows; + match action { + Action::Down => self.apply.cursor.down(1, len), + Action::Up => self.apply.cursor.up(1), + Action::PageDown => self.apply.cursor.down(page, len), + Action::PageUp => self.apply.cursor.up(page), + Action::Top => self.apply.cursor.top(), + _ => self.apply.cursor.bottom(len), + } + self.dirty = true; + } + + /// Carries the Jobs view's abort key out on the job under the cursor: + /// the running one goes through the same confirm as the global key, a + /// queued one leaves the list, and a finished one stays. + fn abort_selected(&mut self, now: Instant) { + let Some(job) = self.selected_job() else { + self.toast(ToastKind::Info, "Nothing is running", now); + return; + }; + if matches!(job.state, JobState::Running { .. }) { + self.request_abort(now); + return; + } + if !matches!(job.state, JobState::Queued) { + return; + } + let pos = self.jobs.list.len() - 1 - self.jobs_view.cursor.selected; + let title = self.jobs.list[pos].title.clone(); + self.jobs.list.remove(pos); + self.jobs_view.cursor.clamp(self.jobs.list.len()); + self.dirty = true; + self.toast( + ToastKind::Info, + format!("Removed {title} from the queue"), + now, + ); + } + + /// The job the Jobs view points at. The list shows newest first, so the + /// cursor counts from the end. + fn selected_job(&self) -> Option<&Job> { + let len = self.jobs.list.len(); + let selected = self.jobs_view.cursor.selected; + (selected < len) + .then(|| len - 1 - selected) + .and_then(|pos| self.jobs.list.get(pos)) + } + + /// Scrolls the pane the jobs view holds focus on. Moving up or to the + /// top stops the log from following its end; the bottom key resumes it. + fn scroll_jobs(&mut self, action: Action) { + if self.view != ViewId::Jobs { + return; + } + match self.jobs_view.focus { + JobsFocus::List => { + let page = self.page_rows(); + let len = self.jobs.list.len(); + match action { + Action::Down => self.jobs_view.cursor.down(1, len), + Action::Up => self.jobs_view.cursor.up(1), + Action::PageDown => self.jobs_view.cursor.down(page, len), + Action::PageUp => self.jobs_view.cursor.up(page), + Action::Top => self.jobs_view.cursor.top(), + _ => self.jobs_view.cursor.bottom(len), + } + } + JobsFocus::Detail => { + let page = self.page_rows(); + let len = self.jobs_view.detail_rows; + match action { + Action::Down => self.jobs_view.detail.down(1, len), + Action::Up => self.jobs_view.detail.up(1), + Action::PageDown => self.jobs_view.detail.down(page, len), + Action::PageUp => self.jobs_view.detail.up(page), + Action::Top => self.jobs_view.detail.top(), + _ => self.jobs_view.detail.bottom(len), + } + } + JobsFocus::Log => { + let page = self.page_rows(); + let len = self.log.lines.len(); + match action { + Action::Down => { + self.log.follow = false; + self.log.cursor.down(1, len); + } + Action::Up => { + self.log.follow = false; + self.log.cursor.up(1); + } + Action::PageDown => { + self.log.follow = false; + self.log.cursor.down(page, len); + } + Action::PageUp => { + self.log.follow = false; + self.log.cursor.up(page); + } + Action::Top => { + self.log.follow = false; + self.log.cursor.top(); + } + _ => { + self.log.follow = true; + self.log.cursor.bottom(len); + } + } + } + } + self.dirty = true; + } + + /// Handles a quit request: with a job running, the guard dialog; with a + /// quit already pending, the force-quit confirm; otherwise quit now. A + /// queued job always has a running job ahead of it, so one check + /// covers both. + fn on_quit(&mut self) { + if self.quit_when_idle { + self.overlay = Some(Overlay::Confirm(Confirm::new( + "Quit", + vec![Line::raw( + "Force quit now? The running job stops wherever it is.", + )], + "Force quit", + true, + OnAccept::QuitForce, + ))); + } else if let Some(job) = self.running_job().or_else(|| self.authorizing_job()) { + let title = job.title.clone(); + let queued = self.queued_count(); + self.overlay = Some(Overlay::QuitGuard(QuitGuard::new(&title, queued))); + } else { + self.quit = true; + } + self.dirty = true; + } + + /// Shows one view, starts the work the view asks for on entering, and + /// marks the screen for a redraw. Opening the Jobs view clears the + /// unseen-failure flag, since the failure is now seen. + fn switch_to(&mut self, view: ViewId, now: Instant) -> Vec { + if view == ViewId::Jobs { + self.jobs.attention = false; + } + self.view = view; + let effects = self.on_enter_view(view, now); + self.dirty = true; + effects + } + + /// The work the view starts when it comes on screen. Views that load + /// their data on the first visit request it here, so one switch shows + /// the view and starts its load. Later views use it too. + fn on_enter_view(&mut self, view: ViewId, now: Instant) -> Vec { + match view { + ViewId::Updates if self.updates.list.is_idle() => { + vec![self.check_effect(None, now)] + } + ViewId::Apply if self.apply.plan.is_idle() => vec![self.apply_effect()], + ViewId::Repos if self.repos.list.is_idle() => { + self.repos.start(); + vec![Effect::LoadRepos] + } + ViewId::Health if self.health.report.is_idle() => { + self.health.start(); + vec![Effect::LoadHealth] + } + _ => Vec::new(), + } + } +} + +/// One picker row per candidate package: `family/name version repo +/// type`, without the family when there is none. +fn variant_rows(candidates: &[Package]) -> Vec> { + candidates + .iter() + .map(|package| { + let name = match package.pkg_family.as_deref() { + Some(family) => format!("{family}/{}", package.pkg_name), + None => package.pkg_name.clone(), + }; + let kind = package.pkg_type.as_deref().unwrap_or(""); + Line::raw(format!( + "{name} {} {} {kind}", + package.version, package.repo_name + )) + }) + .collect() +} + +/// One picker row per installed variant: `family/name version repo +/// type size`, without the family when there is none, and the active +/// one marked. +fn variant_pick_rows(variants: &[VariantInfo], theme: &Theme) -> Vec> { + variants + .iter() + .map(|variant| { + let package = &variant.package; + let name = match package.pkg_family.as_deref() { + Some(family) => format!("{family}/{}", package.pkg_name), + None => package.pkg_name.clone(), + }; + let kind = package.pkg_type.as_deref().unwrap_or(""); + let mut spans = vec![Span::raw(format!( + "{name} {} {} {kind} {}", + package.version, + package.repo_name, + format::size(package.size) + ))]; + if variant.is_active { + spans.push(Span::styled( + format!(" {} active", theme.sym().marked), + theme.success(), + )); + } + Line::from(spans) + }) + .collect() +} + +/// The exact query naming one package variant, `family/name@version:repo`, +/// without the family when there is none. +fn variant_query(package: &Package) -> String { + match package.pkg_family.as_deref() { + Some(family) => { + format!( + "{family}/{}@{}:{}", + package.pkg_name, package.version, package.repo_name + ) + } + None => { + format!( + "{}@{}:{}", + package.pkg_name, package.version, package.repo_name + ) + } + } +} + +/// One confirm line for a package: `name version repo size`, without +/// the size when the repository gives none. +fn package_line(package: &Package) -> Line<'static> { + let mut text = format!( + "{} {} {}", + package.pkg_name, package.version, package.repo_name + ); + if package.ghcr_size.or(package.size).is_some() { + let bytes = package_size(package); + text.push_str(&format!(" {}", format::size(bytes))); + } + Line::raw(text) +} + +/// One confirm line for an installed package: `name version repo +/// size`, with the size on disk that removing it frees. +fn installed_package_line(entry: &InstalledEntry) -> Line<'static> { + Line::raw(format!( + "{} {} {} {}", + entry.package.pkg_name, + entry.package.version, + entry.package.repo_name, + format::size(entry.disk_size) + )) +} + +/// The download size shown for a package: the registry image size when +/// the repository gives one, else the artifact size, else nothing. +fn package_size(package: &Package) -> u64 { + package.ghcr_size.or(package.size).unwrap_or(0) +} + +/// The line summarizing the options that differ from a plain install, or +/// `None` when every choice is the default. +fn options_line(choices: &InstallChoices) -> Option> { + let mut parts: Vec = Vec::new(); + if choices.force { + parts.push("force".to_string()); + } + if choices.binary_only { + parts.push("binary only".to_string()); + } + if choices.no_verify { + parts.push("skip verification".to_string()); + } + match choices.portable.as_deref() { + Some("") => parts.push("portable".to_string()), + Some(path) => parts.push(format!("portable: {path}")), + None => {} + } + (!parts.is_empty()).then(|| { + let summary = parts.join(", "); + Line::raw(format!("Options: {summary}")) + }) +} + +#[cfg(test)] +mod tests { + use std::{ + path::{Path, PathBuf}, + time::{Duration, Instant}, + }; + + use ratatui::{ + crossterm::event::{ + Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton, MouseEvent, + MouseEventKind, + }, + text::Line, + }; + use soar_core::{database::models::Package, package::install::InstallTarget}; + use soar_events::{SoarEvent, SyncStage}; + use soar_operations::{ + AmbiguousPackage, ApplyDiff, BrokenPackage, HealthReport, InstalledListResult, + PrepareRunResult, UpdateInfo, VariantInfo, + privilege::{EscalationKind, EscalationTool}, + }; + + use super::{App, AppEnv}; + use crate::{ + action::Action, + effect::{Effect, Suspended}, + jobs::{ + InstallChoices, JobId, JobKind, JobOutcome, JobSpec, JobState, OutcomeLine, RepoChange, + SystemMode, + }, + loadable::Loadable, + msg::{Loaded, Msg, Resolution}, + privileged::EscalationProbe, + progress::Phase, + test_support::{ + apply_plan, catalog_row, code, ctrl, health_paths, health_report, install_entry, + installed_entry, installed_package, key, package, screen, update_info, + }, + theme::Theme, + views::{ViewId, apply::ApplyPlan, browse::CatalogRow, repos::RepoRow}, + widgets::{ + confirm::Confirm, + overlay::{OnAccept, Overlay}, + picker::Picker, + text_input::Prompt, + toast::ToastKind, + }, + }; + + fn app() -> App { + App::new( + AppEnv { + version: String::new(), + profile: String::new(), + system: false, + config_path: PathBuf::from("/tmp/soar-test-config.toml"), + packages_path: PathBuf::from("/tmp/soar-test-packages.toml"), + }, + Theme::new(true, true), + ) + } + + /// A catalog reply for the load the app still expects before any + /// reload has started. + fn catalog_loaded(rows: Vec) -> Msg { + Msg::Loaded(Loaded::Catalog { + check: 0, + result: Ok(rows), + }) + } + + /// A repositories list, loaded. + fn repos_loaded(rows: Vec) -> Msg { + Msg::Loaded(Loaded::Repos(Ok(rows))) + } + + /// One repository row with the given enabled flag, never synced. + fn repo_row(name: &str, enabled: bool) -> RepoRow { + RepoRow { + name: name.to_string(), + url: format!("https://example.com/{name}.db"), + enabled, + signed: true, + desktop: true, + sync_interval: "3h".to_string(), + synced: None, + } + } + + /// An installed list over the given entries, answering the load the + /// app still expects before any reload has started. + fn installed_loaded(entries: Vec) -> Msg { + let total_count = entries.len(); + let total_size = entries.iter().map(|entry| entry.disk_size).sum(); + Msg::Loaded(Loaded::Installed { + check: 0, + result: Ok(InstalledListResult { + packages: entries, + total_count, + total_size, + }), + }) + } + + /// A variants result for one package name. + fn variants_loaded(name: &str, variants: Vec) -> Msg { + Msg::Loaded(Loaded::Variants { + name: name.to_string(), + result: Box::new(Ok(variants)), + }) + } + + /// One installed variant of a package, with its database id. + fn variant(id: u64, name: &str, version: &str, repo: &str, active: bool) -> VariantInfo { + let mut package = installed_package(name, version, repo); + package.id = id; + VariantInfo { + package, + is_active: active, + } + } + + /// A resolve result with the default choices. + fn resolved(list: Vec) -> Msg { + Msg::Loaded(Loaded::Resolved { + choices: InstallChoices::default(), + result: Ok(list), + }) + } + + /// An install target for one package. + fn target(package: Package) -> InstallTarget { + InstallTarget { + package, + ..Default::default() + } + } + + /// The one resolve the effects hold, failing the test otherwise. + fn resolve_of(effects: &[Effect]) -> &Vec { + let [ + Effect::Resolve { + queries, .. + }, + ] = effects + else { + panic!("expected one resolve"); + }; + queries + } + + fn press(code: KeyCode, modifiers: KeyModifiers, kind: KeyEventKind) -> Msg { + Msg::Input(Event::Key(KeyEvent::new_with_kind(code, modifiers, kind))) + } + + #[test] + fn pressing_three_selects_updates() { + let mut app = app(); + app.update( + press(KeyCode::Char('3'), KeyModifiers::NONE, KeyEventKind::Press), + Instant::now(), + ); + assert_eq!(app.view, ViewId::Updates); + } + + #[test] + fn tab_from_jobs_selects_browse() { + let mut app = app(); + app.view = ViewId::Jobs; + app.update( + press(KeyCode::Tab, KeyModifiers::NONE, KeyEventKind::Press), + Instant::now(), + ); + assert_eq!(app.view, ViewId::Browse); + } + + #[test] + fn q_sets_quit() { + let mut app = app(); + app.update( + press(KeyCode::Char('q'), KeyModifiers::NONE, KeyEventKind::Press), + Instant::now(), + ); + assert!(app.quit); + } + + #[test] + fn release_kind_changes_nothing() { + let mut app = app(); + app.update( + press( + KeyCode::Char('q'), + KeyModifiers::NONE, + KeyEventKind::Release, + ), + Instant::now(), + ); + assert!(!app.quit); + assert_eq!(app.view, ViewId::Browse); + } + + #[test] + fn startup_sets_the_catalog_loading_and_returns_the_load_effect() { + let mut app = app(); + let effects = app.startup(); + assert!(matches!( + effects.as_slice(), + [Effect::LoadCatalog { .. }, Effect::LoadInstalled { .. }] + )); + assert!(app.browse.catalog.is_loading()); + assert!(app.installed.list.is_loading()); + } + + #[test] + fn a_loaded_catalog_replaces_the_view_state() { + let mut app = app(); + app.update( + Msg::Loaded(Loaded::Catalog { + check: 0, + result: Ok(Vec::new()), + }), + Instant::now(), + ); + assert!(app.browse.catalog.ready().is_some()); + assert!(app.dirty); + app.dirty = false; + app.update( + Msg::Loaded(Loaded::Catalog { + check: 0, + result: Err("offline".to_string()), + }), + Instant::now(), + ); + assert!(app.browse.catalog.ready().is_none()); + assert!(app.dirty); + } + + #[test] + fn the_first_catalog_load_quietly_starts_an_update_check() { + let mut app = app(); + let effects = app.update(catalog_loaded(Vec::new()), Instant::now()); + assert!(matches!( + effects.as_slice(), + [Effect::CheckUpdates { + names: None, + .. + }] + )); + assert!(app.updates.list.is_loading()); + } + + #[test] + fn page_keys_move_by_half_the_drawn_list() { + let rows: Vec = (0..40) + .map(|n| catalog_row(&format!("pkg{n}"), "1.0.0", "bincache")) + .collect(); + let mut app = app(); + app.update(catalog_loaded(rows), Instant::now()); + let now = Instant::now(); + screen(&mut app, 80, 24); + assert_eq!(app.browse.cursor.selected, 0); + let page = app.page_rows(); + let rows = app.layout.list.expect("the list drew").0.height as usize; + assert_eq!(page, (rows / 2).max(1)); + app.update(code(KeyCode::PageDown), now); + assert_eq!(app.browse.cursor.selected, page); + app.update(ctrl('d'), now); + assert_eq!(app.browse.cursor.selected, page * 2); + app.update(code(KeyCode::PageUp), now); + assert_eq!(app.browse.cursor.selected, page); + app.update(ctrl('u'), now); + assert_eq!(app.browse.cursor.selected, 0); + } + + #[test] + fn later_catalog_loads_start_no_further_check() { + let mut app = app(); + app.update(catalog_loaded(Vec::new()), Instant::now()); + let effects = app.update(catalog_loaded(Vec::new()), Instant::now()); + assert!(effects.is_empty()); + } + + #[test] + fn a_failed_catalog_load_starts_no_check() { + let mut app = app(); + let effects = app.update( + Msg::Loaded(Loaded::Catalog { + check: 0, + result: Err("offline".to_string()), + }), + Instant::now(), + ); + assert!(effects.is_empty()); + assert!(app.updates.list.is_idle()); + } + + #[test] + fn ctrl_r_on_browse_reloads_the_catalog() { + let mut app = app(); + let effects = app.update( + press( + KeyCode::Char('r'), + KeyModifiers::CONTROL, + KeyEventKind::Press, + ), + Instant::now(), + ); + assert!(matches!(effects.as_slice(), [Effect::LoadCatalog { .. }])); + assert!(app.browse.catalog.is_loading()); + } + + #[test] + fn ctrl_r_on_another_view_does_nothing_yet() { + let mut app = app(); + app.view = ViewId::Jobs; + let effects = app.update( + press( + KeyCode::Char('r'), + KeyModifiers::CONTROL, + KeyEventKind::Press, + ), + Instant::now(), + ); + assert!(effects.is_empty()); + } + + #[test] + fn an_open_overlay_captures_every_key() { + let mut app = app(); + app.overlay = Some(Overlay::Confirm(Confirm::new( + "Remove 2 packages", + Vec::new(), + "Remove", + true, + OnAccept::Test, + ))); + app.update( + press(KeyCode::Char('q'), KeyModifiers::NONE, KeyEventKind::Press), + Instant::now(), + ); + assert!(!app.quit); + assert!(app.overlay.is_some()); + app.update( + press(KeyCode::Char('y'), KeyModifiers::NONE, KeyEventKind::Press), + Instant::now(), + ); + assert!(app.overlay.is_none()); + } + + #[test] + fn help_opens_and_captures_keys_until_it_closes() { + let mut app = app(); + app.update( + press(KeyCode::Char('?'), KeyModifiers::NONE, KeyEventKind::Press), + Instant::now(), + ); + assert!(matches!(app.overlay, Some(Overlay::Help(_)))); + app.update( + press(KeyCode::Char('1'), KeyModifiers::NONE, KeyEventKind::Press), + Instant::now(), + ); + assert_eq!(app.view, ViewId::Browse); + app.update( + press(KeyCode::Esc, KeyModifiers::NONE, KeyEventKind::Press), + Instant::now(), + ); + assert!(app.overlay.is_none()); + } + + #[test] + fn a_toast_marks_the_screen_dirty() { + let mut app = app(); + app.dirty = false; + app.toast(ToastKind::Info, "installed fd", Instant::now()); + assert!(app.dirty); + assert_eq!(app.toasts.iter().count(), 1); + } + + #[test] + fn a_tick_expires_toasts_and_marks_the_screen_dirty() { + let mut app = app(); + let now = Instant::now(); + app.toast(ToastKind::Info, "installed fd", now); + app.dirty = false; + app.update(Msg::Tick, now + Duration::from_secs(5)); + assert!(app.dirty); + assert_eq!(app.toasts.iter().count(), 0); + } + + fn finished(id: JobId, ok: bool, headline: &str) -> Msg { + Msg::JobFinished { + id, + outcome: JobOutcome { + ok, + aborted: false, + headline: headline.to_string(), + lines: Vec::new(), + }, + } + } + + /// An install of one package by name, for the abort flows. + fn install_spec(name: &str) -> JobSpec { + JobSpec::Install { + targets: Vec::new(), + picked: vec![package(name, "1.0.0", "bincache")], + options: InstallChoices::default(), + } + } + + #[test] + fn enqueueing_two_jobs_while_idle_starts_only_the_first() { + let mut app = app(); + let now = Instant::now(); + let effects = app.enqueue(JobSpec::Sync, now); + assert!(matches!( + effects.as_slice(), + [Effect::StartJob { + id: 0, + spec: JobSpec::Sync + }] + )); + assert!(app.enqueue(JobSpec::CleanCache, now).is_empty()); + assert!(matches!(app.jobs.list[0].state, JobState::Running { .. })); + assert!(matches!(app.jobs.list[1].state, JobState::Queued)); + } + + #[test] + fn enqueue_refuses_new_work_once_a_wait_and_quit_is_pending() { + let mut app = app(); + let now = Instant::now(); + app.enqueue(install_spec("bat"), now); + app.quit_when_idle = true; + let effects = app.enqueue(install_spec("fd"), now); + assert!(effects.is_empty()); + assert_eq!(app.jobs.list.len(), 1, "no job may join a quitting queue"); + let toasts = format!("{:?}", app.toasts); + assert!( + toasts.contains("Quitting soon, so no new work is accepted"), + "toasts are {toasts:?}" + ); + } + + #[test] + fn nothing_starts_while_a_job_waits_for_authorization() { + let mut app = app(); + let now = Instant::now(); + app.enqueue(JobSpec::CleanCache, now); + app.jobs.list[0].state = JobState::Authorizing; + let effects = app.enqueue(JobSpec::Sync, now); + assert!(effects.is_empty()); + assert!(matches!(app.jobs.list[1].state, JobState::Queued)); + // Once the wait is over the queue moves again. + app.jobs.list.remove(0); + let effects = app.enqueue(JobSpec::CleanCache, now); + assert!(matches!( + effects.as_slice(), + [Effect::StartJob { + id: 1, + spec: JobSpec::Sync + }] + )); + } + + #[test] + fn finishing_a_job_starts_the_next_queued_one() { + let mut app = app(); + let now = Instant::now(); + app.enqueue(JobSpec::CleanCache, now); + app.enqueue(JobSpec::Sync, now); + let effects = app.update(finished(0, true, "Cache cleaned"), now); + assert!(matches!( + effects.as_slice(), + [ + Effect::LoadHealth, + Effect::StartJob { + id: 1, + spec: JobSpec::Sync + } + ] + )); + assert!(app.health.report.is_loading()); + assert!(matches!(app.jobs.list[1].state, JobState::Running { .. })); + assert_eq!(app.toasts.iter().count(), 1); + } + + #[test] + fn finishing_a_sync_rebuilds_the_context_before_the_next_job_starts() { + let mut app = app(); + let now = Instant::now(); + app.enqueue(JobSpec::Sync, now); + app.enqueue(JobSpec::CleanCache, now); + let effects = app.update(finished(0, true, "Repositories synced"), now); + assert!(matches!(effects[0], Effect::RebuildContext)); + assert!(matches!(effects[1], Effect::LoadCatalog { .. })); + assert!(matches!(effects[2], Effect::LoadInstalled { .. })); + assert!(matches!(effects[3], Effect::LoadRepos)); + assert!(matches!( + effects[4..], + [Effect::StartJob { + id: 1, + spec: JobSpec::CleanCache + }] + )); + } + + #[test] + fn pressing_s_once_enqueues_one_sync_and_the_second_presses_only_toast() { + let mut app = app(); + let now = Instant::now(); + app.view = ViewId::Repos; + let effects = app.update(key('s'), now); + assert!(matches!( + effects.as_slice(), + [Effect::StartJob { + spec: JobSpec::Sync, + .. + }] + )); + let effects = app.update(key('s'), now); + assert!(effects.is_empty()); + assert_eq!(app.toasts.iter().count(), 1); + assert!(format!("{:?}", app.toasts).contains("Sync already pending")); + } + + #[test] + fn pressing_e_on_repos_suspends_to_edit_the_config() { + let mut app = app(); + let now = Instant::now(); + app.view = ViewId::Repos; + let effects = app.update(key('E'), now); + let [Effect::Suspend(Suspended::Edit(path))] = &effects[..] else { + panic!("expected a suspend"); + }; + assert_eq!(path, &app.env.config_path); + assert!(app.dirty); + } + + #[test] + fn pressing_e_while_a_job_runs_toasts_instead_of_editing() { + let mut app = app(); + let now = Instant::now(); + app.view = ViewId::Repos; + app.enqueue(JobSpec::Sync, now); + let effects = app.update(key('E'), now); + assert!(effects.is_empty()); + assert_eq!(app.toasts.iter().count(), 1); + assert!(format!("{:?}", app.toasts).contains("Wait for the running job")); + } + + #[test] + fn finishing_a_repository_change_reloads_the_catalog() { + let mut app = app(); + let now = Instant::now(); + app.enqueue( + JobSpec::Repo(RepoChange::SetEnabled { + name: "pkgforge".to_string(), + enabled: false, + }), + now, + ); + let effects = app.update(finished(0, true, "Repository pkgforge disabled"), now); + assert!(matches!( + effects.as_slice(), + [ + Effect::RebuildContext, + Effect::LoadRepos, + Effect::LoadCatalog { .. }, + Effect::LoadInstalled { .. } + ] + )); + } + + #[test] + fn editing_the_config_reloads_the_context_and_the_views() { + let mut app = app(); + let now = Instant::now(); + let effects = app.update(Msg::Edited(app.env.config_path.clone()), now); + assert!(matches!( + effects.as_slice(), + [ + Effect::RebuildContext, + Effect::LoadRepos, + Effect::LoadCatalog { .. }, + Effect::LoadInstalled { .. } + ] + )); + assert!(app.dirty); + } + + #[test] + fn editing_another_file_only_redraws() { + let mut app = app(); + let now = Instant::now(); + let effects = app.update(Msg::Edited(PathBuf::from("/tmp/other.toml")), now); + assert!(effects.is_empty()); + assert!(app.dirty); + } + + #[test] + fn n_with_an_existing_packages_file_does_nothing() { + let mut app = app(); + let now = Instant::now(); + app.view = ViewId::Apply; + app.update(apply_loaded(apply_plan()), now); + let effects = app.update(key('n'), now); + assert!(effects.is_empty()); + } + + #[test] + fn n_with_a_missing_packages_file_enqueues_the_create_job() { + let mut app = app(); + let now = Instant::now(); + app.view = ViewId::Apply; + let mut missing = apply_plan(); + missing.diff = None; + app.update(apply_loaded(missing), now); + let effects = app.update(key('n'), now); + assert!(matches!( + effects.as_slice(), + [Effect::StartJob { + spec: JobSpec::CreatePackagesConfig, + .. + }] + )); + } + + #[test] + fn e_opens_the_packages_file_in_the_editor() { + let mut app = app(); + let now = Instant::now(); + app.view = ViewId::Apply; + let plan = apply_plan(); + let path = plan.path.clone(); + app.update(apply_loaded(plan), now); + let effects = app.update(key('e'), now); + assert!(matches!( + effects.as_slice(), + [Effect::Suspend(Suspended::Edit(edited))] if *edited == path + )); + } + + #[test] + fn e_before_the_plan_loads_uses_the_startup_path() { + let mut app = app(); + let now = Instant::now(); + app.view = ViewId::Apply; + let effects = app.update(key('e'), now); + assert!(matches!( + effects.as_slice(), + [Effect::Suspend(Suspended::Edit(edited))] if *edited == app.env.packages_path + )); + } + + #[test] + fn editing_the_packages_file_recomputes_the_plan() { + let mut app = app(); + let now = Instant::now(); + let effects = app.update(Msg::Edited(app.env.packages_path.clone()), now); + assert!(matches!( + effects.as_slice(), + [Effect::ComputeApplyDiff { + prune: false, + .. + }] + )); + assert!(app.apply.plan.is_loading()); + } + + #[test] + fn the_create_hint_shows_only_for_a_missing_file() { + let mut app = app(); + app.view = ViewId::Apply; + app.update(apply_loaded(apply_plan()), Instant::now()); + assert!(!app.hint_visible(&Action::CreatePackages)); + let mut missing = apply_plan(); + missing.diff = None; + app.update(apply_loaded(missing), Instant::now()); + assert!(app.hint_visible(&Action::CreatePackages)); + } + + #[test] + fn e_on_an_enabled_repo_disables_it_after_a_confirm() { + let mut app = app(); + let now = Instant::now(); + app.view = ViewId::Repos; + app.update(repos_loaded(vec![repo_row("bincache", true)]), now); + app.update(key('e'), now); + let screen = screen(&mut app, 80, 24); + assert!( + screen.contains("Its packages will no longer appear in Browse."), + "screen is {screen:?}" + ); + let effects = app.update(key('y'), now); + assert!(matches!( + effects.as_slice(), + [Effect::StartJob { + spec: JobSpec::Repo(RepoChange::SetEnabled { + enabled: false, + .. + }), + .. + }] + )); + } + + #[test] + fn e_on_a_disabled_repo_enables_it_and_queues_a_sync() { + let mut app = app(); + let now = Instant::now(); + app.view = ViewId::Repos; + app.update(repos_loaded(vec![repo_row("bincache", false)]), now); + app.update(key('e'), now); + let effects = app.update(key('y'), now); + assert!(matches!( + effects.as_slice(), + [Effect::StartJob { + spec: JobSpec::Repo(RepoChange::SetEnabled { + enabled: true, + .. + }), + .. + }] + )); + let queued = app + .jobs + .list + .iter() + .filter(|job| matches!(job.state, JobState::Queued) && job.kind == JobKind::Sync) + .count(); + assert_eq!(queued, 1); + } + + #[test] + fn d_on_a_repo_removes_it_after_a_danger_confirm() { + let mut app = app(); + let now = Instant::now(); + app.view = ViewId::Repos; + app.update(repos_loaded(vec![repo_row("bincache", true)]), now); + app.update(key('d'), now); + let screen = screen(&mut app, 80, 24); + assert!( + screen.contains("This edits config.toml."), + "screen is {screen:?}" + ); + let effects = app.update(key('y'), now); + assert!(matches!( + effects.as_slice(), + [Effect::StartJob { + spec: JobSpec::Repo(RepoChange::Remove(name)), + .. + }] if name == "bincache" + )); + } + + #[test] + fn a_on_repos_opens_the_add_repository_form() { + let mut app = app(); + let now = Instant::now(); + app.view = ViewId::Repos; + app.update(repos_loaded(vec![repo_row("bincache", true)]), now); + app.update(key('a'), now); + let screen = screen(&mut app, 80, 24); + for text in [ + "Add repository", + "Name", + "URL", + "Public key", + "Desktop integration", + "Sync interval", + "[ Add ]", + ] { + assert!(screen.contains(text), "screen is {screen:?}"); + } + } + + #[test] + fn accepting_the_add_form_queues_the_repository_and_a_sync() { + let mut app = app(); + let now = Instant::now(); + app.view = ViewId::Repos; + app.update(repos_loaded(vec![repo_row("bincache", true)]), now); + app.update(key('a'), now); + app.update( + press(KeyCode::Char('x'), KeyModifiers::NONE, KeyEventKind::Press), + now, + ); + app.update( + press(KeyCode::Tab, KeyModifiers::NONE, KeyEventKind::Press), + now, + ); + for c in "https://example.com/m.json".chars() { + app.update( + press(KeyCode::Char(c), KeyModifiers::NONE, KeyEventKind::Press), + now, + ); + } + for _ in 0..6 { + app.update( + press(KeyCode::Tab, KeyModifiers::NONE, KeyEventKind::Press), + now, + ); + } + let effects = app.update( + press(KeyCode::Enter, KeyModifiers::NONE, KeyEventKind::Press), + now, + ); + assert!(matches!( + effects.as_slice(), + [Effect::StartJob { + spec: JobSpec::Repo(RepoChange::Add(repo)), + .. + }] if repo.name == "x" + && repo.url == "https://example.com/m.json" + && repo.pubkey.is_none() + && repo.signature_verification.is_none() + && repo.enabled == Some(true) + && repo.desktop_integration == Some(true) + && repo.sync_interval.is_none() + )); + let queued = app + .jobs + .list + .iter() + .filter(|job| matches!(job.state, JobState::Queued) && job.kind == JobKind::Sync) + .count(); + assert_eq!(queued, 1); + } + + #[test] + fn a_failed_job_marks_attention_until_the_jobs_view_opens() { + let mut app = app(); + let now = Instant::now(); + app.enqueue(JobSpec::Sync, now); + app.update(finished(0, false, "Sync failed"), now); + assert!(app.jobs.attention); + assert!(app.jobs_attention()); + app.update( + press(KeyCode::Char('7'), KeyModifiers::NONE, KeyEventKind::Press), + now, + ); + assert!(!app.jobs.attention); + assert!(!app.jobs_attention()); + } + + #[test] + fn download_progress_while_a_job_runs_updates_that_jobs_tracker() { + let mut app = app(); + let now = Instant::now(); + app.enqueue(JobSpec::Sync, now); + app.dirty = false; + app.update( + Msg::Soar(SoarEvent::DownloadProgress { + op_id: 7, + pkg_name: "bat".to_string(), + current: 250, + total: 1000, + }), + now, + ); + assert!(app.dirty); + let job = app.running_job().unwrap(); + assert_eq!(job.tracker.ops.len(), 1); + assert_eq!(job.tracker.ops[0].name, "bat"); + assert_eq!( + job.tracker.ops[0].phase, + Phase::Downloading { + current: 250, + total: 1000 + } + ); + assert!(app.background.ops.is_empty()); + } + + #[test] + fn soar_events_without_a_running_job_reach_the_background_tracker() { + let mut app = app(); + let now = Instant::now(); + app.update( + Msg::Soar(SoarEvent::SyncProgress { + repo_name: "bincache".to_string(), + stage: SyncStage::Fetching, + }), + now, + ); + assert_eq!( + app.background.sync, + vec![("bincache".to_string(), "fetching".to_string())] + ); + assert!(app.background.ops.is_empty()); + } + + #[test] + fn q_with_a_running_job_opens_the_guard_instead_of_quitting() { + let mut app = app(); + let now = Instant::now(); + app.enqueue(JobSpec::Sync, now); + app.update( + press(KeyCode::Char('q'), KeyModifiers::NONE, KeyEventKind::Press), + now, + ); + assert!(!app.quit); + assert!(matches!(app.overlay, Some(Overlay::QuitGuard(_)))); + } + + #[test] + fn waiting_and_quitting_finishes_the_job_then_quits() { + let mut app = app(); + let now = Instant::now(); + app.enqueue(JobSpec::Sync, now); + app.jobs.list.push(crate::jobs::Job { + id: 1, + kind: crate::jobs::JobKind::Sync, + title: "Sync repositories".into(), + state: JobState::Queued, + spec: None, + tracker: Default::default(), + }); + app.update( + press(KeyCode::Char('q'), KeyModifiers::NONE, KeyEventKind::Press), + now, + ); + // Right moves to wait and quit, enter accepts it. + for code in [KeyCode::Right, KeyCode::Enter] { + app.update(press(code, KeyModifiers::NONE, KeyEventKind::Press), now); + } + assert!(app.quit_when_idle); + assert_eq!(app.queued_count(), 0); + assert!(format!("{:?}", app.toasts).contains("Quitting after the current job finishes")); + assert!(!app.quit); + app.update(finished(0, true, "Synced 3 repositories"), now); + assert!(app.quit); + } + + #[test] + fn q_while_waiting_offers_force_quit() { + let mut app = app(); + let now = Instant::now(); + app.enqueue(JobSpec::Sync, now); + app.update( + press(KeyCode::Char('q'), KeyModifiers::NONE, KeyEventKind::Press), + now, + ); + for code in [KeyCode::Right, KeyCode::Enter] { + app.update(press(code, KeyModifiers::NONE, KeyEventKind::Press), now); + } + assert!(app.quit_when_idle); + app.update( + press(KeyCode::Char('q'), KeyModifiers::NONE, KeyEventKind::Press), + now, + ); + assert!(matches!(app.overlay, Some(Overlay::Confirm(_)))); + assert!(!app.quit); + app.update( + press(KeyCode::Char('y'), KeyModifiers::NONE, KeyEventKind::Press), + now, + ); + assert!(app.quit); + } + + #[test] + fn ctrl_x_with_a_running_install_opens_the_abort_confirm() { + let mut app = app(); + let now = Instant::now(); + app.enqueue(install_spec("bat"), now); + app.update( + press( + KeyCode::Char('x'), + KeyModifiers::CONTROL, + KeyEventKind::Press, + ), + now, + ); + assert!(matches!(app.overlay, Some(Overlay::Confirm(_)))); + let screen = screen(&mut app, 80, 24); + assert!( + screen.contains("Abort Install bat?"), + "screen is {screen:?}" + ); + assert!( + screen.contains("Packages that already finished stay installed."), + "screen is {screen:?}" + ); + } + + #[test] + fn accepting_the_abort_confirm_sets_aborting_and_returns_the_effect() { + let mut app = app(); + let now = Instant::now(); + app.enqueue(install_spec("bat"), now); + app.update(ctrl('x'), now); + let effects = app.update(key('y'), now); + assert!(matches!(effects.as_slice(), [Effect::AbortJob])); + assert!(app.overlay.is_none()); + assert!(matches!( + app.running_job().map(|job| &job.state), + Some(JobState::Running { + aborting: true, + .. + }) + )); + app.update(ctrl('x'), now); + assert!(app.overlay.is_none()); + } + + #[test] + fn the_abort_confirm_retires_when_its_job_finishes() { + let mut app = app(); + let now = Instant::now(); + app.enqueue(install_spec("bat"), now); + app.update(ctrl('x'), now); + assert!(matches!(app.overlay, Some(Overlay::Confirm(_)))); + assert_eq!(app.abort_pick, Some(0)); + app.enqueue(install_spec("fd"), now); + app.update(finished(0, true, "Installed bat 1.0.0"), now); + assert!(app.overlay.is_none(), "the confirm cannot outlive its job"); + assert!(app.abort_pick.is_none()); + assert!(matches!(app.jobs.list[1].state, JobState::Running { .. })); + } + + #[test] + fn accepting_a_retired_abort_confirm_cannot_stop_the_next_job() { + let mut app = app(); + let now = Instant::now(); + app.enqueue(install_spec("bat"), now); + app.update(ctrl('x'), now); + app.enqueue(install_spec("fd"), now); + app.update(finished(0, true, "Installed bat 1.0.0"), now); + let effects = app.update(key('y'), now); + assert!(effects.is_empty()); + assert!(matches!( + app.running_job().map(|job| &job.state), + Some(JobState::Running { + aborting: false, + .. + }) + )); + } + + #[test] + fn ctrl_x_with_a_running_sync_says_it_cannot_be_aborted() { + let mut app = app(); + let now = Instant::now(); + app.enqueue(JobSpec::Sync, now); + let effects = app.update( + press( + KeyCode::Char('x'), + KeyModifiers::CONTROL, + KeyEventKind::Press, + ), + now, + ); + assert!(effects.is_empty()); + assert!(app.overlay.is_none()); + assert!(format!("{:?}", app.toasts).contains("Sync cannot be aborted")); + } + + #[test] + fn ctrl_x_with_nothing_running_says_so() { + let mut app = app(); + let now = Instant::now(); + let effects = app.update( + press( + KeyCode::Char('x'), + KeyModifiers::CONTROL, + KeyEventKind::Press, + ), + now, + ); + assert!(effects.is_empty()); + assert!(app.overlay.is_none()); + assert!(format!("{:?}", app.toasts).contains("Nothing is running")); + } + + #[test] + fn abort_and_quit_stops_the_job_then_quits_when_it_stops() { + let mut app = app(); + let now = Instant::now(); + app.enqueue(install_spec("bat"), now); + app.enqueue(JobSpec::CleanCache, now); + app.update( + press(KeyCode::Char('q'), KeyModifiers::NONE, KeyEventKind::Press), + now, + ); + // Right twice moves to abort and quit, enter accepts it. + let mut effects = Vec::new(); + for code in [KeyCode::Right, KeyCode::Right, KeyCode::Enter] { + effects = app.update(press(code, KeyModifiers::NONE, KeyEventKind::Press), now); + } + assert!(matches!(effects.as_slice(), [Effect::AbortJob])); + assert!(app.quit_when_idle); + assert_eq!(app.queued_count(), 0); + assert!(matches!( + app.running_job().map(|job| &job.state), + Some(JobState::Running { + aborting: true, + .. + }) + )); + app.update(finished(0, true, "Installed bat 1.0.0"), now); + assert!(app.quit); + } + + #[test] + fn abort_and_quit_with_a_running_sync_waits_instead() { + let mut app = app(); + let now = Instant::now(); + app.enqueue(JobSpec::Sync, now); + app.update( + press(KeyCode::Char('q'), KeyModifiers::NONE, KeyEventKind::Press), + now, + ); + let mut effects = Vec::new(); + for code in [KeyCode::Right, KeyCode::Right, KeyCode::Enter] { + effects = app.update(press(code, KeyModifiers::NONE, KeyEventKind::Press), now); + } + assert!(effects.is_empty()); + assert!(app.quit_when_idle); + assert!(matches!( + app.running_job().map(|job| &job.state), + Some(JobState::Running { + aborting: false, + .. + }) + )); + app.update(finished(0, true, "Repositories synced"), now); + assert!(app.quit); + } + + #[test] + fn an_aborted_job_toasts_as_a_warning_without_attention() { + let mut app = app(); + let now = Instant::now(); + app.enqueue(JobSpec::Sync, now); + app.update( + Msg::JobFinished { + id: 0, + outcome: JobOutcome { + ok: true, + aborted: true, + headline: "Aborted: 1 installed, 2 skipped".to_string(), + lines: Vec::new(), + }, + }, + now, + ); + let debug = format!("{:?}", app.toasts); + assert!(debug.contains("Warning"), "toasts are {debug:?}"); + assert!(debug.contains("Aborted: 1 installed, 2 skipped")); + assert!(!app.jobs.attention); + } + + #[test] + fn x_on_a_queued_job_removes_it_from_the_queue() { + let mut app = app(); + let now = Instant::now(); + app.enqueue(JobSpec::Sync, now); + app.enqueue(JobSpec::CleanCache, now); + app.view = ViewId::Jobs; + app.update( + press(KeyCode::Char('x'), KeyModifiers::NONE, KeyEventKind::Press), + now, + ); + assert_eq!(app.jobs.list.len(), 1); + assert_eq!(app.queued_count(), 0); + assert!( + format!("{:?}", app.toasts).contains("Removed Clean cache from the queue"), + "toasts are {:?}", + app.toasts + ); + } + + #[test] + fn x_on_a_finished_job_changes_nothing() { + let mut app = app(); + let now = Instant::now(); + app.enqueue(JobSpec::Sync, now); + app.update(finished(0, true, "Repositories synced"), now); + app.view = ViewId::Jobs; + let toasts_before = app.toasts.iter().count(); + app.update( + press(KeyCode::Char('x'), KeyModifiers::NONE, KeyEventKind::Press), + now, + ); + assert_eq!(app.jobs.list.len(), 1); + assert_eq!(app.toasts.iter().count(), toasts_before); + } + + #[test] + fn i_on_a_not_installed_row_resolves_its_exact_query() { + let mut app = app(); + let now = Instant::now(); + app.update( + catalog_loaded(vec![catalog_row("bat", "0.24.0", "bincache")]), + now, + ); + let effects = app.update(key('i'), now); + assert_eq!(resolve_of(&effects), &["bat@0.24.0:bincache".to_string()]); + assert!(app.pending.is_none()); + } + + #[test] + fn i_on_an_installed_row_only_toasts() { + let mut rows = vec![catalog_row("bat", "0.24.0", "bincache")]; + rows[0].installed = true; + let mut app = app(); + let now = Instant::now(); + app.update(catalog_loaded(rows), now); + let effects = app.update(key('i'), now); + assert!(effects.is_empty()); + assert!(app.pending.is_none()); + assert!( + format!("{:?}", app.toasts) + .contains("bat is already installed. Use I and Force reinstall to reinstall."), + "toasts are {:?}", + app.toasts + ); + } + + #[test] + fn i_reports_installed_rows_and_resolves_the_rest() { + let mut rows = vec![ + catalog_row("bat", "0.24.0", "bincache"), + catalog_row("fd", "10.2.0", "bincache"), + catalog_row("jq", "1.7.1", "bincache"), + ]; + rows[0].installed = true; + rows[1].installed = true; + let mut app = app(); + let now = Instant::now(); + app.update(catalog_loaded(rows), now); + for _ in 0..3 { + app.update(key(' '), now); + } + let effects = app.update(key('i'), now); + assert_eq!(resolve_of(&effects), &["jq@1.7.1:bincache".to_string()]); + assert!( + format!("{:?}", app.toasts).contains( + "2 packages are already installed. Use I and Force reinstall to reinstall." + ), + "toasts are {:?}", + app.toasts + ); + } + + #[test] + fn a_resolved_target_opens_a_confirm_and_y_installs() { + let mut app = app(); + let now = Instant::now(); + app.update( + catalog_loaded(vec![ + catalog_row("bat", "0.24.0", "bincache"), + catalog_row("fd", "10.2.0", "pkgforge"), + ]), + now, + ); + app.update(key(' '), now); + let effects = app.update(key('i'), now); + assert_eq!(resolve_of(&effects), &["bat@0.24.0:bincache".to_string()]); + let effects = app.update( + resolved(vec![Resolution::Ready(vec![target(package( + "bat", "0.24.0", "bincache", + ))])]), + now, + ); + assert!(effects.is_empty()); + assert!(app.pending.is_some()); + assert!(matches!(app.overlay, Some(Overlay::Confirm(_)))); + let open = screen(&mut app, 80, 24); + assert!(open.contains("Install bat"), "screen is {open:?}"); + let effects = app.update(key('y'), now); + let [ + Effect::StartJob { + spec: + JobSpec::Install { + targets, + picked, + .. + }, + .. + }, + ] = &effects[..] + else { + panic!("expected the install to start"); + }; + assert_eq!(targets.len(), 1); + assert!(picked.is_empty()); + assert!(app.pending.is_none()); + assert!(app.overlay.is_none()); + assert!(app.browse.marks.is_empty()); + } + + #[test] + fn an_ambiguous_query_opens_a_picker_then_the_confirm() { + let mut app = app(); + let now = Instant::now(); + app.update( + catalog_loaded(vec![catalog_row("ffmpeg", "7.1", "bincache")]), + now, + ); + app.update(key('i'), now); + let mut old = package("ffmpeg", "7.0.2", "pkgcache"); + old.pkg_family = Some("jellyfin".to_string()); + app.update( + resolved(vec![Resolution::Ambiguous { + query: "ffmpeg".to_string(), + candidates: vec![package("ffmpeg", "7.1", "bincache"), old], + }]), + now, + ); + assert!(app.pending.is_some()); + assert!(matches!(app.overlay, Some(Overlay::Picker(_)))); + let picker = screen(&mut app, 80, 24); + assert!( + picker.contains("Choose a variant of \"ffmpeg\""), + "screen is {picker:?}" + ); + assert!( + picker.contains("jellyfin/ffmpeg 7.0.2"), + "screen is {picker:?}" + ); + app.update(key('j'), now); + let effects = app.update(code(KeyCode::Enter), now); + assert!(effects.is_empty()); + assert!(matches!(app.overlay, Some(Overlay::Confirm(_)))); + let effects = app.update(key('y'), now); + let [ + Effect::StartJob { + spec: JobSpec::Install { + picked, .. + }, + .. + }, + ] = &effects[..] + else { + panic!("expected the install to start"); + }; + assert_eq!(picked.len(), 1); + assert_eq!(picked[0].version, "7.0.2"); + } + + #[test] + fn esc_on_the_variant_picker_drops_the_query_and_the_flow() { + let mut app = app(); + let now = Instant::now(); + app.update( + catalog_loaded(vec![catalog_row("ffmpeg", "7.1", "bincache")]), + now, + ); + app.update(key('i'), now); + app.update( + resolved(vec![Resolution::Ambiguous { + query: "ffmpeg".to_string(), + candidates: vec![package("ffmpeg", "7.1", "bincache")], + }]), + now, + ); + assert!(matches!(app.overlay, Some(Overlay::Picker(_)))); + app.update(code(KeyCode::Esc), now); + assert!(app.overlay.is_none()); + assert!(app.pending.is_none()); + assert!(app.jobs.list.is_empty()); + } + + #[test] + fn esc_moves_through_the_queries_and_the_confirm_cancel_ends_the_flow() { + let mut app = app(); + let now = Instant::now(); + app.update( + catalog_loaded(vec![catalog_row("ffmpeg", "7.1", "bincache")]), + now, + ); + app.update(key('i'), now); + app.update( + resolved(vec![ + Resolution::Ambiguous { + query: "ffmpeg".to_string(), + candidates: vec![package("ffmpeg", "7.1", "bincache")], + }, + Resolution::Ambiguous { + query: "python".to_string(), + candidates: vec![package("python", "3.12.0", "pkgcache")], + }, + ]), + now, + ); + assert!(matches!(app.overlay, Some(Overlay::Picker(_)))); + app.update(code(KeyCode::Esc), now); + let picker = screen(&mut app, 80, 24); + assert!( + picker.contains("Choose a variant of \"python\""), + "screen is {picker:?}" + ); + assert!(app.pending.is_some()); + app.update(code(KeyCode::Enter), now); + assert!(matches!(app.overlay, Some(Overlay::Confirm(_)))); + app.update(code(KeyCode::Esc), now); + assert!(app.overlay.is_none()); + assert!(app.pending.is_none()); + assert!(app.jobs.list.is_empty()); + } + + #[test] + fn the_options_form_with_force_resolves_an_installed_row() { + let mut rows = vec![catalog_row("bat", "0.24.0", "bincache")]; + rows[0].installed = true; + let mut app = app(); + let now = Instant::now(); + app.update(catalog_loaded(rows), now); + app.update(key('I'), now); + assert!(matches!(app.overlay, Some(Overlay::Form(_)))); + let open = screen(&mut app, 80, 24); + assert!( + open.contains("Install bat with options"), + "screen is {open:?}" + ); + app.update(key(' '), now); + for _ in 0..6 { + app.update(code(KeyCode::Tab), now); + } + let effects = app.update(code(KeyCode::Enter), now); + let [ + Effect::Resolve { + choices, .. + }, + ] = &effects[..] + else { + panic!("expected a resolve"); + }; + assert!(choices.force); + assert_eq!(resolve_of(&effects), &["bat@0.24.0:bincache".to_string()]); + } + + #[test] + fn the_confirm_lists_sizes_and_the_options_summary() { + let mut app = app(); + let now = Instant::now(); + app.update( + catalog_loaded(vec![catalog_row("bat", "0.24.0", "bincache")]), + now, + ); + app.update(key('I'), now); + app.update(key(' '), now); + app.update(code(KeyCode::Tab), now); + app.update(key(' '), now); + for _ in 0..5 { + app.update(code(KeyCode::Tab), now); + } + let effects = app.update(code(KeyCode::Enter), now); + let [ + Effect::Resolve { + choices, .. + }, + ] = &effects[..] + else { + panic!("expected a resolve"); + }; + let mut bat = package("bat", "0.24.0", "bincache"); + bat.ghcr_size = Some(1_048_576); + app.update( + Msg::Loaded(Loaded::Resolved { + choices: choices.clone(), + result: Ok(vec![Resolution::Ready(vec![target(bat)])]), + }), + now, + ); + assert!(matches!(app.overlay, Some(Overlay::Confirm(_)))); + let open = screen(&mut app, 80, 24); + assert!( + open.contains("bat 0.24.0 bincache 1.0 MiB"), + "screen is {open:?}" + ); + assert!( + open.contains("Options: force, binary only"), + "screen is {open:?}" + ); + assert!( + open.contains("Download size: 1.0 MiB"), + "screen is {open:?}" + ); + } + + #[test] + fn picking_the_second_version_targets_that_version() { + let mut row = catalog_row("bat", "0.24.0", "bincache"); + row.other_versions = vec!["0.23.0".to_string()]; + let mut app = app(); + let now = Instant::now(); + app.update(catalog_loaded(vec![row]), now); + app.update(key('v'), now); + assert!(matches!(app.overlay, Some(Overlay::Picker(_)))); + let picker = screen(&mut app, 80, 24); + assert!(picker.contains("Versions of bat"), "screen is {picker:?}"); + assert!(picker.contains("latest"), "screen is {picker:?}"); + app.update(key('j'), now); + let effects = app.update(code(KeyCode::Enter), now); + assert_eq!(resolve_of(&effects), &["bat@0.23.0:bincache".to_string()]); + } + + #[test] + fn a_version_pick_survives_a_catalog_reload_under_the_picker() { + let mut bat = catalog_row("bat", "0.24.0", "bincache"); + bat.other_versions = vec!["0.23.0".to_string()]; + let fd = catalog_row("fd", "10.2.0", "pkgforge"); + let mut app = app(); + let now = Instant::now(); + app.update(catalog_loaded(vec![fd, bat]), now); + app.update(key('j'), now); + app.update(key('v'), now); + assert!(matches!(app.overlay, Some(Overlay::Picker(_)))); + // The catalog swaps while the picker is open, moving the cursor. + app.update( + catalog_loaded(vec![catalog_row("jq", "1.7.1", "bincache")]), + now, + ); + assert_eq!(app.browse.cursor.selected, 0); + app.update(key('j'), now); + let effects = app.update(code(KeyCode::Enter), now); + assert_eq!( + resolve_of(&effects), + &["bat@0.23.0:bincache".to_string()], + "the pick must target the package the picker named" + ); + } + + #[test] + fn the_run_prompt_runs_the_package_it_was_opened_for() { + let mut app = app(); + let now = Instant::now(); + app.update( + catalog_loaded(vec![ + catalog_row("jq", "1.7.1", "bincache"), + catalog_row("fd", "10.2.0", "pkgforge"), + ]), + now, + ); + app.update(key('j'), now); + app.update(key('x'), now); + let prompt = screen(&mut app, 80, 24); + assert!( + prompt.contains("Run fd with arguments"), + "screen is {prompt:?}" + ); + // The catalog swaps while the prompt is open, moving the cursor. + app.update( + catalog_loaded(vec![catalog_row("jq", "1.7.1", "bincache")]), + now, + ); + for c in ['-', 'v', 'e'] { + app.update(key(c), now); + } + let effects = app.update(code(KeyCode::Enter), now); + let [ + Effect::PrepareRun { + query, + args, + .. + }, + ] = &effects[..] + else { + panic!("expected a run"); + }; + assert_eq!(query, "fd:pkgforge", "the prompt's package runs"); + assert_eq!(args, &["-ve".to_string()]); + } + + #[test] + fn v_without_other_versions_says_so() { + let mut app = app(); + let now = Instant::now(); + app.update( + catalog_loaded(vec![catalog_row("bat", "0.24.0", "bincache")]), + now, + ); + let effects = app.update(key('v'), now); + assert!(effects.is_empty()); + assert!(app.overlay.is_none()); + assert!( + format!("{:?}", app.toasts).contains("bat has only one version"), + "toasts are {:?}", + app.toasts + ); + } + + #[test] + fn the_prompt_splits_its_text_into_queries() { + let mut app = app(); + let now = Instant::now(); + app.update( + catalog_loaded(vec![catalog_row("bat", "0.24.0", "bincache")]), + now, + ); + app.update(key('+'), now); + assert!(matches!(app.overlay, Some(Overlay::Prompt(_)))); + for c in "bat ".chars() { + app.update(key(c), now); + } + for c in "https://example.com/x.AppImage".chars() { + app.update(key(c), now); + } + let effects = app.update(code(KeyCode::Enter), now); + let queries = resolve_of(&effects); + assert_eq!(queries.len(), 2); + assert_eq!(queries[0], "bat"); + assert_eq!(queries[1], "https://example.com/x.AppImage"); + } + + /// The one prepare-run the effects hold, failing the test otherwise. + fn prepare_run_of( + effects: &[Effect], + ) -> (&String, &Option, &Option, &Vec) { + let [ + Effect::PrepareRun { + query, + repo, + pkg_id, + args, + }, + ] = effects + else { + panic!("expected one prepare run"); + }; + (query, repo, pkg_id, args) + } + + /// A run-ready result with the given arguments. + fn run_ready(result: Result, args: Vec) -> Msg { + Msg::Loaded(Loaded::RunReady { + args, + result: Box::new(result), + }) + } + + #[test] + fn x_on_a_row_opens_the_run_prompt_asking_for_arguments() { + let mut app = app(); + let now = Instant::now(); + app.update( + catalog_loaded(vec![catalog_row("jq", "1.7.1", "bincache")]), + now, + ); + let effects = app.update(key('x'), now); + assert!(effects.is_empty()); + assert!(matches!(app.overlay, Some(Overlay::Prompt(_)))); + let open = screen(&mut app, 80, 24); + assert!(open.contains("Run jq with arguments"), "screen is {open:?}"); + assert!( + open.contains("args are split on spaces"), + "screen is {open:?}" + ); + } + + #[test] + fn x_without_a_row_opens_nothing() { + let mut app = app(); + let now = Instant::now(); + let effects = app.update(key('x'), now); + assert!(effects.is_empty()); + assert!(app.overlay.is_none()); + } + + #[test] + fn accepting_the_run_prompt_prepares_the_rows_exact_query_with_the_arguments() { + let mut row = catalog_row("ffmpeg", "7.1", "bincache"); + row.key.pkg_family = Some("jellyfin".to_string()); + row.key.pkg_id = Some("ffmpeg-1".to_string()); + let mut app = app(); + let now = Instant::now(); + app.update(catalog_loaded(vec![row]), now); + app.update(key('x'), now); + for c in "--version".chars() { + app.update(key(c), now); + } + let effects = app.update(code(KeyCode::Enter), now); + let (query, repo, pkg_id, args) = prepare_run_of(&effects); + assert_eq!(query, "jellyfin/ffmpeg:bincache"); + assert_eq!(repo.as_deref(), Some("bincache")); + assert_eq!(pkg_id.as_deref(), Some("ffmpeg-1")); + assert_eq!(args, &["--version".to_string()]); + assert!(app.overlay.is_none()); + } + + #[test] + fn accepting_the_run_prompt_without_arguments_prepares_an_empty_run() { + let mut app = app(); + let now = Instant::now(); + app.update( + catalog_loaded(vec![catalog_row("jq", "1.7.1", "bincache")]), + now, + ); + app.update(key('x'), now); + let effects = app.update(code(KeyCode::Enter), now); + let (query, repo, pkg_id, args) = prepare_run_of(&effects); + assert_eq!(query, "jq:bincache"); + assert_eq!(repo.as_deref(), Some("bincache")); + assert!(pkg_id.is_none()); + assert!(args.is_empty()); + } + + #[test] + fn a_ready_run_suspends_to_execute_the_binary_with_the_arguments() { + let mut app = app(); + let now = Instant::now(); + let effects = app.update( + run_ready( + Ok(PrepareRunResult::Ready { + path: PathBuf::from("/cache/bin/jq"), + downloaded: false, + }), + vec!["--version".to_string()], + ), + now, + ); + let [ + Effect::Suspend(Suspended::Exec { + path, + args, + }), + ] = &effects[..] + else { + panic!("expected a suspend"); + }; + assert_eq!(path, &PathBuf::from("/cache/bin/jq")); + assert_eq!(args, &["--version".to_string()]); + assert!(app.dirty); + } + + #[test] + fn an_ambiguous_run_opens_a_picker_and_reruns_the_chosen_variant() { + let mut chosen = package("ffmpeg", "7.1", "bincache"); + chosen.pkg_id = Some("ffmpeg-1".to_string()); + let mut other = package("ffmpeg", "7.0.2", "pkgcache"); + other.pkg_family = Some("jellyfin".to_string()); + let mut app = app(); + let now = Instant::now(); + app.update( + run_ready( + Ok(PrepareRunResult::Ambiguous(AmbiguousPackage { + query: "ffmpeg".to_string(), + candidates: vec![chosen, other], + })), + vec!["-i".to_string()], + ), + now, + ); + assert!(matches!(app.overlay, Some(Overlay::Picker(_)))); + assert!(app.run_pick.is_some()); + let picker = screen(&mut app, 80, 24); + assert!( + picker.contains("Choose a variant of \"ffmpeg\""), + "screen is {picker:?}" + ); + assert!( + picker.contains("jellyfin/ffmpeg 7.0.2"), + "screen is {picker:?}" + ); + let effects = app.update(code(KeyCode::Enter), now); + let (query, repo, pkg_id, args) = prepare_run_of(&effects); + assert_eq!(query, "ffmpeg@7.1:bincache"); + assert_eq!(repo.as_deref(), Some("bincache")); + assert_eq!(pkg_id.as_deref(), Some("ffmpeg-1")); + assert_eq!(args, &["-i".to_string()]); + assert!(app.run_pick.is_none()); + assert!(app.overlay.is_none()); + } + + #[test] + fn esc_on_the_run_picker_drops_the_arguments_and_the_candidates() { + let mut app = app(); + let now = Instant::now(); + app.update( + run_ready( + Ok(PrepareRunResult::Ambiguous(AmbiguousPackage { + query: "ffmpeg".to_string(), + candidates: vec![package("ffmpeg", "7.1", "bincache")], + })), + Vec::new(), + ), + now, + ); + assert!(matches!(app.overlay, Some(Overlay::Picker(_)))); + app.update(code(KeyCode::Esc), now); + assert!(app.overlay.is_none()); + assert!(app.run_pick.is_none()); + assert!(app.pending.is_none()); + } + + #[test] + fn an_ambiguous_run_cannot_displace_a_password_dialog() { + let (mut app, now) = authorizing_app(); + app.update( + Msg::Loaded(Loaded::Escalation(EscalationProbe::Password)), + now, + ); + let mut chosen = package("ffmpeg", "7.1", "bincache"); + chosen.pkg_id = Some("ffmpeg-1".to_string()); + let mut other = package("ffmpeg", "7.0.2", "pkgcache"); + other.pkg_family = Some("jellyfin".to_string()); + app.update( + run_ready( + Ok(PrepareRunResult::Ambiguous(AmbiguousPackage { + query: "ffmpeg".to_string(), + candidates: vec![chosen, other], + })), + vec!["-i".to_string()], + ), + now, + ); + assert!( + matches!(app.overlay, Some(Overlay::Authorize(_))), + "the pass dialog keeps its slot" + ); + assert!(app.run_pick.is_none(), "the run waits for a retry"); + } + + #[test] + fn a_failed_run_toasts_the_error_without_an_effect() { + let mut app = app(); + let now = Instant::now(); + let effects = app.update( + run_ready(Err("no candidate found".to_string()), Vec::new()), + now, + ); + assert!(effects.is_empty()); + assert!(app.overlay.is_none()); + let toasts = format!("{:?}", app.toasts); + assert!( + toasts.contains("no candidate found"), + "toasts are {toasts:?}" + ); + } + + #[test] + fn a_redraw_message_marks_the_screen_dirty() { + let mut app = app(); + app.dirty = false; + app.update(Msg::Redraw, Instant::now()); + assert!(app.dirty); + } + + #[test] + fn a_dead_input_thread_sets_the_fatal_error_and_quits() { + let mut app = app(); + app.dirty = false; + let effects = app.update( + Msg::InputFailed("got an error from the terminal".to_string()), + Instant::now(), + ); + assert!(effects.is_empty()); + assert!(app.quit, "a deaf interface has no way to stay open"); + assert!(app.dirty); + assert_eq!(app.fatal.as_deref(), Some("got an error from the terminal")); + } + + #[test] + fn a_not_found_resolution_toasts_with_suggestions() { + let mut app = app(); + let now = Instant::now(); + app.update( + catalog_loaded(vec![catalog_row("bat", "0.24.0", "bincache")]), + now, + ); + app.update(key('i'), now); + app.update( + resolved(vec![ + Resolution::NotFound { + query: "batt".to_string(), + suggestions: vec!["bat".to_string(), "bass".to_string()], + }, + Resolution::AlreadyInstalled { + name: "fd".to_string(), + repo: "pkgforge".to_string(), + version: "10.2.0".to_string(), + }, + ]), + now, + ); + assert!(app.pending.is_none()); + assert!(app.overlay.is_none()); + let toasts = format!("{:?}", app.toasts); + assert!( + toasts.contains("Not found: batt. Did you mean bat, bass?"), + "toasts are {toasts:?}" + ); + assert!( + toasts.contains("fd is already installed"), + "toasts are {toasts:?}" + ); + } + + #[test] + fn a_failed_resolve_toasts_the_error_without_a_flow() { + let mut app = app(); + let now = Instant::now(); + app.update( + catalog_loaded(vec![catalog_row("bat", "0.24.0", "bincache")]), + now, + ); + app.update(key('i'), now); + app.update( + Msg::Loaded(Loaded::Resolved { + choices: InstallChoices::default(), + result: Err("metadata locked".to_string()), + }), + now, + ); + assert!(app.pending.is_none()); + assert!(app.overlay.is_none()); + assert!( + format!("{:?}", app.toasts).contains("metadata locked"), + "toasts are {:?}", + app.toasts + ); + } + + #[test] + fn a_finished_install_reloads_the_catalog_and_the_installed_list() { + let mut app = app(); + let now = Instant::now(); + app.enqueue(install_spec("bat"), now); + let effects = app.update(finished(0, true, "Installed bat 1.0.0"), now); + assert!(matches!( + effects.as_slice(), + [Effect::LoadCatalog { .. }, Effect::LoadInstalled { .. }] + )); + } + + #[test] + fn a_finished_remove_reloads_the_installed_list_alone() { + let mut app = app(); + let now = Instant::now(); + app.enqueue( + JobSpec::Remove { + packages: vec![crate::test_support::installed_package( + "bat", "1.0.0", "bincache", + )], + }, + now, + ); + let effects = app.update(finished(0, true, "Removed bat 1.0.0"), now); + assert!(matches!(effects.as_slice(), [Effect::LoadInstalled { .. }])); + } + + #[test] + fn a_finished_cache_clean_reloads_health() { + let mut app = app(); + let now = Instant::now(); + app.enqueue(JobSpec::CleanCache, now); + let effects = app.update(finished(0, true, "Cache cleaned"), now); + assert!(matches!(effects.as_slice(), [Effect::LoadHealth])); + assert!(app.health.report.is_loading()); + } + + #[test] + fn a_finished_remove_reloads_health_once_it_loaded() { + let mut app = app(); + let now = Instant::now(); + app.view = ViewId::Health; + app.update( + Msg::Loaded(Loaded::Health(Ok(( + crate::test_support::health_report(), + crate::test_support::health_paths(), + )))), + now, + ); + app.view = ViewId::Installed; + app.enqueue( + JobSpec::Remove { + packages: vec![installed_package("bat", "1.0.0", "bincache")], + }, + now, + ); + let effects = app.update(finished(0, true, "Removed bat 1.0.0"), now); + assert!(matches!( + effects.as_slice(), + [Effect::LoadInstalled { .. }, Effect::LoadHealth] + )); + assert!(app.health.report.is_loading()); + } + + #[test] + fn a_loaded_installed_list_replaces_the_view_state() { + let mut app = app(); + let entries = vec![crate::test_support::installed_entry( + "bat", "0.24.0", "bincache", + )]; + let total_size = entries.iter().map(|entry| entry.disk_size).sum(); + app.update( + Msg::Loaded(Loaded::Installed { + check: 0, + result: Ok(soar_operations::InstalledListResult { + packages: entries, + total_count: 1, + total_size, + }), + }), + Instant::now(), + ); + assert!(app.installed.list.ready().is_some()); + assert_eq!(app.installed.visible, vec![0]); + assert!(app.dirty); + app.dirty = false; + app.update( + Msg::Loaded(Loaded::Installed { + check: 0, + result: Err("offline".to_string()), + }), + Instant::now(), + ); + assert!(app.installed.list.ready().is_none()); + assert!(app.dirty); + } + + #[test] + fn ctrl_r_on_installed_reloads_the_installed_list() { + let mut app = app(); + app.view = ViewId::Installed; + let effects = app.update( + press( + KeyCode::Char('r'), + KeyModifiers::CONTROL, + KeyEventKind::Press, + ), + Instant::now(), + ); + assert!(matches!(effects.as_slice(), [Effect::LoadInstalled { .. }])); + assert!(app.installed.list.is_loading()); + } + + #[test] + fn s_on_the_installed_list_loads_the_rows_variants() { + let mut app = app(); + let now = Instant::now(); + app.view = ViewId::Installed; + app.update( + installed_loaded(vec![installed_entry("bat", "0.24.0", "bincache")]), + now, + ); + let effects = app.update(key('s'), now); + let [ + Effect::LoadVariants { + name, + }, + ] = &effects[..] + else { + panic!("expected a variant load"); + }; + assert_eq!(name, "bat"); + } + + #[test] + fn u_on_the_installed_list_scopes_the_updates_check() { + let mut app = app(); + let now = Instant::now(); + app.view = ViewId::Installed; + app.update( + installed_loaded(vec![installed_entry("bat", "0.24.0", "bincache")]), + now, + ); + let effects = app.update(key('u'), now); + assert_eq!(app.view, ViewId::Updates); + assert_eq!( + app.updates.scope.as_deref(), + Some(["bat".to_string()].as_slice()) + ); + assert!(matches!( + effects.as_slice(), + [Effect::CheckUpdates { names: Some(names), .. }] if names == &["bat".to_string()] + )); + } + + #[test] + fn esc_in_a_scoped_updates_list_checks_everything() { + let mut app = app(); + let now = Instant::now(); + app.view = ViewId::Installed; + app.update( + installed_loaded(vec![installed_entry("bat", "0.24.0", "bincache")]), + now, + ); + app.update(key('u'), now); + let effects = app.update(code(KeyCode::Esc), now); + assert!(app.updates.scope.is_none()); + assert!(matches!( + effects.as_slice(), + [Effect::CheckUpdates { + names: None, + .. + }] + )); + } + + #[test] + fn esc_without_a_scope_checks_nothing() { + let mut app = app(); + let now = Instant::now(); + app.view = ViewId::Updates; + let effects = app.update(code(KeyCode::Esc), now); + assert!(effects.is_empty()); + } + + #[test] + fn an_empty_variant_list_toasts_that_the_package_is_not_installed() { + let mut app = app(); + let now = Instant::now(); + let effects = app.update( + Msg::Loaded(Loaded::Variants { + name: "bat".to_string(), + result: Box::new(Ok(Vec::new())), + }), + now, + ); + assert!(effects.is_empty()); + assert!(app.overlay.is_none()); + assert!(app.variant_pick.is_none()); + let toasts = format!("{:?}", app.toasts); + assert!( + toasts.contains("bat is not installed"), + "toasts are {toasts:?}" + ); + assert!(toasts.contains("Info"), "toasts are {toasts:?}"); + } + + #[test] + fn a_sole_active_variant_toasts_that_no_other_exists() { + let mut app = app(); + let now = Instant::now(); + let effects = app.update( + variants_loaded("bat", vec![variant(7, "bat", "0.24.0", "bincache", true)]), + now, + ); + assert!(effects.is_empty()); + assert!(app.overlay.is_none()); + assert!(app.variant_pick.is_none()); + assert!(format!("{:?}", app.toasts).contains("bat has no other variants")); + } + + #[test] + fn a_sole_inactive_variant_confirms_then_switches_to_it() { + let mut app = app(); + let now = Instant::now(); + let effects = app.update( + variants_loaded("bat", vec![variant(7, "bat", "0.24.0", "bincache", false)]), + now, + ); + assert!(effects.is_empty()); + assert!(app.variant_pick.is_none()); + assert!(matches!(app.overlay, Some(Overlay::Confirm(_)))); + let open = screen(&mut app, 80, 24); + assert!(open.contains("Switch bat to 0.24.0"), "screen is {open:?}"); + assert!(open.contains("bat 0.24.0 bincache"), "screen is {open:?}"); + let effects = app.update(key('y'), now); + let [ + Effect::StartJob { + spec: + JobSpec::Switch { + id, + name, + }, + .. + }, + ] = &effects[..] + else { + panic!("expected the switch to start"); + }; + assert_eq!(*id, 7); + assert_eq!(name, "bat"); + assert!(app.overlay.is_none()); + } + + #[test] + fn several_variants_open_a_picker_and_the_inactive_one_switches() { + let mut app = app(); + let now = Instant::now(); + let mut active = variant(7, "bat", "0.24.0", "bincache", true); + active.package.pkg_family = Some("jellyfin".to_string()); + let other = variant(9, "bat", "0.23.0", "pkgcache", false); + let effects = app.update(variants_loaded("bat", vec![active, other]), now); + assert!(effects.is_empty()); + assert!(app.variant_pick.is_some()); + assert!(matches!(app.overlay, Some(Overlay::Picker(_)))); + let open = screen(&mut app, 80, 24); + assert!(open.contains("Variants of bat"), "screen is {open:?}"); + assert!(open.contains("jellyfin/bat 0.24.0"), "screen is {open:?}"); + assert!(open.contains("● active"), "screen is {open:?}"); + app.update(key('j'), now); + let effects = app.update(code(KeyCode::Enter), now); + let [ + Effect::StartJob { + spec: + JobSpec::Switch { + id, + name, + }, + .. + }, + ] = &effects[..] + else { + panic!("expected the switch to start"); + }; + assert_eq!(*id, 9); + assert_eq!(name, "bat"); + assert!(app.variant_pick.is_none()); + assert!(app.overlay.is_none()); + } + + #[test] + fn picking_the_active_variant_closes_without_a_job() { + let mut app = app(); + let now = Instant::now(); + let active = variant(7, "bat", "0.24.0", "bincache", true); + let other = variant(9, "bat", "0.23.0", "pkgcache", false); + app.update(variants_loaded("bat", vec![active, other]), now); + assert!(matches!(app.overlay, Some(Overlay::Picker(_)))); + let effects = app.update(code(KeyCode::Enter), now); + assert!(effects.is_empty()); + assert!(app.jobs.list.is_empty()); + assert!(app.variant_pick.is_none()); + assert!(app.overlay.is_none()); + } + + #[test] + fn a_variants_picker_cannot_displace_a_password_dialog() { + let (mut app, now) = authorizing_app(); + app.update( + Msg::Loaded(Loaded::Escalation(EscalationProbe::Password)), + now, + ); + let active = variant(7, "bat", "0.24.0", "bincache", true); + let other = variant(9, "bat", "0.23.0", "pkgcache", false); + app.update(variants_loaded("bat", vec![active, other]), now); + assert!( + matches!(app.overlay, Some(Overlay::Authorize(_))), + "the pass dialog keeps its slot" + ); + assert!(app.variant_pick.is_none(), "the switch waits for a retry"); + } + + #[test] + fn a_sole_variant_switch_cannot_displace_a_password_dialog() { + let (mut app, now) = authorizing_app(); + app.update( + Msg::Loaded(Loaded::Escalation(EscalationProbe::Password)), + now, + ); + let effects = app.update( + variants_loaded("bat", vec![variant(7, "bat", "0.24.0", "bincache", false)]), + now, + ); + assert!(effects.is_empty()); + assert!( + matches!(app.overlay, Some(Overlay::Authorize(_))), + "the pass dialog keeps its slot" + ); + assert!(app.variant_pick.is_none(), "the switch waits for a retry"); + let toasts = format!("{:?}", app.toasts); + assert!( + toasts.contains("Try again once it finishes"), + "toasts are {toasts:?}" + ); + } + + #[test] + fn esc_on_the_variants_picker_drops_the_flow() { + let mut app = app(); + let now = Instant::now(); + let active = variant(7, "bat", "0.24.0", "bincache", true); + let other = variant(9, "bat", "0.23.0", "pkgcache", false); + app.update(variants_loaded("bat", vec![active, other]), now); + app.update(code(KeyCode::Esc), now); + assert!(app.overlay.is_none()); + assert!(app.variant_pick.is_none()); + assert!(app.jobs.list.is_empty()); + } + + #[test] + fn a_failed_variant_load_toasts_the_error() { + let mut app = app(); + let now = Instant::now(); + let effects = app.update( + Msg::Loaded(Loaded::Variants { + name: "bat".to_string(), + result: Box::new(Err("metadata locked".to_string())), + }), + now, + ); + assert!(effects.is_empty()); + assert!(app.overlay.is_none()); + let toasts = format!("{:?}", app.toasts); + assert!(toasts.contains("metadata locked"), "toasts are {toasts:?}"); + assert!(toasts.contains("Error"), "toasts are {toasts:?}"); + } + + /// A ready updates list holding the given entries, answering the + /// current check. + fn updates_loaded(app: &App, list: Vec) -> Msg { + Msg::Loaded(Loaded::Updates { + check: app.updates.check, + result: Ok(list), + }) + } + + /// Three checked updates, the usual fixtures. + fn three_updates() -> Vec { + vec![ + update_info("bat", "0.23.0", "0.24.0", "bincache"), + update_info("fd", "10.1.0", "10.2.0", "bincache"), + update_info("yq", "4.44.2", "4.44.3", "bincache"), + ] + } + + #[test] + fn u_with_two_of_three_marked_confirms_then_updates_those_two() { + let mut app = app(); + let now = Instant::now(); + app.view = ViewId::Updates; + app.update(updates_loaded(&app, three_updates()), now); + app.update(key(' '), now); + app.update(key(' '), now); + assert_eq!(app.updates.marks, [0, 1].into_iter().collect()); + let effects = app.update(key('u'), now); + assert!(effects.is_empty()); + assert!(matches!(app.overlay, Some(Overlay::Confirm(_)))); + assert_eq!(app.update_pick.as_deref(), Some(&[0, 1][..])); + let open = screen(&mut app, 80, 24); + assert!(open.contains("Update 2 packages"), "screen is {open:?}"); + assert!(open.contains("bat 0.23.0"), "screen is {open:?}"); + assert!(open.contains(app.theme.sym().arrow), "screen is {open:?}"); + assert!( + !open.contains("Keep old versions: yes"), + "screen is {open:?}" + ); + let effects = app.update(key('y'), now); + let [ + Effect::StartJob { + spec: + JobSpec::Update { + updates, + keep_old, + }, + .. + }, + ] = &effects[..] + else { + panic!("expected the update to start"); + }; + assert_eq!(updates.len(), 2); + assert_eq!(updates[0].pkg_name, "bat"); + assert_eq!(updates[1].pkg_name, "fd"); + assert!(!*keep_old); + assert!(app.update_pick.is_none()); + assert!(app.overlay.is_none()); + assert!(app.updates.marks.is_empty()); + assert!(app.updates.list.is_loading()); + assert_eq!(app.jobs.list[0].kind, JobKind::Update); + } + + #[test] + fn u_with_one_marked_update_confirms_under_the_package_name() { + let mut app = app(); + let now = Instant::now(); + app.view = ViewId::Updates; + app.update(updates_loaded(&app, three_updates()), now); + app.update(key('j'), now); + app.update(key(' '), now); + app.update(key('u'), now); + let open = screen(&mut app, 80, 24); + assert!(open.contains("Update fd"), "screen is {open:?}"); + assert!(open.contains("fd 10.1.0"), "screen is {open:?}"); + let effects = app.update(key('y'), now); + let [ + Effect::StartJob { + spec: JobSpec::Update { + updates, .. + }, + .. + }, + ] = &effects[..] + else { + panic!("expected the update to start"); + }; + assert_eq!(updates.len(), 1); + assert_eq!(updates[0].pkg_name, "fd"); + } + + #[test] + fn u_without_marks_confirms_every_row() { + let mut app = app(); + let now = Instant::now(); + app.view = ViewId::Updates; + app.update(updates_loaded(&app, three_updates()), now); + let effects = app.update(key('u'), now); + assert!(effects.is_empty()); + assert_eq!(app.update_pick.as_deref(), Some(&[0, 1, 2][..])); + let open = screen(&mut app, 80, 24); + assert!(open.contains("Update 3 packages"), "screen is {open:?}"); + let effects = app.update(key('y'), now); + let [ + Effect::StartJob { + spec: JobSpec::Update { + updates, .. + }, + .. + }, + ] = &effects[..] + else { + panic!("expected the update to start"); + }; + assert_eq!(updates.len(), 3); + assert_eq!(updates[2].pkg_name, "yq"); + } + + #[test] + fn u_with_an_empty_list_only_toasts() { + let mut app = app(); + let now = Instant::now(); + app.view = ViewId::Updates; + app.update(updates_loaded(&app, Vec::new()), now); + let effects = app.update(key('u'), now); + assert!(effects.is_empty()); + assert!(app.overlay.is_none()); + assert!(app.update_pick.is_none()); + assert!(app.jobs.list.is_empty()); + let toasts = format!("{:?}", app.toasts); + assert!( + toasts.contains("Nothing to update"), + "toasts are {toasts:?}" + ); + } + + #[test] + fn keep_old_shows_in_the_confirm_and_reaches_the_job() { + let mut app = app(); + let now = Instant::now(); + app.view = ViewId::Updates; + app.update(updates_loaded(&app, three_updates()), now); + app.update(key('o'), now); + assert!(app.updates.keep_old); + app.update(key('u'), now); + let open = screen(&mut app, 80, 24); + assert!( + open.contains("Keep old versions: yes"), + "screen is {open:?}" + ); + let effects = app.update(key('y'), now); + let [ + Effect::StartJob { + spec: JobSpec::Update { + keep_old, .. + }, + .. + }, + ] = &effects[..] + else { + panic!("expected the update to start"); + }; + assert!(*keep_old); + } + + #[test] + fn esc_on_the_update_confirm_leaves_the_list_unchanged() { + let mut app = app(); + let now = Instant::now(); + app.view = ViewId::Updates; + app.update(updates_loaded(&app, three_updates()), now); + app.update(key('u'), now); + app.update(code(KeyCode::Esc), now); + assert!(app.overlay.is_none()); + assert!(app.update_pick.is_none()); + assert!(app.jobs.list.is_empty()); + let Loadable::Ready(list) = &app.updates.list else { + panic!("expected the list to stay ready"); + }; + assert_eq!(list.len(), 3); + assert_eq!(list[0].pkg_name, "bat"); + } + + #[test] + fn a_finished_update_rechecks_with_the_scope_and_reloads_everything() { + let mut app = app(); + let now = Instant::now(); + app.updates.scope = Some(vec!["bat".to_string()]); + app.enqueue( + JobSpec::Update { + updates: vec![update_info("bat", "0.23.0", "0.24.0", "bincache")], + keep_old: false, + }, + now, + ); + let effects = app.update(finished(0, true, "Updated bat 0.24.0"), now); + let [ + Effect::CheckUpdates { + names, .. + }, + Effect::LoadInstalled { + .. + }, + Effect::LoadCatalog { + .. + }, + ] = &effects[..] + else { + panic!("expected a recheck with the reloads"); + }; + assert_eq!(names, &Some(vec!["bat".to_string()])); + assert!(app.updates.list.is_loading()); + assert_eq!(app.updates.checked, 0); + assert!(app.updates.skipped.is_empty()); + } + + #[test] + fn a_finished_install_rechecks_when_updates_was_visited() { + let mut app = app(); + let now = Instant::now(); + app.view = ViewId::Updates; + app.update(updates_loaded(&app, three_updates()), now); + app.view = ViewId::Browse; + app.enqueue(install_spec("bat"), now); + let effects = app.update(finished(0, true, "Installed bat 1.0.0"), now); + assert!(matches!( + effects.as_slice(), + [ + Effect::LoadCatalog { .. }, + Effect::LoadInstalled { .. }, + Effect::CheckUpdates { .. } + ] + )); + } + + #[test] + fn a_finished_remove_rechecks_when_updates_was_visited() { + let mut app = app(); + let now = Instant::now(); + app.view = ViewId::Updates; + app.update(updates_loaded(&app, three_updates()), now); + app.view = ViewId::Installed; + app.enqueue( + JobSpec::Remove { + packages: vec![installed_package("bat", "1.0.0", "bincache")], + }, + now, + ); + let effects = app.update(finished(0, true, "Removed bat 1.0.0"), now); + assert!(matches!( + effects.as_slice(), + [Effect::LoadInstalled { .. }, Effect::CheckUpdates { .. }] + )); + } + + #[test] + fn a_finished_switch_rechecks_when_updates_was_visited() { + let mut app = app(); + let now = Instant::now(); + app.view = ViewId::Updates; + app.update(updates_loaded(&app, three_updates()), now); + app.view = ViewId::Installed; + app.enqueue( + JobSpec::Switch { + id: 7, + name: "bat".to_string(), + }, + now, + ); + let effects = app.update(finished(0, true, "Switched bat"), now); + assert!(matches!( + effects.as_slice(), + [Effect::LoadInstalled { .. }, Effect::CheckUpdates { .. }] + )); + } + + /// A ready health load carrying the given report and the usual paths. + fn health_loaded(report: HealthReport) -> Msg { + health_loaded_with_paths(report, health_paths()) + } + + /// A session on the health view with the given report loaded. + fn health_app(report: HealthReport) -> (App, Instant) { + let mut app = app(); + app.view = ViewId::Health; + app.update(health_loaded(report), Instant::now()); + (app, Instant::now()) + } + + /// One broken package with the given name and install path. + fn broken_package(name: &str, path: &str) -> BrokenPackage { + BrokenPackage { + pkg_name: name.to_string(), + installed_path: path.to_string(), + } + } + + #[test] + fn b_without_broken_symlinks_only_leaves_a_note() { + let (mut app, now) = health_app(health_report()); + let effects = app.update(key('b'), now); + assert!(effects.is_empty()); + assert!(app.overlay.is_none()); + let toasts = format!("{:?}", app.toasts); + assert!( + toasts.contains("No broken symlinks"), + "toasts are {toasts:?}" + ); + } + + #[test] + fn b_with_three_broken_symlinks_confirms_then_removes_them() { + let mut report = health_report(); + report.broken_symlinks = (1..=3) + .map(|n| Path::new("/home/user/.local/bin").join(format!("tool{n}"))) + .collect(); + let (mut app, now) = health_app(report); + let effects = app.update(key('b'), now); + assert!(effects.is_empty()); + assert!(matches!(app.overlay, Some(Overlay::Confirm(_)))); + let open = screen(&mut app, 80, 24); + assert!( + open.contains("Remove 3 broken symlinks"), + "screen is {open:?}" + ); + assert!(open.contains("tool1"), "screen is {open:?}"); + assert!(open.contains("tool3"), "screen is {open:?}"); + let effects = app.update(key('y'), now); + let [ + Effect::StartJob { + spec: JobSpec::RemoveBrokenSymlinks, + .. + }, + ] = &effects[..] + else { + panic!("expected the symlink fix to start"); + }; + assert!(app.overlay.is_none()); + } + + #[test] + fn p_with_two_broken_packages_confirms_then_removes_them() { + let mut report = health_report(); + report.broken_packages = vec![ + broken_package("obsidian", "/gone/obsidian"), + broken_package("zellij", "/gone/zellij"), + ]; + let (mut app, now) = health_app(report); + let effects = app.update(key('p'), now); + assert!(effects.is_empty()); + assert!(matches!(app.overlay, Some(Overlay::Confirm(_)))); + let open = screen(&mut app, 80, 24); + assert!( + open.contains("Remove 2 broken packages"), + "screen is {open:?}" + ); + assert!( + open.contains("obsidian /gone/obsidian"), + "screen is {open:?}" + ); + assert!(open.contains("zellij /gone/zellij"), "screen is {open:?}"); + let effects = app.update(key('y'), now); + let [ + Effect::StartJob { + spec: JobSpec::RemoveBrokenPackages, + .. + }, + ] = &effects[..] + else { + panic!("expected the package fix to start"); + }; + assert!(app.overlay.is_none()); + } + + #[test] + fn p_without_broken_packages_only_leaves_a_note() { + let (mut app, now) = health_app(health_report()); + let effects = app.update(key('p'), now); + assert!(effects.is_empty()); + assert!(app.overlay.is_none()); + let toasts = format!("{:?}", app.toasts); + assert!( + toasts.contains("No broken packages"), + "toasts are {toasts:?}" + ); + } + + #[test] + fn c_names_the_cache_path_then_cleans_it() { + let mut app = app(); + let now = Instant::now(); + app.view = ViewId::Health; + let mut paths = health_paths(); + let Ok(home) = std::env::var("HOME") else { + return; + }; + if home.is_empty() { + return; + } + paths[4] = ( + "Cache".to_string(), + Path::new(&home).join(".local/share/soar/cache"), + ); + app.update(health_loaded_with_paths(health_report(), paths), now); + let effects = app.update(key('c'), now); + assert!(effects.is_empty()); + assert!(matches!(app.overlay, Some(Overlay::Confirm(_)))); + let open = screen(&mut app, 80, 24); + assert!(open.contains("Clean cache"), "screen is {open:?}"); + assert!( + open.contains("~/.local/share/soar/cache"), + "screen is {open:?}" + ); + assert!(open.contains("[ Clean ]"), "screen is {open:?}"); + let effects = app.update(key('y'), now); + let [ + Effect::StartJob { + spec: JobSpec::CleanCache, + .. + }, + ] = &effects[..] + else { + panic!("expected the cache clean to start"); + }; + assert!(app.overlay.is_none()); + } + + /// A ready health load carrying the given report and paths. + fn health_loaded_with_paths(report: HealthReport, paths: Vec<(String, PathBuf)>) -> Msg { + Msg::Loaded(Loaded::Health(Ok((report, paths)))) + } + + #[test] + fn the_eleventh_confirm_row_folds_into_a_count() { + let mut report = health_report(); + report.broken_symlinks = (1..=11) + .map(|n| Path::new("/home/user/.local/bin").join(format!("tool{n}"))) + .collect(); + let (mut app, now) = health_app(report); + app.update(key('b'), now); + let open = screen(&mut app, 80, 24); + assert!(open.contains("tool10"), "screen is {open:?}"); + assert!(open.contains("… and 1 more"), "screen is {open:?}"); + assert!(!open.contains("tool11"), "screen is {open:?}"); + } + + #[test] + fn the_fixes_do_nothing_while_the_report_loads() { + let mut app = app(); + app.view = ViewId::Health; + let now = Instant::now(); + for pressed in ['b', 'p', 'c'] { + let effects = app.update(key(pressed), now); + assert!(effects.is_empty()); + assert!(app.overlay.is_none()); + } + } + + /// The apply view with the given plan loaded. + fn apply_app(plan: ApplyPlan) -> (App, Instant) { + let mut app = app(); + app.view = ViewId::Apply; + app.update(apply_loaded(plan), Instant::now()); + (app, Instant::now()) + } + + /// A finished computation for the given plan, answering the check the + /// view still expects before any recompute has started. + fn apply_loaded(plan: ApplyPlan) -> Msg { + Msg::Loaded(Loaded::ApplyDiff { + check: 0, + result: Ok(plan), + }) + } + + /// A plan whose only change is removing the named package. + fn removal_plan(name: &str) -> ApplyPlan { + let mut pruned = apply_plan(); + if let Some(diff) = pruned.diff.as_mut() { + diff.to_install.clear(); + diff.to_update.clear(); + diff.to_remove = vec![installed_package(name, "1.7.7", "pkgcache")]; + diff.in_sync.clear(); + } + pruned + } + + #[test] + fn enter_with_a_removal_opens_a_danger_confirm_naming_it() { + let (mut app, now) = apply_app(removal_plan("obsidian")); + app.apply.prune = true; + let effects = app.update(code(KeyCode::Enter), now); + assert!(effects.is_empty()); + assert!(matches!(app.overlay, Some(Overlay::Confirm(_)))); + let open = screen(&mut app, 80, 24); + assert!(open.contains("Apply packages.toml"), "screen is {open:?}"); + assert!(open.contains("Remove 1"), "screen is {open:?}"); + assert!(open.contains("obsidian"), "screen is {open:?}"); + assert!(open.contains("[ Apply ]"), "screen is {open:?}"); + let effects = app.update(code(KeyCode::Enter), now); + assert!(effects.is_empty()); + assert!(app.overlay.is_none()); + assert!(app.jobs.list.is_empty()); + } + + #[test] + fn accepting_the_confirm_moves_the_diff_into_the_job() { + let (mut app, now) = apply_app(apply_plan()); + app.update(code(KeyCode::Enter), now); + let effects = app.update(key('y'), now); + let [ + Effect::StartJob { + spec: + JobSpec::Apply { + diff, + packages_path, + }, + .. + }, + ] = &effects[..] + else { + panic!("expected the apply to start"); + }; + assert_eq!(diff.to_install.len(), 1); + assert_eq!(diff.to_update.len(), 1); + assert_eq!(packages_path, "/home/user/.config/soar/packages.toml"); + assert_eq!(app.jobs.list[0].kind, JobKind::Apply); + assert!(app.apply.plan.is_loading()); + assert!(app.overlay.is_none()); + } + + #[test] + fn p_flips_prune_and_recomputes_with_the_new_value() { + let (mut app, now) = apply_app(apply_plan()); + assert!(!app.apply.prune); + let effects = app.update(key('p'), now); + let [ + Effect::ComputeApplyDiff { + prune, .. + }, + ] = &effects[..] + else { + panic!("expected a recomputation"); + }; + assert!(*prune); + assert!(app.apply.prune); + assert!(app.apply.plan.is_loading()); + } + + #[test] + fn enter_with_nothing_to_apply_only_leaves_a_note() { + let mut settled = apply_plan(); + if let Some(diff) = settled.diff.as_mut() { + diff.to_install.clear(); + diff.to_update.clear(); + diff.in_sync = vec!["fd".to_string()]; + } + let (mut app, now) = apply_app(settled); + let effects = app.update(code(KeyCode::Enter), now); + assert!(effects.is_empty()); + assert!(app.overlay.is_none()); + assert!(app.jobs.list.is_empty()); + let toasts = format!("{:?}", app.toasts); + assert!(toasts.contains("Nothing to apply"), "toasts are {toasts:?}"); + } + + #[test] + fn the_confirm_names_the_counts_and_the_system_pass() { + let mut full = apply_plan(); + full.system = vec!["docker-compose".to_string()]; + if let Some(diff) = full.diff.as_mut() { + diff.to_install.push(install_entry("jq", "1.7.1")); + } + let (mut app, now) = apply_app(full); + app.update(code(KeyCode::Enter), now); + let open = screen(&mut app, 80, 24); + assert!(open.contains("Install 2"), "screen is {open:?}"); + assert!(open.contains("Update 1"), "screen is {open:?}"); + assert!( + open.contains("System 1 (asks for administrator rights)"), + "screen is {open:?}" + ); + assert!(!open.contains("Remove"), "screen is {open:?}"); + } + + #[test] + fn esc_on_the_apply_confirm_leaves_the_plan_ready_and_unchanged() { + let (mut app, now) = apply_app(apply_plan()); + app.update(code(KeyCode::Enter), now); + app.update(code(KeyCode::Esc), now); + assert!(app.overlay.is_none()); + assert!(app.jobs.list.is_empty()); + let Loadable::Ready(plan) = &app.apply.plan else { + panic!("expected the plan to stay ready"); + }; + let Some(diff) = plan.diff.as_ref() else { + panic!("expected the plan to keep its diff"); + }; + assert_eq!(diff.to_install.len(), 1); + assert!(diff.has_changes()); + } + + #[test] + fn a_fresh_plan_under_the_apply_confirm_closes_it_with_a_note() { + let (mut app, now) = apply_app(apply_plan()); + app.update(code(KeyCode::Enter), now); + assert!(app.overlay.is_some()); + assert_eq!(app.apply_pick, Some(app.apply.check)); + // An edit of the packages file recomputes while the confirm is + // open, exactly the reload that can land under it. + app.update(Msg::Edited(app.env.packages_path.clone()), now); + assert!(app.apply.plan.is_loading()); + let effects = app.update( + Msg::Loaded(Loaded::ApplyDiff { + check: app.apply.check, + result: Ok(apply_plan()), + }), + now, + ); + assert!(effects.is_empty()); + assert!(app.overlay.is_none(), "the confirm cannot outlive its plan"); + assert!(app.apply_pick.is_none()); + assert!(app.jobs.list.is_empty(), "nothing was queued from it"); + let toasts = format!("{:?}", app.toasts); + assert!( + toasts.contains("The plan changed, so the confirm closed"), + "toasts are {toasts:?}" + ); + } + + #[test] + fn a_stale_plan_result_under_the_apply_confirm_changes_nothing() { + let (mut app, now) = apply_app(apply_plan()); + app.update(code(KeyCode::Enter), now); + assert!(app.overlay.is_some()); + let stale = app.apply.check; + app.update(Msg::Edited(app.env.packages_path.clone()), now); + let effects = app.update( + Msg::Loaded(Loaded::ApplyDiff { + check: stale, + result: Ok(removal_plan("obsidian")), + }), + now, + ); + assert!(effects.is_empty()); + assert!( + app.apply.plan.is_loading(), + "a stale result must not fill the view" + ); + assert!( + app.overlay.is_some(), + "a stale result leaves the confirm alone" + ); + assert_eq!(app.apply_pick, Some(stale)); + } + + #[test] + fn a_finished_apply_recomputes_the_plan_and_reloads_the_lists() { + let mut app = app(); + app.view = ViewId::Apply; + app.apply.prune = true; + let now = Instant::now(); + app.enqueue( + JobSpec::Apply { + diff: ApplyDiff::default(), + packages_path: "packages.toml".to_string(), + }, + now, + ); + let effects = app.update(finished(0, true, "Applied packages.toml"), now); + let [ + Effect::ComputeApplyDiff { + prune, .. + }, + Effect::LoadCatalog { + .. + }, + Effect::LoadInstalled { + .. + }, + ] = &effects[..] + else { + panic!("expected the plan to recompute and the lists to reload"); + }; + assert!(*prune); + assert!(app.apply.plan.is_loading()); + } + + #[test] + fn a_finished_apply_rechecks_updates_once_loaded() { + let mut app = app(); + let now = Instant::now(); + app.view = ViewId::Updates; + app.update(updates_loaded(&app, three_updates()), now); + app.view = ViewId::Apply; + app.enqueue( + JobSpec::Apply { + diff: ApplyDiff::default(), + packages_path: "packages.toml".to_string(), + }, + now, + ); + let effects = app.update(finished(0, true, "Applied packages.toml"), now); + assert!(matches!( + effects.as_slice(), + [ + Effect::ComputeApplyDiff { .. }, + Effect::LoadCatalog { .. }, + Effect::LoadInstalled { .. }, + Effect::CheckUpdates { .. } + ] + )); + } + + /// A system pass over one declared package. + fn system_spec() -> JobSpec { + JobSpec::ApplySystem { + names: vec!["jq".to_string()], + packages_path: "packages.toml".to_string(), + mode: SystemMode::Pending, + } + } + + /// The doas binary as the probe would have found it. + fn doas_tool() -> EscalationTool { + EscalationTool { + path: PathBuf::from("/usr/bin/doas"), + kind: EscalationKind::Doas, + } + } + + /// Enqueues a system pass and answers its probe, so the job sits in + /// the authorizing state. + fn authorizing_app() -> (App, Instant) { + let mut app = app(); + let now = Instant::now(); + app.enqueue(system_spec(), now); + assert!(matches!(app.jobs.list[0].state, JobState::Authorizing)); + (app, now) + } + + #[test] + fn a_queued_system_pass_probes_escalation_and_holds_the_queue() { + let mut app = app(); + let now = Instant::now(); + let effects = app.enqueue(system_spec(), now); + assert!(matches!(effects.as_slice(), [Effect::ProbeEscalation])); + assert!(matches!(app.jobs.list[0].state, JobState::Authorizing)); + let effects = app.enqueue(JobSpec::Sync, now); + assert!(effects.is_empty()); + assert_eq!(app.jobs.list[1].kind, JobKind::Sync); + assert!(matches!(app.jobs.list[1].state, JobState::Queued)); + } + + #[test] + fn a_ready_probe_starts_the_pass_directly() { + let (mut app, now) = authorizing_app(); + let effects = app.update(Msg::Loaded(Loaded::Escalation(EscalationProbe::Ready)), now); + let [ + Effect::StartJob { + spec: JobSpec::ApplySystem { + mode, .. + }, + .. + }, + ] = &effects[..] + else { + panic!("expected the pass to start"); + }; + assert!(matches!(mode, SystemMode::Direct)); + assert!(matches!(app.jobs.list[0].state, JobState::Running { .. })); + } + + #[test] + fn a_password_probe_opens_the_authorize_dialog() { + let (mut app, now) = authorizing_app(); + let effects = app.update( + Msg::Loaded(Loaded::Escalation(EscalationProbe::Password)), + now, + ); + assert!(effects.is_empty()); + assert!(matches!(app.overlay, Some(Overlay::Authorize(_)))); + let open = screen(&mut app, 80, 24); + assert!( + open.contains("Administrator rights needed"), + "screen is {open:?}" + ); + assert!(open.contains("jq"), "screen is {open:?}"); + assert!(open.contains("[ Authorize ]"), "screen is {open:?}"); + } + + #[test] + fn the_authorize_dialog_drops_the_state_of_the_overlay_it_replaces() { + let (mut app, now) = authorizing_app(); + let mut bat = catalog_row("bat", "0.24.0", "bincache"); + bat.other_versions = vec!["0.23.0".to_string()]; + app.update(catalog_loaded(vec![bat]), now); + app.update(key('v'), now); + assert!(matches!(app.overlay, Some(Overlay::Picker(_)))); + assert!(app.version_pick.is_some()); + app.update( + Msg::Loaded(Loaded::Escalation(EscalationProbe::Password)), + now, + ); + assert!(matches!(app.overlay, Some(Overlay::Authorize(_)))); + assert!(app.version_pick.is_none()); + } + + #[test] + fn the_terminal_confirm_drops_the_state_of_the_overlay_it_replaces() { + let (mut app, now) = authorizing_app(); + let mut bat = catalog_row("bat", "0.24.0", "bincache"); + bat.other_versions = vec!["0.23.0".to_string()]; + app.update(catalog_loaded(vec![bat]), now); + app.update(key('v'), now); + assert!(matches!(app.overlay, Some(Overlay::Picker(_)))); + assert!(app.version_pick.is_some()); + app.update( + Msg::Loaded(Loaded::Escalation(EscalationProbe::Terminal(doas_tool()))), + now, + ); + assert!(matches!(app.overlay, Some(Overlay::Confirm(_)))); + assert!(app.version_pick.is_none()); + } + + #[test] + fn a_submitted_password_reaches_the_runner_and_waits() { + let (mut app, now) = authorizing_app(); + app.update( + Msg::Loaded(Loaded::Escalation(EscalationProbe::Password)), + now, + ); + let effects = app.update(key('x'), now); + assert!(effects.is_empty()); + let effects = app.update(code(KeyCode::Enter), now); + let [effect] = &effects[..] else { + panic!("expected the password check to run"); + }; + assert!(matches!(effect, Effect::Authenticate { .. })); + assert!(matches!(app.overlay, Some(Overlay::Authorize(_)))); + let open = screen(&mut app, 80, 24); + assert!(open.contains("Checking password"), "screen is {open:?}"); + } + + #[test] + fn a_refused_password_shows_the_error_for_another_try() { + let (mut app, now) = authorizing_app(); + app.update( + Msg::Loaded(Loaded::Escalation(EscalationProbe::Password)), + now, + ); + app.update(key('x'), now); + app.update(code(KeyCode::Enter), now); + let check = app.pass_check; + let effects = app.update( + Msg::Loaded(Loaded::Authenticated { + check, + result: Err("Incorrect password, try again".to_string()), + }), + now, + ); + assert!(effects.is_empty()); + assert!(matches!(app.overlay, Some(Overlay::Authorize(_)))); + let open = screen(&mut app, 80, 24); + assert!( + open.contains("Incorrect password, try again"), + "screen is {open:?}" + ); + assert!(open.contains("[ Authorize ]"), "screen is {open:?}"); + } + + #[test] + fn a_refusal_from_a_withdrawn_dialog_spares_the_next_one() { + let (mut app, now) = authorizing_app(); + app.update( + Msg::Loaded(Loaded::Escalation(EscalationProbe::Password)), + now, + ); + app.update(key('x'), now); + app.update(code(KeyCode::Enter), now); + let stale = app.pass_check; + // The user gives up on the first dialog and starts a second pass. + app.update(code(KeyCode::Esc), now); + app.enqueue(system_spec(), now); + app.update( + Msg::Loaded(Loaded::Escalation(EscalationProbe::Password)), + now, + ); + assert!(matches!(app.overlay, Some(Overlay::Authorize(_)))); + // The first check's refusal arrives under the second dialog. + app.update( + Msg::Loaded(Loaded::Authenticated { + check: stale, + result: Err("Incorrect password, try again".to_string()), + }), + now, + ); + let open = screen(&mut app, 80, 24); + assert!( + !open.contains("Incorrect password"), + "the refusal belongs to a withdrawn dialog, screen is {open:?}" + ); + assert!(open.contains("[ Authorize ]"), "screen is {open:?}"); + } + + #[test] + fn an_accepted_password_starts_the_pass_directly() { + let (mut app, now) = authorizing_app(); + app.update( + Msg::Loaded(Loaded::Escalation(EscalationProbe::Password)), + now, + ); + app.update(key('x'), now); + app.update(code(KeyCode::Enter), now); + let check = app.pass_check; + let effects = app.update( + Msg::Loaded(Loaded::Authenticated { + check, + result: Ok(()), + }), + now, + ); + let [ + Effect::StartJob { + spec: JobSpec::ApplySystem { + mode, .. + }, + .. + }, + ] = &effects[..] + else { + panic!("expected the pass to start"); + }; + assert!(matches!(mode, SystemMode::Direct)); + assert!(app.overlay.is_none()); + assert!(matches!(app.jobs.list[0].state, JobState::Running { .. })); + } + + #[test] + fn cancelling_the_dialog_skips_the_pass_and_starts_the_next_job() { + let mut app = app(); + let now = Instant::now(); + app.enqueue(system_spec(), now); + app.enqueue(JobSpec::Sync, now); + app.update( + Msg::Loaded(Loaded::Escalation(EscalationProbe::Password)), + now, + ); + let effects = app.update(code(KeyCode::Esc), now); + let [ + Effect::ComputeApplyDiff { + .. + }, + Effect::StartJob { + spec: JobSpec::Sync, + .. + }, + ] = &effects[..] + else { + panic!("expected the sync to start, got something else"); + }; + let JobState::Finished { + outcome, .. + } = &app.jobs.list[0].state + else { + panic!("expected the pass to be over"); + }; + assert!(outcome.aborted); + assert_eq!(outcome.headline, "System packages skipped"); + assert!(app.overlay.is_none()); + } + + #[test] + fn a_terminal_probe_confirms_then_hands_over_the_terminal() { + let (mut app, now) = authorizing_app(); + let effects = app.update( + Msg::Loaded(Loaded::Escalation(EscalationProbe::Terminal(doas_tool()))), + now, + ); + assert!(effects.is_empty()); + assert!(matches!(app.overlay, Some(Overlay::Confirm(_)))); + let open = screen(&mut app, 80, 24); + assert!( + open.contains("Administrator rights needed"), + "screen is {open:?}" + ); + assert!( + open.contains("doas will ask for your password in the terminal."), + "screen is {open:?}" + ); + assert!( + open.contains("pauses until it finishes."), + "screen is {open:?}" + ); + assert!(open.contains("[ Continue ]"), "screen is {open:?}"); + let effects = app.update(key('y'), now); + let [ + Effect::Suspend(Suspended::SystemPass { + id, + tool, + packages_path, + names, + }), + ] = &effects[..] + else { + panic!("expected the terminal pass, got something else"); + }; + assert_eq!(*id, 0); + assert_eq!(tool.path, PathBuf::from("/usr/bin/doas")); + assert_eq!(packages_path, "packages.toml"); + assert_eq!(names, &["jq".to_string()]); + assert!(app.overlay.is_none()); + assert!(matches!(app.jobs.list[0].state, JobState::Running { .. })); + } + + #[test] + fn an_unavailable_probe_fails_the_job_and_starts_the_next() { + let mut app = app(); + let now = Instant::now(); + app.enqueue(system_spec(), now); + app.enqueue(JobSpec::Sync, now); + let effects = app.update( + Msg::Loaded(Loaded::Escalation(EscalationProbe::Unavailable( + "no tool here".to_string(), + ))), + now, + ); + let [ + Effect::ComputeApplyDiff { + .. + }, + Effect::StartJob { + spec: JobSpec::Sync, + .. + }, + ] = &effects[..] + else { + panic!("expected the sync to start, got something else"); + }; + let JobState::Finished { + outcome, .. + } = &app.jobs.list[0].state + else { + panic!("expected the pass to be over"); + }; + assert!(!outcome.ok); + assert_eq!(outcome.headline, "Apply 1 system package failed"); + assert!( + matches!(&outcome.lines[0], OutcomeLine::Failed { error, .. } if error == "no tool here") + ); + } + + #[test] + fn ctrl_x_with_a_running_system_pass_says_it_cannot_be_aborted() { + let (mut app, now) = authorizing_app(); + app.update(Msg::Loaded(Loaded::Escalation(EscalationProbe::Ready)), now); + let effects = app.update(ctrl('x'), now); + assert!(effects.is_empty()); + assert!(app.overlay.is_none()); + let toasts = format!("{:?}", app.toasts); + assert!( + toasts.contains("System apply cannot be aborted"), + "toasts are {toasts:?}" + ); + } + + #[test] + fn quitting_while_a_pass_authorizes_opens_the_guard() { + let (mut app, now) = authorizing_app(); + app.update(key('q'), now); + assert!(!app.quit, "the pass must not be dropped silently"); + assert!(matches!(app.overlay, Some(Overlay::QuitGuard(_)))); + let open = screen(&mut app, 80, 24); + assert!( + open.contains("Apply 1 system package"), + "screen is {open:?}" + ); + } + + #[test] + fn waiting_to_quit_over_a_pass_alone_withdraws_it_and_quits() { + let (mut app, now) = authorizing_app(); + app.update( + Msg::Loaded(Loaded::Escalation(EscalationProbe::Password)), + now, + ); + assert!(matches!(app.overlay, Some(Overlay::Authorize(_)))); + let effects = app.wait_and_quit(now, false); + assert!(effects.is_empty()); + assert!(app.quit, "nothing is left to wait for"); + assert!( + app.overlay.is_none(), + "the dialog has no pass left to serve" + ); + assert!(app.jobs.list.is_empty()); + } + + #[test] + fn abort_and_quit_leaves_a_system_pass_running_to_its_end() { + let (mut app, now) = authorizing_app(); + app.update(Msg::Loaded(Loaded::Escalation(EscalationProbe::Ready)), now); + let effects = app.wait_and_quit(now, true); + assert!( + !effects + .iter() + .any(|effect| matches!(effect, Effect::AbortJob)), + "the system pass cannot be aborted, so no abort may be sent" + ); + assert!(app.quit_when_idle); + let JobState::Running { + aborting, .. + } = app.jobs.list[0].state + else { + panic!("the pass keeps running"); + }; + assert!(!aborting); + } + + #[test] + fn the_apply_confirm_queues_the_system_pass_behind_the_user_packages() { + let mut full = apply_plan(); + full.system = vec!["jq".to_string()]; + let mut app = app(); + app.view = ViewId::Apply; + let now = Instant::now(); + app.update( + Msg::Loaded(Loaded::ApplyDiff { + check: 0, + result: Ok(full), + }), + now, + ); + app.update(code(KeyCode::Enter), now); + let effects = app.update(key('y'), now); + let [ + Effect::StartJob { + spec: JobSpec::Apply { + .. + }, + .. + }, + ] = &effects[..] + else { + panic!("expected the user apply to start"); + }; + assert_eq!(app.jobs.list.len(), 2); + assert_eq!(app.jobs.list[0].kind, JobKind::Apply); + assert_eq!(app.jobs.list[1].kind, JobKind::ApplySystem); + assert!(matches!(app.jobs.list[1].state, JobState::Queued)); + } + + #[test] + fn a_finished_user_apply_probes_the_system_pass_turn() { + let mut full = apply_plan(); + full.system = vec!["jq".to_string()]; + let mut app = app(); + app.view = ViewId::Apply; + let now = Instant::now(); + app.update( + Msg::Loaded(Loaded::ApplyDiff { + check: 0, + result: Ok(full), + }), + now, + ); + app.update(code(KeyCode::Enter), now); + app.update(key('y'), now); + let effects = app.update(finished(0, true, "Applied: 1 installed"), now); + assert!(matches!( + effects.as_slice(), + [_, _, _, Effect::ProbeEscalation] + )); + assert!(matches!(app.jobs.list[1].state, JobState::Authorizing)); + } + + #[test] + fn a_result_from_a_replaced_check_is_dropped() { + let mut app = app(); + let now = Instant::now(); + app.update(key('3'), now); + let replaced = app.updates.check; + app.update(ctrl('r'), now); + assert_eq!(app.updates.check, replaced.wrapping_add(1)); + let effects = app.update( + Msg::Loaded(Loaded::Updates { + check: replaced, + result: Ok(Vec::new()), + }), + now, + ); + assert!(effects.is_empty()); + assert!( + app.updates.list.is_loading(), + "a stale result must not fill the list" + ); + } + + #[test] + fn a_catalog_reply_from_a_replaced_load_is_dropped() { + let mut app = app(); + let now = Instant::now(); + app.update(ctrl('r'), now); + let replaced = app.catalog_load; + app.update(ctrl('r'), now); + let effects = app.update( + Msg::Loaded(Loaded::Catalog { + check: replaced, + result: Ok(vec![catalog_row("bat", "0.24.0", "bincache")]), + }), + now, + ); + assert!(effects.is_empty()); + assert!( + app.browse.catalog.is_loading(), + "a stale reply must not fill the catalog" + ); + assert!(app.updates.list.is_idle(), "a stale reply starts no check"); + let effects = app.update( + Msg::Loaded(Loaded::Catalog { + check: app.catalog_load, + result: Ok(vec![catalog_row("bat", "0.24.0", "bincache")]), + }), + now, + ); + assert!(matches!(effects.as_slice(), [Effect::CheckUpdates { .. }])); + assert!(app.browse.catalog.ready().is_some()); + } + + #[test] + fn an_installed_reply_from_a_replaced_load_is_dropped() { + let mut app = app(); + app.view = ViewId::Installed; + let now = Instant::now(); + app.update(ctrl('r'), now); + let replaced = app.installed_load; + app.update(ctrl('r'), now); + app.update( + Msg::Loaded(Loaded::Installed { + check: replaced, + result: Ok(InstalledListResult { + packages: Vec::new(), + total_count: 0, + total_size: 0, + }), + }), + now, + ); + assert!( + app.installed.list.is_loading(), + "a stale reply must not fill the list" + ); + app.update( + Msg::Loaded(Loaded::Installed { + check: app.installed_load, + result: Ok(InstalledListResult { + packages: vec![installed_entry("bat", "0.24.0", "bincache")], + total_count: 1, + total_size: 0, + }), + }), + now, + ); + assert!(app.installed.list.ready().is_some()); + } + + #[test] + fn a_fresh_check_under_the_update_confirm_withdraws_it() { + let mut app = app(); + let now = Instant::now(); + app.update(key('3'), now); + app.update(updates_loaded(&app, three_updates()), now); + app.update(key('u'), now); + assert!(app.update_pick.is_some()); + assert!(matches!(app.overlay, Some(Overlay::Confirm(_)))); + app.update(key('3'), now); + app.update(updates_loaded(&app, Vec::new()), now); + assert!(app.update_pick.is_none(), "the moved list invalidates it"); + assert!(app.overlay.is_none(), "the confirm cannot be trusted"); + let effects = app.update(key('y'), now); + assert!(effects.is_empty(), "nothing is queued from a dead confirm"); + } + + #[test] + fn a_recheck_started_under_the_update_confirm_closes_it_with_a_note() { + let mut app = app(); + let now = Instant::now(); + let started = app.enqueue(JobSpec::Sync, now); + assert!(matches!(started.as_slice(), [Effect::StartJob { .. }])); + app.update(key('3'), now); + app.update(updates_loaded(&app, three_updates()), now); + app.update(key('u'), now); + assert!(app.update_pick.is_some()); + assert!(matches!(app.overlay, Some(Overlay::Confirm(_)))); + // The job's finish starts a recheck while the confirm is open. + let effects = app.update(finished(0, true, "Synced 3 repositories"), now); + assert!( + effects + .iter() + .any(|effect| matches!(effect, Effect::CheckUpdates { .. })), + "the finished job starts the recheck" + ); + assert!(app.update_pick.is_none()); + assert!(app.overlay.is_none(), "the confirm cannot outlive its list"); + assert!(app.updates.list.is_loading()); + let toasts = format!("{:?}", app.toasts); + assert!( + toasts.contains("the confirm closed"), + "toasts are {toasts:?}" + ); + } + + #[test] + fn an_update_accepted_while_the_list_rechecks_toasts_and_queues_nothing() { + let mut app = app(); + let now = Instant::now(); + app.update(key('3'), now); + app.update(updates_loaded(&app, three_updates()), now); + app.update(ctrl('r'), now); + app.update_pick = Some(vec![0]); + let effects = app.update_now(now); + assert!(effects.is_empty(), "nothing can update a moving list"); + assert!(app.update_pick.is_none()); + assert!(app.updates.list.is_loading()); + let toasts = format!("{:?}", app.toasts); + assert!(toasts.contains("rechecked"), "toasts are {toasts:?}"); + } + + #[test] + fn a_stale_authenticated_answer_changes_nothing() { + let mut app = app(); + let now = Instant::now(); + let effects = app.update( + Msg::Loaded(Loaded::Authenticated { + check: 7, + result: Ok(()), + }), + now, + ); + assert!(effects.is_empty()); + assert!(app.overlay.is_none()); + } + + /// A pointer event at the given cell. + fn mouse(kind: MouseEventKind, column: u16, row: u16) -> Msg { + Msg::Input(Event::Mouse(MouseEvent { + kind, + column, + row, + modifiers: KeyModifiers::NONE, + })) + } + + /// A catalog of `count` rows, loaded, so the list has rows to hit. + fn catalog(count: usize) -> Msg { + let rows: Vec = (0..count) + .map(|n| catalog_row(&format!("pkg{n}"), "1.0.0", "bincache")) + .collect(); + catalog_loaded(rows) + } + + /// A confirm naming one package, as the removal flow opens it. + fn remove_confirm() -> Overlay { + Overlay::Confirm(Confirm::new( + "Remove jq", + vec![Line::raw("jq 1.7.1")], + "Remove", + true, + OnAccept::Test, + )) + } + + #[test] + fn an_install_resolution_cannot_displace_a_password_dialog() { + let (mut app, now) = authorizing_app(); + app.update( + Msg::Loaded(Loaded::Escalation(EscalationProbe::Password)), + now, + ); + app.update( + resolved(vec![Resolution::Ready(vec![target(package( + "bat", "0.24.0", "bincache", + ))])]), + now, + ); + assert!( + matches!(app.overlay, Some(Overlay::Authorize(_))), + "the pass dialog keeps its slot" + ); + assert!(app.pending.is_none(), "the install waits for a retry"); + } + + #[test] + fn a_left_click_on_the_second_tab_switches_to_installed() { + let mut app = app(); + screen(&mut app, 100, 24); + let (rect, view) = app.layout.tabs[1]; + assert_eq!(view, ViewId::Installed); + let now = Instant::now(); + let effects = app.update( + mouse(MouseEventKind::Down(MouseButton::Left), rect.x, rect.y), + now, + ); + assert!(effects.is_empty()); + assert_eq!(app.view, ViewId::Installed); + } + + #[test] + fn a_tab_click_enters_the_view_like_the_number_keys() { + let mut app = app(); + screen(&mut app, 100, 24); + let (rect, view) = app.layout.tabs[4]; + assert_eq!(view, ViewId::Repos); + let now = Instant::now(); + let effects = app.update( + mouse(MouseEventKind::Down(MouseButton::Left), rect.x, rect.y), + now, + ); + assert_eq!(app.view, ViewId::Repos); + assert!(matches!(effects.as_slice(), [Effect::LoadRepos])); + } + + #[test] + fn a_wheel_event_scrolls_the_list_by_three_rows() { + let mut app = app(); + app.update(catalog(10), Instant::now()); + screen(&mut app, 80, 24); + let (rect, offset) = app.layout.list.expect("the list hit area after a render"); + assert_eq!(offset, 0); + let now = Instant::now(); + let effects = app.update(mouse(MouseEventKind::ScrollDown, rect.x, rect.y), now); + assert!(effects.is_empty()); + assert_eq!(app.browse.cursor.selected, 3); + app.update(mouse(MouseEventKind::ScrollUp, rect.x, rect.y), now); + assert_eq!(app.browse.cursor.selected, 0); + app.update(mouse(MouseEventKind::ScrollUp, rect.x, rect.y), now); + assert_eq!(app.browse.cursor.selected, 0); + } + + #[test] + fn a_wheel_outside_the_rows_moves_nothing() { + let mut app = app(); + app.update(catalog(10), Instant::now()); + screen(&mut app, 80, 24); + let (rect, _) = app.layout.list.expect("the list hit area after a render"); + let now = Instant::now(); + app.update(mouse(MouseEventKind::ScrollDown, rect.x, rect.y - 1), now); + assert_eq!(app.browse.cursor.selected, 0); + } + + #[test] + fn the_wheel_scrolls_the_full_screen_detail() { + let mut app = app(); + let now = Instant::now(); + let mut row = catalog_row("bat", "0.24.0", "bincache"); + row.description = "word ".repeat(80); + app.update(catalog_loaded(vec![row]), now); + app.update(code(KeyCode::Enter), now); + screen(&mut app, 80, 24); + let rect = app.layout.detail.expect("the detail hit area"); + app.update(mouse(MouseEventKind::ScrollDown, rect.x, rect.y), now); + assert_eq!( + app.browse.detail.selected, 3, + "the detail follows the wheel" + ); + app.update(mouse(MouseEventKind::ScrollUp, rect.x, rect.y), now); + assert_eq!(app.browse.detail.selected, 0); + } + + #[test] + fn the_wheel_scrolls_the_log_pane_under_the_pointer() { + let mut app = app(); + let now = Instant::now(); + app.enqueue(JobSpec::Sync, now); + for n in 0..60 { + app.log + .push(crate::log::LogLevel::Info, format!("line {n}")); + } + app.update(key('7'), now); + screen(&mut app, 80, 24); + let rect = app.layout.log.expect("the log hit area"); + let following_end = app.log.cursor.selected; + app.update(mouse(MouseEventKind::ScrollUp, rect.x, rect.y), now); + assert!(!app.log.follow, "scrolling up stops following the end"); + assert_eq!( + app.log.cursor.selected, + following_end.saturating_sub(3), + "the log follows the wheel" + ); + } + + #[test] + fn a_click_on_a_list_row_moves_the_cursor_there() { + let mut app = app(); + app.update(catalog(5), Instant::now()); + screen(&mut app, 100, 24); + let (rect, offset) = app.layout.list.expect("the list hit area after a render"); + let now = Instant::now(); + let effects = app.update( + mouse( + MouseEventKind::Down(MouseButton::Left), + rect.x, + rect.y + u16::try_from(offset).unwrap() + 2, + ), + now, + ); + assert!(effects.is_empty()); + assert!(!app.browse.detail_open); + assert_eq!(app.browse.cursor.selected, offset + 2); + } + + #[test] + fn a_click_past_the_last_list_row_moves_nothing() { + let mut app = app(); + app.update(catalog(3), Instant::now()); + screen(&mut app, 80, 24); + let (rect, offset) = app.layout.list.expect("the list hit area after a render"); + let now = Instant::now(); + app.update( + mouse( + MouseEventKind::Down(MouseButton::Left), + rect.x, + rect.y + u16::try_from(offset).unwrap() + 10, + ), + now, + ); + assert_eq!(app.browse.cursor.selected, 0); + } + + #[test] + fn a_click_on_the_cursor_row_toggles_the_browse_detail() { + let mut app = app(); + app.update(catalog(5), Instant::now()); + screen(&mut app, 100, 24); + let (rect, offset) = app.layout.list.expect("the list hit area after a render"); + let now = Instant::now(); + let effects = app.update( + mouse( + MouseEventKind::Down(MouseButton::Left), + rect.x, + rect.y + u16::try_from(offset).unwrap(), + ), + now, + ); + assert!(effects.is_empty()); + assert!(app.browse.detail_open); + screen(&mut app, 100, 24); + assert!(app.layout.list.is_none()); + app.update( + mouse( + MouseEventKind::Down(MouseButton::Left), + rect.x, + rect.y + u16::try_from(offset).unwrap(), + ), + now, + ); + assert!(app.browse.detail_open); + } + + #[test] + fn a_click_on_the_cursor_row_toggles_the_installed_detail() { + let mut app = app(); + app.view = ViewId::Installed; + let entries: Vec<_> = (0..3) + .map(|n| installed_entry(&format!("pkg{n}"), "1.0.0", "bincache")) + .collect(); + app.update(installed_loaded(entries), Instant::now()); + screen(&mut app, 100, 24); + let (rect, offset) = app.layout.list.expect("the list hit area after a render"); + let now = Instant::now(); + app.update( + mouse( + MouseEventKind::Down(MouseButton::Left), + rect.x, + rect.y + u16::try_from(offset).unwrap(), + ), + now, + ); + assert!(app.installed.detail_open); + } + + #[test] + fn the_hit_areas_reset_between_frames() { + let mut app = app(); + app.update(catalog(5), Instant::now()); + screen(&mut app, 80, 24); + assert!(app.layout.list.is_some()); + app.view = ViewId::Jobs; + screen(&mut app, 80, 24); + assert!(app.layout.list.is_none()); + assert!(app.layout.overlay.is_none()); + } + + #[test] + fn a_click_outside_a_confirm_closes_it_like_esc() { + let mut app = app(); + app.overlay = Some(remove_confirm()); + screen(&mut app, 80, 24); + let rect = app + .layout + .overlay + .expect("the overlay hit area after a render"); + assert!(rect.y > 0); + let now = Instant::now(); + let effects = app.update(mouse(MouseEventKind::Down(MouseButton::Left), 0, 0), now); + assert!(effects.is_empty()); + assert!(app.overlay.is_none()); + } + + #[test] + fn a_click_inside_a_confirm_keeps_it_open() { + let mut app = app(); + app.overlay = Some(remove_confirm()); + screen(&mut app, 80, 24); + let rect = app + .layout + .overlay + .expect("the overlay hit area after a render"); + let now = Instant::now(); + app.update( + mouse(MouseEventKind::Down(MouseButton::Left), rect.x, rect.y), + now, + ); + assert!(matches!(app.overlay, Some(Overlay::Confirm(_)))); + } + + #[test] + fn a_click_outside_a_picker_closes_it_and_drops_what_it_kept() { + let mut app = app(); + app.run_pick = Some((vec!["--verbose".to_string()], Vec::new())); + app.overlay = Some(Overlay::Picker(Picker::new( + "Pick a variant", + vec![Line::raw("jq 1.7.1")], + OnAccept::Test, + ))); + screen(&mut app, 80, 24); + let now = Instant::now(); + app.update(mouse(MouseEventKind::Down(MouseButton::Left), 0, 0), now); + assert!(app.overlay.is_none()); + assert!(app.run_pick.is_none()); + } + + #[test] + fn mouse_events_do_nothing_while_a_prompt_is_open() { + let mut app = app(); + app.update(catalog(5), Instant::now()); + app.overlay = Some(Overlay::Prompt(Prompt::new( + "Install by name, URL, or path", + OnAccept::Test, + ))); + screen(&mut app, 80, 24); + let rect = app + .layout + .overlay + .expect("the overlay hit area after a render"); + let now = Instant::now(); + app.update(mouse(MouseEventKind::ScrollDown, rect.x, rect.y), now); + app.update(mouse(MouseEventKind::Down(MouseButton::Left), 0, 0), now); + app.update( + mouse(MouseEventKind::Down(MouseButton::Left), rect.x, rect.y), + now, + ); + assert!(matches!(app.overlay, Some(Overlay::Prompt(_)))); + assert_eq!(app.browse.cursor.selected, 0); + } +} diff --git a/crates/soar-tui/src/effect.rs b/crates/soar-tui/src/effect.rs new file mode 100644 index 00000000..9fd15656 --- /dev/null +++ b/crates/soar-tui/src/effect.rs @@ -0,0 +1,167 @@ +//! Work the interface's state asks the runner to carry out. + +use std::path::PathBuf; + +use soar_operations::privilege::EscalationTool; + +use crate::{ + jobs::{InstallChoices, JobId, JobSpec}, + privileged::Secret, + views::browse::PackageKey, +}; + +/// A request for work outside the state, such as talking to soar. +pub(crate) enum Effect { + /// Rebuilds the soar context from the current configuration. + /// + /// Produced once configuration changes through the interface, such as + /// after a repository sync replaces the metadata databases. + RebuildContext, + /// Runs the queued job through the runner. + StartJob { + /// The job to mark started. + id: JobId, + /// What the job runs. + spec: JobSpec, + }, + /// Stops the job running now at its next safe point. + AbortJob, + /// Loads the package catalog the Browse view shows. + LoadCatalog { + /// Which load this is: every start numbers itself, and a reply + /// from a load a newer one replaced is dropped, so only the + /// newest load fills the catalog. + check: u32, + }, + /// Loads the installed packages the Installed view shows. The listing + /// walks the disk for sizes, so the runner runs it off the async + /// workers. + LoadInstalled { + /// Which load this is: every start numbers itself, and a reply + /// from a load a newer one replaced is dropped, so only the + /// newest load fills the list. + check: u32, + }, + /// Loads the configured repositories the Repos view shows. + LoadRepos, + /// Loads the installation health report and the paths it names, for + /// the Health view. The check walks the filesystem, so the runner runs + /// it off the async workers. + LoadHealth, + /// Computes what applying the packages file would change, for the + /// Apply view. Remote declarations are resolved over the network, so + /// the runner runs it on the async workers. + ComputeApplyDiff { + /// Whether applying also removes packages the file does not + /// declare. + prune: bool, + /// Which computation this is: every start numbers itself, and a + /// result from an older one is dropped, so only the newest + /// computation fills the view. + check: u32, + }, + /// Loads the installed variants of one package name, for the flow + /// that chooses which one is linked. The listing queries the + /// metadata database, so the runner runs it off the async workers. + LoadVariants { + /// The package name whose variants load. + name: String, + }, + /// Loads one package's full metadata for the detail pane. + /// + /// The version rides along because the key alone cannot pick it: the + /// catalog row knows which variant the pane should show, and the + /// query needs that version to fetch exactly it. + LoadDetail { + /// The package to load. + key: PackageKey, + /// The version the catalog row shows. + version: String, + }, + /// Resolves install queries into targets, variants to pick, and + /// not-found reports, without installing anything yet. + Resolve { + /// The queries to resolve, each a name, an exact + /// `family/name@version:repo`, a URL, or a local path. + queries: Vec, + /// The options the install runs with once it is confirmed. + choices: InstallChoices, + }, + /// Prepares a package run without installing it: resolves the query, + /// downloads the binary when the cache lacks it, and reports the path + /// to execute or the variants to pick between. + PrepareRun { + /// The query naming the package, either `family/name:repo` for + /// its newest variant or an exact `family/name@version:repo`. + query: String, + /// The repository to search, when the query does not name one. + repo: Option, + /// The package id pinning the variant, so a query picked out of + /// an ambiguity cannot turn ambiguous again. + pkg_id: Option, + /// The arguments the binary runs with. + args: Vec, + }, + /// Checks the installed packages for newer versions, limited to the + /// named packages when some are given. The check reports its progress + /// through `UpdateCheck` events and its result through + /// `Loaded::Updates`, tagged with the check it answers. + CheckUpdates { + /// The packages the check is limited to, or every installed one. + names: Option>, + /// Which check this is: every start numbers itself, and a result + /// from an older number is dropped, so only the newest check + /// fills the list. + check: u32, + }, + /// Hands the terminal to a program and takes it back after it exits. + Suspend(Suspended), + /// Checks how the administrator pass could run here: already root, a + /// password question, a terminal question, or no way to get root. The + /// answer arrives as `Loaded::Escalation`. + ProbeEscalation, + /// Sends the password the dialog collected to sudo, which caches the + /// credentials for the system pass that follows. The answer arrives + /// as `Loaded::Authenticated`. The `check` number says which + /// password check is asking; an answer with a number the app no + /// longer expects is stale. + Authenticate { + /// The password the dialog collected, moved out of the input so + /// it never lingers in the interface's state. + secret: Secret, + /// Which password check this is: every submission numbers + /// itself, and an answer from an older one is dropped. + check: u32, + }, +} + +/// Something that runs with the terminal handed back to the user, while +/// the interface's input is paused. +pub(crate) enum Suspended { + /// Runs a package's cached binary with the arguments the run prompt + /// collected. + Exec { + /// The binary to execute. + path: PathBuf, + /// The arguments handed to the binary. + args: Vec, + }, + /// Opens the configuration file in the user's editor. + Edit(PathBuf), + /// Runs the system pass with the terminal handed over, so the + /// escalation tool can ask for the password itself. The job named by + /// `id` is already marked running; the outcome comes back through the + /// queue when the pass is over. + SystemPass { + /// The job whose outcome reports the pass. + id: JobId, + /// The escalation tool that asks for the password. + tool: EscalationTool, + /// Where the declared packages are written. + packages_path: String, + /// The system names the confirm named. The runner reads the file + /// again before spawning the child, so an edit after the + /// confirmation cannot apply unapproved packages. + names: Vec, + }, +} diff --git a/crates/soar-tui/src/event_loop.rs b/crates/soar-tui/src/event_loop.rs new file mode 100644 index 00000000..b1aafd3d --- /dev/null +++ b/crates/soar-tui/src/event_loop.rs @@ -0,0 +1,178 @@ +//! The blocking loop that turns messages into frames, and the thread that +//! feeds it terminal input. + +use std::{ + io, + sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + mpsc::{Receiver, RecvTimeoutError, Sender}, + }, + time::{Duration, Instant}, +}; + +use ratatui::crossterm::event; + +use crate::{app::App, msg::Msg, runner::Runner, terminal::Session, ui}; + +/// How often the state receives a tick, driving spinners and timeouts. +const TICK: Duration = Duration::from_millis(100); + +/// The most messages handled between two redraws. +const MAX_BATCH: usize = 256; + +/// How long pausing waits for the reader to drain its buffers. +const PAUSE_HANDSHAKE: Duration = Duration::from_millis(250); + +/// Reads terminal events in the background and sends them into the message +/// channel. +pub(crate) struct InputThread { + paused: Arc, + drained: Arc, + stop: Arc, +} + +impl InputThread { + /// Starts reading terminal events into `tx` on a background thread. + pub(crate) fn spawn(tx: Sender) -> io::Result { + let paused = Arc::new(AtomicBool::new(false)); + let drained = Arc::new(AtomicBool::new(true)); + let stop = Arc::new(AtomicBool::new(false)); + std::thread::Builder::new() + .name("soar-tui-input".into()) + .spawn({ + let paused = Arc::clone(&paused); + let drained = Arc::clone(&drained); + let stop = Arc::clone(&stop); + move || input_loop(tx, paused, drained, stop) + })?; + Ok(InputThread { + paused, + drained, + stop, + }) + } + + /// Stops reading keystrokes while a suspended program uses the + /// terminal, after asking the reader to throw away what was already + /// buffered, so the suspended program starts from a clean terminal + /// instead of receiving keystrokes meant for the interface. The call + /// waits up to `PAUSE_HANDSHAKE` for that drain and proceeds + /// regardless, so a wedged reader cannot stall the interface. + pub(crate) fn pause(&self) { + self.drained.store(false, Ordering::Relaxed); + self.paused.store(true, Ordering::Relaxed); + let deadline = Instant::now() + PAUSE_HANDSHAKE; + while !self.drained.load(Ordering::Relaxed) && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(1)); + } + } + + /// Resumes reading keystrokes after a suspended program has finished. + pub(crate) fn resume(&self) { + self.paused.store(false, Ordering::Relaxed); + } + + /// Ends the background thread. + pub(crate) fn stop(&self) { + self.stop.store(true, Ordering::Relaxed); + } +} + +/// Polls for terminal events until asked to stop, giving up the terminal +/// while paused so a suspended program keeps its keystrokes. Taking the +/// pause throws away whatever keystrokes were buffered before it, so the +/// suspended program starts from a clean terminal. +fn input_loop( + tx: Sender, + paused: Arc, + drained: Arc, + stop: Arc, +) { + while !stop.load(Ordering::Relaxed) { + if paused.load(Ordering::Relaxed) { + // The flag, not a memory of having paused before, gates the + // drain: a pause landing while this thread sleeps must + // drain again, or stale keystrokes reach the suspended + // program and the handshake never completes. + if !drained.load(Ordering::Relaxed) { + while event::poll(Duration::ZERO).unwrap_or(false) { + if event::read().is_err() { + break; + } + } + drained.store(true, Ordering::Relaxed); + } + std::thread::sleep(Duration::from_millis(50)); + continue; + } + match event::poll(Duration::from_millis(50)) { + Ok(true) => { + match event::read() { + Ok(ev) => { + if tx.send(Msg::Input(ev)).is_err() { + break; + } + } + Err(error) => { + // The runner and the other senders keep the + // channel alive, so a dead reader would go + // unnoticed and leave the interface deaf. + let _ = tx.send(Msg::InputFailed(error.to_string())); + break; + } + } + } + Ok(false) => {} + Err(error) => { + let _ = tx.send(Msg::InputFailed(error.to_string())); + break; + } + } + } +} + +/// Drives the interface: redraws when the state changed, applies arriving +/// messages in batches so a burst causes one redraw, and hands the requested +/// work to the runner. The channel sender stays unused until suspended +/// effects report back through it. +pub(crate) fn run_loop( + session: &mut Session, + app: &mut App, + rx: &Receiver, + runner: &mut Runner, + input: &InputThread, + _tx: &Sender, +) -> io::Result<()> { + let mut last_tick = Instant::now(); + loop { + if app.dirty { + session.terminal.draw(|f| ui::render(f, app))?; + app.dirty = false; + } + let timeout = TICK.saturating_sub(last_tick.elapsed()); + let first = match rx.recv_timeout(timeout) { + Ok(msg) => Some(msg), + Err(RecvTimeoutError::Timeout) => None, + Err(RecvTimeoutError::Disconnected) => return Ok(()), + }; + let mut effects = Vec::new(); + let now = Instant::now(); + if let Some(msg) = first { + effects.extend(app.update(msg, now)); + for msg in rx.try_iter().take(MAX_BATCH) { + effects.extend(app.update(msg, now)); + } + } + if last_tick.elapsed() >= TICK { + effects.extend(app.update(Msg::Tick, now)); + last_tick = Instant::now(); + } + for effect in effects { + runner.execute(effect, session, input)?; + } + if app.quit { + return Ok(()); + } + } +} diff --git a/crates/soar-tui/src/format.rs b/crates/soar-tui/src/format.rs new file mode 100644 index 00000000..dfb6bd3e --- /dev/null +++ b/crates/soar-tui/src/format.rs @@ -0,0 +1,394 @@ +//! Turns raw counts and times into the short strings the interface shows. +//! +//! Most helpers below wait for the views that will call them. + +#![allow(dead_code)] + +use std::{ + path::Path, + time::{Duration, SystemTime}, +}; + +use ratatui::text::Span; +use soar_utils::bytes::format_bytes; + +/// A byte count with one decimal, such as `5.2 MiB`. +pub(crate) fn size(bytes: u64) -> String { + format_bytes(bytes, 1) +} + +/// A transfer rate, such as `12.5 MiB/s`. +pub(crate) fn speed(bytes_per_sec: f64) -> String { + format!("{}/s", size(bytes_per_sec as u64)) +} + +/// An elapsed time as `m:ss`, or `h:mm:ss` past one hour. +pub(crate) fn clock(d: Duration) -> String { + let total = d.as_secs(); + let hours = total / 3600; + let minutes = (total % 3600) / 60; + let seconds = total % 60; + if hours > 0 { + format!("{hours}:{minutes:02}:{seconds:02}") + } else { + format!("{minutes}:{seconds:02}") + } +} + +/// A remaining time rounded down to its coarsest unit, such as `3s` or `2m`. +pub(crate) fn eta(d: Duration) -> String { + let total = d.as_secs(); + if total < 60 { + format!("{total}s") + } else if total < 3600 { + format!("{}m", total / 60) + } else { + format!("{}h", total / 3600) + } +} + +/// How long ago something happened, such as `just now` or `3 days ago`. +pub(crate) fn relative(then: SystemTime, now: SystemTime) -> String { + let elapsed = now.duration_since(then).unwrap_or(Duration::ZERO).as_secs(); + match elapsed { + 0..=59 => "just now".to_string(), + 60..=3599 => ago(elapsed / 60, "minute"), + 3600..=86399 => ago(elapsed / 3600, "hour"), + 86400..=172799 => "yesterday".to_string(), + 172800..=604799 => ago(elapsed / 86400, "day"), + 604800..=2591999 => ago(elapsed / 604800, "week"), + 2592000..=31535999 => ago(elapsed / 2592000, "month"), + _ => ago(elapsed / 31536000, "year"), + } +} + +/// One count of a named span of time, singular for one. +fn ago(count: u64, unit: &str) -> String { + if count == 1 { + format!("1 {unit} ago") + } else { + format!("{count} {unit}s ago") + } +} + +/// Cuts text to fit `width` display columns, keeping its start and adding +/// the ellipsis. +pub(crate) fn truncate(s: &str, width: usize, ellipsis: &str) -> String { + if Span::raw(s).width() <= width { + return s.to_string(); + } + let ellipsis_width = Span::raw(ellipsis).width(); + if ellipsis_width >= width { + return take(s, width); + } + format!("{}{ellipsis}", take(s, width - ellipsis_width)) +} + +/// Cuts text to fit `width` display columns, keeping its start and end, so +/// long paths and URLs keep both sides. +pub(crate) fn truncate_middle(s: &str, width: usize, ellipsis: &str) -> String { + if Span::raw(s).width() <= width { + return s.to_string(); + } + let ellipsis_width = Span::raw(ellipsis).width(); + if ellipsis_width >= width { + return take(s, width); + } + let kept = width - ellipsis_width; + let start_keep = kept.div_ceil(2); + let start = take(s, start_keep); + let end = take_end(s, kept - start_keep); + format!("{start}{ellipsis}{end}") +} + +/// The longest prefix of `s` that fits `width` display columns. +fn take(s: &str, width: usize) -> String { + let mut out = String::new(); + let mut used = 0; + for ch in s.chars() { + let char_width = Span::raw(ch.to_string()).width(); + if used + char_width > width { + break; + } + out.push(ch); + used += char_width; + } + out +} + +/// The longest suffix of `s` that fits `width` display columns. +fn take_end(s: &str, width: usize) -> String { + let mut out = String::new(); + let mut used = 0; + for ch in s.chars().rev() { + let char_width = Span::raw(ch.to_string()).width(); + if used + char_width > width { + break; + } + out.push(ch); + used += char_width; + } + out.chars().rev().collect() +} + +/// A number with a separator every three digits: `4213` becomes `4,213`. +pub(crate) fn thousands(n: usize) -> String { + if n < 1000 { + return n.to_string(); + } + format!("{},{:03}", thousands(n / 1000), n % 1000) +} + +/// Splits `text` into rows at most `width` display columns wide, +/// breaking at spaces so words stay whole. A word wider than the row is +/// cut into pieces that fit. +pub(crate) fn wrap(text: &str, width: usize) -> Vec { + if width == 0 { + return vec![text.to_string()]; + } + // Words wider than the wrap width become pieces that fit, so the + // assembly below only handles spaces. + let mut tokens = Vec::new(); + for word in text.split(' ') { + let mut rest = word; + while Span::raw(rest).width() > width { + let piece = take(rest, width); + if piece.is_empty() { + break; + } + tokens.push(piece.clone()); + rest = &rest[piece.len()..]; + } + tokens.push(rest.to_string()); + } + let mut rows = Vec::new(); + let mut row = String::new(); + let mut row_width = 0; + for token in tokens { + let token_width = Span::raw(&token).width(); + let gap = usize::from(!row.is_empty()); + if row_width + gap + token_width > width { + // A token that cannot fit an empty row, such as a wide + // character at a tiny width, starts its own row instead of + // flushing an empty one ahead of it. + if !row.is_empty() { + rows.push(std::mem::take(&mut row)); + row_width = 0; + } + } else if gap == 1 { + row.push(' '); + } + row.push_str(&token); + row_width += gap + token_width; + } + if !row.is_empty() { + rows.push(row); + } + rows +} + +/// A path with the user's home directory replaced by `~`. +pub(crate) fn home_relative(path: &Path) -> String { + let text = path.to_string_lossy(); + let Ok(home) = std::env::var("HOME") else { + return text.into_owned(); + }; + if home.is_empty() { + return text.into_owned(); + } + if text == home { + return "~".to_string(); + } + let prefix = format!("{home}/"); + match text.strip_prefix(prefix.as_str()) { + Some(rest) => format!("~/{rest}"), + None => text.into_owned(), + } +} + +/// Parses an install date as soar records it in UTC, `2026-11-02 13:45:07`. +pub(crate) fn parse_installed_date(s: &str) -> Option { + let date = chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S").ok()?; + Some(SystemTime::from(date.and_utc())) +} + +/// The current local time as `HH:MM:SS`. +pub(crate) fn clock_now() -> String { + chrono::Local::now().format("%H:%M:%S").to_string() +} + +#[cfg(test)] +mod tests { + use std::{ + path::Path, + time::{Duration, SystemTime}, + }; + + use ratatui::text::Span; + + use super::{ + clock, clock_now, eta, home_relative, parse_installed_date, relative, size, speed, + thousands, truncate, truncate_middle, wrap, + }; + + #[test] + fn sizes_show_one_decimal() { + assert_eq!(size(0), "0.0 B"); + assert_eq!(size(1024), "1.0 KiB"); + assert_eq!(size(5452595), "5.2 MiB"); + } + + #[test] + fn speeds_append_per_second() { + assert_eq!(speed(0.0), "0.0 B/s"); + assert_eq!(speed(1024.0), "1.0 KiB/s"); + } + + #[test] + fn clocks_split_below_an_hour() { + assert_eq!(clock(Duration::from_secs(7)), "0:07"); + assert_eq!(clock(Duration::from_secs(307)), "5:07"); + assert_eq!(clock(Duration::from_secs(3600)), "1:00:00"); + assert_eq!(clock(Duration::from_secs(3723)), "1:02:03"); + } + + #[test] + fn etas_round_down_to_the_coarsest_unit() { + assert_eq!(eta(Duration::from_secs(3)), "3s"); + assert_eq!(eta(Duration::from_secs(59)), "59s"); + assert_eq!(eta(Duration::from_secs(60)), "1m"); + assert_eq!(eta(Duration::from_secs(125)), "2m"); + assert_eq!(eta(Duration::from_secs(3599)), "59m"); + assert_eq!(eta(Duration::from_secs(3600)), "1h"); + assert_eq!(eta(Duration::from_secs(7200)), "2h"); + } + + #[test] + fn relative_times_use_the_right_unit() { + let now = SystemTime::UNIX_EPOCH + Duration::from_secs(2_000_000_000); + let ago = |secs: u64| now - Duration::from_secs(secs); + assert_eq!(relative(ago(0), now), "just now"); + assert_eq!(relative(ago(59), now), "just now"); + assert_eq!(relative(ago(60), now), "1 minute ago"); + assert_eq!(relative(ago(300), now), "5 minutes ago"); + assert_eq!(relative(ago(3600), now), "1 hour ago"); + assert_eq!(relative(ago(3 * 3600), now), "3 hours ago"); + assert_eq!(relative(ago(86399), now), "23 hours ago"); + assert_eq!(relative(ago(86400), now), "yesterday"); + assert_eq!(relative(ago(3 * 86400), now), "3 days ago"); + assert_eq!(relative(ago(7 * 86400), now), "1 week ago"); + assert_eq!(relative(ago(14 * 86400), now), "2 weeks ago"); + assert_eq!(relative(ago(30 * 86400), now), "1 month ago"); + assert_eq!(relative(ago(60 * 86400), now), "2 months ago"); + assert_eq!(relative(ago(365 * 86400), now), "1 year ago"); + assert_eq!(relative(ago(2 * 365 * 86400), now), "2 years ago"); + assert_eq!(relative(now + Duration::from_secs(100), now), "just now"); + } + + #[test] + fn truncate_keeps_the_start() { + assert_eq!(truncate("bat", 10, "…"), "bat"); + assert_eq!(truncate("bat-extras", 10, "…"), "bat-extras"); + assert_eq!(truncate("bat-extras", 9, "…"), "bat-extr…"); + assert_eq!(truncate("bat-extras", 0, "…"), ""); + assert_eq!(truncate("日本語", 3, "…"), "日…"); + } + + #[test] + fn truncate_drops_the_ellipsis_when_it_does_not_fit() { + assert_eq!(truncate("bat-extras", 3, "..."), "bat"); + } + + #[test] + fn truncate_middle_keeps_both_ends() { + assert_eq!(truncate_middle("bat", 10, "…"), "bat"); + assert_eq!(truncate_middle("bat-extras", 10, "…"), "bat-extras"); + assert_eq!(truncate_middle("abcdefgh", 5, "…"), "ab…gh"); + assert_eq!( + truncate_middle("https://example.com/path", 12, "…"), + "https:…/path" + ); + assert_eq!(truncate_middle("bat-extras", 0, "…"), ""); + } + + #[test] + fn thousands_separate_every_third_digit() { + assert_eq!(thousands(0), "0"); + assert_eq!(thousands(999), "999"); + assert_eq!(thousands(1000), "1,000"); + assert_eq!(thousands(4213), "4,213"); + assert_eq!(thousands(1_000_000), "1,000,000"); + } + + #[test] + fn paths_under_home_shrink_to_a_tilde() { + let Ok(home) = std::env::var("HOME") else { + return; + }; + if home.is_empty() { + return; + } + let deep = Path::new(&home).join("packages").join("bat"); + assert_eq!(home_relative(&deep), "~/packages/bat"); + assert_eq!(home_relative(Path::new(&home)), "~"); + assert_eq!(home_relative(Path::new("/usr/bin")), "/usr/bin"); + } + + #[test] + fn installed_dates_parse_from_the_recorded_format() { + assert_eq!( + parse_installed_date("1970-01-01 00:00:01"), + Some(SystemTime::UNIX_EPOCH + Duration::from_secs(1)) + ); + assert!(parse_installed_date("2026-11-02 13:45:07").is_some()); + assert!(parse_installed_date("2026-11-02").is_none()); + assert!(parse_installed_date("").is_none()); + } + + #[test] + fn wrap_breaks_at_spaces_within_the_width() { + assert_eq!(wrap("one two three", 8), ["one two", "three"]); + assert_eq!(wrap("short", 8), ["short"]); + assert!(wrap("", 8).is_empty()); + } + + #[test] + fn wrap_counts_display_columns_not_characters() { + // Each character is two columns wide, so four of them cannot + // share a five-column row. + assert_eq!(wrap("日本語よ", 5), ["日本", "語よ"]); + assert_eq!(wrap("日本語 テスト", 6), ["日本語", "テスト"]); + } + + #[test] + fn wrap_cuts_a_long_ascii_word_to_fit() { + assert_eq!(wrap("abcdefghij", 4), ["abcd", "efgh", "ij"]); + } + + #[test] + fn wrap_of_a_token_wider_than_the_row_never_starts_empty() { + let token = "a".repeat(70); + let rows = wrap(&token, 30); + assert_eq!(rows.len(), 3); + for row in &rows { + assert!(!row.is_empty(), "empty row among {rows:?}"); + assert!( + Span::raw(row).width() <= 30, + "row {row:?} is over 30 columns" + ); + } + } + + #[test] + fn wrap_of_a_wide_character_at_a_one_column_row_is_one_row() { + assert_eq!(wrap("日本", 1), ["日本"]); + } + + #[test] + fn the_clock_shows_hours_minutes_and_seconds() { + let now = clock_now(); + assert_eq!(now.len(), 8); + assert_eq!(now.as_bytes()[2], b':'); + assert_eq!(now.as_bytes()[5], b':'); + } +} diff --git a/crates/soar-tui/src/jobs.rs b/crates/soar-tui/src/jobs.rs new file mode 100644 index 00000000..6abaa9db --- /dev/null +++ b/crates/soar-tui/src/jobs.rs @@ -0,0 +1,555 @@ +//! The job queue: what runs, one operation at a time, and what each job +//! reports when it is over. + +use std::time::Instant; + +use soar_config::repository::Repository; +use soar_core::{ + database::models::{InstalledPackage, Package}, + package::install::InstallTarget, +}; +use soar_operations::{ApplyDiff, InstallOptions, UpdateInfo}; + +use crate::progress::Tracker; + +/// Identifies a job within the session. +pub(crate) type JobId = u64; + +/// The install options the interface holds while arranging an install. The +/// runner turns them into [`soar_operations::InstallOptions`], whose other +/// fields keep their defaults. +#[derive(Debug, Clone, Default)] +pub(crate) struct InstallChoices { + /// Install again even when the package is already installed. + pub(crate) force: bool, + /// Keep only the binary, skipping desktop integration and extras. + pub(crate) binary_only: bool, + /// Skip checksum verification. + pub(crate) no_verify: bool, + /// Install into the named portable directory instead of the shared tree. + pub(crate) portable: Option, +} + +impl InstallChoices { + /// The operation's options for these choices. The fields the interface + /// does not hold keep the operation's defaults. + pub(crate) fn options(&self) -> InstallOptions { + InstallOptions { + force: self.force, + binary_only: self.binary_only, + no_verify: self.no_verify, + portable: self.portable.clone(), + ..Default::default() + } + } +} + +/// A mutating operation and everything it needs to run. The views build +/// specs as their actions are accepted; until then only tests do. +#[allow(dead_code)] +pub(crate) enum JobSpec { + /// Installs the targets resolved for the packages the user picked. + Install { + /// The resolved install plans, one per package. + targets: Vec, + /// The catalog packages behind the targets, empty for installs from + /// a URL or a local path. + picked: Vec, + /// The options the install form gathered. + options: InstallChoices, + }, + /// Removes the installed packages the user marked. + Remove { + /// The database records of the packages to remove. + packages: Vec, + }, + /// Applies the listed updates, optionally keeping the old versions. + Update { + /// The checked updates to apply. + updates: Vec, + /// Whether superseded versions stay on disk. + keep_old: bool, + }, + /// Links another installed variant of a package as the active one. + Switch { + /// The database id of the variant to link. + id: u64, + /// The package name, for the job's title. + name: String, + }, + /// Refetches every enabled repository's metadata. + Sync, + /// Applies the declarative packages.toml. + Apply { + /// The plan computed beforehand, with everything to change. + diff: ApplyDiff, + /// Where the declared packages are written. + packages_path: String, + }, + /// Applies the packages marked `system = true` through a privileged + /// child. The authorization for it happens when the job's turn comes, + /// before anything runs. + ApplySystem { + /// The declared packages the system pass applies. + names: Vec, + /// Where the declared packages are written. + packages_path: String, + /// How the pass runs, decided by what the escalation probe found. + mode: SystemMode, + }, + /// Clears the download cache. + CleanCache, + /// Deletes links in the bin directory that point nowhere. + RemoveBrokenSymlinks, + /// Removes installed packages whose files are gone. + RemoveBrokenPackages, + /// Changes the repository list in the config file. + Repo(RepoChange), + /// Writes the default packages.toml when it is missing. + CreatePackagesConfig, +} + +impl JobSpec { + /// The kind of job this spec runs, kept after the spec is consumed. + pub(crate) fn kind(&self) -> JobKind { + match self { + JobSpec::Install { + .. + } => JobKind::Install, + JobSpec::Remove { + .. + } => JobKind::Remove, + JobSpec::Update { + .. + } => JobKind::Update, + JobSpec::Switch { + .. + } => JobKind::Switch, + JobSpec::Sync => JobKind::Sync, + JobSpec::Apply { + .. + } => JobKind::Apply, + JobSpec::ApplySystem { + .. + } => JobKind::ApplySystem, + JobSpec::CleanCache => JobKind::CleanCache, + JobSpec::RemoveBrokenSymlinks => JobKind::RemoveBrokenSymlinks, + JobSpec::RemoveBrokenPackages => JobKind::RemoveBrokenPackages, + JobSpec::Repo(_) => JobKind::Repo, + JobSpec::CreatePackagesConfig => JobKind::CreatePackagesConfig, + } + } + + /// The short name a job lists under. + pub(crate) fn title(&self) -> String { + match self { + JobSpec::Install { + targets, + picked, + .. + } => { + let count = if picked.is_empty() { + targets.len() + } else { + picked.len() + }; + if count > 1 { + format!("Install {count} packages") + } else if let Some(pkg) = picked.first() { + format!("Install {}", pkg.pkg_name) + } else if let Some(target) = targets.first() { + format!("Install {}", target.package.pkg_name) + } else { + "Install package".to_string() + } + } + JobSpec::Remove { + packages, + } => { + match packages.as_slice() { + [one] => format!("Remove {}", one.pkg_name), + many => format!("Remove {} packages", many.len()), + } + } + JobSpec::Update { + updates, .. + } => { + match updates.as_slice() { + [one] => format!("Update {}", one.pkg_name), + many => format!("Update {} packages", many.len()), + } + } + JobSpec::Switch { + name, .. + } => format!("Switch to {name}"), + JobSpec::Sync => "Sync repositories".to_string(), + JobSpec::Apply { + .. + } => "Apply packages.toml".to_string(), + JobSpec::ApplySystem { + names, .. + } => { + match names.len() { + 1 => "Apply 1 system package".to_string(), + count => format!("Apply {count} system packages"), + } + } + JobSpec::CleanCache => "Clean cache".to_string(), + JobSpec::RemoveBrokenSymlinks => "Remove broken symlinks".to_string(), + JobSpec::RemoveBrokenPackages => "Remove broken packages".to_string(), + JobSpec::Repo(RepoChange::Add(repo)) => format!("Add repository {}", repo.name), + JobSpec::Repo(RepoChange::SetEnabled { + name, + enabled: true, + }) => { + format!("Enable {name}") + } + JobSpec::Repo(RepoChange::SetEnabled { + name, + enabled: false, + }) => { + format!("Disable {name}") + } + JobSpec::Repo(RepoChange::Remove(name)) => format!("Remove repository {name}"), + JobSpec::CreatePackagesConfig => "Create packages.toml".to_string(), + } + } +} + +/// A change to the repository list in the config file. The repositories +/// view builds these once it exists; until then nothing constructs them. +#[allow(dead_code)] +pub(crate) enum RepoChange { + /// Adds a repository to the config. + Add(Repository), + /// Enables or disables an existing repository. + SetEnabled { + /// The repository to change. + name: String, + /// Whether it becomes enabled. + enabled: bool, + }, + /// Removes a repository from the config. + Remove(String), +} + +/// How the system pass runs. A new job starts `Pending`; the escalation +/// probe sets the mode when the job's turn comes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum SystemMode { + /// Not decided yet: the probe runs first. + Pending, + /// Through the escalation tool with its input and output captured, so + /// progress shows in the interface. + Direct, + /// With the terminal handed over, so the tool asks for a password + /// itself. + Terminal, +} + +/// What kind of job ran, kept after the spec is consumed. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum JobKind { + Install, + Remove, + Update, + Switch, + Sync, + Apply, + ApplySystem, + CleanCache, + RemoveBrokenSymlinks, + RemoveBrokenPackages, + Repo, + CreatePackagesConfig, +} + +/// Where a job is in its life. The job views read the timings and the +/// outcome once they exist; until then the queue only writes them. +pub(crate) enum JobState { + /// Waiting for its turn in the queue. + Queued, + /// Its turn has come, but it waits for the user to authorize the + /// administrator pass. The spec stays with the job, and the queue + /// holds still until the authorization ends one way or another. + Authorizing, + /// Running, with when it started and whether an abort was asked for. + Running { + /// When the job began running. + started: Instant, + /// Whether the user asked it to stop. + aborting: bool, + }, + /// Over, with when it ran and what it reports. + Finished { + /// When the job began running. + started: Instant, + /// When the job finished. + ended: Instant, + /// What the job reports. + outcome: JobOutcome, + }, +} + +/// One entry in the job list: what runs or ran, under what name, and how it +/// went. +pub(crate) struct Job { + /// The number identifying the job in the queue and its messages. + pub(crate) id: JobId, + /// The kind of operation the job runs, kept after the spec is taken. + pub(crate) kind: JobKind, + /// The short name the job lists under, in the job list and the activity + /// strip. + pub(crate) title: String, + /// Where the job is in its life. + pub(crate) state: JobState, + /// What to run. Held while the job is queued, taken when it starts. + pub(crate) spec: Option, + /// The per-package progress the operation reported so far. + pub(crate) tracker: Tracker, +} + +/// What a finished job reports, independent of which operation ran. +pub(crate) struct JobOutcome { + /// Whether everything the job touched succeeded. + pub(crate) ok: bool, + /// Whether the job stopped early because the user aborted it. The job + /// views color such jobs as warnings. + pub(crate) aborted: bool, + /// The one-line summary the toast and the activity strip show. + pub(crate) headline: String, + /// The per-package lines the job views list. + pub(crate) lines: Vec, +} + +/// One line of a finished job's report. The runner fills these from the +/// operation reports and the job views list them. +pub(crate) enum OutcomeLine { + /// A package that succeeded, as `name version`. + Done(String), + /// A package passed over without running. + Skipped(String), + /// A package that failed, with its name and the error. + Failed { + /// The package that failed. + name: String, + /// What went wrong. + error: String, + }, + /// A note about a package, such as where its configuration lives. + Note { + /// The package the note is about. + name: String, + /// What the note says. + text: String, + }, + /// Something worth knowing that is not about one package. + Warning(String), +} + +/// The jobs of the session, in the order they were queued, with the flag +/// marking an unseen failure. +pub(crate) struct Jobs { + /// Every job of the session, oldest first. + pub(crate) list: Vec, + /// The number the next job gets. + pub(crate) next_id: JobId, + /// Whether the last job failed without being seen. + pub(crate) attention: bool, +} + +impl Jobs { + /// Creates the empty queue the session starts with. + pub(crate) fn new() -> Jobs { + Jobs { + list: Vec::new(), + next_id: 0, + attention: false, + } + } +} + +#[cfg(test)] +mod tests { + use soar_core::package::install::InstallTarget; + + use super::*; + use crate::test_support::{installed_package, package}; + + fn repo(name: &str) -> Repository { + Repository { + name: name.to_string(), + url: String::new(), + desktop_integration: None, + pubkey: None, + enabled: None, + signature_verification: None, + sync_interval: None, + } + } + + fn update_info(name: &str) -> UpdateInfo { + UpdateInfo { + pkg_name: name.to_string(), + repo_name: "bincache".to_string(), + current_version: "1.0.0".to_string(), + new_version: "1.1.0".to_string(), + target: InstallTarget::default(), + update_toml_url: None, + } + } + + #[test] + fn specs_carry_kind_and_title() { + let cases: Vec<(JobSpec, JobKind, &str)> = vec![ + ( + JobSpec::Install { + targets: Vec::new(), + picked: vec![package("bat", "0.24.0", "bincache")], + options: InstallChoices::default(), + }, + JobKind::Install, + "Install bat", + ), + ( + JobSpec::Install { + targets: Vec::new(), + picked: vec![ + package("bat", "0.24.0", "bincache"), + package("fd", "10.2.0", "bincache"), + package("jq", "1.7.1", "bincache"), + ], + options: InstallChoices::default(), + }, + JobKind::Install, + "Install 3 packages", + ), + ( + JobSpec::Install { + targets: vec![InstallTarget { + package: package("bat", "0.24.0", "bincache"), + ..Default::default() + }], + picked: Vec::new(), + options: InstallChoices::default(), + }, + JobKind::Install, + "Install bat", + ), + ( + JobSpec::Remove { + packages: vec![installed_package("obsidian", "1.7.7", "pkgcache")], + }, + JobKind::Remove, + "Remove obsidian", + ), + ( + JobSpec::Remove { + packages: vec![ + installed_package("obsidian", "1.7.7", "pkgcache"), + installed_package("zellij", "0.41.2", "bincache"), + ], + }, + JobKind::Remove, + "Remove 2 packages", + ), + ( + JobSpec::Update { + updates: vec![update_info("yq")], + keep_old: false, + }, + JobKind::Update, + "Update yq", + ), + ( + JobSpec::Update { + updates: vec![update_info("yq"), update_info("fd")], + keep_old: false, + }, + JobKind::Update, + "Update 2 packages", + ), + ( + JobSpec::Switch { + id: 4, + name: "ffmpeg".to_string(), + }, + JobKind::Switch, + "Switch to ffmpeg", + ), + (JobSpec::Sync, JobKind::Sync, "Sync repositories"), + ( + JobSpec::Apply { + diff: ApplyDiff::default(), + packages_path: "packages.toml".to_string(), + }, + JobKind::Apply, + "Apply packages.toml", + ), + ( + JobSpec::ApplySystem { + names: vec!["jq".to_string()], + packages_path: "packages.toml".to_string(), + mode: SystemMode::Pending, + }, + JobKind::ApplySystem, + "Apply 1 system package", + ), + ( + JobSpec::ApplySystem { + names: vec!["docker-compose".to_string(), "tailscale".to_string()], + packages_path: "packages.toml".to_string(), + mode: SystemMode::Pending, + }, + JobKind::ApplySystem, + "Apply 2 system packages", + ), + (JobSpec::CleanCache, JobKind::CleanCache, "Clean cache"), + ( + JobSpec::RemoveBrokenSymlinks, + JobKind::RemoveBrokenSymlinks, + "Remove broken symlinks", + ), + ( + JobSpec::RemoveBrokenPackages, + JobKind::RemoveBrokenPackages, + "Remove broken packages", + ), + ( + JobSpec::Repo(RepoChange::Add(repo("foo"))), + JobKind::Repo, + "Add repository foo", + ), + ( + JobSpec::Repo(RepoChange::SetEnabled { + name: "foo".to_string(), + enabled: true, + }), + JobKind::Repo, + "Enable foo", + ), + ( + JobSpec::Repo(RepoChange::SetEnabled { + name: "foo".to_string(), + enabled: false, + }), + JobKind::Repo, + "Disable foo", + ), + ( + JobSpec::Repo(RepoChange::Remove("foo".to_string())), + JobKind::Repo, + "Remove repository foo", + ), + ( + JobSpec::CreatePackagesConfig, + JobKind::CreatePackagesConfig, + "Create packages.toml", + ), + ]; + for (spec, kind, title) in cases { + assert_eq!(spec.kind(), kind, "title {title}"); + assert_eq!(spec.title(), title, "kind {kind:?}"); + } + } +} diff --git a/crates/soar-tui/src/keymap.rs b/crates/soar-tui/src/keymap.rs new file mode 100644 index 00000000..ef74b403 --- /dev/null +++ b/crates/soar-tui/src/keymap.rs @@ -0,0 +1,264 @@ +//! The table of keys and the actions they trigger. +//! +//! The status bar hints and the help overlay read from this table, so the +//! interface never shows a hint for a key that does nothing. + +use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; + +use crate::{action::Action, views::ViewId}; + +/// One key, as the terminal reports it. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) struct Key { + /// The key itself, such as a character or a named key. + pub(crate) code: KeyCode, + /// The modifier keys held down. + pub(crate) mods: KeyModifiers, +} + +/// A key bound to an action, with how it is described to the user. +pub(crate) struct Binding { + /// Every key that triggers [`Binding::action`]. + pub(crate) keys: &'static [Key], + /// What pressing one of the keys does. + pub(crate) action: Action, + /// Short label for the status bar and help, like "install". + pub(crate) label: &'static str, + /// Whether the status bar shows this binding. + pub(crate) bar: bool, +} + +/// A plain character key without modifiers. +const fn ch(c: char) -> Key { + Key { + code: KeyCode::Char(c), + mods: KeyModifiers::NONE, + } +} + +/// A character key held with Ctrl. +const fn ctrl(c: char) -> Key { + Key { + code: KeyCode::Char(c), + mods: KeyModifiers::CONTROL, + } +} + +/// A named key without modifiers, such as an arrow or Enter. +const fn code(c: KeyCode) -> Key { + Key { + code: c, + mods: KeyModifiers::NONE, + } +} + +/// One row of a key table. +const fn bind(keys: &'static [Key], action: Action, label: &'static str, bar: bool) -> Binding { + Binding { + keys, + action, + label, + bar, + } +} + +/// Keys that work the same in every view while no overlay or text input is +/// open. +#[rustfmt::skip] +pub(crate) const GLOBAL: &[Binding] = &[ + bind(&[ch('1')], Action::View(ViewId::Browse), "browse", false), + bind(&[ch('2')], Action::View(ViewId::Installed), "installed", false), + bind(&[ch('3')], Action::View(ViewId::Updates), "updates", false), + bind(&[ch('4')], Action::View(ViewId::Apply), "apply", false), + bind(&[ch('5')], Action::View(ViewId::Repos), "repos", false), + bind(&[ch('6')], Action::View(ViewId::Health), "health", false), + bind(&[ch('7')], Action::View(ViewId::Jobs), "jobs", false), + bind(&[code(KeyCode::Tab)], Action::NextView, "next view", false), + bind(&[code(KeyCode::BackTab)], Action::PrevView, "previous view", false), + bind(&[ch('?')], Action::Help, "help", true), + bind(&[ch('q'), ctrl('c')], Action::Quit, "quit", false), + bind(&[ctrl('x')], Action::AbortJob, "abort", true), + bind(&[ctrl('r')], Action::Reload, "reload", false), + bind(&[ch('j'), code(KeyCode::Down)], Action::Down, "down", false), + bind(&[ch('k'), code(KeyCode::Up)], Action::Up, "up", false), + bind(&[ch('g'), code(KeyCode::Home)], Action::Top, "top", false), + bind(&[ch('G'), code(KeyCode::End)], Action::Bottom, "bottom", false), + bind(&[ctrl('d'), code(KeyCode::PageDown)], Action::PageDown, "page down", false), + bind(&[ctrl('u'), code(KeyCode::PageUp)], Action::PageUp, "page up", false), + bind(&[code(KeyCode::Esc)], Action::Escape, "clear", false), +]; + +/// Keys of the package catalog view. +#[rustfmt::skip] +const BROWSE: &[Binding] = &[ + bind(&[ch('/')], Action::Filter, "filter", true), + bind(&[ch(' ')], Action::ToggleMark, "mark", true), + bind(&[ch('i')], Action::Install, "install", true), + bind(&[ch('I')], Action::InstallWithOptions, "install options", false), + bind(&[ch('v')], Action::PickVersion, "version", true), + bind(&[ch('x')], Action::RunPackage, "run", true), + bind(&[ch('+')], Action::InstallByQuery, "add", true), + bind(&[ch('R')], Action::CycleRepo, "repo", true), + bind(&[code(KeyCode::Enter)], Action::ToggleDetail, "details", false), +]; + +/// Keys of the installed packages view. +#[rustfmt::skip] +const INSTALLED: &[Binding] = &[ + bind(&[ch('/')], Action::Filter, "filter", true), + bind(&[ch(' ')], Action::ToggleMark, "mark", true), + bind(&[ch('d')], Action::Remove, "remove", true), + bind(&[ch('s')], Action::SwitchVariant, "switch", true), + bind(&[ch('u')], Action::UpdateSelected, "update", true), + bind(&[ch('o')], Action::CycleSort, "sort", true), + bind(&[code(KeyCode::Enter)], Action::ToggleDetail, "details", true), +]; + +/// Keys of the updates view. +#[rustfmt::skip] +const UPDATES: &[Binding] = &[ + bind(&[ch(' ')], Action::ToggleMark, "mark", true), + bind(&[ch('a')], Action::MarkAll, "all", true), + bind(&[ch('u')], Action::Update, "update", true), + bind(&[ch('o')], Action::ToggleKeepOld, "keep old", true), + bind(&[ch('S')], Action::ToggleSkipped, "skipped", true), +]; + +/// Keys of the apply view. +#[rustfmt::skip] +const APPLY: &[Binding] = &[ + bind(&[code(KeyCode::Enter)], Action::Apply, "apply", true), + bind(&[ch('p')], Action::TogglePrune, "prune", true), + bind(&[ch('e')], Action::EditPackages, "edit", true), + bind(&[ch('n')], Action::CreatePackages, "create", true), +]; + +/// Keys of the repositories view. +#[rustfmt::skip] +const REPOS: &[Binding] = &[ + bind(&[ch('s')], Action::Sync, "sync", true), + bind(&[ch('e')], Action::ToggleEnabled, "enable/disable", true), + bind(&[ch('a')], Action::AddRepo, "add", true), + bind(&[ch('d')], Action::RemoveRepo, "remove", true), + bind(&[ch('E')], Action::EditConfig, "edit config", true), +]; + +/// Keys of the health view. +#[rustfmt::skip] +const HEALTH: &[Binding] = &[ + bind(&[ch('c')], Action::CleanCache, "clean cache", true), + bind(&[ch('b')], Action::FixSymlinks, "fix symlinks", true), + bind(&[ch('p')], Action::RemoveBroken, "remove broken", true), +]; + +/// Keys of the jobs view. +#[rustfmt::skip] +const JOBS: &[Binding] = &[ + bind(&[code(KeyCode::Enter)], Action::FocusDetail, "details", true), + bind(&[ch('l')], Action::FocusLog, "focus log", true), + bind(&[ch('x')], Action::AbortSelected, "abort", true), + bind(&[ch('c')], Action::ClearFinished, "clear finished", true), +]; + +/// Every binding of one view, without the global keys. +pub(crate) fn bindings(view: ViewId) -> &'static [Binding] { + match view { + ViewId::Browse => BROWSE, + ViewId::Installed => INSTALLED, + ViewId::Updates => UPDATES, + ViewId::Apply => APPLY, + ViewId::Repos => REPOS, + ViewId::Health => HEALTH, + ViewId::Jobs => JOBS, + } +} + +/// The action one key press stands for in a view, or `None` when the key is +/// not bound. The view's own table wins over the global table. +pub(crate) fn lookup(view: ViewId, event: KeyEvent) -> Option { + let key = normalise(event); + bindings(view) + .iter() + .chain(GLOBAL.iter()) + .find(|binding| binding.keys.contains(&key)) + .map(|binding| binding.action) +} + +/// Prepares a key event for comparison with the tables: shift alone on a +/// character key is dropped, since terminals report capital letters that way. +fn normalise(event: KeyEvent) -> Key { + let mut mods = event.modifiers; + if mods == KeyModifiers::SHIFT && matches!(event.code, KeyCode::Char(_)) { + mods = KeyModifiers::NONE; + } + Key { + code: event.code, + mods, + } +} + +/// Writes one key the way hints and help show it, like "ctrl-r" or "pgdn". +pub(crate) fn key_label(key: Key) -> String { + match (key.code, key.mods) { + (KeyCode::Char(c), KeyModifiers::CONTROL) => format!("ctrl-{}", c.to_ascii_lowercase()), + (KeyCode::Char(' '), _) => "space".to_string(), + (KeyCode::Char(c), _) => c.to_string(), + (KeyCode::Enter, _) => "enter".to_string(), + (KeyCode::Esc, _) => "esc".to_string(), + (KeyCode::Tab, _) => "tab".to_string(), + (KeyCode::BackTab, _) => "backtab".to_string(), + (KeyCode::Up, _) => "↑".to_string(), + (KeyCode::Down, _) => "↓".to_string(), + (KeyCode::Left, _) => "←".to_string(), + (KeyCode::Right, _) => "→".to_string(), + (KeyCode::Home, _) => "home".to_string(), + (KeyCode::End, _) => "end".to_string(), + (KeyCode::PageUp, _) => "pgup".to_string(), + (KeyCode::PageDown, _) => "pgdn".to_string(), + (KeyCode::Backspace, _) => "backspace".to_string(), + (KeyCode::Delete, _) => "del".to_string(), + (KeyCode::Insert, _) => "ins".to_string(), + (KeyCode::F(n), _) => format!("f{n}"), + _ => format!("{:?}", key.code).to_lowercase(), + } +} + +#[cfg(test)] +mod tests { + use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; + + use super::{GLOBAL, Key, bindings, lookup}; + use crate::{action::Action, views::ViewId}; + + #[test] + fn a_shifted_character_matches_its_binding() { + let shifted = KeyEvent::new(KeyCode::Char('G'), KeyModifiers::SHIFT); + assert_eq!(lookup(ViewId::Browse, shifted), Some(Action::Bottom)); + } + + #[test] + fn keymap_has_no_duplicate_keys() { + for view in ViewId::ALL { + let mut seen: Vec = Vec::new(); + for binding in bindings(view).iter().chain(GLOBAL.iter()) { + for key in binding.keys { + assert!( + !seen.contains(key), + "{key:?} is bound more than once for the {view:?} view", + ); + seen.push(*key); + } + } + } + } + + #[test] + fn every_view_has_bar_hints() { + for view in ViewId::ALL { + assert!( + bindings(view).iter().any(|binding| binding.bar), + "the {view:?} view has no binding for the status bar", + ); + } + } +} diff --git a/crates/soar-tui/src/lib.rs b/crates/soar-tui/src/lib.rs new file mode 100644 index 00000000..16685b92 --- /dev/null +++ b/crates/soar-tui/src/lib.rs @@ -0,0 +1,124 @@ +//! Full-screen terminal interface for soar. +//! +//! [`run`] takes over the terminal until the user quits. It drives the same +//! operations as the command line, so anything installed here is visible to +//! `soar` and the other way around. + +use std::sync::mpsc; + +use soar_config::{ + config::{CONFIG_PATH, get_current_profile, is_system_mode}, + packages::PackagesConfig, +}; +use soar_core::{SoarResult, error::SoarError}; +use tokio::runtime::Handle; + +mod action; +mod app; +mod effect; +mod event_loop; +mod format; +mod jobs; +mod keymap; +mod loadable; +mod log; +mod logging; +mod msg; +mod privileged; +mod progress; +mod runner; +mod sink; +mod terminal; +#[cfg(test)] +mod test_support; +mod theme; +mod ui; +mod views; +mod widgets; + +use app::{App, AppEnv}; +use event_loop::{InputThread, run_loop}; +use msg::Msg; +use runner::Runner; +use terminal::Session; +use theme::Theme; + +/// Settings the command line passes to the interface. +#[derive(Debug, Clone)] +pub struct TuiOptions { + /// Version string shown in the header. + pub version: String, + /// Draw without colors, using only bold, dim, and reversed text. + pub no_color: bool, + /// Use unicode symbols. When false, ASCII fallbacks are used. + pub icons: bool, + /// How many `-v` flags were given. One shows debug messages, two or more + /// show traces. + pub verbosity: u8, + /// Show only errors, hiding warnings and informational messages. + pub quiet: bool, + /// Global options to pass to a privileged soar child, such as + /// `--config` and `--profile`. + pub forward_args: Vec, +} + +/// Runs the interface until the user quits. +pub async fn run(options: TuiOptions) -> SoarResult<()> { + terminal::install_panic_hook(); + let handle = Handle::current(); + let env = AppEnv { + version: options.version.clone(), + profile: get_current_profile(), + system: is_system_mode(), + config_path: CONFIG_PATH + .read() + .map(|path| path.to_path_buf()) + .unwrap_or_default(), + packages_path: PackagesConfig::resolve_path(None), + }; + tokio::task::spawn_blocking(move || session_main(options, env, handle)) + .await + .map_err(|e| SoarError::Custom(e.to_string()))? +} + +/// Builds the channel, the state, and the terminal session, then runs the +/// loop until the user quits. +fn session_main(options: TuiOptions, env: AppEnv, handle: Handle) -> SoarResult<()> { + let (tx, rx) = mpsc::channel(); + let mut runner = Runner::new(handle, tx.clone(), options.forward_args.clone()); + let theme = Theme::new(!options.no_color, options.icons); + let mut app = App::new(env, theme); + let log_tx = tx.clone(); + logging::init(&options, move |line| { + let _ = log_tx.send(Msg::Output(line)); + }); + let mut session = Session::enter().map_err(io_failed("taking over the terminal"))?; + let input = InputThread::spawn(tx.clone()).map_err(io_failed("starting the input thread"))?; + for effect in app.startup() { + runner + .execute(effect, &mut session, &input) + .map_err(io_failed("running the startup work"))?; + } + let result = run_loop(&mut session, &mut app, &rx, &mut runner, &input, &tx); + input.stop(); + session + .leave() + .map_err(io_failed("restoring the terminal"))?; + // The interface cannot show a dead input thread's error itself, so + // the reason it gave up is reported once the screen is back. + if let Some(fatal) = &app.fatal { + eprintln!("soar-tui: {fatal}"); + } + result.map_err(io_failed("running the interface"))?; + Ok(()) +} + +/// Names what the interface was doing when an I/O error happened. +fn io_failed(action: &'static str) -> impl Fn(std::io::Error) -> SoarError { + move |source| { + SoarError::IoError { + action: action.to_string(), + source, + } + } +} diff --git a/crates/soar-tui/src/loadable.rs b/crates/soar-tui/src/loadable.rs new file mode 100644 index 00000000..8a487937 --- /dev/null +++ b/crates/soar-tui/src/loadable.rs @@ -0,0 +1,47 @@ +//! Data that background work fills in over time. + +/// The lifecycle of one piece of data a view shows. +#[allow(dead_code)] +#[derive(Debug, Default)] +pub(crate) enum Loadable { + /// Nothing has been requested yet. + #[default] + Idle, + /// A request is running. + Loading, + /// The request succeeded. + Ready(T), + /// The request failed. + Failed(String), +} + +#[allow(dead_code)] +impl Loadable { + /// Whether nothing has been requested yet. + pub(crate) fn is_idle(&self) -> bool { + matches!(self, Self::Idle) + } + + /// Whether a request is running. + pub(crate) fn is_loading(&self) -> bool { + matches!(self, Self::Loading) + } + + /// The loaded data, when the request succeeded. + pub(crate) fn ready(&self) -> Option<&T> { + if let Self::Ready(data) = self { + Some(data) + } else { + None + } + } + + /// The loaded data, when the request succeeded. + pub(crate) fn ready_mut(&mut self) -> Option<&mut T> { + if let Self::Ready(data) = self { + Some(data) + } else { + None + } + } +} diff --git a/crates/soar-tui/src/log.rs b/crates/soar-tui/src/log.rs new file mode 100644 index 00000000..9c066c8a --- /dev/null +++ b/crates/soar-tui/src/log.rs @@ -0,0 +1,180 @@ +//! The rolling log of everything the interface and soar printed. + +use std::collections::VecDeque; + +use crate::widgets::scroll::ListCursor; + +/// How many lines the log keeps, dropping the oldest beyond that. +const CAP: usize = 2000; + +/// How serious one log line is. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum LogLevel { + /// Detail that usually does not matter. + Debug, + /// Ordinary progress. + Info, + /// Something worth reading. + Warn, + /// Something failed. + Error, +} + +/// One line of the log, with when it arrived. +#[derive(Debug)] +pub(crate) struct LogLine { + /// When the line arrived, as a wall-clock string. + pub(crate) time: String, + /// How serious the line is. + pub(crate) level: LogLevel, + /// What the line says. + pub(crate) text: String, +} + +/// The last few thousand lines, with where the log pane is scrolled to. +#[derive(Debug, Default)] +pub(crate) struct Log { + /// The kept lines, oldest first. + pub(crate) lines: VecDeque, + /// Which line the log pane shows first. + pub(crate) cursor: ListCursor, + /// Whether the pane sticks to the newest line. + pub(crate) follow: bool, +} + +impl Log { + /// Creates a log that follows its own end. + pub(crate) fn new() -> Log { + Log { + lines: VecDeque::new(), + cursor: ListCursor::default(), + follow: true, + } + } + + /// Appends one line, stamped now, and drops the oldest lines above the + /// cap. While following, the cursor stays on the newest line. + pub(crate) fn push(&mut self, level: LogLevel, text: impl Into) { + self.lines.push_back(LogLine { + time: crate::format::clock_now(), + level, + text: text.into(), + }); + let len = self.lines.len(); + if len > CAP { + self.lines.drain(..len - CAP); + } + if self.follow { + self.cursor.bottom(self.lines.len()); + } + self.cursor.clamp(self.lines.len()); + } + + /// Splits one formatted subscriber line into its level and message. + /// The level word is padded to a fixed width, so the line is trimmed + /// first; a line without a known level word counts as info. + pub(crate) fn parse_output(raw: &str) -> (LogLevel, String) { + let trimmed = raw.trim_start(); + let Some((word, rest)) = trimmed.split_once(' ') else { + return (LogLevel::Info, trimmed.to_string()); + }; + let level = match word { + "ERROR" => LogLevel::Error, + "WARN" => LogLevel::Warn, + "INFO" => LogLevel::Info, + "DEBUG" | "TRACE" => LogLevel::Debug, + _ => return (LogLevel::Info, trimmed.to_string()), + }; + (level, rest.trim_start().to_string()) + } + + /// Removes ANSI escape sequences, which hook and child output often + /// carry: `ESC [` sequences end at the first byte from `@` to `~`, and + /// any other escape covers exactly one following byte. + pub(crate) fn strip_ansi(input: &str) -> String { + let bytes = input.as_bytes(); + let mut kept = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + if bytes[i] != 0x1b { + kept.push(bytes[i]); + i += 1; + continue; + } + if bytes.get(i + 1) == Some(&b'[') { + i += 2; + while i < bytes.len() && !(0x40..=0x7e).contains(&bytes[i]) { + i += 1; + } + i += 1; + } else { + i += 2; + } + } + String::from_utf8_lossy(&kept).into_owned() + } +} + +#[cfg(test)] +mod tests { + use super::{CAP, Log, LogLevel}; + + #[test] + fn pushing_past_the_cap_keeps_only_the_newest_lines() { + let mut log = Log::new(); + for n in 0..=CAP { + log.push(LogLevel::Info, format!("line {n}")); + } + assert_eq!(log.lines.len(), CAP); + assert_eq!( + log.lines.front().map(|line| line.text.as_str()), + Some("line 1") + ); + assert_eq!( + log.lines.back().map(|line| line.text.clone()), + Some(format!("line {CAP}")) + ); + } + + #[test] + fn a_padded_level_word_sets_the_level_and_the_rest_is_text() { + let (level, text) = Log::parse_output(" WARN x"); + assert_eq!(level, LogLevel::Warn); + assert_eq!(text, "x"); + let (level, text) = Log::parse_output("ERROR disk full"); + assert_eq!(level, LogLevel::Error); + assert_eq!(text, "disk full"); + } + + #[test] + fn a_line_without_a_level_word_is_info() { + let (level, text) = Log::parse_output("just some output"); + assert_eq!(level, LogLevel::Info); + assert_eq!(text, "just some output"); + } + + #[test] + fn trace_maps_to_debug() { + let (level, _) = Log::parse_output("TRACE deep detail"); + assert_eq!(level, LogLevel::Debug); + } + + #[test] + fn ansi_sequences_are_stripped() { + assert_eq!(Log::strip_ansi("\x1b[33mhi\x1b[0m"), "hi"); + assert_eq!(Log::strip_ansi("a\x1b[1mb"), "ab"); + assert_eq!(Log::strip_ansi("a\x1bXb"), "ab"); + } + + #[test] + fn following_keeps_the_cursor_on_the_newest_line() { + let mut log = Log::new(); + log.push(LogLevel::Info, "one"); + log.push(LogLevel::Info, "two"); + assert_eq!(log.cursor.window(2, 1), 1..2); + log.follow = false; + log.cursor.up(1); + log.push(LogLevel::Info, "three"); + assert_eq!(log.cursor.window(3, 1), 0..1); + } +} diff --git a/crates/soar-tui/src/logging.rs b/crates/soar-tui/src/logging.rs new file mode 100644 index 00000000..79e6415e --- /dev/null +++ b/crates/soar-tui/src/logging.rs @@ -0,0 +1,117 @@ +//! Routes soar's log records into the interface instead of onto the screen. +//! +//! While the interface runs, nothing else may write to the terminal. A +//! subscriber formats each record as one plain line and hands it to a callback, +//! which feeds the interface's log. + +use std::{io::Write, sync::Arc}; + +use tracing_subscriber::{filter::LevelFilter, fmt::MakeWriter}; + +use crate::TuiOptions; + +/// The callback that receives each formatted log line. +type OnLine = Arc; + +/// Creates the writer each log record is formatted into. +struct LineWriter { + on_line: OnLine, +} + +impl LineWriter { + fn new(on_line: impl Fn(String) + Send + Sync + 'static) -> Self { + Self { + on_line: Arc::new(on_line), + } + } +} + +impl<'a> MakeWriter<'a> for LineWriter { + type Writer = LineBuffer; + + fn make_writer(&'a self) -> Self::Writer { + LineBuffer { + buffer: Vec::new(), + on_line: Arc::clone(&self.on_line), + } + } +} + +/// Collects the bytes of one record and hands each of its lines to the callback +/// once the record is fully formatted. +struct LineBuffer { + buffer: Vec, + on_line: OnLine, +} + +impl Write for LineBuffer { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.buffer.extend_from_slice(buf); + Ok(buf.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +impl Drop for LineBuffer { + fn drop(&mut self) { + let output = String::from_utf8_lossy(&self.buffer); + for line in output.lines() { + if !line.is_empty() { + (self.on_line)(line.to_string()); + } + } + } +} + +/// Installs the interface's log subscriber. +/// +/// The level follows the command line: errors only when quiet, debug with one +/// `-v`, trace with two or more, and info otherwise. Lines are plain text whose +/// prefix names the level, so they can be shown in the interface's log. +/// Installing does nothing when a subscriber is already set. +pub(crate) fn init(options: &TuiOptions, on_line: impl Fn(String) + Send + Sync + 'static) { + let level = if options.quiet { + LevelFilter::ERROR + } else if options.verbosity >= 2 { + LevelFilter::TRACE + } else if options.verbosity == 1 { + LevelFilter::DEBUG + } else { + LevelFilter::INFO + }; + + let _ = tracing_subscriber::fmt() + .with_ansi(false) + .without_time() + .with_target(false) + .with_level(true) + .with_max_level(level) + .with_writer(LineWriter::new(on_line)) + .try_init(); +} + +#[cfg(test)] +mod tests { + use std::{ + io::Write as _, + sync::{Arc, Mutex}, + }; + + use tracing_subscriber::fmt::MakeWriter as _; + + use super::LineWriter; + + #[test] + fn lines_reach_the_callback_when_the_writer_drops() { + let lines: Arc>> = Arc::new(Mutex::new(Vec::new())); + let seen = Arc::clone(&lines); + let writer = LineWriter::new(move |line| seen.lock().unwrap().push(line)); + let mut sink = writer.make_writer(); + sink.write_all(b"WARN a\nINFO b\n").unwrap(); + drop(sink); + assert_eq!(*lines.lock().unwrap(), ["WARN a", "INFO b"]); + } +} diff --git a/crates/soar-tui/src/msg.rs b/crates/soar-tui/src/msg.rs new file mode 100644 index 00000000..be47755a --- /dev/null +++ b/crates/soar-tui/src/msg.rs @@ -0,0 +1,176 @@ +//! Everything that can arrive while the interface runs. + +use std::path::PathBuf; + +use ratatui::crossterm::event::Event; +use soar_core::{database::models::Package, package::install::InstallTarget}; +use soar_events::SoarEvent; +use soar_operations::{ + HealthReport, InstalledListResult, PrepareRunResult, UpdateInfo, VariantInfo, +}; + +use crate::{ + jobs::{InstallChoices, JobId, JobOutcome}, + privileged::EscalationProbe, + views::{ + apply::ApplyPlan, + browse::{CatalogRow, PackageKey}, + repos::RepoRow, + }, +}; + +/// One thing the interface's state can react to. +pub(crate) enum Msg { + /// A terminal event, such as a key press or a resize. + Input(Event), + /// The periodic tick that drives animation. + Tick, + /// Asks for one repaint after the interface has taken the terminal + /// back from a suspended program. + Redraw, + /// Reports the file the user finished editing while the interface was + /// suspended, so the views that depend on it can reload. + Edited(PathBuf), + /// Reports that reading the terminal failed, with why, so the + /// interface can quit instead of running deaf. + InputFailed(String), + /// An event from a running soar operation, feeding the progress of the + /// running job or of background work. + Soar(SoarEvent), + /// One formatted log line from the interface's subscriber. + Output(String), + /// Read-only background work finished, with its result. + Loaded(Loaded), + /// A job finished, with what it reports. + JobFinished { + /// The job that finished. + id: JobId, + /// What the job reports. + outcome: JobOutcome, + }, +} + +/// Results of read-only background work the runner performed. +pub(crate) enum Loaded { + /// The package catalog, one row per package, or why it could not + /// load. The `check` number says which load is answering; a number + /// the app no longer expects is stale, because a newer load replaced + /// it while both ran. + Catalog { + /// The number the load was started with. + check: u32, + /// The catalog rows, or why the load failed. + result: Result, String>, + }, + /// The installed packages, with their sizes and health, or why the + /// listing could not load. The `check` number says which load is + /// answering; a number the app no longer expects is stale. + Installed { + /// The number the load was started with. + check: u32, + /// The installed listing, or why the load failed. + result: Result, + }, + /// The installed packages with a newer version available, or why the + /// check could not run. The `check` number says which check is + /// answering; a number the view no longer expects is stale. + Updates { + /// The number the check was started with. + check: u32, + /// What the check found. + result: Result, String>, + }, + /// What applying the packages file would change, or why the plan + /// could not be computed. The `check` number says which computation + /// is answering; a number the view no longer expects is stale. + ApplyDiff { + /// The number the computation was started with. + check: u32, + /// The computed plan, or why it failed. + result: Result, + }, + /// The configured repositories, one row each, or why the load could + /// not run. + Repos(Result, String>), + /// The installation health report with the paths soar uses, or why + /// the check could not run. + Health(Result<(HealthReport, Vec<(String, PathBuf)>), String>), + /// The installed variants of one package name, or why the listing + /// could not load. + Variants { + /// The package name the variants belong to. + name: String, + /// The variants, or why they could not load. + result: Box, String>>, + }, + /// One package's full metadata for the detail pane. The result stays + /// `None` when the repositories hold no package with that query. It + /// is boxed because the metadata alone outweighs every other message. + Detail { + /// The package the details are for. + key: PackageKey, + /// The metadata, or why it could not load. + result: Box, String>>, + }, + /// The outcome of resolving install queries, with the options the + /// install runs with once it is confirmed. + Resolved { + /// The options gathered before the queries were sent. + choices: InstallChoices, + /// One outcome per query, in query order, or why the resolve + /// failed. + result: Result, String>, + }, + /// The outcome of preparing a package run, with the arguments the + /// run prompt collected. The result is boxed because an ambiguous + /// query can carry a large list of packages. + RunReady { + /// The arguments the binary runs with. + args: Vec, + /// The path to execute, the variants to pick between, or why the + /// preparation failed. + result: Box>, + }, + /// What the escalation probe learned about running the system pass. + Escalation(EscalationProbe), + /// The answer of the password check `check` started by + /// `Effect::Authenticate`, or why it could not run. + Authenticated { + /// Which password check this answers: every submission numbers + /// itself, and an answer from an older one is dropped. + check: u32, + /// Whether sudo took the password, or why it refused it. + result: Result<(), String>, + }, +} + +/// The outcome of resolving one install query. +pub(crate) enum Resolution { + /// The query resolved into install plans, ready to run. + Ready(Vec), + /// Several packages match the query; one has to be picked. + Ambiguous { + /// The query that matched more than one package. + query: String, + /// The packages the query matched. + candidates: Vec, + }, + /// Nothing matches the query, with close names to suggest. + NotFound { + /// The query nothing matched. + query: String, + /// Similar names worth trying instead. + suggestions: Vec, + }, + /// A version of the package is installed already. + AlreadyInstalled { + /// The installed package's name. + name: String, + /// The repository the installed copy came from. + #[allow(dead_code)] + repo: String, + /// The version of the installed copy. + #[allow(dead_code)] + version: String, + }, +} diff --git a/crates/soar-tui/src/privileged.rs b/crates/soar-tui/src/privileged.rs new file mode 100644 index 00000000..d5c0f939 --- /dev/null +++ b/crates/soar-tui/src/privileged.rs @@ -0,0 +1,148 @@ +//! Running the administrator pass: the password secret, and what a probe +//! learned about getting root here. + +use std::{ + io::Write as _, + process::{Command, Stdio}, +}; + +use soar_operations::privilege::{ + ESCALATION_DIRS, EscalationKind, EscalationTool, find_escalation_tool, runs_without_password, +}; + +/// A password on its way to sudo. Zeroed when dropped, never printed. +pub(crate) struct Secret(Vec); + +impl Secret { + /// Wraps the password bytes. The dialog builds one when the user + /// submits it. + pub(crate) fn new(bytes: Vec) -> Secret { + Secret(bytes) + } + + /// The bytes to write to sudo's input. + pub(crate) fn bytes(&self) -> &[u8] { + &self.0 + } +} + +impl Drop for Secret { + fn drop(&mut self) { + self.0.fill(0); + std::hint::black_box(&self.0); + } +} + +impl std::fmt::Debug for Secret { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("Secret(hidden)") + } +} + +/// What it takes to run the system pass. +pub(crate) enum EscalationProbe { + /// Root already, or the tool runs without asking. + Ready, + /// sudo needs a password, which the dialog can supply. + Password, + /// doas needs a password, which only it can ask for, in the + /// terminal. The probe carries the tool so the pass can run through + /// it once the user agrees. + Terminal(EscalationTool), + /// No way to get root. The message is the same one the command line + /// prints, and lands in the job's report. + Unavailable(String), +} + +/// Checks how the system pass could run here. Probing runs +/// `tool -n true` with no terminal input, so it never prompts. +pub(crate) fn probe_escalation() -> EscalationProbe { + if soar_utils::system::is_root() { + return EscalationProbe::Ready; + } + let Some(tool) = find_escalation_tool() else { + return EscalationProbe::Unavailable(format!( + "System mode requires root privileges. Neither 'doas' nor 'sudo' found in {}.", + ESCALATION_DIRS.join(", ") + )); + }; + if runs_without_password(&tool) { + return EscalationProbe::Ready; + } + match tool.kind { + EscalationKind::Sudo => EscalationProbe::Password, + EscalationKind::Doas => EscalationProbe::Terminal(tool), + } +} + +/// Writes the password to `sudo -S -v`, which caches the credentials, so +/// the system pass itself later runs with `sudo -n` and never sees the +/// password. It is never logged, formatted, or kept past this call. A +/// failed write ends the attempt instead of leaving sudo reading the +/// interface's own input. +pub(crate) fn authenticate(secret: Secret) -> Result<(), String> { + let Some(tool) = find_escalation_tool() else { + return Err("No escalation tool found".to_string()); + }; + if !matches!(tool.kind, EscalationKind::Sudo) { + return Err(format!( + "{} cannot take a password from the interface", + tool.path.display() + )); + } + let mut child = Command::new(&tool.path) + .args(["-S", "-v", "-p", ""]) + .stdin(Stdio::piped()) + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .spawn() + .map_err(|err| format!("starting {}: {err}", tool.path.display()))?; + let Some(mut stdin) = child.stdin.take() else { + let _ = child.wait(); + return Err("sudo would not take the password".to_string()); + }; + if let Err(err) = stdin + .write_all(secret.bytes()) + .and_then(|()| stdin.write_all(b"\n")) + { + // A failed write means the pipe broke and sudo is going away, so + // the wait cannot hang; dropping the input first also signals EOF + // if it lingers. + drop(stdin); + let _ = child.wait(); + return Err(format!("writing the password to sudo: {err}")); + } + // Closing the input tells sudo the password is complete; the secret + // is gone from memory before sudo answers. + drop(stdin); + drop(secret); + let output = child + .wait_with_output() + .map_err(|err| format!("waiting for {}: {err}", tool.path.display()))?; + if output.status.success() { + return Ok(()); + } + let stderr = String::from_utf8_lossy(&output.stderr); + let lowered = stderr.to_lowercase(); + if lowered.contains("incorrect password") + || lowered.contains("sorry") + || lowered.contains("no password") + || lowered.contains("a password is required") + { + return Err("Incorrect password, try again".to_string()); + } + Err(stderr.trim().to_string()) +} + +#[cfg(test)] +mod tests { + use super::Secret; + + #[test] + fn debugging_a_secret_hides_the_password() { + let secret = Secret::new("hunter2".bytes().collect()); + let printed = format!("{secret:?}"); + assert_eq!(printed, "Secret(hidden)"); + assert!(!printed.contains("hunter2")); + } +} diff --git a/crates/soar-tui/src/progress.rs b/crates/soar-tui/src/progress.rs new file mode 100644 index 00000000..fc0b49dc --- /dev/null +++ b/crates/soar-tui/src/progress.rs @@ -0,0 +1,956 @@ +//! Live per-package progress, folded from the events operations emit. +//! +//! The tracker is pure state with no I/O: [`Tracker::apply`] folds events in +//! against a timestamp, and rendering reads rows out. The activity strip and +//! the job detail list the rows once they render. + +#![allow(dead_code)] + +use std::time::{Duration, Instant}; + +use soar_events::{ + BuildStage, HookStage, InstallStage, OperationId, RemoveStage, RunStage, SoarEvent, SyncStage, + UpdateCleanupStage, VerifyStage, +}; + +/// Where one operation is in its work. +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum Phase { + /// Known but untouched: its first event carried no stage of its own. + Waiting, + /// Bytes are moving, with how many arrived and how many to expect. + Downloading { + /// Bytes received so far. + current: u64, + /// Bytes to receive in total. + total: u64, + }, + /// Between downloads, showing what the operation is doing now. + Step(String), + /// Finished cleanly. + Done, + /// Stopped by an error, carrying it for display. + Failed(String), + /// Passed over without running, such as by an abort. + Skipped, +} + +/// One operation's progress inside a job, shown as one line. +#[derive(Debug)] +pub(crate) struct OpRow { + /// The operation the row belongs to. + pub(crate) op_id: OperationId, + /// The package the operation works on. + pub(crate) name: String, + /// Where the operation is in its work. + pub(crate) phase: Phase, + /// The smoothed download speed in bytes per second, while downloading. + pub(crate) speed: Option, + /// The last line a hook or build command printed. + pub(crate) last_output: Option, + /// The previous byte count and when it was seen, for the speed. + last_sample: Option<(Instant, u64)>, +} + +impl OpRow { + /// Folds a new byte count into the smoothed download speed. Samples + /// less than 200 ms apart are too noisy to divide. + fn sample(&mut self, current: u64, now: Instant) { + let Some((at, bytes)) = self.last_sample else { + self.last_sample = Some((now, current)); + return; + }; + let dt = now.duration_since(at); + if dt < Duration::from_millis(200) || current < bytes { + return; + } + let inst = (current - bytes) as f64 / dt.as_secs_f64(); + self.speed = Some(match self.speed { + Some(smoothed) => 0.3 * inst + 0.7 * smoothed, + None => inst, + }); + self.last_sample = Some((now, current)); + } + + /// The time left until the download finishes, when the size is known + /// and the smoothed speed is high enough to divide by. + pub(crate) fn eta(&self) -> Option { + let Phase::Downloading { + current, + total, + } = self.phase + else { + return None; + }; + let speed = self.speed?; + if total == 0 || speed <= 1.0 { + return None; + } + Some(Duration::from_secs_f64( + total.saturating_sub(current) as f64 / speed, + )) + } +} + +/// Every operation row of one job or of background work, plus the overall +/// batch and sync progress. +#[derive(Debug, Default)] +pub(crate) struct Tracker { + /// One row per operation, in the order their first event arrived. + pub(crate) ops: Vec, + /// The batch counts as completed, total, and failed. + pub(crate) batch: Option<(u32, u32, u32)>, + /// Each repository's sync stage, in first-seen order. + pub(crate) sync: Vec<(String, String)>, +} + +impl Tracker { + /// Folds one operation event in. A new operation appends a row at the + /// end; a known one updates in place, so rows never jump around. + pub(crate) fn apply(&mut self, event: &SoarEvent, now: Instant) { + match event { + SoarEvent::DownloadPreparing { + op_id, + pkg_name, + } => { + self.row(*op_id, pkg_name).phase = Phase::Step("connecting".into()); + } + SoarEvent::DownloadStarting { + op_id, + pkg_name, + total, + } => { + self.row(*op_id, pkg_name).phase = Phase::Downloading { + current: 0, + total: *total, + }; + } + SoarEvent::DownloadResuming { + op_id, + pkg_name, + current, + total, + } => { + self.row(*op_id, pkg_name).phase = Phase::Downloading { + current: *current, + total: *total, + }; + } + SoarEvent::DownloadProgress { + op_id, + pkg_name, + current, + total, + } => { + let row = self.row(*op_id, pkg_name); + row.phase = Phase::Downloading { + current: *current, + total: *total, + }; + row.sample(*current, now); + } + SoarEvent::DownloadComplete { + op_id, + pkg_name, + .. + } => { + self.row(*op_id, pkg_name).phase = Phase::Step("downloaded".into()); + } + SoarEvent::DownloadRetry { + op_id, + pkg_name, + } => { + self.row(*op_id, pkg_name).phase = Phase::Step("retrying".into()); + } + SoarEvent::DownloadAborted { + op_id, + pkg_name, + } => { + self.row(*op_id, pkg_name).phase = Phase::Failed("download aborted".into()); + } + SoarEvent::DownloadRecovered { + op_id, + pkg_name, + } => { + self.row(*op_id, pkg_name); + } + SoarEvent::Verifying { + op_id, + pkg_name, + stage, + } => { + self.row(*op_id, pkg_name).phase = match stage { + VerifyStage::Checksum => Phase::Step("verifying checksum".into()), + VerifyStage::Signature => Phase::Step("verifying signature".into()), + VerifyStage::Passed => Phase::Step("verified".into()), + VerifyStage::Failed(error) => Phase::Failed(error.clone()), + }; + } + SoarEvent::Installing { + op_id, + pkg_name, + stage, + } => { + self.row(*op_id, pkg_name).phase = match stage { + InstallStage::Extracting | InstallStage::ExtractingNested => { + Phase::Step("extracting".into()) + } + InstallStage::LinkingBinaries => Phase::Step("linking binaries".into()), + InstallStage::DesktopIntegration => Phase::Step("desktop integration".into()), + InstallStage::FetchingSet(set) => Phase::Step(format!("fetching {set}")), + InstallStage::SetupPortable => Phase::Step("portable directories".into()), + InstallStage::RecordingDatabase => Phase::Step("recording".into()), + InstallStage::RunningHook(hook) => Phase::Step(format!("running {hook}")), + InstallStage::Complete => Phase::Done, + }; + } + SoarEvent::Removing { + op_id, + pkg_name, + stage, + } => { + self.row(*op_id, pkg_name).phase = match stage { + RemoveStage::RunningHook(hook) => Phase::Step(format!("running {hook}")), + RemoveStage::UnlinkingBinaries + | RemoveStage::UnlinkingDesktop + | RemoveStage::UnlinkingIcons => Phase::Step("unlinking".into()), + RemoveStage::RemovingDirectory => Phase::Step("deleting files".into()), + RemoveStage::CleaningDatabase => Phase::Step("recording".into()), + RemoveStage::Complete { + .. + } => Phase::Done, + }; + } + SoarEvent::UpdateCleanup { + op_id, + pkg_name, + old_version, + stage, + } => { + let row = self.row(*op_id, pkg_name); + if let UpdateCleanupStage::Removing = stage { + row.phase = Phase::Step(format!("removing {old_version}")); + } + } + SoarEvent::Hook { + op_id, + pkg_name, + hook_name, + stage, + } => { + let row = self.row(*op_id, pkg_name); + match stage { + HookStage::Starting => { + row.phase = Phase::Step(format!("running {hook_name}")); + } + HookStage::Failed { + exit_code, + } => { + row.phase = Phase::Step(match exit_code { + Some(code) => format!("{hook_name} failed ({code})"), + None => format!("{hook_name} failed"), + }); + } + HookStage::Complete => {} + } + } + SoarEvent::Building { + op_id, + pkg_name, + stage, + } => { + let row = self.row(*op_id, pkg_name); + match stage { + BuildStage::Sandboxing => { + row.phase = Phase::Step("preparing sandbox".into()); + } + BuildStage::Running { + command_index, + total_commands, + } => { + row.phase = Phase::Step(format!( + "building {}/{}", + command_index + 1, + total_commands + )); + } + BuildStage::CommandComplete { + .. + } => {} + } + } + SoarEvent::Running { + op_id, + pkg_name, + stage, + } => { + self.row(*op_id, pkg_name).phase = match stage { + RunStage::CacheHit => Phase::Step("cached".into()), + RunStage::Downloading => Phase::Step("downloading".into()), + RunStage::Executing => Phase::Step("running".into()), + RunStage::Complete { + .. + } => Phase::Done, + }; + } + SoarEvent::ProcessOutput { + op_id, + pkg_name, + line, + } => { + self.row(*op_id, pkg_name).last_output = Some(line.clone()); + } + SoarEvent::OperationComplete { + op_id, + pkg_name, + } => { + self.row(*op_id, pkg_name).phase = Phase::Done; + } + SoarEvent::OperationFailed { + op_id, + pkg_name, + error, + } => { + self.row(*op_id, pkg_name).phase = Phase::Failed(error.clone()); + } + SoarEvent::OperationCancelled { + op_id, + pkg_name, + } => { + self.row(*op_id, pkg_name).phase = Phase::Skipped; + } + SoarEvent::BatchProgress { + completed, + total, + failed, + } => { + self.batch = Some((*completed, *total, *failed)); + } + SoarEvent::SyncProgress { + repo_name, + stage, + } => { + let label = match stage { + SyncStage::Fetching => "fetching", + SyncStage::UpToDate => "up to date", + SyncStage::Decompressing => "decompressing", + SyncStage::WritingDatabase => "writing", + SyncStage::Validating => "validating", + SyncStage::Complete { + .. + } => "done", + }; + match self.sync.iter_mut().find(|(repo, _)| repo == repo_name) { + Some((_, known)) => *known = label.to_string(), + None => self.sync.push((repo_name.clone(), label.to_string())), + } + } + SoarEvent::UpdateCheck { + .. + } + | SoarEvent::ApplyComplete { + .. + } + | SoarEvent::Log { + .. + } => {} + } + } + + /// The rows still working: waiting, downloading, or between stages. + /// Finished, failed, and skipped rows drop out. + pub(crate) fn active(&self) -> impl Iterator { + self.ops + .iter() + .filter(|row| !matches!(row.phase, Phase::Done | Phase::Failed(_) | Phase::Skipped)) + } + + /// The repositories whose sync is still moving, in first-seen order. + /// Repositories that reached their final stage drop out, so the + /// activity strip stops listing them once their work ends. + pub(crate) fn active_sync(&self) -> impl Iterator { + self.sync + .iter() + .filter(|(_, stage)| !matches!(stage.as_str(), "done" | "up to date")) + } + + /// The row of one operation, appended at the end when it is new. + fn row(&mut self, op_id: OperationId, name: &str) -> &mut OpRow { + let index = match self.ops.iter().position(|row| row.op_id == op_id) { + Some(index) => index, + None => { + self.ops.push(OpRow { + op_id, + name: name.to_string(), + phase: Phase::Waiting, + speed: None, + last_sample: None, + last_output: None, + }); + self.ops.len() - 1 + } + }; + &mut self.ops[index] + } +} + +#[cfg(test)] +mod tests { + use std::time::{Duration, Instant}; + + use soar_events::{ + BuildStage, HookStage, InstallStage, RemoveStage, RunStage, SoarEvent, SyncStage, + UpdateCheckStatus, UpdateCleanupStage, VerifyStage, + }; + + use super::{Phase, Tracker}; + + fn preparing(op: u64, name: &str) -> SoarEvent { + SoarEvent::DownloadPreparing { + op_id: op, + pkg_name: name.into(), + } + } + + fn progress(op: u64, current: u64, total: u64) -> SoarEvent { + SoarEvent::DownloadProgress { + op_id: op, + pkg_name: "bat".into(), + current, + total, + } + } + + fn verifying(op: u64, stage: VerifyStage) -> SoarEvent { + SoarEvent::Verifying { + op_id: op, + pkg_name: "bat".into(), + stage, + } + } + + fn installing(op: u64, stage: InstallStage) -> SoarEvent { + SoarEvent::Installing { + op_id: op, + pkg_name: "bat".into(), + stage, + } + } + + fn removing(op: u64, stage: RemoveStage) -> SoarEvent { + SoarEvent::Removing { + op_id: op, + pkg_name: "bat".into(), + stage, + } + } + + fn running(op: u64, stage: RunStage) -> SoarEvent { + SoarEvent::Running { + op_id: op, + pkg_name: "bat".into(), + stage, + } + } + + fn building(op: u64, stage: BuildStage) -> SoarEvent { + SoarEvent::Building { + op_id: op, + pkg_name: "bat".into(), + stage, + } + } + + fn sync_progress(repo: &str, stage: SyncStage) -> SoarEvent { + SoarEvent::SyncProgress { + repo_name: repo.into(), + stage, + } + } + + /// Asserts a smoothed speed within one byte per second of the expected + /// one. + fn assert_speed(actual: Option, expected: f64) { + let actual = actual.unwrap(); + assert!( + (actual - expected).abs() < 1.0, + "expected {expected}, got {actual}" + ); + } + + #[test] + fn a_download_replays_from_connecting_to_done() { + let mut tracker = Tracker::default(); + let start = Instant::now(); + tracker.apply(&preparing(1, "bat"), start); + assert_eq!(tracker.ops[0].phase, Phase::Step("connecting".into())); + tracker.apply( + &SoarEvent::DownloadStarting { + op_id: 1, + pkg_name: "bat".into(), + total: 1000, + }, + start, + ); + assert_eq!( + tracker.ops[0].phase, + Phase::Downloading { + current: 0, + total: 1000 + } + ); + tracker.apply(&progress(1, 500, 1000), start + Duration::from_millis(500)); + assert_eq!( + tracker.ops[0].phase, + Phase::Downloading { + current: 500, + total: 1000 + } + ); + assert_eq!(tracker.ops[0].speed, None); + tracker.apply( + &progress(1, 1000, 1000), + start + Duration::from_millis(1000), + ); + assert_speed(tracker.ops[0].speed, 1000.0); + tracker.apply(&verifying(1, VerifyStage::Checksum), start); + assert_eq!( + tracker.ops[0].phase, + Phase::Step("verifying checksum".into()) + ); + tracker.apply(&installing(1, InstallStage::LinkingBinaries), start); + assert_eq!(tracker.ops[0].phase, Phase::Step("linking binaries".into())); + tracker.apply(&installing(1, InstallStage::Complete), start); + assert_eq!(tracker.ops[0].phase, Phase::Done); + } + + #[test] + fn speed_smooths_over_the_previous_sample() { + let mut tracker = Tracker::default(); + let start = Instant::now(); + tracker.apply(&progress(1, 0, 10_000), start); + tracker.apply(&progress(1, 1_000, 10_000), start + Duration::from_secs(1)); + tracker.apply(&progress(1, 3_000, 10_000), start + Duration::from_secs(2)); + assert_speed(tracker.ops[0].speed, 1300.0); + } + + #[test] + fn samples_closer_than_200ms_do_not_move_the_speed() { + let mut tracker = Tracker::default(); + let start = Instant::now(); + tracker.apply(&progress(1, 0, 10_000), start); + tracker.apply(&progress(1, 1_000, 10_000), start + Duration::from_secs(1)); + assert_speed(tracker.ops[0].speed, 1000.0); + tracker.apply( + &progress(1, 1_500, 10_000), + start + Duration::from_millis(1100), + ); + assert_speed(tracker.ops[0].speed, 1000.0); + tracker.apply( + &progress(1, 2_000, 10_000), + start + Duration::from_millis(1500), + ); + assert_speed(tracker.ops[0].speed, 1300.0); + } + + #[test] + fn interleaved_operations_keep_first_seen_order() { + let mut tracker = Tracker::default(); + let start = Instant::now(); + tracker.apply(&preparing(1, "bat"), start); + tracker.apply(&preparing(2, "fd"), start); + tracker.apply(&progress(2, 100, 500), start); + tracker.apply(&progress(1, 300, 500), start); + assert_eq!(tracker.ops.len(), 2); + assert_eq!(tracker.ops[0].op_id, 1); + assert_eq!(tracker.ops[0].name, "bat"); + assert_eq!( + tracker.ops[0].phase, + Phase::Downloading { + current: 300, + total: 500 + } + ); + assert_eq!(tracker.ops[1].op_id, 2); + assert_eq!(tracker.ops[1].name, "fd"); + assert_eq!( + tracker.ops[1].phase, + Phase::Downloading { + current: 100, + total: 500 + } + ); + } + + #[test] + fn an_operation_failure_records_the_message() { + let mut tracker = Tracker::default(); + let start = Instant::now(); + tracker.apply(&preparing(1, "bat"), start); + tracker.apply( + &SoarEvent::OperationFailed { + op_id: 1, + pkg_name: "bat".into(), + error: "checksum mismatch".into(), + }, + start, + ); + assert_eq!( + tracker.ops[0].phase, + Phase::Failed("checksum mismatch".into()) + ); + assert_eq!(tracker.active().count(), 0); + } + + #[test] + fn a_cancelled_operation_is_skipped_and_inactive() { + let mut tracker = Tracker::default(); + let start = Instant::now(); + tracker.apply(&preparing(1, "bat"), start); + tracker.apply( + &SoarEvent::OperationCancelled { + op_id: 1, + pkg_name: "bat".into(), + }, + start, + ); + assert_eq!(tracker.ops[0].phase, Phase::Skipped); + assert_eq!(tracker.active().count(), 0); + } + + #[test] + fn batch_progress_records_the_counts_without_making_a_row() { + let mut tracker = Tracker::default(); + let start = Instant::now(); + tracker.apply( + &SoarEvent::BatchProgress { + completed: 1, + total: 3, + failed: 1, + }, + start, + ); + tracker.apply(&preparing(1, "bat"), start); + assert_eq!(tracker.batch, Some((1, 3, 1))); + assert_eq!(tracker.ops.len(), 1); + } + + #[test] + fn sync_progress_upserts_repos_in_first_seen_order() { + let mut tracker = Tracker::default(); + let start = Instant::now(); + tracker.apply(&sync_progress("bincache", SyncStage::Fetching), start); + tracker.apply(&sync_progress("pkgforge", SyncStage::Decompressing), start); + tracker.apply( + &sync_progress( + "bincache", + SyncStage::Complete { + package_count: Some(1200), + }, + ), + start, + ); + tracker.apply(&sync_progress("pkgforge", SyncStage::UpToDate), start); + assert_eq!( + tracker.sync, + vec![ + ("bincache".to_string(), "done".to_string()), + ("pkgforge".to_string(), "up to date".to_string()), + ] + ); + } + + #[test] + fn process_output_keeps_the_phase_and_holds_the_line() { + let mut tracker = Tracker::default(); + let start = Instant::now(); + tracker.apply( + &installing(1, InstallStage::RunningHook("post_install".into())), + start, + ); + tracker.apply( + &SoarEvent::ProcessOutput { + op_id: 1, + pkg_name: "bat".into(), + line: "Created ~/.config/bat".into(), + }, + start, + ); + assert_eq!( + tracker.ops[0].phase, + Phase::Step("running post_install".into()) + ); + assert_eq!( + tracker.ops[0].last_output.as_deref(), + Some("Created ~/.config/bat") + ); + } + + #[test] + fn update_checks_touch_no_row() { + let mut tracker = Tracker::default(); + let start = Instant::now(); + tracker.apply(&preparing(1, "bat"), start); + tracker.apply( + &SoarEvent::UpdateCheck { + pkg_name: "bat".into(), + status: UpdateCheckStatus::UpToDate { + version: "1.0.0".into(), + }, + }, + start, + ); + assert_eq!(tracker.ops.len(), 1); + assert_eq!(tracker.batch, None); + assert!(tracker.sync.is_empty()); + } + + #[test] + fn stages_show_their_labels() { + let cases: Vec<(SoarEvent, &str)> = vec![ + (verifying(1, VerifyStage::Signature), "verifying signature"), + (verifying(1, VerifyStage::Passed), "verified"), + (installing(1, InstallStage::Extracting), "extracting"), + (installing(1, InstallStage::ExtractingNested), "extracting"), + ( + installing(1, InstallStage::DesktopIntegration), + "desktop integration", + ), + ( + installing(1, InstallStage::FetchingSet("onelf".into())), + "fetching onelf", + ), + ( + installing(1, InstallStage::SetupPortable), + "portable directories", + ), + (installing(1, InstallStage::RecordingDatabase), "recording"), + ( + installing(1, InstallStage::RunningHook("post_download".into())), + "running post_download", + ), + ( + removing(1, RemoveStage::RunningHook("pre_remove".into())), + "running pre_remove", + ), + (removing(1, RemoveStage::UnlinkingBinaries), "unlinking"), + (removing(1, RemoveStage::UnlinkingDesktop), "unlinking"), + (removing(1, RemoveStage::UnlinkingIcons), "unlinking"), + ( + removing(1, RemoveStage::RemovingDirectory), + "deleting files", + ), + (removing(1, RemoveStage::CleaningDatabase), "recording"), + (building(1, BuildStage::Sandboxing), "preparing sandbox"), + (running(1, RunStage::CacheHit), "cached"), + (running(1, RunStage::Downloading), "downloading"), + (running(1, RunStage::Executing), "running"), + ]; + for (event, label) in cases { + let mut tracker = Tracker::default(); + tracker.apply(&event, Instant::now()); + assert_eq!(tracker.ops[0].phase, Phase::Step(label.into()), "{event:?}"); + } + } + + #[test] + fn failures_completions_and_resumes_map_their_phases() { + let cases: Vec<(SoarEvent, Phase)> = vec![ + ( + verifying(1, VerifyStage::Failed("bad signature".into())), + Phase::Failed("bad signature".into()), + ), + ( + SoarEvent::DownloadAborted { + op_id: 1, + pkg_name: "bat".into(), + }, + Phase::Failed("download aborted".into()), + ), + ( + SoarEvent::DownloadRetry { + op_id: 1, + pkg_name: "bat".into(), + }, + Phase::Step("retrying".into()), + ), + ( + SoarEvent::DownloadComplete { + op_id: 1, + pkg_name: "bat".into(), + total: 500, + }, + Phase::Step("downloaded".into()), + ), + ( + SoarEvent::DownloadResuming { + op_id: 1, + pkg_name: "bat".into(), + current: 200, + total: 500, + }, + Phase::Downloading { + current: 200, + total: 500, + }, + ), + ( + running( + 1, + RunStage::Complete { + exit_code: 0, + }, + ), + Phase::Done, + ), + ( + removing( + 1, + RemoveStage::Complete { + size_freed: None, + }, + ), + Phase::Done, + ), + ( + SoarEvent::OperationComplete { + op_id: 1, + pkg_name: "bat".into(), + }, + Phase::Done, + ), + ( + SoarEvent::Hook { + op_id: 1, + pkg_name: "bat".into(), + hook_name: "post_install".into(), + stage: HookStage::Failed { + exit_code: Some(3), + }, + }, + Phase::Step("post_install failed (3)".into()), + ), + ( + SoarEvent::UpdateCleanup { + op_id: 1, + pkg_name: "bat".into(), + old_version: "0.23.0".into(), + stage: UpdateCleanupStage::Removing, + }, + Phase::Step("removing 0.23.0".into()), + ), + ( + building( + 1, + BuildStage::Running { + command_index: 1, + total_commands: 4, + }, + ), + Phase::Step("building 2/4".into()), + ), + ]; + for (event, phase) in cases { + let mut tracker = Tracker::default(); + tracker.apply(&event, Instant::now()); + assert_eq!(tracker.ops[0].phase, phase, "{event:?}"); + } + } + + #[test] + fn recovery_and_cleanup_ends_keep_the_phase() { + let mut tracker = Tracker::default(); + let start = Instant::now(); + tracker.apply(&progress(1, 300, 500), start); + tracker.apply( + &SoarEvent::DownloadRecovered { + op_id: 1, + pkg_name: "bat".into(), + }, + start, + ); + tracker.apply( + &SoarEvent::UpdateCleanup { + op_id: 1, + pkg_name: "bat".into(), + old_version: "0.23.0".into(), + stage: UpdateCleanupStage::Kept, + }, + start, + ); + tracker.apply( + &SoarEvent::UpdateCleanup { + op_id: 1, + pkg_name: "bat".into(), + old_version: "0.23.0".into(), + stage: UpdateCleanupStage::Complete { + size_freed: None, + }, + }, + start, + ); + tracker.apply( + &SoarEvent::Hook { + op_id: 1, + pkg_name: "bat".into(), + hook_name: "post_install".into(), + stage: HookStage::Complete, + }, + start, + ); + tracker.apply( + &building( + 1, + BuildStage::CommandComplete { + command_index: 0, + }, + ), + start, + ); + assert_eq!( + tracker.ops[0].phase, + Phase::Downloading { + current: 300, + total: 500 + } + ); + } + + #[test] + fn eta_needs_a_known_size_and_a_useful_speed() { + let mut tracker = Tracker::default(); + let start = Instant::now(); + tracker.apply( + &SoarEvent::DownloadStarting { + op_id: 1, + pkg_name: "bat".into(), + total: 10_000, + }, + start, + ); + tracker.apply(&progress(1, 1_000, 10_000), start); + assert_eq!(tracker.ops[0].eta(), None); + tracker.apply(&progress(1, 3_000, 10_000), start + Duration::from_secs(1)); + assert_eq!(tracker.ops[0].eta(), Some(Duration::from_millis(3500))); + tracker.apply(&installing(1, InstallStage::Extracting), start); + assert_eq!(tracker.ops[0].eta(), None); + } + + #[test] + fn eta_stays_empty_while_the_speed_is_a_crawl() { + let mut tracker = Tracker::default(); + let start = Instant::now(); + tracker.apply( + &SoarEvent::DownloadStarting { + op_id: 1, + pkg_name: "bat".into(), + total: 1_000, + }, + start, + ); + tracker.apply(&progress(1, 0, 1_000), start); + tracker.apply(&progress(1, 1, 1_000), start + Duration::from_secs(1)); + assert_speed(tracker.ops[0].speed, 1.0); + assert_eq!(tracker.ops[0].eta(), None); + } +} diff --git a/crates/soar-tui/src/runner.rs b/crates/soar-tui/src/runner.rs new file mode 100644 index 00000000..f2fd33de --- /dev/null +++ b/crates/soar-tui/src/runner.rs @@ -0,0 +1,1559 @@ +//! Carries out the work the interface's state asks for. + +use std::{ + collections::VecDeque, + ffi::OsString, + fs, + future::Future, + io::{BufRead as _, BufReader}, + path::{Path, PathBuf}, + process::{Command, Stdio}, + sync::{ + Arc, + mpsc::{Receiver, RecvTimeoutError, Sender}, + }, + time::{Duration, Instant}, +}; + +use soar_config::{ + config::{CONFIG_PATH, Config, get_config, init, is_system_mode}, + error::ConfigError, + packages::{PACKAGES_CONFIG_PATH, PackagesConfig}, + repository::Repository, +}; +use soar_core::{SoarResult, error::SoarError}; +use soar_events::{EventSinkHandle, SoarEvent}; +use soar_operations::{ + AmbiguousPackage, ApplyReport, InstallOptions, InstallReport, PackageListEntry, RemoveReport, + ResolveResult, SoarContext, UpdateReport, apply, health, install, list, + privilege::{ESCALATION_DIRS, EscalationTool, escalated_command, find_escalation_tool}, + remove, + repo::RepoUpdate, + run, search, switch, update, +}; +use soar_utils::cancel::CancelToken; +use tokio::runtime::Handle; + +use crate::{ + effect::{Effect, Suspended}, + event_loop::InputThread, + jobs::{JobId, JobOutcome, JobSpec, OutcomeLine, RepoChange, SystemMode}, + msg::{Loaded, Msg, Resolution}, + privileged::{self, EscalationProbe}, + sink::TuiSink, + terminal::{self, Session}, + views::{ + apply::ApplyPlan, + browse::{CatalogRow, PackageKey}, + repos::RepoRow, + }, +}; + +/// How many lines of the system pass's stderr the report keeps. +const KEPT_STDERR_LINES: usize = 20; + +/// How often the system pass's output loop checks whether the child +/// exited. +const PIPE_POLL: Duration = Duration::from_millis(50); + +/// How long the output loop keeps reading after the child exited, so a +/// grandchild holding the pipes cannot hold the job hostage. +const PIPE_GRACE: Duration = Duration::from_millis(300); + +/// One line the system pass wrote, with the pipe it came from. +enum PipeLine { + /// A line of stdout, which holds the JSON event stream. + Out(String), + /// A line of stderr, which holds the child's own logging. + Err(String), +} + +/// Executes effects. It is the only part of the interface that calls into +/// soar's operations. +pub(crate) struct Runner { + /// The context operations run through. + ctx: SoarContext, + /// Where operations report their progress. + sink: EventSinkHandle, + /// The runtime asynchronous work is spawned on. + handle: Handle, + /// Channel the results of spawned asynchronous work arrive through. + tx: Sender, + /// Global options a privileged soar child runs with, so it reads the + /// same configuration and connections this session was given. + forward_args: Vec, + /// The token that asks the job running now to stop. + current_cancel: Option, +} + +impl Runner { + /// Creates the runner whose operations report into the interface's + /// message channel. + pub(crate) fn new(handle: Handle, tx: Sender, forward_args: Vec) -> Runner { + let sink: EventSinkHandle = Arc::new(TuiSink::new(tx.clone())); + let ctx = SoarContext::new(get_config(), Arc::clone(&sink)); + Runner { + ctx, + sink, + handle, + tx, + forward_args, + current_cancel: None, + } + } + + /// Performs one piece of requested work. + /// + /// A suspended effect hands the terminal to another program: the + /// input thread stops reading keystrokes and the session gives the + /// screen back until the program exits. + pub(crate) fn execute( + &mut self, + effect: Effect, + session: &mut Session, + input: &InputThread, + ) -> std::io::Result<()> { + match effect { + Effect::RebuildContext => { + if let Err(err) = init() { + tracing::error!("reloading config: {err}"); + } else { + self.ctx = SoarContext::new(get_config(), Arc::clone(&self.sink)); + } + } + Effect::StartJob { + id, + spec, + } => { + let cancel = CancelToken::new(); + self.current_cancel = Some(cancel.clone()); + let ctx = self.ctx.with_cancel(cancel); + let forward_args = self.forward_args.clone(); + let tx = self.tx.clone(); + self.spawn(async move { + Msg::JobFinished { + id, + outcome: run_job(ctx, spec, &forward_args, tx).await, + } + }); + } + Effect::AbortJob => { + if let Some(cancel) = &self.current_cancel { + cancel.cancel(); + } + } + Effect::LoadCatalog { + check, + } => { + let ctx = self.ctx.clone(); + self.spawn(async move { + let result = match list::list_packages(&ctx, None).await { + Ok(listing) => Ok(listing.packages.into_iter().map(catalog_row).collect()), + Err(err) => Err(err.to_string()), + }; + Msg::Loaded(Loaded::Catalog { + check, + result, + }) + }); + } + Effect::LoadInstalled { + check, + } => { + let ctx = self.ctx.clone(); + self.spawn(async move { + let result = tokio::task::spawn_blocking(move || { + list::list_installed(&ctx, None).map_err(|err| err.to_string()) + }) + .await + .unwrap_or_else(|err| Err(err.to_string())); + Msg::Loaded(Loaded::Installed { + check, + result, + }) + }); + } + Effect::LoadRepos => { + let config = self.ctx.config().clone(); + let repositories = config.repositories.clone(); + self.spawn(async move { + Msg::Loaded(Loaded::Repos(Ok(repo_rows(&config, &repositories)))) + }); + } + Effect::LoadHealth => { + let ctx = self.ctx.clone(); + let config = self.ctx.config().clone(); + self.spawn(async move { + let result = tokio::task::spawn_blocking(move || { + let paths = health_paths(&config).map_err(|err| err.to_string())?; + let report = health::check_health(&ctx).map_err(|err| err.to_string())?; + Ok((report, paths)) + }) + .await + .unwrap_or_else(|err| Err(err.to_string())); + Msg::Loaded(Loaded::Health(result)) + }); + } + Effect::ComputeApplyDiff { + prune, + check, + } => { + let ctx = self.ctx.clone(); + self.spawn(async move { + let result = compute_apply_plan(&ctx, prune).await; + Msg::Loaded(Loaded::ApplyDiff { + check, + result, + }) + }); + } + Effect::LoadVariants { + name, + } => { + let ctx = self.ctx.clone(); + let query = name.clone(); + self.spawn(async move { + let result = tokio::task::spawn_blocking(move || { + switch::list_variants(&ctx, &query).map_err(|err| err.to_string()) + }) + .await + .unwrap_or_else(|err| Err(err.to_string())); + Msg::Loaded(Loaded::Variants { + name, + result: Box::new(result), + }) + }); + } + Effect::LoadDetail { + key, + version, + } => { + let ctx = self.ctx.clone(); + self.spawn(async move { + let query = match key.pkg_family.as_deref() { + Some(family) => format!("{family}/{}:{}", key.pkg_name, key.repo_name), + None => format!("{}:{}", key.pkg_name, key.repo_name), + }; + let result = match search::query_package(&ctx, &query).await { + Ok(packages) => { + Ok(packages + .iter() + .find(|package| package.version == version) + .cloned() + .or_else(|| packages.first().cloned())) + } + Err(err) => Err(err.to_string()), + }; + Msg::Loaded(Loaded::Detail { + key, + result: Box::new(result), + }) + }); + } + Effect::Resolve { + queries, + choices, + } => { + let ctx = self.ctx.clone(); + let options = choices.options(); + self.spawn(async move { + let result = resolve_queries(&ctx, &queries, &options).await; + Msg::Loaded(Loaded::Resolved { + choices, + result, + }) + }); + } + Effect::PrepareRun { + query, + repo, + pkg_id, + args, + } => { + let ctx = self.ctx.clone(); + self.spawn(async move { + let result = + run::prepare_run(&ctx, &query, repo.as_deref(), pkg_id.as_deref(), false) + .await + .map_err(|err| err.to_string()); + Msg::Loaded(Loaded::RunReady { + args, + result: Box::new(result), + }) + }); + } + Effect::CheckUpdates { + names, + check, + } => { + let ctx = self.ctx.clone(); + self.spawn(async move { + let result = update::check_updates(&ctx, names.as_deref()) + .await + .map_err(|err| err.to_string()); + Msg::Loaded(Loaded::Updates { + check, + result, + }) + }); + } + Effect::Suspend(suspended) => { + input.pause(); + if let Err(err) = session.suspend() { + input.resume(); + return Err(err); + } + let mut edited: Option = None; + let mut finished: Option<(JobId, JobOutcome)> = None; + match suspended { + Suspended::Exec { + path, + args, + } => { + match run::execute_binary(&path, &args) { + Ok(result) => { + println!( + "\n{} exited with code {}", + path.display(), + result.exit_code + ) + } + Err(err) => eprintln!("\n{err}"), + } + terminal::wait_for_enter(); + } + Suspended::Edit(path) => { + // The editor already held the screen while it ran, + // so only a failed one pauses for Enter on the way + // back into the interface. + if let Err(err) = open_in_editor(&path) { + eprintln!("\n{err}"); + terminal::wait_for_enter(); + } + edited = Some(path); + } + Suspended::SystemPass { + id, + tool, + packages_path, + names, + } => { + println!( + "\nApplying system packages. {} may ask for your password.", + tool_name(&tool) + ); + let outcome = + run_system_terminal(&self.forward_args, &tool, &packages_path, &names); + terminal::wait_for_enter(); + finished = Some((id, outcome)); + } + } + // The keystrokes come back whatever restoring does, so a + // failed restore cannot leave the interface deaf. + let resumed = session.resume(); + input.resume(); + resumed?; + if let Some((id, outcome)) = finished { + let _ = self.tx.send(Msg::JobFinished { + id, + outcome, + }); + } + if let Some(path) = edited { + let _ = self.tx.send(Msg::Edited(path)); + } + let _ = self.tx.send(Msg::Redraw); + } + Effect::ProbeEscalation => { + self.spawn(async move { + let probe = tokio::task::spawn_blocking(privileged::probe_escalation) + .await + .unwrap_or_else(|err| EscalationProbe::Unavailable(err.to_string())); + Msg::Loaded(Loaded::Escalation(probe)) + }); + } + Effect::Authenticate { + secret, + check, + } => { + self.spawn(async move { + let result = + tokio::task::spawn_blocking(move || privileged::authenticate(secret)) + .await + .unwrap_or_else(|err| Err(err.to_string())); + Msg::Loaded(Loaded::Authenticated { + check, + result, + }) + }); + } + } + Ok(()) + } + + /// Spawns asynchronous work on the runtime and sends its message back + /// through the channel when it is done. + fn spawn(&self, fut: impl Future + Send + 'static) { + let tx = self.tx.clone(); + self.handle.spawn(async move { + let msg = fut.await; + let _ = tx.send(msg); + }); + } +} + +/// Runs the user's editor on `path` through the shell, so editors whose +/// command carries arguments of its own, such as `code --wait`, work. The +/// path is passed as an argument rather than spliced into the command line. +fn open_in_editor(path: &Path) -> Result<(), String> { + let editor = std::env::var("EDITOR").unwrap_or_else(|_| "vi".to_string()); + let status = Command::new("sh") + .arg("-c") + .arg(format!("{editor} \"$1\"")) + .arg("sh") + .arg(path) + .status() + .map_err(|err| format!("executing command {editor} {}: {err}", path.display()))?; + if !status.success() { + return Err(format!( + "{editor} exited with {status} while editing {}", + path.display() + )); + } + Ok(()) +} + +/// Turns the configured repositories into the rows the repositories view +/// keeps. Each row reads the repository's data directory once, so a load +/// is a handful of filesystem stats. +fn repo_rows(config: &Config, repositories: &[Repository]) -> Vec { + repositories + .iter() + .map(|repo| { + RepoRow { + name: repo.name.clone(), + url: repo.url.clone(), + enabled: repo.is_enabled(), + signed: repo.signature_verification(), + desktop: config.has_desktop_integration(&repo.name), + sync_interval: repo + .sync_interval + .clone() + .unwrap_or_else(|| "3h".to_string()), + synced: repo + .get_path() + .ok() + .and_then(|path| fs::metadata(path.join("metadata.db")).ok()) + .and_then(|metadata| metadata.modified().ok()), + } + }) + .collect() +} + +/// Builds the plan the apply view shows: the diff of the user's declared +/// packages against what is installed, plus the names left for the system +/// pass. A missing packages file is not an error; it plans an empty +/// diff so the view can offer to create the file. +async fn compute_apply_plan(ctx: &SoarContext, prune: bool) -> Result { + let path = PackagesConfig::resolve_path(None); + let config = match PackagesConfig::load(None) { + Ok(config) => config, + Err(ConfigError::PackagesConfigNotFound(_)) => { + return Ok(ApplyPlan { + path, + diff: None, + system: Vec::new(), + }); + } + Err(err) => return Err(err.to_string()), + }; + let declared = config.resolved_packages(); + let (resolved, system): (Vec<_>, Vec<_>) = if is_system_mode() { + (declared, Vec::new()) + } else { + declared.into_iter().partition(|pkg| !pkg.system) + }; + let diff = apply::compute_diff(ctx, &resolved, prune) + .await + .map_err(|err| err.to_string())?; + Ok(ApplyPlan { + path, + diff: Some(diff), + system: system.into_iter().map(|pkg| pkg.name).collect(), + }) +} + +/// The paths soar uses, under the labels the health view shows them +/// with. The two configuration file paths come from their shared slots; +/// the rest come from the session's configuration, so one of them failing +/// fails the whole load. +fn health_paths(config: &Config) -> Result, String> { + let bin = config.get_bin_path().map_err(|err| err.to_string())?; + let db = config.get_db_path().map_err(|err| err.to_string())?; + let cache = config.get_cache_path().map_err(|err| err.to_string())?; + let packages = config + .get_packages_path(None) + .map_err(|err| err.to_string())?; + let repositories = config + .get_repositories_path() + .map_err(|err| err.to_string())?; + Ok(vec![ + ( + "Config".to_string(), + CONFIG_PATH + .read() + .map(|path| path.to_path_buf()) + .unwrap_or_default(), + ), + ( + "Packages config".to_string(), + PACKAGES_CONFIG_PATH + .read() + .map(|path| path.to_path_buf()) + .unwrap_or_default(), + ), + ("Bin".to_string(), bin), + ("Database".to_string(), db), + ("Cache".to_string(), cache), + ("Packages".to_string(), packages), + ("Repositories".to_string(), repositories), + ]) +} + +/// Turns one listing entry into the row the catalog view keeps. +fn catalog_row(entry: PackageListEntry) -> CatalogRow { + let package = entry.package; + let haystack = match package.pkg_family.as_deref() { + Some(family) => format!("{family}/{}", package.pkg_name), + None => package.pkg_name.clone(), + } + .to_lowercase(); + CatalogRow { + key: PackageKey { + repo_name: package.repo_name, + pkg_name: package.pkg_name, + pkg_family: package.pkg_family, + pkg_id: package.pkg_id, + }, + version: package.version, + pkg_type: package.pkg_type, + description: package.description, + installed: entry.installed, + other_versions: entry.other_versions, + haystack, + } +} + +/// Runs one job and reports what it did. Each arm hands the spec to the +/// operation it names and turns the operation's report into an outcome. +/// The system pass in direct mode is the exception: it runs as another +/// process through the escalation tool, and its progress reaches the +/// interface through the child's own event stream. +async fn run_job( + ctx: SoarContext, + spec: JobSpec, + forward_args: &[OsString], + tx: Sender, +) -> JobOutcome { + let title = spec.title(); + match spec { + JobSpec::Install { + mut targets, + picked, + options, + } => { + let options = options.options(); + for package in picked { + match install::target_for(&ctx, package, &options) { + Ok(target) => targets.push(target), + Err(err) => return failed_outcome(&title, err), + } + } + match install::perform_installation(&ctx, targets, &options).await { + Ok(report) => { + let installed = report.installed.len(); + let skipped = report.cancelled.len(); + let mut outcome = install_outcome(report); + if ctx.cancel_token().is_cancelled() { + outcome.aborted = true; + outcome.headline = + format!("Aborted: {installed} installed, {skipped} skipped"); + } + outcome + } + Err(err) => failed_outcome(&title, err), + } + } + JobSpec::Remove { + packages, + } => { + match remove::perform_removal(&ctx, packages).await { + Ok(report) => { + let removed = report.removed.len(); + let skipped = report.cancelled.len(); + let mut outcome = remove_outcome(report); + if ctx.cancel_token().is_cancelled() { + outcome.aborted = true; + outcome.headline = format!("Aborted: {removed} removed, {skipped} skipped"); + } + outcome + } + Err(err) => failed_outcome(&title, err), + } + } + JobSpec::Update { + updates, + keep_old, + } => { + match update::perform_update(&ctx, updates, keep_old, false).await { + Ok(report) => { + let updated = report.updated.len(); + let skipped = report.cancelled.len(); + let mut outcome = update_outcome(report); + if ctx.cancel_token().is_cancelled() { + outcome.aborted = true; + outcome.headline = format!("Aborted: {updated} updated, {skipped} skipped"); + } + outcome + } + Err(err) => failed_outcome(&title, err), + } + } + JobSpec::Switch { + id, + name, + } => { + match switch::switch_variant(&ctx, id).await { + Ok(()) => ok_outcome(format!("Switched to {name}")), + Err(err) => failed_outcome(&title, err), + } + } + JobSpec::Sync => { + match ctx.sync().await { + Ok(()) => ok_outcome("Repositories synced".to_string()), + Err(err) => failed_outcome(&title, err), + } + } + JobSpec::Apply { + diff, + packages_path, + } => { + match apply::execute_apply(&ctx, diff, false, &packages_path).await { + Ok(report) => { + let mut outcome = apply_outcome(report); + if ctx.cancel_token().is_cancelled() { + outcome.aborted = true; + } + outcome + } + Err(err) => failed_outcome(&title, err), + } + } + // The direct mode reaches this arm only through the authorization + // flow; the other modes never run here, since the interface asks + // first and a terminal pass suspends the interface itself. + JobSpec::ApplySystem { + names, + packages_path, + mode: SystemMode::Direct, + } => { + let forward = forward_args.to_vec(); + let pass_tx = tx.clone(); + match tokio::task::spawn_blocking(move || { + run_system_direct(packages_path, names, forward, pass_tx) + }) + .await + { + Ok(outcome) => outcome, + Err(err) => system_failed(err.to_string()), + } + } + JobSpec::ApplySystem { + .. + } => { + failed_outcome( + &title, + SoarError::Custom("System apply is not ready".into()), + ) + } + JobSpec::CleanCache => { + match blocking(soar_core::utils::cleanup_cache).await { + Ok(()) => ok_outcome("Cache cleaned".to_string()), + Err(err) => failed_outcome(&title, err), + } + } + JobSpec::RemoveBrokenSymlinks => { + match blocking(move || health::remove_broken_symlinks(&ctx)).await { + Ok(paths) => { + let count = paths.len(); + JobOutcome { + ok: true, + aborted: false, + headline: format!("Removed {count} broken symlinks"), + lines: paths + .into_iter() + .map(|path| OutcomeLine::Done(path.display().to_string())) + .collect(), + } + } + Err(err) => failed_outcome(&title, err), + } + } + JobSpec::RemoveBrokenPackages => { + match health::remove_broken_packages(&ctx).await { + Ok(report) => { + let removed = report.removed.len(); + let skipped = report.cancelled.len(); + let mut outcome = remove_outcome(report); + if ctx.cancel_token().is_cancelled() { + outcome.aborted = true; + outcome.headline = format!("Aborted: {removed} removed, {skipped} skipped"); + } + outcome + } + Err(err) => failed_outcome(&title, err), + } + } + JobSpec::Repo(RepoChange::Add(repo)) => { + let name = repo.name.clone(); + match blocking(move || ctx.add_repository(repo)).await { + Ok(()) => ok_outcome(format!("Added repository {name}")), + Err(err) => failed_outcome(&title, err), + } + } + JobSpec::Repo(RepoChange::SetEnabled { + name, + enabled, + }) => { + let change = RepoUpdate { + url: None, + enabled: Some(enabled), + pubkey: None, + desktop_integration: None, + signature_verification: None, + sync_interval: None, + }; + let headline = if enabled { + format!("Enabled {name}") + } else { + format!("Disabled {name}") + }; + match blocking(move || ctx.update_repository(&name, change)).await { + Ok(()) => ok_outcome(headline), + Err(err) => failed_outcome(&title, err), + } + } + JobSpec::Repo(RepoChange::Remove(name)) => { + let headline = format!("Removed repository {name}"); + match blocking(move || ctx.remove_repository(&name)).await { + Ok(()) => ok_outcome(headline), + Err(err) => failed_outcome(&title, err), + } + } + JobSpec::CreatePackagesConfig => { + match soar_config::packages::generate_default_packages_config() { + Ok(()) => ok_outcome("Created packages.toml".to_string()), + Err(err) => failed_outcome(&title, SoarError::Config(err)), + } + } + } +} + +/// Resolves install queries, one outcome per query. A query nothing +/// matches also gets the similar names worth trying; a failed lookup +/// leaves that list empty rather than failing the whole resolve. +async fn resolve_queries( + ctx: &SoarContext, + queries: &[String], + options: &InstallOptions, +) -> Result, String> { + let results = match install::resolve_packages(ctx, queries, options).await { + Ok(results) => results, + Err(err) => return Err(err.to_string()), + }; + let mut resolutions = Vec::with_capacity(results.len()); + for result in results { + resolutions.push(match result { + ResolveResult::Resolved(targets) => Resolution::Ready(targets), + ResolveResult::Ambiguous(AmbiguousPackage { + query, + candidates, + }) => { + Resolution::Ambiguous { + query, + candidates, + } + } + ResolveResult::NotFound(query) => { + let suggestions = search::suggest_similar(ctx, &query, 3) + .await + .unwrap_or_default(); + Resolution::NotFound { + query, + suggestions, + } + } + ResolveResult::AlreadyInstalled { + pkg_name, + repo_name, + version, + } => { + Resolution::AlreadyInstalled { + name: pkg_name, + repo: repo_name, + version, + } + } + }); + } + Ok(resolutions) +} + +/// Runs a filesystem-bound call on the blocking pool, so it does not hold up +/// the async workers. A panic in the call reports as a job failure. +async fn blocking( + call: impl FnOnce() -> SoarResult + Send + 'static, +) -> SoarResult { + tokio::task::spawn_blocking(call) + .await + .unwrap_or_else(|err| Err(SoarError::Custom(err.to_string()))) +} + +/// The escalation tool's own name, for the note the interface prints +/// before the terminal pass takes the screen. +fn tool_name(tool: &EscalationTool) -> String { + tool.path.file_name().map_or_else( + || tool.path.display().to_string(), + |name| name.to_string_lossy().into_owned(), + ) +} + +/// The arguments the privileged soar child runs with. `--json` keeps the +/// progress flowing over the captured output, `--system` selects the +/// system tree, the forwarded options carry the configuration and network +/// settings, and `apply --only-system --yes` applies just the packages +/// marked `system = true` without asking again. +fn system_pass_args(packages_path: &str, forward_args: &[OsString], json: bool) -> Vec { + let mut args: Vec = Vec::new(); + if json { + args.push("--json".into()); + } + args.push("--system".into()); + args.extend(forward_args.iter().cloned()); + args.push("apply".into()); + args.push("--only-system".into()); + args.push("--yes".into()); + args.push("--packages".into()); + args.push(packages_path.into()); + args +} + +/// The names the packages file declares `system = true` right now, read +/// the way the apply plan reads it. A missing file declares nothing. +fn declared_system_names() -> Result, String> { + match PackagesConfig::load(None) { + Ok(config) => { + Ok(config + .resolved_packages() + .into_iter() + .filter(|package| package.system) + .map(|package| package.name) + .collect()) + } + Err(ConfigError::PackagesConfigNotFound(_)) => Ok(Vec::new()), + Err(err) => Err(err.to_string()), + } +} + +/// Whether the confirmed system names still match what the file declares. +/// Order-insensitive, since the file's order means nothing to the pass. +fn system_names_agree(confirmed: &[String], declared: &[String]) -> bool { + let mut confirmed: Vec<&str> = confirmed.iter().map(String::as_str).collect(); + let mut declared: Vec<&str> = declared.iter().map(String::as_str).collect(); + confirmed.sort_unstable(); + declared.sort_unstable(); + confirmed == declared +} + +/// The outcome of a system pass refused before its child ran, because the +/// file it would apply no longer declares what the confirm named. +fn system_stale_outcome() -> JobOutcome { + JobOutcome { + ok: false, + aborted: false, + headline: "packages.toml changed since the confirmation".to_string(), + lines: vec![OutcomeLine::Failed { + name: "System apply".to_string(), + error: + "The system packages in packages.toml changed since you confirmed the apply. Confirm it again to run the new list." + .to_string(), + }], + } +} + +/// Checks the file against the names the confirm named, so a pass never +/// applies an edit the user has not seen. `Ok(())` lets the child run; +/// `Err(outcome)` fails the job with it instead. +fn verify_system_names(confirmed: &[String]) -> Result<(), JobOutcome> { + let declared = match declared_system_names() { + Ok(declared) => declared, + Err(err) => { + return Err(system_failed(format!( + "reading packages.toml before the system pass: {err}" + ))); + } + }; + if system_names_agree(confirmed, &declared) { + Ok(()) + } else { + Err(system_stale_outcome()) + } +} + +/// Runs the system pass with the terminal handed over, so the escalation +/// tool can ask for the password itself. The output lands in the terminal +/// the user is looking at, and only the exit status reports back. The +/// confirmed names are checked against the file first, so the child +/// applies what was approved and nothing else. +fn run_system_terminal( + forward_args: &[OsString], + tool: &EscalationTool, + packages_path: &str, + confirmed: &[String], +) -> JobOutcome { + if let Err(outcome) = verify_system_names(confirmed) { + return outcome; + } + let exe = match std::env::current_exe() { + Ok(exe) => exe, + Err(err) => return system_failed(format!("finding the soar executable: {err}")), + }; + let args = system_pass_args(packages_path, forward_args, false); + match escalated_command(tool, &[], &exe, &args).status() { + Ok(status) if status.success() => ok_outcome("System packages applied".to_string()), + Ok(status) => system_failed(format!("the system pass exited with {status}")), + Err(err) => system_failed(format!("running the system pass: {err}")), + } +} + +/// Runs the system pass through the escalation tool with its output +/// captured, so the child's JSON event stream feeds the job's progress. +/// Root runs the executable on its own; otherwise the tool runs it with +/// the credentials the password check cached. The confirmed names are +/// checked against the file first, like the terminal pass does. +fn run_system_direct( + packages_path: String, + confirmed: Vec, + forward_args: Vec, + tx: Sender, +) -> JobOutcome { + if let Err(outcome) = verify_system_names(&confirmed) { + return outcome; + } + let exe = match std::env::current_exe() { + Ok(exe) => exe, + Err(err) => return system_failed(format!("finding the soar executable: {err}")), + }; + let args = system_pass_args(&packages_path, &forward_args, true); + let mut command = if soar_utils::system::is_root() { + let mut command = Command::new(&exe); + command.args(&args); + command + } else { + match find_escalation_tool() { + Some(tool) => escalated_command(&tool, &["-n"], &exe, &args), + None => { + return system_failed(format!( + "System mode requires root privileges. Neither 'doas' nor 'sudo' found in {}.", + ESCALATION_DIRS.join(", ") + )); + } + } + }; + command + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + let mut child = match command.spawn() { + Ok(child) => child, + Err(err) => return system_failed(format!("running the system pass: {err}")), + }; + + // Both pipes feed one channel. The exit check runs on every pass + // before the wait, so output arriving faster than the poll cannot + // hide an exit: once the child is gone, a grandchild it left behind + // may still hold the pipes open, and the loop stops a short grace + // after the exit rather than waiting for an end of output that may + // never come. A reader thread blocked in read() notices neither the + // receiver dropping nor that grace, so after a grace break it stays + // leaked until the pipes close; two leaked threads per grace-broken + // pass is the accepted cost. + let (line_tx, line_rx) = std::sync::mpsc::channel::(); + let out_tx = line_tx.clone(); + let stdout = child.stdout.take(); + std::thread::spawn(move || { + if let Some(stdout) = stdout { + for line in BufReader::new(stdout).lines().map_while(Result::ok) { + if out_tx.send(PipeLine::Out(line)).is_err() { + return; + } + } + } + }); + let stderr = child.stderr.take(); + std::thread::spawn(move || { + if let Some(stderr) = stderr { + for line in BufReader::new(stderr).lines().map_while(Result::ok) { + if line_tx.send(PipeLine::Err(line)).is_err() { + return; + } + } + } + }); + + let (complete, kept_errors) = collect_output( + &line_rx, + &mut || child.try_wait().ok().flatten().is_some(), + &tx, + ); + let status = child.wait(); + match status { + Ok(status) if status.success() => { + match complete { + Some(counts) => { + JobOutcome { + ok: counts.failed == 0, + aborted: false, + headline: format!( + "System: {} installed, {} updated, {} removed", + counts.installed, counts.updated, counts.removed + ), + lines: Vec::new(), + } + } + None => ok_outcome("System packages applied".to_string()), + } + } + Ok(status) => { + let mut error = if kept_errors.is_empty() { + format!("the system pass exited with {status}") + } else { + kept_errors.into_iter().collect::>().join("\n") + }; + if password_demanded(&error) { + error.push('\n'); + error.push_str( + "sudo did not keep the authorization. Run soar apply in a terminal instead.", + ); + } + system_failed(error) + } + Err(err) => system_failed(format!("waiting for the system pass: {err}")), + } +} + +/// Reads the system pass's pipe lines until the child has exited and the +/// grace passed, or the readers hung up. The exit check runs before every +/// wait, so a grandchild emitting a line more often than the poll cannot +/// keep the loop running past the child's own exit. Stdout lines are +/// forwarded as events or plain output, stderr lines as warnings, with +/// the last few kept back for a failure report. Returns the completion +/// counts and the kept error lines. +fn collect_output( + line_rx: &Receiver, + is_exited: &mut dyn FnMut() -> bool, + tx: &Sender, +) -> (Option, VecDeque) { + let mut complete = None; + let mut kept_errors: VecDeque = VecDeque::new(); + let mut exited_at: Option = None; + loop { + if is_exited() { + let since = exited_at.get_or_insert_with(Instant::now); + if Instant::now() - *since > PIPE_GRACE { + break; + } + } + match line_rx.recv_timeout(PIPE_POLL) { + Ok(PipeLine::Out(line)) => { + match serde_json::from_str::(&line) { + Ok(event) => { + if let SoarEvent::ApplyComplete { + installed, + updated, + removed, + failed, + } = &event + { + complete = Some(ApplyCounts { + installed: *installed, + updated: *updated, + removed: *removed, + failed: *failed, + }); + } + let _ = tx.send(Msg::Soar(event)); + } + Err(_) => { + let _ = tx.send(Msg::Output(line)); + } + } + } + Ok(PipeLine::Err(line)) => { + let _ = tx.send(Msg::Output(format!("WARN {line}"))); + if kept_errors.len() == KEPT_STDERR_LINES { + kept_errors.pop_front(); + } + kept_errors.push_back(line); + } + Err(RecvTimeoutError::Timeout) => {} + Err(RecvTimeoutError::Disconnected) => break, + } + } + (complete, kept_errors) +} + +/// The installed, updated, removed, and failed counts the system pass +/// reported when it was over. +struct ApplyCounts { + installed: usize, + updated: usize, + removed: usize, + failed: usize, +} + +/// Whether stderr says the tool wanted a password after all, meaning the +/// credentials cached by the password check ran out before the pass. +fn password_demanded(stderr: &str) -> bool { + stderr.to_lowercase().contains("password is required") +} + +/// The outcome of a system pass that did not run through. +fn system_failed(error: String) -> JobOutcome { + JobOutcome { + ok: false, + aborted: false, + headline: "System apply failed".to_string(), + lines: vec![OutcomeLine::Failed { + name: "System apply".to_string(), + error, + }], + } +} + +/// The outcome of a job that ran through without a failure. +fn ok_outcome(headline: String) -> JobOutcome { + JobOutcome { + ok: true, + aborted: false, + headline, + lines: Vec::new(), + } +} + +/// The outcome of a call that failed outright. A call stopped by an abort +/// reports as aborted rather than failed. +fn failed_outcome(title: &str, err: SoarError) -> JobOutcome { + if matches!(err, SoarError::Cancelled) { + JobOutcome { + ok: true, + aborted: true, + headline: "Aborted".into(), + lines: Vec::new(), + } + } else { + JobOutcome { + ok: false, + aborted: false, + headline: format!("{title} failed"), + lines: vec![OutcomeLine::Failed { + name: title.to_string(), + error: err.to_string(), + }], + } + } +} + +/// Turns an install report into the job's outcome. +fn install_outcome(report: InstallReport) -> JobOutcome { + let mut lines = Vec::new(); + for info in &report.installed { + lines.push(OutcomeLine::Done(format!( + "{} {}", + info.pkg_name, info.version + ))); + } + for failed in &report.failed { + lines.push(OutcomeLine::Failed { + name: failed.pkg_name.clone(), + error: failed.error.clone(), + }); + } + for name in &report.cancelled { + lines.push(OutcomeLine::Skipped(name.clone())); + } + for info in &report.installed { + for text in info.notes.iter().flatten() { + lines.push(OutcomeLine::Note { + name: info.pkg_name.clone(), + text: text.clone(), + }); + } + } + for warning in &report.warnings { + lines.push(OutcomeLine::Warning(warning.clone())); + } + let headline = if report.failed.is_empty() { + match report.installed.as_slice() { + [] => "Installed 0 packages".to_string(), + [one] => format!("Installed {} {}", one.pkg_name, one.version), + many => format!("Installed {} packages", many.len()), + } + } else { + format!("Install finished with {} failures", report.failed.len()) + }; + JobOutcome { + ok: report.failed.is_empty(), + aborted: false, + headline, + lines, + } +} + +/// Turns a removal report into the job's outcome. +fn remove_outcome(report: RemoveReport) -> JobOutcome { + let mut lines = Vec::new(); + for info in &report.removed { + lines.push(OutcomeLine::Done(format!( + "{} {}", + info.pkg_name, info.version + ))); + } + for failed in &report.failed { + lines.push(OutcomeLine::Failed { + name: failed.pkg_name.clone(), + error: failed.error.clone(), + }); + } + for name in &report.cancelled { + lines.push(OutcomeLine::Skipped(name.clone())); + } + JobOutcome { + ok: report.failed.is_empty(), + aborted: false, + headline: format!("Removed {} packages", report.removed.len()), + lines, + } +} + +/// Turns an update report into the job's outcome. +fn update_outcome(report: UpdateReport) -> JobOutcome { + let mut lines = Vec::new(); + for info in &report.updated { + lines.push(OutcomeLine::Done(format!( + "{} {}", + info.pkg_name, info.version + ))); + } + for failed in &report.failed { + lines.push(OutcomeLine::Failed { + name: failed.pkg_name.clone(), + error: failed.error.clone(), + }); + } + for name in &report.cancelled { + lines.push(OutcomeLine::Skipped(name.clone())); + } + JobOutcome { + ok: report.failed.is_empty(), + aborted: false, + headline: format!("Updated {} packages", report.updated.len()), + lines, + } +} + +/// Turns an apply report into the job's outcome. The report carries counts +/// only, so there are no per-package lines. +fn apply_outcome(report: ApplyReport) -> JobOutcome { + JobOutcome { + ok: report.failed_count == 0, + aborted: false, + headline: format!( + "Applied: {} installed, {} updated, {} removed", + report.installed_count, report.updated_count, report.removed_count + ), + lines: Vec::new(), + } +} + +#[cfg(test)] +mod tests { + use std::path::PathBuf; + + use soar_operations::{ + ApplyReport, FailedInfo, InstallReport, InstalledInfo, RemoveReport, RemovedInfo, + UpdateReport, + }; + + use super::*; + + #[test] + fn the_system_pass_args_carry_the_config_and_the_json_stream() { + let forward: Vec = ["--user".into(), "--net-timeout".into()].to_vec(); + let args = system_pass_args("/tmp/packages.toml", &forward, true); + let shown: Vec = args + .iter() + .map(|arg| arg.to_string_lossy().into_owned()) + .collect(); + assert_eq!( + shown, + vec![ + "--json", + "--system", + "--user", + "--net-timeout", + "apply", + "--only-system", + "--yes", + "--packages", + "/tmp/packages.toml", + ] + ); + let quiet = system_pass_args("/tmp/packages.toml", &[], false); + assert!( + !quiet.iter().any(|arg| arg.to_string_lossy() == "--json"), + "the terminal pass prints for a person" + ); + } + + #[test] + fn password_demanded_spots_sudos_own_words() { + assert!(password_demanded("sudo: a password is required")); + assert!(!password_demanded("dpkg gave up halfway")); + } + + #[test] + fn the_system_names_compare_is_order_insensitive() { + let confirmed = vec!["jq".to_string(), "bat".to_string()]; + let reordered = vec!["bat".to_string(), "jq".to_string()]; + assert!(system_names_agree(&confirmed, &reordered)); + let with_extra = vec![ + "bat".to_string(), + "docker-compose".to_string(), + "jq".to_string(), + ]; + assert!(!system_names_agree(&confirmed, &with_extra)); + let with_missing = vec!["jq".to_string()]; + assert!(!system_names_agree(&confirmed, &with_missing)); + assert!(system_names_agree(&[], &[])); + } + + #[test] + fn a_stale_packages_file_names_the_reconfirm_in_its_report() { + let outcome = system_stale_outcome(); + assert!(!outcome.ok); + assert!(!outcome.aborted); + assert_eq!( + outcome.headline, + "packages.toml changed since the confirmation" + ); + assert!(matches!( + &outcome.lines[0], + OutcomeLine::Failed { error, .. } if error.contains("Confirm it again") + )); + } + + #[test] + fn the_output_wait_honors_the_grace_while_lines_keep_arriving() { + let (line_tx, line_rx) = std::sync::mpsc::channel::(); + let (msg_tx, _msg_rx) = std::sync::mpsc::channel::(); + // A grandchild that never stops emitting: the sends only fail + // once the receiver is gone. + let writer = std::thread::spawn(move || { + while line_tx.send(PipeLine::Out("heartbeat".to_string())).is_ok() { + std::thread::sleep(Duration::from_millis(10)); + } + }); + let mut exited = || true; + let started = Instant::now(); + let (complete, kept_errors) = collect_output(&line_rx, &mut exited, &msg_tx); + let elapsed = started.elapsed(); + drop(line_rx); + let _ = writer.join(); + assert!(complete.is_none()); + assert!(kept_errors.is_empty()); + assert!(elapsed >= PIPE_GRACE, "the wait gave up after {elapsed:?}"); + assert!( + elapsed < Duration::from_secs(3), + "the wait ran {elapsed:?}, far past the {PIPE_GRACE:?} grace" + ); + } + + fn installed_info(name: &str, version: &str) -> InstalledInfo { + InstalledInfo { + pkg_name: name.to_string(), + pkg_family: None, + repo_name: "bincache".to_string(), + version: version.to_string(), + install_dir: PathBuf::new(), + symlinks: Vec::new(), + shared: Vec::new(), + notes: None, + } + } + + fn removed_info(name: &str, version: &str) -> RemovedInfo { + RemovedInfo { + pkg_name: name.to_string(), + repo_name: "bincache".to_string(), + version: version.to_string(), + } + } + + fn failed_info(name: &str, error: &str) -> FailedInfo { + FailedInfo { + pkg_name: name.to_string(), + error: error.to_string(), + } + } + + #[test] + fn an_install_report_becomes_per_package_lines_and_a_counted_headline() { + let mut bat = installed_info("bat", "0.24.0"); + bat.notes = Some(vec!["Config lives in ~/.config/bat".to_string()]); + let report = InstallReport { + installed: vec![bat, installed_info("fd", "10.2.0")], + failed: vec![failed_info("jq", "no checksum")], + warnings: vec!["Signature verification skipped".to_string()], + cancelled: vec!["yq".to_string()], + }; + let outcome = install_outcome(report); + assert!(!outcome.ok); + assert!(!outcome.aborted); + assert_eq!(outcome.headline, "Install finished with 1 failures"); + assert_eq!(outcome.lines.len(), 6); + assert!(matches!(&outcome.lines[0], OutcomeLine::Done(text) if text == "bat 0.24.0")); + assert!(matches!(&outcome.lines[1], OutcomeLine::Done(text) if text == "fd 10.2.0")); + assert!( + matches!(&outcome.lines[2], OutcomeLine::Failed { name, error } if name == "jq" && error == "no checksum") + ); + assert!(matches!(&outcome.lines[3], OutcomeLine::Skipped(name) if name == "yq")); + assert!( + matches!(&outcome.lines[4], OutcomeLine::Note { name, text } if name == "bat" && text == "Config lives in ~/.config/bat") + ); + assert!( + matches!(&outcome.lines[5], OutcomeLine::Warning(text) if text == "Signature verification skipped") + ); + } + + #[test] + fn a_single_install_is_named_in_the_headline() { + let report = InstallReport { + installed: vec![installed_info("bat", "0.24.0")], + failed: Vec::new(), + warnings: Vec::new(), + cancelled: Vec::new(), + }; + let outcome = install_outcome(report); + assert!(outcome.ok); + assert_eq!(outcome.headline, "Installed bat 0.24.0"); + assert_eq!(outcome.lines.len(), 1); + } + + #[test] + fn several_installs_are_counted_in_the_headline() { + let report = InstallReport { + installed: vec![ + installed_info("bat", "0.24.0"), + installed_info("fd", "10.2.0"), + ], + failed: Vec::new(), + warnings: Vec::new(), + cancelled: Vec::new(), + }; + let outcome = install_outcome(report); + assert!(outcome.ok); + assert_eq!(outcome.headline, "Installed 2 packages"); + } + + #[test] + fn a_remove_report_becomes_per_package_lines_and_a_counted_headline() { + let report = RemoveReport { + removed: vec![ + removed_info("obsidian", "1.7.7"), + removed_info("zellij", "0.41.2"), + ], + failed: vec![failed_info("fd", "files still open")], + cancelled: vec!["jq".to_string()], + }; + let outcome = remove_outcome(report); + assert!(!outcome.ok); + assert_eq!(outcome.headline, "Removed 2 packages"); + assert!(matches!(&outcome.lines[0], OutcomeLine::Done(text) if text == "obsidian 1.7.7")); + assert!(matches!(&outcome.lines[1], OutcomeLine::Done(text) if text == "zellij 0.41.2")); + assert!( + matches!(&outcome.lines[2], OutcomeLine::Failed { name, error } if name == "fd" && error == "files still open") + ); + assert!(matches!(&outcome.lines[3], OutcomeLine::Skipped(name) if name == "jq")); + } + + #[test] + fn an_update_report_becomes_per_package_lines_and_a_counted_headline() { + let report = UpdateReport { + updated: vec![installed_info("yq", "4.44.3")], + failed: Vec::new(), + url_updates: Vec::new(), + cancelled: Vec::new(), + }; + let outcome = update_outcome(report); + assert!(outcome.ok); + assert_eq!(outcome.headline, "Updated 1 packages"); + assert!(matches!(&outcome.lines[0], OutcomeLine::Done(text) if text == "yq 4.44.3")); + } + + #[test] + fn an_apply_report_becomes_a_counted_headline() { + let outcome = apply_outcome(ApplyReport { + installed_count: 2, + updated_count: 1, + removed_count: 0, + failed_count: 0, + cancelled_count: 0, + }); + assert!(outcome.ok); + assert_eq!( + outcome.headline, + "Applied: 2 installed, 1 updated, 0 removed" + ); + + let failed = apply_outcome(ApplyReport { + installed_count: 2, + updated_count: 1, + removed_count: 0, + failed_count: 1, + cancelled_count: 0, + }); + assert!(!failed.ok); + } + + #[test] + fn a_cancelled_call_reports_as_aborted() { + let outcome = failed_outcome("Sync repositories", SoarError::Cancelled); + assert!(outcome.ok); + assert!(outcome.aborted); + assert_eq!(outcome.headline, "Aborted"); + assert!(outcome.lines.is_empty()); + } + + #[test] + fn a_failed_call_names_the_job_and_carries_the_error() { + let outcome = failed_outcome("Sync repositories", SoarError::Custom("offline".into())); + assert!(!outcome.ok); + assert!(!outcome.aborted); + assert_eq!(outcome.headline, "Sync repositories failed"); + assert_eq!(outcome.lines.len(), 1); + assert!( + matches!(&outcome.lines[0], OutcomeLine::Failed { name, error } if name == "Sync repositories" && error == "offline") + ); + } +} diff --git a/crates/soar-tui/src/sink.rs b/crates/soar-tui/src/sink.rs new file mode 100644 index 00000000..d77aa822 --- /dev/null +++ b/crates/soar-tui/src/sink.rs @@ -0,0 +1,44 @@ +//! Bridges soar's operations into the interface's message channel. + +use std::sync::mpsc::Sender; + +use soar_events::{EventSink, SoarEvent}; + +use crate::msg::Msg; + +/// Forwards soar events into the interface's message channel. +pub(crate) struct TuiSink(Sender); + +impl TuiSink { + /// Creates the sink that delivers events to `tx`. + pub(crate) fn new(tx: Sender) -> Self { + Self(tx) + } +} + +impl EventSink for TuiSink { + fn emit(&self, event: SoarEvent) { + let _ = self.0.send(Msg::Soar(event)); + } +} + +#[cfg(test)] +mod tests { + use std::sync::mpsc; + + use soar_events::{EventSink as _, LogLevel, SoarEvent}; + + use super::TuiSink; + use crate::msg::Msg; + + #[test] + fn emitted_events_arrive_as_soar_messages() { + let (tx, rx) = mpsc::channel(); + let sink = TuiSink::new(tx); + sink.emit(SoarEvent::Log { + level: LogLevel::Info, + message: "sync finished".into(), + }); + assert!(matches!(rx.recv(), Ok(Msg::Soar(_)))); + } +} diff --git a/crates/soar-tui/src/terminal.rs b/crates/soar-tui/src/terminal.rs new file mode 100644 index 00000000..ad939878 --- /dev/null +++ b/crates/soar-tui/src/terminal.rs @@ -0,0 +1,137 @@ +//! Terminal session handling: taking over the screen, giving it back, and +//! restoring it even on a panic. + +use std::io::{self, Write}; + +use ratatui::{ + Terminal, + backend::CrosstermBackend, + crossterm::{ + cursor, + event::{DisableMouseCapture, EnableMouseCapture}, + execute, + terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode}, + }, +}; + +/// Backend used to draw on stdout. +pub(crate) type Backend = CrosstermBackend; + +/// The terminal the interface draws on. +pub(crate) struct Session { + /// Terminal used to render frames. + pub(crate) terminal: Terminal, + active: bool, +} + +impl Session { + /// Takes over the terminal: raw mode, alternate screen, mouse capture, + /// hidden cursor. + pub(crate) fn enter() -> io::Result { + enable_raw_mode()?; + let taken = execute!( + io::stdout(), + EnterAlternateScreen, + EnableMouseCapture, + cursor::Hide + ); + let terminal = taken.and_then(|()| Terminal::new(CrosstermBackend::new(io::stdout()))); + match terminal { + Ok(terminal) => { + Ok(Self { + terminal, + active: true, + }) + } + Err(err) => { + // Raw mode and the screen were already partly taken + // over, so they go back before the failure escapes. + let _ = restore(); + Err(err) + } + } + } + + /// Returns the terminal to its original state. Safe to call twice. + pub(crate) fn leave(&mut self) -> io::Result<()> { + if !self.active { + return Ok(()); + } + let restored = restore(); + // A failed restore keeps the session active, so Drop retries + // instead of the failure ending the attempts. + if restored.is_ok() { + self.active = false; + } + restored + } + + /// Returns the terminal to its original state so another program can use it. + pub(crate) fn suspend(&mut self) -> io::Result<()> { + self.leave() + } + + /// Takes the terminal back after [`Session::suspend`] and repaints it. + pub(crate) fn resume(&mut self) -> io::Result<()> { + enable_raw_mode()?; + let taken = execute!( + io::stdout(), + EnterAlternateScreen, + EnableMouseCapture, + cursor::Hide + ); + let repainted = taken.and_then(|()| self.terminal.clear()); + match repainted { + Ok(()) => { + self.active = true; + Ok(()) + } + Err(err) => { + // The terminal is half-taken and only this session could + // restore it, so it goes back before the failure + // escapes; like leave(), a failed restore stays active + // for Drop to retry. + if restore().is_err() { + self.active = true; + } + Err(err) + } + } + } +} + +impl Drop for Session { + fn drop(&mut self) { + let _ = self.leave(); + } +} + +/// Restores the terminal from inside the panic handler before the regular +/// panic message is printed. +pub(crate) fn install_panic_hook() { + let previous = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |info| { + let _ = restore(); + previous(info); + })); +} + +/// Prints a notice and waits for the user to press Enter after a suspended +/// program has finished, so its output stays readable. +pub(crate) fn wait_for_enter() { + print!("\nPress Enter to return to soar"); + let _ = io::stdout().flush(); + let mut line = String::new(); + let _ = io::stdin().read_line(&mut line); +} + +fn restore() -> io::Result<()> { + let result = execute!( + io::stdout(), + LeaveAlternateScreen, + DisableMouseCapture, + cursor::Show + ); + disable_raw_mode()?; + result +} diff --git a/crates/soar-tui/src/test_support.rs b/crates/soar-tui/src/test_support.rs new file mode 100644 index 00000000..e6fb92d3 --- /dev/null +++ b/crates/soar-tui/src/test_support.rs @@ -0,0 +1,299 @@ +//! Test-only helpers for the interface: rendering the state into text, +//! building key messages, and making database fixtures. + +use std::path::PathBuf; + +use ratatui::{ + Terminal, + backend::TestBackend, + crossterm::event::{Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers}, +}; +use soar_config::packages::ResolvedPackage; +use soar_core::{ + database::models::{InstalledPackage, Package}, + package::install::InstallTarget, +}; +use soar_operations::{ApplyDiff, HealthReport, InstalledEntry, UpdateInfo}; + +use crate::{ + app::{App, AppEnv}, + msg::Msg, + theme::Theme, + ui, + views::{ + apply::ApplyPlan, + browse::{CatalogRow, PackageKey}, + }, +}; + +/// Renders one frame into a fixed-size buffer and returns it as text rows. +/// Wide characters occupy two cells, the second of which is empty, so the +/// joined row reproduces the visible text. +pub(crate) fn render(app: &mut App, width: u16, height: u16) -> Vec { + let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap(); + terminal.draw(|f| ui::render(f, app)).unwrap(); + let buf = terminal.backend().buffer(); + (0..height) + .map(|y| (0..width).map(|x| buf[(x, y)].symbol()).collect::()) + .collect() +} + +/// Renders one frame and joins the rows into one screen of text. +pub(crate) fn screen(app: &mut App, width: u16, height: u16) -> String { + render(app, width, height).join("\n") +} + +/// Builds a plain character key press. +pub(crate) fn key(c: char) -> Msg { + key_msg(KeyCode::Char(c), KeyModifiers::NONE) +} + +/// Builds a named key press, such as Tab or Enter. +pub(crate) fn code(code: KeyCode) -> Msg { + key_msg(code, KeyModifiers::NONE) +} + +/// Builds a character key press held with Ctrl. +pub(crate) fn ctrl(c: char) -> Msg { + key_msg(KeyCode::Char(c), KeyModifiers::CONTROL) +} + +fn key_msg(code: KeyCode, mods: KeyModifiers) -> Msg { + Msg::Input(Event::Key(KeyEvent::new_with_kind( + code, + mods, + KeyEventKind::Press, + ))) +} + +/// Builds the state the interface starts in, with fixed session facts. +pub(crate) fn test_app() -> App { + test_app_with(Theme::new(true, true)) +} + +/// Builds the interface around a given theme, for the sessions that draw +/// the ASCII glyph set. +pub(crate) fn test_app_with(theme: Theme) -> App { + App::new( + AppEnv { + version: "0.0.0".to_string(), + profile: "default".to_string(), + system: false, + config_path: PathBuf::from("/tmp/soar-test-config.toml"), + packages_path: PathBuf::from("/tmp/soar-test-packages.toml"), + }, + theme, + ) +} + +/// Builds a catalog package with the given name, version, and repository. +pub(crate) fn package(name: &str, version: &str, repo: &str) -> Package { + Package { + pkg_name: name.to_string(), + version: version.to_string(), + repo_name: repo.to_string(), + ..Default::default() + } +} + +/// Builds a catalog row with the given name, version, and repository. +pub(crate) fn catalog_row(name: &str, version: &str, repo: &str) -> CatalogRow { + CatalogRow { + key: PackageKey { + repo_name: repo.to_string(), + pkg_name: name.to_string(), + pkg_family: None, + pkg_id: None, + }, + version: version.to_string(), + pkg_type: None, + description: String::new(), + installed: false, + other_versions: Vec::new(), + haystack: name.to_lowercase(), + } +} + +/// Builds an installed package row with the given name, version, and +/// repository. +pub(crate) fn installed_package(name: &str, version: &str, repo: &str) -> InstalledPackage { + InstalledPackage { + repo_name: repo.to_string(), + pkg_name: name.to_string(), + version: version.to_string(), + id: name_id(name), + pkg_id: None, + pkg_family: None, + pkg_type: None, + size: 0, + checksum: None, + installed_path: String::new(), + installed_date: String::new(), + profile: String::new(), + pinned: false, + is_installed: true, + detached: false, + unlinked: false, + provides: None, + portable_path: None, + portable_home: None, + portable_config: None, + portable_share: None, + portable_cache: None, + install_patterns: None, + download_url: None, + update_info: None, + } +} + +/// Builds an installed entry with the given name, version, and repository, +/// healthy and with no size recorded yet. +pub(crate) fn installed_entry(name: &str, version: &str, repo: &str) -> InstalledEntry { + InstalledEntry { + package: installed_package(name, version, repo), + disk_size: 0, + is_healthy: true, + } +} + +/// Builds one checked update: the package named moving from `current` to +/// `new` in the given repository, with the new package behind the install +/// target. +pub(crate) fn update_info(name: &str, current: &str, new: &str, repo: &str) -> UpdateInfo { + UpdateInfo { + pkg_name: name.to_string(), + repo_name: repo.to_string(), + current_version: current.to_string(), + new_version: new.to_string(), + target: InstallTarget { + package: package(name, new, repo), + ..Default::default() + }, + update_toml_url: None, + } +} + +/// Builds a health report with every check passing and nothing broken. +pub(crate) fn health_report() -> HealthReport { + HealthReport { + path_configured: true, + bin_path: PathBuf::from("/home/user/.local/bin"), + man_path: None, + man_path_configured: true, + broken_packages: Vec::new(), + broken_symlinks: Vec::new(), + } +} + +/// One declared package with the given name. +pub(crate) fn resolved_package(name: &str) -> ResolvedPackage { + ResolvedPackage { + name: name.to_string(), + ..Default::default() + } +} + +/// An install plan entry for a package with the given name and version. +pub(crate) fn install_entry(name: &str, version: &str) -> (ResolvedPackage, InstallTarget) { + ( + resolved_package(name), + InstallTarget { + package: package(name, version, "bincache"), + ..Default::default() + }, + ) +} + +/// A computed plan for the packages file holding one install, one update, +/// and two in sync, at the usual path. +pub(crate) fn apply_plan() -> ApplyPlan { + let update = InstallTarget { + package: package("yq", "4.44.3", "bincache"), + existing_install: Some(installed_package("yq", "4.44.2", "bincache")), + ..Default::default() + }; + let diff = ApplyDiff { + to_install: vec![install_entry("bat", "0.24.0")], + to_update: vec![(resolved_package("yq"), update)], + in_sync: vec!["fd".to_string(), "jq".to_string()], + ..Default::default() + }; + ApplyPlan { + path: PathBuf::from("/home/user/.config/soar/packages.toml"), + diff: Some(diff), + system: Vec::new(), + } +} + +/// Builds the paths list the health view shows beside its checks. +pub(crate) fn health_paths() -> Vec<(String, PathBuf)> { + [ + ("Config", "/home/user/.config/soar/config.toml"), + ("Packages config", "/home/user/.config/soar/packages.toml"), + ("Bin", "/home/user/.local/share/soar/bin"), + ("Database", "/home/user/.local/share/soar/db"), + ("Cache", "/home/user/.local/share/soar/cache"), + ("Packages", "/home/user/.local/share/soar/packages"), + ("Repositories", "/home/user/.local/share/soar/repos"), + ] + .into_iter() + .map(|(label, path)| (label.to_string(), PathBuf::from(path))) + .collect() +} + +/// A database id for a fixture name, unique enough for the names tests +/// use, so marks can tell fixtures apart. +fn name_id(name: &str) -> u64 { + name.bytes().fold(0u64, |acc, byte| { + acc.wrapping_mul(31).wrapping_add(u64::from(byte)) + }) +} + +#[cfg(test)] +mod tests { + use std::time::Instant; + + use ratatui::crossterm::event::KeyCode; + + use super::{code, ctrl, installed_package, key, package, screen, test_app}; + use crate::views::ViewId; + + #[test] + fn the_first_view_title_appears_on_screen() { + assert!(screen(&mut test_app(), 80, 24).contains("Browse")); + } + + #[test] + fn a_character_key_reaches_the_app() { + let mut app = test_app(); + app.update(key('q'), Instant::now()); + assert!(app.quit); + } + + #[test] + fn a_named_key_reaches_the_app() { + let mut app = test_app(); + app.update(code(KeyCode::Tab), Instant::now()); + assert_eq!(app.view, ViewId::Installed); + } + + #[test] + fn a_ctrl_key_reaches_the_app() { + let mut app = test_app(); + app.update(ctrl('c'), Instant::now()); + assert!(app.quit); + } + + #[test] + fn fixtures_carry_name_version_and_repo() { + let pkg = package("fd", "10.2.0", "pkgforge"); + assert_eq!(pkg.pkg_name, "fd"); + assert_eq!(pkg.version, "10.2.0"); + assert_eq!(pkg.repo_name, "pkgforge"); + + let installed = installed_package("fd", "10.2.0", "pkgforge"); + assert_eq!(installed.pkg_name, "fd"); + assert_eq!(installed.version, "10.2.0"); + assert_eq!(installed.repo_name, "pkgforge"); + } +} diff --git a/crates/soar-tui/src/theme.rs b/crates/soar-tui/src/theme.rs new file mode 100644 index 00000000..918fdec0 --- /dev/null +++ b/crates/soar-tui/src/theme.rs @@ -0,0 +1,389 @@ +//! The palette, text styles, and symbols every part of the interface draws +//! with. +//! +//! All colors come from the 16 named ANSI colors, so the interface follows +//! the terminal's theme. Without color, every style is built from modifiers +//! alone. The styles and glyphs no view draws yet carry their own allow +//! until their views arrive. + +use ratatui::style::{Color, Modifier, Style}; + +/// The colors and glyphs one session draws with. +/// +/// A session either renders colors and icons or it does not, so every style +/// and symbol comes from here instead of being written at the drawing site. +pub(crate) struct Theme { + color: bool, + icons: bool, +} + +impl Theme { + /// Builds the theme for one session. + /// + /// `color` turns the palette on; without it the styles fall back to + /// bold, dim, italic, reversed, and underlined text. `icons` selects the + /// unicode glyph set over its ASCII fallback. + pub(crate) fn new(color: bool, icons: bool) -> Theme { + Theme { + color, + icons, + } + } + + /// The brand and focus color: the header mark, the focused border, the + /// active tab, and gauges. + pub(crate) fn accent(&self) -> Style { + self.styled(Color::Cyan, Modifier::BOLD) + } + + /// Version numbers and package family names. + pub(crate) fn accent2(&self) -> Style { + self.styled(Color::Magenta, Modifier::ITALIC) + } + + /// Normal text. + pub(crate) fn text(&self) -> Style { + self.styled(Color::Reset, Modifier::empty()) + } + + /// Secondary text: hints, descriptions, and unfocused borders. + pub(crate) fn muted(&self) -> Style { + self.styled(Color::DarkGray, Modifier::DIM) + } + + /// Installed, healthy, done, and new versions. + pub(crate) fn success(&self) -> Style { + self.styled(Color::Green, Modifier::empty()) + } + + /// Notes, pinned packages, skipped items, and the system badge. + pub(crate) fn warning(&self) -> Style { + self.styled(Color::Yellow, Modifier::BOLD) + } + + /// Errors, broken packages, and removal. + pub(crate) fn danger(&self) -> Style { + self.styled(Color::Red, Modifier::BOLD | Modifier::UNDERLINED) + } + + /// Package names in summaries and repository names. + pub(crate) fn info(&self) -> Style { + self.styled(Color::Blue, Modifier::empty()) + } + + /// The row under the cursor. + pub(crate) fn cursor_row(&self) -> Style { + if self.color { + Style::new() + .fg(Color::Black) + .bg(Color::Cyan) + .add_modifier(Modifier::BOLD) + } else { + Style::new().add_modifier(Modifier::REVERSED | Modifier::BOLD) + } + } + + /// A row the user selected for an action. + pub(crate) fn marked(&self) -> Style { + if self.color { + self.accent().add_modifier(Modifier::BOLD) + } else { + Style::new().add_modifier(Modifier::BOLD | Modifier::UNDERLINED) + } + } + + /// The title of a list or pane. + pub(crate) fn title(&self) -> Style { + Style::new().add_modifier(Modifier::BOLD) + } + + /// A key name in hints and help. + pub(crate) fn key(&self) -> Style { + self.accent().add_modifier(Modifier::BOLD) + } + + /// The border of a pane: accent while it has focus, muted otherwise. + pub(crate) fn border(&self, focused: bool) -> Style { + if self.color { + if focused { self.accent() } else { self.muted() } + } else if focused { + Style::new().add_modifier(Modifier::BOLD) + } else { + Style::new() + } + } + + /// The style of a package type badge, such as `appimage` or `archive`. + pub(crate) fn type_badge(&self, pkg_type: &str) -> Style { + match pkg_type { + "appimage" => self.info(), + "flatimage" => self.accent2(), + "static" | "dynamic" => self.success(), + "archive" => self.warning(), + _ => self.muted(), + } + } + + /// The glyph set for this session: unicode when icons are on, ASCII + /// otherwise. + pub(crate) fn sym(&self) -> &'static Symbols { + if self.icons { &UNICODE } else { &ASCII } + } + + /// Whether this session draws the unicode glyph set. + pub(crate) fn icons(&self) -> bool { + self.icons + } + + /// The spinner frame for the given tick counter, wrapping around. + pub(crate) fn spinner(&self, frame: u64) -> &'static str { + let symbols = self.sym(); + symbols.spinner[(frame % symbols.spinner.len() as u64) as usize] + } + + /// Builds a style with the given foreground in color mode, or the given + /// modifiers alone without it. + fn styled(&self, color: Color, modifiers: Modifier) -> Style { + if self.color { + Style::new().fg(color) + } else { + Style::new().add_modifier(modifiers) + } + } +} + +/// The glyphs one session draws with, in one of two forms. +pub(crate) struct Symbols { + /// The mark shown before the program name in the header. + pub(crate) brand: &'static str, + /// Marks an installed or finished item. + pub(crate) installed: &'static str, + /// Marks a package that is not installed yet. + pub(crate) available: &'static str, + /// Marks a row the user selected for an action. + pub(crate) marked: &'static str, + /// Marks the row under the cursor. + pub(crate) cursor: &'static str, + /// Marks a package with a newer version. + pub(crate) update: &'static str, + /// Marks a package the plan would take away again. + pub(crate) remove: &'static str, + /// Marks a note or a skipped item. + pub(crate) warning: &'static str, + /// Marks a failure. + pub(crate) error: &'static str, + /// Stands for one typed character of a hidden value, such as a + /// password. + pub(crate) mask: &'static str, + /// Marks a package held on its current version. + pub(crate) pinned: &'static str, + /// Points from an old version to a new one. + pub(crate) arrow: &'static str, + /// Separates two short facts, such as profile and mode. + pub(crate) dot: &'static str, + /// The filled part of a progress bar. + pub(crate) gauge_fill: &'static str, + /// The empty part of a progress bar. + pub(crate) gauge_empty: &'static str, + /// Marks text cut short to fit its column. + pub(crate) ellipsis: &'static str, + /// The frames a spinner cycles through, one per tick. + pub(crate) spinner: &'static [&'static str], +} + +/// The unicode glyph set. +const UNICODE: Symbols = Symbols { + brand: "◆", + installed: "✓", + available: "○", + marked: "●", + cursor: "▌", + update: "↑", + remove: "−", + warning: "⚠", + error: "✗", + mask: "•", + pinned: "⊙", + arrow: "→", + dot: "·", + gauge_fill: "━", + gauge_empty: "─", + ellipsis: "…", + spinner: &["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"], +}; + +/// The ASCII fallback glyph set. +const ASCII: Symbols = Symbols { + brand: "*", + installed: "+", + available: "-", + marked: "*", + cursor: ">", + update: "^", + remove: "-", + warning: "!", + error: "x", + mask: "*", + pinned: "p", + arrow: "->", + dot: "|", + gauge_fill: "#", + gauge_empty: "-", + ellipsis: "...", + spinner: &["-", "\\", "|", "/"], +}; + +#[cfg(test)] +mod tests { + use ratatui::style::{Color, Modifier}; + + use super::{ASCII, Theme, UNICODE}; + + fn colored() -> Theme { + Theme::new(true, true) + } + + fn plain() -> Theme { + Theme::new(false, true) + } + + #[test] + fn no_color_leaves_every_style_colorless() { + let theme = plain(); + let styles = [ + theme.accent(), + theme.accent2(), + theme.text(), + theme.muted(), + theme.success(), + theme.warning(), + theme.danger(), + theme.info(), + theme.cursor_row(), + theme.marked(), + theme.title(), + theme.key(), + theme.border(true), + theme.border(false), + theme.type_badge("appimage"), + theme.type_badge("flatimage"), + theme.type_badge("static"), + theme.type_badge("dynamic"), + theme.type_badge("archive"), + theme.type_badge("other"), + ]; + for style in styles { + assert_eq!(style.fg, None); + assert_eq!(style.bg, None); + } + } + + #[test] + fn tokens_use_the_palette_with_color() { + let theme = colored(); + assert_eq!(theme.accent().fg, Some(Color::Cyan)); + assert_eq!(theme.accent2().fg, Some(Color::Magenta)); + assert_eq!(theme.text().fg, Some(Color::Reset)); + assert_eq!(theme.muted().fg, Some(Color::DarkGray)); + assert_eq!(theme.success().fg, Some(Color::Green)); + assert_eq!(theme.warning().fg, Some(Color::Yellow)); + assert_eq!(theme.danger().fg, Some(Color::Red)); + assert_eq!(theme.info().fg, Some(Color::Blue)); + } + + #[test] + fn tokens_fall_back_to_modifiers_without_color() { + let theme = plain(); + assert!(theme.accent().add_modifier.contains(Modifier::BOLD)); + assert!(theme.accent2().add_modifier.contains(Modifier::ITALIC)); + assert_eq!(theme.text().add_modifier, Modifier::empty()); + assert!(theme.muted().add_modifier.contains(Modifier::DIM)); + assert_eq!(theme.success().add_modifier, Modifier::empty()); + assert!(theme.warning().add_modifier.contains(Modifier::BOLD)); + assert!(theme.danger().add_modifier.contains(Modifier::BOLD)); + assert!(theme.danger().add_modifier.contains(Modifier::UNDERLINED)); + assert_eq!(theme.info().add_modifier, Modifier::empty()); + } + + #[test] + fn the_cursor_row_reverses_without_color() { + let style = plain().cursor_row(); + assert!(style.add_modifier.contains(Modifier::REVERSED)); + assert!(style.add_modifier.contains(Modifier::BOLD)); + + let style = colored().cursor_row(); + assert_eq!(style.fg, Some(Color::Black)); + assert_eq!(style.bg, Some(Color::Cyan)); + } + + #[test] + fn a_marked_row_underlines_without_color() { + let style = plain().marked(); + assert!(style.add_modifier.contains(Modifier::BOLD)); + assert!(style.add_modifier.contains(Modifier::UNDERLINED)); + + let style = colored().marked(); + assert_eq!(style.fg, Some(Color::Cyan)); + assert!(style.add_modifier.contains(Modifier::BOLD)); + } + + #[test] + fn borders_follow_focus() { + assert_eq!(colored().border(true).fg, Some(Color::Cyan)); + assert_eq!(colored().border(false).fg, Some(Color::DarkGray)); + assert!(plain().border(true).add_modifier.contains(Modifier::BOLD)); + assert_eq!(plain().border(false).add_modifier, Modifier::empty()); + } + + #[test] + fn the_ascii_glyphs_are_ascii() { + let symbols = &ASCII; + let glyphs = [ + symbols.brand, + symbols.installed, + symbols.available, + symbols.marked, + symbols.cursor, + symbols.update, + symbols.remove, + symbols.warning, + symbols.error, + symbols.mask, + symbols.pinned, + symbols.arrow, + symbols.dot, + symbols.gauge_fill, + symbols.gauge_empty, + symbols.ellipsis, + ]; + for glyph in glyphs { + assert!(glyph.is_ascii(), "{glyph:?} is not ASCII"); + } + for frame in ASCII.spinner { + assert!(frame.is_ascii(), "{frame:?} is not ASCII"); + } + } + + #[test] + fn both_spinners_have_frames() { + assert!(!UNICODE.spinner.is_empty()); + assert!(!ASCII.spinner.is_empty()); + } + + #[test] + fn the_spinner_picks_its_set() { + assert_eq!(colored().sym().brand, UNICODE.brand); + assert_eq!(Theme::new(true, false).sym().brand, ASCII.brand); + } + + #[test] + fn the_spinner_wraps_around() { + let theme = colored(); + let frames = theme.sym().spinner; + let len = frames.len() as u64; + assert_eq!(theme.spinner(0), frames[0]); + assert_eq!(theme.spinner(len - 1), frames[(len - 1) as usize]); + assert_eq!(theme.spinner(len), frames[0]); + assert_eq!(theme.spinner(len + 2), frames[2]); + } +} diff --git a/crates/soar-tui/src/ui.rs b/crates/soar-tui/src/ui.rs new file mode 100644 index 00000000..28529beb --- /dev/null +++ b/crates/soar-tui/src/ui.rs @@ -0,0 +1,135 @@ +//! The frame layout: the too-small screen, the header, the view body, the +//! activity strip, and the status bar. + +use ratatui::{ + Frame, + layout::{Alignment, Constraint, Layout, Rect}, + widgets::{Clear, Paragraph}, +}; + +use crate::{ + app::{App, LayoutCache}, + views::{self, ViewId}, + widgets::{activity, header, status_bar, toast}, +}; + +/// The narrowest terminal the interface renders at. +pub(crate) const MIN_WIDTH: u16 = 60; + +/// The shortest terminal the interface renders at. +pub(crate) const MIN_HEIGHT: u16 = 16; + +/// Draws one frame: the chrome around the active view, or the too-small +/// message below the minimum size. The frame's hit areas are collected +/// from scratch, so a pointer click always reads the last drawn frame. +pub(crate) fn render(f: &mut Frame, app: &mut App) { + app.layout = LayoutCache::default(); + let area = f.area(); + if area.width < MIN_WIDTH || area.height < MIN_HEIGHT { + render_too_small(f, area, app); + return; + } + let [header_row, body, activity_area, status_row] = Layout::vertical([ + Constraint::Length(1), + Constraint::Fill(1), + Constraint::Length(app.activity_height()), + Constraint::Length(1), + ]) + .areas(area); + header::render(f, header_row, app); + render_body(f, body, app); + if activity_area.height > 0 { + activity::render(f, activity_area, app); + } + status_bar::render(f, status_row, app); + toast::render(f, body, app); + if let Some(overlay) = &app.overlay { + let rect = overlay.render(f, body, app); + app.layout.overlay = Some(rect); + } +} + +/// Draws the message a terminal below the minimum size shows instead of the +/// interface. +fn render_too_small(f: &mut Frame, area: Rect, app: &App) { + f.render_widget(Clear, area); + let times = if app.theme.icons() { "×" } else { "x" }; + let message = format!( + "Terminal too small: need {MIN_WIDTH}{times}{MIN_HEIGHT}, have {}{times}{}", + area.width, area.height, + ); + let row = Rect { + y: area.y + area.height / 2, + height: 1, + ..area + }; + f.render_widget(Paragraph::new(message).alignment(Alignment::Center), row); +} + +/// Draws the active view in the body. +fn render_body(f: &mut Frame, area: Rect, app: &mut App) { + match app.view { + ViewId::Browse => views::browse::render(f, area, app), + ViewId::Installed => views::installed::render(f, area, app), + ViewId::Updates => views::updates::render(f, area, app), + ViewId::Apply => views::apply::render(f, area, app), + ViewId::Repos => views::repos::render(f, area, app), + ViewId::Health => views::health::render(f, area, app), + ViewId::Jobs => views::jobs::render(f, area, app), + } +} + +#[cfg(test)] +mod tests { + use crate::test_support::{render, screen, test_app}; + + #[test] + fn a_too_small_terminal_shows_the_message() { + let mut app = test_app(); + assert!(screen(&mut app, 59, 20).contains("Terminal too small")); + assert!(screen(&mut app, 60, 15).contains("Terminal too small")); + } + + #[test] + fn a_full_terminal_shows_the_view_pane() { + let mut app = test_app(); + let lines = render(&mut app, 80, 24); + let screen = lines.join("\n"); + assert!(!screen.contains("Terminal too small")); + assert!(lines[1].contains("Browse"), "body top is {:?}", lines[1]); + } + + #[test] + fn the_ascii_glyph_set_draws_through_the_interface() { + use crate::{ + msg::{Loaded, Msg}, + test_support::{catalog_row, test_app_with}, + theme::Theme, + }; + let mut app = test_app_with(Theme::new(true, false)); + let mut long = catalog_row( + "a-very-long-package-name-that-cannot-fit-the-column", + "1.0.0", + "bincache", + ); + long.description = "shaped by the glyph set".to_string(); + app.update( + Msg::Loaded(Loaded::Catalog { + check: 0, + result: Ok(vec![catalog_row("bat", "0.24.0", "bincache"), long]), + }), + std::time::Instant::now(), + ); + let screen = screen(&mut app, 60, 20); + assert!( + screen.contains('>'), + "the ascii cursor, screen is {screen:?}" + ); + assert!( + screen.contains("..."), + "the ascii ellipsis cuts a long name, screen is {screen:?}" + ); + assert!(!screen.contains('▌'), "screen is {screen:?}"); + assert!(!screen.contains('…'), "screen is {screen:?}"); + } +} diff --git a/crates/soar-tui/src/views/apply.rs b/crates/soar-tui/src/views/apply.rs new file mode 100644 index 00000000..a246d6b2 --- /dev/null +++ b/crates/soar-tui/src/views/apply.rs @@ -0,0 +1,628 @@ +//! The apply view: what applying `packages.toml` would change, and what +//! it would leave alone. + +use std::path::PathBuf; + +use ratatui::{ + Frame, + layout::Rect, + style::{Modifier, Style}, + text::{Line, Span}, + widgets::{Block, BorderType, Paragraph}, +}; +use soar_operations::ApplyDiff; + +use crate::{ + app::App, + format, + loadable::Loadable, + theme::Theme, + widgets::{scroll::ListCursor, states}, +}; + +/// How far the rows under a section header are indented. +const INDENT_WIDTH: usize = 4; + +/// What applying the packages file would do, and what it leaves alone. +pub(crate) struct ApplyPlan { + /// The packages file the plan was computed from. + pub(crate) path: PathBuf, + /// The changes applying would make, or `None` when the file does not + /// exist. + pub(crate) diff: Option, + /// Names of `system = true` packages left for the system pass. + /// Always empty in system mode. + pub(crate) system: Vec, +} + +/// The state of the apply view. +#[derive(Default)] +pub(crate) struct ApplyView { + /// The computed plan, loaded on the first visit and again after every + /// change to the file, the installation, or the prune flag. + pub(crate) plan: Loadable, + /// Whether applying also removes packages the file does not declare. + pub(crate) prune: bool, + /// The number of the computation in flight. Every start numbers + /// itself so a result from a computation a newer one replaced can be + /// dropped, whatever it found. + pub(crate) check: u32, + /// The body line the cursor sits on. + pub(crate) cursor: ListCursor, + /// How many lines the body drew last frame, so the cursor knows its + /// ends between renders. + pub(crate) body_rows: usize, +} + +impl ApplyView { + /// Starts a fresh computation. The last plan goes when the new one + /// arrives, and the start numbers itself so a result from a + /// computation a newer one replaced is dropped. + pub(crate) fn start(&mut self) { + self.check = self.check.wrapping_add(1); + self.plan = Loadable::Loading; + } + + /// Adopts a finished computation. The cursor returns to the top + /// because the body it pointed into has been rebuilt. + pub(crate) fn loaded(&mut self, result: Result) { + self.plan = match result { + Ok(plan) => Loadable::Ready(plan), + Err(error) => Loadable::Failed(error), + }; + self.cursor = ListCursor::default(); + } +} + +/// Draws the apply view: its border with the file's path and the prune +/// flag in the title, then the plan body, or the loading, missing-file, +/// and error states. +pub(crate) fn render(f: &mut Frame, area: Rect, app: &mut App) { + let theme = &app.theme; + let block = apply_block(&app.apply, theme, area.width); + let inner = block.inner(area); + f.render_widget(block, area); + let height = usize::from(inner.height); + match &app.apply.plan { + Loadable::Idle => {} + Loadable::Loading => { + states::loading(f, inner, theme, app.frame, "Computing changes"); + } + Loadable::Failed(error) => states::error(f, inner, theme, error), + Loadable::Ready(plan) => { + match &plan.diff { + None => { + let text = format!( + "No packages.toml at {}. Press n to create one.", + format::home_relative(&plan.path) + ); + states::empty(f, inner, theme, &text); + } + Some(diff) => { + let lines = plan_lines(plan, diff, usize::from(inner.width), theme); + app.apply.body_rows = lines.len(); + app.apply.cursor.clamp(lines.len()); + let window = app.apply.cursor.window(lines.len(), height); + let visible = lines[window.clone()].to_vec(); + app.layout.list = Some((inner, window.start)); + f.render_widget(Paragraph::new(visible), inner); + } + } + } + } +} + +/// The pane border: the file name in bold with its home-relative path +/// beside it, and the prune flag on the right of the top edge. +fn apply_block(view: &ApplyView, theme: &Theme, width: u16) -> Block<'static> { + let mut spans = vec![Span::raw(" "), Span::styled("packages.toml", theme.title())]; + if let Some(plan) = view.plan.ready() { + spans.push(Span::raw(" ")); + spans.push(Span::styled( + format::home_relative(&plan.path), + theme.muted(), + )); + } + let left = Line::from(spans); + let budget = usize::from(width).saturating_sub(2 + left.width()); + let block = Block::bordered() + .border_type(BorderType::Rounded) + .border_style(theme.border(true)) + .title(left); + if budget > 0 { + block.title_top(prune_line(view.prune, theme, budget).right_aligned()) + } else { + block + } +} + +/// The right end of the top border: whether applying also prunes, dropped +/// when the title leaves no room for it. +fn prune_line(prune: bool, theme: &Theme, budget: usize) -> Line<'static> { + let state = if prune { "on" } else { "off" }; + let mut line = Line::styled(format!(" prune: {state} "), theme.muted()); + if line.width() > budget { + line.spans.clear(); + } + line +} + +/// The body lines for one computed plan, in section order. Install, +/// update, and remove always show their count so a zero is visible; the +/// other sections fold away when they have nothing to list. +fn plan_lines( + plan: &ApplyPlan, + diff: &ApplyDiff, + width: usize, + theme: &Theme, +) -> Vec> { + let symbols = theme.sym(); + let mut lines = Vec::new(); + section_header( + &mut lines, + "+", + theme.success(), + "Install", + diff.to_install.len(), + ); + for (_resolved, target) in &diff.to_install { + let package = &target.package; + lines.push(row_line( + name_version_repo_row( + &package.pkg_name, + &package.version, + &package.repo_name, + theme, + ), + width, + theme, + )); + } + section_header( + &mut lines, + symbols.update, + theme.warning(), + "Update", + diff.to_update.len(), + ); + for (_resolved, target) in &diff.to_update { + let old = target + .existing_install + .as_ref() + .map_or_else(|| "?".to_string(), |installed| installed.version.clone()); + let package = &target.package; + lines.push(row_line( + vec![ + Span::styled(package.pkg_name.clone(), theme.text()), + Span::raw(" "), + Span::styled(old, theme.danger()), + Span::raw(" "), + Span::styled(symbols.arrow, theme.muted()), + Span::raw(" "), + Span::styled(package.version.clone(), theme.success()), + ], + width, + theme, + )); + } + section_header( + &mut lines, + symbols.remove, + theme.danger(), + "Remove", + diff.to_remove.len(), + ); + for package in &diff.to_remove { + lines.push(row_line( + name_version_repo_row( + &package.pkg_name, + &package.version, + &package.repo_name, + theme, + ), + width, + theme, + )); + } + if !diff.not_found.is_empty() { + section_header( + &mut lines, + symbols.error, + theme.danger(), + "Not found", + diff.not_found.len(), + ); + for name in &diff.not_found { + lines.push(row_line( + vec![Span::styled(name.clone(), theme.warning())], + width, + theme, + )); + } + } + if !diff.has_changes() && !diff.has_toml_updates() { + lines.push(Line::styled( + format!("{} Everything matches packages.toml", symbols.installed), + theme.success(), + )); + } + if !diff.in_sync.is_empty() { + section_header( + &mut lines, + symbols.installed, + theme.muted(), + "In sync", + diff.in_sync.len(), + ); + } + if !diff.pending_version_updates.is_empty() { + section_header( + &mut lines, + symbols.pinned, + theme.info(), + "Version pins", + diff.pending_version_updates.len(), + ); + for (name, version) in &diff.pending_version_updates { + lines.push(row_line( + vec![ + Span::styled(name.clone(), theme.text()), + Span::raw(" "), + Span::styled(version.clone(), theme.accent2()), + ], + width, + theme, + )); + } + lines.push(row_line( + vec![Span::styled("written back to packages.toml", theme.muted())], + width, + theme, + )); + } + if !plan.system.is_empty() { + lines.push(Line::from(vec![ + Span::styled( + format!("{} System {}", symbols.dot, plan.system.len()), + theme.warning().add_modifier(Modifier::BOLD), + ), + Span::raw(" "), + Span::styled("(asks for administrator rights)", theme.muted()), + ])); + let room = width.saturating_sub(INDENT_WIDTH); + let names = plan.system.join(" "); + for row in format::wrap(&names, room) { + lines.push(row_line( + vec![Span::styled(row, theme.text())], + width, + theme, + )); + } + } + lines +} + +/// One bold section header in its own color: `{symbol} {label} {count}`. +fn section_header( + lines: &mut Vec>, + symbol: &str, + style: Style, + label: &str, + count: usize, +) { + lines.push(Line::styled( + format!("{symbol} {label} {count}"), + style.add_modifier(Modifier::BOLD), + )); +} + +/// The `name version repo` spans shared by the install and remove rows. +fn name_version_repo_row( + name: &str, + version: &str, + repo: &str, + theme: &Theme, +) -> Vec> { + vec![ + Span::styled(name.to_string(), theme.text()), + Span::raw(" "), + Span::styled(version.to_string(), theme.accent2()), + Span::raw(" "), + Span::styled(repo.to_string(), theme.info()), + ] +} + +/// One indented row, cut to the pane width when its spans run past it. +fn row_line(spans: Vec>, width: usize, theme: &Theme) -> Line<'static> { + let mut all = vec![Span::raw(" ".repeat(INDENT_WIDTH))]; + all.extend(spans); + let total: usize = all.iter().map(|span| span.width()).sum(); + if total <= width { + return Line::from(all); + } + let text = all + .iter() + .map(|span| span.content.to_string()) + .collect::(); + Line::styled( + format::truncate(&text, width, theme.sym().ellipsis), + theme.text(), + ) +} + +#[cfg(test)] +mod tests { + use std::{ + path::{Path, PathBuf}, + time::Instant, + }; + + use soar_operations::ApplyDiff; + + use super::{ApplyPlan, ApplyView}; + use crate::{ + effect::Effect, + msg::{Loaded, Msg}, + test_support::{apply_plan, ctrl, install_entry, key, screen, test_app}, + views::ViewId, + }; + + /// The apply view with the given plan loaded. + fn apply_app(plan: ApplyPlan) -> (crate::app::App, Instant) { + let mut app = test_app(); + app.view = ViewId::Apply; + app.update(loaded(plan), Instant::now()); + (app, Instant::now()) + } + + /// A finished computation for the given plan, answering the check the + /// view still expects before any recompute has started. + fn loaded(plan: ApplyPlan) -> Msg { + Msg::Loaded(Loaded::ApplyDiff { + check: 0, + result: Ok(plan), + }) + } + + #[test] + fn entering_apply_the_first_time_computes_the_plan() { + let mut app = test_app(); + let effects = app.update(key('4'), Instant::now()); + let [ + Effect::ComputeApplyDiff { + prune, .. + }, + ] = &effects[..] + else { + panic!("expected one computation on first entry"); + }; + assert!(!*prune); + assert!(app.apply.plan.is_loading()); + } + + #[test] + fn reentering_apply_starts_nothing() { + let mut app = test_app(); + let now = Instant::now(); + app.update(key('4'), now); + app.update( + Msg::Loaded(Loaded::ApplyDiff { + check: app.apply.check, + result: Ok(apply_plan()), + }), + now, + ); + app.update(key('1'), now); + let effects = app.update(key('4'), now); + assert!(effects.is_empty()); + assert!(app.apply.plan.ready().is_some()); + } + + #[test] + fn ctrl_r_recomputes_with_the_current_prune() { + let (mut app, now) = apply_app(apply_plan()); + app.apply.prune = true; + let effects = app.update(ctrl('r'), now); + let [ + Effect::ComputeApplyDiff { + prune, .. + }, + ] = &effects[..] + else { + panic!("expected one computation on reload"); + }; + assert!(*prune); + assert!(app.apply.plan.is_loading()); + } + + #[test] + fn the_sections_show_their_counts() { + let (mut app, _) = apply_app(apply_plan()); + let screen = screen(&mut app, 100, 24); + for label in ["Install 1", "Update 1", "Remove 0", "In sync 2"] { + assert!(screen.contains(label), "screen is {screen:?}"); + } + } + + #[test] + fn rows_show_the_packages_the_plan_touches() { + let (mut app, _) = apply_app(apply_plan()); + let screen = screen(&mut app, 100, 24); + assert!(screen.contains("bat"), "screen is {screen:?}"); + assert!(screen.contains("0.24.0"), "screen is {screen:?}"); + assert!(screen.contains("bincache"), "screen is {screen:?}"); + assert!(screen.contains("4.44.2"), "screen is {screen:?}"); + assert!(screen.contains("4.44.3"), "screen is {screen:?}"); + assert!( + screen.contains(app.theme.sym().arrow), + "screen is {screen:?}" + ); + } + + #[test] + fn nothing_to_do_says_so_above_the_in_sync_count() { + let mut settled = apply_plan(); + if let Some(diff) = settled.diff.as_mut() { + diff.to_install.clear(); + diff.to_update.clear(); + diff.in_sync = vec!["fd".to_string()]; + } + let (mut app, _) = apply_app(settled); + let screen = screen(&mut app, 100, 24); + assert!( + screen.contains("Everything matches packages.toml"), + "screen is {screen:?}" + ); + assert!(screen.contains("In sync 1"), "screen is {screen:?}"); + } + + #[test] + fn a_missing_file_shows_how_to_create_one() { + let Ok(home) = std::env::var("HOME") else { + return; + }; + if home.is_empty() { + return; + } + let missing = ApplyPlan { + path: Path::new(&home).join(".config/soar/packages.toml"), + diff: None, + system: Vec::new(), + }; + let (mut app, _) = apply_app(missing); + let screen = screen(&mut app, 100, 24); + assert!( + screen.contains("No packages.toml at"), + "screen is {screen:?}" + ); + assert!( + screen.contains("Press n to create one."), + "screen is {screen:?}" + ); + } + + #[test] + fn a_failed_computation_shows_the_error_state() { + let mut app = test_app(); + app.view = ViewId::Apply; + app.update( + Msg::Loaded(Loaded::ApplyDiff { + check: 0, + result: Err("packages file unreadable".to_string()), + }), + Instant::now(), + ); + let screen = screen(&mut app, 80, 24); + assert!( + screen.contains("packages file unreadable"), + "screen is {screen:?}" + ); + assert!(screen.contains("ctrl-r to retry"), "screen is {screen:?}"); + } + + #[test] + fn the_system_section_lists_the_deferred_names() { + let mut deferred = apply_plan(); + deferred.system = vec!["docker-compose".to_string(), "tailscale".to_string()]; + let (mut app, _) = apply_app(deferred); + let screen = screen(&mut app, 100, 24); + assert!(screen.contains("System 2"), "screen is {screen:?}"); + assert!( + screen.contains("asks for administrator rights"), + "screen is {screen:?}" + ); + assert!(screen.contains("docker-compose"), "screen is {screen:?}"); + assert!(screen.contains("tailscale"), "screen is {screen:?}"); + } + + #[test] + fn the_system_section_is_left_out_when_empty() { + let (mut app, _) = apply_app(apply_plan()); + let screen = screen(&mut app, 100, 24); + assert!(!screen.contains("System"), "screen is {screen:?}"); + } + + #[test] + fn version_pins_note_the_write_back() { + let mut pinned = apply_plan(); + if let Some(diff) = pinned.diff.as_mut() { + diff.pending_version_updates = vec![("bat".to_string(), "0.24.0".to_string())]; + } + let (mut app, _) = apply_app(pinned); + let screen = screen(&mut app, 100, 24); + assert!(screen.contains("Version pins 1"), "screen is {screen:?}"); + assert!( + screen.contains("written back to packages.toml"), + "screen is {screen:?}" + ); + } + + #[test] + fn the_border_shows_the_prune_flag() { + let (mut app, _) = apply_app(apply_plan()); + assert!(screen(&mut app, 100, 24).contains("prune: off")); + app.apply.prune = true; + let screen = screen(&mut app, 100, 24); + assert!(screen.contains("prune: on"), "screen is {screen:?}"); + } + + #[test] + fn the_title_shows_the_home_relative_path() { + let Ok(home) = std::env::var("HOME") else { + return; + }; + if home.is_empty() { + return; + } + let mut titled = apply_plan(); + titled.path = Path::new(&home).join(".config/soar/packages.toml"); + let (mut app, _) = apply_app(titled); + let screen = screen(&mut app, 100, 24); + assert!( + screen.contains("~/.config/soar/packages.toml"), + "screen is {screen:?}" + ); + } + + #[test] + fn a_tall_body_scrolls_with_j_to_the_last_row() { + let diff = ApplyDiff { + to_install: (0..40) + .map(|n| install_entry(&format!("pkg{n:03}"), "1.0.0")) + .collect(), + ..Default::default() + }; + let tall = ApplyPlan { + path: PathBuf::from("/home/user/.config/soar/packages.toml"), + diff: Some(diff), + system: Vec::new(), + }; + let (mut app, now) = apply_app(tall); + screen(&mut app, 100, 20); + for _ in 0..40 { + app.update(key('j'), now); + } + let screen = screen(&mut app, 100, 20); + assert!(screen.contains("pkg039"), "screen is {screen:?}"); + assert!(!screen.contains("pkg000"), "screen is {screen:?}"); + } + + #[test] + fn a_loaded_plan_puts_the_cursor_back_at_the_top() { + let (mut app, now) = apply_app(apply_plan()); + screen(&mut app, 100, 24); + app.update(key('j'), now); + app.update(key('j'), now); + assert_eq!(app.apply.cursor.selected, 2); + app.update(loaded(apply_plan()), now); + assert_eq!(app.apply.cursor.selected, 0); + } + + #[test] + fn the_view_state_starts_empty() { + let view = ApplyView::default(); + assert!(view.plan.is_idle()); + assert!(!view.prune); + assert_eq!(view.cursor.selected, 0); + } +} diff --git a/crates/soar-tui/src/views/browse.rs b/crates/soar-tui/src/views/browse.rs new file mode 100644 index 00000000..2ccdc21d --- /dev/null +++ b/crates/soar-tui/src/views/browse.rs @@ -0,0 +1,1377 @@ +//! The package catalog view: its table, the filter, and the marks. + +use std::{ + collections::{HashMap, HashSet}, + ops::Range, + time::{Duration, Instant}, +}; + +use nucleo_matcher::{ + Matcher, Utf32String, + pattern::{CaseMatching, Normalization, Pattern}, +}; +use ratatui::{ + Frame, + layout::{Constraint, Layout, Rect}, + style::{Modifier, Style}, + text::{Line, Span}, + widgets::{Block, BorderType, Cell, Row, Table}, +}; +use soar_core::database::models::Package; + +use crate::{ + app::App, + format, + loadable::Loadable, + theme::Theme, + views::ViewId, + widgets::{badge, package_detail, scroll::ListCursor, states, text_input::TextInput}, +}; + +/// Identifies one catalog row across reloads, marks, and the filter. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub(crate) struct PackageKey { + /// The repository the package comes from. + pub(crate) repo_name: String, + /// The package's name inside its repository. + pub(crate) pkg_name: String, + /// The family grouping the package's variants, when it has one. + pub(crate) pkg_family: Option, + /// The package id the repository publishes, when it does. + pub(crate) pkg_id: Option, +} + +impl PackageKey { + /// The exact install query naming this package at `version`, as + /// `family/name@version:repo`, without the family when there is none. + pub(crate) fn query(&self, version: &str) -> String { + match self.pkg_family.as_deref() { + Some(family) => format!("{family}/{}@{version}:{}", self.pkg_name, self.repo_name), + None => format!("{}@{version}:{}", self.pkg_name, self.repo_name), + } + } +} + +/// One package of the catalog, with what the list shows and the filter +/// searches. +#[derive(Clone, Debug)] +pub(crate) struct CatalogRow { + /// What identifies this row across reloads. + pub(crate) key: PackageKey, + /// The newest version the repository publishes. + pub(crate) version: String, + /// The package's kind, such as `static` or `appimage`. + pub(crate) pkg_type: Option, + /// The short summary shown in the detail pane and searched by the + /// filter. + pub(crate) description: String, + /// Whether a version of this package is installed. + pub(crate) installed: bool, + /// The other versions the repository publishes, newest first. The + /// detail pane lists them; the version picker reads them once it + /// lands. + pub(crate) other_versions: Vec, + /// `family/name` or `name`, lowercased once for matching. + pub(crate) haystack: String, +} + +/// How long the cursor must rest on a row before its details load. +const DETAIL_DELAY: Duration = Duration::from_millis(120); + +/// How many packages the detail cache keeps before it starts over. +const DETAIL_CACHE_MAX: usize = 256; + +/// The narrowest terminal that shows the list beside the detail pane. +const SPLIT_WIDTH: u16 = 100; + +/// The state of the catalog view. +#[derive(Debug, Default)] +pub(crate) struct BrowseView { + /// The whole package catalog, loaded at startup and reloaded on + /// request. + pub(crate) catalog: Loadable>, + /// The indexes into the catalog of the rows shown, in display order. + pub(crate) visible: Vec, + /// The visible row the cursor sits on. + pub(crate) cursor: ListCursor, + /// The text the filter matches rows against. + pub(crate) filter: TextInput, + /// Whether the filter holds the keyboard. + pub(crate) filter_focused: bool, + /// The repository the list is narrowed to, when it is. + pub(crate) repo_filter: Option, + /// The rows marked for the next bulk action. + pub(crate) marks: HashSet, + /// The details already fetched, keyed by package. The value stays + /// `None` when the repositories hold no package with that query. + pub(crate) details: HashMap>>, + /// The row waiting for its details to load, with when the cursor + /// arrived on it. + pub(crate) wanted: Option<(PackageKey, Instant)>, + /// The scroll of the detail pane while it fills the screen. + pub(crate) detail: ListCursor, + /// How many rows the detail held at the last render, so scrolling + /// moves over what the pane actually shows. + pub(crate) detail_rows: usize, + /// Whether the detail fills the whole body instead of sitting beside + /// the list. + pub(crate) detail_open: bool, + /// The fuzzy matcher scoring the filter against rows. It allocates on + /// creation, so one instance is reused for every keystroke. + matcher: Matcher, +} + +impl BrowseView { + /// The catalog row the cursor points at, when the list has one. The + /// indexes can be stale right after a reload replaced the catalog, so + /// the lookups tolerate a missing row. + pub(crate) fn cursor_row(&self) -> Option<&CatalogRow> { + let rows = self.catalog.ready()?; + let index = *self.visible.get(self.cursor.selected)?; + rows.get(index) + } + + /// The key of the row the cursor points at, when the list has one. + fn cursor_key(&self) -> Option { + self.cursor_row().map(|row| row.key.clone()) + } + + /// The version of the row a key names, so the detail query can ask + /// for that exact variant. + pub(crate) fn row_version(&self, key: &PackageKey) -> Option { + let rows = self.catalog.ready()?; + rows.iter() + .find(|row| &row.key == key) + .map(|row| row.version.clone()) + } + + /// The catalog row a key names, when the catalog holds it. + pub(crate) fn row(&self, key: &PackageKey) -> Option<&CatalogRow> { + self.catalog.ready()?.iter().find(|row| &row.key == key) + } + + /// Records the row the cursor rests on, so its details start loading + /// once the cursor stays put long enough. + pub(crate) fn note_cursor(&mut self, now: Instant) { + self.wanted = self.cursor_key().map(|key| (key, now)); + } + + /// The detail request whose row the cursor has rested on long enough, + /// if any, marking it loading so it is requested only once. The row's + /// version is resolved here, because the catalog can be mid-reload + /// while the cursor rests: asking then would park the row on a + /// Loading entry no request ever answers, so the want stays put and + /// the next tick retries once the reload has landed. + pub(crate) fn due_detail(&mut self, now: Instant) -> Option { + let (key, rested_at) = self.wanted.clone()?; + if now.duration_since(rested_at) < DETAIL_DELAY { + return None; + } + // The version must resolve now, or the request would go out + // for a variant the mid-reload catalog cannot name yet. + self.row_version(&key)?; + self.wanted = None; + if self.details.contains_key(&key) { + return None; + } + self.cache_detail(key.clone(), Loadable::Loading); + Some(key) + } + + /// Stores one package's details, emptying the cache first when it + /// grew past its bound. + pub(crate) fn cache_detail(&mut self, key: PackageKey, state: Loadable>) { + if self.details.len() > DETAIL_CACHE_MAX { + self.details.clear(); + } + self.details.insert(key, state); + } + + /// Rebuilds the visible rows from the filter text and the repository + /// filter. A query matches names first, then descriptions once it is + /// long enough to be worth scanning them; name matches rank above + /// description matches, and ties order by name. The cursor stays on + /// its package while that row survives the new filter. + pub(crate) fn refilter(&mut self, now: Instant) { + let previous = self.cursor_key(); + let mut ranked: Vec<((u8, i64), usize)> = Vec::new(); + if let Loadable::Ready(rows) = &self.catalog { + let query = self.filter.value().trim(); + let repo = self.repo_filter.as_deref(); + let pattern = (!query.is_empty()) + .then(|| Pattern::parse(query, CaseMatching::Smart, Normalization::Smart)); + match pattern { + None => { + for (index, row) in rows.iter().enumerate() { + if repo.is_none_or(|name| row.key.repo_name == name) { + ranked.push(((0, 0), index)); + } + } + } + Some(pattern) => { + let matcher = &mut self.matcher; + let scan_descriptions = query.len() >= 3; + for (index, row) in rows.iter().enumerate() { + if !repo.is_none_or(|name| row.key.repo_name == name) { + continue; + } + let mut rank = pattern + .score(Utf32String::from(row.haystack.as_str()).slice(..), matcher) + .map(|score| (0u8, -i64::from(score))); + if rank.is_none() && scan_descriptions { + rank = pattern + .score( + Utf32String::from(row.description.as_str()).slice(..), + matcher, + ) + .map(|score| (1u8, -i64::from(score))); + } + if let Some(rank) = rank { + ranked.push((rank, index)); + } + } + ranked.sort_by(|a, b| { + a.0.cmp(&b.0) + .then_with(|| rows[a.1].key.pkg_name.cmp(&rows[b.1].key.pkg_name)) + }); + } + } + } + self.visible = ranked.into_iter().map(|(_, index)| index).collect(); + self.cursor = ListCursor::default(); + if let Some(previous) = previous + && let Loadable::Ready(rows) = &self.catalog + && let Some(position) = self + .visible + .iter() + .position(|&index| rows[index].key == previous) + { + self.cursor.selected = position; + } + self.note_cursor(now); + } + + /// Marks or unmarks the row under the cursor, then moves one row down. + pub(crate) fn toggle_mark(&mut self, now: Instant) { + let Some(index) = self.visible.get(self.cursor.selected).copied() else { + return; + }; + let Some(rows) = self.catalog.ready() else { + return; + }; + let Some(row) = rows.get(index) else { + return; + }; + let key = row.key.clone(); + if !self.marks.remove(&key) { + self.marks.insert(key); + } + self.cursor.down(1, self.visible.len()); + self.note_cursor(now); + } + + /// Moves the repository filter to its next value: no filter first, then + /// each repository in the catalog in name order, then back to no + /// filter. The visible rows are rebuilt with the new value. + pub(crate) fn cycle_repo(&mut self, now: Instant) { + let Loadable::Ready(rows) = &self.catalog else { + return; + }; + let mut repos: Vec<&str> = rows.iter().map(|row| row.key.repo_name.as_str()).collect(); + repos.sort_unstable(); + repos.dedup(); + self.repo_filter = match self.repo_filter.as_deref() { + None => repos.first().map(|name| (*name).to_string()), + Some(current) => { + match repos.iter().position(|name| *name == current) { + Some(position) if position + 1 < repos.len() => { + Some(repos[position + 1].to_string()) + } + _ => None, + } + } + }; + self.refilter(now); + } + + /// The keys the next bulk action works on: every marked row, or the row + /// under the cursor when nothing is marked. Rows marked but hidden by + /// the filters stay in the list, and the install confirm lists them all. + pub(crate) fn selected_keys(&self) -> Vec { + if !self.marks.is_empty() { + let mut keys: Vec = self.marks.iter().cloned().collect(); + keys.sort(); + return keys; + } + self.cursor_key().into_iter().collect() + } + + /// The selected rows as `(key, version)` pairs, each pinning the + /// version its catalog row shows. + pub(crate) fn selected_versions(&self) -> Vec<(PackageKey, String)> { + self.selected_keys() + .into_iter() + .filter_map(|key| { + let version = self.row_version(&key)?; + Some((key, version)) + }) + .collect() + } +} + +/// Draws the catalog view: the list pane, and beside it the detail pane +/// of the row under the cursor, or the detail alone while it fills the +/// screen. +pub(crate) fn render(f: &mut Frame, area: Rect, app: &mut App) { + if app.browse.detail_open { + package_detail::render(f, area, app, true); + return; + } + if area.width >= SPLIT_WIDTH { + let [list, detail] = + Layout::horizontal([Constraint::Percentage(55), Constraint::Percentage(45)]) + .areas(area); + render_list(f, list, app, area.width); + package_detail::render(f, detail, app, false); + } else { + render_list(f, area, app, area.width); + } +} + +/// Draws the catalog pane: its border with the counts and the filter in the +/// title, then the table of visible rows or the loading, error, and empty +/// states. The column layout follows the full terminal width, whatever the +/// list shares it with. +fn render_list(f: &mut Frame, area: Rect, app: &mut App, full_width: u16) { + let theme = &app.theme; + let rows_height = usize::from(area.height.saturating_sub(3)); + let window = match &app.browse.catalog { + Loadable::Ready(_) => { + app.browse + .cursor + .window(app.browse.visible.len(), rows_height) + } + _ => 0..0, + }; + let block = list_block(&app.browse, theme, area.width); + let inner = block.inner(area); + f.render_widget(block, area); + let view = &app.browse; + match &view.catalog { + Loadable::Idle => {} + Loadable::Loading => states::loading(f, inner, theme, app.frame, "Loading packages"), + Loadable::Failed(error) => states::error(f, inner, theme, error), + Loadable::Ready(rows) if rows.is_empty() => { + states::empty( + f, + inner, + theme, + "No packages. Add or enable a repository in Repos (5).", + ) + } + Loadable::Ready(rows) if view.visible.is_empty() => { + states::empty( + f, + inner, + theme, + &format!("No packages match {}", view.filter.value()), + ) + } + Loadable::Ready(rows) => { + let (columns, constraints) = columns(full_width); + let name_width = usize::from(name_column_width(area.width, &constraints)); + let offset = window.start; + let table = Table::new( + table_rows(view, rows, window, &columns, name_width, theme), + constraints, + ) + .header(header_row(&columns, theme)); + app.layout.list = Some((rows_area(inner), offset)); + f.render_widget(table, inner); + } + } +} + +/// The rows area of a table pane: its header row takes the first line of +/// the pane's inner area, and the window range maps onto what is left. +fn rows_area(inner: Rect) -> Rect { + Rect { + y: inner.y.saturating_add(1), + height: inner.height.saturating_sub(1), + ..inner + } +} + +/// The columns the table shows at one terminal width. The type badge +/// leaves on narrow terminals and the repository column on very narrow +/// ones; the full terminal width decides, whatever the list shares it +/// with. +fn columns(width: u16) -> (Columns, Vec) { + let every = ( + Columns { + repo: true, + kind: true, + }, + vec![ + Constraint::Length(2), + Constraint::Fill(1), + Constraint::Length(14), + Constraint::Length(12), + Constraint::Length(10), + ], + ); + let no_kind = ( + Columns { + repo: true, + kind: false, + }, + vec![ + Constraint::Length(2), + Constraint::Fill(1), + Constraint::Length(14), + Constraint::Length(12), + ], + ); + let no_repo = ( + Columns { + repo: false, + kind: false, + }, + vec![ + Constraint::Length(2), + Constraint::Fill(1), + Constraint::Length(14), + ], + ); + if width < 70 { + no_repo + } else if width < 80 { + no_kind + } else { + every + } +} + +/// Which optional columns the table shows. +#[derive(Clone, Copy)] +struct Columns { + /// The repository column. + repo: bool, + /// The package type column. + kind: bool, +} + +/// The width the name column gets: everything the fixed columns and the +/// spacing between them leave over. +fn name_column_width(width: u16, constraints: &[Constraint]) -> u16 { + let fixed: u16 = constraints + .iter() + .map(|constraint| { + match constraint { + Constraint::Length(n) => *n, + _ => 0, + } + }) + .sum(); + let spacing = constraints.len().saturating_sub(1) as u16; + width.saturating_sub(2).saturating_sub(fixed + spacing) +} + +/// The column labels in muted bold. +fn header_row(columns: &Columns, theme: &Theme) -> Row<'static> { + let mut labels = vec!["", "NAME", "VERSION"]; + if columns.repo { + labels.push("REPO"); + } + if columns.kind { + labels.push("TYPE"); + } + Row::new(labels).style(theme.muted().add_modifier(Modifier::BOLD)) +} + +/// Builds the rows the window shows: the mark, the family and name, the +/// version, and the repository and type badge when their columns exist. +fn table_rows( + view: &BrowseView, + rows: &[CatalogRow], + window: Range, + columns: &Columns, + name_width: usize, + theme: &Theme, +) -> Vec> { + let shown = &view.visible[window.clone()]; + window + .zip(shown.iter()) + .map(|(position, &index)| { + let row = &rows[index]; + list_row( + row, + view.marks.contains(&row.key), + position == view.cursor.selected, + columns, + name_width, + theme, + ) + }) + .collect() +} + +/// One table row. The cursor row takes the cursor highlight across its +/// whole width and starts with the cursor symbol; a marked row starts with +/// the marked symbol. +fn list_row( + row: &CatalogRow, + marked: bool, + cursor_here: bool, + columns: &Columns, + name_width: usize, + theme: &Theme, +) -> Row<'static> { + let symbols = theme.sym(); + let lead = if cursor_here { + Span::styled(symbols.cursor.to_string(), theme.cursor_row()) + } else if marked { + Span::styled(symbols.marked.to_string(), theme.marked()) + } else { + Span::raw(" ") + }; + let mut cells = vec![ + Cell::from(Line::from(vec![lead, Span::raw(" ")])), + name_cell(row, theme, name_width), + Cell::from(Span::styled(row.version.clone(), theme.accent2())), + ]; + if columns.repo { + cells.push(Cell::from(Span::styled( + row.key.repo_name.clone(), + theme.info(), + ))); + } + if columns.kind { + cells.push(Cell::from(badge::pkg_type(row.pkg_type.as_deref(), theme))); + } + let style = if cursor_here { + theme.cursor_row() + } else { + Style::new() + }; + Row::new(cells).style(style) +} + +/// The name cell: `family/` before the name in the family color, with the +/// installed mark at the right edge of the cell for installed packages. +fn name_cell(row: &CatalogRow, theme: &Theme, width: usize) -> Cell<'static> { + let mut full = String::new(); + let mut family_chars = 0; + if let Some(family) = row.key.pkg_family.as_deref() { + full.push_str(family); + full.push('/'); + family_chars = full.chars().count(); + } + full.push_str(&row.key.pkg_name); + let symbols = theme.sym(); + let mark_width = Span::raw(symbols.installed).width(); + let reserved = usize::from(row.installed) * (1 + mark_width); + let text = format::truncate(&full, width.saturating_sub(reserved), symbols.ellipsis); + let mut spans: Vec> = Vec::new(); + if family_chars > 0 { + let boundary = text + .char_indices() + .nth(family_chars) + .map_or(text.len(), |(at, _)| at); + spans.push(Span::styled(text[..boundary].to_string(), theme.accent2())); + spans.push(Span::styled(text[boundary..].to_string(), theme.text())); + } else { + spans.push(Span::styled(text, theme.text())); + } + if row.installed { + let used = spans.iter().map(Span::width).sum::(); + let pad = width.saturating_sub(used + mark_width); + spans.push(Span::raw(" ".repeat(pad))); + spans.push(badge::installed(theme)); + } + Cell::from(Line::from(spans)) +} + +/// The pane border: the package count on the left of the top edge and the +/// filter and repository filter on its right. +fn list_block(view: &BrowseView, theme: &Theme, width: u16) -> Block<'static> { + let left = match view.catalog.ready() { + Some(rows) => { + let filtered = !view.filter.value().trim().is_empty() || view.repo_filter.is_some(); + let count = if filtered { + format!( + "Packages {} of {}", + format::thousands(view.visible.len()), + format::thousands(rows.len()) + ) + } else { + format!("Packages {}", format::thousands(rows.len())) + }; + Line::styled(format!(" {count} "), theme.title()) + } + None => Line::styled(format!(" {} ", ViewId::Browse.title()), theme.title()), + }; + let budget = usize::from(width).saturating_sub(2 + left.width()); + let block = Block::bordered() + .border_type(BorderType::Rounded) + .border_style(theme.border(true)) + .title(left); + if budget > 0 { + block.title_top(right_title(view, theme, budget).right_aligned()) + } else { + block + } +} + +/// The right end of the top border: the filter text while it is being +/// typed or holds one, then the repository filter, cut to `budget` cells +/// so it never reaches the title on the left. +fn right_title(view: &BrowseView, theme: &Theme, budget: usize) -> Line<'static> { + let mut spans: Vec> = Vec::new(); + let show_filter = !view.filter.is_empty() || view.filter_focused; + let repo = view + .repo_filter + .as_deref() + .map(|name| format!("repo: {name}")); + let repo_width = repo.as_deref().map_or(0, |text| Span::raw(text).width()); + let gap = usize::from(show_filter && repo.is_some()); + if show_filter { + let room = budget.saturating_sub(2).saturating_sub(gap + repo_width); + spans.push(Span::styled("/ ".to_string(), theme.muted())); + spans.extend(view.filter.line(view.filter_focused, room, theme).spans); + } + if let Some(text) = repo { + if show_filter { + spans.push(Span::raw(" ")); + } + spans.push(Span::styled(text, theme.muted())); + } + if !spans.is_empty() { + spans.insert(0, Span::raw(" ")); + spans.push(Span::raw(" ")); + } + let mut shown: Vec> = Vec::new(); + let mut used = 0; + for span in spans { + let width = span.width(); + if used + width > budget { + break; + } + used += width; + shown.push(span); + } + Line::from(shown) +} + +#[cfg(test)] +mod tests { + use std::time::{Duration, Instant}; + + use ratatui::crossterm::event::KeyCode; + use soar_core::database::models::Package; + + use crate::{ + action::Action, + effect::Effect, + jobs::{InstallChoices, JobOutcome, JobSpec}, + loadable::Loadable, + msg::{Loaded, Msg}, + test_support::{catalog_row, code, key, package, screen, test_app}, + views::browse::{BrowseView, CatalogRow, PackageKey}, + }; + + /// A catalog reply for the load the app still expects before any + /// reload has started. + fn loaded(rows: Vec) -> Msg { + Msg::Loaded(Loaded::Catalog { + check: 0, + result: Ok(rows), + }) + } + + fn catalog() -> Vec { + vec![ + catalog_row("bat", "0.24.0", "bincache"), + catalog_row("fd", "10.2.0", "pkgforge"), + catalog_row("jq", "1.7.1", "bincache"), + ] + } + + fn key_for(name: &str, repo: &str) -> PackageKey { + PackageKey { + repo_name: repo.to_string(), + pkg_name: name.to_string(), + pkg_family: None, + pkg_id: None, + } + } + + fn bat_key() -> PackageKey { + key_for("bat", "bincache") + } + + #[test] + fn the_exact_query_names_family_name_version_and_repo() { + let mut key = key_for("ffmpeg", "bincache"); + key.pkg_family = Some("jellyfin".to_string()); + assert_eq!(key.query("7.1"), "jellyfin/ffmpeg@7.1:bincache"); + assert_eq!( + key_for("bat", "bincache").query("0.24.0"), + "bat@0.24.0:bincache" + ); + } + + fn detail(key: PackageKey, result: Result, String>) -> Msg { + Msg::Loaded(Loaded::Detail { + key, + result: Box::new(result), + }) + } + + #[test] + fn a_loaded_catalog_renders_every_name() { + let mut app = test_app(); + app.update(loaded(catalog()), Instant::now()); + let screen = screen(&mut app, 80, 24); + assert!(screen.contains("bat"), "screen is {screen:?}"); + assert!(screen.contains("fd"), "screen is {screen:?}"); + assert!(screen.contains("jq"), "screen is {screen:?}"); + } + + #[test] + fn a_failed_catalog_shows_the_error() { + let mut app = test_app(); + app.update( + Msg::Loaded(Loaded::Catalog { + check: 0, + result: Err("metadata unreadable".to_string()), + }), + Instant::now(), + ); + let screen = screen(&mut app, 80, 24); + assert!( + screen.contains("metadata unreadable"), + "screen is {screen:?}" + ); + } + + #[test] + fn an_empty_catalog_says_where_to_add_repositories() { + let mut app = test_app(); + app.update(loaded(Vec::new()), Instant::now()); + let screen = screen(&mut app, 80, 24); + assert!( + screen.contains("No packages. Add or enable a repository in Repos (5)."), + "screen is {screen:?}" + ); + } + + #[test] + fn a_loading_catalog_shows_the_spinner_line() { + let mut app = test_app(); + app.startup(); + assert!(screen(&mut app, 80, 24).contains("Loading packages")); + } + + #[test] + fn more_rows_than_screen_lines_render_only_the_visible_ones() { + let mut app = test_app(); + let rows: Vec<_> = (0..50) + .map(|n| catalog_row(&format!("pkg{n}"), "1.0.0", "bincache")) + .collect(); + app.update(loaded(rows), Instant::now()); + let screen = screen(&mut app, 80, 24); + assert!(screen.contains("pkg0"), "screen is {screen:?}"); + assert!(screen.contains("pkg15"), "screen is {screen:?}"); + assert!(!screen.contains("pkg40"), "screen is {screen:?}"); + } + + #[test] + fn the_header_names_its_columns() { + let mut app = test_app(); + app.update(loaded(catalog()), Instant::now()); + let screen = screen(&mut app, 80, 24); + for label in ["NAME", "VERSION", "REPO", "TYPE"] { + assert!(screen.contains(label), "screen is {screen:?}"); + } + } + + #[test] + fn moving_the_cursor_down_scrolls_the_window_with_it() { + let mut app = test_app(); + let rows: Vec<_> = (0..50) + .map(|n| catalog_row(&format!("pkg{n}"), "1.0.0", "bincache")) + .collect(); + app.update(loaded(rows), Instant::now()); + let now = Instant::now(); + for _ in 0..40 { + app.update(key('j'), now); + } + let screen = screen(&mut app, 100, 30); + assert!(screen.contains("pkg40"), "screen is {screen:?}"); + assert!(!screen.contains("pkg0"), "screen is {screen:?}"); + } + + #[test] + fn the_title_shows_the_total_count() { + let mut app = test_app(); + app.update(loaded(catalog()), Instant::now()); + assert!(screen(&mut app, 80, 24).contains("Packages 3")); + } + + #[test] + fn the_title_shows_the_filtered_count() { + let mut app = test_app(); + app.update(loaded(catalog()), Instant::now()); + let now = Instant::now(); + app.update(key('/'), now); + app.update(key('b'), now); + let screen = screen(&mut app, 80, 24); + assert!(screen.contains("Packages 1 of 3"), "screen is {screen:?}"); + assert!(screen.contains("/ b"), "screen is {screen:?}"); + } + + #[test] + fn narrow_terminals_drop_the_type_then_the_repo_column() { + let mut app = test_app(); + app.update(loaded(catalog()), Instant::now()); + let mid = screen(&mut app, 79, 20); + assert!(mid.contains("REPO"), "screen is {mid:?}"); + assert!(!mid.contains("TYPE"), "screen is {mid:?}"); + let narrow = screen(&mut app, 69, 20); + assert!(!narrow.contains("REPO"), "screen is {narrow:?}"); + assert!(!narrow.contains("TYPE"), "screen is {narrow:?}"); + } + + #[test] + fn marked_and_installed_rows_show_their_symbols() { + let mut app = test_app(); + let mut rows = catalog(); + rows[1].installed = true; + app.update(loaded(rows), Instant::now()); + let now = Instant::now(); + app.update(key(' '), now); + let screen = screen(&mut app, 80, 24); + assert!(screen.contains("●"), "screen is {screen:?}"); + assert!(screen.contains("✓"), "screen is {screen:?}"); + assert!(screen.contains("1 marked"), "screen is {screen:?}"); + } + + #[test] + fn the_type_badge_renders() { + let mut app = test_app(); + let mut rows = catalog(); + rows[0].pkg_type = Some("appimage".to_string()); + app.update(loaded(rows), Instant::now()); + assert!(screen(&mut app, 80, 24).contains("appimage")); + } + + #[test] + fn typing_while_the_filter_holds_focus_reaches_the_filter_only() { + let mut app = test_app(); + app.update(loaded(catalog()), Instant::now()); + let now = Instant::now(); + app.update(key('/'), now); + app.update(key('q'), now); + assert!(!app.quit); + assert!(app.browse.filter_focused); + assert_eq!(app.browse.filter.value(), "q"); + } + + #[test] + fn enter_keeps_the_filter_and_esc_clears_it() { + let mut app = test_app(); + app.update(loaded(catalog()), Instant::now()); + let now = Instant::now(); + app.update(key('/'), now); + for c in ['b', 'a'] { + app.update(key(c), now); + } + assert_eq!(app.browse.visible, vec![0]); + app.update(code(KeyCode::Enter), now); + assert!(!app.browse.filter_focused); + assert_eq!(app.browse.filter.value(), "ba"); + assert_eq!(app.browse.visible, vec![0]); + app.update(code(KeyCode::Esc), now); + assert!(!app.browse.filter_focused); + assert!(app.browse.filter.value().is_empty()); + assert_eq!(app.browse.visible, vec![0, 1, 2]); + } + + #[test] + fn a_three_character_query_ranks_name_matches_above_description_matches() { + let mut app = test_app(); + let mut rows = catalog(); + rows[1].key.pkg_name = "mole".to_string(); + rows[1].haystack = "mole".to_string(); + rows[1].description = "a bat with poor eyesight".to_string(); + app.update(loaded(rows), Instant::now()); + let now = Instant::now(); + app.update(key('/'), now); + for c in ['b', 'a', 't'] { + app.update(key(c), now); + } + assert_eq!(app.browse.visible, vec![0, 1]); + } + + #[test] + fn a_two_character_query_skips_the_descriptions() { + let mut app = test_app(); + let mut rows = catalog(); + rows[1].key.pkg_name = "mole".to_string(); + rows[1].haystack = "mole".to_string(); + rows[1].description = "a bat with poor eyesight".to_string(); + app.update(loaded(rows), Instant::now()); + let now = Instant::now(); + app.update(key('/'), now); + for c in ['b', 't'] { + app.update(key(c), now); + } + assert_eq!(app.browse.visible, vec![0]); + } + + #[test] + fn a_filter_matching_nothing_shows_the_empty_text() { + let mut app = test_app(); + app.update(loaded(catalog()), Instant::now()); + let now = Instant::now(); + app.update(key('/'), now); + for c in ['x', 'y', 'z'] { + app.update(key(c), now); + } + let screen = screen(&mut app, 80, 24); + assert!( + screen.contains("No packages match xyz"), + "screen is {screen:?}" + ); + } + + #[test] + fn refiltering_keeps_the_cursor_on_its_package_while_it_is_visible() { + let mut app = test_app(); + let rows = vec![ + catalog_row("ant", "1.0", "bincache"), + catalog_row("bat", "1.0", "bincache"), + catalog_row("cat", "1.0", "bincache"), + ]; + app.update(loaded(rows), Instant::now()); + let now = Instant::now(); + app.update(key('j'), now); + assert_eq!(app.browse.cursor.selected, 1); + app.update(key('/'), now); + for c in ['b', 'a'] { + app.update(key(c), now); + } + assert_eq!(app.browse.visible, vec![1]); + assert_eq!(app.browse.cursor.selected, 0); + for c in ['x', 'y'] { + app.update(key(c), now); + } + assert!(app.browse.visible.is_empty()); + assert_eq!(app.browse.cursor.selected, 0); + } + + #[test] + fn marking_two_rows_then_hiding_one_keeps_both_selected() { + let mut app = test_app(); + let rows = vec![ + catalog_row("red", "1.0", "bincache"), + catalog_row("green", "1.0", "bincache"), + catalog_row("blue", "1.0", "bincache"), + ]; + app.update(loaded(rows), Instant::now()); + let now = Instant::now(); + app.update(key(' '), now); + app.update(key(' '), now); + assert_eq!(app.browse.marks.len(), 2); + app.update(key('/'), now); + for c in ['b', 'l'] { + app.update(key(c), now); + } + assert_eq!(app.browse.visible, vec![2]); + let keys = app.browse.selected_keys(); + assert_eq!(keys.len(), 2); + let red = PackageKey { + repo_name: "bincache".to_string(), + pkg_name: "red".to_string(), + pkg_family: None, + pkg_id: None, + }; + let green = PackageKey { + repo_name: "bincache".to_string(), + pkg_name: "green".to_string(), + pkg_family: None, + pkg_id: None, + }; + assert!(keys.contains(&red)); + assert!(keys.contains(&green)); + } + + #[test] + fn a_reload_onto_a_smaller_catalog_keeps_the_state_valid() { + let mut app = test_app(); + let rows: Vec<_> = (0..50) + .map(|n| catalog_row(&format!("pkg{n}"), "1.0.0", "bincache")) + .collect(); + app.update(loaded(rows), Instant::now()); + let now = Instant::now(); + for _ in 0..40 { + app.update(key('j'), now); + } + app.update(key(' '), now); + app.update(loaded(vec![catalog_row("bat", "1.0", "bincache")]), now); + assert_eq!(app.browse.visible, vec![0]); + assert_eq!(app.browse.cursor.selected, 0); + assert_eq!(app.browse.marks.len(), 1); + assert_eq!(app.browse.selected_keys().len(), 1); + app.update(key(' '), now); + assert_eq!(app.browse.marks.len(), 2); + } + + #[test] + fn a_second_esc_clears_the_marks() { + let mut app = test_app(); + app.update(loaded(catalog()), Instant::now()); + let now = Instant::now(); + app.update(key(' '), now); + assert_eq!(app.browse.marks.len(), 1); + app.update(key('/'), now); + app.update(key('b'), now); + app.update(code(KeyCode::Esc), now); + assert!(app.browse.filter.value().is_empty()); + assert_eq!(app.browse.marks.len(), 1); + app.update(code(KeyCode::Esc), now); + assert!(app.browse.marks.is_empty()); + } + + #[test] + fn cycling_the_repo_filter_walks_every_repository_and_back() { + let mut app = test_app(); + app.update(loaded(catalog()), Instant::now()); + let now = Instant::now(); + assert_eq!( + app.hint_suffix(&Action::CycleRepo), + Some(": all".to_string()) + ); + assert!(screen(&mut app, 100, 24).contains("repo: all")); + app.update(key('R'), now); + assert_eq!(app.browse.repo_filter.as_deref(), Some("bincache")); + assert_eq!(app.browse.visible, vec![0, 2]); + assert_eq!( + app.hint_suffix(&Action::CycleRepo), + Some(": bincache".to_string()) + ); + app.update(key('R'), now); + assert_eq!(app.browse.repo_filter.as_deref(), Some("pkgforge")); + assert_eq!(app.browse.visible, vec![1]); + app.update(key('R'), now); + assert_eq!(app.browse.repo_filter, None); + assert_eq!(app.browse.visible, vec![0, 1, 2]); + } + + #[test] + fn escape_clears_the_repo_filter() { + let mut app = test_app(); + app.update(loaded(catalog()), Instant::now()); + let now = Instant::now(); + app.update(key('R'), now); + assert_eq!(app.browse.repo_filter.as_deref(), Some("bincache")); + app.update(code(KeyCode::Esc), now); + assert_eq!(app.browse.repo_filter, None); + assert_eq!(app.browse.visible, vec![0, 1, 2]); + } + + #[test] + fn the_filter_and_the_repo_filter_both_narrow_the_list() { + let mut app = test_app(); + app.update(loaded(catalog()), Instant::now()); + let now = Instant::now(); + app.update(key('R'), now); + app.update(key('R'), now); + assert_eq!(app.browse.repo_filter.as_deref(), Some("pkgforge")); + app.update(key('/'), now); + app.update(key('f'), now); + assert_eq!(app.browse.visible, vec![1]); + assert_eq!( + app.hint_suffix(&Action::CycleRepo), + Some(": pkgforge".to_string()) + ); + } + + /// Times 20 filter passes over a catalog of 10,000 rows and asserts the + /// average stays under 15 ms, so matching on every keystroke never + /// lags. The numbers are only meaningful without debug assertions, so + /// run it with `cargo test --release -- --ignored`. + #[test] + #[ignore] + fn refiltering_ten_thousand_rows_stays_fast() { + let mut view = BrowseView::default(); + let rows: Vec<_> = (0..10_000) + .map(|n| { + let mut row = catalog_row(&format!("package-{n}"), "1.0.0", "bincache"); + row.description = format!("a test package with the number {n} in it"); + row + }) + .collect(); + view.catalog = Loadable::Ready(rows); + view.refilter(Instant::now()); + view.filter.set("ab".to_string()); + let start = Instant::now(); + for _ in 0..20 { + view.refilter(Instant::now()); + } + let average = start.elapsed() / 20; + assert!( + average < Duration::from_millis(15), + "average refilter took {average:?}" + ); + } + + #[test] + fn a_resting_cursor_requests_its_details_after_the_delay() { + let mut app = test_app(); + app.update(loaded(catalog()), Instant::now()); + let now = Instant::now(); + app.update(key('j'), now); + let effects = app.update(Msg::Tick, now + Duration::from_millis(50)); + assert!(effects.is_empty()); + assert!(app.browse.details.is_empty()); + let effects = app.update(Msg::Tick, now + Duration::from_millis(130)); + assert_eq!(effects.len(), 1); + assert!(matches!( + &effects[0], + Effect::LoadDetail { + key, + version, + } if key.pkg_name == "fd" && version == "10.2.0" + )); + assert!(matches!( + app.browse.details.get(&key_for("fd", "pkgforge")), + Some(Loadable::Loading) + )); + } + + #[test] + fn a_detail_request_waits_for_a_mid_reload_catalog() { + let mut app = test_app(); + app.startup(); + let now = Instant::now(); + let key = bat_key(); + app.browse.wanted = Some((key.clone(), now)); + let effects = app.update(Msg::Tick, now + Duration::from_millis(200)); + assert!(effects.is_empty()); + assert!(app.browse.details.is_empty(), "nothing is cached yet"); + assert!(app.browse.wanted.is_some(), "the want stays for a retry"); + app.update( + Msg::Loaded(Loaded::Catalog { + check: app.catalog_load, + result: Ok(catalog()), + }), + now, + ); + let effects = app.update(Msg::Tick, now + Duration::from_millis(200)); + assert!(matches!( + &effects[..], + [Effect::LoadDetail { + key, + version, + }] if key.pkg_name == "bat" && version == "0.24.0" + )); + assert!(matches!( + app.browse.details.get(&bat_key()), + Some(Loadable::Loading) + )); + } + + #[test] + fn an_arrived_detail_is_cached_and_rendered_in_the_pane() { + let mut app = test_app(); + let mut rows = catalog(); + rows[1].description = "A descendant of the unix fortune program".to_string(); + app.update(loaded(rows), Instant::now()); + let now = Instant::now(); + app.update(key('j'), now); + let key = key_for("fd", "pkgforge"); + let mut fd = package("fd", "10.2.0", "pkgforge"); + fd.homepages = Some(vec!["https://github.com/sharkdp/fd".to_string()]); + app.update(detail(key.clone(), Ok(Some(fd))), now); + assert!(matches!( + app.browse.details.get(&key), + Some(Loadable::Ready(Some(_))) + )); + let screen = screen(&mut app, 100, 24); + assert!( + screen.contains("A descendant of the unix fortune program"), + "screen is {screen:?}" + ); + assert!( + screen.contains("https://github.com/sharkdp/fd"), + "screen is {screen:?}" + ); + } + + #[test] + fn a_failed_detail_shows_the_error_state() { + let mut app = test_app(); + app.update(loaded(catalog()), Instant::now()); + app.update( + detail(bat_key(), Err("metadata locked".to_string())), + Instant::now(), + ); + let screen = screen(&mut app, 100, 24); + assert!(screen.contains("metadata locked"), "screen is {screen:?}"); + } + + #[test] + fn a_detail_query_that_finds_nothing_renders_not_found() { + let mut app = test_app(); + app.update(loaded(catalog()), Instant::now()); + app.update(detail(bat_key(), Ok(None)), Instant::now()); + let screen = screen(&mut app, 100, 24); + assert!(screen.contains("not found"), "screen is {screen:?}"); + } + + #[test] + fn an_install_job_clears_the_cached_details_but_a_sync_keeps_them() { + let mut app = test_app(); + app.update(loaded(catalog()), Instant::now()); + app.update( + detail(bat_key(), Ok(Some(package("bat", "0.24.0", "bincache")))), + Instant::now(), + ); + assert_eq!(app.browse.details.len(), 1); + let now = Instant::now(); + app.enqueue( + JobSpec::Install { + targets: Vec::new(), + picked: vec![package("bat", "0.24.0", "bincache")], + options: InstallChoices::default(), + }, + now, + ); + app.update( + Msg::JobFinished { + id: 0, + outcome: JobOutcome { + ok: true, + aborted: false, + headline: "Installed bat 0.24.0".to_string(), + lines: Vec::new(), + }, + }, + now, + ); + assert!(app.browse.details.is_empty()); + app.update( + detail(bat_key(), Ok(Some(package("bat", "0.24.0", "bincache")))), + now, + ); + app.enqueue(JobSpec::Sync, now); + app.update( + Msg::JobFinished { + id: 1, + outcome: JobOutcome { + ok: true, + aborted: false, + headline: "Repositories synced".to_string(), + lines: Vec::new(), + }, + }, + now, + ); + assert_eq!(app.browse.details.len(), 1); + } + + #[test] + fn the_cache_clears_itself_once_it_exceeds_its_bound() { + let mut app = test_app(); + app.update(loaded(catalog()), Instant::now()); + for n in 0..257 { + let key = PackageKey { + repo_name: "bincache".to_string(), + pkg_name: format!("pkg{n}"), + pkg_family: None, + pkg_id: None, + }; + app.browse.details.insert(key, Loadable::Ready(None)); + } + assert_eq!(app.browse.details.len(), 257); + app.update( + detail(bat_key(), Ok(Some(package("bat", "0.24.0", "bincache")))), + Instant::now(), + ); + assert_eq!(app.browse.details.len(), 1); + } + + #[test] + fn enter_opens_the_full_screen_detail_and_esc_closes_it() { + let mut app = test_app(); + app.update(loaded(catalog()), Instant::now()); + let now = Instant::now(); + app.update(code(KeyCode::Enter), now); + assert!(app.browse.detail_open); + let open = screen(&mut app, 80, 24); + assert!(open.contains("bat"), "screen is {open:?}"); + assert!(!open.contains("NAME"), "screen is {open:?}"); + app.update(code(KeyCode::Esc), now); + assert!(!app.browse.detail_open); + let closed = screen(&mut app, 80, 24); + assert!(closed.contains("NAME"), "screen is {closed:?}"); + } + + #[test] + fn marking_still_works_while_the_detail_is_full_screen() { + let mut app = test_app(); + app.update(loaded(catalog()), Instant::now()); + let now = Instant::now(); + app.update(code(KeyCode::Enter), now); + app.update(key(' '), now); + assert!(app.browse.detail_open); + assert_eq!(app.browse.marks.len(), 1); + } + + #[test] + fn the_full_screen_detail_scrolls_with_the_cursor_keys() { + let mut app = test_app(); + let mut rows = catalog(); + rows[0].description = "lorem ipsum dolor sit amet ".repeat(80); + app.update(loaded(rows), Instant::now()); + let now = Instant::now(); + app.update(code(KeyCode::Enter), now); + assert!(screen(&mut app, 80, 24).contains("0.24.0")); + assert!(app.browse.detail_rows > 20); + app.update(key('G'), now); + assert_eq!(app.browse.detail.selected, app.browse.detail_rows - 1); + assert!(!screen(&mut app, 80, 24).contains("0.24.0")); + app.update(key('g'), now); + assert!(screen(&mut app, 80, 24).contains("0.24.0")); + } + + /// A catalog ten thousand rows long must still draw instantly: the + /// window builds only the visible rows, so the frame cost cannot grow + /// with the catalog. Timings are only meaningful in release mode, so + /// the test carries `ignore` and runs through + /// `cargo test -p soar-tui --release -- --ignored`. + #[test] + #[ignore] + fn a_ten_thousand_row_catalog_draws_under_five_milliseconds() { + let rows: Vec = (0..10_000) + .map(|n| catalog_row(&format!("pkg{n}"), "1.0.0", "bincache")) + .collect(); + let mut app = test_app(); + app.update(loaded(rows), Instant::now()); + let mut terminal = + ratatui::Terminal::new(ratatui::backend::TestBackend::new(200, 60)).unwrap(); + terminal.draw(|f| crate::ui::render(f, &mut app)).unwrap(); + let start = Instant::now(); + for _ in 0..100 { + terminal.draw(|f| crate::ui::render(f, &mut app)).unwrap(); + } + let average = start.elapsed() / 100; + println!("average frame: {average:?}"); + assert!( + average < Duration::from_millis(5), + "average frame was {average:?}" + ); + } +} diff --git a/crates/soar-tui/src/views/health.rs b/crates/soar-tui/src/views/health.rs new file mode 100644 index 00000000..ce8474c9 --- /dev/null +++ b/crates/soar-tui/src/views/health.rs @@ -0,0 +1,647 @@ +//! The health view: whether PATH, MANPATH, packages, and symlinks are in +//! order, and where soar keeps its files. + +use std::{ops::Range, path::PathBuf}; + +use ratatui::{ + Frame, + layout::{Constraint, Layout, Rect}, + style::{Modifier, Style}, + text::{Line, Span}, + widgets::{Block, BorderType, Paragraph}, +}; +use soar_operations::{BrokenPackage, HealthReport}; + +use crate::{ + action::Action, + app::App, + format, keymap, + loadable::Loadable, + theme::Theme, + views::ViewId, + widgets::{scroll::ListCursor, states}, +}; + +/// The width of a check's label column. +const LABEL_WIDTH: usize = 10; + +/// The width of a path's label column. +const PATH_LABEL_WIDTH: usize = 16; + +/// How far the check rows and the rows under them are indented: the +/// symbol, its space, the label, and its space. +const INDENT_WIDTH: usize = LABEL_WIDTH + 3; + +/// How many broken symlink paths show before the rest fold into a count. +const VISIBLE_SYMLINKS: usize = 5; + +/// The narrowest terminal that shows the checks beside the paths. +const SIDE_BY_SIDE_WIDTH: u16 = 100; + +/// The state of the health view. +#[derive(Default)] +pub(crate) struct HealthView { + /// The health report and the paths it names, loaded on the first visit + /// and again after every job that changes what the checks report on. + pub(crate) report: Loadable<(HealthReport, Vec<(String, PathBuf)>)>, + /// The row of the paths pane the cursor sits on. + pub(crate) cursor: ListCursor, +} + +impl HealthView { + /// Starts a fresh load. The last report goes when the new one arrives. + pub(crate) fn start(&mut self) { + self.report = Loadable::Loading; + } + + /// Adopts a finished load. The cursor clamps to the paths list. + pub(crate) fn loaded( + &mut self, + result: Result<(HealthReport, Vec<(String, PathBuf)>), String>, + ) { + self.report = match result { + Ok(data) => Loadable::Ready(data), + Err(error) => Loadable::Failed(error), + }; + self.cursor.clamp(self.paths_len()); + } + + /// The number of rows in the paths list, zero while it loads. + pub(crate) fn paths_len(&self) -> usize { + self.report.ready().map_or(0, |(_, paths)| paths.len()) + } +} + +/// Draws the health view: the checks and the paths side by side, stacked +/// under the width where they stop fitting beside each other. +pub(crate) fn render(f: &mut Frame, area: Rect, app: &mut App) { + let (health_area, paths_area) = if area.width >= SIDE_BY_SIDE_WIDTH { + let [health, paths] = + Layout::horizontal([Constraint::Percentage(55), Constraint::Percentage(45)]) + .areas(area); + (health, paths) + } else { + let [health, paths] = + Layout::vertical([Constraint::Percentage(50), Constraint::Percentage(50)]).areas(area); + (health, paths) + }; + let rows_height = usize::from(paths_area.height.saturating_sub(2)); + let window = app + .health + .cursor + .window(app.health.paths_len(), rows_height); + render_checks(f, health_area, app); + render_paths(f, paths_area, app, window); +} + +/// Draws the checks pane: its border, then the rows the report describes, +/// or the loading and error states while the report is not there. +fn render_checks(f: &mut Frame, area: Rect, app: &App) { + let block = pane_block(ViewId::Health.title(), &app.theme); + let inner = block.inner(area); + f.render_widget(block, area); + let theme = &app.theme; + let Some((report, _)) = app.health.report.ready() else { + match &app.health.report { + Loadable::Loading => states::loading(f, inner, theme, app.frame, "Checking health"), + Loadable::Failed(error) => states::error(f, inner, theme, error), + Loadable::Idle | Loadable::Ready(_) => {} + } + return; + }; + let width = usize::from(inner.width); + f.render_widget(Paragraph::new(check_lines(report, width, theme)), inner); +} + +/// Draws the paths pane: its border, then the window of paths the cursor +/// points into. +fn render_paths(f: &mut Frame, area: Rect, app: &mut App, window: Range) { + let block = pane_block("Paths", &app.theme); + let inner = block.inner(area); + f.render_widget(block, area); + let Some((_, paths)) = app.health.report.ready() else { + return; + }; + let width = usize::from(inner.width); + let offset = window.start; + let lines = path_lines(paths, window, width, &app.theme); + app.layout.list = Some((inner, offset)); + f.render_widget(Paragraph::new(lines), inner); +} + +/// A rounded, bordered pane titled with the given name. +fn pane_block(title: &str, theme: &Theme) -> Block<'static> { + Block::bordered() + .border_type(BorderType::Rounded) + .border_style(theme.border(true)) + .title(Line::from(vec![ + Span::raw(" "), + Span::styled(title.to_string(), theme.title()), + Span::raw(" "), + ])) +} + +/// The check rows for one report, plus the fixes line for what is broken. +fn check_lines(report: &HealthReport, width: usize, theme: &Theme) -> Vec> { + let symbols = theme.sym(); + let mut lines = Vec::new(); + let bin = format::home_relative(&report.bin_path); + if report.path_configured { + lines.push(check_line( + symbols.installed, + theme.success(), + "PATH", + &format!("{bin} is in PATH"), + width, + theme, + )); + } else { + lines.push(check_line( + symbols.warning, + theme.warning(), + "PATH", + &format!("{bin} is not in PATH"), + width, + theme, + )); + lines.push(path_hint_line(&bin, width, theme)); + } + if let Some(man_path) = &report.man_path { + let man = format::home_relative(man_path); + if report.man_path_configured { + lines.push(check_line( + symbols.installed, + theme.success(), + "MANPATH", + "configured", + width, + theme, + )); + } else { + lines.push(check_line( + symbols.warning, + theme.warning(), + "MANPATH", + &format!("{man} is not searched by man"), + width, + theme, + )); + } + } + let broken = &report.broken_packages; + if broken.is_empty() { + lines.push(check_line( + symbols.installed, + theme.success(), + "Packages", + "none broken", + width, + theme, + )); + } else { + let count = broken.len(); + lines.push(check_line( + symbols.error, + theme.danger(), + "Packages", + &format!("{count} broken"), + width, + theme, + )); + for package in broken { + lines.push(broken_package_line(package, width, theme)); + } + } + let symlinks = &report.broken_symlinks; + if symlinks.is_empty() { + lines.push(check_line( + symbols.installed, + theme.success(), + "Symlinks", + "none broken", + width, + theme, + )); + } else { + let count = symlinks.len(); + lines.push(check_line( + symbols.error, + theme.danger(), + "Symlinks", + &format!("{count} broken"), + width, + theme, + )); + for path in symlinks.iter().take(VISIBLE_SYMLINKS) { + lines.push(indented_line(&path.display().to_string(), width, theme)); + } + let hidden = count.saturating_sub(VISIBLE_SYMLINKS); + if hidden > 0 { + lines.push(indented_line(&format!("+{hidden} more"), width, theme)); + } + } + if let Some(line) = fixes_line(report, theme) { + lines.push(line); + } + lines +} + +/// One check row: the status symbol, the bold label, and the message, +/// each cut so the row never overflows its pane. +fn check_line( + symbol: &str, + style: Style, + label: &str, + message: &str, + width: usize, + theme: &Theme, +) -> Line<'static> { + let message_width = width.saturating_sub(INDENT_WIDTH); + Line::from(vec![ + Span::styled(symbol.to_string(), style), + Span::raw(" "), + Span::styled( + format!("{: Line<'static> { + let hint = format!("add to your shell: export PATH=\"{bin}:$PATH\""); + let hint = format::truncate( + &hint, + width.saturating_sub(INDENT_WIDTH), + theme.sym().ellipsis, + ); + Line::styled(format!("{}{hint}", " ".repeat(INDENT_WIDTH)), theme.muted()) +} + +/// One broken package under its count: `name path`, indented to the +/// message column, the path cut in the middle. +fn broken_package_line(package: &BrokenPackage, width: usize, theme: &Theme) -> Line<'static> { + let room = width.saturating_sub(INDENT_WIDTH); + let name = format::truncate( + &package.pkg_name, + room.saturating_sub(2), + theme.sym().ellipsis, + ); + let path_room = room + .saturating_sub(Span::raw(name.as_str()).width()) + .saturating_sub(2); + let path = format::truncate_middle(&package.installed_path, path_room, theme.sym().ellipsis); + Line::from(vec![ + Span::raw(" ".repeat(INDENT_WIDTH)), + Span::styled(name, theme.text()), + Span::raw(" "), + Span::styled(path, theme.muted()), + ]) +} + +/// One indented muted line: a broken symlink path or the count of the +/// paths that folded away. +fn indented_line(text: &str, width: usize, theme: &Theme) -> Line<'static> { + let text = format::truncate( + text, + width.saturating_sub(INDENT_WIDTH), + theme.sym().ellipsis, + ); + Line::from(vec![ + Span::raw(" ".repeat(INDENT_WIDTH)), + Span::styled(text, theme.muted()), + ]) +} + +/// The fixes worth running for what is broken, as `key label` pairs taken +/// from the health key table. Nothing broken leaves the line out. +fn fixes_line(report: &HealthReport, theme: &Theme) -> Option> { + let broken_packages = !report.broken_packages.is_empty(); + let broken_symlinks = !report.broken_symlinks.is_empty(); + let mut spans: Vec> = Vec::new(); + for binding in keymap::bindings(ViewId::Health) { + let label = match binding.action { + Action::FixSymlinks if broken_symlinks => binding.label.to_string(), + Action::RemoveBroken if broken_packages => format!("{} packages", binding.label), + _ => continue, + }; + if !spans.is_empty() { + spans.push(Span::raw(" ")); + } + spans.push(Span::styled( + keymap::key_label(binding.keys[0]), + theme.key(), + )); + spans.push(Span::raw(" ")); + spans.push(Span::styled(label, theme.muted())); + } + if spans.is_empty() { + None + } else { + Some(Line::from(spans)) + } +} + +/// The window of paths the pane shows, each label padded to its column +/// and the path shown relative to the home directory. +fn path_lines( + paths: &[(String, PathBuf)], + window: Range, + width: usize, + theme: &Theme, +) -> Vec> { + window + .map(|index| { + let (label, path) = &paths[index]; + let value = format::home_relative(path); + Line::from(vec![ + Span::styled( + format!("{: (crate::app::App, Instant) { + let mut app = test_app(); + app.view = ViewId::Health; + app.update(loaded(report), Instant::now()); + (app, Instant::now()) + } + + /// A finished health load for the given report. + fn loaded(report: HealthReport) -> Msg { + Msg::Loaded(Loaded::Health(Ok((report, health_paths())))) + } + + /// One broken package with the given name and install path. + fn broken(name: &str, path: &str) -> BrokenPackage { + BrokenPackage { + pkg_name: name.to_string(), + installed_path: path.to_string(), + } + } + + #[test] + fn entering_health_the_first_time_loads_the_report() { + let mut app = test_app(); + let effects = app.update(key('6'), Instant::now()); + let [Effect::LoadHealth] = &effects[..] else { + panic!("expected one load on first entry"); + }; + assert!(app.health.report.is_loading()); + } + + #[test] + fn reentering_health_starts_nothing() { + let mut app = test_app(); + let now = Instant::now(); + app.update(key('6'), now); + app.update(loaded(health_report()), now); + app.update(key('1'), now); + let effects = app.update(key('6'), now); + assert!(effects.is_empty()); + assert!(app.health.report.ready().is_some()); + } + + #[test] + fn ctrl_r_reloads_the_report() { + let (mut app, now) = health_app(health_report()); + let effects = app.update(ctrl('r'), now); + let [Effect::LoadHealth] = &effects[..] else { + panic!("expected one load on reload"); + }; + assert!(app.health.report.is_loading()); + } + + #[test] + fn a_path_not_in_path_shows_the_export_hint() { + let mut report = health_report(); + report.path_configured = false; + let (mut app, _) = health_app(report); + let screen = screen(&mut app, 100, 24); + assert!(screen.contains("is not in PATH"), "screen is {screen:?}"); + assert!(screen.contains("export PATH="), "screen is {screen:?}"); + } + + #[test] + fn a_configured_path_shows_no_hint() { + let (mut app, _) = health_app(health_report()); + let screen = screen(&mut app, 100, 24); + assert!(screen.contains("is in PATH"), "screen is {screen:?}"); + assert!(!screen.contains("export PATH="), "screen is {screen:?}"); + } + + #[test] + fn the_manpath_row_shows_only_with_a_man_path() { + let (mut app, _) = health_app(health_report()); + let without = screen(&mut app, 100, 24); + assert!(!without.contains("MANPATH"), "screen is {without:?}"); + + let mut report = health_report(); + report.man_path = Some("/home/user/.local/share/soar/bin/share/man".into()); + let (mut app, _) = health_app(report); + let with = screen(&mut app, 100, 24); + assert!(with.contains("MANPATH"), "screen is {with:?}"); + assert!(with.contains("configured"), "screen is {with:?}"); + } + + #[test] + fn an_unsearched_man_path_warns() { + let mut report = health_report(); + report.man_path = Some("/home/user/man".into()); + report.man_path_configured = false; + let (mut app, _) = health_app(report); + let screen = screen(&mut app, 100, 24); + assert!( + screen.contains("is not searched by man"), + "screen is {screen:?}" + ); + } + + #[test] + fn broken_packages_are_named_under_their_count() { + let mut report = health_report(); + report.broken_packages = vec![ + broken("obsidian", "/home/user/.local/share/soar/packages/obsidian"), + broken("zellij", "/home/user/.local/share/soar/packages/zellij"), + ]; + let (mut app, _) = health_app(report); + let screen = screen(&mut app, 100, 24); + assert!(screen.contains("2 broken"), "screen is {screen:?}"); + assert!(screen.contains("obsidian"), "screen is {screen:?}"); + assert!(screen.contains("zellij"), "screen is {screen:?}"); + } + + #[test] + fn a_long_broken_package_path_is_cut_in_the_middle() { + let mut report = health_report(); + let long = "/home/user/.local/share/soar/packages/delta-shell-0.4.1-full-distribution"; + report.broken_packages = vec![broken("delta-shell", long)]; + let (mut app, _) = health_app(report); + let screen = screen(&mut app, 100, 24); + assert!(screen.contains("delta-shell"), "screen is {screen:?}"); + assert!(screen.contains('…'), "screen is {screen:?}"); + assert!(!screen.contains(long), "screen is {screen:?}"); + } + + #[test] + fn broken_symlinks_fold_after_five_paths() { + let mut report = health_report(); + report.broken_symlinks = (1..=7) + .map(|n| Path::new("/home/user/.local/bin").join(format!("tool{n}"))) + .collect(); + let (mut app, _) = health_app(report); + let screen = screen(&mut app, 100, 24); + assert!(screen.contains("7 broken"), "screen is {screen:?}"); + assert!(screen.contains("tool5"), "screen is {screen:?}"); + assert!(screen.contains("+2 more"), "screen is {screen:?}"); + assert!(!screen.contains("tool6"), "screen is {screen:?}"); + } + + #[test] + fn broken_symlinks_offer_their_fix() { + let mut report = health_report(); + report.broken_symlinks = vec![Path::new("/home/user/.local/bin/tool").into()]; + let (mut app, _) = health_app(report); + let screen = screen(&mut app, 100, 24); + assert!(screen.contains("b fix symlinks"), "screen is {screen:?}"); + } + + #[test] + fn broken_packages_offer_their_fix() { + let mut report = health_report(); + report.broken_packages = vec![broken("obsidian", "/gone/obsidian")]; + let (mut app, _) = health_app(report); + let screen = screen(&mut app, 100, 24); + assert!( + screen.contains("p remove broken packages"), + "screen is {screen:?}" + ); + } + + #[test] + fn a_clean_report_lists_no_fixes() { + let (mut app, _) = health_app(health_report()); + let screen = screen(&mut app, 100, 24); + assert!(!screen.contains("broken packages"), "screen is {screen:?}"); + } + + #[test] + fn the_paths_block_shows_a_home_relative_value() { + let Ok(home) = std::env::var("HOME") else { + return; + }; + if home.is_empty() { + return; + } + let report = health_report(); + let mut paths = health_paths(); + paths[5] = ("Packages".to_string(), Path::new(&home).join(".local/bin")); + let mut app = test_app(); + app.view = ViewId::Health; + app.update( + Msg::Loaded(Loaded::Health(Ok((report, paths)))), + Instant::now(), + ); + let screen = screen(&mut app, 100, 24); + assert!(screen.contains("~/.local/bin"), "screen is {screen:?}"); + } + + #[test] + fn the_paths_block_names_every_path() { + let (mut app, _) = health_app(health_report()); + let screen = screen(&mut app, 120, 24); + for label in [ + "Config", + "Packages config", + "Bin", + "Database", + "Cache", + "Packages", + "Repositories", + ] { + assert!(screen.contains(label), "screen is {screen:?}"); + } + } + + #[test] + fn a_failed_load_shows_the_error_state() { + let mut app = test_app(); + app.view = ViewId::Health; + app.update( + Msg::Loaded(Loaded::Health(Err("database locked".to_string()))), + Instant::now(), + ); + let screen = screen(&mut app, 80, 24); + assert!(screen.contains("database locked"), "screen is {screen:?}"); + assert!(screen.contains("ctrl-r to retry"), "screen is {screen:?}"); + } + + #[test] + fn j_moves_the_paths_cursor() { + let (mut app, now) = health_app(health_report()); + app.update(key('j'), now); + app.update(key('j'), now); + assert_eq!(app.health.cursor.selected, 2); + } + + #[test] + fn a_finished_fix_reloads_the_report() { + let (mut app, now) = health_app(health_report()); + app.enqueue(JobSpec::CleanCache, now); + let effects = app.update( + Msg::JobFinished { + id: 0, + outcome: crate::jobs::JobOutcome { + ok: true, + aborted: false, + headline: "Cache cleaned".to_string(), + lines: Vec::new(), + }, + }, + now, + ); + assert!(matches!(effects.as_slice(), [Effect::LoadHealth])); + assert!(app.health.report.is_loading()); + } + + #[test] + fn stacked_layouts_at_a_narrow_width() { + let (mut app, _) = health_app(health_report()); + let screen = screen(&mut app, 80, 30); + assert!(screen.contains("Paths"), "screen is {screen:?}"); + assert!(screen.contains("is in PATH"), "screen is {screen:?}"); + } +} diff --git a/crates/soar-tui/src/views/installed.rs b/crates/soar-tui/src/views/installed.rs new file mode 100644 index 00000000..4decc514 --- /dev/null +++ b/crates/soar-tui/src/views/installed.rs @@ -0,0 +1,1279 @@ +//! The installed packages view: its table, the filter, the sort, the +//! marks, and the detail pane. + +use std::{collections::HashSet, ops::Range, time::SystemTime}; + +use ratatui::{ + Frame, + layout::{Alignment, Constraint, Layout, Rect}, + style::{Modifier, Style}, + text::{Line, Span}, + widgets::{Block, BorderType, Cell, Row, Table}, +}; +use soar_operations::{InstalledEntry, InstalledListResult}; + +use crate::{ + app::App, + format, + loadable::Loadable, + theme::Theme, + views::ViewId, + widgets::{installed_detail, scroll::ListCursor, states, text_input::TextInput}, +}; + +/// The narrowest terminal that shows the list beside the detail pane. +const SPLIT_WIDTH: u16 = 100; + +/// The order the installed list sorts its rows in. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub(crate) enum InstalledSort { + /// By package name. + #[default] + Name, + /// By size on disk, largest first. + Size, + /// By install date, newest first. + Date, +} + +impl InstalledSort { + /// The sort this one cycles to: name, then size, then date, then back + /// to name. + pub(crate) fn next(self) -> InstalledSort { + match self { + InstalledSort::Name => InstalledSort::Size, + InstalledSort::Size => InstalledSort::Date, + InstalledSort::Date => InstalledSort::Name, + } + } + + /// The word the sort hint shows. + pub(crate) fn label(self) -> &'static str { + match self { + InstalledSort::Name => "name", + InstalledSort::Size => "size", + InstalledSort::Date => "date", + } + } +} + +/// The state of the installed packages view. +#[derive(Default)] +pub(crate) struct InstalledView { + /// The whole installed list, loaded at startup and reloaded after any + /// job that changes installs. + pub(crate) list: Loadable, + /// The indexes into the list of the rows shown, in display order. + pub(crate) visible: Vec, + /// The visible row the cursor sits on. + pub(crate) cursor: ListCursor, + /// The text the filter matches rows against. + pub(crate) filter: TextInput, + /// Whether the filter holds the keyboard. + pub(crate) filter_focused: bool, + /// The order the rows sort in. + pub(crate) sort: InstalledSort, + /// The rows marked for the next bulk action, by package id. + pub(crate) marks: HashSet, + /// The scroll of the detail pane while it fills the screen. + pub(crate) detail: ListCursor, + /// How many rows the detail held at the last render, so scrolling + /// moves over what the pane actually shows. + pub(crate) detail_rows: usize, + /// Whether the detail fills the whole body instead of sitting beside + /// the list. + pub(crate) detail_open: bool, +} + +impl InstalledView { + /// The entry the cursor points at, when the list has one. The indexes + /// can be stale right after a reload replaced the list, so the lookup + /// tolerates a missing row. + pub(crate) fn cursor_entry(&self) -> Option<&InstalledEntry> { + let listing = self.list.ready()?; + let index = *self.visible.get(self.cursor.selected)?; + listing.packages.get(index) + } + + /// The package id of the row the cursor points at, when there is one. + fn cursor_id(&self) -> Option { + self.cursor_entry().map(|entry| entry.package.id) + } + + /// Rebuilds the visible rows from the filter text and the sort. The + /// cursor stays on its package while that row survives the new order. + pub(crate) fn refilter(&mut self) { + let previous = self.cursor_id(); + let query = self.filter.value().trim().to_lowercase(); + let mut shown: Vec = Vec::new(); + if let Loadable::Ready(listing) = &self.list { + for (index, entry) in listing.packages.iter().enumerate() { + if !is_finished(entry) { + continue; + } + if !query.is_empty() && !haystack(entry).contains(&query) { + continue; + } + shown.push(index); + } + match self.sort { + InstalledSort::Name => { + shown.sort_by(|&a, &b| { + let (x, y) = (&listing.packages[a], &listing.packages[b]); + x.package + .pkg_name + .cmp(&y.package.pkg_name) + .then(x.package.pkg_family.cmp(&y.package.pkg_family)) + .then(x.package.repo_name.cmp(&y.package.repo_name)) + }) + } + InstalledSort::Size => { + shown.sort_by(|&a, &b| { + listing.packages[b] + .disk_size + .cmp(&listing.packages[a].disk_size) + }) + } + InstalledSort::Date => { + shown.sort_by(|&a, &b| { + let (x, y) = (&listing.packages[a], &listing.packages[b]); + date_of(y).cmp(&date_of(x)) + }) + } + } + } + self.visible = shown; + self.cursor = ListCursor::default(); + if let Some(previous) = previous + && let Loadable::Ready(listing) = &self.list + && let Some(position) = self + .visible + .iter() + .position(|&index| listing.packages[index].package.id == previous) + { + self.cursor.selected = position; + } + } + + /// Marks or unmarks the row under the cursor, then moves one row down. + pub(crate) fn toggle_mark(&mut self) { + let Some(&index) = self.visible.get(self.cursor.selected) else { + return; + }; + let Loadable::Ready(listing) = &self.list else { + return; + }; + let Some(entry) = listing.packages.get(index) else { + return; + }; + let id = entry.package.id; + if !self.marks.remove(&id) { + self.marks.insert(id); + } + self.cursor.down(1, self.visible.len()); + } + + /// The rows the next bulk action works on: every marked row, or the + /// row under the cursor when nothing is marked. The records are + /// copied so the removal confirm keeps them until it is accepted. + /// Marks whose rows a reload dropped are skipped. + pub(crate) fn selected_entries(&self) -> Vec { + let Some(listing) = self.list.ready() else { + return Vec::new(); + }; + if self.marks.is_empty() { + return self.cursor_entry().map(cloned_entry).into_iter().collect(); + } + listing + .packages + .iter() + .filter(|entry| self.marks.contains(&entry.package.id)) + .map(cloned_entry) + .collect() + } + + /// Moves the sort to its next order and rebuilds the rows. + pub(crate) fn cycle_sort(&mut self) { + self.sort = self.sort.next(); + self.refilter(); + } + + /// Opens the full-screen detail on the row under the cursor, or + /// closes it back to the list. + pub(crate) fn toggle_detail(&mut self) { + if self.detail_open { + self.detail_open = false; + } else if self.cursor_entry().is_some() { + self.detail_open = true; + self.detail.top(); + } + } +} + +/// Whether an entry represents a finished install. Rows recorded with +/// `is_installed == false` are leftovers of interrupted installs, which +/// Health handles, so the list skips them. +fn is_finished(entry: &InstalledEntry) -> bool { + entry.package.is_installed +} + +/// A copy of one entry: the record cloned, the computed size and health +/// kept as they are. +fn cloned_entry(entry: &InstalledEntry) -> InstalledEntry { + InstalledEntry { + package: entry.package.clone(), + disk_size: entry.disk_size, + is_healthy: entry.is_healthy, + } +} + +/// The text the filter matches against: `family/name` when a family is +/// recorded, else the name. +fn haystack(entry: &InstalledEntry) -> String { + match entry.package.pkg_family.as_deref() { + Some(family) => format!("{family}/{}", entry.package.pkg_name), + None => entry.package.pkg_name.clone(), + } + .to_lowercase() +} + +/// The install date an entry was recorded with, when it parses. +fn date_of(entry: &InstalledEntry) -> Option { + format::parse_installed_date(&entry.package.installed_date) +} + +/// Draws the installed packages view: the list pane, and beside it the +/// detail pane of the row under the cursor, or the detail alone while it +/// fills the screen. +pub(crate) fn render(f: &mut Frame, area: Rect, app: &mut App) { + if app.installed.detail_open { + installed_detail::render(f, area, app, true); + return; + } + if area.width >= SPLIT_WIDTH { + let [list, detail] = + Layout::horizontal([Constraint::Percentage(55), Constraint::Percentage(45)]) + .areas(area); + render_list(f, list, app); + installed_detail::render(f, detail, app, false); + } else { + render_list(f, area, app); + } +} + +/// Draws the list pane: its border with the count, the total size, and the +/// filter in the title, then the table of visible rows or the loading, +/// error, and empty states. +fn render_list(f: &mut Frame, area: Rect, app: &mut App) { + let theme = &app.theme; + let rows_height = usize::from(area.height.saturating_sub(3)); + let window = match &app.installed.list { + Loadable::Ready(_) => { + app.installed + .cursor + .window(app.installed.visible.len(), rows_height) + } + _ => 0..0, + }; + let block = list_block(&app.installed, theme, area.width); + let inner = block.inner(area); + f.render_widget(block, area); + let view = &app.installed; + match &view.list { + Loadable::Idle => {} + Loadable::Loading => { + states::loading(f, inner, theme, app.frame, "Loading installed packages") + } + Loadable::Failed(error) => states::error(f, inner, theme, error), + Loadable::Ready(listing) if listing.packages.is_empty() => { + states::empty( + f, + inner, + theme, + "Nothing installed yet. Find something in Browse (1).", + ) + } + Loadable::Ready(_) if view.visible.is_empty() => { + states::empty( + f, + inner, + theme, + &format!("No packages match {}", view.filter.value()), + ) + } + Loadable::Ready(listing) => { + let (columns, constraints) = columns(area.width); + let name_width = usize::from(name_column_width(area.width, &constraints)); + let offset = window.start; + let table = Table::new( + table_rows(view, listing, window, &columns, name_width, theme), + constraints, + ) + .header(header_row(&columns, theme)); + app.layout.list = Some((rows_area(inner), offset)); + f.render_widget(table, inner); + } + } +} + +/// The rows area of a table pane: its header row takes the first line of +/// the pane's inner area, and the window range maps onto what is left. +fn rows_area(inner: Rect) -> Rect { + Rect { + y: inner.y.saturating_add(1), + height: inner.height.saturating_sub(1), + ..inner + } +} + +/// Which optional columns the table shows at one terminal width. +#[derive(Clone, Copy)] +struct Columns { + /// The repository column. + repo: bool, + /// The install date column. + installed: bool, + /// The profile column. + profile: bool, +} + +/// The columns the table shows at one terminal width. The profile column +/// leaves on narrow terminals, the install date on very narrow ones, and +/// the repository column on the narrowest. +fn columns(width: u16) -> (Columns, Vec) { + let shown = Columns { + repo: width >= 70, + installed: width >= 80, + profile: width >= 100, + }; + let mut constraints = vec![ + Constraint::Length(2), + Constraint::Fill(1), + Constraint::Length(14), + ]; + if shown.repo { + constraints.push(Constraint::Length(12)); + } + constraints.push(Constraint::Length(10)); + if shown.installed { + constraints.push(Constraint::Length(12)); + } + if shown.profile { + constraints.push(Constraint::Length(10)); + } + constraints.push(Constraint::Length(8)); + (shown, constraints) +} + +/// The width the name column gets: everything the fixed columns and the +/// spacing between them leave over. +fn name_column_width(width: u16, constraints: &[Constraint]) -> u16 { + let fixed: u16 = constraints + .iter() + .map(|constraint| { + match constraint { + Constraint::Length(n) => *n, + _ => 0, + } + }) + .sum(); + let spacing = constraints.len().saturating_sub(1) as u16; + width.saturating_sub(2).saturating_sub(fixed + spacing) +} + +/// The column labels in muted bold. +fn header_row(columns: &Columns, theme: &Theme) -> Row<'static> { + let mut labels = vec!["", "NAME", "VERSION"]; + if columns.repo { + labels.push("REPO"); + } + labels.push("SIZE"); + if columns.installed { + labels.push("INSTALLED"); + } + if columns.profile { + labels.push("PROFILE"); + } + labels.push("FLAG"); + Row::new(labels).style(theme.muted().add_modifier(Modifier::BOLD)) +} + +/// Builds the rows the window shows: the mark, the name, and the columns +/// that exist at this width. +fn table_rows( + view: &InstalledView, + listing: &InstalledListResult, + window: Range, + columns: &Columns, + name_width: usize, + theme: &Theme, +) -> Vec> { + let shown = &view.visible[window.clone()]; + window + .zip(shown.iter()) + .map(|(position, &index)| { + let entry = &listing.packages[index]; + list_row( + entry, + view.marks.contains(&entry.package.id), + position == view.cursor.selected, + columns, + name_width, + theme, + ) + }) + .collect() +} + +/// One table row. The cursor row takes the cursor highlight across its +/// whole width and starts with the cursor symbol; a marked row starts with +/// the marked symbol. +fn list_row( + entry: &InstalledEntry, + marked: bool, + cursor_here: bool, + columns: &Columns, + name_width: usize, + theme: &Theme, +) -> Row<'static> { + let symbols = theme.sym(); + let lead = if cursor_here { + Span::styled(symbols.cursor.to_string(), theme.cursor_row()) + } else if marked { + Span::styled(symbols.marked.to_string(), theme.marked()) + } else { + Span::raw(" ") + }; + let mut cells = vec![ + Cell::from(Line::from(vec![lead, Span::raw(" ")])), + name_cell(entry, theme, name_width), + Cell::from(Span::styled(entry.package.version.clone(), theme.accent2())), + ]; + if columns.repo { + cells.push(Cell::from(Span::styled( + entry.package.repo_name.clone(), + theme.info(), + ))); + } + cells.push(Cell::from( + Line::from(Span::raw(format::size(entry.disk_size))).alignment(Alignment::Right), + )); + if columns.installed { + cells.push(Cell::from(Span::styled(age_of(entry), theme.text()))); + } + if columns.profile { + cells.push(Cell::from(Span::styled( + entry.package.profile.clone(), + theme.muted(), + ))); + } + cells.push(Cell::from( + flag_span(entry, theme).unwrap_or_else(|| Span::raw("")), + )); + let style = if cursor_here { + theme.cursor_row() + } else { + Style::new() + }; + Row::new(cells).style(style) +} + +/// How long ago an entry was installed, such as `3 days ago`, or nothing +/// when its date is missing or unreadable. +fn age_of(entry: &InstalledEntry) -> String { + date_of(entry).map_or_else(String::new, |then| { + format::relative(then, SystemTime::now()) + }) +} + +/// The name cell: the state symbol first, then `family/` before the name +/// in the family color. +fn name_cell(entry: &InstalledEntry, theme: &Theme, width: usize) -> Cell<'static> { + let symbols = theme.sym(); + let symbol = status_span(entry, theme); + let mut full = String::new(); + let mut family_chars = 0; + if let Some(family) = entry.package.pkg_family.as_deref() { + full.push_str(family); + full.push('/'); + family_chars = full.chars().count(); + } + full.push_str(&entry.package.pkg_name); + let reserved = symbol.width() + 1; + let text = format::truncate(&full, width.saturating_sub(reserved), symbols.ellipsis); + let mut spans = vec![symbol, Span::raw(" ")]; + if family_chars > 0 { + let boundary = text + .char_indices() + .nth(family_chars) + .map_or(text.len(), |(at, _)| at); + spans.push(Span::styled(text[..boundary].to_string(), theme.accent2())); + spans.push(Span::styled(text[boundary..].to_string(), theme.text())); + } else { + spans.push(Span::styled(text, theme.text())); + } + Cell::from(Line::from(spans)) +} + +/// The state span starting the name cell: broken first, then not active, +/// then pinned, then the plain installed mark, each in its own color. +fn status_span(entry: &InstalledEntry, theme: &Theme) -> Span<'static> { + let symbols = theme.sym(); + let (symbol, style) = if !entry.is_healthy { + (symbols.warning, theme.danger()) + } else if entry.package.unlinked { + (symbols.available, theme.muted()) + } else if entry.package.pinned { + (symbols.pinned, theme.warning()) + } else { + (symbols.installed, theme.success()) + }; + Span::styled(symbol.to_string(), style) +} + +/// The word the flag column shows, first match wins: broken, then +/// inactive, then pinned. +fn flag_span(entry: &InstalledEntry, theme: &Theme) -> Option> { + if !entry.is_healthy { + Some(Span::styled("broken", theme.danger())) + } else if entry.package.unlinked { + Some(Span::styled("inactive", theme.muted())) + } else if entry.package.pinned { + Some(Span::styled("pinned", theme.warning())) + } else { + None + } +} + +/// The pane border: the shown count and the total size on the left of the +/// top edge, and the filter on its right. +fn list_block(view: &InstalledView, theme: &Theme, width: u16) -> Block<'static> { + let left = match view.list.ready() { + Some(listing) => { + Line::styled( + format!( + " Installed {} {} {} ", + view.visible.len(), + theme.sym().dot, + format::size(listing.total_size) + ), + theme.title(), + ) + } + None => Line::styled(format!(" {} ", ViewId::Installed.title()), theme.title()), + }; + let budget = usize::from(width).saturating_sub(2 + left.width()); + let block = Block::bordered() + .border_type(BorderType::Rounded) + .border_style(theme.border(true)) + .title(left); + if budget > 0 { + block.title_top(right_title(view, theme, budget).right_aligned()) + } else { + block + } +} + +/// The right end of the top border: the filter text while it is being +/// typed or holds one, cut to `budget` cells so it never reaches the +/// title on the left. +fn right_title(view: &InstalledView, theme: &Theme, budget: usize) -> Line<'static> { + let mut spans: Vec> = Vec::new(); + if !view.filter.is_empty() || view.filter_focused { + let room = budget.saturating_sub(2); + spans.push(Span::styled("/ ".to_string(), theme.muted())); + spans.extend(view.filter.line(view.filter_focused, room, theme).spans); + } + if !spans.is_empty() { + spans.insert(0, Span::raw(" ")); + spans.push(Span::raw(" ")); + } + let mut shown: Vec> = Vec::new(); + let mut used = 0; + for span in spans { + let width = span.width(); + if used + width > budget { + break; + } + used += width; + shown.push(span); + } + Line::from(shown) +} + +#[cfg(test)] +mod tests { + use std::time::Instant; + + use ratatui::crossterm::event::KeyCode; + use soar_operations::{InstalledEntry, InstalledListResult}; + + use crate::{ + action::Action, + app::App, + effect::Effect, + format, + jobs::JobSpec, + msg::{Loaded, Msg}, + test_support::{code, installed_entry, key, screen, test_app}, + views::{ViewId, installed::InstalledSort}, + widgets::overlay::Overlay, + }; + + /// A loaded installed list holding the given entries, with the total + /// size and count summed from them, answering the load the app still + /// expects before any reload has started. + fn installed(entries: Vec) -> Msg { + let total_size = entries.iter().map(|entry| entry.disk_size).sum(); + let total_count = entries.len(); + Msg::Loaded(Loaded::Installed { + check: 0, + result: Ok(InstalledListResult { + packages: entries, + total_count, + total_size, + }), + }) + } + + fn catalog() -> Vec { + vec![ + installed_entry("bat", "0.24.0", "bincache"), + installed_entry("fd", "10.2.0", "bincache"), + installed_entry("jq", "1.7.1", "pkgcache"), + ] + } + + fn failed(message: &str) -> Msg { + Msg::Loaded(Loaded::Installed { + check: 0, + result: Err(message.to_string()), + }) + } + + /// The interface state on the installed view, where its keys and its + /// pane are live. + fn installed_app() -> App { + let mut app = test_app(); + app.view = ViewId::Installed; + app + } + + #[test] + fn a_loaded_list_renders_every_name() { + let mut app = installed_app(); + app.update(installed(catalog()), Instant::now()); + let screen = screen(&mut app, 100, 24); + for name in ["bat", "fd", "jq"] { + assert!(screen.contains(name), "screen is {screen:?}"); + } + } + + #[test] + fn a_failed_list_shows_the_error() { + let mut app = installed_app(); + app.update(failed("database locked"), Instant::now()); + let screen = screen(&mut app, 80, 24); + assert!(screen.contains("database locked"), "screen is {screen:?}"); + } + + #[test] + fn an_empty_list_says_where_to_find_packages() { + let mut app = installed_app(); + app.update(installed(Vec::new()), Instant::now()); + let screen = screen(&mut app, 80, 24); + assert!( + screen.contains("Nothing installed yet. Find something in Browse (1)."), + "screen is {screen:?}" + ); + } + + #[test] + fn a_loading_list_shows_the_spinner_line() { + let mut app = installed_app(); + app.startup(); + assert!(screen(&mut app, 80, 24).contains("Loading installed packages")); + } + + #[test] + fn the_title_shows_the_shown_count_and_the_total_size() { + let mut app = installed_app(); + let mut entries = catalog(); + entries[0].disk_size = 5_452_595; + entries[1].disk_size = 3_250_585; + entries[2].disk_size = 300; + app.update(installed(entries), Instant::now()); + let expected = format!( + "Installed 3 {} {}", + app.theme.sym().dot, + format::size(5_452_595 + 3_250_585 + 300) + ); + assert!(screen(&mut app, 100, 24).contains(&expected)); + } + + #[test] + fn the_header_names_its_columns() { + let mut app = installed_app(); + app.update(installed(catalog()), Instant::now()); + let screen = screen(&mut app, 200, 24); + for label in [ + "NAME", + "VERSION", + "REPO", + "SIZE", + "INSTALLED", + "PROFILE", + "FLAG", + ] { + assert!(screen.contains(label), "screen is {screen:?}"); + } + } + + #[test] + fn narrow_terminals_drop_the_profile_then_the_date_then_the_repo_column() { + let mut app = installed_app(); + app.update(installed(catalog()), Instant::now()); + let full = screen(&mut app, 200, 20); + assert!(full.contains("PROFILE"), "screen is {full:?}"); + let no_profile = screen(&mut app, 99, 20); + assert!(!no_profile.contains("PROFILE"), "screen is {no_profile:?}"); + assert!(no_profile.contains("INSTALLED"), "screen is {no_profile:?}"); + let no_date = screen(&mut app, 79, 20); + assert!(!no_date.contains("INSTALLED"), "screen is {no_date:?}"); + assert!(no_date.contains("REPO"), "screen is {no_date:?}"); + let no_repo = screen(&mut app, 69, 20); + assert!(!no_repo.contains("REPO"), "screen is {no_repo:?}"); + } + + #[test] + fn rows_sorted_by_size_put_the_biggest_first() { + let mut app = installed_app(); + let mut entries = catalog(); + entries[0].disk_size = 300; + entries[1].disk_size = 5_452_595; + entries[2].disk_size = 1_048_576; + app.update(installed(entries), Instant::now()); + app.update(key('o'), Instant::now()); + assert_eq!(app.installed.sort, InstalledSort::Size); + assert_eq!(app.installed.visible, vec![1, 2, 0]); + } + + #[test] + fn date_sort_puts_the_newest_first() { + let mut app = installed_app(); + let mut entries = catalog(); + entries[0].package.installed_date = "2026-01-01 10:00:00".to_string(); + entries[1].package.installed_date = "2026-06-01 10:00:00".to_string(); + entries[2].package.installed_date = "2024-03-05 09:30:00".to_string(); + app.update(installed(entries), Instant::now()); + let now = Instant::now(); + app.update(key('o'), now); + app.update(key('o'), now); + assert_eq!(app.installed.sort, InstalledSort::Date); + assert_eq!(app.installed.visible, vec![1, 0, 2]); + } + + #[test] + fn a_row_left_by_an_interrupted_install_is_skipped() { + let mut app = installed_app(); + let mut entries = catalog(); + entries[1].package.is_installed = false; + app.update(installed(entries), Instant::now()); + assert_eq!(app.installed.visible, vec![0, 2]); + let screen = screen(&mut app, 100, 24); + assert!(!screen.contains("fd"), "screen is {screen:?}"); + } + + #[test] + fn filter_ba_keeps_bat_and_hides_fd() { + let mut app = installed_app(); + app.update(installed(catalog()), Instant::now()); + let now = Instant::now(); + app.update(key('/'), now); + for c in ['b', 'a'] { + app.update(key(c), now); + } + assert_eq!(app.installed.visible, vec![0]); + app.update(code(KeyCode::Esc), now); + assert_eq!(app.installed.visible, vec![0, 1, 2]); + } + + #[test] + fn the_filter_matches_the_family_before_the_name() { + let mut app = installed_app(); + let mut entries = catalog(); + entries[0].package.pkg_family = Some("sharkdp".to_string()); + app.update(installed(entries), Instant::now()); + let now = Instant::now(); + app.update(key('/'), now); + for c in ['s', 'h', 'a', 'r', 'k', 'd', 'p', '/', 'b'] { + app.update(key(c), now); + } + assert_eq!(app.installed.visible, vec![0]); + } + + #[test] + fn a_filter_matching_nothing_shows_the_empty_text() { + let mut app = installed_app(); + app.update(installed(catalog()), Instant::now()); + let now = Instant::now(); + app.update(key('/'), now); + for c in ['x', 'y', 'z'] { + app.update(key(c), now); + } + let screen = screen(&mut app, 80, 24); + assert!( + screen.contains("No packages match xyz"), + "screen is {screen:?}" + ); + } + + #[test] + fn typing_while_the_filter_holds_focus_reaches_the_filter_only() { + let mut app = installed_app(); + app.update(installed(catalog()), Instant::now()); + let now = Instant::now(); + app.update(key('/'), now); + app.update(key('q'), now); + assert!(!app.quit); + assert!(app.installed.filter_focused); + assert_eq!(app.installed.filter.value(), "q"); + } + + #[test] + fn enter_keeps_the_filter_and_esc_clears_it() { + let mut app = installed_app(); + app.update(installed(catalog()), Instant::now()); + let now = Instant::now(); + app.update(key('/'), now); + for c in ['b', 'a'] { + app.update(key(c), now); + } + app.update(code(KeyCode::Enter), now); + assert!(!app.installed.filter_focused); + assert_eq!(app.installed.filter.value(), "ba"); + assert_eq!(app.installed.visible, vec![0]); + app.update(code(KeyCode::Esc), now); + assert!(!app.installed.filter_focused); + assert!(app.installed.filter.value().is_empty()); + assert_eq!(app.installed.visible, vec![0, 1, 2]); + } + + #[test] + fn a_second_esc_clears_the_marks() { + let mut app = installed_app(); + app.update(installed(catalog()), Instant::now()); + let now = Instant::now(); + app.update(key(' '), now); + assert_eq!(app.installed.marks.len(), 1); + app.update(key('/'), now); + app.update(key('b'), now); + app.update(code(KeyCode::Esc), now); + assert!(app.installed.filter.value().is_empty()); + assert_eq!(app.installed.marks.len(), 1); + app.update(code(KeyCode::Esc), now); + assert!(app.installed.marks.is_empty()); + } + + #[test] + fn space_marks_the_row_its_package_is_recorded_under() { + let mut app = installed_app(); + let entries = catalog(); + let first = entries[0].package.id; + app.update(installed(entries), Instant::now()); + let now = Instant::now(); + app.update(key(' '), now); + assert_eq!(app.installed.marks, [first].into_iter().collect()); + assert_eq!(app.installed.cursor.selected, 1); + let screen = screen(&mut app, 100, 24); + assert!(screen.contains("1 marked"), "screen is {screen:?}"); + } + + #[test] + fn cycling_the_sort_shows_its_name_in_the_hint_suffix() { + let mut app = installed_app(); + app.update(installed(catalog()), Instant::now()); + let now = Instant::now(); + assert_eq!( + app.hint_suffix(&Action::CycleSort), + Some(": name".to_string()) + ); + assert!(screen(&mut app, 100, 24).contains("sort: name")); + app.update(key('o'), now); + assert_eq!( + app.hint_suffix(&Action::CycleSort), + Some(": size".to_string()) + ); + app.update(key('o'), now); + assert_eq!( + app.hint_suffix(&Action::CycleSort), + Some(": date".to_string()) + ); + app.update(key('o'), now); + assert_eq!( + app.hint_suffix(&Action::CycleSort), + Some(": name".to_string()) + ); + } + + #[test] + fn broken_inactive_and_pinned_rows_show_their_symbols_and_flags() { + let mut app = installed_app(); + let mut entries = catalog(); + entries[0].is_healthy = false; + entries[1].package.unlinked = true; + entries[2].package.pinned = true; + app.update(installed(entries), Instant::now()); + let screen = screen(&mut app, 110, 24); + for text in ["⚠", "broken", "○", "inactive", "⊙", "pinned"] { + assert!(screen.contains(text), "screen is {screen:?}"); + } + } + + #[test] + fn enter_toggles_the_detail_flag() { + let mut app = installed_app(); + app.update(installed(catalog()), Instant::now()); + let now = Instant::now(); + app.update(code(KeyCode::Enter), now); + assert!(app.installed.detail_open); + app.update(code(KeyCode::Esc), now); + assert!(!app.installed.detail_open); + } + + #[test] + fn enter_without_a_row_opens_nothing() { + let mut app = installed_app(); + app.update(installed(catalog()), Instant::now()); + let now = Instant::now(); + app.update(key('/'), now); + for c in ['x', 'y', 'z'] { + app.update(key(c), now); + } + app.update(code(KeyCode::Enter), now); + assert!(!app.installed.detail_open); + } + + #[test] + fn refiltering_keeps_the_cursor_on_its_package_while_it_is_visible() { + let mut app = installed_app(); + let mut entries = catalog(); + entries[1].package.pkg_name = "ant".to_string(); + entries[2].package.pkg_name = "cat".to_string(); + app.update(installed(entries), Instant::now()); + let now = Instant::now(); + app.update(key('j'), now); + assert_eq!(app.installed.cursor.selected, 1); + app.update(key('/'), now); + for c in ['b', 'a'] { + app.update(key(c), now); + } + assert_eq!(app.installed.visible, vec![0]); + assert_eq!(app.installed.cursor.selected, 0); + app.update(code(KeyCode::Esc), now); + assert_eq!(app.installed.cursor.selected, 1); + } + + #[test] + fn more_rows_than_screen_lines_render_only_the_visible_ones() { + let mut app = installed_app(); + let entries: Vec<_> = (0..50) + .map(|n| installed_entry(&format!("pkg{n:03}"), "1.0.0", "bincache")) + .collect(); + app.update(installed(entries), Instant::now()); + let now = Instant::now(); + for _ in 0..40 { + app.update(key('j'), now); + } + let screen = screen(&mut app, 100, 30); + assert!(screen.contains("pkg040"), "screen is {screen:?}"); + assert!(!screen.contains("pkg000"), "screen is {screen:?}"); + assert!(!screen.contains("pkg049"), "screen is {screen:?}"); + } + + #[test] + fn an_install_date_renders_as_a_relative_age() { + let mut app = installed_app(); + let mut entries = catalog(); + let three_days = chrono::Utc::now() - chrono::Duration::days(3); + entries[0].package.installed_date = three_days.format("%Y-%m-%d %H:%M:%S").to_string(); + app.update(installed(entries), Instant::now()); + let screen = screen(&mut app, 99, 24); + assert!(screen.contains("3 days ago"), "screen is {screen:?}"); + } + + #[test] + fn enter_opens_the_full_screen_detail_and_esc_closes_it_at_narrow_width() { + let mut app = installed_app(); + app.update(installed(catalog()), Instant::now()); + let now = Instant::now(); + app.update(code(KeyCode::Enter), now); + assert!(app.installed.detail_open); + let open = screen(&mut app, 80, 24); + assert!(open.contains("0.24.0"), "screen is {open:?}"); + assert!(!open.contains("NAME"), "screen is {open:?}"); + app.update(code(KeyCode::Esc), now); + assert!(!app.installed.detail_open); + let closed = screen(&mut app, 80, 24); + assert!(closed.contains("NAME"), "screen is {closed:?}"); + } + + #[test] + fn the_side_pane_shows_the_cursor_rows_details_at_full_width() { + let mut app = installed_app(); + let mut entries = catalog(); + entries[0].package.installed_path = "/opt/unique-path/bat".to_string(); + app.update(installed(entries), Instant::now()); + let wide = screen(&mut app, 110, 24); + assert!(wide.contains("/opt/unique-path/bat"), "screen is {wide:?}"); + assert!(wide.contains("NAME"), "screen is {wide:?}"); + let narrow = screen(&mut app, 99, 24); + assert!( + !narrow.contains("/opt/unique-path/bat"), + "screen is {narrow:?}" + ); + } + + #[test] + fn the_detail_pane_titles_and_heads_itself_like_the_catalog_pane() { + let mut app = installed_app(); + let mut entries = catalog(); + entries[0].package.pkg_family = Some("sharkdp".to_string()); + entries[0].package.pkg_type = Some("static".to_string()); + app.update(installed(entries), Instant::now()); + let now = Instant::now(); + app.update(code(KeyCode::Enter), now); + let screen = screen(&mut app, 80, 24); + assert!(screen.contains("sharkdp/bat"), "screen is {screen:?}"); + assert!(screen.contains("0.24.0"), "screen is {screen:?}"); + assert!(screen.contains("static"), "screen is {screen:?}"); + assert!(screen.contains("bincache"), "screen is {screen:?}"); + } + + #[test] + fn a_broken_entry_shows_the_missing_files_banner_when_the_detail_is_open() { + let mut app = installed_app(); + let mut entries = catalog(); + entries[0].is_healthy = false; + app.update(installed(entries), Instant::now()); + let now = Instant::now(); + app.update(code(KeyCode::Enter), now); + let screen = screen(&mut app, 80, 24); + assert!(screen.contains(app.theme.sym().error)); + assert!( + screen.contains("Files are missing. Remove it, or use Health (6) to clean up."), + "screen is {screen:?}" + ); + } + + #[test] + fn a_healthy_entry_shows_no_missing_files_banner() { + let mut app = installed_app(); + app.update(installed(catalog()), Instant::now()); + let now = Instant::now(); + app.update(code(KeyCode::Enter), now); + let screen = screen(&mut app, 80, 24); + assert!( + !screen.contains("Files are missing"), + "screen is {screen:?}" + ); + } + + #[test] + fn the_detail_shows_the_recorded_date_and_the_relative_age() { + let mut app = installed_app(); + let mut entries = catalog(); + let three_days = chrono::Utc::now() - chrono::Duration::days(3); + let date = three_days.format("%Y-%m-%d %H:%M:%S").to_string(); + entries[0].package.installed_date = date.clone(); + app.update(installed(entries), Instant::now()); + let now = Instant::now(); + app.update(code(KeyCode::Enter), now); + let screen = screen(&mut app, 80, 24); + assert!(screen.contains("(3 days ago)"), "screen is {screen:?}"); + assert!(screen.contains(&date), "screen is {screen:?}"); + } + + #[test] + fn the_checksum_is_shortened_with_an_ellipsis() { + let mut app = installed_app(); + let mut entries = catalog(); + let checksum = "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"; + entries[0].package.checksum = Some(checksum.to_string()); + app.update(installed(entries), Instant::now()); + let now = Instant::now(); + app.update(code(KeyCode::Enter), now); + let expected = format::truncate(checksum, 16, app.theme.sym().ellipsis); + let screen = screen(&mut app, 80, 24); + assert!(screen.contains(&expected), "screen is {screen:?}"); + assert!(!screen.contains(checksum), "screen is {screen:?}"); + } + + #[test] + fn portable_directories_show_one_line_each() { + let mut app = installed_app(); + let mut entries = catalog(); + entries[0].package.portable_home = Some("~/.local/share/bat".to_string()); + entries[0].package.portable_cache = Some("~/.cache/bat".to_string()); + app.update(installed(entries), Instant::now()); + let now = Instant::now(); + app.update(code(KeyCode::Enter), now); + let screen = screen(&mut app, 80, 24); + assert!( + screen.contains("home ~/.local/share/bat"), + "screen is {screen:?}" + ); + assert!( + screen.contains("cache ~/.cache/bat"), + "screen is {screen:?}" + ); + } + + #[test] + fn the_flags_row_joins_the_recorded_states() { + let mut app = installed_app(); + let mut entries = catalog(); + entries[0].package.pinned = true; + entries[0].package.detached = true; + entries[0].package.unlinked = true; + app.update(installed(entries), Instant::now()); + let now = Instant::now(); + app.update(code(KeyCode::Enter), now); + let screen = screen(&mut app, 80, 24); + assert!( + screen.contains("pinned, detached, inactive"), + "screen is {screen:?}" + ); + } + + #[test] + fn the_detail_shows_the_profile_the_size_and_the_source() { + let mut app = installed_app(); + let mut entries = catalog(); + entries[0].package.profile = "default".to_string(); + entries[0].disk_size = 5_452_595; + entries[0].package.download_url = Some("https://example.com/bat-0.24.0.tar.gz".to_string()); + app.update(installed(entries), Instant::now()); + let now = Instant::now(); + app.update(code(KeyCode::Enter), now); + let screen = screen(&mut app, 80, 24); + assert!(screen.contains("default"), "screen is {screen:?}"); + assert!(screen.contains("5.2 MiB"), "screen is {screen:?}"); + assert!( + screen.contains("https://example.com/bat-0.24.0.tar.gz"), + "screen is {screen:?}" + ); + } + + #[test] + fn d_on_a_row_opens_a_danger_confirm_naming_the_package() { + let mut app = installed_app(); + let mut entries = catalog(); + entries[0].disk_size = 5_452_595; + app.update(installed(entries), Instant::now()); + let now = Instant::now(); + let effects = app.update(key('d'), now); + assert!(effects.is_empty()); + assert!(matches!(app.overlay, Some(Overlay::Confirm(_)))); + let open = screen(&mut app, 80, 24); + assert!(open.contains("Remove bat"), "screen is {open:?}"); + assert!( + open.contains("bat 0.24.0 bincache 5.2 MiB"), + "screen is {open:?}" + ); + assert!( + open.contains("5.2 MiB will be freed."), + "screen is {open:?}" + ); + } + + #[test] + fn y_on_the_remove_confirm_enqueues_the_job_and_clears_the_marks() { + let mut app = installed_app(); + let entries = catalog(); + let first = entries[0].package.id; + app.update(installed(entries), Instant::now()); + let now = Instant::now(); + app.update(key(' '), now); + assert_eq!(app.installed.marks, [first].into_iter().collect()); + app.update(key('d'), now); + let effects = app.update(key('y'), now); + let [ + Effect::StartJob { + spec: JobSpec::Remove { + packages, + }, + .. + }, + ] = &effects[..] + else { + panic!("expected the removal to start"); + }; + assert_eq!(packages.len(), 1); + assert_eq!(packages[0].pkg_name, "bat"); + assert!(app.installed.marks.is_empty()); + assert!(app.overlay.is_none()); + } + + #[test] + fn two_marked_rows_show_the_plural_title_and_both_names() { + let mut app = installed_app(); + app.update(installed(catalog()), Instant::now()); + let now = Instant::now(); + app.update(key(' '), now); + app.update(key(' '), now); + app.update(key('d'), now); + let open = screen(&mut app, 80, 24); + assert!(open.contains("Remove 2 packages"), "screen is {open:?}"); + assert!( + open.contains("bat 0.24.0 bincache 0.0 B"), + "screen is {open:?}" + ); + assert!( + open.contains("fd 10.2.0 bincache 0.0 B"), + "screen is {open:?}" + ); + let effects = app.update(key('y'), now); + let [ + Effect::StartJob { + spec: JobSpec::Remove { + packages, + }, + .. + }, + ] = &effects[..] + else { + panic!("expected the removal to start"); + }; + assert_eq!(packages.len(), 2); + } + + #[test] + fn esc_on_the_remove_confirm_enqueues_nothing() { + let mut app = installed_app(); + app.update(installed(catalog()), Instant::now()); + let now = Instant::now(); + app.update(key('d'), now); + assert!(matches!(app.overlay, Some(Overlay::Confirm(_)))); + let effects = app.update(code(KeyCode::Esc), now); + assert!(effects.is_empty()); + assert!(app.overlay.is_none()); + assert!(app.jobs.list.is_empty()); + } + + #[test] + fn d_without_a_row_opens_nothing() { + let mut app = installed_app(); + app.update(installed(catalog()), Instant::now()); + let now = Instant::now(); + app.update(key('/'), now); + for c in ['x', 'y', 'z'] { + app.update(key(c), now); + } + app.update(code(KeyCode::Enter), now); + let effects = app.update(key('d'), now); + assert!(effects.is_empty()); + assert!(app.overlay.is_none()); + assert!(app.jobs.list.is_empty()); + } +} diff --git a/crates/soar-tui/src/views/jobs.rs b/crates/soar-tui/src/views/jobs.rs new file mode 100644 index 00000000..154dd051 --- /dev/null +++ b/crates/soar-tui/src/views/jobs.rs @@ -0,0 +1,575 @@ +//! The jobs view: what the queue has run, the selected job's detail, and +//! the log of everything printed. + +use ratatui::{ + Frame, + layout::{Alignment, Constraint, Layout, Rect}, + style::Style, + text::{Line, Span}, + widgets::{Block, BorderType, Paragraph}, +}; + +use crate::{ + app::App, + format, + jobs::{Job, JobState}, + log::LogLevel, + progress::OpRow, + theme::Theme, + views::ViewId, + widgets::{activity, states}, +}; + +/// Which pane of the jobs view holds the cursor. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum JobsFocus { + /// The job list. + #[default] + List, + /// The selected job's detail. + Detail, + /// The log. + Log, +} + +/// The jobs view's cursor state: the selected job, the detail scroll, and +/// which pane holds them. +#[derive(Debug, Default)] +pub(crate) struct JobsView { + /// The selected row of the job list, which shows jobs newest first. + pub(crate) cursor: crate::widgets::scroll::ListCursor, + /// The first detail row shown when the detail is longer than its pane. + pub(crate) detail: crate::widgets::scroll::ListCursor, + /// How many rows the detail held at the last render, so scrolling + /// moves over what the pane actually shows. + pub(crate) detail_rows: usize, + /// The pane that scrolling moves. + pub(crate) focus: JobsFocus, +} + +/// The narrowest terminal that shows the list beside the detail. +const SIDE_BY_SIDE_WIDTH: u16 = 100; + +/// Draws the three panes: the job list and the selected job's detail on +/// top, the log below. +pub(crate) fn render(f: &mut Frame, area: Rect, app: &mut App) { + let [top, log_area] = + Layout::vertical([Constraint::Percentage(60), Constraint::Percentage(40)]).areas(area); + let (list_area, detail_area) = if area.width >= SIDE_BY_SIDE_WIDTH { + let [list, detail] = + Layout::horizontal([Constraint::Percentage(40), Constraint::Percentage(60)]).areas(top); + (list, detail) + } else { + let [list, detail] = + Layout::vertical([Constraint::Percentage(50), Constraint::Percentage(50)]).areas(top); + (list, detail) + }; + + // Panes draw from shared state, so every scroll adjustment happens + // here, before the panes borrow the jobs and the log. + let list_len = app.jobs.list.len(); + let list_height = list_area.height.saturating_sub(2) as usize; + let index = app + .jobs_view + .cursor + .selected + .min(list_len.saturating_sub(1)); + let selected = app.jobs.list.iter().rev().nth(index); + let detail_lines = detail_lines(selected, &app.theme, detail_area.width as usize); + let detail_here = match selected.map(|job| &job.state) { + Some(JobState::Running { + .. + }) => { + selected + .map(|job| job.tracker.active().count()) + .unwrap_or(0) + } + _ => detail_lines.len(), + }; + app.jobs_view.detail_rows = detail_here; + let detail_height = detail_area.height.saturating_sub(2) as usize; + let log_len = app.log.lines.len(); + let log_height = log_area.height.saturating_sub(2) as usize; + + let list_rows = app.jobs_view.cursor.window(list_len, list_height); + let detail_rows = app.jobs_view.detail.window(detail_here, detail_height); + let log_rows = if app.log.follow { + log_len.saturating_sub(log_height)..log_len + } else { + app.log.cursor.window(log_len, log_height) + }; + + // The wheel scrolls the pane under the pointer, so the detail and + // log panes record their rows areas beside the list's. + app.layout.detail = Some(Block::bordered().inner(detail_area)); + app.layout.log = Some(Block::bordered().inner(log_area)); + render_list(f, list_area, app, list_rows); + render_detail(f, detail_area, app, detail_rows, &detail_lines); + render_log(f, log_area, app, log_rows); +} + +/// Draws the job list, newest first, with each job's status and duration. +fn render_list(f: &mut Frame, area: Rect, app: &mut App, rows: std::ops::Range) { + let theme = &app.theme; + let focused = app.jobs_view.focus == JobsFocus::List && app.view == ViewId::Jobs; + let block = Block::bordered() + .border_type(BorderType::Rounded) + .border_style(theme.border(focused)) + .title(pane_title("Jobs", theme)); + let inner = block.inner(area); + f.render_widget(block, area); + let jobs: Vec<&Job> = app.jobs.list.iter().rev().collect(); + if jobs.is_empty() { + states::empty( + f, + inner, + theme, + "No jobs yet. Install, update, or sync something and it shows up here.", + ); + return; + } + app.layout.list = Some((inner, rows.start)); + + let selected_index = app.jobs_view.cursor.selected; + for (row, job) in jobs[rows.clone()].iter().enumerate() { + let rect = Rect { + y: inner.y + row as u16, + height: 1, + ..inner + }; + let line = Line::from(vec![ + Span::styled( + if rows.start + row == selected_index { + "▌" + } else { + " " + }, + theme.cursor_row(), + ), + Span::raw(" "), + status_span(job, app, theme), + Span::raw(" "), + Span::styled(job.title.clone(), theme.text()), + ]); + f.render_widget(Paragraph::new(line), rect); + f.render_widget( + Paragraph::new(duration_span(job, app, theme)).alignment(Alignment::Right), + rect, + ); + } +} + +/// The status glyph of one job row: a spinner while running, a dot while +/// queued or waiting for authorization, and the outcome symbols after. +fn status_span(job: &Job, app: &App, theme: &Theme) -> Span<'static> { + let symbols = theme.sym(); + match &job.state { + JobState::Running { + aborting, .. + } => { + Span::styled( + theme.spinner(app.frame), + if *aborting { + theme.warning() + } else { + theme.accent() + }, + ) + } + JobState::Queued | JobState::Authorizing => Span::styled(symbols.dot, theme.muted()), + JobState::Finished { + outcome, .. + } => { + if outcome.aborted { + Span::styled(symbols.warning, theme.warning()) + } else if outcome.ok { + Span::styled(symbols.installed, theme.success()) + } else { + Span::styled(symbols.error, theme.danger()) + } + } + } +} + +/// The right-aligned duration of one job row: elapsed while running, the +/// word queued while waiting, the word authorizing while the user has not +/// approved the administrator pass yet, and the total once finished. +fn duration_span(job: &Job, app: &App, theme: &Theme) -> Span<'static> { + match &job.state { + JobState::Running { + started, + aborting, + } => { + if *aborting { + Span::styled("aborting", theme.warning()) + } else { + Span::styled( + format::clock(app.now.duration_since(*started)), + theme.muted(), + ) + } + } + JobState::Queued => Span::styled("queued", theme.muted()), + JobState::Authorizing => Span::styled("authorizing", theme.muted()), + JobState::Finished { + started, + ended, + .. + } => Span::styled(format::clock(ended.duration_since(*started)), theme.muted()), + } +} + +/// Draws the selected job: its operations while running, or its headline +/// and report once finished. +fn render_detail( + f: &mut Frame, + area: Rect, + app: &App, + rows: std::ops::Range, + lines: &[Line<'static>], +) { + let theme = &app.theme; + let index = app + .jobs_view + .cursor + .selected + .min(app.jobs.list.len().saturating_sub(1)); + let job = app.jobs.list.iter().rev().nth(index); + let title_text = match job { + None => "Job".to_string(), + Some(job) => job.title.clone(), + }; + let focused = app.jobs_view.focus == JobsFocus::Detail && app.view == ViewId::Jobs; + let block = Block::bordered() + .border_type(BorderType::Rounded) + .border_style(theme.border(focused)) + .title(pane_title(&title_text, theme)); + let inner = block.inner(area); + f.render_widget(block, area); + + let Some(job) = job else { + return; + }; + match &job.state { + JobState::Running { + .. + } => { + let active: Vec<&OpRow> = job.tracker.active().collect(); + for (row, op) in active[rows].iter().enumerate() { + let rect = Rect { + y: inner.y + row as u16, + height: 1, + ..inner + }; + activity::render_op(f, rect, op, theme, inner.width); + } + } + _ => { + let rect = Rect { + height: inner.height, + ..inner + }; + f.render_widget(Paragraph::new(lines[rows].to_vec()), rect); + } + } +} + +/// The report rows of the selected job: its operations while running, or +/// its headline and outcome once finished. +fn detail_lines(job: Option<&Job>, theme: &Theme, width: usize) -> Vec> { + match job { + None => Vec::new(), + Some(job) => { + match &job.state { + JobState::Finished { + outcome, .. + } => { + let mut lines = vec![headline_line(outcome, theme)]; + lines.extend(outcome_lines(outcome, theme, width)); + lines + } + _ => Vec::new(), + } + } + } +} + +/// The first detail row of a finished job, colored by how it went. +fn headline_line(outcome: &crate::jobs::JobOutcome, theme: &Theme) -> Line<'static> { + let style = if outcome.aborted { + theme.warning() + } else if outcome.ok { + theme.success() + } else { + theme.danger() + }; + Line::from(Span::styled(outcome.headline.clone(), style)) +} + +/// The report rows of a finished job: what succeeded, what was skipped, +/// what failed with its full error, and the notes and warnings around it. +fn outcome_lines( + outcome: &crate::jobs::JobOutcome, + theme: &Theme, + width: usize, +) -> Vec> { + use crate::jobs::OutcomeLine; + + let symbols = theme.sym(); + let mut lines = Vec::new(); + let mut notes_started = false; + for entry in &outcome.lines { + match entry { + OutcomeLine::Done(name) => { + lines.push(Line::from(vec![ + Span::styled(symbols.installed, theme.success()), + Span::raw(" "), + Span::styled(name.clone(), theme.text()), + ])) + } + OutcomeLine::Skipped(name) => { + lines.push(Line::from(vec![ + Span::styled(symbols.available, theme.muted()), + Span::raw(" "), + Span::styled(format!("{name} skipped"), theme.muted()), + ])) + } + OutcomeLine::Failed { + name, + error, + } => { + lines.push(Line::from(vec![ + Span::styled(symbols.error, theme.danger()), + Span::raw(" "), + Span::styled(name.clone(), theme.danger()), + ])); + for text in format::wrap(error, width.saturating_sub(4)) { + lines.push(Line::from(Span::styled( + format!(" {text}"), + theme.danger(), + ))); + } + } + OutcomeLine::Note { + name, + text, + } => { + if !notes_started { + notes_started = true; + lines.push(Line::from(Span::styled("Notes", theme.warning()))); + } + lines.push(Line::from(Span::styled( + format!("{name}: {text}"), + theme.text(), + ))); + } + OutcomeLine::Warning(text) => { + lines.push(Line::from(vec![ + Span::styled(symbols.warning, theme.warning()), + Span::raw(" "), + Span::styled(text.clone(), theme.warning()), + ])) + } + } + } + lines +} + +/// Draws the log pane: one row per line, following the newest line unless +/// the user scrolled away from it. +fn render_log(f: &mut Frame, area: Rect, app: &App, rows: std::ops::Range) { + let theme = &app.theme; + let focused = app.jobs_view.focus == JobsFocus::Log && app.view == ViewId::Jobs; + let block = Block::bordered() + .border_type(BorderType::Rounded) + .border_style(theme.border(focused)) + .title(pane_title("Log", theme)); + let inner = block.inner(area); + f.render_widget(block, area); + + let log = &app.log; + if log.lines.is_empty() { + states::empty(f, inner, theme, "Nothing logged yet."); + return; + } + for (row, line) in log.lines.range(rows.clone()).enumerate() { + let mut spans = vec![ + Span::styled(line.time.clone(), theme.muted()), + Span::raw(" "), + ]; + if line.level != LogLevel::Info { + spans.push(Span::styled( + level_tag(line.level), + level_style(line.level, theme), + )); + spans.push(Span::raw(" ")); + } + spans.push(Span::styled( + line.text.clone(), + text_style(line.level, theme), + )); + f.render_widget( + Paragraph::new(Line::from(spans)), + Rect { + y: inner.y + row as u16, + height: 1, + ..inner + }, + ); + } +} + +/// The level word shown in the log pane. +fn level_tag(level: LogLevel) -> &'static str { + match level { + LogLevel::Debug => "DEBUG", + LogLevel::Info => "INFO", + LogLevel::Warn => "WARN", + LogLevel::Error => "ERROR", + } +} + +/// The color of the level tag. +fn level_style(level: LogLevel, theme: &Theme) -> Style { + match level { + LogLevel::Debug | LogLevel::Info => theme.muted(), + LogLevel::Warn => theme.warning(), + LogLevel::Error => theme.danger(), + } +} + +/// The color of the message text. +fn text_style(level: LogLevel, theme: &Theme) -> Style { + match level { + LogLevel::Error => theme.danger(), + _ => theme.text(), + } +} + +/// The title of a pane block. +fn pane_title(text: &str, theme: &Theme) -> Line<'static> { + Line::from(vec![ + Span::raw(" "), + Span::styled(text.to_string(), theme.title()), + Span::raw(" "), + ]) +} + +#[cfg(test)] +mod tests { + use std::time::Instant; + + use crate::{ + app::App, + jobs::{Job, JobKind, JobOutcome, JobState, OutcomeLine}, + progress::Tracker, + test_support::{key, screen, test_app}, + views::ViewId, + }; + + fn finished_failed_app() -> App { + let mut app = test_app(); + app.view = ViewId::Jobs; + let now = Instant::now(); + app.jobs.list.push(Job { + id: 0, + kind: JobKind::Install, + title: "Install 1 package".into(), + state: JobState::Finished { + started: now, + ended: now, + outcome: JobOutcome { + ok: false, + aborted: false, + headline: "Install finished with 1 failure".into(), + lines: vec![OutcomeLine::Failed { + name: "obsidian".into(), + error: "checksum mismatch: expected abc, got def".into(), + }], + }, + }, + spec: None, + tracker: Tracker::default(), + }); + app + } + + #[test] + fn a_finished_failed_job_shows_its_title_and_full_error() { + let mut app = finished_failed_app(); + let screen = screen(&mut app, 110, 30); + assert!(screen.contains("Install 1 package"), "screen is {screen:?}"); + assert!( + screen.contains("Install finished with 1 failure"), + "screen is {screen:?}" + ); + assert!( + screen.contains("checksum mismatch: expected abc, got def"), + "screen is {screen:?}" + ); + } + + #[test] + fn the_empty_state_names_what_lands_here() { + let mut app = test_app(); + app.view = ViewId::Jobs; + let screen = screen(&mut app, 110, 30); + assert!( + screen.contains("No jobs yet. Install, update, or"), + "screen is {screen:?}" + ); + } + + #[test] + fn clearing_finished_jobs_empties_the_list() { + let mut app = finished_failed_app(); + app.update(key('c'), Instant::now()); + assert!(app.jobs.list.is_empty()); + } + + #[test] + fn an_aborting_job_lists_the_word_in_place_of_its_duration() { + let mut app = test_app(); + app.view = ViewId::Jobs; + app.jobs.list.push(Job { + id: 0, + kind: JobKind::Install, + title: "Install 1 package".into(), + state: JobState::Running { + started: Instant::now(), + aborting: true, + }, + spec: None, + tracker: Tracker::default(), + }); + let screen = screen(&mut app, 110, 30); + assert!(screen.contains("aborting"), "screen is {screen:?}"); + } + + #[test] + fn an_authorizing_job_lists_like_a_queued_one_with_a_note() { + let mut app = test_app(); + app.view = ViewId::Jobs; + app.jobs.list.push(Job { + id: 0, + kind: JobKind::ApplySystem, + title: "Apply 2 system packages".into(), + state: JobState::Authorizing, + spec: None, + tracker: Tracker::default(), + }); + let screen = screen(&mut app, 110, 30); + assert!( + screen.contains("Apply 2 system packages"), + "screen is {screen:?}" + ); + assert!(screen.contains("authorizing"), "screen is {screen:?}"); + } + + #[test] + fn wrapping_breaks_at_spaces_and_hard_splits_long_words() { + use crate::format::wrap; + assert_eq!(wrap("aa bb cc", 5), vec!["aa bb", "cc"]); + assert_eq!(wrap("abcdef", 3), vec!["abc", "def"]); + } +} diff --git a/crates/soar-tui/src/views/mod.rs b/crates/soar-tui/src/views/mod.rs new file mode 100644 index 00000000..707fb8db --- /dev/null +++ b/crates/soar-tui/src/views/mod.rs @@ -0,0 +1,99 @@ +//! The views the tab bar switches between. + +pub(crate) mod apply; +pub(crate) mod browse; +pub(crate) mod health; +pub(crate) mod installed; +pub(crate) mod jobs; +pub(crate) mod repos; +pub(crate) mod updates; + +/// One screen of the interface, in tab order. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub(crate) enum ViewId { + /// The package catalog with its filter and detail pane. + Browse, + /// The packages installed in this profile. + Installed, + /// The packages with a newer version available. + Updates, + /// The declarative packages.toml and the changes it would make. + Apply, + /// The enabled repositories and their sync state. + Repos, + /// The checks for a healthy installation. + Health, + /// The running and finished jobs, with their log. + Jobs, +} + +impl ViewId { + /// Every view in tab order. + pub(crate) const ALL: [ViewId; 7] = [ + ViewId::Browse, + ViewId::Installed, + ViewId::Updates, + ViewId::Apply, + ViewId::Repos, + ViewId::Health, + ViewId::Jobs, + ]; + + /// The name shown on the tab. + pub(crate) fn title(self) -> &'static str { + match self { + ViewId::Browse => "Browse", + ViewId::Installed => "Installed", + ViewId::Updates => "Updates", + ViewId::Apply => "Apply", + ViewId::Repos => "Repos", + ViewId::Health => "Health", + ViewId::Jobs => "Jobs", + } + } + + /// The position of this view in [`Self::ALL`]. + pub(crate) fn index(self) -> usize { + match self { + ViewId::Browse => 0, + ViewId::Installed => 1, + ViewId::Updates => 2, + ViewId::Apply => 3, + ViewId::Repos => 4, + ViewId::Health => 5, + ViewId::Jobs => 6, + } + } + + /// The view after this one, wrapping around to the first. + pub(crate) fn next(self) -> ViewId { + Self::ALL[(self.index() + 1) % Self::ALL.len()] + } + + /// The view before this one, wrapping around to the last. + pub(crate) fn prev(self) -> ViewId { + Self::ALL[(self.index() + Self::ALL.len() - 1) % Self::ALL.len()] + } +} + +#[cfg(test)] +mod tests { + use super::ViewId; + + #[test] + fn next_from_jobs_wraps_to_browse() { + assert_eq!(ViewId::Jobs.next(), ViewId::Browse); + } + + #[test] + fn prev_from_browse_wraps_to_jobs() { + assert_eq!(ViewId::Browse.prev(), ViewId::Jobs); + } + + #[test] + fn index_matches_position_in_all() { + for (position, view) in ViewId::ALL.iter().enumerate() { + assert_eq!(view.index(), position); + } + } +} diff --git a/crates/soar-tui/src/views/repos.rs b/crates/soar-tui/src/views/repos.rs new file mode 100644 index 00000000..5c700cee --- /dev/null +++ b/crates/soar-tui/src/views/repos.rs @@ -0,0 +1,528 @@ +//! The repositories view: every configured repository, its state, and +//! when its metadata was last written to disk. + +use std::{ops::Range, time::SystemTime}; + +use ratatui::{ + Frame, + layout::{Alignment, Constraint, Rect}, + style::{Modifier, Style}, + text::{Line, Span}, + widgets::{Block, BorderType, Cell, Row, Table}, +}; + +use crate::{ + app::App, + format, + loadable::Loadable, + theme::Theme, + views::ViewId, + widgets::{scroll::ListCursor, states}, +}; + +/// The width of the name column. +const NAME_WIDTH: usize = 16; + +/// The width of the signed column. +const SIGNED_WIDTH: u16 = 8; + +/// The width of the desktop column. +const DESKTOP_WIDTH: u16 = 8; + +/// The width of the synced column. +const SYNCED_WIDTH: u16 = 14; + +/// One configured repository as the repositories view keeps it. +pub(crate) struct RepoRow { + /// The repository's unique name. + pub(crate) name: String, + /// The URL its metadata is fetched from. + pub(crate) url: String, + /// Whether the repository takes part in searches and installs. + pub(crate) enabled: bool, + /// Whether the repository's metadata is checked against its key. + pub(crate) signed: bool, + /// Whether packages from this repository get desktop entries. + pub(crate) desktop: bool, + /// The interval between syncs as configured, or the default. + #[allow(dead_code)] + pub(crate) sync_interval: String, + /// When the repository's metadata database was last written to disk. + pub(crate) synced: Option, +} + +/// The state of the repositories view. +#[derive(Default)] +pub(crate) struct ReposView { + /// The configured repositories, loaded on the first visit and again + /// after every job that changes them or their metadata. + pub(crate) list: Loadable>, + /// The visible row the cursor sits on. + pub(crate) cursor: ListCursor, +} + +impl ReposView { + /// Starts a fresh load. The last one's rows go when the result + /// arrives. + pub(crate) fn start(&mut self) { + self.list = Loadable::Loading; + } + + /// Adopts a finished load. The cursor stays on its row while the new + /// list still has one. + pub(crate) fn loaded(&mut self, result: Result, String>) { + self.list = match result { + Ok(rows) => Loadable::Ready(rows), + Err(error) => Loadable::Failed(error), + }; + self.cursor.clamp(self.ready_len()); + } + + /// The number of rows in the ready list, zero while it loads. + pub(crate) fn ready_len(&self) -> usize { + self.list.ready().map_or(0, Vec::len) + } + + /// The row the cursor points at, when the list has one. + pub(crate) fn cursor_row(&self) -> Option<&RepoRow> { + self.list + .ready() + .and_then(|rows| rows.get(self.cursor.selected)) + } +} + +/// Draws the repositories view: its border with the count in the title, +/// then the table of repositories or the loading, empty, and error +/// states. +pub(crate) fn render(f: &mut Frame, area: Rect, app: &mut App) { + let rows_height = usize::from(area.height.saturating_sub(3)); + let window = app.repos.cursor.window(app.repos.ready_len(), rows_height); + let block = list_block(&app.repos, &app.theme); + let inner = block.inner(area); + f.render_widget(block, area); + let view = &app.repos; + let theme = &app.theme; + match &view.list { + Loadable::Idle => {} + Loadable::Loading => states::loading(f, inner, theme, app.frame, "Loading repositories"), + Loadable::Failed(error) => states::error(f, inner, theme, error), + Loadable::Ready(rows) if rows.is_empty() => { + states::empty(f, inner, theme, "No repositories. Press a to add one.") + } + Loadable::Ready(rows) => { + let offset = window.start; + let rows_area = render_table(f, inner, rows, window, view.cursor.selected, theme); + app.layout.list = Some((rows_area, offset)); + } + } +} + +/// Draws the table of repositories, one row each, and returns the rect +/// the rows drew into. +fn render_table( + f: &mut Frame, + area: Rect, + rows: &[RepoRow], + window: Range, + selected: usize, + theme: &Theme, +) -> Rect { + let constraints = [ + Constraint::Length(2), + Constraint::Length(NAME_WIDTH as u16), + Constraint::Fill(1), + Constraint::Length(SIGNED_WIDTH), + Constraint::Length(DESKTOP_WIDTH), + Constraint::Length(SYNCED_WIDTH), + ]; + let url_width = url_column_width(area.width, &constraints); + let table = Table::new( + table_rows(rows, window, selected, url_width, theme), + constraints, + ) + .header(header_row(theme)); + f.render_widget(table, area); + Rect { + y: area.y.saturating_add(1), + height: area.height.saturating_sub(1), + ..area + } +} + +/// The width the url column gets: everything the fixed columns and the +/// spacing between them leave over. +fn url_column_width(width: u16, constraints: &[Constraint; 6]) -> usize { + let fixed: u16 = constraints + .iter() + .map(|constraint| { + match constraint { + Constraint::Length(n) => *n, + _ => 0, + } + }) + .sum(); + let spacing = constraints.len().saturating_sub(1) as u16; + usize::from(width.saturating_sub(2).saturating_sub(fixed + spacing)) +} + +/// The column labels in muted bold. The enabled column stays unlabeled. +fn header_row(theme: &Theme) -> Row<'static> { + Row::new(["", "NAME", "URL", "SIGNED", "DESKTOP", "SYNCED"]) + .style(theme.muted().add_modifier(Modifier::BOLD)) +} + +/// Builds the rows the window shows. +fn table_rows( + rows: &[RepoRow], + window: Range, + selected: usize, + url_width: usize, + theme: &Theme, +) -> Vec> { + window + .map(|index| repo_row(&rows[index], index == selected, url_width, theme)) + .collect() +} + +/// One table row. The cursor row takes the cursor highlight across its +/// whole width and starts with the cursor symbol; other rows lead with +/// the enabled state, the marked symbol for enabled repositories and +/// the available symbol for disabled ones, whose name is also muted. +fn repo_row(repo: &RepoRow, cursor_here: bool, url_width: usize, theme: &Theme) -> Row<'static> { + let symbols = theme.sym(); + let lead = if cursor_here { + Span::styled(symbols.cursor.to_string(), theme.cursor_row()) + } else if repo.enabled { + Span::styled(symbols.marked.to_string(), theme.success()) + } else { + Span::styled(symbols.available.to_string(), theme.muted()) + }; + let name_style = if repo.enabled { + theme.text() + } else { + theme.muted() + }; + let style = if cursor_here { + theme.cursor_row() + } else { + Style::new() + }; + Row::new(vec![ + Cell::from(Line::from(vec![lead, Span::raw(" ")])), + Cell::from(Span::styled( + format::truncate(&repo.name, NAME_WIDTH, symbols.ellipsis), + name_style, + )), + Cell::from(Span::styled( + format::truncate_middle(&repo.url, url_width, symbols.ellipsis), + theme.muted(), + )), + bool_cell(repo.signed, theme), + bool_cell(repo.desktop, theme), + Cell::from(Span::styled(synced_text(repo.synced), theme.text())), + ]) + .style(style) +} + +/// The centered mark a boolean column shows: the installed symbol in the +/// success color when true, the error symbol muted when not. +fn bool_cell(value: bool, theme: &Theme) -> Cell<'static> { + let symbols = theme.sym(); + let (symbol, style) = if value { + (symbols.installed, theme.success()) + } else { + (symbols.error, theme.muted()) + }; + Cell::from(Line::from(Span::styled(symbol.to_string(), style)).alignment(Alignment::Center)) +} + +/// When the metadata was last written to disk, as a relative age, or +/// `never` when the repository has not synced yet. +fn synced_text(synced: Option) -> String { + synced.map_or_else( + || "never".to_string(), + |then| format::relative(then, SystemTime::now()), + ) +} + +/// The pane border: the repository count on the left of the top edge. +fn list_block(view: &ReposView, theme: &Theme) -> Block<'static> { + let left = match view.list.ready() { + Some(rows) => Line::styled(format!(" Repositories {} ", rows.len()), theme.title()), + None => Line::styled(format!(" {} ", ViewId::Repos.title()), theme.title()), + }; + Block::bordered() + .border_type(BorderType::Rounded) + .border_style(theme.border(true)) + .title(left) +} + +#[cfg(test)] +mod tests { + use std::time::{Duration, Instant, SystemTime}; + + use crate::{ + effect::Effect, + jobs::{JobOutcome, JobSpec, RepoChange}, + msg::{Loaded, Msg}, + test_support::{ctrl, key, screen, test_app}, + views::{ViewId, repos::RepoRow}, + }; + + /// A loaded repositories list holding the given rows. + fn repos(rows: Vec) -> Msg { + Msg::Loaded(Loaded::Repos(Ok(rows))) + } + + fn failed(message: &str) -> Msg { + Msg::Loaded(Loaded::Repos(Err(message.to_string()))) + } + + /// One repository row with the given name, url, and enabled flag, + /// signed and desktop-integrated, synced two hours ago. + fn repo_row(name: &str, url: &str, enabled: bool) -> RepoRow { + repo_row_synced( + name, + url, + enabled, + Some(SystemTime::now() - Duration::from_secs(2 * 3600 + 30)), + ) + } + + /// One repository row with an explicit last-sync time. + fn repo_row_synced( + name: &str, + url: &str, + enabled: bool, + synced: Option, + ) -> RepoRow { + RepoRow { + name: name.to_string(), + url: url.to_string(), + enabled, + signed: true, + desktop: true, + sync_interval: "3h".to_string(), + synced, + } + } + + /// Three configured repositories, the usual fixtures, the last one + /// disabled. + fn catalog() -> Vec { + vec![ + repo_row( + "bincache", + "https://meta.pkgforge.dev/bincache/metadata.db.zstd", + true, + ), + repo_row( + "pkgcache", + "https://meta.pkgforge.dev/pkgcache/metadata.db.zstd", + true, + ), + repo_row( + "ivan-hc-am", + "https://meta.pkgforge.dev/external/AM/metadata.db.zstd", + false, + ), + ] + } + + /// The repositories view with its rows loaded, where its keys and its + /// pane are live. + fn repos_app(rows: Vec) -> (crate::app::App, Instant) { + let mut app = test_app(); + app.view = ViewId::Repos; + app.update(repos(rows), Instant::now()); + (app, Instant::now()) + } + + fn finished(id: u64, headline: &str) -> Msg { + Msg::JobFinished { + id, + outcome: JobOutcome { + ok: true, + aborted: false, + headline: headline.to_string(), + lines: Vec::new(), + }, + } + } + + #[test] + fn entering_repos_the_first_time_loads_the_list() { + let mut app = test_app(); + let effects = app.update(key('5'), Instant::now()); + let [Effect::LoadRepos] = &effects[..] else { + panic!("expected one load on first entry"); + }; + assert!(app.repos.list.is_loading()); + } + + #[test] + fn reentering_repos_starts_nothing() { + let mut app = test_app(); + let now = Instant::now(); + app.update(key('5'), now); + app.update(repos(catalog()), now); + app.update(key('1'), now); + let effects = app.update(key('5'), now); + assert!(effects.is_empty()); + assert!(app.repos.list.ready().is_some()); + } + + #[test] + fn a_finished_sync_reloads_the_repositories() { + let mut app = test_app(); + let now = Instant::now(); + app.enqueue(JobSpec::Sync, now); + let effects = app.update(finished(0, "Repositories synced"), now); + let [ + Effect::RebuildContext, + Effect::LoadCatalog { + .. + }, + Effect::LoadInstalled { + .. + }, + Effect::LoadRepos, + ] = &effects[..] + else { + panic!("expected the reloads a sync causes"); + }; + assert!(app.repos.list.is_loading()); + } + + #[test] + fn a_finished_repository_change_reloads_the_repositories() { + let mut app = test_app(); + let now = Instant::now(); + app.enqueue(JobSpec::Repo(RepoChange::Remove("old".to_string())), now); + let effects = app.update(finished(0, "Removed repository old"), now); + assert!(matches!( + effects.as_slice(), + [ + Effect::RebuildContext, + Effect::LoadRepos, + Effect::LoadCatalog { .. }, + Effect::LoadInstalled { .. } + ] + )); + } + + #[test] + fn ctrl_r_reloads_the_repositories() { + let (mut app, now) = repos_app(catalog()); + let effects = app.update(ctrl('r'), now); + let [Effect::LoadRepos] = &effects[..] else { + panic!("expected one load on reload"); + }; + assert!(app.repos.list.is_loading()); + } + + #[test] + fn the_title_shows_the_repository_count() { + let (mut app, _) = repos_app(catalog()); + let screen = screen(&mut app, 100, 24); + assert!(screen.contains("Repositories 3"), "screen is {screen:?}"); + } + + #[test] + fn an_empty_list_says_how_to_add_one() { + let (mut app, _) = repos_app(Vec::new()); + let screen = screen(&mut app, 80, 24); + assert!( + screen.contains("No repositories. Press a to add one."), + "screen is {screen:?}" + ); + } + + #[test] + fn a_disabled_row_shows_the_available_symbol() { + let (mut app, _) = repos_app(catalog()); + let screen = screen(&mut app, 110, 24); + assert!(screen.contains('●'), "screen is {screen:?}"); + assert!( + screen.contains(app.theme.sym().available), + "screen is {screen:?}" + ); + } + + #[test] + fn a_repository_never_synced_shows_never() { + let rows = vec![repo_row_synced( + "fresh", + "https://example.com/fresh.db", + true, + None, + )]; + let (mut app, _) = repos_app(rows); + let screen = screen(&mut app, 100, 24); + assert!(screen.contains("never"), "screen is {screen:?}"); + } + + #[test] + fn a_synced_row_shows_a_relative_age() { + let (mut app, _) = repos_app(catalog()); + let screen = screen(&mut app, 110, 24); + assert!(screen.contains("2 hours ago"), "screen is {screen:?}"); + } + + #[test] + fn a_failed_load_shows_the_error_state() { + let mut app = test_app(); + app.view = ViewId::Repos; + app.update(failed("config unreadable"), Instant::now()); + let screen = screen(&mut app, 80, 24); + assert!(screen.contains("config unreadable"), "screen is {screen:?}"); + assert!(screen.contains("ctrl-r to retry"), "screen is {screen:?}"); + } + + #[test] + fn the_table_names_its_columns() { + let (mut app, _) = repos_app(catalog()); + let screen = screen(&mut app, 120, 24); + for label in ["NAME", "URL", "SIGNED", "DESKTOP", "SYNCED"] { + assert!(screen.contains(label), "screen is {screen:?}"); + } + } + + #[test] + fn a_long_url_is_cut_in_the_middle() { + let long = "https://meta.pkgforge.dev/bincache/x86_64-linux/metadata.db.zstd"; + let rows = vec![repo_row("bincache", long, true)]; + let (mut app, _) = repos_app(rows); + let screen = screen(&mut app, 100, 24); + assert!(screen.contains("https://me"), "screen is {screen:?}"); + assert!(screen.contains("db.zstd"), "screen is {screen:?}"); + assert!(!screen.contains(long), "screen is {screen:?}"); + } + + #[test] + fn more_rows_than_screen_lines_render_only_the_visible_ones() { + let rows: Vec<_> = (0..50) + .map(|n| repo_row(&format!("repo{n:03}"), "https://example.com/db", true)) + .collect(); + let (mut app, now) = repos_app(rows); + for _ in 0..40 { + app.update(key('j'), now); + } + let screen = screen(&mut app, 100, 30); + assert!(screen.contains("repo040"), "screen is {screen:?}"); + assert!(!screen.contains("repo000"), "screen is {screen:?}"); + assert!(!screen.contains("repo049"), "screen is {screen:?}"); + } + + #[test] + fn a_reload_keeps_the_cursor_on_its_row_while_the_list_shrinks() { + let rows: Vec<_> = (0..10) + .map(|n| repo_row(&format!("repo{n}"), "https://example.com/db", true)) + .collect(); + let (mut app, now) = repos_app(rows); + app.update(key('G'), now); + assert_eq!(app.repos.cursor.selected, 9); + app.update(repos(catalog()), now); + assert_eq!(app.repos.cursor.selected, 2); + } +} diff --git a/crates/soar-tui/src/views/updates.rs b/crates/soar-tui/src/views/updates.rs new file mode 100644 index 00000000..697c2184 --- /dev/null +++ b/crates/soar-tui/src/views/updates.rs @@ -0,0 +1,806 @@ +//! The available updates view: its table, the marks, the keep-old flag, +//! and the skipped list. + +use std::collections::HashSet; + +use ratatui::{ + Frame, + layout::{Alignment, Constraint, Layout, Rect}, + style::{Modifier, Style}, + text::{Line, Span}, + widgets::{Block, BorderType, Cell, List, ListItem, Row, Table}, +}; +use soar_operations::UpdateInfo; + +use crate::{ + app::App, + format, + loadable::Loadable, + theme::Theme, + views::ViewId, + widgets::{scroll::ListCursor, states}, +}; + +/// The state of the available updates view. +#[derive(Default)] +pub(crate) struct UpdatesView { + /// The checked updates, loaded on the first visit and again on every + /// manual recheck. + pub(crate) list: Loadable>, + /// How many packages the running check has reported on so far. + pub(crate) checked: usize, + /// Packages the running check passed over, each with why. + pub(crate) skipped: Vec<(String, String)>, + /// Whether the skipped list replaces the table. + pub(crate) show_skipped: bool, + /// The visible row the cursor sits on. + pub(crate) cursor: ListCursor, + /// The rows marked for the next update, by index into the ready list. + /// The indexes move on every load, so the marks clear with it. + pub(crate) marks: HashSet, + /// Whether superseded versions stay on disk during an update. + pub(crate) keep_old: bool, + /// The packages a check is limited to, when it was started for a + /// selection made in another view. + pub(crate) scope: Option>, + /// The number of the check in flight. Every start numbers itself so a + /// result from a check a newer one replaced can be dropped. + pub(crate) check: u32, + /// Whether the check in flight replaced one that was still running, + /// so its unnumbered events could have landed in the live counters. + /// The next load cannot tell those strays from the newest check's + /// own progress and drops the lot. + superseded: bool, +} + +impl UpdatesView { + /// Starts a fresh check: the count and the skipped list of the last + /// one go, and the marks and cursor go when the result arrives. + /// A check that replaces one still running marks the progress + /// suspect, since the old check's events keep landing while both + /// run. + pub(crate) fn start_check(&mut self) { + self.superseded = self.list.is_loading(); + self.list = Loadable::Loading; + self.checked = 0; + self.skipped.clear(); + self.check = self.check.wrapping_add(1); + } + + /// Adopts a finished check. The marks and the cursor reset because + /// the rows they pointed at have moved. The check's own skipped + /// list stays for the S key, unless the check replaced one still + /// running: the two checks' events were indistinguishable while + /// they overlapped, so that progress cannot be trusted and goes. + pub(crate) fn loaded(&mut self, result: Result, String>) { + self.list = match result { + Ok(updates) => Loadable::Ready(updates), + Err(error) => Loadable::Failed(error), + }; + self.marks.clear(); + self.cursor = ListCursor::default(); + if self.superseded { + self.checked = 0; + self.skipped.clear(); + self.show_skipped = false; + self.superseded = false; + } + } + + /// Marks or unmarks the row under the cursor, then moves one row down. + pub(crate) fn toggle_mark(&mut self) { + let len = self.ready_len(); + if len == 0 { + return; + } + let index = self.cursor.selected; + if !self.marks.remove(&index) { + self.marks.insert(index); + } + self.cursor.down(1, len); + } + + /// Marks every row, or clears the marks when every row is marked. + pub(crate) fn mark_all(&mut self) { + let len = self.ready_len(); + if len == 0 { + return; + } + if self.marks.len() == len { + self.marks.clear(); + } else { + self.marks = (0..len).collect(); + } + } + + /// The number of rows in the ready list, zero while it loads. + pub(crate) fn ready_len(&self) -> usize { + self.list.ready().map_or(0, Vec::len) + } +} + +/// Draws the updates view: its border with the count and the keep-old +/// flag in the title, then the table, the checking and skipped states, or +/// the up-to-date and error states. +pub(crate) fn render(f: &mut Frame, area: Rect, app: &mut App) { + // The skipped-note row leaves one less row for the table, so the + // window must shrink with it or the bottom row hides below it. + let note = u16::from(!app.updates.skipped.is_empty()); + let rows_height = usize::from(area.height.saturating_sub(3 + note)); + let window = app + .updates + .cursor + .window(app.updates.ready_len(), rows_height); + let block = list_block(&app.updates, &app.theme, area.width); + let inner = block.inner(area); + f.render_widget(block, area); + let view = &app.updates; + let theme = &app.theme; + match &view.list { + Loadable::Idle => {} + Loadable::Loading => { + let text = format!("Checking {}{}", view.checked, theme.sym().ellipsis); + states::loading(f, inner, theme, app.frame, &text); + } + Loadable::Failed(error) => states::error(f, inner, theme, error), + Loadable::Ready(list) if list.is_empty() => render_up_to_date(f, inner, view, theme), + Loadable::Ready(_) if view.show_skipped && !view.skipped.is_empty() => { + render_skipped(f, inner, view, theme); + } + Loadable::Ready(list) => { + let offset = window.start; + let rows = render_table(f, inner, view, list, window, theme); + app.layout.list = Some((rows, offset)); + } + } +} + +/// Draws the success state saying nothing needs an update, with the +/// skipped count on a line under it when the check passed any over. +fn render_up_to_date(f: &mut Frame, area: Rect, view: &UpdatesView, theme: &Theme) { + if view.skipped.is_empty() { + states::success(f, area, theme, "Everything is up to date"); + return; + } + let [state, note] = Layout::vertical([Constraint::Fill(1), Constraint::Length(1)]).areas(area); + states::success(f, state, theme, "Everything is up to date"); + f.render_widget(skipped_note(view, theme), note); +} + +/// Draws the checked updates table, with the skipped count on a line +/// under it when the check passed any over, and returns the rect the +/// rows drew into. +fn render_table( + f: &mut Frame, + area: Rect, + view: &UpdatesView, + list: &[UpdateInfo], + window: std::ops::Range, + theme: &Theme, +) -> Rect { + let (table_area, note_area) = if view.skipped.is_empty() { + (area, None) + } else { + let [top, bottom] = + Layout::vertical([Constraint::Fill(1), Constraint::Length(1)]).areas(area); + (top, Some(bottom)) + }; + let constraints = [ + Constraint::Length(2), + Constraint::Fill(1), + Constraint::Length(14), + Constraint::Length(4), + Constraint::Length(14), + Constraint::Length(12), + Constraint::Length(10), + ]; + let name_width = name_column_width(table_area.width, &constraints); + let table = Table::new( + table_rows(view, list, window, name_width, theme), + constraints, + ) + .header(header_row(theme)); + f.render_widget(table, table_area); + if let Some(note) = note_area { + f.render_widget(skipped_note(view, theme), note); + } + Rect { + y: table_area.y.saturating_add(1), + height: table_area.height.saturating_sub(1), + ..table_area + } +} + +/// The width the name column gets: everything the fixed columns and the +/// spacing between them leave over. +fn name_column_width(width: u16, constraints: &[Constraint; 7]) -> usize { + let fixed: u16 = constraints + .iter() + .map(|constraint| { + match constraint { + Constraint::Length(n) => *n, + _ => 0, + } + }) + .sum(); + let spacing = constraints.len().saturating_sub(1) as u16; + usize::from(width.saturating_sub(2).saturating_sub(fixed + spacing)) +} + +/// The column labels in muted bold. The arrow column stays unlabeled. +fn header_row(theme: &Theme) -> Row<'static> { + Row::new(["", "NAME", "CURRENT", "", "NEW", "REPO", "SIZE"]) + .style(theme.muted().add_modifier(Modifier::BOLD)) +} + +/// Builds the rows the window shows: the mark, the name, the two +/// versions with the arrow between them, the repository, and the size. +fn table_rows( + view: &UpdatesView, + list: &[UpdateInfo], + window: std::ops::Range, + name_width: usize, + theme: &Theme, +) -> Vec> { + window + .map(|index| { + update_row( + &list[index], + view.marks.contains(&index), + index == view.cursor.selected, + name_width, + theme, + ) + }) + .collect() +} + +/// One table row. The cursor row takes the cursor highlight across its +/// whole width and starts with the cursor symbol; a marked row starts with +/// the marked symbol. +fn update_row( + info: &UpdateInfo, + marked: bool, + cursor_here: bool, + name_width: usize, + theme: &Theme, +) -> Row<'static> { + let symbols = theme.sym(); + let lead = if cursor_here { + Span::styled(symbols.cursor.to_string(), theme.cursor_row()) + } else if marked { + Span::styled(symbols.marked.to_string(), theme.marked()) + } else { + Span::raw(" ") + }; + let name = format::truncate(&info.pkg_name, name_width, symbols.ellipsis); + let size = info + .target + .package + .ghcr_size + .or(info.target.package.size) + .unwrap_or(0); + let style = if cursor_here { + theme.cursor_row() + } else { + Style::new() + }; + Row::new(vec![ + Cell::from(Line::from(vec![lead, Span::raw(" ")])), + Cell::from(Span::styled(name, theme.text())), + Cell::from(Span::styled(info.current_version.clone(), theme.danger())), + Cell::from( + Line::from(Span::styled(symbols.arrow.to_string(), theme.muted())) + .alignment(Alignment::Center), + ), + Cell::from(Span::styled(info.new_version.clone(), theme.success())), + Cell::from(Span::styled(info.repo_name.clone(), theme.info())), + Cell::from(Line::from(Span::raw(format::size(size))).alignment(Alignment::Right)), + ]) + .style(style) +} + +/// Draws the skipped packages as `name reason` rows, one per line. +fn render_skipped(f: &mut Frame, area: Rect, view: &UpdatesView, theme: &Theme) { + let rows: Vec> = view + .skipped + .iter() + .map(|(name, reason)| { + ListItem::new(Line::from(vec![ + Span::styled(name.clone(), theme.text()), + Span::raw(" "), + Span::styled(reason.clone(), theme.muted()), + ])) + }) + .collect(); + f.render_widget(List::new(rows), area); +} + +/// The line telling how many packages the check passed over and that `S` +/// shows them. +fn skipped_note(view: &UpdatesView, theme: &Theme) -> Line<'static> { + Line::styled( + format!(" {} skipped (press S to show)", view.skipped.len()), + theme.muted(), + ) +} + +/// The pane border: the update count and the scoped-selection count on +/// the left of the top edge, and the keep-old flag on its right. +fn list_block(view: &UpdatesView, theme: &Theme, width: u16) -> Block<'static> { + let left = match (&view.list, &view.scope) { + (Loadable::Ready(list), Some(scope)) => { + Line::styled( + format!( + " Updates {} {} {} selected ", + list.len(), + theme.sym().dot, + scope.len() + ), + theme.title(), + ) + } + (Loadable::Ready(list), None) => { + Line::styled(format!(" Updates {} ", list.len()), theme.title()) + } + _ => Line::styled(format!(" {} ", ViewId::Updates.title()), theme.title()), + }; + let budget = usize::from(width).saturating_sub(2 + left.width()); + let block = Block::bordered() + .border_type(BorderType::Rounded) + .border_style(theme.border(true)) + .title(left); + if budget > 0 { + block.title_top(keep_old_line(view, theme, budget).right_aligned()) + } else { + block + } +} + +/// The right end of the top border: whether updates keep the old versions +/// on disk, dropped when the title leaves no room for it. +fn keep_old_line(view: &UpdatesView, theme: &Theme, budget: usize) -> Line<'static> { + let state = if view.keep_old { "on" } else { "off" }; + let mut line = Line::styled(format!(" keep old versions: {state} "), theme.muted()); + if line.width() > budget { + line.spans.clear(); + } + line +} + +#[cfg(test)] +mod tests { + use std::time::Instant; + + use soar_events::{SoarEvent, UpdateCheckStatus}; + use soar_operations::UpdateInfo; + + use crate::{ + app::App, + effect::Effect, + msg::{Loaded, Msg}, + test_support::{ctrl, key, screen, test_app, update_info}, + }; + + /// A ready list holding the given updates, answering the current + /// check. + fn updates(app: &App, list: Vec) -> Msg { + Msg::Loaded(Loaded::Updates { + check: app.updates.check, + result: Ok(list), + }) + } + + fn failed(app: &App, message: &str) -> Msg { + Msg::Loaded(Loaded::Updates { + check: app.updates.check, + result: Err(message.to_string()), + }) + } + + /// One `UpdateCheck` event for the named package. + fn checked(name: &str, status: UpdateCheckStatus) -> Msg { + Msg::Soar(SoarEvent::UpdateCheck { + pkg_name: name.to_string(), + status, + }) + } + + /// Two checked updates, the usual fixtures, the first one with a + /// recorded download size. + fn two_updates() -> Vec { + let mut list = vec![ + update_info("bat", "0.23.0", "0.24.0", "bincache"), + update_info("fd", "10.1.0", "10.2.0", "bincache"), + ]; + list[0].target.package.ghcr_size = Some(5_452_595); + list + } + + fn now() -> Instant { + Instant::now() + } + + #[test] + fn the_last_row_stays_visible_alongside_the_skipped_note() { + let mut app = test_app(); + let now = Instant::now(); + app.update(key('3'), now); + let many: Vec = (0..30) + .map(|n| update_info(&format!("pkg{n}"), "1.0.0", "2.0.0", "bincache")) + .collect(); + app.update( + checked( + "pinned", + UpdateCheckStatus::Skipped { + reason: "pinned".to_string(), + }, + ), + now, + ); + app.update(updates(&app, many), now); + app.update(key('G'), now); + let open = screen(&mut app, 80, 24); + assert!( + open.contains("pkg29"), + "the selected last row must be on screen, screen is {open:?}" + ); + assert!(open.contains("skipped"), "the note row is present"); + } + + #[test] + fn list_keys_do_not_reach_the_table_while_the_skipped_list_shows() { + let mut app = test_app(); + let now = Instant::now(); + app.update(key('3'), now); + app.update( + checked( + "pinned", + UpdateCheckStatus::Skipped { + reason: "pinned".to_string(), + }, + ), + now, + ); + app.update(updates(&app, two_updates()), now); + app.update(key('S'), now); + app.update(key('j'), now); + app.update(key(' '), now); + assert_eq!(app.updates.cursor.selected, 0, "the hidden table stays put"); + assert!( + app.updates.marks.is_empty(), + "marks cannot land on hidden rows" + ); + app.update(key('u'), now); + assert!( + app.overlay.is_none(), + "an update cannot be driven from off screen" + ); + } + + #[test] + fn entering_updates_the_first_time_starts_a_check() { + let mut app = test_app(); + let effects = app.update(key('3'), now()); + let [ + Effect::CheckUpdates { + names: scope, .. + }, + ] = &effects[..] + else { + panic!("expected one check on first entry"); + }; + assert_eq!(scope, &None); + assert!(app.updates.list.is_loading()); + assert_eq!(app.updates.checked, 0); + assert!(app.updates.skipped.is_empty()); + } + + #[test] + fn reentering_updates_starts_nothing() { + let mut app = test_app(); + app.update(key('3'), now()); + app.update(key('1'), now()); + let effects = app.update(key('3'), now()); + assert!(effects.is_empty()); + } + + #[test] + fn three_check_events_raise_the_count_to_three() { + let mut app = test_app(); + app.update(key('3'), now()); + for _ in 0..3 { + app.update( + checked( + "bat", + UpdateCheckStatus::UpToDate { + version: "0.24.0".to_string(), + }, + ), + now(), + ); + } + assert_eq!(app.updates.checked, 3); + } + + #[test] + fn check_events_stop_counting_once_the_result_arrived() { + let mut app = test_app(); + app.update(key('3'), now()); + app.update(updates(&app, Vec::new()), now()); + app.update( + checked( + "bat", + UpdateCheckStatus::UpToDate { + version: "0.24.0".to_string(), + }, + ), + now(), + ); + assert_eq!(app.updates.checked, 0); + } + + #[test] + fn a_skipped_event_records_the_reason() { + let mut app = test_app(); + app.update(key('3'), now()); + app.update( + checked( + "yq", + UpdateCheckStatus::Skipped { + reason: "pinned".to_string(), + }, + ), + now(), + ); + assert_eq!( + app.updates.skipped, + vec![("yq".to_string(), "pinned".to_string())] + ); + } + + #[test] + fn a_finished_check_clears_the_marks_and_the_cursor() { + let mut app = test_app(); + app.update(key('3'), now()); + app.update(updates(&app, two_updates()), now()); + app.update(key(' '), now()); + app.update(key('G'), now()); + assert!(!app.updates.marks.is_empty()); + app.update(updates(&app, two_updates()), now()); + assert!(app.updates.marks.is_empty()); + assert_eq!(app.updates.cursor.selected, 0); + } + + #[test] + fn a_load_that_replaced_a_running_check_drops_its_progress() { + let mut app = test_app(); + app.update(key('3'), now()); + app.update( + checked( + "pinned", + UpdateCheckStatus::Skipped { + reason: "pinned".to_string(), + }, + ), + now(), + ); + // The reload replaces a check still in flight, whose events keep + // landing in the live counters with no number to tell them by. + app.update(ctrl('r'), now()); + app.update( + checked( + "pinned", + UpdateCheckStatus::Skipped { + reason: "pinned".to_string(), + }, + ), + now(), + ); + assert_eq!(app.updates.checked, 1); + assert!(!app.updates.skipped.is_empty()); + app.updates.show_skipped = true; + app.update(updates(&app, two_updates()), now()); + assert_eq!(app.updates.checked, 0); + assert!(app.updates.skipped.is_empty()); + assert!(!app.updates.show_skipped); + } + + #[test] + fn a_failed_check_shows_the_error_state() { + let mut app = test_app(); + app.update(key('3'), now()); + app.update(failed(&app, "metadata missing"), now()); + let screen = screen(&mut app, 80, 24); + assert!(screen.contains("metadata missing"), "screen is {screen:?}"); + assert!(screen.contains("ctrl-r to retry"), "screen is {screen:?}"); + } + + #[test] + fn ctrl_r_checks_again_with_the_current_scope() { + let mut app = test_app(); + app.update(key('3'), now()); + app.update(updates(&app, two_updates()), now()); + app.updates.scope = Some(vec!["bat".to_string()]); + let effects = app.update(ctrl('r'), now()); + let [ + Effect::CheckUpdates { + names, .. + }, + ] = &effects[..] + else { + panic!("expected one check on reload"); + }; + assert_eq!(names, &Some(vec!["bat".to_string()])); + assert!(app.updates.list.is_loading()); + } + + #[test] + fn the_badge_counts_the_ready_updates() { + let mut app = test_app(); + assert_eq!(app.updates_badge(), None); + app.update(key('3'), now()); + app.update(updates(&app, two_updates()), now()); + assert_eq!(app.updates_badge(), Some(2)); + } + + #[test] + fn space_marks_the_row_under_the_cursor_by_index() { + let mut app = test_app(); + app.update(key('3'), now()); + app.update(updates(&app, two_updates()), now()); + app.update(key(' '), now()); + assert_eq!(app.updates.marks, [0].into_iter().collect()); + assert_eq!(app.updates.cursor.selected, 1); + } + + #[test] + fn mark_all_marks_every_row_and_a_second_press_clears_them() { + let mut app = test_app(); + app.update(key('3'), now()); + app.update(updates(&app, two_updates()), now()); + app.update(key('a'), now()); + assert_eq!(app.updates.marks, [0, 1].into_iter().collect()); + app.update(key('a'), now()); + assert!(app.updates.marks.is_empty()); + } + + #[test] + fn o_toggles_the_keep_old_flag_in_the_border() { + let mut app = test_app(); + app.update(key('3'), now()); + app.update(updates(&app, two_updates()), now()); + assert!(screen(&mut app, 100, 24).contains("keep old versions: off")); + app.update(key('o'), now()); + let screen = screen(&mut app, 100, 24); + assert!( + screen.contains("keep old versions: on"), + "screen is {screen:?}" + ); + } + + #[test] + fn two_updates_render_both_new_versions_and_the_arrow() { + let mut app = test_app(); + app.update(key('3'), now()); + app.update(updates(&app, two_updates()), now()); + let screen = screen(&mut app, 100, 24); + assert!(screen.contains("0.24.0"), "screen is {screen:?}"); + assert!(screen.contains("10.2.0"), "screen is {screen:?}"); + assert!( + screen.contains(app.theme.sym().arrow), + "screen is {screen:?}" + ); + assert!(screen.contains("Updates 2"), "screen is {screen:?}"); + assert!(screen.contains("5.2 MiB"), "screen is {screen:?}"); + } + + #[test] + fn the_table_names_its_columns() { + let mut app = test_app(); + app.update(key('3'), now()); + app.update(updates(&app, two_updates()), now()); + let screen = screen(&mut app, 120, 24); + for label in ["NAME", "CURRENT", "NEW", "REPO", "SIZE"] { + assert!(screen.contains(label), "screen is {screen:?}"); + } + } + + #[test] + fn the_title_shows_the_scoped_selection_count() { + let mut app = test_app(); + app.update(key('3'), now()); + app.update(updates(&app, two_updates()), now()); + app.updates.scope = Some(vec!["bat".to_string(), "fd".to_string()]); + let screen = screen(&mut app, 100, 24); + assert!(screen.contains("2 selected"), "screen is {screen:?}"); + } + + #[test] + fn an_empty_check_shows_the_up_to_date_state() { + let mut app = test_app(); + app.update(key('3'), now()); + app.update(updates(&app, Vec::new()), now()); + let screen = screen(&mut app, 80, 24); + assert!( + screen.contains("Everything is up to date"), + "screen is {screen:?}" + ); + } + + #[test] + fn the_loading_state_shows_the_running_count() { + let mut app = test_app(); + app.update(key('3'), now()); + app.update( + checked( + "bat", + UpdateCheckStatus::UpToDate { + version: "0.24.0".to_string(), + }, + ), + now(), + ); + app.update( + checked( + "fd", + UpdateCheckStatus::Available { + current_version: "10.1.0".to_string(), + new_version: "10.2.0".to_string(), + }, + ), + now(), + ); + let screen = screen(&mut app, 80, 24); + assert!(screen.contains("Checking 2"), "screen is {screen:?}"); + assert!(!screen.contains("0.24.0"), "screen is {screen:?}"); + } + + #[test] + fn the_skipped_count_sits_under_the_table_until_s_shows_the_list() { + let mut app = test_app(); + app.update(key('3'), now()); + app.update( + checked( + "pinned-pkg", + UpdateCheckStatus::Skipped { + reason: "held back".to_string(), + }, + ), + now(), + ); + let mut list = two_updates(); + list.push(update_info("yq", "4.44.2", "4.44.3", "bincache")); + app.update(updates(&app, list), now()); + let rendered = screen(&mut app, 100, 24); + assert!( + rendered.contains("1 skipped (press S to show)"), + "screen is {rendered:?}" + ); + assert!(!rendered.contains("held back"), "screen is {rendered:?}"); + app.update(key('S'), now()); + let rendered = screen(&mut app, 100, 24); + assert!(rendered.contains("pinned-pkg"), "screen is {rendered:?}"); + assert!(rendered.contains("held back"), "screen is {rendered:?}"); + app.update(key('S'), now()); + let rendered = screen(&mut app, 100, 24); + assert!(!rendered.contains("held back"), "screen is {rendered:?}"); + } + + #[test] + fn more_rows_than_screen_lines_render_only_the_visible_ones() { + let mut app = test_app(); + app.update(key('3'), now()); + let list: Vec<_> = (0..50) + .map(|n| update_info(&format!("pkg{n:03}"), "1.0.0", "1.1.0", "bincache")) + .collect(); + app.update(updates(&app, list), now()); + for _ in 0..40 { + app.update(key('j'), now()); + } + let screen = screen(&mut app, 100, 30); + assert!(screen.contains("pkg040"), "screen is {screen:?}"); + assert!(!screen.contains("pkg000"), "screen is {screen:?}"); + assert!(!screen.contains("pkg049"), "screen is {screen:?}"); + } +} diff --git a/crates/soar-tui/src/widgets/activity.rs b/crates/soar-tui/src/widgets/activity.rs new file mode 100644 index 00000000..6344e9e4 --- /dev/null +++ b/crates/soar-tui/src/widgets/activity.rs @@ -0,0 +1,616 @@ +//! The live job strip above the status bar, showing what runs from any +//! view. + +use ratatui::{ + Frame, + layout::{Alignment, Rect}, + style::Modifier, + text::{Line, Span}, + widgets::Paragraph, +}; + +use crate::{ + app::App, + format, + jobs::{Job, JobKind, JobState}, + progress::{OpRow, Phase}, + theme::Theme, + widgets::gauge, +}; + +/// How many operation lines the strip shows before folding the rest into a +/// count. +const MAX_OP_LINES: usize = 4; + +/// How wide a progress gauge tries to be before it yields space to text. +const GAUGE_WIDTH: u16 = 24; + +/// Draws the strip: a separating rule, the job's headline with its overall +/// progress, and up to four operation lines. +pub(crate) fn render(f: &mut Frame, area: Rect, app: &App) { + let theme = &app.theme; + let mut rows = Rows::new(area); + + let rule = rows.next(area.width); + f.render_widget( + Paragraph::new(Span::styled( + theme.sym().gauge_empty.repeat(area.width as usize), + theme.muted(), + )), + rule, + ); + + if let Some(job) = app.running_job() { + render_summary(f, rows.next(area.width), job, app); + if job.kind == JobKind::Sync { + let syncing: Vec<&(String, String)> = job.tracker.sync.iter().collect(); + for (repo, stage) in syncing.iter().take(MAX_OP_LINES) { + render_sync(f, rows.next(area.width), repo, stage, theme); + } + if syncing.len() > MAX_OP_LINES { + let text = format!("+{} more", syncing.len() - MAX_OP_LINES); + f.render_widget( + Paragraph::new(text).style(theme.muted()), + rows.next(area.width), + ); + } + } else { + let active: Vec<&OpRow> = job.tracker.active().collect(); + for op in active.iter().take(MAX_OP_LINES) { + render_op(f, rows.next(area.width), op, theme, area.width); + } + if active.len() > MAX_OP_LINES { + let text = format!("+{} more", active.len() - MAX_OP_LINES); + f.render_widget( + Paragraph::new(text).style(theme.muted()), + rows.next(area.width), + ); + } + } + } else if let Some((job, _)) = app + .jobs + .list + .iter() + .filter_map(|job| { + match &job.state { + JobState::Finished { + ended, .. + } => Some((job, ended)), + _ => None, + } + }) + .max_by_key(|(_, ended)| *ended) + { + render_finished(f, rows.next(area.width), job, theme); + } else { + render_background(f, &mut rows, app, area.width); + } +} + +/// One repository line while a sync job runs: the repository name, then +/// its stage, with the finished stages in the success color. +fn render_sync(f: &mut Frame, row: Rect, repo: &str, stage: &str, theme: &Theme) { + let symbols = theme.sym(); + let name = format::truncate(repo, 12, symbols.ellipsis); + let mut line = vec![ + Span::raw(" "), + Span::styled(format!("{name:<12}"), theme.text()), + ]; + if matches!(stage, "done" | "up to date") { + line.push(Span::styled(stage.to_string(), theme.success())); + } else { + line.push(Span::styled(stage.to_string(), theme.muted())); + } + f.render_widget(Paragraph::new(Line::from(line)), row); +} + +/// The background lines: one per repository still syncing, then one +/// summary line while other soar work runs outside the queue. +fn render_background(f: &mut Frame, rows: &mut Rows, app: &App, width: u16) { + let theme = &app.theme; + let syncing: Vec<&(String, String)> = app.background.active_sync().collect(); + for (repo, stage) in syncing.iter().take(MAX_OP_LINES) { + let line = Line::from(vec![ + Span::raw(" "), + Span::styled("Syncing ", theme.muted()), + Span::styled(repo.clone(), theme.info()), + Span::raw(": "), + Span::styled(stage.clone(), theme.muted()), + ]); + f.render_widget(Paragraph::new(line), rows.next(width)); + } + if syncing.len() > MAX_OP_LINES { + let text = format!("+{} more", syncing.len() - MAX_OP_LINES); + f.render_widget(Paragraph::new(text).style(theme.muted()), rows.next(width)); + } + if let Some(op) = app.background.active().next() { + let line = Line::from(vec![ + Span::raw(" "), + Span::styled(theme.spinner(app.frame), theme.accent()), + Span::raw(" "), + Span::styled("Preparing ", theme.muted()), + Span::styled(op.name.clone(), theme.text()), + ]); + f.render_widget(Paragraph::new(line), rows.next(width)); + } +} + +/// The summary line: spinner, title, overall gauge, counts, and the abort +/// hint on the right. +fn render_summary(f: &mut Frame, row: Rect, job: &Job, app: &App) { + let theme = &app.theme; + let JobState::Running { + aborting, .. + } = job.state + else { + return; + }; + let symbols = theme.sym(); + + let spinner_style = if aborting { + theme.warning() + } else { + theme.accent() + }; + let mut left = vec![ + Span::raw(" "), + Span::styled(theme.spinner(app.frame), spinner_style), + Span::raw(" "), + Span::styled(job.title.clone(), theme.title()), + ]; + + let hint = if aborting { + Some(Line::from(Span::styled( + format!("aborting{}", symbols.ellipsis), + theme.warning(), + ))) + } else if job.kind != JobKind::Sync { + Some(Line::from(Span::styled("ctrl-x abort", theme.muted()))) + } else { + None + }; + let hint_width = hint.as_ref().map_or(0, Line::width) as u16; + + let mut fits = row.width.saturating_sub(hint_width + 1) as usize; + if let Some(ratio) = job_ratio(job) { + let gauge_width = GAUGE_WIDTH.min(fits.saturating_sub(2) as u16); + if gauge_width > 3 { + left.push(Span::raw(" ")); + left.extend(gauge::line(ratio, gauge_width, theme).spans); + fits = fits.saturating_sub(gauge_width as usize + 2); + } + } + + for (i, part) in job_counts(job, app, theme).into_iter().enumerate() { + let separator = if i == 0 { " " } else { " · " }; + let width = Span::raw(separator).width() + part.width(); + if width > fits { + break; + } + left.push(Span::styled(separator, theme.muted())); + left.push(part); + fits -= width; + } + + f.render_widget(Paragraph::new(Line::from(left)), row); + if let Some(hint) = hint { + f.render_widget(Paragraph::new(hint).alignment(Alignment::Right), row); + } +} + +/// The overall progress parts of the summary line: the counts when a batch +/// runs, then the queue depth. Trailing parts drop off a narrow screen +/// first. +fn job_counts(job: &Job, app: &App, theme: &Theme) -> Vec> { + let mut parts = Vec::new(); + if let Some((completed, total, failed)) = job.tracker.batch { + parts.push(Span::styled(format!("{completed}/{total}"), theme.text())); + parts.push(Span::styled( + format!("{failed} failed"), + if failed > 0 { + theme.danger() + } else { + theme.muted() + }, + )); + } + let queued = app.queued_count(); + if queued > 0 { + parts.push(Span::styled(format!("{queued} queued"), theme.muted())); + } + parts +} + +/// The overall fill ratio, from the batch counts or a lone download. +fn job_ratio(job: &Job) -> Option { + if let Some((completed, total, _)) = job.tracker.batch { + return (total > 0).then(|| f64::from(completed) / f64::from(total)); + } + let mut active = job.tracker.active(); + let lone = active.next()?; + if active.next().is_some() { + return None; + } + let Phase::Downloading { + current, + total, + } = lone.phase + else { + return None; + }; + (total > 0).then_some(current as f64 / total as f64) +} + +/// One operation line: the name, then where its work is. The activity +/// strip and the jobs detail share it. +pub(crate) fn render_op(f: &mut Frame, row: Rect, op: &OpRow, theme: &Theme, width: u16) { + let symbols = theme.sym(); + let name = format::truncate(&op.name, 12, symbols.ellipsis); + let mut line = vec![ + Span::raw(" "), + Span::styled(format!("{name:<12}"), theme.text()), + ]; + + match &op.phase { + Phase::Waiting => line.push(Span::styled("waiting", theme.muted())), + Phase::Step(label) => { + line.push(Span::styled(label.clone(), theme.muted())); + if let Some(output) = &op.last_output { + let room = width.saturating_sub(spans_width(&line) as u16 + 1) as usize; + if room > 2 { + let text = format::truncate(output, room, symbols.ellipsis); + line.push(Span::raw(" ")); + line.push(Span::styled( + text, + theme.muted().add_modifier(Modifier::DIM), + )); + } + } + } + Phase::Downloading { + current, + total, + } => { + let ratio = if *total > 0 { + *current as f64 / *total as f64 + } else { + 0.0 + }; + let mut tail = format!(" {}/{}", format::size(*current), format::size(*total)); + if let Some(speed) = op.speed { + tail.push_str(&format!(" {}", format::speed(speed))); + } + if let Some(eta) = op.eta() { + tail.push_str(&format!(" {}", format::eta(eta))); + } + let room = width.saturating_sub(spans_width(&line) as u16) as usize; + let tail_width = Span::raw(tail.as_str()).width(); + let gauge_width = 30u16.min(room.saturating_sub(tail_width + 1) as u16); + if gauge_width > 3 { + line.push(Span::raw(" ")); + line.extend(gauge::line(ratio, gauge_width, theme).spans); + } + line.push(Span::raw(tail)); + } + Phase::Done => { + line.push(Span::styled(symbols.installed, theme.success())); + line.push(Span::styled(" done", theme.success())); + } + Phase::Failed(error) => { + let room = width.saturating_sub(spans_width(&line) as u16 + 2) as usize; + let text = format::truncate(error, room, symbols.ellipsis); + line.push(Span::styled(symbols.error, theme.danger())); + line.push(Span::raw(" ")); + line.push(Span::styled(text, theme.danger())); + } + Phase::Skipped => { + line.push(Span::styled(symbols.available, theme.muted())); + line.push(Span::styled(" skipped", theme.muted())); + } + } + + f.render_widget(Paragraph::new(Line::from(line)), row); +} + +/// The one-line summary a finished job leaves behind for three seconds. +fn render_finished(f: &mut Frame, row: Rect, job: &Job, theme: &Theme) { + let symbols = theme.sym(); + let JobState::Finished { + started, + ended, + outcome, + } = &job.state + else { + return; + }; + let duration = ended.duration_since(*started); + let line = if outcome.aborted { + Line::from(vec![ + Span::raw(" "), + Span::styled(symbols.warning, theme.warning()), + Span::styled(format!(" {}", outcome.headline), theme.warning()), + Span::styled(format!(" in {}", format::clock(duration)), theme.muted()), + ]) + } else if outcome.ok { + Line::from(vec![ + Span::raw(" "), + Span::styled(symbols.installed, theme.success()), + Span::styled(format!(" {}", outcome.headline), theme.success()), + Span::styled(format!(" in {}", format::clock(duration)), theme.muted()), + ]) + } else { + Line::from(vec![ + Span::raw(" "), + Span::styled(symbols.error, theme.danger()), + Span::styled(format!(" {} (see Jobs)", outcome.headline), theme.danger()), + ]) + }; + f.render_widget(Paragraph::new(line), row); +} + +/// The display width of a run of spans. +fn spans_width(spans: &[Span]) -> usize { + spans.iter().map(Span::width).sum() +} + +/// Hands out one-row slices of the strip's area, top to bottom. +struct Rows { + x: u16, + next_y: u16, + bottom: u16, +} + +impl Rows { + /// Starts above the first row of `area`. + fn new(area: Rect) -> Rows { + Rows { + x: area.x, + next_y: area.y, + bottom: area.y + area.height, + } + } + + /// Returns the next row, clipped to nothing once the area is spent so + /// extra renders draw nowhere. + fn next(&mut self, width: u16) -> Rect { + let y = self.next_y; + self.next_y += 1; + Rect { + x: self.x, + y, + width: if y < self.bottom { width } else { 0 }, + height: 1, + } + } +} + +#[cfg(test)] +mod tests { + use std::time::{Duration, Instant}; + + use soar_events::{OperationId, SoarEvent, SyncStage}; + + use crate::{ + app::App, + jobs::{Job, JobKind, JobOutcome, JobState}, + msg::Msg, + progress::Tracker, + test_support::{screen, test_app}, + }; + + /// A running sync job whose tracker holds one stage line per + /// repository. + fn running_sync_app(repos: &[(&str, &str)]) -> App { + let mut app = test_app(); + let mut tracker = Tracker::default(); + let now = Instant::now(); + for (repo, stage) in repos { + let sync_stage = match *stage { + "fetching" => SyncStage::Fetching, + "done" => { + SyncStage::Complete { + package_count: None, + } + } + "up to date" => SyncStage::UpToDate, + "decompressing" => SyncStage::Decompressing, + "writing" => SyncStage::WritingDatabase, + "validating" => SyncStage::Validating, + other => panic!("unknown stage {other}"), + }; + tracker.apply( + &SoarEvent::SyncProgress { + repo_name: repo.to_string(), + stage: sync_stage, + }, + now, + ); + } + app.jobs.list.push(Job { + id: 0, + kind: JobKind::Sync, + title: "Sync repositories".to_string(), + state: JobState::Running { + started: now, + aborting: false, + }, + spec: None, + tracker, + }); + app + } + + fn running_app_with_ops(count: usize) -> App { + let mut app = test_app(); + let mut tracker = Tracker::default(); + let now = Instant::now(); + for i in 0..count as OperationId { + tracker.apply( + &SoarEvent::DownloadPreparing { + op_id: i, + pkg_name: format!("pkg{i}"), + }, + now, + ); + } + app.jobs.list.push(Job { + id: 0, + kind: JobKind::Install, + title: format!("Install {count} packages"), + state: JobState::Running { + started: now, + aborting: false, + }, + spec: None, + tracker, + }); + app + } + + #[test] + fn a_running_job_with_six_active_ops_folds_the_last_two() { + let mut app = running_app_with_ops(6); + assert_eq!(app.activity_height(), 7); + assert!(screen(&mut app, 80, 24).contains("+2 more")); + } + + #[test] + fn an_idle_screen_shows_no_strip() { + let app = test_app(); + assert_eq!(app.activity_height(), 0); + } + + #[test] + fn a_failed_job_shows_a_see_jobs_summary_for_three_seconds() { + let mut app = test_app(); + let now = Instant::now(); + app.jobs.list.push(Job { + id: 0, + kind: JobKind::Install, + title: "Install 1 package".into(), + state: JobState::Finished { + started: now, + ended: now, + outcome: JobOutcome { + ok: false, + aborted: false, + headline: "Install finished with 1 failure".into(), + lines: Vec::new(), + }, + }, + spec: None, + tracker: Tracker::default(), + }); + app.activity_until = Some(now + Duration::from_secs(3)); + assert_eq!(app.activity_height(), 2); + assert!(screen(&mut app, 80, 24).contains("(see Jobs)")); + app.update(Msg::Tick, now + Duration::from_secs(4)); + assert_eq!(app.activity_height(), 0); + } + + #[test] + fn an_aborting_job_shows_the_warning_hint_on_the_strip() { + let mut app = running_app_with_ops(1); + if let Some(job) = app.running_job_mut() + && let JobState::Running { + aborting, .. + } = &mut job.state + { + *aborting = true; + } + let hint = format!("aborting{}", app.theme.sym().ellipsis); + let screen = screen(&mut app, 80, 24); + assert!(screen.contains(&hint), "screen is {screen:?}"); + } + + #[test] + fn a_running_sync_job_shows_one_line_per_repository() { + let mut app = running_sync_app(&[ + ("bincache", "fetching"), + ("pkgforge", "done"), + ("isolated", "up to date"), + ]); + let screen = screen(&mut app, 80, 24); + for text in [ + "bincache fetching", + "pkgforge done", + "isolated up to date", + ] { + assert!(screen.contains(text), "screen is {screen:?}"); + } + } + + #[test] + fn a_running_sync_job_folds_past_four_repositories() { + let repos: Vec<(String, String)> = (0..6) + .map(|i| (format!("repo{i}"), "fetching".to_string())) + .collect(); + let refs: Vec<(&str, &str)> = repos + .iter() + .map(|(r, s)| (r.as_str(), s.as_str())) + .collect(); + let mut app = running_sync_app(&refs); + let screen = screen(&mut app, 80, 24); + assert!(screen.contains("repo3"), "screen is {screen:?}"); + assert!(!screen.contains("repo4"), "screen is {screen:?}"); + assert!(screen.contains("+2 more"), "screen is {screen:?}"); + } + + #[test] + fn a_background_sync_shows_one_line_per_repo() { + let mut app = test_app(); + let now = Instant::now(); + for (repo, stage) in [ + ("bincache", SyncStage::Fetching), + ("pkgforge", SyncStage::Decompressing), + ] { + app.update( + Msg::Soar(SoarEvent::SyncProgress { + repo_name: repo.to_string(), + stage, + }), + now, + ); + } + assert_eq!(app.activity_height(), 3); + let screen = screen(&mut app, 80, 24); + assert!( + screen.contains("Syncing bincache: fetching"), + "screen is {screen:?}" + ); + assert!( + screen.contains("Syncing pkgforge: decompressing"), + "screen is {screen:?}" + ); + } + + #[test] + fn a_finished_sync_leaves_no_background_lines() { + let mut app = test_app(); + let now = Instant::now(); + app.update( + Msg::Soar(SoarEvent::SyncProgress { + repo_name: "bincache".to_string(), + stage: SyncStage::Complete { + package_count: Some(1200), + }, + }), + now, + ); + assert_eq!(app.activity_height(), 0); + } + + #[test] + fn a_background_sync_marks_the_screen_dirty_for_the_next_frame() { + let mut app = test_app(); + app.dirty = false; + app.update( + Msg::Soar(SoarEvent::SyncProgress { + repo_name: "bincache".to_string(), + stage: SyncStage::Fetching, + }), + Instant::now(), + ); + assert!(app.dirty); + } +} diff --git a/crates/soar-tui/src/widgets/authorize.rs b/crates/soar-tui/src/widgets/authorize.rs new file mode 100644 index 00000000..0bc6ba6e --- /dev/null +++ b/crates/soar-tui/src/widgets/authorize.rs @@ -0,0 +1,473 @@ +//! The administrator password dialog for the system pass. + +use ratatui::{ + Frame, + crossterm::event::{KeyCode, KeyEvent}, + layout::Rect, + text::{Line, Span}, + widgets::{Clear, Paragraph}, +}; + +use crate::{ + app::App, + format, + privileged::Secret, + theme::Theme, + widgets::{ + overlay::{Overlay, OverlayOutcome, buttons, centered, frame}, + text_input::TextInput, + }, +}; + +/// The focus positions: the password field, then cancel, then authorize. +const PASSWORD: usize = 0; +const CANCEL: usize = 1; +const AUTHORIZE: usize = 2; +const LAST_FOCUS: usize = AUTHORIZE; + +/// Asks for the administrator password before the system pass runs. The +/// value never shows: each typed character draws as the theme's mask, and +/// the only way out of the widget is through a [`Secret`] handed straight +/// to the runner, or closing the dialog. The debug output hides the +/// password, because the input keeps it out of its own debug output. +#[derive(Debug)] +pub(crate) struct Authorize { + /// The declared packages the pass applies, named in the body. + names: Vec, + /// The password field, its value hidden. + input: TextInput, + /// Why the last password was refused, shown until the next one is + /// typed. + error: Option, + /// Which of the password field and the two buttons holds the focus. + focus: usize, + /// Whether a password is being checked: a spinner replaces the + /// buttons and every key except esc is ignored. + busy: bool, +} + +impl Authorize { + /// Builds the dialog for the named packages, focus in the password + /// field. + pub(crate) fn new(names: Vec) -> Authorize { + Authorize { + names, + input: TextInput::default().masked(), + error: None, + focus: PASSWORD, + busy: false, + } + } + + /// Whether the dialog waits for a password check to answer. Only a + /// waiting dialog can receive an answer. + pub(crate) fn is_busy(&self) -> bool { + self.busy + } + + /// Builds the dialog already waiting for the password check to come + /// back. + pub(crate) fn waiting(names: Vec) -> Authorize { + let mut dialog = Authorize::new(names); + dialog.busy = true; + dialog + } + + /// Acts on one pressed key. Typing edits the password while the field + /// holds the focus, and tab and up and down walk the focus across the + /// field and the two buttons, where left and right step the focus as + /// well. Enter submits or presses a button, and esc closes. + /// Keystrokes the focused control does not use are ignored, so the + /// hidden password edits only from the field in view. While busy + /// only esc is heard. + pub(crate) fn handle(mut self, key: KeyEvent) -> OverlayOutcome { + if self.busy { + return match key.code { + KeyCode::Esc => OverlayOutcome::Close, + _ => OverlayOutcome::Stay(Overlay::Authorize(self)), + }; + } + match (key.code, key.modifiers) { + (KeyCode::Esc, _) => OverlayOutcome::Close, + (KeyCode::Tab | KeyCode::Down, _) => { + self.focus = (self.focus + 1).min(LAST_FOCUS); + OverlayOutcome::Stay(Overlay::Authorize(self)) + } + (KeyCode::BackTab | KeyCode::Up, _) => { + self.focus = self.focus.saturating_sub(1); + OverlayOutcome::Stay(Overlay::Authorize(self)) + } + (KeyCode::Left, _) if self.focus != PASSWORD => { + self.focus = self.focus.saturating_sub(1); + OverlayOutcome::Stay(Overlay::Authorize(self)) + } + (KeyCode::Right, _) if self.focus != PASSWORD => { + self.focus = (self.focus + 1).min(LAST_FOCUS); + OverlayOutcome::Stay(Overlay::Authorize(self)) + } + (KeyCode::Enter, _) => { + match self.focus { + CANCEL => OverlayOutcome::Close, + _ => self.submit(), + } + } + _ => { + if self.focus == PASSWORD && self.input.handle(key) { + self.error = None; + } + OverlayOutcome::Stay(Overlay::Authorize(self)) + } + } + } + + /// Moves the typed value into a secret for the runner and waits for + /// its answer. An empty password does nothing. + fn submit(mut self) -> OverlayOutcome { + if self.input.is_empty() { + return OverlayOutcome::Stay(Overlay::Authorize(self)); + } + let secret = Secret::new(self.input.take().into_bytes()); + self.busy = true; + OverlayOutcome::Authenticate(secret) + } + + /// Shows why the password was refused and takes the focus back for + /// another try. + pub(crate) fn fail(&mut self, error: String) { + self.error = Some(error); + self.busy = false; + self.focus = PASSWORD; + } + + /// Draws the dialog centered in the body area, and returns the rect it + /// drew into. + pub(crate) fn render(&self, f: &mut Frame, area: Rect, app: &App) -> Rect { + let theme = &app.theme; + let width = area.width.saturating_sub(4).min(64); + // The content is what the borders and the one-column padding on + // each side leave, so every body line sizes against what it + // actually draws into. + let content = usize::from(width.saturating_sub(4)); + let lines = self.body_lines(theme, app.frame, content); + let rect = centered(area, width, lines.len() as u16 + 2); + f.render_widget(Clear, rect); + + let block = frame( + Line::styled(" Administrator rights needed ", theme.title()), + None, + false, + theme, + ); + f.render_widget(Paragraph::new(lines).block(block), rect); + rect + } + + /// The body: what the pass applies, what runs it, the password field, + /// the refusal of the last password if there was one, and the buttons + /// or the waiting spinner. `content` is the dialog's inner width, so + /// every row is cut to the width it really draws into. + fn body_lines(&self, theme: &Theme, frame_tick: u64, content: usize) -> Vec> { + let mut lines = vec![Line::raw("")]; + lines.push(Line::raw(format!( + " Apply {} system packages from packages.toml:", + self.names.len() + ))); + let names = self.names.join(", "); + for row in format::wrap(&names, content.saturating_sub(2)) { + lines.push(Line::raw(format!(" {row}"))); + } + lines.push(Line::raw("")); + lines.push(Line::raw(" sudo will run:")); + lines.push(Line::styled( + " soar --system apply --only-system", + theme.muted(), + )); + lines.push(Line::raw("")); + let mut field = vec![Span::raw(" "), Span::raw("Password"), Span::raw(" ")]; + // The field label takes twelve of the dialog's columns and the + // focused cursor cell draws one past the value's window, so the + // value reserves both and keeps its tail in view. + field.extend( + self.input + .line(self.focus == PASSWORD, content.saturating_sub(13), theme) + .spans, + ); + lines.push(Line::from(field)); + if let Some(error) = &self.error { + let symbol = theme.sym().error; + // The refusal's lead takes four of the content's columns, so + // the text wraps to the rest and no row overflows the dialog. + for (index, row) in format::wrap(error, content.saturating_sub(4)) + .into_iter() + .enumerate() + { + let lead = if index == 0 { + format!(" {symbol} ") + } else { + " ".to_string() + }; + lines.push(Line::styled(format!("{lead}{row}"), theme.danger())); + } + } + lines.push(Line::raw("")); + if self.busy { + lines.push( + Line::from(vec![ + Span::styled(theme.spinner(frame_tick), theme.accent()), + Span::raw(" Checking password"), + ]) + .right_aligned(), + ); + } else { + lines.push( + buttons( + "Authorize", + self.focus == CANCEL, + self.focus == AUTHORIZE, + false, + theme, + ) + .right_aligned(), + ); + } + lines + } +} + +#[cfg(test)] +mod tests { + use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; + + use super::Authorize; + use crate::{ + test_support::{screen, test_app}, + widgets::overlay::{Overlay, OverlayOutcome}, + }; + + fn press(c: char) -> KeyEvent { + KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE) + } + + fn press_key(key: KeyCode) -> KeyEvent { + KeyEvent::new(key, KeyModifiers::NONE) + } + + fn dialog() -> Authorize { + Authorize::new(vec!["docker-compose".to_string(), "tailscale".to_string()]) + } + + fn stay(outcome: OverlayOutcome) -> Authorize { + match outcome { + OverlayOutcome::Stay(Overlay::Authorize(dialog)) => dialog, + other => panic!("expected the dialog to stay open, got {other:?}"), + } + } + + #[test] + fn the_dialog_names_the_packages_and_the_pass() { + let mut app = test_app(); + app.overlay = Some(Overlay::Authorize(dialog())); + let screen = screen(&mut app, 80, 24); + for text in [ + "Administrator rights needed", + "Apply 2 system packages from packages.toml:", + "docker-compose, tailscale", + "sudo will run:", + "soar --system apply --only-system", + "Password", + "[ Cancel ]", + "[ Authorize ]", + ] { + assert!(screen.contains(text), "screen is {screen:?}"); + } + } + + #[test] + fn typed_characters_draw_as_masks_and_the_value_stays_hidden() { + let mut app = test_app(); + let mut dialog = dialog(); + for c in ['a', 'b', 'c'] { + dialog = stay(dialog.handle(press(c))); + } + app.overlay = Some(Overlay::Authorize(dialog)); + let screen = screen(&mut app, 80, 24); + assert!(screen.contains("•••"), "screen is {screen:?}"); + assert!(!screen.contains("abc"), "screen is {screen:?}"); + } + + #[test] + fn enter_moves_the_value_into_a_secret_and_waits() { + let mut dialog = dialog(); + for c in ['a', 'b', 'c'] { + dialog = stay(dialog.handle(press(c))); + } + let outcome = dialog.handle(press_key(KeyCode::Enter)); + match outcome { + OverlayOutcome::Authenticate(secret) => { + assert_eq!(secret.bytes(), b"abc"); + } + other => panic!("expected the password to submit, got {other:?}"), + } + } + + #[test] + fn enter_on_an_empty_password_does_nothing() { + let outcome = dialog().handle(press_key(KeyCode::Enter)); + stay(outcome); + } + + #[test] + fn esc_and_the_cancel_button_close() { + assert!(matches!( + dialog().handle(press_key(KeyCode::Esc)), + OverlayOutcome::Close + )); + let dialog = stay(dialog().handle(press_key(KeyCode::Tab))); + assert!(matches!( + dialog.handle(press_key(KeyCode::Enter)), + OverlayOutcome::Close + )); + } + + #[test] + fn tab_walks_the_focus_between_the_field_and_the_buttons() { + // One tab reaches cancel, whose enter closes. + let shifted = stay(dialog().handle(press_key(KeyCode::Tab))); + assert!(matches!( + shifted.handle(press_key(KeyCode::Enter)), + OverlayOutcome::Close + )); + // Two tabs reach authorize, whose enter submits. + let mut dialog = dialog(); + for c in ['a', 'b'] { + dialog = stay(dialog.handle(press(c))); + } + dialog = stay(dialog.handle(press_key(KeyCode::Tab))); + let shifted = stay(dialog.handle(press_key(KeyCode::Tab))); + assert!(matches!( + shifted.handle(press_key(KeyCode::Enter)), + OverlayOutcome::Authenticate(_) + )); + } + + #[test] + fn left_and_right_stay_in_the_password_field() { + let mut dialog = dialog(); + for c in ['a', 'b'] { + dialog = stay(dialog.handle(press(c))); + } + dialog = stay(dialog.handle(press_key(KeyCode::Left))); + dialog = stay(dialog.handle(press('c'))); + match dialog.handle(press_key(KeyCode::Enter)) { + OverlayOutcome::Authenticate(secret) => { + assert_eq!(secret.bytes(), b"acb"); + } + other => panic!("the field kept the focus and submitted, got {other:?}"), + } + } + + #[test] + fn typing_while_a_button_holds_the_focus_edits_nothing() { + let mut dialog = dialog(); + for c in ['a', 'b'] { + dialog = stay(dialog.handle(press(c))); + } + // One tab reaches cancel, one right the authorize button. + dialog = stay(dialog.handle(press_key(KeyCode::Tab))); + dialog = stay(dialog.handle(press_key(KeyCode::Right))); + dialog = stay(dialog.handle(press('x'))); + match dialog.handle(press_key(KeyCode::Enter)) { + OverlayOutcome::Authenticate(secret) => { + assert_eq!(secret.bytes(), b"ab"); + } + other => panic!("the button submitted the typed password, got {other:?}"), + } + } + + #[test] + fn a_long_refusal_wraps_inside_the_dialog() { + let mut app = test_app(); + let mut dialog = dialog(); + dialog.fail( + "one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen" + .to_string(), + ); + app.overlay = Some(Overlay::Authorize(dialog)); + let screen = screen(&mut app, 80, 24); + assert!(screen.contains("eight nine ten"), "screen is {screen:?}"); + assert!(screen.contains("twelve thirteen"), "screen is {screen:?}"); + assert!( + !screen.contains("eleven twelve"), + "the refusal must wrap, screen is {screen:?}" + ); + } + + #[test] + fn the_password_line_fits_the_dialog_content_at_full_width() { + let app = test_app(); + let mut dialog = dialog(); + // Longer than the value room at the dialog's full width, so the + // line draws a full window of masks. + for c in "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" + .chars() + { + dialog = stay(dialog.handle(press(c))); + } + let lines = dialog.body_lines(&app.theme, 0, 60); + let Some(field) = lines.iter().find(|line| { + line.spans + .get(1) + .is_some_and(|span| span.content == "Password") + }) else { + panic!("the password line is in the body"); + }; + assert!( + field.width() <= 60, + "the field must fit the content width, got {}", + field.width() + ); + } + + #[test] + fn a_refused_password_shows_in_danger_until_the_next_keystroke() { + let mut app = test_app(); + let mut dialog = dialog(); + dialog.fail("Incorrect password, try again".to_string()); + app.overlay = Some(Overlay::Authorize(dialog)); + let screen = screen(&mut app, 80, 24); + assert!( + screen.contains("Incorrect password, try again"), + "screen is {screen:?}" + ); + } + + #[test] + fn waiting_ignores_every_key_except_esc() { + let dialog = Authorize::waiting(Vec::new()); + let outcome = dialog.handle(press('x')); + stay(outcome); + assert!(matches!( + Authorize::waiting(Vec::new()).handle(press_key(KeyCode::Esc)), + OverlayOutcome::Close + )); + } + + #[test] + fn waiting_draws_a_spinner_instead_of_the_buttons() { + let mut app = test_app(); + app.overlay = Some(Overlay::Authorize(Authorize::waiting(Vec::new()))); + let screen = screen(&mut app, 80, 24); + assert!(screen.contains("Checking password"), "screen is {screen:?}"); + assert!(!screen.contains("[ Authorize ]"), "screen is {screen:?}"); + } + + #[test] + fn debugging_the_dialog_never_carries_the_password() { + let mut dialog = dialog(); + for c in ['s', 'e', 'c', 'r', 'e', 't'] { + dialog = stay(dialog.handle(press(c))); + } + let printed = format!("{dialog:?}"); + assert!(!printed.contains("secret"), "debug output is {printed:?}"); + } +} diff --git a/crates/soar-tui/src/widgets/badge.rs b/crates/soar-tui/src/widgets/badge.rs new file mode 100644 index 00000000..1e92409d --- /dev/null +++ b/crates/soar-tui/src/widgets/badge.rs @@ -0,0 +1,54 @@ +//! Small marks shown beside package rows and names. +//! +//! The views draw the badges once they hold their own rows. + +#![allow(dead_code)] + +use ratatui::text::Span; + +use crate::theme::Theme; + +/// The package type word in its own color, or an empty span when the row +/// has no package type. +pub(crate) fn pkg_type(pkg_type: Option<&str>, theme: &Theme) -> Span<'static> { + match pkg_type { + None => Span::raw(""), + Some(pkg_type) => Span::styled(pkg_type.to_string(), theme.type_badge(pkg_type)), + } +} + +/// The mark showing a package is installed. +pub(crate) fn installed(theme: &Theme) -> Span<'static> { + Span::styled(theme.sym().installed, theme.success()) +} + +#[cfg(test)] +mod tests { + use super::{installed, pkg_type}; + use crate::theme::Theme; + + #[test] + fn a_missing_package_type_renders_nothing() { + let theme = Theme::new(true, true); + assert_eq!(pkg_type(None, &theme).width(), 0); + } + + #[test] + fn the_package_type_takes_its_own_color() { + let theme = Theme::new(true, true); + let span = pkg_type(Some("appimage"), &theme); + assert_eq!(span.content, "appimage"); + assert!(span.style.fg.is_some()); + + let plain = Theme::new(false, true); + assert_eq!(pkg_type(Some("appimage"), &plain).style.fg, None); + } + + #[test] + fn the_installed_mark_uses_the_installed_glyph() { + let theme = Theme::new(true, true); + let span = installed(&theme); + assert_eq!(span.content, theme.sym().installed); + assert!(span.style.fg.is_some()); + } +} diff --git a/crates/soar-tui/src/widgets/confirm.rs b/crates/soar-tui/src/widgets/confirm.rs new file mode 100644 index 00000000..3d3ab325 --- /dev/null +++ b/crates/soar-tui/src/widgets/confirm.rs @@ -0,0 +1,245 @@ +//! The yes-or-no dialog that names everything about to change. + +#![allow(dead_code)] + +use ratatui::{ + Frame, + crossterm::event::{KeyCode, KeyModifiers}, + layout::Rect, + text::Line, + widgets::{Clear, Paragraph}, +}; + +use crate::{ + app::App, + theme::Theme, + widgets::overlay::{OnAccept, Overlay, OverlayOutcome, buttons, centered, frame}, +}; + +/// A dialog asking whether to carry out one action, naming everything that +/// will change. Destructive dialogs start focused on cancel so an +/// accidental enter cannot act. +#[derive(Debug)] +pub(crate) struct Confirm { + title: String, + body: Vec>, + action_label: String, + danger: bool, + focus_action: bool, + on_accept: OnAccept, +} + +impl Confirm { + /// Builds a confirm dialog. Destructive dialogs start with the focus on + /// the cancel button. + pub(crate) fn new( + title: impl Into, + body: Vec>, + action_label: impl Into, + danger: bool, + on_accept: OnAccept, + ) -> Confirm { + Confirm { + title: title.into(), + body, + action_label: action_label.into(), + danger, + focus_action: !danger, + on_accept, + } + } + + /// What accepting this dialog carries out. + pub(crate) fn action(&self) -> &OnAccept { + &self.on_accept + } + + /// Acts on one pressed key. `y` accepts, `n` and esc close, enter + /// presses the focused button, and the movement keys switch it. + pub(crate) fn handle(mut self, key: ratatui::crossterm::event::KeyEvent) -> OverlayOutcome { + match (key.code, key.modifiers) { + (KeyCode::Char('y'), KeyModifiers::NONE | KeyModifiers::SHIFT) => { + OverlayOutcome::Accept(self.on_accept, None) + } + (KeyCode::Char('n'), KeyModifiers::NONE | KeyModifiers::SHIFT) | (KeyCode::Esc, _) => { + OverlayOutcome::Close + } + ( + KeyCode::Left + | KeyCode::Right + | KeyCode::Tab + | KeyCode::Char('h') + | KeyCode::Char('l'), + _, + ) => { + self.focus_action = !self.focus_action; + OverlayOutcome::Stay(Overlay::Confirm(self)) + } + (KeyCode::Enter, _) if self.focus_action => { + OverlayOutcome::Accept(self.on_accept, None) + } + (KeyCode::Enter, _) => OverlayOutcome::Close, + _ => OverlayOutcome::Stay(Overlay::Confirm(self)), + } + } + + /// Draws the dialog centered in the body area, and returns the rect it + /// drew into. + pub(crate) fn render(&self, f: &mut Frame, area: Rect, app: &App) -> Rect { + let theme = &app.theme; + let width = area.width.saturating_sub(4).min(64); + let rect = centered(area, width, self.body.len() as u16 + 6); + f.render_widget(Clear, rect); + + let mut lines = vec![Line::raw("")]; + lines.extend(self.visible_body(theme, rect.height)); + lines.push(Line::raw("")); + let buttons = buttons( + &self.action_label, + !self.focus_action, + self.focus_action, + self.danger, + theme, + ) + .right_aligned(); + lines.push(buttons); + + let block = frame( + Line::styled(format!(" {} ", self.title), theme.title()), + None, + self.danger, + theme, + ); + f.render_widget(Paragraph::new(lines).block(block), rect); + rect + } + + /// The body lines that fit in `height` rows, ending with a count of the + /// ones cut off. + fn visible_body(&self, theme: &Theme, height: u16) -> Vec> { + let budget = usize::from(height).saturating_sub(5); + if self.body.len() <= budget { + return self.body.clone(); + } + let shown = budget.saturating_sub(1); + let mut lines: Vec> = self.body.iter().take(shown).cloned().collect(); + let hidden = self.body.len() - shown; + let more = format!("{} and {hidden} more", theme.sym().ellipsis); + lines.push(Line::styled(more, theme.muted())); + lines + } +} + +#[cfg(test)] +mod tests { + use ratatui::{ + crossterm::event::{KeyCode, KeyEvent, KeyModifiers}, + text::Line, + }; + + use super::Confirm; + use crate::{ + test_support::{screen, test_app}, + widgets::overlay::{OnAccept, Overlay, OverlayOutcome}, + }; + + fn press(key: KeyCode) -> KeyEvent { + KeyEvent::new(key, KeyModifiers::NONE) + } + + fn confirm(danger: bool) -> Confirm { + Confirm::new( + "Remove 2 packages", + vec![Line::raw("obsidian 1.7.7"), Line::raw("zellij 0.41.2")], + "Remove", + danger, + OnAccept::Test, + ) + } + + fn stay(outcome: OverlayOutcome) -> Confirm { + match outcome { + OverlayOutcome::Stay(Overlay::Confirm(confirm)) => confirm, + other => panic!("expected the dialog to stay open, got {other:?}"), + } + } + + #[test] + fn enter_on_a_danger_confirm_closes_without_accepting() { + assert!(matches!( + confirm(true).handle(press(KeyCode::Enter)), + OverlayOutcome::Close + )); + } + + #[test] + fn enter_on_a_plain_confirm_accepts() { + assert!(matches!( + confirm(false).handle(press(KeyCode::Enter)), + OverlayOutcome::Accept(OnAccept::Test, None) + )); + } + + #[test] + fn y_accepts_whether_the_action_is_focused() { + for danger in [true, false] { + assert!(matches!( + confirm(danger).handle(press(KeyCode::Char('y'))), + OverlayOutcome::Accept(OnAccept::Test, None) + )); + } + } + + #[test] + fn n_and_esc_close() { + assert!(matches!( + confirm(true).handle(press(KeyCode::Char('n'))), + OverlayOutcome::Close + )); + assert!(matches!( + confirm(true).handle(press(KeyCode::Esc)), + OverlayOutcome::Close + )); + } + + #[test] + fn movement_keys_switch_the_focused_button() { + let confirm = stay(confirm(true).handle(press(KeyCode::Right))); + assert!(matches!( + confirm.handle(press(KeyCode::Enter)), + OverlayOutcome::Accept(OnAccept::Test, None) + )); + } + + #[test] + fn the_dialog_shows_its_title_body_and_buttons() { + let mut app = test_app(); + app.overlay = Some(Overlay::Confirm(confirm(true))); + let screen = screen(&mut app, 80, 24); + for text in [ + "Remove 2 packages", + "obsidian 1.7.7", + "[ Cancel ]", + "[ Remove ]", + ] { + assert!(screen.contains(text), "screen is {screen:?}"); + } + } + + #[test] + fn a_tall_body_lists_what_does_not_fit() { + let mut app = test_app(); + let body: Vec> = (0..20).map(|n| Line::raw(format!("package {n}"))).collect(); + app.overlay = Some(Overlay::Confirm(Confirm::new( + "Remove", + body, + "Remove", + true, + OnAccept::Test, + ))); + let screen = screen(&mut app, 80, 24); + assert!(screen.contains("package 0"), "screen is {screen:?}"); + assert!(screen.contains("and 4 more"), "screen is {screen:?}"); + assert!(!screen.contains("package 19"), "screen is {screen:?}"); + } +} diff --git a/crates/soar-tui/src/widgets/form.rs b/crates/soar-tui/src/widgets/form.rs new file mode 100644 index 00000000..3806f064 --- /dev/null +++ b/crates/soar-tui/src/widgets/form.rs @@ -0,0 +1,504 @@ +//! The dialog that collects several values at once, accepted as a whole. + +#![allow(dead_code)] + +use ratatui::{ + Frame, + crossterm::event::{KeyCode, KeyEvent, KeyModifiers}, + layout::Rect, + text::{Line, Span}, + widgets::{Clear, Paragraph}, +}; + +use crate::{ + app::App, + theme::Theme, + widgets::{ + overlay::{OnAccept, Overlay, OverlayOutcome, Value, buttons, centered, frame}, + text_input::TextInput, + }, +}; + +/// One row of a form: a checkbox or a single line of text. +#[derive(Debug)] +pub(crate) enum Field { + /// A toggle, shown as `[x]` or `[ ]`. + Check { + /// The name shown beside the box. + label: &'static str, + /// Whether the box is ticked. + checked: bool, + }, + /// A single line of text. + Text { + /// The name shown beside the value. + label: &'static str, + /// The editable value. + input: TextInput, + }, + /// A single line of text the form refuses to accept while it is + /// blank or only whitespace. + RequiredText { + /// The name shown beside the value. + label: &'static str, + /// The editable value. + input: TextInput, + }, +} + +/// The values of every field of an accepted form, in field order. +#[derive(Debug, PartialEq, Eq)] +pub(crate) struct FormValues(pub(crate) Vec); + +/// The value of one form field. +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum FieldValue { + /// The text of a text field. + Text(String), + /// The state of a checkbox. + Check(bool), +} + +/// A dialog with checkboxes and text fields, accepted with its two buttons. +/// The focus walks over the fields and then the buttons. +#[derive(Debug)] +pub(crate) struct Form { + title: String, + fields: Vec, + focus: usize, + action_label: String, + on_accept: OnAccept, + /// Why the last accept was refused, shown in danger above the + /// buttons. Editing any text field drops it again. + error: Option, +} + +impl Form { + /// Builds a form with the focus on its first field. + pub(crate) fn new( + title: impl Into, + fields: Vec, + action_label: impl Into, + on_accept: OnAccept, + ) -> Form { + Form { + title: title.into(), + fields, + focus: 0, + action_label: action_label.into(), + on_accept, + error: None, + } + } + + /// The focus position of the action button, after the fields and the + /// cancel button. + fn last_focus(&self) -> usize { + self.fields.len() + 1 + } + + /// Acts on one pressed key. Tab and the arrows move the focus, space + /// toggles a checkbox, other keys edit a focused text field, enter + /// presses a button or moves to the next field, and esc closes. + pub(crate) fn handle(mut self, key: KeyEvent) -> OverlayOutcome { + match (key.code, key.modifiers) { + (KeyCode::Esc, _) => return OverlayOutcome::Close, + (KeyCode::Tab | KeyCode::Down, _) => { + self.focus = (self.focus + 1).min(self.last_focus()); + } + (KeyCode::BackTab | KeyCode::Up, _) => self.focus = self.focus.saturating_sub(1), + (KeyCode::Enter, _) => { + if self.focus == self.last_focus() { + if let Some((position, message)) = self.missing_required() { + self.focus = position; + self.error = Some(message); + return OverlayOutcome::Stay(Overlay::Form(self)); + } + let values = self.values(); + return OverlayOutcome::Accept(self.on_accept, Some(Value::Form(values))); + } + if self.focus == self.fields.len() { + return OverlayOutcome::Close; + } + self.focus = (self.focus + 1).min(self.last_focus()); + } + (KeyCode::Char(' '), KeyModifiers::NONE | KeyModifiers::SHIFT) + if matches!(self.fields.get(self.focus), Some(Field::Check { .. })) => + { + if let Some(Field::Check { + checked, .. + }) = self.fields.get_mut(self.focus) + { + *checked = !*checked; + } + } + _ => { + let edited = match self.fields.get_mut(self.focus) { + Some( + Field::Text { + input, .. + } + | Field::RequiredText { + input, .. + }, + ) => input.handle(key), + _ => false, + }; + if edited { + self.error = None; + } + } + } + OverlayOutcome::Stay(Overlay::Form(self)) + } + + /// The first required field left blank, with the message naming it. + fn missing_required(&self) -> Option<(usize, String)> { + self.fields + .iter() + .enumerate() + .find_map(|(position, field)| { + match field { + Field::RequiredText { + label, + input, + } if input.value().trim().is_empty() => { + Some((position, format!("{label} is required"))) + } + _ => None, + } + }) + } + + /// The values of every field, in field order. + fn values(&self) -> FormValues { + FormValues( + self.fields + .iter() + .map(|field| { + match field { + Field::Text { + input, .. + } + | Field::RequiredText { + input, .. + } => FieldValue::Text(input.value().to_owned()), + Field::Check { + checked, .. + } => FieldValue::Check(*checked), + } + }) + .collect(), + ) + } + + /// Draws the form centered in the body area, and returns the rect it + /// drew into. + pub(crate) fn render(&self, f: &mut Frame, area: Rect, app: &App) -> Rect { + let theme = &app.theme; + let width = area.width.saturating_sub(4).min(64); + let rows = self.fields.len() + usize::from(self.error.is_some()); + let rect = centered(area, width, rows as u16 + 4); + f.render_widget(Clear, rect); + + // The block's border and padding take two columns on each side, + // so the field rows are budgeted the body that is left. + let content = usize::from(rect.width).saturating_sub(4); + let mut lines = Vec::with_capacity(rows + 2); + for (position, field) in self.fields.iter().enumerate() { + lines.push(self.field_line(field, position == self.focus, content, theme)); + } + lines.push(Line::raw("")); + if let Some(error) = &self.error { + lines.push(Line::styled(error.clone(), theme.danger())); + } + let buttons = buttons( + &self.action_label, + self.focus == self.fields.len(), + self.focus == self.last_focus(), + false, + theme, + ) + .right_aligned(); + lines.push(buttons); + + let block = frame( + Line::styled(format!(" {} ", self.title), theme.title()), + None, + false, + theme, + ); + f.render_widget(Paragraph::new(lines).block(block), rect); + rect + } + + /// One field as a row, the focused one highlighted. `content` is the + /// dialog body's width in columns, which the row's value is budgeted + /// after the row's own furniture. + fn field_line( + &self, + field: &Field, + focused: bool, + content: usize, + theme: &Theme, + ) -> Line<'static> { + let mut line = match field { + Field::Check { + label, + checked, + } => { + let mark = if *checked { "[x]" } else { "[ ]" }; + Line::from(vec![ + Span::raw(" "), + Span::raw(mark), + Span::raw(" "), + Span::raw(*label), + ]) + } + Field::Text { + label, + input, + } + | Field::RequiredText { + label, + input, + } => { + let mut spans = vec![Span::raw(" "), Span::raw(*label), Span::raw(" ")]; + // The indent, label, and gap take their columns of the + // dialog body first, so a long value keeps its tail, + // where the cursor is, in view. + let used = 6 + Span::raw(*label).width() + 2; + let room = content.saturating_sub(used); + spans.extend(input.line(focused, room, theme).spans); + Line::from(spans) + } + }; + if focused { + line = line.style(theme.cursor_row()); + } + line + } +} + +#[cfg(test)] +mod tests { + use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; + + use super::{Field, FieldValue, Form, FormValues}; + use crate::{ + test_support::{screen, test_app}, + widgets::{ + overlay::{OnAccept, Overlay, OverlayOutcome, Value}, + text_input::TextInput, + }, + }; + + fn press(key: KeyCode) -> KeyEvent { + KeyEvent::new(key, KeyModifiers::NONE) + } + + fn form() -> Form { + Form::new( + "Install bat with options", + vec![ + Field::Check { + label: "Force reinstall", + checked: false, + }, + Field::Check { + label: "Binary only", + checked: false, + }, + Field::Text { + label: "Portable path", + input: TextInput::default(), + }, + ], + "Install", + OnAccept::Test, + ) + } + + fn stay(outcome: OverlayOutcome) -> Form { + match outcome { + OverlayOutcome::Stay(Overlay::Form(form)) => form, + other => panic!("expected the form to stay open, got {other:?}"), + } + } + + #[test] + fn toggling_a_checkbox_then_accepting_returns_its_value() { + let mut form = stay(form().handle(press(KeyCode::Char(' ')))); + for _ in 0..4 { + form = stay(form.handle(press(KeyCode::Tab))); + } + assert!(matches!( + form.handle(press(KeyCode::Enter)), + OverlayOutcome::Accept(OnAccept::Test, Some(Value::Form(FormValues(values)))) + if values == vec![ + FieldValue::Check(true), + FieldValue::Check(false), + FieldValue::Text(String::new()), + ] + )); + } + + #[test] + fn enter_on_a_field_moves_to_the_next_one() { + let form = stay(form().handle(press(KeyCode::Enter))); + assert_eq!(form.focus, 1); + let form = stay(form.handle(press(KeyCode::Enter))); + assert_eq!(form.focus, 2); + } + + #[test] + fn esc_closes() { + assert!(matches!( + form().handle(press(KeyCode::Esc)), + OverlayOutcome::Close + )); + } + + #[test] + fn text_keys_reach_the_focused_text_field() { + let form = stay(form().handle(press(KeyCode::Tab))); + let form = stay(form.handle(press(KeyCode::Tab))); + let form = stay(form.handle(press(KeyCode::Char('x')))); + assert_eq!(form.focus, 2); + let form = stay(form.handle(press(KeyCode::Enter))); + let form = stay(form.handle(press(KeyCode::Tab))); + assert!(matches!( + form.handle(press(KeyCode::Enter)), + OverlayOutcome::Accept(OnAccept::Test, Some(Value::Form(FormValues(values)))) + if values == vec![ + FieldValue::Check(false), + FieldValue::Check(false), + FieldValue::Text("x".to_string()), + ] + )); + } + + #[test] + fn the_form_shows_its_fields_and_buttons() { + let mut app = test_app(); + let form = stay(form().handle(press(KeyCode::Char(' ')))); + app.overlay = Some(Overlay::Form(form)); + let screen = screen(&mut app, 80, 24); + for text in [ + "Install bat with options", + "[x]", + "[ ]", + "[ Cancel ]", + "[ Install ]", + ] { + assert!(screen.contains(text), "screen is {screen:?}"); + } + } + + #[test] + fn a_field_row_stays_within_the_body_width_it_is_given() { + let theme = crate::theme::Theme::new(true, true); + let mut input = TextInput::default(); + input.set("x".repeat(200)); + let form = Form::new( + "Install bat with options", + vec![Field::Text { + label: "Portable path", + input, + }], + "Install", + OnAccept::Test, + ); + let line = form.field_line(&form.fields[0], false, 60, &theme); + let width: usize = line.spans.iter().map(|span| span.width()).sum(); + assert!(width <= 60, "row is {width} columns, body is 60"); + let line = form.field_line(&form.fields[0], false, 40, &theme); + let width: usize = line.spans.iter().map(|span| span.width()).sum(); + assert!(width <= 40, "row is {width} columns, body is 40"); + } + + /// A form with two required text fields and one checkbox. + fn required_form() -> Form { + Form::new( + "Add repository", + vec![ + Field::RequiredText { + label: "Name", + input: TextInput::default(), + }, + Field::RequiredText { + label: "URL", + input: TextInput::default(), + }, + Field::Check { + label: "Enabled", + checked: true, + }, + ], + "Add", + OnAccept::Test, + ) + } + + #[test] + fn accepting_with_an_empty_required_field_stays_and_sets_the_error() { + let mut form = required_form(); + for _ in 0..4 { + form = stay(form.handle(press(KeyCode::Tab))); + } + assert_eq!(form.focus, 4); + let form = stay(form.handle(press(KeyCode::Enter))); + assert_eq!(form.focus, 0); + assert_eq!(form.error.as_deref(), Some("Name is required")); + } + + #[test] + fn filling_the_required_fields_then_accepting_returns_their_values() { + let mut form = required_form(); + for c in "x".chars() { + form = stay(form.handle(press(KeyCode::Char(c)))); + } + form = stay(form.handle(press(KeyCode::Tab))); + for c in "https://example.com/m.json".chars() { + form = stay(form.handle(press(KeyCode::Char(c)))); + } + for _ in 0..3 { + form = stay(form.handle(press(KeyCode::Tab))); + } + assert_eq!(form.focus, 4); + assert!(matches!( + form.handle(press(KeyCode::Enter)), + OverlayOutcome::Accept(OnAccept::Test, Some(Value::Form(FormValues(values)))) + if values == vec![ + FieldValue::Text("x".to_string()), + FieldValue::Text("https://example.com/m.json".to_string()), + FieldValue::Check(true), + ] + )); + } + + #[test] + fn editing_a_field_clears_the_error_again() { + let mut form = required_form(); + for _ in 0..4 { + form = stay(form.handle(press(KeyCode::Tab))); + } + let form = stay(form.handle(press(KeyCode::Enter))); + assert!(form.error.is_some()); + let form = stay(form.handle(press(KeyCode::Char('a')))); + assert!(form.error.is_none()); + } + + #[test] + fn the_form_shows_the_error_in_danger_above_the_buttons() { + let mut app = test_app(); + let mut form = required_form(); + for _ in 0..4 { + form = stay(form.handle(press(KeyCode::Tab))); + } + let form = stay(form.handle(press(KeyCode::Enter))); + app.overlay = Some(Overlay::Form(form)); + let screen = screen(&mut app, 80, 24); + assert!(screen.contains("Name is required"), "screen is {screen:?}"); + } +} diff --git a/crates/soar-tui/src/widgets/gauge.rs b/crates/soar-tui/src/widgets/gauge.rs new file mode 100644 index 00000000..831f69a8 --- /dev/null +++ b/crates/soar-tui/src/widgets/gauge.rs @@ -0,0 +1,115 @@ +//! The progress bar drawn as a row of gauge glyphs. +//! +//! The views draw it once they hold their own progress. + +#![allow(dead_code)] + +use ratatui::text::{Line, Span}; + +use crate::theme::Theme; + +/// One row of progress `width` columns wide, filled to `ratio` of its +/// length. The ratio clamps to 0..=1 and one that is not a number renders +/// the bar empty. +pub(crate) fn line(ratio: f64, width: u16, theme: &Theme) -> Line<'static> { + let symbols = theme.sym(); + let filled = ((ratio * f64::from(width)).round() as usize).min(usize::from(width)); + let mut spans = Vec::with_capacity(2); + if filled > 0 { + spans.push(Span::styled( + symbols.gauge_fill.repeat(filled), + theme.accent(), + )); + } + let rest = usize::from(width) - filled; + if rest > 0 { + spans.push(Span::styled( + symbols.gauge_empty.repeat(rest), + theme.muted(), + )); + } + Line::from(spans) +} + +#[cfg(test)] +mod tests { + use super::line; + use crate::theme::Theme; + + #[test] + fn a_half_full_gauge_fills_half_the_width() { + let theme = Theme::new(true, true); + let symbols = theme.sym(); + let line = line(0.5, 10, &theme); + assert_eq!(line.width(), 10); + assert_eq!( + line.spans[0].content.to_string(), + symbols.gauge_fill.repeat(5) + ); + assert_eq!( + line.spans[1].content.to_string(), + symbols.gauge_empty.repeat(5) + ); + assert!(line.spans[0].style.fg.is_some()); + assert!(line.spans[1].style.fg.is_some()); + } + + #[test] + fn a_ratio_above_one_fills_the_width() { + let theme = Theme::new(true, true); + let line = line(2.0, 10, &theme); + assert_eq!(line.width(), 10); + assert_eq!(line.spans.len(), 1); + assert_eq!( + line.spans[0].content.to_string(), + theme.sym().gauge_fill.repeat(10) + ); + } + + #[test] + fn a_ratio_below_zero_renders_empty() { + let theme = Theme::new(true, true); + let line = line(-1.0, 10, &theme); + assert_eq!(line.width(), 10); + assert_eq!(line.spans.len(), 1); + assert_eq!( + line.spans[0].content.to_string(), + theme.sym().gauge_empty.repeat(10) + ); + } + + #[test] + fn a_nan_ratio_renders_empty() { + let theme = Theme::new(true, true); + let line = line(f64::NAN, 10, &theme); + assert_eq!(line.width(), 10); + assert_eq!(line.spans.len(), 1); + assert_eq!( + line.spans[0].content.to_string(), + theme.sym().gauge_empty.repeat(10) + ); + } + + #[test] + fn the_ascii_gauge_uses_the_ascii_glyphs() { + let theme = Theme::new(true, false); + let symbols = theme.sym(); + let line = line(0.5, 10, &theme); + assert_eq!( + line.spans[0].content.to_string(), + symbols.gauge_fill.repeat(5) + ); + assert_eq!( + line.spans[1].content.to_string(), + symbols.gauge_empty.repeat(5) + ); + } + + #[test] + fn the_gauge_keeps_its_modifiers_without_color() { + let theme = Theme::new(false, true); + let line = line(0.5, 10, &theme); + assert_eq!(line.spans[0].style.fg, None); + assert_eq!(line.spans[1].style.fg, None); + } +} diff --git a/crates/soar-tui/src/widgets/header.rs b/crates/soar-tui/src/widgets/header.rs new file mode 100644 index 00000000..f071b991 --- /dev/null +++ b/crates/soar-tui/src/widgets/header.rs @@ -0,0 +1,214 @@ +//! The header line: the brand, the view tabs, and the profile with the +//! session mode. + +use ratatui::{ + Frame, + layout::Rect, + style::{Modifier, Style}, + text::{Line, Span}, +}; + +use crate::{app::App, format, theme::Theme, views::ViewId}; + +/// Which extra parts of the header survive as the terminal narrows, fullest +/// first: (version, tab digits, full tab titles). +const DEGRADATIONS: [(bool, bool, bool); 4] = [ + (true, true, true), + (false, true, true), + (false, false, true), + (false, false, false), +]; + +/// One candidate header: its left and right spans, and where its tabs sit +/// relative to the row start. +struct Parts { + left: Vec>, + tabs: Vec<(u16, u16, ViewId)>, + right: Vec>, +} + +/// Draws the header row and records where each tab landed, so pointer +/// clicks can find the tab they hit. +pub(crate) fn render(f: &mut Frame, area: Rect, app: &mut App) { + let row = Rect { + height: 1, + ..area + }; + let header = DEGRADATIONS + .iter() + .find_map(|&(version, digits, full_titles)| { + let candidate = parts(app, version, digits, full_titles, row.width); + let width = spans_width(&candidate.left) + spans_width(&candidate.right); + (width <= row.width as usize).then_some(candidate) + }) + .unwrap_or_else(|| parts(app, false, false, true, row.width)); + app.layout.tabs = header + .tabs + .into_iter() + .map(|(offset, width, view)| { + ( + Rect { + x: row.x + offset, + y: row.y, + width, + height: 1, + }, + view, + ) + }) + .collect(); + f.render_widget(Line::from(header.left), row); + f.render_widget(Line::from(header.right).right_aligned(), row); +} + +/// Builds the header at one degradation level. The right side truncates its +/// profile to whatever the left side leaves of `width`. +fn parts(app: &App, with_version: bool, with_digits: bool, full_titles: bool, width: u16) -> Parts { + let theme = &app.theme; + let symbols = theme.sym(); + let mut left = Vec::new(); + let mut x: usize = 0; + let mut tabs = Vec::with_capacity(ViewId::ALL.len()); + + left.push(Span::raw(" ")); + x += 1; + let brand = format!("{} soar ", symbols.brand); + x += Span::raw(brand.as_str()).width(); + left.push(Span::styled( + brand, + theme.accent().add_modifier(Modifier::BOLD), + )); + if with_version { + x += Span::raw(app.env.version.as_str()).width(); + left.push(Span::styled(app.env.version.clone(), theme.muted())); + } + for (position, view) in ViewId::ALL.iter().enumerate() { + let title = if full_titles { + view.title().to_string() + } else { + view.title().chars().take(3).collect() + }; + let label = if with_digits { + let number = position + 1; + format!("{number} {title}") + } else { + title + }; + left.push(Span::raw(" ")); + x += 2; + let start = x as u16; + let mut tab_width = Span::raw(label.as_str()).width() as u16; + x += tab_width as usize; + left.push(Span::styled(label, tab_style(theme, *view, app.view))); + if *view == ViewId::Updates + && let Some(count) = app.updates_badge() + && count > 0 + { + let badge = Span::styled(format!(" {count}"), theme.warning()); + tab_width += badge.width() as u16; + x += badge.width(); + left.push(badge); + } + if *view == ViewId::Jobs && app.jobs_attention() { + let mark = Span::styled(" !", theme.danger()); + tab_width += mark.width() as u16; + x += mark.width(); + left.push(mark); + } + if *view == ViewId::Jobs && app.running_job().is_some() { + let mark = Span::styled(format!(" {}", theme.spinner(app.frame)), theme.accent()); + tab_width += mark.width() as u16; + x += mark.width(); + left.push(mark); + } + tabs.push((start, tab_width, *view)); + } + + let mode = if app.env.system { "SYSTEM" } else { "user" }; + let mode_style = if app.env.system { + theme.warning().add_modifier(Modifier::BOLD) + } else { + theme.muted() + }; + let reserved = 2 + Span::raw(symbols.dot).width() + Span::raw(mode).width(); + let profile_budget = (width as usize).saturating_sub(reserved); + let profile = format::truncate(&app.env.profile, profile_budget, symbols.ellipsis); + let right = vec![ + Span::styled(profile, theme.text()), + Span::styled(format!(" {} ", symbols.dot), theme.muted()), + Span::styled(mode.to_string(), mode_style), + ]; + Parts { + left, + tabs, + right, + } +} + +/// The style of one tab: the active one stands out. +fn tab_style(theme: &Theme, view: ViewId, active: ViewId) -> Style { + if view == active { + theme + .accent() + .add_modifier(Modifier::BOLD | Modifier::UNDERLINED) + } else { + theme.muted() + } +} + +/// The display width of a row of spans. +fn spans_width(spans: &[Span<'_>]) -> usize { + spans.iter().map(Span::width).sum() +} + +#[cfg(test)] +mod tests { + use crate::{ + test_support::{render, test_app}, + views::ViewId, + }; + + #[test] + fn the_header_shows_tabs_profile_and_mode_at_full_width() { + let mut app = test_app(); + let lines = render(&mut app, 100, 16); + for text in ["1 Browse", "7 Jobs", "default", "user"] { + assert!(lines[0].contains(text), "header is {:?}", lines[0]); + } + assert_eq!(app.layout.tabs.len(), 7); + assert_eq!(app.layout.tabs[0].1, ViewId::Browse); + } + + #[test] + fn system_mode_shows_the_system_badge() { + let mut app = test_app(); + app.env.system = true; + let lines = render(&mut app, 100, 16); + assert!(lines[0].contains("SYSTEM"), "header is {:?}", lines[0]); + } + + #[test] + fn a_narrow_header_drops_the_version_first() { + let mut app = test_app(); + let lines = render(&mut app, 96, 16); + assert!(lines[0].contains("1 Browse"), "header is {:?}", lines[0]); + assert!(!lines[0].contains("0.0.0"), "header is {:?}", lines[0]); + } + + #[test] + fn a_narrower_header_drops_the_tab_digits() { + let mut app = test_app(); + let lines = render(&mut app, 80, 16); + assert!(lines[0].contains("Browse"), "header is {:?}", lines[0]); + assert!(!lines[0].contains("1 Browse"), "header is {:?}", lines[0]); + } + + #[test] + fn the_narrowest_header_shortens_the_titles() { + let mut app = test_app(); + let lines = render(&mut app, 70, 16); + assert!(lines[0].contains("Job"), "header is {:?}", lines[0]); + assert!(!lines[0].contains("Jobs"), "header is {:?}", lines[0]); + assert!(lines[0].contains("default"), "header is {:?}", lines[0]); + } +} diff --git a/crates/soar-tui/src/widgets/help.rs b/crates/soar-tui/src/widgets/help.rs new file mode 100644 index 00000000..62292900 --- /dev/null +++ b/crates/soar-tui/src/widgets/help.rs @@ -0,0 +1,204 @@ +//! The overlay listing every key that works while a view is open. + +use ratatui::{ + Frame, + crossterm::event::{KeyCode, KeyEvent, KeyModifiers}, + layout::Rect, + text::{Line, Span}, + widgets::{Clear, Paragraph}, +}; + +use crate::{ + action::Action, + app::App, + keymap, + theme::Theme, + views::ViewId, + widgets::overlay::{Overlay, OverlayOutcome, centered, frame}, +}; + +/// The key reference of the active view, opened with `?`. +#[derive(Debug)] +pub(crate) struct Help { + view: ViewId, + scroll: u16, +} + +impl Help { + /// Builds the reference for one view, starting at its top. + pub(crate) fn new(view: ViewId) -> Help { + Help { + view, + scroll: 0, + } + } + + /// Acts on one pressed key. `j` and `k` scroll, and esc, `?`, and `q` + /// close. + pub(crate) fn handle(mut self, key: KeyEvent) -> OverlayOutcome { + match (key.code, key.modifiers) { + (KeyCode::Char('j'), KeyModifiers::NONE | KeyModifiers::SHIFT) => { + self.scroll = self.scroll.saturating_add(1); + } + (KeyCode::Char('k'), KeyModifiers::NONE | KeyModifiers::SHIFT) => { + self.scroll = self.scroll.saturating_sub(1); + } + (KeyCode::Esc, _) + | (KeyCode::Char('?') | KeyCode::Char('q'), KeyModifiers::NONE | KeyModifiers::SHIFT) => + { + return OverlayOutcome::Close; + } + _ => {} + } + OverlayOutcome::Stay(Overlay::Help(self)) + } + + /// Draws the reference centered in the body area, taking most of it, + /// and returns the rect it drew into. + pub(crate) fn render(&self, f: &mut Frame, area: Rect, app: &App) -> Rect { + let theme = &app.theme; + let width = u32::from(area.width) * 70 / 100; + let height = u32::from(area.height) * 80 / 100; + let rect = centered(area, width as u16, height as u16); + f.render_widget(Clear, rect); + + let lines = self.lines(app); + let visible = usize::from(rect.height.saturating_sub(2)); + let scroll = usize::from(self.scroll).min(lines.len().saturating_sub(visible)); + let shown: Vec> = lines.into_iter().skip(scroll).take(visible).collect(); + + let block = frame(Line::styled(" Keys ", theme.title()), None, false, theme); + f.render_widget(Paragraph::new(shown).block(block), rect); + rect + } + + /// Every line of the reference: the global keys, then the view's own, + /// and the marks note where marks exist. + fn lines(&self, app: &App) -> Vec> { + let theme = &app.theme; + let view_bindings = keymap::bindings(self.view); + let mut lines = vec![section_line("Global", theme)]; + lines.extend(binding_lines(keymap::GLOBAL, theme)); + lines.push(section_line(self.view.title(), theme)); + lines.extend(binding_lines(view_bindings, theme)); + if view_bindings + .iter() + .any(|binding| matches!(binding.action, Action::ToggleMark)) + { + lines.push(Line::styled( + "Marks select rows for i, d, and u.", + theme.muted(), + )); + lines.push(Line::styled( + "Without marks, the current row is used.", + theme.muted(), + )); + } + lines + } +} + +/// One section heading of the reference. +fn section_line(name: &str, theme: &Theme) -> Line<'static> { + Line::styled(name.to_owned(), theme.title()) +} + +/// The rows of one key table: the keys padded to a fixed width in the key +/// style, then the label. +fn binding_lines(bindings: &[keymap::Binding], theme: &Theme) -> Vec> { + bindings + .iter() + .map(|binding| { + let keys = binding + .keys + .iter() + .map(|key| keymap::key_label(*key)) + .collect::>() + .join("/"); + Line::from(vec![ + Span::styled(format!("{keys:<16}"), theme.key()), + Span::styled(binding.label, theme.muted()), + ]) + }) + .collect() +} + +#[cfg(test)] +mod tests { + use std::time::Instant; + + use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; + + use super::Help; + use crate::{ + test_support::{key, screen, test_app}, + views::ViewId, + widgets::overlay::{Overlay, OverlayOutcome}, + }; + + fn press(c: char) -> KeyEvent { + KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE) + } + + fn stay(outcome: OverlayOutcome) -> Help { + match outcome { + OverlayOutcome::Stay(Overlay::Help(help)) => help, + other => panic!("expected the help to stay open, got {other:?}"), + } + } + + #[test] + fn opening_help_lists_the_global_and_view_keys() { + let mut app = test_app(); + app.update(key('?'), Instant::now()); + assert!(matches!(app.overlay, Some(Overlay::Help(_)))); + let screen = screen(&mut app, 100, 40); + assert!(screen.contains("Global"), "screen is {screen:?}"); + assert!(screen.contains("install"), "screen is {screen:?}"); + } + + #[test] + fn the_marks_note_shows_only_where_marks_exist() { + let mut app = test_app(); + app.update(key('?'), Instant::now()); + assert!(screen(&mut app, 100, 48).contains("Marks select rows")); + + app.overlay = None; + app.view = ViewId::Jobs; + app.update(key('?'), Instant::now()); + assert!(!screen(&mut app, 100, 48).contains("Marks select rows")); + } + + #[test] + fn every_binding_of_the_view_is_listed() { + let mut app = test_app(); + app.overlay = Some(crate::widgets::overlay::Overlay::Help(Help::new( + ViewId::Browse, + ))); + let screen = screen(&mut app, 100, 40); + assert!(screen.contains("install options"), "screen is {screen:?}"); + assert!(screen.contains("page down"), "screen is {screen:?}"); + } + + #[test] + fn j_and_k_scroll() { + let help = stay(Help::new(ViewId::Browse).handle(press('j'))); + assert_eq!(help.scroll, 1); + let help = stay(help.handle(press('k'))); + assert_eq!(help.scroll, 0); + } + + #[test] + fn question_mark_esc_and_q_close() { + for key in ['?', 'q'] { + assert!(matches!( + Help::new(ViewId::Browse).handle(press(key)), + OverlayOutcome::Close + )); + } + assert!(matches!( + Help::new(ViewId::Browse).handle(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)), + OverlayOutcome::Close + )); + } +} diff --git a/crates/soar-tui/src/widgets/installed_detail.rs b/crates/soar-tui/src/widgets/installed_detail.rs new file mode 100644 index 00000000..92b4028f --- /dev/null +++ b/crates/soar-tui/src/widgets/installed_detail.rs @@ -0,0 +1,236 @@ +//! The installed package detail pane: where a package lives and how it +//! was installed, drawn as a headline, a banner for a broken install, and +//! a label and value grid. +//! +//! Beside the list the pane clips its rows at the bottom; filling the +//! screen it scrolls with the view's own cursor. + +use std::{path::Path, time::SystemTime}; + +use ratatui::{ + Frame, + layout::Rect, + text::{Line, Span}, + widgets::{Block, BorderType, Paragraph}, +}; +use soar_operations::InstalledEntry; + +use crate::{app::App, format, theme::Theme, widgets::badge}; + +/// How many cells a grid label keeps before its value starts. +const LABEL_WIDTH: usize = 12; + +/// How many cells a checksum keeps before an ellipsis ends it. +const CHECKSUM_WIDTH: usize = 16; + +/// Draws the pane: a rounded border titled with the package name, then the +/// headline, the banner a broken install shows, and the label and value +/// grid. While the pane fills the screen its rows scroll; beside the list +/// they clip. +pub(crate) fn render(f: &mut Frame, area: Rect, app: &mut App, full: bool) { + let theme = &app.theme; + let title = app + .installed + .cursor_entry() + .map_or_else(|| "Details".to_string(), pane_title); + let block = Block::bordered() + .border_type(BorderType::Rounded) + .border_style(theme.border(true)) + .title(Line::styled(format!(" {title} "), theme.title())); + let inner = block.inner(area); + f.render_widget(block, area); + if full { + // The wheel scrolls this pane while it fills the screen. + app.layout.detail = Some(inner); + } + let width = usize::from(inner.width); + let height = usize::from(inner.height); + let lines = match app.installed.cursor_entry() { + Some(entry) => lines(entry, width, theme), + None => return, + }; + let rows = if full { + app.installed.detail_rows = lines.len(); + app.installed.detail.window(lines.len(), height) + } else { + 0..lines.len().min(height) + }; + f.render_widget(Paragraph::new(lines[rows].to_vec()), inner); +} + +/// The pane's rows: the headline, the banner a broken install shows, then +/// the label and value grid. +fn lines(entry: &InstalledEntry, width: usize, theme: &Theme) -> Vec> { + let mut lines = vec![headline(entry, theme)]; + if !entry.is_healthy { + lines.push(broken_banner(theme)); + } + lines.push(Line::raw("")); + grid(entry, width, theme, &mut lines); + lines +} + +/// The pane title: `family/name` when a family is recorded, else the name. +fn pane_title(entry: &InstalledEntry) -> String { + match entry.package.pkg_family.as_deref() { + Some(family) => format!("{family}/{}", entry.package.pkg_name), + None => entry.package.pkg_name.clone(), + } +} + +/// The first row: the version, the package type, and the repository. +fn headline(entry: &InstalledEntry, theme: &Theme) -> Line<'static> { + let mut spans = vec![Span::styled(entry.package.version.clone(), theme.accent2())]; + if let Some(pkg_type) = entry.package.pkg_type.as_deref() { + spans.push(Span::raw(" ")); + spans.push(badge::pkg_type(Some(pkg_type), theme)); + } + spans.push(Span::raw(" ")); + spans.push(Span::styled(entry.package.repo_name.clone(), theme.info())); + Line::from(spans) +} + +/// The danger row under the headline when the installed files are gone +/// from disk. +fn broken_banner(theme: &Theme) -> Line<'static> { + Line::from(vec![ + Span::styled(theme.sym().error, theme.danger()), + Span::styled( + " Files are missing. Remove it, or use Health (6) to clean up.", + theme.danger(), + ), + ]) +} + +/// The label and value grid. A fact the record omits leaves no row. +fn grid(entry: &InstalledEntry, width: usize, theme: &Theme, lines: &mut Vec>) { + let budget = width.saturating_sub(LABEL_WIDTH); + let ellipsis = theme.sym().ellipsis; + let mut grid: Vec<(&'static str, String)> = Vec::new(); + let path = format::home_relative(Path::new(&entry.package.installed_path)); + if !path.is_empty() { + grid.push(("Path", format::truncate_middle(&path, budget, ellipsis))); + } + if let Some(installed) = installed_line(entry) { + grid.push(("Installed", installed)); + } + grid.push(("Size", format::size(entry.disk_size))); + if let Some(checksum) = entry.package.checksum.as_deref() { + grid.push(( + "Checksum", + format::truncate(checksum, CHECKSUM_WIDTH, ellipsis), + )); + } + if !entry.package.profile.is_empty() { + grid.push(("Profile", entry.package.profile.clone())); + } + portable_dirs(entry, &mut grid); + provides(entry, &mut grid); + if let Some(url) = entry + .package + .download_url + .as_deref() + .filter(|url| !url.is_empty()) + { + grid.push(("Source", url.to_string())); + } + if let Some(flags) = flags_line(entry) { + grid.push(("Flags", flags)); + } + for (label, value) in grid { + if value.is_empty() { + continue; + } + lines.push(Line::from(vec![ + Span::styled( + format!("{: Option { + let date = &entry.package.installed_date; + if date.is_empty() { + return None; + } + let mut line = date.clone(); + if let Some(then) = format::parse_installed_date(date) { + line.push_str(&format!(" ({})", format::relative(then, SystemTime::now()))); + } + Some(line) +} + +/// One grid row per portable directory the package keeps, as `home +/// ~/path` style, with the label on the first row only. +fn portable_dirs(entry: &InstalledEntry, grid: &mut Vec<(&'static str, String)>) { + let dirs = [ + ("home", entry.package.portable_home.as_deref()), + ("config", entry.package.portable_config.as_deref()), + ("share", entry.package.portable_share.as_deref()), + ("cache", entry.package.portable_cache.as_deref()), + ]; + let mut first = true; + for (name, path) in dirs { + let Some(path) = path.filter(|path| !path.is_empty()) else { + continue; + }; + grid.push(( + if first { "Portable" } else { "" }, + format!("{name} {}", format::home_relative(Path::new(path))), + )); + first = false; + } +} + +/// The provides row: one entry per provide, `@name` when it links straight +/// into bin, `name=>target` style when it carries a target. +fn provides(entry: &InstalledEntry, grid: &mut Vec<(&'static str, String)>) { + let Some(provides) = entry + .package + .provides + .as_deref() + .filter(|provides| !provides.is_empty()) + else { + return; + }; + let names = provides + .iter() + .map(|provide| { + let mut text = if provide.symlink_to_bin { + format!("@{}", provide.name) + } else { + provide.name.clone() + }; + if let Some(target) = provide.target.as_deref() { + if let Some(strategy) = provide.strategy.as_ref() { + text.push_str(&strategy.to_string()); + } + text.push_str(target); + } + text + }) + .collect::>() + .join(", "); + grid.push(("Provides", names)); +} + +/// The flags row: the words for the record's pinned, detached, and not +/// active states, in that order, when any holds. +fn flags_line(entry: &InstalledEntry) -> Option { + let mut flags: Vec<&'static str> = Vec::new(); + if entry.package.pinned { + flags.push("pinned"); + } + if entry.package.detached { + flags.push("detached"); + } + if entry.package.unlinked { + flags.push("inactive"); + } + (!flags.is_empty()).then(|| flags.join(", ")) +} diff --git a/crates/soar-tui/src/widgets/mod.rs b/crates/soar-tui/src/widgets/mod.rs new file mode 100644 index 00000000..50deaf44 --- /dev/null +++ b/crates/soar-tui/src/widgets/mod.rs @@ -0,0 +1,20 @@ +//! Reusable drawing pieces the frame and the views assemble their screens +//! from. + +pub(crate) mod activity; +pub(crate) mod authorize; +pub(crate) mod badge; +pub(crate) mod confirm; +pub(crate) mod form; +pub(crate) mod gauge; +pub(crate) mod header; +pub(crate) mod help; +pub(crate) mod installed_detail; +pub(crate) mod overlay; +pub(crate) mod package_detail; +pub(crate) mod picker; +pub(crate) mod scroll; +pub(crate) mod states; +pub(crate) mod status_bar; +pub(crate) mod text_input; +pub(crate) mod toast; diff --git a/crates/soar-tui/src/widgets/overlay.rs b/crates/soar-tui/src/widgets/overlay.rs new file mode 100644 index 00000000..7d4cc0c1 --- /dev/null +++ b/crates/soar-tui/src/widgets/overlay.rs @@ -0,0 +1,356 @@ +//! The dialogs that draw over the active view and capture every key press +//! until the user closes or accepts them. + +use ratatui::{ + Frame, + crossterm::event::{KeyCode, KeyEvent}, + layout::Rect, + text::{Line, Span}, + widgets::{Block, BorderType, Clear, Padding, Paragraph}, +}; +use soar_core::database::models::InstalledPackage; +use soar_operations::privilege::EscalationTool; + +use crate::{ + app::App, + privileged::Secret, + theme::Theme, + widgets::{ + authorize::Authorize, + confirm::Confirm, + form::{Form, FormValues}, + help::Help, + picker::Picker, + text_input::Prompt, + }, +}; +/// A dialog drawn over the active view. While one is open it captures every +/// key press. +#[derive(Debug)] +pub(crate) enum Overlay { + /// A yes-or-no dialog that names everything about to change. + Confirm(Confirm), + /// A list of rows, accepted by index. + Picker(Picker), + /// A single line of text, accepted as that text. + Prompt(Prompt), + /// Checkboxes and text fields, accepted as their values. + Form(Form), + /// The key reference of the active view. + Help(Help), + /// The choice of how to quit while a job runs. + QuitGuard(QuitGuard), + /// The administrator password dialog for the system pass. + Authorize(Authorize), +} + +impl Overlay { + /// Hands one pressed key to the overlay and reports what it decided. + pub(crate) fn handle(self, key: KeyEvent) -> OverlayOutcome { + match self { + Overlay::Confirm(confirm) => confirm.handle(key), + Overlay::Picker(picker) => picker.handle(key), + Overlay::Prompt(prompt) => prompt.handle(key), + Overlay::Form(form) => form.handle(key), + Overlay::Help(help) => help.handle(key), + Overlay::QuitGuard(guard) => guard.handle(key), + Overlay::Authorize(dialog) => dialog.handle(key), + } + } + + /// Draws the overlay centered in `area`, over what it holds, and + /// returns the rect it drew into. + pub(crate) fn render(&self, f: &mut Frame, area: Rect, app: &App) -> Rect { + match self { + Overlay::Confirm(confirm) => confirm.render(f, area, app), + Overlay::Picker(picker) => picker.render(f, area, app), + Overlay::Prompt(prompt) => prompt.render(f, area, app), + Overlay::Form(form) => form.render(f, area, app), + Overlay::Help(help) => help.render(f, area, app), + Overlay::QuitGuard(guard) => guard.render(f, area, app), + Overlay::Authorize(dialog) => dialog.render(f, area, app), + } + } +} + +/// The dialog that opens when quitting while a job runs: wait for it, stop +/// it and quit, or stay. The focus starts on cancel so an accidental enter +/// cannot act. +#[derive(Debug)] +pub(crate) struct QuitGuard { + /// What runs and what waits behind it. + body: Vec>, + /// The focused button: 0 cancel, 1 wait, 2 abort and quit. + focus: usize, +} + +/// The guard's buttons in focus order. +const QUIT_BUTTONS: [&str; 3] = ["Cancel", "Wait and quit", "Abort and quit"]; + +impl QuitGuard { + /// Builds the guard naming the running job and how much is queued + /// behind it. + pub(crate) fn new(running_title: &str, queued: usize) -> QuitGuard { + let mut body = vec![Line::raw(format!("A job is running: {running_title}."))]; + if queued > 0 { + body.push(Line::raw(format!("{queued} more queued."))); + } + QuitGuard { + body, + focus: 0, + } + } + + /// Acts on one pressed key. The movement keys cycle the focus, enter + /// presses the focused button, and esc and n stay. + pub(crate) fn handle(mut self, key: KeyEvent) -> OverlayOutcome { + match (key.code, key.modifiers) { + ( + KeyCode::Left + | KeyCode::Right + | KeyCode::Tab + | KeyCode::Char('h') + | KeyCode::Char('l'), + _, + ) => { + self.focus = (self.focus + 1) % QUIT_BUTTONS.len(); + OverlayOutcome::Stay(Overlay::QuitGuard(self)) + } + (KeyCode::Enter, _) => { + match self.focus { + 0 => OverlayOutcome::Close, + 1 => OverlayOutcome::Accept(OnAccept::QuitWait, None), + _ => OverlayOutcome::Accept(OnAccept::QuitAbort, None), + } + } + (KeyCode::Esc, _) | (KeyCode::Char('n'), _) => OverlayOutcome::Close, + _ => OverlayOutcome::Stay(Overlay::QuitGuard(self)), + } + } + + /// Draws the guard centered in the body area, and returns the rect it + /// drew into. + pub(crate) fn render(&self, f: &mut Frame, area: Rect, app: &App) -> Rect { + let theme = &app.theme; + let width = area.width.saturating_sub(4).min(64); + let rect = centered(area, width, self.body.len() as u16 + 6); + f.render_widget(Clear, rect); + + let mut lines = vec![Line::raw("")]; + lines.extend(self.body.iter().cloned()); + lines.push(Line::raw("")); + let mut spans = Vec::new(); + for (i, label) in QUIT_BUTTONS.iter().enumerate() { + if i > 0 { + spans.push(Span::raw(" ")); + } + let style = if i == self.focus { + theme.cursor_row() + } else { + theme.text() + }; + spans.push(Span::styled(format!("[ {label} ]"), style)); + } + lines.push(Line::from(spans).right_aligned()); + + let block = frame(Line::styled(" Quit ", theme.title()), None, false, theme); + f.render_widget(Paragraph::new(lines).block(block), rect); + rect + } +} + +/// What an accepted overlay asks the interface to do. +#[derive(Debug)] +pub(crate) enum OnAccept { + /// Wait for the running job to finish, then quit. + QuitWait, + /// Stop the running job, then quit once it stops. + QuitAbort, + /// Quit right away, leaving the running job where it is. + QuitForce, + /// Stops the running job, after the abort confirm was accepted. + Abort, + /// Queues the removal of the installed packages the confirm listed, + /// exactly the rows the user chose. + Remove(Vec), + /// Queues the updates the confirm listed: the selected entries move + /// out of the ready list when the accept lands. + UpdateNow, + /// Records the variant the picker chose for an ambiguous install + /// query, then moves on to the next step of the flow. + PickVariant, + /// Queues the install the confirm listed. + InstallNow, + /// Builds the install choices out of the accepted options form, then + /// resolves the selected rows with them. + InstallWithOptions, + /// Starts the install flow for the version the picker chose. + PickVersion, + /// Starts the install flow for the queries the prompt collected. + InstallByQuery, + /// Prepares the run of the row the prompt was opened for, with the + /// arguments the prompt collected. + RunArguments, + /// Prepares the run again for the exact variant the picker chose. + RunVariant, + /// Links the variant the variants picker chose, keeping nothing when + /// the active one was chosen. + SwitchVariant, + /// Links the named variant the switch confirm accepted. + SwitchConfirm { + /// The database id of the variant to link. + id: u64, + /// The package name, for the job's title. + name: String, + }, + /// Enables or disables the repository the confirm named. + RepoEnabled { + /// The repository to change. + name: String, + /// Whether it becomes enabled. + enabled: bool, + }, + /// Removes the repository the confirm named. + RepoRemoved { + /// The repository to remove. + name: String, + }, + /// Queues the cache clean the health confirm named. + CleanCacheConfirm, + /// Queues the removal of the broken symlinks the health confirm + /// listed. + FixSymlinksConfirm, + /// Queues the removal of the broken packages the health confirm + /// listed. + RemoveBrokenConfirm, + /// Adds the repository the form collected, then queues a sync so its + /// packages appear in Browse. + AddRepo, + /// Queues the apply of the declarative packages file, moving the + /// loaded plan's diff into the job. + ApplyPlan, + /// Runs the system pass with the terminal handed over, so doas can + /// ask for the password itself. The tool runs the pass; everything + /// else about the job is read from the queue. + SystemTerminal { + /// The escalation tool that asks for the password. + tool: EscalationTool, + }, + /// Stands in for a real action, letting tests observe an accepted + /// overlay. + #[cfg(test)] + Test, +} + +/// The answer of an accepted overlay. +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum Value { + /// The index of the chosen picker row. + Index(usize), + /// The text the prompt collected, already trimmed. + Text(String), + /// The values of every form field, in field order. + Form(FormValues), +} + +/// What an overlay decided to do with one pressed key. +#[derive(Debug)] +pub(crate) enum OverlayOutcome { + /// The overlay stays open and keeps the state it built. It carries + /// itself back because the handler took ownership to be able to hand + /// over its accept decision. + Stay(Overlay), + /// The overlay closed without acting. + Close, + /// The user accepted: the overlay carries what to do and its answer. + Accept(OnAccept, Option), + /// The password dialog submitted: the secret goes straight to the + /// runner's password check, never through the debug-derived accept + /// payloads, and the interface waits for the check's answer. + Authenticate(Secret), +} + +/// The rect of a dialog `width` by `height` centered in `area`, never +/// leaving it. +pub(crate) fn centered(area: Rect, width: u16, height: u16) -> Rect { + let width = width.min(area.width); + let height = height.min(area.height); + Rect { + x: area.x.saturating_add(area.width.saturating_sub(width) / 2), + y: area + .y + .saturating_add(area.height.saturating_sub(height) / 2), + width, + height, + } +} + +/// The shared dialog chrome: a rounded border in the danger or accent +/// color, one column of padding, and the footer right-aligned on the bottom +/// border when one is given. +pub(crate) fn frame<'a>( + title: Line<'a>, + footer: Option>, + danger: bool, + theme: &Theme, +) -> Block<'a> { + let border = if danger { + theme.danger() + } else { + theme.accent() + }; + let block = Block::bordered() + .border_type(BorderType::Rounded) + .border_style(border) + .title(title) + .padding(Padding::horizontal(1)); + match footer { + Some(footer) => block.title_bottom(footer.right_aligned()), + None => block, + } +} + +/// The bottom row of a dialog: the cancel and action buttons with the +/// focused one highlighted. In a danger dialog the action text keeps the +/// danger style while unfocused. +pub(crate) fn buttons( + action_label: &str, + cancel_focused: bool, + action_focused: bool, + danger: bool, + theme: &Theme, +) -> Line<'static> { + let focused = theme.cursor_row(); + let plain = theme.text(); + let cancel = Span::styled("[ Cancel ]", if cancel_focused { focused } else { plain }); + let action_style = if action_focused { + focused + } else if danger { + theme.danger() + } else { + plain + }; + let action = Span::styled(format!("[ {action_label} ]"), action_style); + Line::from(vec![cancel, Span::raw(" "), action]) +} + +#[cfg(test)] +mod tests { + use super::centered; + + #[test] + fn a_dialog_bigger_than_the_area_fills_it() { + let area = ratatui::layout::Rect::new(0, 0, 40, 10); + assert_eq!(centered(area, 100, 20), area); + } + + #[test] + fn a_small_dialog_sits_in_the_middle() { + let area = ratatui::layout::Rect::new(5, 5, 40, 10); + let rect = centered(area, 10, 4); + assert_eq!(rect.x, 20); + assert_eq!(rect.y, 8); + assert_eq!(rect.width, 10); + assert_eq!(rect.height, 4); + } +} diff --git a/crates/soar-tui/src/widgets/package_detail.rs b/crates/soar-tui/src/widgets/package_detail.rs new file mode 100644 index 00000000..2ffec927 --- /dev/null +++ b/crates/soar-tui/src/widgets/package_detail.rs @@ -0,0 +1,458 @@ +//! The package detail pane: what the repositories know about the package +//! under the catalog cursor, drawn as a headline, warning banners, a +//! wrapped description, a label and value grid, and notes. +//! +//! Beside the list the pane clips its rows at the bottom; filling the +//! screen it scrolls with the view's own cursor. + +use ratatui::{ + Frame, + layout::Rect, + text::{Line, Span}, + widgets::{Block, BorderType, Paragraph}, +}; +use soar_core::database::models::Package; + +use crate::{ + app::App, + format, + loadable::Loadable, + theme::Theme, + views::browse::CatalogRow, + widgets::{badge, states}, +}; + +/// How many cells a grid label keeps before its value starts. +const LABEL_WIDTH: usize = 12; + +/// How many versions the grid lists before it counts the rest. +const VERSIONS_SHOWN: usize = 5; + +/// Draws the pane: a rounded border titled with the package name, then the +/// detail rows, or the state a failed load shows. While the pane fills the +/// screen its rows scroll; beside the list they clip. +pub(crate) fn render(f: &mut Frame, area: Rect, app: &mut App, full: bool) { + let theme = &app.theme; + let row = app.browse.cursor_row().cloned(); + let title = row + .as_ref() + .map(|row| row.key.pkg_name.clone()) + .unwrap_or_else(|| "Details".to_string()); + let block = Block::bordered() + .border_type(BorderType::Rounded) + .border_style(theme.border(true)) + .title(Line::styled(format!(" {title} "), theme.title())); + let inner = block.inner(area); + f.render_widget(block, area); + if full { + // The wheel scrolls this pane while it fills the screen. + app.layout.detail = Some(inner); + } + let Some(row) = row else { + return; + }; + let entry = app.browse.details.get(&row.key); + if let Some(Loadable::Failed(error)) = entry { + states::error(f, inner, theme, error); + return; + } + let lines = lines(&row, entry, usize::from(inner.width), app.frame, theme); + let height = usize::from(inner.height); + let rows = if full { + app.browse.detail_rows = lines.len(); + app.browse.detail.window(lines.len(), height) + } else { + 0..lines.len().min(height) + }; + f.render_widget(Paragraph::new(lines[rows].to_vec()), inner); +} + +/// The pane's rows: the headline, the warning banners, the wrapped +/// description, then the package's facts and notes, or the line a pending +/// or empty load shows. +fn lines( + row: &CatalogRow, + entry: Option<&Loadable>>, + width: usize, + frame: u64, + theme: &Theme, +) -> Vec> { + let mut lines = vec![headline(row, theme)]; + if let Some(Loadable::Ready(Some(package))) = entry { + banners(package, theme, &mut lines); + } + lines.push(Line::raw("")); + let before = lines.len(); + lines.extend( + format::wrap(&row.description, width) + .into_iter() + .map(|piece| Line::styled(piece, theme.text())), + ); + if lines.len() > before { + lines.push(Line::raw("")); + } + match entry { + Some(Loadable::Ready(Some(package))) => facts(row, package, width, theme, &mut lines), + Some(Loadable::Ready(None)) => { + lines.push(Line::styled("not found".to_string(), theme.muted())); + } + Some(Loadable::Loading) => { + lines.push(Line::styled( + format!("{} loading details", theme.spinner(frame)), + theme.muted(), + )) + } + _ => {} + } + lines +} + +/// The first row: the version, the package type, and the installed mark. +fn headline(row: &CatalogRow, theme: &Theme) -> Line<'static> { + let mut spans = vec![Span::styled(row.version.clone(), theme.accent2())]; + if let Some(pkg_type) = row.pkg_type.as_deref() { + spans.push(Span::raw(" ")); + spans.push(badge::pkg_type(Some(pkg_type), theme)); + } + if row.installed { + spans.push(Span::raw(" ")); + spans.push(Span::styled( + format!("{} installed", theme.sym().installed), + theme.success(), + )); + } + Line::from(spans) +} + +/// The warning rows above the description: a deprecated package, and a +/// disabled one with its reason. +fn banners(package: &Package, theme: &Theme, lines: &mut Vec>) { + let symbol = theme.sym().warning; + if package.deprecated { + lines.push(Line::from(vec![ + Span::styled(symbol, theme.warning()), + Span::styled(" Deprecated", theme.warning()), + ])); + } + if package.disabled == Some(true) { + let mut text = "Disabled".to_string(); + if let Some(reason) = package.disabled_reason.as_deref().filter(|r| !r.is_empty()) { + text.push_str(": "); + text.push_str(reason); + } + lines.push(Line::from(vec![ + Span::styled(symbol, theme.warning()), + Span::styled(format!(" {text}"), theme.warning()), + ])); + } +} + +/// The label and value grid, then the notes. A fact the package omits +/// leaves no row. +fn facts( + row: &CatalogRow, + package: &Package, + width: usize, + theme: &Theme, + lines: &mut Vec>, +) { + let mut grid: Vec<(&'static str, String)> = Vec::new(); + grid.push(("Repository", row.key.repo_name.clone())); + if let Some(family) = row.key.pkg_family.as_deref() { + grid.push(("Family", family.to_string())); + } + if let Some(bytes) = package.ghcr_size.or(package.size) { + grid.push(("Size", format::size(bytes))); + } + joined(&mut grid, "License", package.licenses.as_deref()); + if let Some(homepages) = package.homepages.as_deref().and_then(non_empty) { + let rest = homepages.len().saturating_sub(1); + let value = if rest > 0 { + format!("{} +{rest}", homepages[0]) + } else { + homepages[0].clone() + }; + grid.push(("Homepage", value)); + } + if let Some(sources) = package.source_urls.as_deref().and_then(non_empty) { + grid.push(("Source", sources[0].clone())); + } + if let Some(maintainers) = package.maintainers.as_deref().and_then(non_empty) { + let names = maintainers + .iter() + .map(|maintainer| maintainer.name.clone()) + .collect::>() + .join(", "); + grid.push(("Maintainer", names)); + } + joined(&mut grid, "Categories", package.categories.as_deref()); + if let Some(provides) = package.provides.as_deref().and_then(non_empty) { + let names = provides + .iter() + .map(|provide| provide.name.clone()) + .collect::>() + .join(", "); + grid.push(("Provides", names)); + } + if let Some(date) = package + .build_date + .as_deref() + .filter(|date| !date.is_empty()) + { + let day = date.split([' ', 'T']).next().unwrap_or(date); + grid.push(("Built", day.to_string())); + } + if let Some(versions) = versions_line(row) { + grid.push(("Versions", versions)); + } + let budget = width.saturating_sub(LABEL_WIDTH); + for (label, value) in grid { + if value.is_empty() { + continue; + } + lines.push(Line::from(vec![ + Span::styled( + format!("{: Option { + let versions = &row.other_versions; + if versions.is_empty() { + return None; + } + let shown = versions + .iter() + .take(VERSIONS_SHOWN) + .cloned() + .collect::>() + .join(", "); + let rest = versions.len().saturating_sub(VERSIONS_SHOWN); + Some(if rest > 0 { + format!("{shown} +{rest}") + } else { + shown + }) +} + +/// Adds a grid row that joins a list of values with commas, when there is +/// at least one. +fn joined(grid: &mut Vec<(&'static str, String)>, label: &'static str, values: Option<&[String]>) { + let Some(values) = values.and_then(non_empty) else { + return; + }; + grid.push((label, values.join(", "))); +} + +/// The slice itself when it holds at least one entry. +fn non_empty(values: &[T]) -> Option<&[T]> { + (!values.is_empty()).then_some(values) +} + +#[cfg(test)] +mod tests { + use std::time::Instant; + + use soar_core::database::models::{Maintainer, Package}; + + use crate::{ + loadable::Loadable, + msg::{Loaded, Msg}, + test_support::{catalog_row, package, screen, test_app}, + views::browse::{CatalogRow, PackageKey}, + }; + + /// A catalog reply for the load the app still expects before any + /// reload has started. + fn loaded(rows: Vec) -> Msg { + Msg::Loaded(Loaded::Catalog { + check: 0, + result: Ok(rows), + }) + } + + /// Builds the interface with the catalog loaded, the cursor resting on + /// `bat`, and the given package stored as its loaded details. + fn app_with_detail(description: &str, package: &Package) -> crate::app::App { + let mut app = test_app(); + let mut rows = vec![catalog_row("bat", "0.24.0", "bincache")]; + rows[0].description = description.to_string(); + app.update(loaded(rows), Instant::now()); + let key = PackageKey { + repo_name: "bincache".to_string(), + pkg_name: "bat".to_string(), + pkg_family: None, + pkg_id: None, + }; + app.browse + .details + .insert(key, Loadable::Ready(Some(package.clone()))); + app + } + + #[test] + fn the_pane_lists_licenses_sizes_and_notes() { + let mut bat = package("bat", "0.24.0", "bincache"); + bat.licenses = Some(vec!["MIT".to_string(), "Apache-2.0".to_string()]); + bat.ghcr_size = Some(5_452_595); + bat.homepages = Some(vec!["https://github.com/sharkdp/bat".to_string()]); + bat.build_date = Some("2026-11-02 13:45:07".to_string()); + bat.notes = Some(vec!["Config lives in ~/.config/bat".to_string()]); + let mut app = app_with_detail("A cat clone with syntax highlighting.", &bat); + let screen = screen(&mut app, 100, 30); + assert!(screen.contains("MIT, Apache-2.0"), "screen is {screen:?}"); + assert!( + screen.contains("Config lives in ~/.config/bat"), + "screen is {screen:?}" + ); + assert!(screen.contains("5.2 MiB"), "screen is {screen:?}"); + assert!(screen.contains("2026-11-02"), "screen is {screen:?}"); + assert!(screen.contains("bincache"), "screen is {screen:?}"); + } + + #[test] + fn a_deprecated_and_disabled_package_warns_above_the_description() { + let mut bat = package("bat", "0.24.0", "bincache"); + bat.deprecated = true; + bat.disabled = Some(true); + bat.disabled_reason = Some("upstream is gone".to_string()); + let mut app = app_with_detail("A cat clone.", &bat); + let screen = screen(&mut app, 100, 24); + assert!(screen.contains("Deprecated"), "screen is {screen:?}"); + assert!( + screen.contains("Disabled: upstream is gone"), + "screen is {screen:?}" + ); + } + + #[test] + fn a_pending_detail_shows_the_known_fields_and_a_spinner() { + let mut app = test_app(); + let mut rows = vec![catalog_row("bat", "0.24.0", "bincache")]; + rows[0].description = "A cat clone.".to_string(); + rows[0].installed = true; + rows[0].pkg_type = Some("static".to_string()); + app.update(loaded(rows), Instant::now()); + let key = PackageKey { + repo_name: "bincache".to_string(), + pkg_name: "bat".to_string(), + pkg_family: None, + pkg_id: None, + }; + app.browse.details.insert(key, Loadable::Loading); + let screen = screen(&mut app, 100, 24); + assert!(screen.contains("loading details"), "screen is {screen:?}"); + assert!(screen.contains("A cat clone."), "screen is {screen:?}"); + assert!(screen.contains("0.24.0"), "screen is {screen:?}"); + assert!(screen.contains("installed"), "screen is {screen:?}"); + } + + #[test] + fn an_empty_detail_shows_not_found() { + let mut app = test_app(); + app.update( + loaded(vec![catalog_row("bat", "0.24.0", "bincache")]), + Instant::now(), + ); + let key = PackageKey { + repo_name: "bincache".to_string(), + pkg_name: "bat".to_string(), + pkg_family: None, + pkg_id: None, + }; + app.browse.details.insert(key, Loadable::Ready(None)); + let screen = screen(&mut app, 100, 24); + assert!(screen.contains("not found"), "screen is {screen:?}"); + } + + #[test] + fn the_grid_lists_five_versions_and_counts_the_rest() { + let mut app = test_app(); + let mut rows = vec![catalog_row("bat", "0.24.0", "bincache")]; + rows[0].other_versions = (1..=7).map(|n| format!("0.{n}")).collect(); + app.update(loaded(rows), Instant::now()); + let key = PackageKey { + repo_name: "bincache".to_string(), + pkg_name: "bat".to_string(), + pkg_family: None, + pkg_id: None, + }; + app.browse.details.insert( + key, + Loadable::Ready(Some(package("bat", "0.24.0", "bincache"))), + ); + let screen = screen(&mut app, 100, 30); + assert!( + screen.contains("0.1, 0.2, 0.3, 0.4, 0.5 +2"), + "screen is {screen:?}" + ); + } + + #[test] + fn maintainers_show_their_names_without_contacts() { + let mut bat = package("bat", "0.24.0", "bincache"); + bat.maintainers = Some(vec![Maintainer { + name: "Jane Doe".to_string(), + contact: "jane@example.com".to_string(), + }]); + let mut app = app_with_detail("A cat clone.", &bat); + let screen = screen(&mut app, 100, 24); + assert!(screen.contains("Jane Doe"), "screen is {screen:?}"); + assert!(!screen.contains("jane@example.com"), "screen is {screen:?}"); + } + + #[test] + fn several_homepages_count_the_ones_beyond_the_first() { + let mut bat = package("bat", "0.24.0", "bincache"); + bat.homepages = Some(vec![ + "https://bat.example".to_string(), + "https://bat-docs.example".to_string(), + "https://bat-chat.example".to_string(), + ]); + let mut app = app_with_detail("A cat clone.", &bat); + let screen = screen(&mut app, 100, 24); + assert!( + screen.contains("https://bat.example +2"), + "screen is {screen:?}" + ); + assert!(!screen.contains("bat-chat.example"), "screen is {screen:?}"); + } + + #[test] + fn below_100_columns_the_pane_stays_hidden() { + let mut app = app_with_detail( + "uniquely hidden pane text", + &package("bat", "0.24.0", "bincache"), + ); + let narrow = screen(&mut app, 99, 24); + assert!( + !narrow.contains("uniquely hidden pane text"), + "screen is {narrow:?}" + ); + let wide = screen(&mut app, 100, 24); + assert!( + wide.contains("uniquely hidden pane text"), + "screen is {wide:?}" + ); + } +} diff --git a/crates/soar-tui/src/widgets/picker.rs b/crates/soar-tui/src/widgets/picker.rs new file mode 100644 index 00000000..9c47229e --- /dev/null +++ b/crates/soar-tui/src/widgets/picker.rs @@ -0,0 +1,222 @@ +//! The dialog that picks one row out of a list. + +use ratatui::{ + Frame, + crossterm::event::{KeyCode, KeyEvent, KeyModifiers}, + layout::Rect, + text::{Line, Span}, + widgets::{Clear, Paragraph}, +}; + +use crate::{ + app::App, + widgets::{ + overlay::{OnAccept, Overlay, OverlayOutcome, Value, centered, frame}, + scroll::ListCursor, + }, +}; + +/// A dialog listing the choices for one decision, accepted by index. +#[derive(Debug)] +pub(crate) struct Picker { + title: String, + rows: Vec>, + cursor: ListCursor, + on_accept: OnAccept, +} + +impl Picker { + /// Builds a picker over `rows`, starting at the first one. The views + /// open pickers once they gain their actions; until then only tests + /// build one. + #[allow(dead_code)] + pub(crate) fn new( + title: impl Into, + rows: Vec>, + on_accept: OnAccept, + ) -> Picker { + Picker { + title: title.into(), + rows, + cursor: ListCursor::default(), + on_accept, + } + } + + /// Acts on one pressed key. The movement keys move the cursor, enter + /// accepts it, and esc closes. + pub(crate) fn handle(mut self, key: KeyEvent) -> OverlayOutcome { + let len = self.rows.len(); + match (key.code, key.modifiers) { + (KeyCode::Char('j') | KeyCode::Down, KeyModifiers::NONE | KeyModifiers::SHIFT) => { + self.cursor.down(1, len); + } + (KeyCode::Char('k') | KeyCode::Up, KeyModifiers::NONE | KeyModifiers::SHIFT) => { + self.cursor.up(1); + } + (KeyCode::Char('g') | KeyCode::Home, KeyModifiers::NONE | KeyModifiers::SHIFT) => { + self.cursor.top(); + } + (KeyCode::Char('G') | KeyCode::End, KeyModifiers::NONE | KeyModifiers::SHIFT) => { + self.cursor.bottom(len); + } + (KeyCode::Enter, _) if len > 0 => { + return OverlayOutcome::Accept( + self.on_accept, + Some(Value::Index(self.cursor.selected)), + ); + } + (KeyCode::Esc, _) => return OverlayOutcome::Close, + _ => {} + } + OverlayOutcome::Stay(Overlay::Picker(self)) + } + + /// Draws the picker centered in the body area, scrolling its rows with + /// the cursor, and returns the rect it drew into. + pub(crate) fn render(&self, f: &mut Frame, area: Rect, app: &App) -> Rect { + let theme = &app.theme; + let width = area.width.saturating_sub(4).min(72); + let height = (self.rows.len() as u16 + 2).min(area.height.saturating_sub(4)); + let rect = centered(area, width, height); + f.render_widget(Clear, rect); + + let visible = usize::from(rect.height.saturating_sub(2)); + // The window derives from the cursor every frame, so its offset + // needs no persistence between frames. + let mut cursor = self.cursor; + let window = cursor.window(self.rows.len(), visible); + + let symbols = theme.sym(); + let mut lines = Vec::new(); + for (index, row) in self + .rows + .iter() + .enumerate() + .skip(window.start) + .take(window.end - window.start) + { + let selected = index == self.cursor.selected; + let marker = if selected { symbols.cursor } else { " " }; + let mut spans = Vec::with_capacity(row.spans.len() + 2); + spans.push(Span::raw(marker)); + spans.push(Span::raw(" ")); + spans.extend(row.spans.iter().cloned()); + let mut line = Line::from(spans); + if selected { + line = line.style(theme.cursor_row()); + } + lines.push(line); + } + + let footer = format!(" enter pick {} esc ", symbols.dot); + let block = frame( + Line::styled(format!(" {} ", self.title), theme.title()), + Some(Line::styled(footer, theme.muted())), + false, + theme, + ); + f.render_widget(Paragraph::new(lines).block(block), rect); + rect + } +} + +#[cfg(test)] +mod tests { + use ratatui::{ + crossterm::event::{KeyCode, KeyEvent, KeyModifiers}, + text::Line, + }; + + use super::Picker; + use crate::{ + test_support::{screen, test_app}, + widgets::overlay::{OnAccept, Overlay, OverlayOutcome, Value}, + }; + + fn press(key: KeyCode) -> KeyEvent { + KeyEvent::new(key, KeyModifiers::NONE) + } + + fn picker() -> Picker { + Picker::new( + "Choose a variant of \"ffmpeg\"", + vec![ + Line::raw("ffmpeg 7.1 bincache static"), + Line::raw("ffmpeg 7.0.2 pkgcache appimage"), + Line::raw("jellyfin/ffmpeg 7.0.2 pkgcache appimage"), + ], + OnAccept::Test, + ) + } + + fn stay(outcome: OverlayOutcome) -> Picker { + match outcome { + OverlayOutcome::Stay(Overlay::Picker(picker)) => picker, + other => panic!("expected the picker to stay open, got {other:?}"), + } + } + + #[test] + fn moving_past_the_end_clamps_the_cursor() { + let mut picker = picker(); + for _ in 0..4 { + picker = stay(picker.handle(press(KeyCode::Char('j')))); + } + assert_eq!(picker.cursor.selected, 2); + } + + #[test] + fn moving_past_the_start_clamps_the_cursor() { + let picker = stay(picker().handle(press(KeyCode::Char('k')))); + assert_eq!(picker.cursor.selected, 0); + } + + #[test] + fn enter_accepts_the_cursor_index() { + let picker = stay(picker().handle(press(KeyCode::Char('j')))); + let picker = stay(picker.handle(press(KeyCode::Char('j')))); + assert!(matches!( + picker.handle(press(KeyCode::Enter)), + OverlayOutcome::Accept(OnAccept::Test, Some(Value::Index(2))) + )); + } + + #[test] + fn jump_keys_go_to_the_ends() { + let picker = stay(picker().handle(press(KeyCode::Char('G')))); + assert_eq!(picker.cursor.selected, 2); + let picker = stay(picker.handle(press(KeyCode::Char('g')))); + assert_eq!(picker.cursor.selected, 0); + } + + #[test] + fn esc_closes() { + assert!(matches!( + picker().handle(press(KeyCode::Esc)), + OverlayOutcome::Close + )); + } + + #[test] + fn the_picker_shows_its_title_rows_and_footer() { + let mut app = test_app(); + app.overlay = Some(Overlay::Picker(picker())); + let screen = screen(&mut app, 80, 24); + for text in ["Choose a variant", "ffmpeg 7.1", "enter pick · esc"] { + assert!(screen.contains(text), "screen is {screen:?}"); + } + } + + #[test] + fn the_window_scrolls_a_long_picker_with_the_cursor() { + let rows: Vec> = (0..30).map(|i| Line::raw(format!("row {i}"))).collect(); + let mut picker = Picker::new("Pick", rows, OnAccept::Test); + picker = stay(picker.handle(press(KeyCode::Char('G')))); + let mut app = test_app(); + app.overlay = Some(Overlay::Picker(picker)); + let screen = screen(&mut app, 80, 24); + assert!(screen.contains("row 29"), "screen is {screen:?}"); + assert!(!screen.contains("row 0"), "screen is {screen:?}"); + } +} diff --git a/crates/soar-tui/src/widgets/scroll.rs b/crates/soar-tui/src/widgets/scroll.rs new file mode 100644 index 00000000..57563cf2 --- /dev/null +++ b/crates/soar-tui/src/widgets/scroll.rs @@ -0,0 +1,176 @@ +//! Cursor and scrolling math for lists longer than the screen. + +use std::ops::Range; + +/// How many rows stay visible above and below the cursor when the list is +/// long enough. +const CONTEXT: usize = 2; + +/// The cursor and scroll offset of a list longer than the screen. +/// +/// Views build their rows only for the window [`ListCursor::window`] +/// returns, so a catalog with many packages costs the same to draw as one +/// that fills the screen. +#[derive(Debug, Default, Clone, Copy)] +pub(crate) struct ListCursor { + /// The row the cursor sits on. + pub(crate) selected: usize, + /// The first row on screen. + pub(crate) offset: usize, +} + +impl ListCursor { + /// Moves the cursor `n` rows down, stopping at the last row. + pub(crate) fn down(&mut self, n: usize, len: usize) { + self.selected = (self.selected + n).min(len.saturating_sub(1)); + } + + /// Moves the cursor `n` rows up, stopping at the first row. + pub(crate) fn up(&mut self, n: usize) { + self.selected = self.selected.saturating_sub(n); + } + + /// Moves the cursor to the first row. + pub(crate) fn top(&mut self) { + self.selected = 0; + } + + /// Moves the cursor to the last row. + pub(crate) fn bottom(&mut self, len: usize) { + self.selected = len.saturating_sub(1); + } + + /// Keeps the cursor inside a list of `len` rows, for when the list + /// shrank under it. + pub(crate) fn clamp(&mut self, len: usize) { + self.selected = self.selected.min(len.saturating_sub(1)); + } + + /// Adjusts `offset` so `selected` stays visible in `height` rows, + /// keeping two rows of context above and below it when the list is long + /// enough, and returns the range of rows to draw. + pub(crate) fn window(&mut self, len: usize, height: usize) -> Range { + if len == 0 || height == 0 { + self.offset = 0; + return 0..0; + } + let height = height.min(len); + let context = CONTEXT.min((height - 1) / 2); + let last_offset = len - height; + self.offset = self.offset.min(last_offset); + if self.selected + context >= self.offset + height { + self.offset = (self.selected + context + 1) + .saturating_sub(height) + .min(last_offset); + } + if self.selected < self.offset + context { + self.offset = self.selected.saturating_sub(context); + } + self.offset..self.offset + height + } +} + +#[cfg(test)] +mod tests { + use super::ListCursor; + + #[test] + fn moving_down_past_the_end_clamps_to_the_last_row() { + let mut cursor = ListCursor::default(); + cursor.down(10, 3); + assert_eq!(cursor.selected, 2); + cursor.down(5, 0); + assert_eq!(cursor.selected, 0); + } + + #[test] + fn moving_up_past_the_start_clamps_to_the_first_row() { + let mut cursor = ListCursor::default(); + cursor.down(2, 3); + cursor.up(5); + assert_eq!(cursor.selected, 0); + } + + #[test] + fn the_jump_keys_go_to_the_ends() { + let mut cursor = ListCursor::default(); + cursor.bottom(4); + assert_eq!(cursor.selected, 3); + cursor.bottom(0); + assert_eq!(cursor.selected, 0); + cursor.top(); + assert_eq!(cursor.selected, 0); + } + + #[test] + fn clamping_keeps_the_cursor_inside_a_shrunk_list() { + let mut cursor = ListCursor::default(); + cursor.down(5, 100); + cursor.clamp(3); + assert_eq!(cursor.selected, 2); + cursor.clamp(0); + assert_eq!(cursor.selected, 0); + } + + #[test] + fn the_window_keeps_the_cursor_visible() { + let mut cursor = ListCursor::default(); + cursor.down(50, 100); + let range = cursor.window(100, 10); + assert!(range.contains(&50), "window is {range:?}"); + } + + #[test] + fn the_window_keeps_two_rows_of_context_around_the_cursor() { + let mut cursor = ListCursor::default(); + cursor.down(50, 100); + assert_eq!(cursor.window(100, 10), 43..53); + } + + #[test] + fn the_window_stays_put_while_the_cursor_has_context() { + let mut cursor = ListCursor::default(); + cursor.down(50, 100); + let first = cursor.window(100, 10); + let second = cursor.window(100, 10); + assert_eq!(first, second); + assert_eq!(cursor.selected, 50); + } + + #[test] + fn the_window_sticks_to_the_top_while_the_cursor_is_near_it() { + let mut cursor = ListCursor::default(); + cursor.down(3, 100); + assert_eq!(cursor.window(100, 10), 0..10); + } + + #[test] + fn the_window_reaches_the_end_with_the_cursor_on_the_last_row() { + let mut cursor = ListCursor::default(); + cursor.bottom(100); + assert_eq!(cursor.window(100, 10), 90..100); + } + + #[test] + fn a_short_list_fills_the_whole_window() { + let mut cursor = ListCursor::default(); + cursor.down(2, 3); + assert_eq!(cursor.window(3, 10), 0..3); + } + + #[test] + fn an_empty_list_yields_an_empty_window_without_panicking() { + let mut cursor = ListCursor::default(); + cursor.bottom(0); + assert_eq!(cursor.window(0, 10), 0..0); + assert_eq!(cursor.window(0, 0), 0..0); + assert_eq!(cursor.offset, 0); + } + + #[test] + fn a_zero_height_window_yields_an_empty_window() { + let mut cursor = ListCursor::default(); + cursor.down(4, 100); + assert_eq!(cursor.window(100, 0), 0..0); + } +} diff --git a/crates/soar-tui/src/widgets/states.rs b/crates/soar-tui/src/widgets/states.rs new file mode 100644 index 00000000..565ec4ce --- /dev/null +++ b/crates/soar-tui/src/widgets/states.rs @@ -0,0 +1,98 @@ +//! The placeholders a view shows while its content loads, when it has +//! nothing to show, or when loading failed. +//! +//! The views draw these once they hold their own state. + +#![allow(dead_code)] + +use ratatui::{ + Frame, + layout::{Alignment, Rect}, + style::Style, + text::Line, + widgets::{Paragraph, Wrap}, +}; + +use crate::{format, theme::Theme}; + +/// Draws `{spinner} {text}` while the view's data loads. +pub(crate) fn loading(f: &mut Frame, area: Rect, theme: &Theme, frame: u64, text: &str) { + let line = one_line( + theme, + &format!("{} {text}", theme.spinner(frame)), + theme.muted(), + area.width, + ); + centered(f, area, vec![line], false); +} + +/// Draws the text in muted when the view has nothing to show. +pub(crate) fn empty(f: &mut Frame, area: Rect, theme: &Theme, text: &str) { + let line = one_line(theme, text, theme.muted(), area.width); + centered(f, area, vec![line], false); +} + +/// Draws the failure message in the danger color and the retry hint in +/// muted under it, wrapping a long message across the area. +pub(crate) fn error(f: &mut Frame, area: Rect, theme: &Theme, text: &str) { + let lines = vec![ + Line::styled(format!("{} {text}", theme.sym().error), theme.danger()), + Line::styled("ctrl-r to retry".to_string(), theme.muted()), + ]; + centered(f, area, lines, true); +} + +/// Draws `{installed} {text}` in the success color when an action finished. +pub(crate) fn success(f: &mut Frame, area: Rect, theme: &Theme, text: &str) { + let line = one_line( + theme, + &format!("{} {text}", theme.sym().installed), + theme.success(), + area.width, + ); + centered(f, area, vec![line], false); +} + +/// One line cut to `width` columns, so long text never overflows the area. +fn one_line(theme: &Theme, text: &str, style: Style, width: u16) -> Line<'static> { + Line::styled( + format::truncate(text, usize::from(width), theme.sym().ellipsis), + style, + ) +} + +/// Draws the lines vertically and horizontally centered in the area, +/// wrapping them across the width when asked. Content taller than the area +/// starts at its top and clips at the bottom. +fn centered(f: &mut Frame, area: Rect, lines: Vec>, wrap: bool) { + let rows = visible_rows(area, &lines, wrap).min(usize::from(area.height)); + let top = ((usize::from(area.height) - rows) / 2) as u16; + let rect = Rect { + y: area.y + top, + height: area.height - top, + ..area + }; + let mut paragraph = Paragraph::new(lines).alignment(Alignment::Center); + if wrap { + paragraph = paragraph.wrap(Wrap { + trim: true, + }); + } + f.render_widget(paragraph, rect); +} + +/// The rows the lines occupy, spreading each line across the area width +/// when it wraps. +fn visible_rows(area: Rect, lines: &[Line<'_>], wrap: bool) -> usize { + let width = usize::from(area.width).max(1); + lines + .iter() + .map(|line| { + if wrap { + line.width().div_ceil(width).max(1) + } else { + 1 + } + }) + .sum() +} diff --git a/crates/soar-tui/src/widgets/status_bar.rs b/crates/soar-tui/src/widgets/status_bar.rs new file mode 100644 index 00000000..7c083c81 --- /dev/null +++ b/crates/soar-tui/src/widgets/status_bar.rs @@ -0,0 +1,137 @@ +//! The status bar: key hints on the left, the view's message on the right. + +use ratatui::{ + Frame, + layout::Rect, + text::{Line, Span}, +}; + +use crate::{action::Action, app::App, format, keymap}; + +/// Draws the hints for the keys that work in the active view, then the +/// message the view has set, right-aligned in what the hints left. +pub(crate) fn render(f: &mut Frame, area: Rect, app: &App) { + let row = Rect { + height: 1, + ..area + }; + let message = app.status_right(); + // The hints hold back room for the message, though at most a third + // of the bar, so a long message cannot hide every hint. + let reserve = if message.is_empty() { + 0 + } else { + (Span::raw(&message).width() + 1).min(usize::from(row.width) / 3) + }; + let hints = hint_spans(app, usize::from(row.width), reserve); + let used = Line::from(hints.clone()).width(); + f.render_widget(Line::from(hints), row); + if !message.is_empty() { + // The message takes what the hints left, so the two sides never + // overwrite each other. + let room = usize::from(row.width).saturating_sub(used + 1); + let message = format::truncate(&message, room, app.theme.sym().ellipsis); + if !message.is_empty() { + f.render_widget( + Line::from(Span::styled(message, app.theme.muted())).right_aligned(), + row, + ); + } + } +} + +/// The left side of the bar: one hint per key binding the view shows on the +/// bar, followed by help and quit. Hints stop once the next one would not +/// fit, `reserve` columns included. +fn hint_spans(app: &App, width: usize, reserve: usize) -> Vec> { + let theme = &app.theme; + let bindings = keymap::bindings(app.view) + .iter() + .filter(|binding| binding.bar && app.hint_visible(&binding.action)) + .chain( + keymap::GLOBAL + .iter() + .filter(|binding| matches!(binding.action, Action::Help | Action::Quit)), + ); + let mut spans = Vec::new(); + let mut used = 1 + reserve; + let mut first = true; + for binding in bindings { + let key = keymap::key_label(binding.keys[0]); + let suffix = app.hint_suffix(&binding.action); + let suffix_width = suffix.as_deref().map_or(0, |text| Span::raw(text).width()); + let separator = if first { 0 } else { 2 }; + let cost = separator + + Span::raw(key.as_str()).width() + + 1 + + Span::raw(binding.label).width() + + suffix_width; + if used + cost > width && !first { + break; + } + spans.push(Span::raw(if first { " " } else { " " })); + spans.push(Span::styled(key, theme.key())); + spans.push(Span::raw(" ")); + spans.push(Span::styled(binding.label, theme.muted())); + if let Some(suffix) = suffix { + spans.push(Span::styled(suffix, theme.muted())); + } + used += cost; + first = false; + } + spans +} + +#[cfg(test)] +mod tests { + use crate::test_support::{render, test_app}; + + #[test] + fn the_browse_bar_shows_filter_and_help() { + let mut app = test_app(); + let lines = render(&mut app, 100, 16); + let bar = lines.last().unwrap(); + assert!(bar.contains("/ filter"), "bar is {bar:?}"); + assert!(bar.contains("? help"), "bar is {bar:?}"); + } + + #[test] + fn hints_stop_when_the_row_is_full() { + let mut app = test_app(); + let lines = render(&mut app, 60, 16); + let bar = lines.last().unwrap(); + assert!(bar.contains("/ filter"), "bar is {bar:?}"); + assert!(bar.contains("+ add"), "bar is {bar:?}"); + assert!(!bar.contains("R repo"), "bar is {bar:?}"); + } + + #[test] + fn the_message_and_the_hints_share_the_row() { + use crate::{ + msg::{Loaded, Msg}, + test_support::{catalog_row, key}, + }; + let mut app = test_app(); + let now = std::time::Instant::now(); + let rows = vec![ + catalog_row("bat", "0.24.0", "bincache"), + catalog_row("fd", "10.2.0", "pkgforge"), + ]; + app.update( + Msg::Loaded(Loaded::Catalog { + check: 0, + result: Ok(rows), + }), + now, + ); + app.update(key(' '), now); + let lines = render(&mut app, 73, 20); + let bar = lines.last().unwrap(); + assert!(bar.contains("+ add"), "bar is {bar:?}"); + assert!(bar.contains("1 marked"), "bar is {bar:?}"); + assert!( + !bar.contains("R repo"), + "a hint the message would run over is dropped, bar is {bar:?}" + ); + } +} diff --git a/crates/soar-tui/src/widgets/text_input.rs b/crates/soar-tui/src/widgets/text_input.rs new file mode 100644 index 00000000..586ac8e8 --- /dev/null +++ b/crates/soar-tui/src/widgets/text_input.rs @@ -0,0 +1,589 @@ +//! The single-line text input and the prompt dialog built on it. + +#![allow(dead_code)] + +use ratatui::{ + Frame, + crossterm::event::{KeyCode, KeyEvent, KeyModifiers}, + layout::Rect, + style::{Modifier, Style}, + text::{Line, Span}, + widgets::{Clear, Paragraph}, +}; + +use crate::{ + app::App, + theme::Theme, + widgets::overlay::{OnAccept, Overlay, OverlayOutcome, Value, centered, frame}, +}; + +/// One editable line of text with the cursor as a character index. +/// +/// The value never appears in debug output, so an input holding a +/// password cannot leak it through a log or a panic message. +#[derive(Default)] +pub(crate) struct TextInput { + value: String, + cursor: usize, + /// Whether every character draws as the theme's mask symbol. + masked: bool, +} + +impl std::fmt::Debug for TextInput { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("TextInput") + .field("value", &"[hidden]") + .field("cursor", &self.cursor) + .field("masked", &self.masked) + .finish() + } +} + +impl Drop for TextInput { + /// Zeroes the value before it returns to the allocator, so a typed + /// password leaves memory with the secret it became. Bytes past the + /// length and copies made by earlier reallocations can still outlive + /// this, so the zeroing is best effort. + fn drop(&mut self) { + scrub(std::mem::take(&mut self.value)); + } +} + +impl TextInput { + /// Feeds one pressed key into the value and reports whether the input + /// used it. + pub(crate) fn handle(&mut self, key: KeyEvent) -> bool { + match (key.code, key.modifiers) { + (KeyCode::Char(c), mods) + if !mods.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) => + { + self.insert(c); + } + (KeyCode::Backspace, _) => self.backspace(), + (KeyCode::Delete, _) => self.delete(), + (KeyCode::Left, _) => self.cursor = self.cursor.saturating_sub(1), + (KeyCode::Right, _) => self.cursor = (self.cursor + 1).min(self.char_len()), + (KeyCode::Home, _) | (KeyCode::Char('a'), KeyModifiers::CONTROL) => self.cursor = 0, + (KeyCode::End, _) | (KeyCode::Char('e'), KeyModifiers::CONTROL) => { + self.cursor = self.char_len(); + } + (KeyCode::Char('u'), KeyModifiers::CONTROL) => self.clear_to_start(), + (KeyCode::Char('w'), KeyModifiers::CONTROL) => self.delete_previous_word(), + _ => return false, + } + true + } + + /// The text collected so far. + pub(crate) fn value(&self) -> &str { + &self.value + } + + /// Replaces the text and puts the cursor after it. + pub(crate) fn set(&mut self, value: String) { + self.cursor = value.chars().count(); + scrub(std::mem::replace(&mut self.value, value)); + } + + /// Removes and returns the whole text, leaving the input empty. + pub(crate) fn take(&mut self) -> String { + self.cursor = 0; + std::mem::take(&mut self.value) + } + + /// Empties the text. + pub(crate) fn clear(&mut self) { + self.value.clear(); + self.cursor = 0; + } + + /// Whether nothing is entered yet. + pub(crate) fn is_empty(&self) -> bool { + self.value.is_empty() + } + + /// Draws every character as the mask symbol instead of the value, + /// for passwords. + pub(crate) fn masked(mut self) -> TextInput { + self.masked = true; + self + } + + /// The value as one line cut to `room` columns, with a reversed cell + /// marking the cursor while focused. When the value overflows, the + /// window keeps its tail and the cursor in view. + pub(crate) fn line(&self, focused: bool, room: usize, theme: &Theme) -> Line<'static> { + let chars: Vec = if self.masked { + self.value + .chars() + .flat_map(|_| theme.sym().mask.chars()) + .collect() + } else { + self.value.chars().collect() + }; + let (start, end) = visible_window(&chars, self.cursor.min(chars.len()), room); + let cursor = self.cursor.min(chars.len()) - start; + let visible = &chars[start..end]; + let mut spans = Vec::new(); + if cursor > 0 { + spans.push(Span::raw(visible[..cursor].iter().collect::())); + } + if focused { + match visible.get(cursor) { + Some(&c) => { + let cell = Style::new().add_modifier(Modifier::REVERSED); + spans.push(Span::styled(c.to_string(), cell)); + if cursor + 1 < visible.len() { + spans.push(Span::raw(visible[cursor + 1..].iter().collect::())); + } + } + None => { + let cell = Style::new().add_modifier(Modifier::REVERSED); + spans.push(Span::styled(" ", cell)); + } + } + } else if cursor < visible.len() { + spans.push(Span::raw(visible[cursor..].iter().collect::())); + } + Line::from(spans).style(theme.text()) + } + + /// The number of characters in the value. + fn char_len(&self) -> usize { + self.value.chars().count() + } + + /// Puts one character at the cursor. + fn insert(&mut self, c: char) { + let byte = byte_index(&self.value, self.cursor); + self.value.insert(byte, c); + self.cursor += 1; + } + + /// Removes the character before the cursor. + fn backspace(&mut self) { + if self.cursor == 0 { + return; + } + let start = byte_index(&self.value, self.cursor - 1); + let end = byte_index(&self.value, self.cursor); + self.value.replace_range(start..end, ""); + self.cursor -= 1; + } + + /// Removes the character at the cursor. + fn delete(&mut self) { + if self.cursor >= self.char_len() { + return; + } + let start = byte_index(&self.value, self.cursor); + let end = byte_index(&self.value, self.cursor + 1); + self.value.replace_range(start..end, ""); + } + + /// Removes everything before the cursor. + fn clear_to_start(&mut self) { + let byte = byte_index(&self.value, self.cursor); + self.value.replace_range(..byte, ""); + self.cursor = 0; + } + + /// Removes the word before the cursor, stopping at the space that + /// separates it. + fn delete_previous_word(&mut self) { + let chars: Vec = self.value.chars().collect(); + let mut end = self.cursor.min(chars.len()); + while end > 0 && chars[end - 1].is_whitespace() { + end -= 1; + } + let mut start = end; + while start > 0 && !chars[start - 1].is_whitespace() { + start -= 1; + } + if start == end { + return; + } + let kept: String = chars[..start].iter().chain(chars[end..].iter()).collect(); + scrub(std::mem::replace(&mut self.value, kept)); + self.cursor = start; + } +} + +/// Zeroes a discarded value's bytes and black-boxes them, so password +/// bytes do not return to the allocator readable. +fn scrub(value: String) { + let mut bytes = value.into_bytes(); + bytes.fill(0); + std::hint::black_box(&bytes); +} + +/// The byte offset of the character `chars` characters into `text`. +fn byte_index(text: &str, chars: usize) -> usize { + text.char_indices() + .nth(chars) + .map_or(text.len(), |(index, _)| index) +} + +/// The range of characters that fits `room` display columns, chosen so +/// the cursor stays in view: the tail while the cursor sits at the end, +/// and a stretch from the cursor once it moves back into the cut part. +fn visible_window(chars: &[char], cursor: usize, room: usize) -> (usize, usize) { + let width = |index: usize| Span::raw(chars[index].to_string()).width(); + let total: usize = (0..chars.len()).map(width).sum(); + if total <= room { + return (0, chars.len()); + } + let mut end = chars.len(); + let mut used = 0; + while end > 0 { + let columns = width(end - 1); + if used + columns > room { + break; + } + used += columns; + end -= 1; + } + if cursor < end { + let mut window_end = cursor; + let mut used = 0; + while window_end < chars.len() { + let columns = width(window_end); + if used + columns > room { + break; + } + used += columns; + window_end += 1; + } + return (cursor, window_end); + } + (end, chars.len()) +} + +/// A dialog asking for one line of text, such as a name or a path. +#[derive(Debug)] +pub(crate) struct Prompt { + title: String, + input: TextInput, + on_accept: OnAccept, + /// Whether enter accepts an empty input instead of keeping the + /// prompt open. + allow_empty: bool, +} + +impl Prompt { + /// Builds a prompt starting from an empty input. + pub(crate) fn new(title: impl Into, on_accept: OnAccept) -> Prompt { + Prompt { + title: title.into(), + input: TextInput::default(), + on_accept, + allow_empty: false, + } + } + + /// Lets enter accept an empty input, whose meaning the caller + /// defines. The footer tells the user how the text is interpreted. + pub(crate) fn allow_empty(mut self) -> Prompt { + self.allow_empty = true; + self + } + + /// Acts on one pressed key. Enter accepts the trimmed text and stays + /// open while it is empty, unless empty input is allowed, esc closes, + /// and everything else edits the text. + pub(crate) fn handle(mut self, key: KeyEvent) -> OverlayOutcome { + match key.code { + KeyCode::Enter => { + let text = self.input.value().trim(); + if text.is_empty() && !self.allow_empty { + OverlayOutcome::Stay(Overlay::Prompt(self)) + } else { + OverlayOutcome::Accept(self.on_accept, Some(Value::Text(text.to_owned()))) + } + } + KeyCode::Esc => OverlayOutcome::Close, + _ => { + self.input.handle(key); + OverlayOutcome::Stay(Overlay::Prompt(self)) + } + } + } + + /// Draws the prompt centered in the body area, and returns the rect + /// it drew into. + pub(crate) fn render(&self, f: &mut Frame, area: Rect, app: &App) -> Rect { + let theme = &app.theme; + let width = area.width.saturating_sub(4).min(64); + let rect = centered(area, width, 3); + f.render_widget(Clear, rect); + + let mut spans = vec![Span::styled("> ", theme.muted())]; + // The frame's border and padding take four columns and the + // marker two, so the value gets what is left, keeping its tail, + // where the cursor is, in view. + let room = usize::from(width).saturating_sub(6); + spans.extend(self.input.line(true, room, theme).spans); + let footer = if self.allow_empty { + format!( + " enter ok {} esc {} args are split on spaces ", + theme.sym().dot, + theme.sym().dot + ) + } else { + format!(" enter ok {} esc ", theme.sym().dot) + }; + let block = frame( + Line::styled(format!(" {} ", self.title), theme.title()), + Some(Line::styled(footer, theme.muted())), + false, + theme, + ); + f.render_widget(Paragraph::new(vec![Line::from(spans)]).block(block), rect); + rect + } +} + +#[cfg(test)] +mod tests { + use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; + + use super::{Prompt, TextInput}; + use crate::{ + test_support::{screen, test_app}, + widgets::overlay::{OnAccept, Overlay, OverlayOutcome, Value}, + }; + + fn press(c: char) -> KeyEvent { + KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE) + } + + fn press_key(key: KeyCode) -> KeyEvent { + KeyEvent::new(key, KeyModifiers::NONE) + } + + fn ctrl(c: char) -> KeyEvent { + KeyEvent::new(KeyCode::Char(c), KeyModifiers::CONTROL) + } + + fn typed(input: &TextInput) -> String { + input.value().to_string() + } + + #[test] + fn typing_then_moving_back_inserts_in_place() { + let mut input = TextInput::default(); + for c in ['a', 'b', 'c'] { + assert!(input.handle(press(c))); + } + assert!(input.handle(press_key(KeyCode::Left))); + assert!(input.handle(press('x'))); + assert_eq!(typed(&input), "abxc"); + } + + #[test] + fn ctrl_w_removes_the_previous_word() { + let mut input = TextInput::default(); + input.set("foo bar".to_string()); + assert!(input.handle(ctrl('w'))); + assert_eq!(typed(&input), "foo "); + } + + #[test] + fn backspace_removes_a_multibyte_character() { + let mut input = TextInput::default(); + assert!(input.handle(press('é'))); + assert_eq!(typed(&input), "é"); + assert!(input.handle(press_key(KeyCode::Backspace))); + assert_eq!(typed(&input), ""); + assert!(input.is_empty()); + } + + #[test] + fn ctrl_u_clears_to_the_start() { + let mut input = TextInput::default(); + input.set("hello world".to_string()); + assert!(input.handle(ctrl('u'))); + assert_eq!(typed(&input), ""); + } + + #[test] + fn home_and_end_reach_the_ends() { + let mut input = TextInput::default(); + input.set("hello".to_string()); + assert!(input.handle(press_key(KeyCode::Home))); + assert!(input.handle(press('x'))); + assert_eq!(typed(&input), "xhello"); + assert!(input.handle(ctrl('e'))); + assert!(input.handle(press('y'))); + assert_eq!(typed(&input), "xhelloy"); + } + + #[test] + fn keys_outside_the_input_are_not_consumed() { + let mut input = TextInput::default(); + assert!(!input.handle(press_key(KeyCode::PageDown))); + } + + #[test] + fn a_masked_input_draws_one_mask_per_character() { + let theme = crate::theme::Theme::new(true, true); + let mut input = TextInput::default().masked(); + for c in ['a', 'b', 'c'] { + input.handle(press(c)); + } + let line = input.line(true, 10, &theme); + let text: String = line + .spans + .iter() + .map(|span| span.content.as_ref()) + .collect(); + assert_eq!(text, "••• "); + assert!(!text.contains("abc")); + let line = input.line(false, 10, &theme); + let text: String = line + .spans + .iter() + .map(|span| span.content.as_ref()) + .collect(); + assert_eq!(text, "•••"); + } + + #[test] + fn an_unmasked_input_still_shows_its_value() { + let mut input = TextInput::default(); + input.set("abc".to_string()); + let theme = crate::theme::Theme::new(true, true); + let line = input.line(false, 10, &theme); + let text: String = line + .spans + .iter() + .map(|span| span.content.as_ref()) + .collect(); + assert_eq!(text, "abc"); + } + + #[test] + fn a_value_wider_than_the_room_shows_its_tail() { + let mut input = TextInput::default(); + input.set("0123456789".to_string()); + let theme = crate::theme::Theme::new(true, true); + let line = input.line(false, 5, &theme); + let text: String = line + .spans + .iter() + .map(|span| span.content.as_ref()) + .collect(); + assert_eq!(text, "56789"); + } + + #[test] + fn a_cursor_moved_back_keeps_its_own_stretch_in_view() { + let mut input = TextInput::default(); + input.set("abcdefghij".to_string()); + input.handle(press_key(KeyCode::Home)); + let theme = crate::theme::Theme::new(true, true); + let line = input.line(false, 4, &theme); + let text: String = line + .spans + .iter() + .map(|span| span.content.as_ref()) + .collect(); + assert_eq!(text, "abcd"); + } + + #[test] + fn debugging_an_input_never_carries_the_value() { + let mut input = TextInput::default().masked(); + input.set("hunter2".to_string()); + let printed = format!("{input:?}"); + assert!(!printed.contains("hunter2"), "debug output is {printed:?}"); + } + + #[test] + fn a_masked_input_drops_with_multibyte_text() { + // Observing freed memory cannot be done safely, so this only + // guards Drop against panics with multibyte content. + let mut input = TextInput::default().masked(); + input.set("välu€".to_string()); + drop(input); + } + + #[test] + fn take_empties_the_input_and_returns_the_text() { + let mut input = TextInput::default(); + input.set("abc".to_string()); + assert_eq!(input.take(), "abc"); + assert!(input.is_empty()); + } + + #[test] + fn enter_accepts_the_trimmed_text() { + let mut prompt = Prompt::new("Install by name, URL, or path", OnAccept::Test); + prompt.input.set(" fd ".to_string()); + assert!(matches!( + prompt.handle(press_key(KeyCode::Enter)), + OverlayOutcome::Accept(OnAccept::Test, Some(Value::Text(text))) if text == "fd" + )); + } + + #[test] + fn enter_on_empty_text_stays_open() { + let prompt = Prompt::new("Install by name, URL, or path", OnAccept::Test); + assert!(matches!( + prompt.handle(press_key(KeyCode::Enter)), + OverlayOutcome::Stay(Overlay::Prompt(_)) + )); + } + + #[test] + fn esc_closes_the_prompt() { + let prompt = Prompt::new("Install by name, URL, or path", OnAccept::Test); + assert!(matches!( + prompt.handle(press_key(KeyCode::Esc)), + OverlayOutcome::Close + )); + } + + #[test] + fn enter_accepts_empty_input_when_allowed() { + let prompt = Prompt::new("Run jq with arguments", OnAccept::Test).allow_empty(); + assert!(matches!( + prompt.handle(press_key(KeyCode::Enter)), + OverlayOutcome::Accept(OnAccept::Test, Some(Value::Text(text))) if text.is_empty() + )); + } + + #[test] + fn enter_accepts_whitespace_only_text_as_empty_when_allowed() { + let mut prompt = Prompt::new("Run jq with arguments", OnAccept::Test).allow_empty(); + prompt.input.set(" ".to_string()); + assert!(matches!( + prompt.handle(press_key(KeyCode::Enter)), + OverlayOutcome::Accept(OnAccept::Test, Some(Value::Text(text))) if text.is_empty() + )); + } + + #[test] + fn the_allowed_empty_prompt_hints_the_split_in_its_footer() { + let mut app = test_app(); + let prompt = Prompt::new("Run jq with arguments", OnAccept::Test).allow_empty(); + app.overlay = Some(Overlay::Prompt(prompt)); + let screen = screen(&mut app, 80, 24); + assert!( + screen.contains("args are split on spaces"), + "screen is {screen:?}" + ); + } + + #[test] + fn the_prompt_shows_its_title_input_line_and_footer() { + let mut app = test_app(); + let mut prompt = Prompt::new("Install by name, URL, or path", OnAccept::Test); + prompt.input.set("https://github.com/user/app".to_string()); + app.overlay = Some(Overlay::Prompt(prompt)); + let screen = screen(&mut app, 80, 24); + for text in ["Install by name", "> https://github.com", "enter ok · esc"] { + assert!(screen.contains(text), "screen is {screen:?}"); + } + } +} diff --git a/crates/soar-tui/src/widgets/toast.rs b/crates/soar-tui/src/widgets/toast.rs new file mode 100644 index 00000000..47e6760f --- /dev/null +++ b/crates/soar-tui/src/widgets/toast.rs @@ -0,0 +1,229 @@ +//! The brief notifications stacked in the top-right corner of the body, +//! reporting what the interface just did. + +use std::{ + collections::VecDeque, + time::{Duration, Instant}, +}; + +use ratatui::{ + Frame, + layout::Rect, + style::Style, + text::{Line, Span}, + widgets::{Block, BorderType, Paragraph}, +}; + +use crate::{app::App, format, theme::Theme}; + +/// How many toasts may show at once. +const MAX_TOASTS: usize = 3; + +/// The widest a toast box gets, whatever its text says. +const MAX_WIDTH: usize = 48; + +/// The rows one toast box occupies: two borders around one message. +const HEIGHT: u16 = 3; + +/// The kinds of toast, deciding the icon, the border color, and how long +/// the toast stays. The views raise toasts as their actions run, so until +/// then only tests construct the kinds. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[allow(dead_code)] +pub(crate) enum ToastKind { + /// Something finished well. + Success, + /// Neutral information. + Info, + /// A note worth reading. + Warning, + /// Something failed. + Error, +} + +impl ToastKind { + /// The glyph marking this kind of toast. + fn symbol(self, theme: &Theme) -> &'static str { + let symbols = theme.sym(); + match self { + ToastKind::Success => symbols.installed, + ToastKind::Info => symbols.dot, + ToastKind::Warning => symbols.warning, + ToastKind::Error => symbols.error, + } + } + + /// The style of the icon and border for this kind. + fn style(self, theme: &Theme) -> Style { + match self { + ToastKind::Success => theme.success(), + ToastKind::Info => theme.info(), + ToastKind::Warning => theme.warning(), + ToastKind::Error => theme.danger(), + } + } + + /// How long the toast stays on screen. + fn lifetime(self) -> Duration { + match self { + ToastKind::Error => Duration::from_secs(8), + ToastKind::Success | ToastKind::Info | ToastKind::Warning => Duration::from_secs(4), + } + } +} + +/// One brief notification. +#[derive(Debug)] +pub(crate) struct Toast { + kind: ToastKind, + text: String, + /// The time the toast stops showing. + until: Instant, +} + +/// The toasts on screen, newest first, at most three. +#[derive(Debug, Default)] +pub(crate) struct Toasts(VecDeque); + +impl Toasts { + /// Shows a toast on top, dropping the oldest one beyond three. Toasts + /// stay four seconds, or eight when they report a failure. + pub(crate) fn push(&mut self, kind: ToastKind, text: impl Into, now: Instant) { + if self.0.len() >= MAX_TOASTS { + self.0.pop_back(); + } + self.0.push_front(Toast { + kind, + text: text.into(), + until: now + kind.lifetime(), + }); + } + + /// Removes the toasts past their lifetime and reports whether any went. + pub(crate) fn expire(&mut self, now: Instant) -> bool { + let before = self.0.len(); + self.0.retain(|toast| toast.until > now); + self.0.len() != before + } + + /// The toasts from newest to oldest. + pub(crate) fn iter(&self) -> std::collections::vec_deque::Iter<'_, Toast> { + self.0.iter() + } +} + +/// Draws the toasts stacked from the top-right corner of the body area, +/// newest on top, each a rounded box sized to its message and colored by +/// its kind. Toasts never take input. +pub(crate) fn render(f: &mut Frame, body: Rect, app: &App) { + let theme = &app.theme; + let mut used: u16 = 0; + for toast in app.toasts.iter() { + if used + HEIGHT > body.height { + break; + } + let text_width = Span::raw(toast.text.as_str()).width(); + let width = (text_width + 4).min(MAX_WIDTH).min(usize::from(body.width)) as u16; + let rect = Rect { + x: body.x + body.width - width, + y: body.y + used, + width, + height: HEIGHT, + }; + used += HEIGHT; + + let symbol = toast.kind.symbol(theme); + let inner = usize::from(width).saturating_sub(2); + let budget = inner.saturating_sub(Span::raw(symbol).width() + 1); + let text = format::truncate(&toast.text, budget, theme.sym().ellipsis); + let line = Line::from(vec![ + Span::styled(symbol, toast.kind.style(theme)), + Span::raw(" "), + Span::raw(text), + ]); + let block = Block::bordered() + .border_type(BorderType::Rounded) + .border_style(toast.kind.style(theme)); + f.render_widget(Paragraph::new(line).block(block), rect); + } +} + +#[cfg(test)] +mod tests { + use std::time::{Duration, Instant}; + + use super::{ToastKind, Toasts}; + use crate::test_support::{render, test_app}; + + fn texts(toasts: &Toasts) -> Vec { + toasts.iter().map(|toast| toast.text.clone()).collect() + } + + #[test] + fn pushing_past_three_drops_the_oldest() { + let mut toasts = Toasts::default(); + let now = Instant::now(); + toasts.push(ToastKind::Info, "first", now); + toasts.push(ToastKind::Info, "second", now); + toasts.push(ToastKind::Info, "third", now); + toasts.push(ToastKind::Info, "fourth", now); + assert_eq!(texts(&toasts), ["fourth", "third", "second"]); + } + + #[test] + fn an_error_outlives_other_toasts() { + let mut toasts = Toasts::default(); + let now = Instant::now(); + toasts.push(ToastKind::Warning, "a note", now); + toasts.push(ToastKind::Error, "the sync failed", now); + toasts.expire(now + Duration::from_secs(5)); + assert_eq!(texts(&toasts), ["the sync failed"]); + } + + #[test] + fn a_toast_leaves_after_its_lifetime() { + let mut toasts = Toasts::default(); + let now = Instant::now(); + toasts.push(ToastKind::Info, "installed fd", now); + assert!(!toasts.expire(now + Duration::from_secs(3))); + assert!(toasts.expire(now + Duration::from_secs(5))); + assert!(texts(&toasts).is_empty()); + } + + #[test] + fn the_newest_toast_draws_on_top_at_the_right_edge() { + let mut app = test_app(); + let now = Instant::now(); + app.toast(ToastKind::Info, "older toast", now); + app.toast(ToastKind::Success, "Installed fd 10.2.0", now); + let lines = render(&mut app, 80, 24); + assert!( + lines[2].contains("Installed fd 10.2.0"), + "top toast row is {:?}", + lines[2] + ); + assert!( + lines[5].contains("older toast"), + "second toast row is {:?}", + lines[5] + ); + assert!(lines[2].ends_with('│'), "top toast row is {:?}", lines[2]); + } + + #[test] + fn a_long_message_fits_the_widest_toast() { + let mut app = test_app(); + app.toast( + ToastKind::Error, + "very long failure ".repeat(6), + Instant::now(), + ); + let lines = render(&mut app, 80, 24); + let row = &lines[2]; + assert!(row.ends_with("…│"), "top toast row is {row:?}"); + let start = row.chars().count() - 48; + let box_row: String = row.chars().skip(start).collect(); + assert_eq!(box_row.chars().count(), 48, "top toast row is {row:?}"); + assert!(box_row.starts_with('│'), "top toast row is {row:?}"); + } +} diff --git a/crates/soar-utils/src/cancel.rs b/crates/soar-utils/src/cancel.rs new file mode 100644 index 00000000..ed9e3b35 --- /dev/null +++ b/crates/soar-utils/src/cancel.rs @@ -0,0 +1,50 @@ +//! Cooperative cancellation. + +use std::sync::{ + Arc, + atomic::{AtomicBool, Ordering}, +}; + +/// A shared flag that asks running work to stop at its next safe point. +/// +/// Clones share the flag. Cancelling cannot be undone; start new work with +/// a new token. +#[derive(Debug, Clone, Default)] +pub struct CancelToken(Arc); + +impl CancelToken { + /// A token that is not cancelled. + pub fn new() -> Self { + Self::default() + } + + /// Asks every holder of this token to stop. + pub fn cancel(&self) { + self.0.store(true, Ordering::Relaxed); + } + + /// Whether [`cancel`](Self::cancel) has been called on any clone. + pub fn is_cancelled(&self) -> bool { + self.0.load(Ordering::Relaxed) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_clone_sees_the_cancel() { + let token = CancelToken::new(); + let shared = token.clone(); + assert!(!shared.is_cancelled()); + token.cancel(); + assert!(shared.is_cancelled()); + } + + #[test] + fn a_fresh_token_is_not_cancelled() { + assert!(!CancelToken::new().is_cancelled()); + assert!(!CancelToken::default().is_cancelled()); + } +} diff --git a/crates/soar-utils/src/lib.rs b/crates/soar-utils/src/lib.rs index 1b19d1f1..bb788db0 100644 --- a/crates/soar-utils/src/lib.rs +++ b/crates/soar-utils/src/lib.rs @@ -1,4 +1,5 @@ pub mod bytes; +pub mod cancel; pub mod elf; pub mod error; pub mod fs; diff --git a/deny.toml b/deny.toml index 3338e8ba..dbdef2ec 100644 --- a/deny.toml +++ b/deny.toml @@ -28,6 +28,14 @@ deny = [] [advisories] yanked = "deny" +ignore = [ + # chrono is unmaintained with no patched replacement; pre-existing + # workspace dependency. Remove when the workspace migrates off chrono. + "RUSTSEC-2026-0543", + # bundled-SQLite CVE; we link the system SQLite, and libsqlite3-sys is + # capped below 0.39 by diesel 2.3.x. Remove once diesel allows 0.39. + "RUSTSEC-2026-0459", +] [sources] unknown-registry = "deny" diff --git a/docs/.vitepress/config.mts b/docs/.vitepress/config.mts index eb05b5b3..6caa4f49 100644 --- a/docs/.vitepress/config.mts +++ b/docs/.vitepress/config.mts @@ -51,6 +51,7 @@ export default defineConfig({ { text: 'Configuration', link: '/configuration' }, { text: 'Profiles', link: '/profiles' }, { text: 'Package Management', link: '/package-management' }, + { text: 'Terminal Interface', link: '/tui' }, ], }, { text: 'Releases', link: '/releases' }, @@ -66,6 +67,7 @@ export default defineConfig({ { text: 'Configuration', link: '/configuration' }, { text: 'Profiles', link: '/profiles' }, { text: 'CLI Reference', link: '/cli-reference' }, + { text: 'Terminal Interface', link: '/tui' }, ], }, { diff --git a/docs/cli-reference.md b/docs/cli-reference.md index ae960227..3dc4df9a 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -164,6 +164,26 @@ System paths: - Root: `/opt/soar` - Binaries: `/opt/soar/bin` +## Terminal Interface + +### `soar tui` + +Open the full-screen terminal interface for browsing, installing, updating, and +maintaining packages. It takes no flags of its own and inherits the global +options, including `--system` / `-S`, `--profile` / `-p`, `--no-color`, and the +proxy and network options. + +```bash +soar tui +soar -p work tui +``` + +It needs an interactive terminal, so piping it is refused. `--json` is refused +for the same reason: the interface draws its own screen. Colored output follows +`--no-color` and the `NO_COLOR` environment variable. + +See [Terminal Interface](./tui.md) for the full guide. + ## Common Combinations ::: code-group @@ -257,3 +277,4 @@ sudo is involved at all. - [Profiles](./profiles.md) for managing multiple installation profiles - [Installation](./installation.md) for the installation guide - [Health & Diagnostics](./health.md) for health checks and debugging +- [Terminal Interface](./tui.md) for the full-screen interface guide diff --git a/docs/tui.md b/docs/tui.md new file mode 100644 index 00000000..bcc1f36d --- /dev/null +++ b/docs/tui.md @@ -0,0 +1,255 @@ +--- +title: Terminal Interface +description: Browse, install, update and maintain packages from soar's full-screen terminal interface. +--- + +# Terminal Interface + +Soar ships a full-screen terminal interface that covers the day-to-day work in +one place: browse and search the catalog, manage installed packages and +updates, apply declarative packages, manage repositories, and run +maintenance. Everything works from the keyboard, and the mouse works too: the +wheel scrolls lists, and clicks switch tabs and move the cursor. + +## Starting the Interface + +Run: + +```sh +soar tui +``` + +The command accepts soar's global options, so the interface runs with the same +configuration the CLI uses: + +```sh +# Manage the system installation +soar -S tui + +# Open the interface for a specific profile +soar -p work tui + +# Disable colored output +soar --no-color tui +``` + +The interface follows `--no-color` and the `NO_COLOR` environment variable, and +falls back to bold and reversed text when colors are off. + +Two restrictions apply: + +- `soar --json tui` is refused. The interface draws its own screen and cannot + emit JSON. +- The interface needs an interactive terminal. Piping it, as in + `soar tui | cat`, is refused with a message that says so. + +In system mode soar escalates once at startup, before the interface opens. +Profiles cannot be switched while it runs: restart with the profile you want. + +## The Views + +The tab bar in the header lists the views. Press the number of a view, press +`Tab` to cycle through them, or click a tab. Each view shows the keys that +work in it in the bar at the bottom of the screen, and `?` opens the full list. + +### Browse + +Browse shows every package in every enabled repository. Press `/` to type a +filter, which narrows the list as you type. Mark packages with `Space` and +install everything marked with `i`; with nothing marked, `i` installs the row +under the cursor. `I` opens a form with install options such as force +reinstall. `v` picks a specific version of the current package and installs +it, `x` runs a package without installing it, and `+` installs by name, URL, +or local path. `R` cycles the repository filter, and `Enter` toggles the +full-screen detail pane with the description, size, license, and available +versions. + +### Installed + +Installed lists what is installed in the current profile, with size, install +date, and state: healthy, broken, inactive because another variant is linked, +or pinned. Press `/` to filter, `Space` to mark, and `d` to remove the marked +packages, or the current one when nothing is marked. `s` switches a package to +another variant, and `u` checks updates for the marked packages or the current +row. `o` cycles the sort order between name, size, and date, and `Enter` +toggles the full-screen detail. + +### Updates + +Updates checks every installed package for a newer version when you enter the +view. Mark packages with `Space`, mark all of them with `a`, and apply the +updates you marked with `u`; with nothing marked, `u` applies everything +listed. `o` toggles whether the old versions are kept. Packages whose check +was skipped are counted and hidden until you press `S`. `Ctrl-r` runs a fresh +check. + +### Apply + +Apply shows what the declarative `packages.toml` would change before anything +happens: packages to install, update, and remove, packages already in sync, +and names it cannot find. Press `Enter` to apply after a confirmation that +names every change. `p` toggles prune, which removes installed packages the +file no longer lists, and the preview recomputes while it is on. `e` opens +`packages.toml` in your editor, and `n` creates the default file when none +exists. + +### Repos + +Repos lists the configured repositories and when each was last synced. Press +`s` to sync all repositories, `e` to enable or disable the current one, `a` to +add a repository, and `d` to remove it. `E` opens `config.toml` in your +editor. + +### Health + +Health reports the state of the installation: whether soar's binary directory +is in `PATH`, broken packages, and broken symlinks. Beside the report, a pane +lists the config, package, and cache paths soar uses. Press `c` to clean the +cache, `b` to remove broken symlinks, and `p` to remove broken packages. Each +asks for confirmation first, and `Ctrl-r` runs the checks again. + +### Jobs + +Jobs lists every job this session has run or queued, each with its outcome. +The log below the list collects soar's own messages and the output of hooks +and child processes, so nothing interrupts the interface while a job runs. +Press `Enter` to focus the selected job's summary, which lists failures with +their full errors, and `l` to focus the log. `x` aborts the selected job if it +is running, or drops it if it is still queued, and `c` clears the finished +jobs from the list. + +## Keyboard Reference + +### Global Keys + +These work in every view while no dialog or text input is open. + +| Key | Action | +|-----|--------| +| `1` to `7` | Switch to the Browse, Installed, Updates, Apply, Repos, Health, or Jobs view | +| `Tab` / `Shift+Tab` | Next / previous view | +| `?` | Open the help overlay, which lists the keys of the current view | +| `q` / `Ctrl-c` | Quit | +| `Ctrl-x` | Abort the running job | +| `Ctrl-r` | Reload the current view | +| `j` / `Down`, `k` / `Up` | Move the cursor down / up | +| `g` / `Home`, `G` / `End` | First / last row | +| `Ctrl-d` / `PageDown`, `Ctrl-u` / `PageUp` | Half a page down / up | +| `Esc` | Close the full-screen detail, then clear the filter, then clear the marks | + +### View Keys + +| View | Key | Action | +|------|-----|--------| +| Browse | `/` | Edit the filter | +| Browse | `Space` | Mark or unmark | +| Browse | `i` | Install the marked packages, or the current row | +| Browse | `I` | Install with options | +| Browse | `v` | Pick a version and install it | +| Browse | `x` | Run without installing | +| Browse | `+` | Install by name, URL, or path | +| Browse | `R` | Cycle the repository filter | +| Browse | `Enter` | Toggle the full-screen detail | +| Installed | `/` | Edit the filter | +| Installed | `Space` | Mark or unmark | +| Installed | `d` | Remove the marked packages, or the current row | +| Installed | `s` | Switch variant | +| Installed | `u` | Check updates for the marked packages, or the current row | +| Installed | `o` | Cycle the sort order: name, size, date | +| Installed | `Enter` | Toggle the full-screen detail | +| Updates | `Space` | Mark or unmark | +| Updates | `a` | Mark all, or clear the marks | +| Updates | `u` | Update the marked packages, or all when none are marked | +| Updates | `o` | Toggle keeping the old versions | +| Updates | `S` | Show or hide the skipped packages | +| Apply | `Enter` | Apply | +| Apply | `p` | Toggle prune | +| Apply | `e` | Edit `packages.toml` | +| Apply | `n` | Create the default `packages.toml`, when none exists | +| Repos | `s` | Sync all repositories | +| Repos | `e` | Enable or disable the current repository | +| Repos | `a` | Add a repository | +| Repos | `d` | Remove the current repository | +| Repos | `E` | Edit `config.toml` | +| Health | `c` | Clean the cache | +| Health | `b` | Remove broken symlinks | +| Health | `p` | Remove broken packages | +| Jobs | `Enter` | Focus the job detail | +| Jobs | `l` | Focus the log | +| Jobs | `x` | Abort the selected job if it is running, or drop it if queued | +| Jobs | `c` | Clear the finished jobs | + +In the Jobs view, `Esc` returns the focus to the job list. After checking +updates for a single package in the Installed view, `Esc` backs the Updates +view out to the full list and checks everything again. + +### Dialogs + +Every change runs through a confirmation that names exactly what will change, +so nothing destructive happens without approval. `y` confirms and `n` or `Esc` +cancels. The arrow keys and `Tab` move between buttons, and `Enter` presses +the focused one. Destructive confirmations start with the focus on Cancel. + +While a filter input has focus, every printable key goes into the text. +`Enter` keeps the filter and returns focus to the list, `Esc` clears it and +returns focus, and the arrow keys still move the cursor. + +### Quitting While a Job Runs + +`q` and `Ctrl-c` quit right away when no job is running or queued. Otherwise a +guard asks what to do: + +- **Wait and quit**: let the running job finish, then quit. Queued jobs are + dropped. +- **Abort and quit**: abort the running job and quit as soon as it stops. + Queued jobs are dropped. +- **Cancel**: keep the interface open. + +While quitting is pending, pressing `q` again offers `Force quit`, which exits +immediately and stops the running job wherever it is. + +### Mouse + +| Input | Action | +|-------|--------| +| Wheel | Scroll the list under the pointer, three rows per notch | +| Click on a tab | Switch to that view | +| Click on a list row | Move the cursor to that row; clicking the selected row toggles the full-screen detail | +| Click outside a confirm or picker | Close it, the same as `Esc` | + +## Notes + +- **One job at a time.** Install, remove, update, sync, apply, and clean run + from a queue: one job runs and the rest wait in order. The Jobs view shows + the queue. +- **Aborting stops at the next safe point.** `Ctrl-x` asks for confirmation + and then stops the job cleanly: downloads stop, hooks and builds are killed, + and packages not yet started are skipped. Everything that already finished + stays finished, and kept downloads resume the next time. A repository sync + and the system pass have no safe stop point, so `Ctrl-x` reports that + instead of aborting them. +- **Output lands in the log.** Messages from soar, hooks, and child processes + appear in the Jobs log. Nothing prints over the interface while it runs. +- **System packages are a second step.** Packages marked `system = true` in + `packages.toml` are applied after the normal apply, in a separate privileged + job. With sudo, a dialog asks for the administrator password and validates + it before starting. With doas, the terminal is handed over so doas can ask + for the password itself. Either way the pass runs + `soar --system apply --only-system` with the same global options the session + started with. + +## Building Without It + +The interface lives behind the `tui` cargo feature, which is enabled by +default. Building without default features produces a binary without it: + +```sh +cargo build --no-default-features +``` + +## See Also + +- [Declarative Packages](./declarative.md) for the `packages.toml` format +- [Health](./health.md) for the command-line equivalent of the checks +- [CLI Reference](./cli-reference.md) for the global options the interface + accepts